OpenTTD Source 20260129-master-g2bb01bd0e4
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 << "/**\n";
232 this->output_stream << " * @file strings.h This file contains IDs for all registered strings.\n";
233 this->output_stream << " * @attention This file is automatically generated. Do not modify.\n";
234 this->output_stream << " */\n\n";
235 this->output_stream << "#ifndef TABLE_STRINGS_H\n";
236 this->output_stream << "#define TABLE_STRINGS_H\n";
237 }
238
239 void WriteStringID(const std::string &name, size_t stringid) override
240 {
241 if (prev + 1 != stringid) this->output_stream << "\n";
242 fmt::print(this->output_stream, "static const StringID {} = 0x{:X};\n", name, stringid);
243 prev = stringid;
244 total_strings++;
245 }
246
247 void Finalise(const StringData &data) override
248 {
249 /* Find the plural form with the most amount of cases. */
250 size_t max_plural_forms = 0;
251 for (const auto &pf : _plural_forms) {
252 max_plural_forms = std::max(max_plural_forms, pf.plural_count);
253 }
254
255 fmt::print(this->output_stream,
256 "\n"
257 "static const uint LANGUAGE_PACK_VERSION = 0x{:X};\n"
258 "static const uint LANGUAGE_MAX_PLURAL = {};\n"
259 "static const uint LANGUAGE_MAX_PLURAL_FORMS = {};\n"
260 "static const uint LANGUAGE_TOTAL_STRINGS = {};\n"
261 "\n",
262 data.Version(), std::size(_plural_forms), max_plural_forms, total_strings
263 );
264
265 this->output_stream << "#endif /* TABLE_STRINGS_H */\n";
266
267 this->FileWriter::Finalise();
268
269 std::error_code error_code;
270 if (CompareFiles(this->path, this->real_path)) {
271 /* files are equal. tmp.xxx is not needed */
272 std::filesystem::remove(this->path, error_code); // Just ignore the error
273 } else {
274 /* else rename tmp.xxx into filename */
275 std::filesystem::rename(this->path, this->real_path, error_code);
276 if (error_code) FatalError("rename({}, {}) failed: {}", this->path, this->real_path, error_code.message());
277 }
278 }
279};
280
287 LanguageFileWriter(const std::filesystem::path &path) : FileWriter(path, std::ofstream::binary | std::ofstream::out)
288 {
289 }
290
291 void WriteHeader(const LanguagePackHeader *header) override
292 {
293 this->Write({reinterpret_cast<const char *>(header), sizeof(*header)});
294 }
295
296 void Finalise() override
297 {
298 this->output_stream.put(0);
299 this->FileWriter::Finalise();
300 }
301
302 void Write(std::string_view buffer) override
303 {
304 this->output_stream.write(buffer.data(), buffer.size());
305 }
306};
307
309static const OptionData _opts[] = {
310 { .type = ODF_NO_VALUE, .id = 'C', .longname = "-export-commands" },
311 { .type = ODF_NO_VALUE, .id = 'L', .longname = "-export-plurals" },
312 { .type = ODF_NO_VALUE, .id = 'P', .longname = "-export-pragmas" },
313 { .type = ODF_NO_VALUE, .id = 't', .shortname = 't', .longname = "--todo" },
314 { .type = ODF_NO_VALUE, .id = 'w', .shortname = 'w', .longname = "--warning" },
315 { .type = ODF_NO_VALUE, .id = 'h', .shortname = 'h', .longname = "--help" },
316 { .type = ODF_NO_VALUE, .id = 'h', .shortname = '?' },
317 { .type = ODF_HAS_VALUE, .id = 's', .shortname = 's', .longname = "--source_dir" },
318 { .type = ODF_HAS_VALUE, .id = 'd', .shortname = 'd', .longname = "--dest_dir" },
319};
320
321int CDECL main(int argc, char *argv[])
322{
323 std::filesystem::path src_dir(".");
324 std::filesystem::path dest_dir;
325
326 std::vector<std::string_view> params;
327 for (int i = 1; i < argc; ++i) params.emplace_back(argv[i]);
328 GetOptData mgo(params, _opts);
329 for (;;) {
330 int i = mgo.GetOpt();
331 if (i == -1) break;
332
333 switch (i) {
334 case 'C':
335 fmt::print("args\tflags\tcommand\treplacement\n");
336 for (const auto &cs : _cmd_structs) {
337 char flags;
338 if (cs.proc == EmitGender) {
339 flags = 'g'; // Command needs number of parameters defined by number of genders
340 } else if (cs.proc == EmitPlural) {
341 flags = 'p'; // Command needs number of parameters defined by plural value
342 } else if (cs.flags.Test(CmdFlag::DontCount)) {
343 flags = 'i'; // Command may be in the translation when it is not in base
344 } else {
345 flags = '0'; // Command needs no parameters
346 }
347 fmt::print("{}\t{:c}\t\"{}\"\t\"{}\"\n", cs.consumes, flags, cs.cmd, cs.cmd.find("STRING") != std::string::npos ? "STRING" : cs.cmd);
348 }
349 return 0;
350
351 case 'L':
352 fmt::print("count\tdescription\tnames\n");
353 for (const auto &pf : _plural_forms) {
354 fmt::print("{}\t\"{}\"\t{}\n", pf.plural_count, pf.description, pf.names);
355 }
356 return 0;
357
358 case 'P':
359 fmt::print("name\tflags\tdefault\tdescription\n");
360 for (const auto &pragma : _pragmas) {
361 fmt::print("\"{}\"\t{}\t\"{}\"\t\"{}\"\n",
362 pragma[0], pragma[1], pragma[2], pragma[3]);
363 }
364 return 0;
365
366 case 't':
367 _strgen.annotate_todos = true;
368 break;
369
370 case 'w':
371 _strgen.show_warnings = true;
372 break;
373
374 case 'h':
375 fmt::print(
376 "strgen\n"
377 " -t | --todo replace any untranslated strings with '<TODO>'\n"
378 " -w | --warning print a warning for any untranslated strings\n"
379 " -h | -? | --help print this help message and exit\n"
380 " -s | --source_dir search for english.txt in the specified directory\n"
381 " -d | --dest_dir put output file in the specified directory, create if needed\n"
382 " -export-commands export all commands and exit\n"
383 " -export-plurals export all plural forms and exit\n"
384 " -export-pragmas export all pragmas and exit\n"
385 " Run without parameters and strgen will search for english.txt and parse it,\n"
386 " creating strings.h. Passing an argument, strgen will translate that language\n"
387 " file using english.txt as a reference and output <language>.lng.\n"
388 );
389 return 0;
390
391 case 's':
392 src_dir = mgo.opt;
393 break;
394
395 case 'd':
396 dest_dir = mgo.opt;
397 break;
398
399 case -2:
400 fmt::print(stderr, "Invalid arguments\n");
401 return 0;
402 }
403 }
404
405 if (dest_dir.empty()) dest_dir = src_dir; // if dest_dir is not specified, it equals src_dir
406
407 try {
408 /* strgen has two modes of operation. If no (free) arguments are passed
409 * strgen generates strings.h to the destination directory. If it is supplied
410 * with a (free) parameter the program will translate that language to destination
411 * directory. As input english.txt is parsed from the source directory */
412 if (mgo.arguments.empty()) {
413 std::filesystem::path input_path = std::move(src_dir);
414 input_path /= "english.txt";
415
416 /* parse master file */
418 FileStringReader master_reader(data, input_path, true, false);
419 master_reader.ParseFile();
420 if (_strgen.errors != 0) return 1;
421
422 /* write strings.h */
423 std::filesystem::path output_path = dest_dir;
424 std::filesystem::create_directories(dest_dir);
425 output_path /= "strings.h";
426
427 HeaderFileWriter writer(output_path);
428 writer.WriteHeader(data);
429 writer.Finalise(data);
430 if (_strgen.errors != 0) return 1;
431 } else {
432 std::filesystem::path input_path = std::move(src_dir);
433 input_path /= "english.txt";
434
436 /* parse master file and check if target file is correct */
437 FileStringReader master_reader(data, input_path, true, false);
438 master_reader.ParseFile();
439
440 for (auto &argument: mgo.arguments) {
441 data.FreeTranslation();
442
443 std::filesystem::path lang_file = argument;
444 FileStringReader translation_reader(data, lang_file, false, lang_file.filename() != "english.txt");
445 translation_reader.ParseFile(); // target file
446 if (_strgen.errors != 0) return 1;
447
448 /* get the targetfile, strip any directories and append to destination path */
449 std::filesystem::path output_file = dest_dir;
450 output_file /= lang_file.filename();
451 output_file.replace_extension("lng");
452
453 LanguageFileWriter writer(output_file);
454 writer.WriteLang(data);
455 writer.Finalise();
456
457 /* if showing warnings, print a summary of the language */
458 if (_strgen.show_warnings) {
459 fmt::print("{} warnings and {} errors for {}\n", _strgen.warnings, _strgen.errors, output_file);
460 }
461 }
462 }
463 } catch (...) {
464 return 2;
465 }
466
467 return 0;
468}
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:309
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:247
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:239
Base class for writing the header, i.e.
Definition strgen.h:88
Class for writing a language to disk.
Definition strgen.cpp:282
LanguageFileWriter(const std::filesystem::path &path)
Open a file to write to.
Definition strgen.cpp:287
void Finalise() override
Finalise writing the file.
Definition strgen.cpp:296
void WriteHeader(const LanguagePackHeader *header) override
Write the header metadata.
Definition strgen.cpp:291
void Write(std::string_view buffer) override
Write a number of bytes.
Definition strgen.cpp:302
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