11#include "../core/endian_func.hpp"
12#include "../core/mem_func.hpp"
13#include "../error_func.h"
14#include "../string_func.h"
15#include "../table/control_codes.h"
20#include "../table/strgen_tables.h"
22#include "../safeguards.h"
28const char *
_file =
"(unknown file)";
30int _errors, _warnings, _show_todo;
33static const CmdStruct *ParseCommandString(
const char **str, std::string ¶m,
int *argno,
int *casei);
41 caseidx(caseidx), string(string)
53 name(name), english(english), index(index), line(line)
91 this->
strings[ls->index].swap(ls);
115 for (; *s !=
'\0'; s++) {
116 hash = std::rotl(hash, 3) ^ *s;
117 hash = (hash & 1 ? hash >> 1 ^ 0xDEADBEEF : hash >> 1);
140 s = ls->
name.c_str();
141 hash ^= i * 0x717239;
142 hash = (hash & 1 ? hash >> 1 ^ 0xDEADBEEF : hash >> 1);
146 while ((cs = ParseCommandString(&s, buf, &argno, &casei)) !=
nullptr) {
149 hash ^= (cs - _cmd_structs) * 0x1234567;
150 hash = (hash & 1 ? hash >> 1 ^ 0xF00BAA4 : hash >> 1);
169static const char *_cur_ident;
173static int _cur_argidx;
183 this->push_back(value);
193 this->push_back(value);
194 }
else if (value < 0x800) {
195 this->push_back(0xC0 +
GB(value, 6, 5));
196 this->push_back(0x80 +
GB(value, 0, 6));
197 }
else if (value < 0x10000) {
198 this->push_back(0xE0 +
GB(value, 12, 4));
199 this->push_back(0x80 +
GB(value, 6, 6));
200 this->push_back(0x80 +
GB(value, 0, 6));
201 }
else if (value < 0x110000) {
202 this->push_back(0xF0 +
GB(value, 18, 3));
203 this->push_back(0x80 +
GB(value, 12, 6));
204 this->push_back(0x80 +
GB(value, 6, 6));
205 this->push_back(0x80 +
GB(value, 0, 6));
207 StrgenWarning(
"Invalid unicode value U+0x{:X}", value);
212size_t Utf8Validate(
const char *s)
219 }
else if (
GB(s[0], 5, 3) == 6 && IsUtf8Part(s[1])) {
221 c =
GB(s[0], 0, 5) << 6 |
GB(s[1], 0, 6);
222 if (c >= 0x80)
return 2;
223 }
else if (
GB(s[0], 4, 4) == 14 && IsUtf8Part(s[1]) && IsUtf8Part(s[2])) {
225 c =
GB(s[0], 0, 4) << 12 |
GB(s[1], 0, 6) << 6 |
GB(s[2], 0, 6);
226 if (c >= 0x800)
return 3;
227 }
else if (
GB(s[0], 3, 5) == 30 && IsUtf8Part(s[1]) && IsUtf8Part(s[2]) && IsUtf8Part(s[3])) {
229 c =
GB(s[0], 0, 3) << 18 |
GB(s[1], 0, 6) << 12 |
GB(s[2], 0, 6) << 6 |
GB(s[3], 0, 6);
230 if (c >= 0x10000 && c <= 0x10FFFF)
return 4;
237void EmitSingleChar(
Buffer *buffer,
char *buf,
int value)
239 if (*buf !=
'\0') StrgenWarning(
"Ignoring trailing letters in command");
250bool ParseRelNum(
char **buf,
int *value,
int *offset)
252 const char *s = *buf;
256 while (*s ==
' ' || *s ==
'\t') s++;
261 int v = std::strtol(s, &end, 0);
262 if (end == s)
return false;
268 if (offset !=
nullptr && *end ==
':') {
271 *offset = std::strtol(s, &end, 0);
272 if (end == s)
return false;
279char *ParseWord(
char **buf)
283 while (*s ==
' ' || *s ==
'\t') s++;
284 if (*s ==
'\0')
return nullptr;
290 if (*s ==
'\0')
break;
301 if (*s ==
'\0')
break;
302 if (*s ==
' ' || *s ==
'\t') {
314static int TranslateArgumentIdx(
int arg,
int offset = 0);
316static void EmitWordList(
Buffer *buffer,
const std::vector<const char *> &words, uint nw)
319 constexpr uint MAX_WORD_LENGTH = UINT8_MAX - 2;
322 for (uint i = 0; i < nw; i++) {
323 size_t len = strlen(words[i]) + 1;
324 if (len >= UINT8_MAX) StrgenFatal(
"WordList {}/{} string '{}' too long, max bytes {}", i + 1, nw, words[i], MAX_WORD_LENGTH);
325 buffer->
AppendByte(
static_cast<uint8_t
>(len));
327 for (uint i = 0; i < nw; i++) {
328 for (uint j = 0; words[i][j] !=
'\0'; j++) buffer->
AppendByte(words[i][j]);
333void EmitPlural(
Buffer *buffer,
char *buf,
int)
335 int argidx = _cur_argidx;
338 std::vector<const char *> words(std::max(expected,
MAX_PLURALS),
nullptr);
342 if (!ParseRelNum(&buf, &argidx, &offset)) argidx--;
344 const CmdStruct *cmd = _cur_pcs.consuming_commands[argidx];
347 if (cmd ==
nullptr || cmd->default_plural_offset < 0) {
348 StrgenFatal(
"Command '{}' has no (default) plural position", cmd ==
nullptr ?
"<empty>" : cmd->cmd);
350 offset = cmd->default_plural_offset;
355 words[nw] = ParseWord(&buf);
356 if (words[nw] ==
nullptr)
break;
360 StrgenFatal(
"{}: No plural words", _cur_ident);
363 if (expected != nw) {
365 StrgenFatal(
"{}: Invalid number of plural forms. Expecting {}, found {}.", _cur_ident,
368 if ((_show_todo & 2) != 0) StrgenWarning(
"'{}' is untranslated. Tweaking english string to allow compilation for plural forms", _cur_ident);
372 for (; nw < expected; nw++) {
373 words[nw] = words[nw - 1];
381 buffer->
AppendByte(TranslateArgumentIdx(argidx, offset));
382 EmitWordList(buffer, words, nw);
385void EmitGender(
Buffer *buffer,
char *buf,
int)
387 int argidx = _cur_argidx;
396 if (nw >=
MAX_NUM_GENDERS) StrgenFatal(
"G argument '{}' invalid", buf);
406 ParseRelNum(&buf, &argidx, &offset);
408 const CmdStruct *cmd = _cur_pcs.consuming_commands[argidx];
410 StrgenFatal(
"Command '{}' can't have a gender", cmd ==
nullptr ?
"<empty>" : cmd->cmd);
414 words[nw] = ParseWord(&buf);
415 if (words[nw] ==
nullptr)
break;
417 if (nw !=
_lang.
num_genders) StrgenFatal(
"Bad # of arguments for gender command");
419 assert(
IsInsideBS(cmd->value, SCC_CONTROL_START, UINT8_MAX));
421 buffer->
AppendByte(TranslateArgumentIdx(argidx, offset));
422 EmitWordList(buffer, words, nw);
426static const CmdStruct *FindCmd(
const char *s,
int len)
428 for (
const auto &cs : _cmd_structs) {
429 if (strncmp(cs.cmd, s, len) == 0 && cs.cmd[len] ==
'\0')
return &cs;
434static uint ResolveCaseName(
const char *str,
size_t len)
438 len = std::min(
lengthof(case_str) - 1, len);
439 memcpy(case_str, str, len);
440 case_str[len] =
'\0';
443 if (case_idx >=
MAX_NUM_CASES) StrgenFatal(
"Invalid case-name '{}'", case_str);
450static const CmdStruct *ParseCommandString(
const char **str, std::string ¶m,
int *argno,
int *casei)
452 const char *s = *str, *start;
459 for (; *s !=
'{'; s++) {
460 if (*s ==
'\0')
return nullptr;
464 if (*s >=
'0' && *s <=
'9') {
467 *argno = std::strtoul(s, &end, 0);
468 if (*end !=
':') StrgenFatal(
"missing arg #");
476 }
while (c !=
'}' && c !=
' ' && c !=
'=' && c !=
'.' && c != 0);
478 const CmdStruct *cmd = FindCmd(start, s - start - 1);
479 if (cmd ==
nullptr) {
480 std::string command(start, s - start - 1);
481 StrgenError(
"Undefined command '{}'", command);
486 const char *casep = s;
489 StrgenFatal(
"Command '{}' can't have a case", cmd->cmd);
494 }
while (c !=
'}' && c !=
' ' && c !=
'\0');
495 *casei = ResolveCaseName(casep, s - casep - 1);
499 StrgenError(
"Missing }} from command '{}'", start);
512 StrgenError(
"Missing }} from command '{}'", start);
532 data(data), file(file), master(master), translation(translation)
547 const CmdStruct *ar = ParseCommandString(&s, param, &argno, &casei);
549 if (ar ==
nullptr)
break;
552 if (argno != -1 && ar->consumes == 0) StrgenFatal(
"Non consumer param can't have a paramindex");
555 if (argno != -1) argidx = argno;
556 if (argidx < 0 || (uint)argidx >= p.consuming_commands.max_size()) StrgenFatal(
"invalid param idx {}", argidx);
557 if (p.consuming_commands[argidx] !=
nullptr && p.consuming_commands[argidx] != ar) StrgenFatal(
"duplicate param idx {}", argidx);
559 p.consuming_commands[argidx++] = ar;
561 p.non_consuming_commands.emplace_back(
CmdPair{ar, std::move(param)});
571 if (a ==
nullptr)
return nullptr;
573 if (strcmp(a->cmd,
"STRING1") == 0 ||
574 strcmp(a->cmd,
"STRING2") == 0 ||
575 strcmp(a->cmd,
"STRING3") == 0 ||
576 strcmp(a->cmd,
"STRING4") == 0 ||
577 strcmp(a->cmd,
"STRING5") == 0 ||
578 strcmp(a->cmd,
"STRING6") == 0 ||
579 strcmp(a->cmd,
"STRING7") == 0 ||
580 strcmp(a->cmd,
"RAW_STRING") == 0) {
581 return FindCmd(
"STRING", 6);
588static bool CheckCommandsMatch(
const char *a,
const char *b,
const char *name)
602 if (templ.non_consuming_commands.max_size() != lang.non_consuming_commands.max_size()) {
603 StrgenWarning(
"{}: template string and language string have a different # of commands", name);
607 for (
auto &templ_nc : templ.non_consuming_commands) {
610 for (
auto &lang_nc : lang.non_consuming_commands) {
611 if (templ_nc.cmd == lang_nc.cmd && templ_nc.param == lang_nc.param) {
613 lang_nc.cmd =
nullptr;
620 StrgenWarning(
"{}: command '{}' exists in template file but not in language file", name, templ_nc.cmd->cmd);
627 for (uint i = 0; i < templ.consuming_commands.max_size(); i++) {
628 if (TranslateCmdForCompare(templ.consuming_commands[i]) != lang.consuming_commands[i]) {
629 StrgenWarning(
"{}: Param idx #{} '{}' doesn't match with template command '{}'", name, i,
630 lang.consuming_commands[i] ==
nullptr ?
"<empty>" : TranslateCmdForCompare(lang.consuming_commands[i])->cmd,
631 templ.consuming_commands[i] == nullptr ?
"<empty>" : templ.consuming_commands[i]->cmd);
639void StringReader::HandleString(
char *str)
642 if (str[1] ==
'#' && str[2] !=
'#') this->
HandlePragma(str + 2);
647 if (*str ==
';' || *str ==
' ' || *str ==
'\0')
return;
649 char *s = strchr(str,
':');
651 StrgenError(
"Line has no ':' delimiter");
658 for (t = s; t > str && (t[-1] ==
' ' || t[-1] ==
'\t'); t--) {}
664 for (tmp = s; *tmp !=
'\0';) {
665 size_t len = Utf8Validate(tmp);
666 if (len == 0) StrgenFatal(
"Invalid UTF-8 sequence in '{}'", s);
672 (c >= 0xE000 && c <= 0xF8FF) ||
673 (c >= 0xFFF0 && c <= 0xFFFF)) {
674 StrgenFatal(
"Unwanted UTF-8 character U+{:04X} in sequence '{}'", (
int)c, s);
682 char *casep = strchr(str,
'.');
683 if (casep !=
nullptr) *casep++ =
'\0';
689 if (casep !=
nullptr) {
690 StrgenError(
"Cases in the base translation are not supported.");
694 if (ent !=
nullptr) {
695 StrgenError(
"String name '{}' is used multiple times", str);
699 if (this->
data.
strings[this->data.next_string_id] !=
nullptr) {
700 StrgenError(
"String ID 0x{:X} for '{}' already in use by '{}'", this->
data.
next_string_id, str, this->data.strings[this->data.next_string_id]->name);
707 if (ent ==
nullptr) {
708 StrgenWarning(
"String name '{}' does not exist in master file", str);
712 if (!ent->
translated.empty() && casep ==
nullptr) {
713 StrgenError(
"String name '{}' is used multiple times", str);
718 if (!CheckCommandsMatch(s, ent->
english.c_str(), str))
return;
720 if (casep !=
nullptr) {
721 ent->
translated_cases.emplace_back(ResolveCaseName(casep, strlen(casep)), s);
734 if (!memcmp(str,
"plural ", 7)) {
740 StrgenFatal(
"unknown pragma '{}'", str);
744static void StripTrailingWhitespace(std::string &str)
746 str.erase(str.find_last_not_of(
"\r\n ") + 1);
751 _warnings = _errors = 0;
768 std::optional<std::string> line = this->
ReadLine();
769 if (!line.has_value())
return;
771 StripTrailingWhitespace(line.value());
772 this->HandleString(line.value().data());
777 StrgenError(
"Too many strings, maximum allowed is {}", this->
data.
max_strings);
789 if (data.
strings[i] !=
nullptr) {
798static int TranslateArgumentIdx(
int argidx,
int offset)
802 if (argidx < 0 || (uint)argidx >= _cur_pcs.consuming_commands.max_size()) {
803 StrgenFatal(
"invalid argidx {}", argidx);
805 const CmdStruct *cs = _cur_pcs.consuming_commands[argidx];
806 if (cs !=
nullptr && cs->consumes <= offset) {
807 StrgenFatal(
"invalid argidx offset {}:{}", argidx, offset);
810 if (_cur_pcs.consuming_commands[argidx] ==
nullptr) {
811 StrgenFatal(
"no command for this argidx {}", argidx);
814 for (
int i = sum = 0; i < argidx; i++) {
815 cs = _cur_pcs.consuming_commands[i];
817 sum += (cs !=
nullptr) ? cs->consumes : 1;
823static void PutArgidxCommand(
Buffer *buffer)
826 buffer->
AppendByte(TranslateArgumentIdx(_cur_argidx));
830static void PutCommandString(
Buffer *buffer,
const char *str)
834 while (*str !=
'\0') {
844 const CmdStruct *cs = ParseCommandString(&str, param, &argno, &casei);
845 if (cs ==
nullptr)
break;
853 if (cs->consumes > 0) {
855 if (argno != -1 && argno != _cur_argidx) {
857 PutArgidxCommand(buffer);
861 cs = _cur_pcs.consuming_commands[_cur_argidx++];
863 StrgenFatal(
"{}: No argument exists at position {}", _cur_ident, _cur_argidx - 1);
867 cs->proc(buffer, param.data(), cs->value);
879 if (length >= 0x4000) {
880 StrgenFatal(
"string too long");
883 if (length >= 0xC0) {
884 buffer[offs++] = (length >> 8) | 0xC0;
886 buffer[offs++] = length & 0xFF;
887 this->
Write((uint8_t*)buffer, offs);
896 std::vector<uint> in_use;
897 for (
size_t tab = 0; tab < data.
tabs; tab++) {
903 for (uint j = 0; j != in_use[tab]; j++) {
917 for (
size_t tab = 0; tab < data.
tabs; tab++) {
918 for (uint j = 0; j != in_use[tab]; j++) {
920 const std::string *cmdp;
928 _cur_ident = ls->
name.c_str();
932 if (_show_todo > 0 && ls->
translated.empty()) {
933 if ((_show_todo & 2) != 0) {
934 StrgenWarning(
"'{}' is untranslated", ls->
name);
936 if ((_show_todo & 1) != 0) {
937 const char *s =
"<TODO> ";
943 _cur_pcs = ExtractCommandString(ls->
english.c_str(),
false);
965 uint pos = (uint)buffer.size();
969 PutCommandString(&buffer, c.string.c_str());
972 uint size = (uint)buffer.size() - (pos + 2);
973 buffer[pos + 0] =
GB(size, 8, 8);
974 buffer[pos + 1] =
GB(size, 0, 8);
978 if (!cmdp->empty()) PutCommandString(&buffer, cmdp->c_str());
981 this->
Write(buffer.data(), buffer.size());
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
static const uint8_t MAX_NUM_GENDERS
Maximum number of supported genders.
static const uint8_t CASE_GENDER_LEN
The (maximum) length of a case/gender string.
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.
void MemSetT(T *ptr, uint8_t value, size_t num=1)
Type-safe version of memset().
#define lengthof(array)
Return the length of an fixed size array.
Structures related to strgen.
LanguagePackHeader _lang
Header information about a language.
int _cur_line
The current line we're parsing in the input file.
const char * _file
The filename of the input, so we can refer to it in errors/warnings.
LanguagePackHeader _lang
Header information about a language.
static bool _translated
Whether the current language is not the master language.
int _cur_line
The current line we're parsing in the input file.
static bool _translation
Is the current file actually a translation or not.
const char * _file
The filename of the input, so we can refer to it in errors/warnings.
static const int MAX_PLURALS
The maximum number of plurals.
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.
void strecpy(std::span< char > dst, std::string_view src)
Copies characters from one buffer to another.
size_t Utf8Decode(char32_t *c, const char *s)
Decode and consume the next UTF-8 encoded character.
static const uint TAB_SIZE
Number of strings per StringTab.
The buffer for writing a single string.
void AppendUtf8(uint32_t value)
Add an Unicode character encoded in UTF-8 to the buffer.
void AppendByte(uint8_t value)
Convenience method for adding a byte.
Container for the different cases of a string.
Case(int caseidx, const std::string &string)
Create a new case.
Information about a single string.
int line
Line of string in source-file.
LangString(const std::string &name, const std::string &english, size_t index, int line)
Create a new string.
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.
virtual void WriteHeader(const LanguagePackHeader *header)=0
Write the header metadata.
virtual void WriteLength(uint length)
Write the length as a simple gamma.
virtual void Write(const uint8_t *buffer, size_t length)=0
Write a number of bytes.
virtual void WriteLang(const StringData &data)
Actually write the language.
Information about the currently known strings.
size_t tabs
The number of 'tabs' of strings.
uint CountInUse(uint tab) const
Count the number of tab elements that are in use.
uint VersionHashStr(uint hash, const char *s) const
Create a compound hash.
std::vector< std::unique_ptr< LangString > > strings
List of all known strings.
size_t max_strings
The maximum number of strings.
void Add(std::unique_ptr< LangString > ls)
Add a newly created LangString.
size_t next_string_id
The next string ID to allocate.
uint Version() const
Make a hash of the file to get a unique "version number".
LangString * Find(const std::string_view s)
Find a LangString based on the string name.
void FreeTranslation()
Free all data related to the translation.
StringData(size_t tabs)
Create a new string data container.
std::unordered_map< std::string_view, LangString * > name_to_string
Lookup table for the strings.
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 std::optional< std::string > ReadLine()=0
Read a single line from the source of strings.
virtual void HandlePragma(char *str)
Handle the pragma of the file.
bool master
Are we reading the master file?