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 for (
const auto &cs : _cmd_structs) {
317 if (cs.cmd == s)
return &cs;
322static uint8_t ResolveCaseName(std::string_view str)
325 if (case_idx >=
MAX_NUM_CASES) StrgenFatal(
"Invalid case-name '{}'", str);
339 result.argno = argno;
340 if (!consumer.
ReadCharIf(
':')) StrgenFatal(
"missing arg #");
345 result.cmd = FindCmd(command);
346 if (result.cmd ==
nullptr) {
347 StrgenError(
"Undefined command '{}'", command);
354 StrgenFatal(
"Command '{}' can't have a case", result.cmd->cmd);
358 result.casei = ResolveCaseName(casep);
365 StrgenError(
"Missing }} from command '{}'", result.cmd->cmd);
380 data(data), file(file), master(master), translation(translation)
392 auto cs = ParseCommandString(consumer);
394 if (cs.cmd ==
nullptr)
break;
397 if (cs.argno.has_value() && cs.cmd->consumes == 0) StrgenFatal(
"Non consumer param can't have a paramindex");
399 if (cs.cmd->consumes > 0) {
400 if (cs.argno.has_value()) argidx = *cs.argno;
401 if (argidx >= p.consuming_commands.max_size()) StrgenFatal(
"invalid param idx {}", argidx);
402 if (p.consuming_commands[argidx] !=
nullptr && p.consuming_commands[argidx] != cs.cmd) StrgenFatal(
"duplicate param idx {}", argidx);
404 p.consuming_commands[argidx++] = cs.cmd;
406 p.non_consuming_commands.emplace_back(cs.cmd, std::move(cs.param));
415 if (a ==
nullptr)
return nullptr;
417 if (a->cmd ==
"STRING1" ||
418 a->cmd ==
"STRING2" ||
419 a->cmd ==
"STRING3" ||
420 a->cmd ==
"STRING4" ||
421 a->cmd ==
"STRING5" ||
422 a->cmd ==
"STRING6" ||
423 a->cmd ==
"STRING7" ||
424 a->cmd ==
"RAW_STRING") {
425 return FindCmd(
"STRING");
431static bool CheckCommandsMatch(std::string_view a, std::string_view b, std::string_view name)
445 if (templ.non_consuming_commands.max_size() != lang.non_consuming_commands.max_size()) {
446 StrgenWarning(
"{}: template string and language string have a different # of commands", name);
450 for (
auto &templ_nc : templ.non_consuming_commands) {
453 for (
auto &lang_nc : lang.non_consuming_commands) {
454 if (templ_nc.cmd == lang_nc.cmd && templ_nc.param == lang_nc.param) {
456 lang_nc.cmd =
nullptr;
463 StrgenWarning(
"{}: command '{}' exists in template file but not in language file", name, templ_nc.cmd->cmd);
470 for (
size_t i = 0; i < templ.consuming_commands.max_size(); i++) {
471 if (TranslateCmdForCompare(templ.consuming_commands[i]) != lang.consuming_commands[i]) {
472 StrgenWarning(
"{}: Param idx #{} '{}' doesn't match with template command '{}'", name, i,
473 lang.consuming_commands[i] ==
nullptr ?
"<empty>" : TranslateCmdForCompare(lang.consuming_commands[i])->cmd,
474 templ.consuming_commands[i] == nullptr ?
"<empty>" : templ.consuming_commands[i]->cmd);
482void StringReader::HandleString(std::string_view src)
485 if (src.empty())
return;
496 StrgenError(
"Line has no ':' delimiter");
501 std::optional<std::string_view> casep;
502 if (
auto index = str_name.find(
"."); index != std::string_view::npos) {
503 casep = str_name.substr(index + 1);
504 str_name = str_name.substr(0, index);
512 auto c = validation_consumer.TryReadUtf8();
513 if (!c.has_value()) StrgenFatal(
"Invalid UTF-8 sequence in '{}'", value);
516 (*c >= 0xE000 && *c <= 0xF8FF) ||
517 (*c >= 0xFFF0 && *c <= 0xFFFF)) {
518 StrgenFatal(
"Unwanted UTF-8 character U+{:04X} in sequence '{}'",
static_cast<uint32_t
>(*c), value);
526 if (casep.has_value()) {
527 StrgenError(
"Cases in the base translation are not supported.");
531 if (ent !=
nullptr) {
532 StrgenError(
"String name '{}' is used multiple times", str_name);
536 if (this->
data.
strings[this->data.next_string_id] !=
nullptr) {
537 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);
544 if (ent ==
nullptr) {
545 StrgenWarning(
"String name '{}' does not exist in master file", str_name);
549 if (!ent->
translated.empty() && !casep.has_value()) {
550 StrgenError(
"String name '{}' is used multiple times", str_name);
555 if (!CheckCommandsMatch(value, ent->
english, str_name))
return;
557 if (casep.has_value()) {
573 if (name ==
"plural") {
576 StrgenFatal(
"Invalid pluralform {}", lang.
plural_form);
579 StrgenFatal(
"unknown pragma '{}'", name);
585 _strgen.warnings = _strgen.errors = 0;
595 std::optional<std::string> line = this->
ReadLine();
596 if (!line.has_value())
return;
603 StrgenError(
"Too many strings, maximum allowed is {}", this->
data.
max_strings);
615 if (data.
strings[i] !=
nullptr) {
624static size_t TranslateArgumentIdx(
size_t argidx,
size_t offset)
626 if (argidx >= _cur_pcs.consuming_commands.max_size()) {
627 StrgenFatal(
"invalid argidx {}", argidx);
629 const CmdStruct *cs = _cur_pcs.consuming_commands[argidx];
630 if (cs !=
nullptr && cs->consumes <= offset) {
631 StrgenFatal(
"invalid argidx offset {}:{}", argidx, offset);
634 if (_cur_pcs.consuming_commands[argidx] ==
nullptr) {
635 StrgenFatal(
"no command for this argidx {}", argidx);
639 for (
size_t i = 0; i < argidx; i++) {
640 cs = _cur_pcs.consuming_commands[i];
642 sum += (cs !=
nullptr) ? cs->consumes : 1;
650 builder.
PutUtf8(SCC_ARG_INDEX);
651 builder.
PutUint8(
static_cast<uint8_t
>(TranslateArgumentIdx(_cur_argidx)));
654static std::string PutCommandString(std::string_view str)
666 auto cs = ParseCommandString(consumer);
668 if (cmd ==
nullptr)
break;
670 if (cs.casei.has_value()) {
676 if (cmd->consumes > 0) {
678 if (cs.argno.has_value() && *cs.argno != _cur_argidx) {
679 _cur_argidx = *cs.argno;
680 PutArgidxCommand(builder);
684 cmd = _cur_pcs.consuming_commands[_cur_argidx++];
685 if (cmd ==
nullptr) {
686 StrgenFatal(
"{}: No argument exists at position {}", _cur_ident, _cur_argidx - 1);
690 cmd->proc(builder, cs.param, cmd->value);
703 if (length >= 0x4000) {
704 StrgenFatal(
"string too long");
707 if (length >= 0xC0) {
708 buffer[offs++] =
static_cast<char>(
static_cast<uint8_t
>((length >> 8) | 0xC0));
710 buffer[offs++] =
static_cast<char>(
static_cast<uint8_t
>(length & 0xFF));
711 this->
Write({buffer, offs});
720 std::vector<size_t> in_use;
721 for (
size_t tab = 0; tab < data.
tabs; tab++) {
725 _strgen.
lang.
offsets[tab] = TO_LE16(
static_cast<uint16_t
>(n));
727 for (
size_t j = 0; j != in_use[tab]; j++) {
740 for (
size_t tab = 0; tab < data.
tabs; tab++) {
741 for (
size_t j = 0; j != in_use[tab]; j++) {
752 _cur_ident = ls->
name;
757 if (_strgen.show_warnings) {
758 StrgenWarning(
"'{}' is untranslated", ls->
name);
760 if (_strgen.annotate_todos) {
761 builder.
Put(
"<TODO> ");
766 _cur_pcs = ExtractCommandString(ls->
english,
false);
776 builder.
PutUtf8(SCC_SWITCH_CASE);
781 auto case_str = PutCommandString(c.string);
783 builder.
PutUint16LE(
static_cast<uint16_t
>(case_str.size()));
784 builder.
Put(case_str);
789 if (!cmdp.empty()) def_str = PutCommandString(cmdp);
791 builder.
PutUint16LE(
static_cast<uint16_t
>(def_str.size()));
793 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?