11#include "../core/endian_func.hpp"
12#include "../core/math_func.hpp"
13#include "../error_func.h"
14#include "../string_func.h"
15#include "../core/string_builder.hpp"
16#include "../table/control_codes.h"
20#include "../table/strgen_tables.h"
22#include "../safeguards.h"
26static std::string_view _cur_ident;
28static size_t _cur_argidx;
33 std::optional<size_t> argno;
34 std::optional<uint8_t> casei;
37static size_t TranslateArgumentIdx(
size_t arg,
size_t offset = 0);
45 caseidx(caseidx), string(string)
57 name(name), english(english), index(index), line(line)
95 this->
strings[ls->index] = std::move(ls);
108 return it->second.get();
120 hash = std::rotl(hash, 3) ^ c;
121 hash = (hash & 1 ? hash >> 1 ^ 0xDEADBEEF : hash >> 1);
138 hash ^= i * 0x717239;
139 hash = (hash & 1 ? hash >> 1 ^ 0xDEADBEEF : hash >> 1);
144 while ((cs = ParseCommandString(consumer)).cmd !=
nullptr) {
147 hash ^= (cs.cmd - _cmd_structs) * 0x1234567;
148 hash = (hash & 1 ? hash >> 1 ^ 0xF00BAA4 : hash >> 1);
163 while (count > 0 && this->
strings[(tab *
TAB_SIZE) + count - 1] ==
nullptr) --count;
167void EmitSingleChar(
StringBuilder &builder, std::string_view param,
char32_t value)
169 if (!param.empty()) StrgenWarning(
"Ignoring trailing letters in command");
175static std::pair<std::optional<size_t>, std::optional<size_t>> ParseRelNum(
StringConsumer &consumer)
179 std::optional<size_t> offset;
180 if (v.has_value() && consumer.
ReadCharIf(
':')) {
183 if (!offset.has_value()) StrgenFatal(
"Expected number for substring parameter");
189std::optional<std::string_view> ParseWord(
StringConsumer &consumer)
197 if (!consumer.
ReadCharIf(
'"')) StrgenFatal(
"Unterminated quotes");
207static void EmitWordList(
StringBuilder &builder,
const std::vector<std::string> &words)
209 builder.
PutUint8(
static_cast<uint8_t
>(words.size()));
210 for (
size_t i = 0; i < words.size(); i++) {
211 size_t len = words[i].size();
212 if (len > UINT8_MAX) StrgenFatal(
"WordList {}/{} string '{}' too long, max bytes {}", i + 1, words.size(), words[i], UINT8_MAX);
213 builder.
PutUint8(
static_cast<uint8_t
>(len));
215 for (
size_t i = 0; i < words.size(); i++) {
216 builder.
Put(words[i]);
220void EmitPlural(
StringBuilder &builder, std::string_view param,
char32_t)
225 auto [argidx, offset] = ParseRelNum(consumer);
226 if (!argidx.has_value()) {
227 if (_cur_argidx == 0) StrgenFatal(
"Plural choice needs positional reference");
228 argidx = _cur_argidx - 1;
231 const CmdStruct *cmd = _cur_pcs.consuming_commands[*argidx];
232 if (!offset.has_value()) {
234 if (cmd ==
nullptr || !cmd->default_plural_offset.has_value()) {
235 StrgenFatal(
"Command '{}' has no (default) plural position", cmd ==
nullptr ?
"<empty>" : cmd->cmd);
237 offset = cmd->default_plural_offset;
241 std::vector<std::string> words;
243 auto word = ParseWord(consumer);
244 if (!word.has_value())
break;
245 words.emplace_back(*word);
249 StrgenFatal(
"{}: No plural words", _cur_ident);
253 if (expected != words.size()) {
255 StrgenFatal(
"{}: Invalid number of plural forms. Expecting {}, found {}.", _cur_ident,
256 expected, words.size());
258 if (_strgen.show_warnings) StrgenWarning(
"'{}' is untranslated. Tweaking english string to allow compilation for plural forms", _cur_ident);
259 if (words.size() > expected) {
260 words.resize(expected);
262 while (words.size() < expected) {
263 words.push_back(words.back());
269 builder.
PutUtf8(SCC_PLURAL_LIST);
271 builder.
PutUint8(
static_cast<uint8_t
>(TranslateArgumentIdx(*argidx, *offset)));
272 EmitWordList(builder, words);
275void EmitGender(
StringBuilder &builder, std::string_view param,
char32_t)
282 if (nw >=
MAX_NUM_GENDERS) StrgenFatal(
"G argument '{}' invalid", gender);
285 builder.
PutUtf8(SCC_GENDER_INDEX);
290 auto [argidx, offset] = ParseRelNum(consumer);
291 if (!argidx.has_value()) argidx = _cur_argidx;
292 if (!offset.has_value()) offset = 0;
294 const CmdStruct *cmd = _cur_pcs.consuming_commands[*argidx];
296 StrgenFatal(
"Command '{}' can't have a gender", cmd ==
nullptr ?
"<empty>" : cmd->cmd);
299 std::vector<std::string> words;
301 auto word = ParseWord(consumer);
302 if (!word.has_value())
break;
303 words.emplace_back(*word);
305 if (words.size() != _strgen.
lang.
num_genders) StrgenFatal(
"Bad # of arguments for gender command");
307 assert(
IsInsideBS(cmd->value, SCC_CONTROL_START, UINT8_MAX));
308 builder.
PutUtf8(SCC_GENDER_LIST);
309 builder.
PutUint8(
static_cast<uint8_t
>(TranslateArgumentIdx(*argidx, *offset)));
310 EmitWordList(builder, words);
314static const CmdStruct *FindCmd(std::string_view s)
316 auto it = std::ranges::find(_cmd_structs, s, &CmdStruct::cmd);
317 if (it != std::end(_cmd_structs))
return &*it;
321static uint8_t ResolveCaseName(std::string_view str)
324 if (case_idx >=
MAX_NUM_CASES) StrgenFatal(
"Invalid case-name '{}'", str);
338 result.argno = argno;
339 if (!consumer.
ReadCharIf(
':')) StrgenFatal(
"missing arg #");
344 result.cmd = FindCmd(command);
345 if (result.cmd ==
nullptr) {
346 StrgenError(
"Undefined command '{}'", command);
353 StrgenFatal(
"Command '{}' can't have a case", result.cmd->cmd);
357 result.casei = ResolveCaseName(casep);
364 StrgenError(
"Missing }} from command '{}'", result.cmd->cmd);
379 data(data), file(file), master(master), translation(translation)
391 auto cs = ParseCommandString(consumer);
393 if (cs.cmd ==
nullptr)
break;
396 if (cs.argno.has_value() && cs.cmd->consumes == 0) StrgenFatal(
"Non consumer param can't have a paramindex");
398 if (cs.cmd->consumes > 0) {
399 if (cs.argno.has_value()) argidx = *cs.argno;
400 if (argidx >= p.consuming_commands.max_size()) StrgenFatal(
"invalid param idx {}", argidx);
401 if (p.consuming_commands[argidx] !=
nullptr && p.consuming_commands[argidx] != cs.cmd) StrgenFatal(
"duplicate param idx {}", argidx);
403 p.consuming_commands[argidx++] = cs.cmd;
405 p.non_consuming_commands.emplace_back(cs.cmd, std::move(cs.param));
414 if (a ==
nullptr)
return nullptr;
416 if (a->cmd ==
"STRING1" ||
417 a->cmd ==
"STRING2" ||
418 a->cmd ==
"STRING3" ||
419 a->cmd ==
"STRING4" ||
420 a->cmd ==
"STRING5" ||
421 a->cmd ==
"STRING6" ||
422 a->cmd ==
"STRING7" ||
423 a->cmd ==
"RAW_STRING") {
424 return FindCmd(
"STRING");
430static bool CheckCommandsMatch(std::string_view a, std::string_view b, std::string_view name)
444 if (templ.non_consuming_commands.max_size() != lang.non_consuming_commands.max_size()) {
445 StrgenWarning(
"{}: template string and language string have a different # of commands", name);
449 for (
auto &templ_nc : templ.non_consuming_commands) {
451 auto it = std::ranges::find(lang.non_consuming_commands, templ_nc);
452 if (it != std::end(lang.non_consuming_commands)) {
456 StrgenWarning(
"{}: command '{}' exists in template file but not in language file", name, templ_nc.cmd->cmd);
463 for (
size_t i = 0; i < templ.consuming_commands.max_size(); i++) {
464 if (TranslateCmdForCompare(templ.consuming_commands[i]) != lang.consuming_commands[i]) {
465 StrgenWarning(
"{}: Param idx #{} '{}' doesn't match with template command '{}'", name, i,
466 lang.consuming_commands[i] ==
nullptr ?
"<empty>" : TranslateCmdForCompare(lang.consuming_commands[i])->cmd,
467 templ.consuming_commands[i] == nullptr ?
"<empty>" : templ.consuming_commands[i]->cmd);
475void StringReader::HandleString(std::string_view src)
478 if (src.empty())
return;
489 StrgenError(
"Line has no ':' delimiter");
494 std::optional<std::string_view> casep;
495 if (
auto index = str_name.find(
"."); index != std::string_view::npos) {
496 casep = str_name.substr(index + 1);
497 str_name = str_name.substr(0, index);
505 auto c = validation_consumer.TryReadUtf8();
506 if (!c.has_value()) StrgenFatal(
"Invalid UTF-8 sequence in '{}'", value);
509 (*c >= 0xE000 && *c <= 0xF8FF) ||
510 (*c >= 0xFFF0 && *c <= 0xFFFF)) {
511 StrgenFatal(
"Unwanted UTF-8 character U+{:04X} in sequence '{}'",
static_cast<uint32_t
>(*c), value);
519 if (casep.has_value()) {
520 StrgenError(
"Cases in the base translation are not supported.");
524 if (ent !=
nullptr) {
525 StrgenError(
"String name '{}' is used multiple times", str_name);
529 if (this->
data.
strings[this->data.next_string_id] !=
nullptr) {
530 StrgenError(
"String ID 0x{:X} for '{}' already in use by '{}'", this->
data.
next_string_id, str_name, this->data.strings[this->data.next_string_id]->name);
537 if (ent ==
nullptr) {
538 StrgenWarning(
"String name '{}' does not exist in master file", str_name);
542 if (!ent->
translated.empty() && !casep.has_value()) {
543 StrgenError(
"String name '{}' is used multiple times", str_name);
548 if (!CheckCommandsMatch(value, ent->
english, str_name))
return;
550 if (casep.has_value()) {
566 if (name ==
"plural") {
569 StrgenFatal(
"Invalid pluralform {}", lang.
plural_form);
572 StrgenFatal(
"unknown pragma '{}'", name);
578 _strgen.warnings = _strgen.errors = 0;
588 std::optional<std::string> line = this->
ReadLine();
589 if (!line.has_value())
return;
596 StrgenError(
"Too many strings, maximum allowed is {}", this->
data.
max_strings);
608 if (data.
strings[i] !=
nullptr) {
617static size_t TranslateArgumentIdx(
size_t argidx,
size_t offset)
619 if (argidx >= _cur_pcs.consuming_commands.max_size()) {
620 StrgenFatal(
"invalid argidx {}", argidx);
622 const CmdStruct *cs = _cur_pcs.consuming_commands[argidx];
623 if (cs !=
nullptr && cs->consumes <= offset) {
624 StrgenFatal(
"invalid argidx offset {}:{}", argidx, offset);
627 if (_cur_pcs.consuming_commands[argidx] ==
nullptr) {
628 StrgenFatal(
"no command for this argidx {}", argidx);
632 for (
size_t i = 0; i < argidx; i++) {
633 cs = _cur_pcs.consuming_commands[i];
635 if (cs ==
nullptr && sum > i)
continue;
637 sum += (cs !=
nullptr) ? cs->consumes : 1;
645 builder.
PutUtf8(SCC_ARG_INDEX);
646 builder.
PutUint8(
static_cast<uint8_t
>(TranslateArgumentIdx(_cur_argidx)));
649static std::string PutCommandString(std::string_view str)
661 auto cs = ParseCommandString(consumer);
663 if (cmd ==
nullptr)
break;
665 if (cs.casei.has_value()) {
671 if (cmd->consumes > 0) {
673 if (cs.argno.has_value() && *cs.argno != _cur_argidx) {
674 _cur_argidx = *cs.argno;
675 PutArgidxCommand(builder);
679 cmd = _cur_pcs.consuming_commands[_cur_argidx++];
680 if (cmd ==
nullptr) {
681 StrgenFatal(
"{}: No argument exists at position {}", _cur_ident, _cur_argidx - 1);
685 cmd->proc(builder, cs.param, cmd->value);
698 if (length >= 0x4000) {
699 StrgenFatal(
"string too long");
702 if (length >= 0xC0) {
703 buffer[offs++] =
static_cast<char>(
static_cast<uint8_t
>((length >> 8) | 0xC0));
705 buffer[offs++] =
static_cast<char>(
static_cast<uint8_t
>(length & 0xFF));
706 this->
Write({buffer, offs});
715 std::vector<size_t> in_use;
716 for (
size_t tab = 0; tab < data.
tabs; tab++) {
720 _strgen.
lang.
offsets[tab] = TO_LE16(
static_cast<uint16_t
>(n));
722 for (
size_t j = 0; j != in_use[tab]; j++) {
735 for (
size_t tab = 0; tab < data.
tabs; tab++) {
736 for (
size_t j = 0; j != in_use[tab]; j++) {
747 _cur_ident = ls->
name;
752 if (_strgen.show_warnings) {
753 StrgenWarning(
"'{}' is untranslated", ls->
name);
755 if (_strgen.annotate_todos) {
756 builder.
Put(
"<TODO> ");
761 _cur_pcs = ExtractCommandString(ls->
english,
false);
771 builder.
PutUtf8(SCC_SWITCH_CASE);
776 auto case_str = PutCommandString(c.string);
778 builder.
PutUint16LE(
static_cast<uint16_t
>(case_str.size()));
779 builder.
Put(case_str);
784 if (!cmdp.empty()) def_str = PutCommandString(cmdp);
786 builder.
PutUint16LE(
static_cast<uint16_t
>(def_str.size()));
788 builder.
Put(def_str);
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
void PutUtf8(char32_t c)
Append UTF.8 char.
void PutUint16LE(uint16_t value)
Append binary uint16 using little endian.
void Put(std::string_view str)
Append string.
void PutUint8(uint8_t value)
Append binary uint8.
Compose data into a growing std::string.
Parse data from a string / buffer.
bool ReadCharIf(char c)
Check whether the next 8-bit char matches 'c', and skip it.
std::optional< T > TryReadIntegerBase(int base, bool clamp=false)
Try to read and parse an integer in number 'base', and then advance the reader.
std::string_view ReadUntilChar(char c, SeparatorUsage sep)
Read data until the first occurrence of 8-bit char 'c', and advance reader.
void SkipUntilChar(char c, SeparatorUsage sep)
Skip data until the first occurrence of 8-bit char 'c'.
@ SKIP_ALL_SEPARATORS
Read and discard all consecutive separators, do not include any in the result.
@ KEEP_SEPARATOR
Keep the separator in the data as next value to be read.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
static const std::string_view WHITESPACE_OR_NEWLINE
ASCII whitespace characters, including new-line.
static const std::string_view WHITESPACE_NO_NEWLINE
ASCII whitespace characters, excluding new-line.
void SkipUntilCharNotIn(std::string_view chars)
Skip 8-bit chars, while they are in 'chars', until they are not.
std::string_view ReadUntilCharIn(std::string_view chars)
Read 8-bit chars, while they are not in 'chars', until they are; and advance reader.
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".
static const uint8_t MAX_NUM_GENDERS
Maximum number of supported genders.
static const uint8_t MAX_NUM_CASES
Maximum number of supported cases.
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
#define lengthof(array)
Return the length of an fixed size array.
Structures related to strgen.
static bool _translated
Whether the current language is not the master language.
static uint32_t VersionHashStr(uint32_t hash, std::string_view s)
Create a compound hash.
static const PluralForm _plural_forms[]
All plural forms used.
@ Gender
These commands support genders.
@ Case
These commands support cases.
@ DontCount
These commands aren't counted for comparison.
static const uint TAB_SIZE
Number of strings per StringTab.
Container for the different cases of a string.
Case(uint8_t caseidx, std::string_view string)
Create a new case.
Information about a single string.
size_t line
Line of string in source-file.
std::string english
English text.
std::vector< Case > translated_cases
Cases of the translation.
std::string translated
Translated text.
void FreeTranslation()
Free all data related to the translation.
std::string name
Name of the string.
LangString(std::string_view name, std::string_view english, size_t index, size_t line)
Create a new string.
virtual void WriteHeader(const LanguagePackHeader *header)=0
Write the header metadata.
virtual void WriteLength(size_t length)
Write the length as a simple gamma.
virtual void Write(std::string_view buffer)=0
Write a number of bytes.
virtual void WriteLang(const StringData &data)
Actually write the language.
Global state shared between strgen.cpp, game_text.cpp and strgen_base.cpp.
std::string file
The filename of the input, so we can refer to it in errors/warnings.
bool translation
Is the current file actually a translation or not.
LanguagePackHeader lang
Header information about a language.
size_t cur_line
The current line we're parsing in the input file.
Information about the currently known strings.
size_t tabs
The number of 'tabs' of strings.
void Add(std::shared_ptr< LangString > ls)
Add a newly created LangString.
size_t max_strings
The maximum number of strings.
size_t next_string_id
The next string ID to allocate.
void FreeTranslation()
Free all data related to the translation.
LangString * Find(std::string_view s)
Find a LangString based on the string name.
StringData(size_t tabs)
Create a new string data container.
std::unordered_map< std::string, std::shared_ptr< LangString >, StringHash, std::equal_to<> > name_to_string
Lookup table for the strings.
std::vector< std::shared_ptr< LangString > > strings
List of all known strings.
uint32_t Version() const
Make a hash of the file to get a unique "version number".
size_t CountInUse(size_t tab) const
Count the number of tab elements that are in use.
const std::string file
The file we are reading.
StringReader(StringData &data, const std::string &file, bool master, bool translation)
Prepare reading.
StringData & data
The data to fill during reading.
virtual void ParseFile()
Start parsing the file.
bool translation
Are we reading a translation, implies !master. However, the base translation will have this false.
virtual void HandlePragma(std::string_view str, LanguagePackHeader &lang)
Handle the pragma of the file.
virtual std::optional< std::string > ReadLine()=0
Read a single line from the source of strings.
bool master
Are we reading the master file?