OpenTTD Source 20251213-master-g1091fa6071
strgen.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "../stdafx.h"
11#include "../error_func.h"
12#include "../string_func.h"
13#include "../strings_type.h"
14#include "../misc/getoptdata.h"
15#include "../table/control_codes.h"
16#include "../3rdparty/fmt/std.h"
17
18#include "strgen.h"
19
20#include <filesystem>
21#include <fstream>
22
23#include "../table/strgen_tables.h"
24
25#include "../safeguards.h"
26
27
28#ifdef _MSC_VER
29# define LINE_NUM_FMT(s) "{} ({}): warning: {} (" s ")\n"
30#else
31# define LINE_NUM_FMT(s) "{}:{}: " s ": {}\n"
32#endif
33
34void StrgenWarningI(const std::string &msg)
35{
36 if (_strgen.translation) {
37 fmt::print(stderr, LINE_NUM_FMT("info"), _strgen.file, _strgen.cur_line, msg);
38 } else {
39 fmt::print(stderr, LINE_NUM_FMT("warning"), _strgen.file, _strgen.cur_line, msg);
40 }
41 _strgen.warnings++;
42}
43
44void StrgenErrorI(const std::string &msg)
45{
46 fmt::print(stderr, LINE_NUM_FMT("error"), _strgen.file, _strgen.cur_line, msg);
47 _strgen.errors++;
48}
49
50[[noreturn]] void StrgenFatalI(const std::string &msg)
51{
52 fmt::print(stderr, LINE_NUM_FMT("FATAL"), _strgen.file, _strgen.cur_line, msg);
53#ifdef _MSC_VER
54 fmt::print(stderr, LINE_NUM_FMT("warning"), _strgen.file, _strgen.cur_line, "language is not compiled");
55#endif
56 throw std::exception();
57}
58
59[[noreturn]] void FatalErrorI(const std::string &msg)
60{
61 fmt::print(stderr, LINE_NUM_FMT("FATAL"), _strgen.file, _strgen.cur_line, msg);
62#ifdef _MSC_VER
63 fmt::print(stderr, LINE_NUM_FMT("warning"), _strgen.file, _strgen.cur_line, "language is not compiled");
64#endif
65 exit(2);
66}
67
70 std::ifstream input_stream;
71
79 FileStringReader(StringData &data, const std::filesystem::path &file, bool master, bool translation) :
80 StringReader(data, file.generic_string(), master, translation)
81 {
82 this->input_stream.open(file, std::ifstream::binary);
83 }
84
85 std::optional<std::string> ReadLine() override
86 {
87 std::string result;
88 if (!std::getline(this->input_stream, result)) return std::nullopt;
89 return result;
90 }
91
92 void HandlePragma(std::string_view str, LanguagePackHeader &lang) override;
93
94 void ParseFile() override
95 {
97
98 if (*_strgen.lang.name == '\0' || *_strgen.lang.own_name == '\0' || *_strgen.lang.isocode == '\0') {
99 FatalError("Language must include ##name, ##ownname and ##isocode");
100 }
101 }
102};
103
104void FileStringReader::HandlePragma(std::string_view str, LanguagePackHeader &lang)
105{
106 StringConsumer consumer(str);
107 auto name = consumer.ReadUntilChar(' ', StringConsumer::SKIP_ALL_SEPARATORS);
108 if (name == "id") {
109 this->data.next_string_id = consumer.ReadIntegerBase<uint32_t>(0);
110 } else if (name == "name") {
111 strecpy(lang.name, consumer.Read(StringConsumer::npos));
112 } else if (name == "ownname") {
113 strecpy(lang.own_name, consumer.Read(StringConsumer::npos));
114 } else if (name == "isocode") {
115 strecpy(lang.isocode, consumer.Read(StringConsumer::npos));
116 } else if (name == "textdir") {
117 auto dir = consumer.Read(StringConsumer::npos);
118 if (dir == "ltr") {
119 lang.text_dir = TD_LTR;
120 } else if (dir == "rtl") {
121 lang.text_dir = TD_RTL;
122 } else {
123 FatalError("Invalid textdir {}", dir);
124 }
125 } else if (name == "digitsep") {
126 auto sep = consumer.Read(StringConsumer::npos);
127 strecpy(lang.digit_group_separator, sep == "{NBSP}" ? NBSP : sep);
128 } else if (name == "digitsepcur") {
129 auto sep = consumer.Read(StringConsumer::npos);
130 strecpy(lang.digit_group_separator_currency, sep == "{NBSP}" ? NBSP : sep);
131 } else if (name == "decimalsep") {
132 auto sep = consumer.Read(StringConsumer::npos);
133 strecpy(lang.digit_decimal_separator, sep == "{NBSP}" ? NBSP : sep);
134 } else if (name == "winlangid") {
135 auto langid = consumer.ReadIntegerBase<int32_t>(0);
136 if (langid > UINT16_MAX || langid < 0) {
137 FatalError("Invalid winlangid {}", langid);
138 }
139 lang.winlangid = static_cast<uint16_t>(langid);
140 } else if (name == "grflangid") {
141 auto langid = consumer.ReadIntegerBase<int32_t>(0);
142 if (langid >= 0x7F || langid < 0) {
143 FatalError("Invalid grflangid {}", langid);
144 }
145 lang.newgrflangid = static_cast<uint8_t>(langid);
146 } else if (name == "gender") {
147 if (this->master) FatalError("Genders are not allowed in the base translation.");
148 for (;;) {
149 auto s = ParseWord(consumer);
150
151 if (!s.has_value()) break;
152 if (lang.num_genders >= MAX_NUM_GENDERS) FatalError("Too many genders, max {}", MAX_NUM_GENDERS);
153 s->copy(lang.genders[lang.num_genders], CASE_GENDER_LEN - 1);
154 lang.num_genders++;
155 }
156 } else if (name == "case") {
157 if (this->master) FatalError("Cases are not allowed in the base translation.");
158 for (;;) {
159 auto s = ParseWord(consumer);
160
161 if (!s.has_value()) break;
162 if (lang.num_cases >= MAX_NUM_CASES) FatalError("Too many cases, max {}", MAX_NUM_CASES);
163 s->copy(lang.cases[lang.num_cases], CASE_GENDER_LEN - 1);
164 lang.num_cases++;
165 }
166 } else {
168 }
169}
170
171static bool CompareFiles(const std::filesystem::path &path1, const std::filesystem::path &path2)
172{
173 /* Check for equal size, but ignore the error code for cases when a file does not exist. */
174 std::error_code error_code;
175 if (std::filesystem::file_size(path1, error_code) != std::filesystem::file_size(path2, error_code)) return false;
176
177 std::ifstream stream1(path1, std::ifstream::binary);
178 std::ifstream stream2(path2, std::ifstream::binary);
179
180 return std::equal(std::istreambuf_iterator<char>(stream1.rdbuf()),
181 std::istreambuf_iterator<char>(),
182 std::istreambuf_iterator<char>(stream2.rdbuf()));
183}
184
186struct FileWriter {
187 std::ofstream output_stream;
188 const std::filesystem::path path;
189
195 FileWriter(const std::filesystem::path &path, std::ios_base::openmode openmode) : path(path)
196 {
197 this->output_stream.open(path, openmode);
198 }
199
201 void Finalise()
202 {
203 this->output_stream.close();
204 }
205
207 virtual ~FileWriter()
208 {
209 /* If we weren't closed an exception was thrown, so remove the temporary file. */
210 if (this->output_stream.is_open()) {
211 this->output_stream.close();
212 std::filesystem::remove(this->path);
213 }
214 }
215};
216
219 const std::filesystem::path real_path;
221 size_t prev;
222 size_t total_strings;
223
228 HeaderFileWriter(const std::filesystem::path &path) : FileWriter("tmp.xxx", std::ofstream::out),
229 real_path(path), prev(0), total_strings(0)
230 {
231 this->output_stream << "/* This file is automatically generated. Do not modify */\n\n";
232 this->output_stream << "#ifndef TABLE_STRINGS_H\n";
233 this->output_stream << "#define TABLE_STRINGS_H\n";
234 }
235
236 void WriteStringID(const std::string &name, size_t stringid) override
237 {
238 if (prev + 1 != stringid) this->output_stream << "\n";
239 fmt::print(this->output_stream, "static const StringID {} = 0x{:X};\n", name, stringid);
240 prev = stringid;
241 total_strings++;
242 }
243
244 void Finalise(const StringData &data) override
245 {
246 /* Find the plural form with the most amount of cases. */
247 size_t max_plural_forms = 0;
248 for (const auto &pf : _plural_forms) {
249 max_plural_forms = std::max(max_plural_forms, pf.plural_count);
250 }
251
252 fmt::print(this->output_stream,
253 "\n"
254 "static const uint LANGUAGE_PACK_VERSION = 0x{:X};\n"
255 "static const uint LANGUAGE_MAX_PLURAL = {};\n"
256 "static const uint LANGUAGE_MAX_PLURAL_FORMS = {};\n"
257 "static const uint LANGUAGE_TOTAL_STRINGS = {};\n"
258 "\n",
259 data.Version(), std::size(_plural_forms), max_plural_forms, total_strings
260 );
261
262 this->output_stream << "#endif /* TABLE_STRINGS_H */\n";
263
264 this->FileWriter::Finalise();
265
266 std::error_code error_code;
267 if (CompareFiles(this->path, this->real_path)) {
268 /* files are equal. tmp.xxx is not needed */
269 std::filesystem::remove(this->path, error_code); // Just ignore the error
270 } else {
271 /* else rename tmp.xxx into filename */
272 std::filesystem::rename(this->path, this->real_path, error_code);
273 if (error_code) FatalError("rename({}, {}) failed: {}", this->path, this->real_path, error_code.message());
274 }
275 }
276};
277
284 LanguageFileWriter(const std::filesystem::path &path) : FileWriter(path, std::ofstream::binary | std::ofstream::out)
285 {
286 }
287
288 void WriteHeader(const LanguagePackHeader *header) override
289 {
290 this->Write({reinterpret_cast<const char *>(header), sizeof(*header)});
291 }
292
293 void Finalise() override
294 {
295 this->output_stream.put(0);
296 this->FileWriter::Finalise();
297 }
298
299 void Write(std::string_view buffer) override
300 {
301 this->output_stream.write(buffer.data(), buffer.size());
302 }
303};
304
306static const OptionData _opts[] = {
307 { .type = ODF_NO_VALUE, .id = 'C', .longname = "-export-commands" },
308 { .type = ODF_NO_VALUE, .id = 'L', .longname = "-export-plurals" },
309 { .type = ODF_NO_VALUE, .id = 'P', .longname = "-export-pragmas" },
310 { .type = ODF_NO_VALUE, .id = 't', .shortname = 't', .longname = "--todo" },
311 { .type = ODF_NO_VALUE, .id = 'w', .shortname = 'w', .longname = "--warning" },
312 { .type = ODF_NO_VALUE, .id = 'h', .shortname = 'h', .longname = "--help" },
313 { .type = ODF_NO_VALUE, .id = 'h', .shortname = '?' },
314 { .type = ODF_HAS_VALUE, .id = 's', .shortname = 's', .longname = "--source_dir" },
315 { .type = ODF_HAS_VALUE, .id = 'd', .shortname = 'd', .longname = "--dest_dir" },
316};
317
318int CDECL main(int argc, char *argv[])
319{
320 std::filesystem::path src_dir(".");
321 std::filesystem::path dest_dir;
322
323 std::vector<std::string_view> params;
324 for (int i = 1; i < argc; ++i) params.emplace_back(argv[i]);
325 GetOptData mgo(params, _opts);
326 for (;;) {
327 int i = mgo.GetOpt();
328 if (i == -1) break;
329
330 switch (i) {
331 case 'C':
332 fmt::print("args\tflags\tcommand\treplacement\n");
333 for (const auto &cs : _cmd_structs) {
334 char flags;
335 if (cs.proc == EmitGender) {
336 flags = 'g'; // Command needs number of parameters defined by number of genders
337 } else if (cs.proc == EmitPlural) {
338 flags = 'p'; // Command needs number of parameters defined by plural value
339 } else if (cs.flags.Test(CmdFlag::DontCount)) {
340 flags = 'i'; // Command may be in the translation when it is not in base
341 } else {
342 flags = '0'; // Command needs no parameters
343 }
344 fmt::print("{}\t{:c}\t\"{}\"\t\"{}\"\n", cs.consumes, flags, cs.cmd, cs.cmd.find("STRING") != std::string::npos ? "STRING" : cs.cmd);
345 }
346 return 0;
347
348 case 'L':
349 fmt::print("count\tdescription\tnames\n");
350 for (const auto &pf : _plural_forms) {
351 fmt::print("{}\t\"{}\"\t{}\n", pf.plural_count, pf.description, pf.names);
352 }
353 return 0;
354
355 case 'P':
356 fmt::print("name\tflags\tdefault\tdescription\n");
357 for (const auto &pragma : _pragmas) {
358 fmt::print("\"{}\"\t{}\t\"{}\"\t\"{}\"\n",
359 pragma[0], pragma[1], pragma[2], pragma[3]);
360 }
361 return 0;
362
363 case 't':
364 _strgen.annotate_todos = true;
365 break;
366
367 case 'w':
368 _strgen.show_warnings = true;
369 break;
370
371 case 'h':
372 fmt::print(
373 "strgen\n"
374 " -t | --todo replace any untranslated strings with '<TODO>'\n"
375 " -w | --warning print a warning for any untranslated strings\n"
376 " -h | -? | --help print this help message and exit\n"
377 " -s | --source_dir search for english.txt in the specified directory\n"
378 " -d | --dest_dir put output file in the specified directory, create if needed\n"
379 " -export-commands export all commands and exit\n"
380 " -export-plurals export all plural forms and exit\n"
381 " -export-pragmas export all pragmas and exit\n"
382 " Run without parameters and strgen will search for english.txt and parse it,\n"
383 " creating strings.h. Passing an argument, strgen will translate that language\n"
384 " file using english.txt as a reference and output <language>.lng.\n"
385 );
386 return 0;
387
388 case 's':
389 src_dir = mgo.opt;
390 break;
391
392 case 'd':
393 dest_dir = mgo.opt;
394 break;
395
396 case -2:
397 fmt::print(stderr, "Invalid arguments\n");
398 return 0;
399 }
400 }
401
402 if (dest_dir.empty()) dest_dir = src_dir; // if dest_dir is not specified, it equals src_dir
403
404 try {
405 /* strgen has two modes of operation. If no (free) arguments are passed
406 * strgen generates strings.h to the destination directory. If it is supplied
407 * with a (free) parameter the program will translate that language to destination
408 * directory. As input english.txt is parsed from the source directory */
409 if (mgo.arguments.empty()) {
410 std::filesystem::path input_path = std::move(src_dir);
411 input_path /= "english.txt";
412
413 /* parse master file */
415 FileStringReader master_reader(data, input_path, true, false);
416 master_reader.ParseFile();
417 if (_strgen.errors != 0) return 1;
418
419 /* write strings.h */
420 std::filesystem::path output_path = dest_dir;
421 std::filesystem::create_directories(dest_dir);
422 output_path /= "strings.h";
423
424 HeaderFileWriter writer(output_path);
425 writer.WriteHeader(data);
426 writer.Finalise(data);
427 if (_strgen.errors != 0) return 1;
428 } else {
429 std::filesystem::path input_path = std::move(src_dir);
430 input_path /= "english.txt";
431
433 /* parse master file and check if target file is correct */
434 FileStringReader master_reader(data, input_path, true, false);
435 master_reader.ParseFile();
436
437 for (auto &argument: mgo.arguments) {
438 data.FreeTranslation();
439
440 std::filesystem::path lang_file = argument;
441 FileStringReader translation_reader(data, lang_file, false, lang_file.filename() != "english.txt");
442 translation_reader.ParseFile(); // target file
443 if (_strgen.errors != 0) return 1;
444
445 /* get the targetfile, strip any directories and append to destination path */
446 std::filesystem::path output_file = dest_dir;
447 output_file /= lang_file.filename();
448 output_file.replace_extension("lng");
449
450 LanguageFileWriter writer(output_file);
451 writer.WriteLang(data);
452 writer.Finalise();
453
454 /* if showing warnings, print a summary of the language */
455 if (_strgen.show_warnings) {
456 fmt::print("{} warnings and {} errors for {}\n", _strgen.warnings, _strgen.errors, output_file);
457 }
458 }
459 }
460 } catch (...) {
461 return 2;
462 }
463
464 return 0;
465}
Parse data from a string / buffer.
std::string_view ReadUntilChar(char c, SeparatorUsage sep)
Read data until the first occurrence of 8-bit char 'c', and advance reader.
@ SKIP_ALL_SEPARATORS
Read and discard all consecutive separators, do not include any in the result.
T ReadIntegerBase(int base, T def=0, bool clamp=false)
Read and parse an integer in number 'base', and advance the reader.
std::string_view Read(size_type len)
Read the next 'len' bytes, and advance reader.
static constexpr size_type npos
Special value for "end of data".
@ ODF_NO_VALUE
A plain option (no value attached to it).
Definition getoptdata.h:15
@ ODF_HAS_VALUE
An option with a value.
Definition getoptdata.h:16
static const uint8_t MAX_NUM_GENDERS
Maximum number of supported genders.
Definition language.h:20
static const uint8_t CASE_GENDER_LEN
The (maximum) length of a case/gender string.
Definition language.h:19
static const uint8_t MAX_NUM_CASES
Maximum number of supported cases.
Definition language.h:21
static const OptionData _opts[]
Options of strgen.
Definition strgen.cpp:306
void FatalErrorI(const std::string &msg)
Error handling for fatal non-user errors.
Definition strgen.cpp:59
Structures related to strgen.
static const std::string_view _pragmas[][4]
All pragmas used.
static const PluralForm _plural_forms[]
All plural forms used.
@ DontCount
These commands aren't counted for comparison.
void strecpy(std::span< char > dst, std::string_view src)
Copies characters from one buffer to another.
Definition string.cpp:56
#define NBSP
A non-breaking space.
Definition string_type.h:16
@ TEXT_TAB_END
End of language files.
@ TD_LTR
Text is written left-to-right by default.
@ TD_RTL
Text is written right-to-left by default.
A reader that simply reads using fopen.
Definition strgen.cpp:69
FileStringReader(StringData &data, const std::filesystem::path &file, bool master, bool translation)
Create the reader.
Definition strgen.cpp:79
void ParseFile() override
Start parsing the file.
Definition strgen.cpp:94
std::optional< std::string > ReadLine() override
Read a single line from the source of strings.
Definition strgen.cpp:85
void HandlePragma(std::string_view str, LanguagePackHeader &lang) override
Handle the pragma of the file.
Definition strgen.cpp:104
Yes, simply writing to a file.
std::ofstream output_stream
The stream to write all the output to.
Definition strgen.cpp:187
virtual ~FileWriter()
Make sure the file is closed.
Definition strgen.cpp:207
const std::filesystem::path path
The file name we're writing to.
Definition strgen.cpp:188
FileWriter(const std::filesystem::path &path, std::ios_base::openmode openmode)
Open a file to write to.
Definition strgen.cpp:195
void Finalise()
Finalise the writing.
Definition strgen.cpp:201
Data storage for parsing command line options.
Definition getoptdata.h:29
const std::filesystem::path real_path
The real path we eventually want to write to.
Definition strgen.cpp:219
void Finalise(const StringData &data) override
Finalise writing the file.
Definition strgen.cpp:244
HeaderFileWriter(const std::filesystem::path &path)
Open a file to write to.
Definition strgen.cpp:228
size_t prev
The previous string ID that was printed.
Definition strgen.cpp:221
void WriteStringID(const std::string &name, size_t stringid) override
Write the string ID.
Definition strgen.cpp:236
Base class for writing the header, i.e.
Definition strgen.h:88
Class for writing a language to disk.
Definition strgen.cpp:279
LanguageFileWriter(const std::filesystem::path &path)
Open a file to write to.
Definition strgen.cpp:284
void Finalise() override
Finalise writing the file.
Definition strgen.cpp:293
void WriteHeader(const LanguagePackHeader *header) override
Write the header metadata.
Definition strgen.cpp:288
void Write(std::string_view buffer) override
Write a number of bytes.
Definition strgen.cpp:299
Header of a language file.
Definition language.h:24
char isocode[16]
the ISO code for the language (not country code)
Definition language.h:31
char own_name[32]
the localized name of this language
Definition language.h:30
char name[32]
the international name of this language
Definition language.h:29
uint16_t winlangid
Windows language ID: Windows cannot and will not convert isocodes to something it can use to determin...
Definition language.h:51
uint8_t num_genders
the number of genders of this language
Definition language.h:53
char cases[MAX_NUM_CASES][CASE_GENDER_LEN]
the cases used by this translation
Definition language.h:58
char digit_group_separator[8]
Thousand separator used for anything not currencies.
Definition language.h:35
uint8_t newgrflangid
newgrf language id
Definition language.h:52
uint8_t text_dir
default direction of the text
Definition language.h:42
char genders[MAX_NUM_GENDERS][CASE_GENDER_LEN]
the genders used by this translation
Definition language.h:57
uint8_t num_cases
the number of cases of this language
Definition language.h:54
char digit_decimal_separator[8]
Decimal separator.
Definition language.h:39
char digit_group_separator_currency[8]
Thousand separator used for currencies.
Definition language.h:37
Base class for all language writers.
Definition strgen.h:109
Data of an option.
Definition getoptdata.h:21
OptionDataType type
The type of option.
Definition getoptdata.h:22
std::string file
The filename of the input, so we can refer to it in errors/warnings.
Definition strgen.h:162
bool translation
Is the current file actually a translation or not.
Definition strgen.h:168
LanguagePackHeader lang
Header information about a language.
Definition strgen.h:169
size_t cur_line
The current line we're parsing in the input file.
Definition strgen.h:163
Information about the currently known strings.
Definition strgen.h:43
size_t next_string_id
The next string ID to allocate.
Definition strgen.h:48
uint32_t Version() const
Make a hash of the file to get a unique "version number".
Helper for reading strings.
Definition strgen.h:59
const std::string file
The file we are reading.
Definition strgen.h:61
StringData & data
The data to fill during reading.
Definition strgen.h:60
virtual void ParseFile()
Start parsing the file.
bool translation
Are we reading a translation, implies !master. However, the base translation will have this false.
Definition strgen.h:63
virtual void HandlePragma(std::string_view str, LanguagePackHeader &lang)
Handle the pragma of the file.
bool master
Are we reading the master file?
Definition strgen.h:62