Skip to content

Commit 49219de

Browse files
committed
Merge pull request godotengine#108862 from timothyqiu/plural-rules
Move context and plural support to `Translation`
2 parents 1ae616d + 4e80190 commit 49219de

15 files changed

+675
-475
lines changed

core/io/translation_loader_po.cpp

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,16 @@
3131
#include "translation_loader_po.h"
3232

3333
#include "core/io/file_access.h"
34-
#include "core/string/translation_po.h"
34+
#include "core/string/translation.h"
3535

3636
Ref<Resource> TranslationLoaderPO::load_translation(Ref<FileAccess> f, Error *r_error) {
3737
if (r_error) {
3838
*r_error = ERR_FILE_CORRUPT;
3939
}
4040

4141
const String path = f->get_path();
42-
Ref<TranslationPO> translation = Ref<TranslationPO>(memnew(TranslationPO));
42+
Ref<Translation> translation;
43+
translation.instantiate();
4344
String config;
4445

4546
uint32_t magic = f->get_32();
@@ -112,7 +113,7 @@ Ref<Resource> TranslationLoaderPO::load_translation(Ref<FileAccess> f, Error *r_
112113
int p_start = config.find("Plural-Forms");
113114
if (p_start != -1) {
114115
int p_end = config.find_char('\n', p_start);
115-
translation->set_plural_rule(config.substr(p_start, p_end - p_start));
116+
translation->set_plural_rules_override(config.substr(p_start, p_end - p_start));
116117
}
117118
} else {
118119
uint32_t str_start = 0;
@@ -228,8 +229,8 @@ Ref<Resource> TranslationLoaderPO::load_translation(Ref<FileAccess> f, Error *r_
228229
int p_start = config.find("Plural-Forms");
229230
if (p_start != -1) {
230231
int p_end = config.find_char('\n', p_start);
231-
translation->set_plural_rule(config.substr(p_start, p_end - p_start));
232-
plural_forms = translation->get_plural_forms();
232+
translation->set_plural_rules_override(config.substr(p_start, p_end - p_start));
233+
plural_forms = translation->get_nplurals();
233234
}
234235
}
235236

core/io/translation_loader_po.h

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@
3232

3333
#include "core/io/file_access.h"
3434
#include "core/io/resource_loader.h"
35-
#include "core/string/translation.h"
3635

3736
class TranslationLoaderPO : public ResourceFormatLoader {
3837
GDSOFTCLASS(TranslationLoaderPO, ResourceFormatLoader);

core/string/locales.h

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,3 +1194,50 @@ static const char *script_list[][2] = {
11941194
{ "Zanabazar Square", "Zanb" },
11951195
{ nullptr, nullptr }
11961196
};
1197+
1198+
// Plural rules.
1199+
// Reference:
1200+
// - https://github.com/unicode-org/cldr/blob/main/common/supplemental/plurals.xml
1201+
static const char *plural_rules[][2] = {
1202+
{ "bm bo dz hnj id ig ii in ja jbo jv jw kde kea km ko lkt lo ms my nqo osa root sah ses sg su th to tpi vi wo yo yue zh", "nplurals=1; plural=0;" },
1203+
{ "am as bn doi fa gu hi kn pcm zu", "nplurals=2; plural=(n==0 || n==1);" },
1204+
{ "ff hy kab", "nplurals=2; plural=(n > 1);" },
1205+
{ "ast de en et fi fy gl ia io ji lij nl sc sv sw ur yi", "nplurals=2; plural=(n != 1);" },
1206+
{ "si", "nplurals=2; plural=(n > 1);" },
1207+
{ "ak bho csw guw ln mg nso pa ti wa", "nplurals=2; plural=(n > 1);" },
1208+
{ "tzm", "nplurals=2; plural=(n<=1 || (n>=11 && n<=99));" },
1209+
{ "af an asa az bal bem bez bg brx ce cgg chr ckb dv ee el eo eu fo fur gsw ha haw hu jgo jmc ka kaj kcg kk kkj kl ks ksb ku ky lb lg mas mgo ml mn mr nah nb nd ne nn nnh no nr ny nyn om or os pap ps rm rof rwk saq sd sdh seh sn so sq ss ssy st syr ta te teo tig tk tn tr ts ug uz ve vo vun wae xh xog", "nplurals=2; plural=(n != 1);" },
1210+
{ "da", "nplurals=2; plural=(n != 1);" },
1211+
{ "is", "nplurals=2; plural=(n%10==1 && n%100!=11);" },
1212+
{ "mk", "nplurals=2; plural=(n%10==1 && n%100!=11);" },
1213+
{ "ceb fil tl", "nplurals=2; plural=(n==1 || n==2 || n==3 || (n%10!=4 && n%10!=6 && n%10!=9));" },
1214+
{ "lv prg", "nplurals=3; plural=(n%10==0 || (n%100>=11 && n%100<=19) ? 0 : n%10==1 && n%100!=11 ? 1 : 2);" },
1215+
{ "lag", "nplurals=3; plural=(n==0 ? 0 : (n==0 || n==1) && n!=0 ? 1 : 2);" },
1216+
{ "blo", "nplurals=3; plural=(n==0 ? 0 : n==1 ? 1 : 2);" },
1217+
{ "ksh", "nplurals=3; plural=(n==0 ? 0 : n==1 ? 1 : 2);" },
1218+
{ "he iw", "nplurals=3; plural=(n==1 ? 0 : n==2 ? 1 : 2);" },
1219+
{ "iu naq sat se sma smi smj smn sms", "nplurals=3; plural=(n==1 ? 0 : n==2 ? 1 : 2);" },
1220+
{ "shi", "nplurals=3; plural=(n==0 || n==1 ? 0 : n>=2 && n<=10 ? 1 : 2);" },
1221+
{ "mo ro", "nplurals=3; plural=(n==1 ? 0 : n==0 || (n!=1 && n%100>=1 && n%100<=19) ? 1 : 2);" },
1222+
{ "bs hr sh sr", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);" },
1223+
{ "fr", "nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % 1000000 == 0 ? 1 : 2);" },
1224+
{ "pt", "nplurals=3; plural=((n == 0 || n == 1) ? 0 : n != 0 && n % 1000000 == 0 ? 1 : 2);" },
1225+
{ "ca it lld pt_PT scn vec", "nplurals=3; plural=(n == 1 ? 0 : n != 0 && n % 1000000 == 0 ? 1 : 2);" },
1226+
{ "es", "nplurals=3; plural=(n == 1 ? 0 : n != 0 && n % 1000000 == 0 ? 1 : 2);" },
1227+
{ "gd", "nplurals=4; plural=(n==1 || n==11 ? 0 : n==2 || n==12 ? 1 : (n>=3 && n<=10) || (n>=13 && n<=19) ? 2 : 3);" },
1228+
{ "sl", "nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100>=3 && n%100<=4 ? 2 : 3);" },
1229+
{ "dsb hsb", "nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100>=3 && n%100<=4 ? 2 : 3);" },
1230+
{ "cs sk", "nplurals=3; plural=(n==1 ? 0 : n>=2 && n<=4 ? 1 : 2);" },
1231+
{ "pl", "nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);" },
1232+
{ "be", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);" },
1233+
{ "lt", "nplurals=3; plural=(n%10==1 && (n%100<11 || n%100>19) ? 0 : n%10>=2 && n%10<=9 && (n%100<11 || n%100>19) ? 1 : 2);" },
1234+
{ "ru uk", "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);" },
1235+
{ "br", "nplurals=5; plural=(n%10==1 && n%100!=11 && n%100!=71 && n%100!=91 ? 0 : n%10==2 && n%100!=12 && n%100!=72 && n%100!=92 ? 1 : ((n%10>=3 && n%10<=4) || n%10==9) && (n%100<10 || n%100>19) && (n%100<70 || n%100>79) && (n%100<90 || n%100>99) ? 2 : n!=0 && n%1000000==0 ? 3 : 4);" },
1236+
{ "mt", "nplurals=5; plural=(n==1 ? 0 : n==2 ? 1 : n==0 || (n%100>=3 && n%100<=10) ? 2 : n%100>=11 && n%100<=19 ? 3 : 4);" },
1237+
{ "ga", "nplurals=5; plural=(n==1 ? 0 : n==2 ? 1 : n>=3 && n<=6 ? 2 : n>=7 && n<=10 ? 3 : 4);" },
1238+
{ "gv", "nplurals=4; plural=(n%10==1 ? 0 : n%10==2 ? 1 : n%100==0 || n%100==20 || n%100==40 || n%100==60 || n%100==80 ? 2 : 3);" },
1239+
{ "kw", "nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n%100==2 || n%100==22 || n%100==42 || n%100==62 || n%100==82 || (n%1000==0 && ((n%100000>=1000 && n%100000<=20000) || n%100000==40000 || n%100000==60000 || n%100000==80000)) || (n!=0 && n%1000000==100000) ? 2 : n%100==3 || n%100==23 || n%100==43 || n%100==63 || n%100==83 ? 3 : n!=1 && (n%100==1 || n%100==21 || n%100==41 || n%100==61 || n%100==81) ? 4 : 5);" },
1240+
{ "ar ars", "nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5);" },
1241+
{ "cy", "nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n==3 ? 3 : n==6 ? 4 : 5);" },
1242+
{ nullptr, nullptr },
1243+
};

core/string/optimized_translation.cpp

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,27 @@ struct CompressedString {
4444

4545
void OptimizedTranslation::generate(const Ref<Translation> &p_from) {
4646
// This method compresses a Translation instance.
47-
// Right now, it doesn't handle context or plurals, so Translation subclasses using plurals or context (i.e TranslationPO) shouldn't be compressed.
47+
// Right now, it doesn't handle context or plurals.
4848
#ifdef TOOLS_ENABLED
4949
ERR_FAIL_COND(p_from.is_null());
50+
5051
List<StringName> keys;
51-
p_from->get_message_list(&keys);
52+
{
53+
List<StringName> raw_keys;
54+
p_from->get_message_list(&raw_keys);
55+
56+
for (const StringName &key : raw_keys) {
57+
const String key_str = key.operator String();
58+
int p = key_str.find_char(0x04);
59+
if (p == -1) {
60+
keys.push_back(key);
61+
} else {
62+
const String &msgctxt = key_str.substr(0, p);
63+
const String &msgid = key_str.substr(p + 1);
64+
WARN_PRINT(vformat("OptimizedTranslation does not support context, ignoring message '%s' with context '%s'.", msgid, msgctxt));
65+
}
66+
}
67+
}
5268

5369
int size = Math::larger_prime(keys.size());
5470

core/string/plural_rules.cpp

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
/**************************************************************************/
2+
/* plural_rules.cpp */
3+
/**************************************************************************/
4+
/* This file is part of: */
5+
/* GODOT ENGINE */
6+
/* https://godotengine.org */
7+
/**************************************************************************/
8+
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9+
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10+
/* */
11+
/* Permission is hereby granted, free of charge, to any person obtaining */
12+
/* a copy of this software and associated documentation files (the */
13+
/* "Software"), to deal in the Software without restriction, including */
14+
/* without limitation the rights to use, copy, modify, merge, publish, */
15+
/* distribute, sublicense, and/or sell copies of the Software, and to */
16+
/* permit persons to whom the Software is furnished to do so, subject to */
17+
/* the following conditions: */
18+
/* */
19+
/* The above copyright notice and this permission notice shall be */
20+
/* included in all copies or substantial portions of the Software. */
21+
/* */
22+
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23+
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24+
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25+
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26+
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27+
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28+
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29+
/**************************************************************************/
30+
31+
#include "plural_rules.h"
32+
33+
#include "core/math/expression.h"
34+
35+
int PluralRules::_eq_test(const Array &p_input_val, const Ref<EQNode> &p_node, const Variant &p_result) const {
36+
if (p_node.is_null()) {
37+
return p_result;
38+
}
39+
40+
static const Vector<String> input_name = { "n" };
41+
42+
Error err = expr->parse(p_node->regex, input_name);
43+
ERR_FAIL_COND_V_MSG(err != OK, 0, vformat("Cannot parse expression \"%s\". Error: %s", p_node->regex, expr->get_error_text()));
44+
45+
Variant result = expr->execute(p_input_val);
46+
ERR_FAIL_COND_V_MSG(expr->has_execute_failed(), 0, vformat("Cannot evaluate expression \"%s\".", p_node->regex));
47+
48+
if (bool(result)) {
49+
return _eq_test(p_input_val, p_node->left, result);
50+
} else {
51+
return _eq_test(p_input_val, p_node->right, result);
52+
}
53+
}
54+
55+
int PluralRules::_find_unquoted(const String &p_src, char32_t p_chr) const {
56+
const int len = p_src.length();
57+
if (len == 0) {
58+
return -1;
59+
}
60+
61+
const char32_t *src = p_src.get_data();
62+
bool in_quote = false;
63+
for (int i = 0; i < len; i++) {
64+
if (in_quote) {
65+
if (src[i] == ')') {
66+
in_quote = false;
67+
}
68+
} else {
69+
if (src[i] == '(') {
70+
in_quote = true;
71+
} else if (src[i] == p_chr) {
72+
return i;
73+
}
74+
}
75+
}
76+
77+
return -1;
78+
}
79+
80+
void PluralRules::_cache_plural_tests(const String &p_plural_rule, Ref<EQNode> &p_node) {
81+
// Some examples of p_plural_rule passed in can have the form:
82+
// "n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5" (Arabic)
83+
// "n >= 2" (French) // When evaluating the last, especially careful with this one.
84+
// "n != 1" (English)
85+
86+
String rule = p_plural_rule;
87+
if (rule.begins_with("(") && rule.ends_with(")")) {
88+
int bcount = 0;
89+
for (int i = 1; i < rule.length() - 1 && bcount >= 0; i++) {
90+
if (rule[i] == '(') {
91+
bcount++;
92+
} else if (rule[i] == ')') {
93+
bcount--;
94+
}
95+
}
96+
if (bcount == 0) {
97+
rule = rule.substr(1, rule.length() - 2);
98+
}
99+
}
100+
101+
int first_ques_mark = _find_unquoted(rule, '?');
102+
int first_colon = _find_unquoted(rule, ':');
103+
104+
if (first_ques_mark == -1) {
105+
p_node->regex = rule.strip_edges();
106+
return;
107+
}
108+
109+
p_node->regex = rule.substr(0, first_ques_mark).strip_edges();
110+
111+
p_node->left.instantiate();
112+
_cache_plural_tests(rule.substr(first_ques_mark + 1, first_colon - first_ques_mark - 1).strip_edges(), p_node->left);
113+
p_node->right.instantiate();
114+
_cache_plural_tests(rule.substr(first_colon + 1).strip_edges(), p_node->right);
115+
}
116+
117+
int PluralRules::evaluate(int p_n) const {
118+
const int *cached = cache.getptr(p_n);
119+
if (cached) {
120+
return *cached;
121+
}
122+
123+
const Array &input_val = { p_n };
124+
int index = _eq_test(input_val, equi_tests, 0);
125+
cache.insert(p_n, index);
126+
return index;
127+
}
128+
129+
PluralRules::PluralRules(int p_nplurals, const String &p_plural) :
130+
nplurals(p_nplurals),
131+
plural(p_plural) {
132+
equi_tests.instantiate();
133+
_cache_plural_tests(plural, equi_tests);
134+
135+
expr.instantiate();
136+
}
137+
138+
PluralRules *PluralRules::parse(const String &p_rules) {
139+
// `p_rules` should be in the format "nplurals=<N>; plural=<Expression>;".
140+
141+
const int nplurals_eq = p_rules.find_char('=');
142+
ERR_FAIL_COND_V_MSG(nplurals_eq == -1, nullptr, "Invalid plural rules format. Missing equal sign for `nplurals`.");
143+
144+
const int nplurals_semi_col = p_rules.find_char(';', nplurals_eq);
145+
ERR_FAIL_COND_V_MSG(nplurals_semi_col == -1, nullptr, "Invalid plural rules format. Missing semicolon for `nplurals`.");
146+
147+
const String nplurals_str = p_rules.substr(nplurals_eq + 1, nplurals_semi_col - (nplurals_eq + 1)).strip_edges();
148+
ERR_FAIL_COND_V_MSG(!nplurals_str.is_valid_int(), nullptr, "Invalid plural rules format. `nplurals` should be an integer.");
149+
150+
const int nplurals = nplurals_str.to_int();
151+
ERR_FAIL_COND_V_MSG(nplurals < 1, nullptr, "Invalid plural rules format. `nplurals` should be at least 1.");
152+
153+
const int expression_eq = p_rules.find_char('=', nplurals_semi_col + 1);
154+
ERR_FAIL_COND_V_MSG(expression_eq == -1, nullptr, "Invalid plural rules format. Missing equal sign for `plural`.");
155+
156+
int expression_end = p_rules.rfind_char(';');
157+
if (expression_end == -1) {
158+
WARN_PRINT("Invalid plural rules format. Missing semicolon at the end of `plural` expression. Assuming ends at the end of the string.");
159+
expression_end = p_rules.length();
160+
}
161+
162+
const int expression_start = expression_eq + 1;
163+
ERR_FAIL_COND_V_MSG(expression_end <= expression_start, nullptr, "Invalid plural rules format. `plural` expression is empty.");
164+
165+
const String &plural = p_rules.substr(expression_start, expression_end - expression_start).strip_edges();
166+
return memnew(PluralRules(nplurals, plural));
167+
}

core/string/plural_rules.h

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**************************************************************************/
2+
/* plural_rules.h */
3+
/**************************************************************************/
4+
/* This file is part of: */
5+
/* GODOT ENGINE */
6+
/* https://godotengine.org */
7+
/**************************************************************************/
8+
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9+
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10+
/* */
11+
/* Permission is hereby granted, free of charge, to any person obtaining */
12+
/* a copy of this software and associated documentation files (the */
13+
/* "Software"), to deal in the Software without restriction, including */
14+
/* without limitation the rights to use, copy, modify, merge, publish, */
15+
/* distribute, sublicense, and/or sell copies of the Software, and to */
16+
/* permit persons to whom the Software is furnished to do so, subject to */
17+
/* the following conditions: */
18+
/* */
19+
/* The above copyright notice and this permission notice shall be */
20+
/* included in all copies or substantial portions of the Software. */
21+
/* */
22+
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23+
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24+
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25+
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26+
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27+
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28+
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29+
/**************************************************************************/
30+
31+
#pragma once
32+
33+
#include "core/object/ref_counted.h"
34+
#include "core/templates/lru.h"
35+
36+
class Expression;
37+
38+
class PluralRules : public Object {
39+
GDSOFTCLASS(PluralRules, Object);
40+
41+
mutable LRUCache<int, int> cache;
42+
43+
// These two fields are initialized in the constructor.
44+
const int nplurals;
45+
const String plural;
46+
47+
// Cache temporary variables related to `evaluate()` to make it faster.
48+
class EQNode : public RefCounted {
49+
GDSOFTCLASS(EQNode, RefCounted);
50+
51+
public:
52+
String regex;
53+
Ref<EQNode> left;
54+
Ref<EQNode> right;
55+
};
56+
Ref<EQNode> equi_tests;
57+
Ref<Expression> expr;
58+
59+
int _find_unquoted(const String &p_src, char32_t p_chr) const;
60+
int _eq_test(const Array &p_input_val, const Ref<EQNode> &p_node, const Variant &p_result) const;
61+
void _cache_plural_tests(const String &p_plural_rule, Ref<EQNode> &p_node);
62+
63+
PluralRules(int p_nplurals, const String &p_plural);
64+
65+
public:
66+
int evaluate(int p_n) const;
67+
68+
int get_nplurals() const { return nplurals; }
69+
String get_plural() const { return plural; }
70+
71+
static PluralRules *parse(const String &p_rules);
72+
};

0 commit comments

Comments
 (0)