/
make_intl_data.py
executable file
·4135 lines (3416 loc) · 133 KB
/
make_intl_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
""" Usage:
make_intl_data.py langtags [cldr_core.zip]
make_intl_data.py tzdata
make_intl_data.py currency
make_intl_data.py units
make_intl_data.py numbering
Target "langtags":
This script extracts information about 1) mappings between deprecated and
current Unicode BCP 47 locale identifiers, and 2) deprecated and current
BCP 47 Unicode extension value from CLDR, and converts it to C++ mapping
code in intl/components/LocaleGenerated.cpp. The code is used in
intl/components/Locale.cpp.
Target "tzdata":
This script computes which time zone informations are not up-to-date in ICU
and provides the necessary mappings to workaround this problem.
https://ssl.icu-project.org/trac/ticket/12044
Target "currency":
Generates the mapping from currency codes to decimal digits used for them.
Target "units":
Generate source and test files using the list of so-called "sanctioned unit
identifiers" and verifies that the ICU data filter includes these units.
Target "numbering":
Generate source and test files using the list of numbering systems with
simple digit mappings and verifies that it's in sync with ICU/CLDR.
"""
from __future__ import print_function
import os
import re
import io
import json
import sys
import tarfile
import tempfile
import yaml
from contextlib import closing
from functools import partial, total_ordering
from itertools import chain, groupby, tee
from operator import attrgetter, itemgetter
from zipfile import ZipFile
if sys.version_info.major == 2:
from itertools import (
ifilter as filter,
ifilterfalse as filterfalse,
imap as map,
izip_longest as zip_longest,
)
from urllib2 import urlopen, Request as UrlRequest
from urlparse import urlsplit
else:
from itertools import filterfalse, zip_longest
from urllib.request import urlopen, Request as UrlRequest
from urllib.parse import urlsplit
# From https://docs.python.org/3/library/itertools.html
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
def writeMappingHeader(println, description, source, url):
if type(description) is not list:
description = [description]
for desc in description:
println("// {0}".format(desc))
println("// Derived from {0}.".format(source))
println("// {0}".format(url))
def writeMappingsVar(println, mapping, name, description, source, url):
"""Writes a variable definition with a mapping table.
Writes the contents of dictionary |mapping| through the |println|
function with the given variable name and a comment with description,
fileDate, and URL.
"""
println("")
writeMappingHeader(println, description, source, url)
println("var {0} = {{".format(name))
for (key, value) in sorted(mapping.items(), key=itemgetter(0)):
println(' "{0}": "{1}",'.format(key, value))
println("};")
def writeMappingsBinarySearch(
println,
fn_name,
type_name,
name,
validate_fn,
validate_case_fn,
mappings,
tag_maxlength,
description,
source,
url,
):
"""Emit code to perform a binary search on language tag subtags.
Uses the contents of |mapping|, which can either be a dictionary or set,
to emit a mapping function to find subtag replacements.
"""
println("")
writeMappingHeader(println, description, source, url)
println(
"""
bool mozilla::intl::Locale::{0}({1} {2}) {{
MOZ_ASSERT({3}({2}.span()));
MOZ_ASSERT({4}({2}.span()));
""".format(
fn_name, type_name, name, validate_fn, validate_case_fn
).strip()
)
writeMappingsBinarySearchBody(println, name, name, mappings, tag_maxlength)
println(
"""
}""".lstrip(
"\n"
)
)
def writeMappingsBinarySearchBody(
println, source_name, target_name, mappings, tag_maxlength
):
def write_array(subtags, name, length, fixed):
if fixed:
println(
" static const char {}[{}][{}] = {{".format(
name, len(subtags), length + 1
)
)
else:
println(" static const char* {}[{}] = {{".format(name, len(subtags)))
# Group in pairs of ten to not exceed the 80 line column limit.
for entries in grouper(subtags, 10):
entries = (
'"{}"'.format(tag).rjust(length + 2)
for tag in entries
if tag is not None
)
println(" {},".format(", ".join(entries)))
println(" };")
trailing_return = True
# Sort the subtags by length. That enables using an optimized comparator
# for the binary search, which only performs a single |memcmp| for multiple
# of two subtag lengths.
mappings_keys = mappings.keys() if type(mappings) == dict else mappings
for (length, subtags) in groupby(sorted(mappings_keys, key=len), len):
# Omit the length check if the current length is the maximum length.
if length != tag_maxlength:
println(
"""
if ({}.length() == {}) {{
""".format(
source_name, length
).rstrip(
"\n"
)
)
else:
trailing_return = False
println(
"""
{
""".rstrip(
"\n"
)
)
# The subtags need to be sorted for binary search to work.
subtags = sorted(subtags)
def equals(subtag):
return """{}.equalTo("{}")""".format(source_name, subtag)
# Don't emit a binary search for short lists.
if len(subtags) == 1:
if type(mappings) == dict:
println(
"""
if ({}) {{
{}.set(mozilla::MakeStringSpan("{}"));
return true;
}}
return false;
""".format(
equals(subtags[0]), target_name, mappings[subtags[0]]
).strip(
"\n"
)
)
else:
println(
"""
return {};
""".format(
equals(subtags[0])
).strip(
"\n"
)
)
elif len(subtags) <= 4:
if type(mappings) == dict:
for subtag in subtags:
println(
"""
if ({}) {{
{}.set("{}");
return true;
}}
""".format(
equals(subtag), target_name, mappings[subtag]
).strip(
"\n"
)
)
println(
"""
return false;
""".strip(
"\n"
)
)
else:
cond = (equals(subtag) for subtag in subtags)
cond = (" ||\n" + " " * (4 + len("return "))).join(cond)
println(
"""
return {};
""".format(
cond
).strip(
"\n"
)
)
else:
write_array(subtags, source_name + "s", length, True)
if type(mappings) == dict:
write_array([mappings[k] for k in subtags], "aliases", length, False)
println(
"""
if (const char* replacement = SearchReplacement({0}s, aliases, {0})) {{
{1}.set(mozilla::MakeStringSpan(replacement));
return true;
}}
return false;
""".format(
source_name, target_name
).rstrip()
)
else:
println(
"""
return HasReplacement({0}s, {0});
""".format(
source_name
).rstrip()
)
println(
"""
}
""".strip(
"\n"
)
)
if trailing_return:
println(
"""
return false;"""
)
def writeComplexLanguageTagMappings(
println, complex_language_mappings, description, source, url
):
println("")
writeMappingHeader(println, description, source, url)
println(
"""
void mozilla::intl::Locale::performComplexLanguageMappings() {
MOZ_ASSERT(IsStructurallyValidLanguageTag(language().span()));
MOZ_ASSERT(IsCanonicallyCasedLanguageTag(language().span()));
""".lstrip()
)
# Merge duplicate language entries.
language_aliases = {}
for (deprecated_language, (language, script, region)) in sorted(
complex_language_mappings.items(), key=itemgetter(0)
):
key = (language, script, region)
if key not in language_aliases:
language_aliases[key] = []
else:
language_aliases[key].append(deprecated_language)
first_language = True
for (deprecated_language, (language, script, region)) in sorted(
complex_language_mappings.items(), key=itemgetter(0)
):
key = (language, script, region)
if deprecated_language in language_aliases[key]:
continue
if_kind = "if" if first_language else "else if"
first_language = False
cond = (
'language().equalTo("{}")'.format(lang)
for lang in [deprecated_language] + language_aliases[key]
)
cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond)
println(
"""
{} ({}) {{""".format(
if_kind, cond
).strip(
"\n"
)
)
println(
"""
setLanguage("{}");""".format(
language
).strip(
"\n"
)
)
if script is not None:
println(
"""
if (script().missing()) {{
setScript("{}");
}}""".format(
script
).strip(
"\n"
)
)
if region is not None:
println(
"""
if (region().missing()) {{
setRegion("{}");
}}""".format(
region
).strip(
"\n"
)
)
println(
"""
}""".strip(
"\n"
)
)
println(
"""
}
""".strip(
"\n"
)
)
def writeComplexRegionTagMappings(
println, complex_region_mappings, description, source, url
):
println("")
writeMappingHeader(println, description, source, url)
println(
"""
void mozilla::intl::Locale::performComplexRegionMappings() {
MOZ_ASSERT(IsStructurallyValidLanguageTag(language().span()));
MOZ_ASSERT(IsCanonicallyCasedLanguageTag(language().span()));
MOZ_ASSERT(IsStructurallyValidRegionTag(region().span()));
MOZ_ASSERT(IsCanonicallyCasedRegionTag(region().span()));
""".lstrip()
)
# |non_default_replacements| is a list and hence not hashable. Convert it
# to a string to get a proper hashable value.
def hash_key(default, non_default_replacements):
return (default, str(sorted(str(v) for v in non_default_replacements)))
# Merge duplicate region entries.
region_aliases = {}
for (deprecated_region, (default, non_default_replacements)) in sorted(
complex_region_mappings.items(), key=itemgetter(0)
):
key = hash_key(default, non_default_replacements)
if key not in region_aliases:
region_aliases[key] = []
else:
region_aliases[key].append(deprecated_region)
first_region = True
for (deprecated_region, (default, non_default_replacements)) in sorted(
complex_region_mappings.items(), key=itemgetter(0)
):
key = hash_key(default, non_default_replacements)
if deprecated_region in region_aliases[key]:
continue
if_kind = "if" if first_region else "else if"
first_region = False
cond = (
'region().equalTo("{}")'.format(region)
for region in [deprecated_region] + region_aliases[key]
)
cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond)
println(
"""
{} ({}) {{""".format(
if_kind, cond
).strip(
"\n"
)
)
replacement_regions = sorted(
{region for (_, _, region) in non_default_replacements}
)
first_case = True
for replacement_region in replacement_regions:
replacement_language_script = sorted(
(language, script)
for (language, script, region) in (non_default_replacements)
if region == replacement_region
)
if_kind = "if" if first_case else "else if"
first_case = False
def compare_tags(language, script):
if script is None:
return 'language().equalTo("{}")'.format(language)
return '(language().equalTo("{}") && script().equalTo("{}"))'.format(
language, script
)
cond = (
compare_tags(language, script)
for (language, script) in replacement_language_script
)
cond = (" ||\n" + " " * (4 + len(if_kind) + 2)).join(cond)
println(
"""
{} ({}) {{
setRegion("{}");
}}""".format(
if_kind, cond, replacement_region
)
.rstrip()
.strip("\n")
)
println(
"""
else {{
setRegion("{}");
}}
}}""".format(
default
)
.rstrip()
.strip("\n")
)
println(
"""
}
""".strip(
"\n"
)
)
def writeVariantTagMappings(println, variant_mappings, description, source, url):
"""Writes a function definition that maps variant subtags."""
println(
"""
static const char* ToCharPointer(const char* str) {
return str;
}
static const char* ToCharPointer(const mozilla::intl::UniqueChars& str) {
return str.get();
}
template <typename T, typename U = T>
static bool IsLessThan(const T& a, const U& b) {
return strcmp(ToCharPointer(a), ToCharPointer(b)) < 0;
}
"""
)
writeMappingHeader(println, description, source, url)
println(
"""
bool mozilla::intl::Locale::performVariantMappings() {
// The variant subtags need to be sorted for binary search.
MOZ_ASSERT(std::is_sorted(variants_.begin(), variants_.end(),
IsLessThan<decltype(variants_)::ElementType>));
auto removeVariantAt = [&](size_t index) {
variants_.erase(variants_.begin() + index);
};
auto insertVariantSortedIfNotPresent = [&](const char* variant) {
auto* p = std::lower_bound(
variants_.begin(), variants_.end(), variant,
IsLessThan<decltype(variants_)::ElementType, decltype(variant)>);
// Don't insert the replacement when already present.
if (p != variants_.end() && strcmp(p->get(), variant) == 0) {
return true;
}
// Insert the preferred variant in sort order.
auto preferred = DuplicateStringToUniqueChars(variant);
return !!variants_.insert(p, std::move(preferred));
};
for (size_t i = 0; i < variants_.length();) {
const char* variant = variants_[i].get();
MOZ_ASSERT(IsCanonicallyCasedVariantTag(mozilla::MakeStringSpan(variant)));
""".lstrip()
)
(no_alias, with_alias) = partition(
variant_mappings.items(), lambda item: item[1] is None
)
no_replacements = " ||\n ".join(
f"""strcmp(variant, "{deprecated_variant}") == 0"""
for (deprecated_variant, _) in sorted(no_alias, key=itemgetter(0))
)
println(
f"""
if ({no_replacements}) {{
removeVariantAt(i);
}}
""".strip(
"\n"
)
)
for (deprecated_variant, (type, replacement)) in sorted(
with_alias, key=itemgetter(0)
):
println(
f"""
else if (strcmp(variant, "{deprecated_variant}") == 0) {{
removeVariantAt(i);
""".strip(
"\n"
)
)
if type == "language":
println(
f"""
setLanguage("{replacement}");
""".strip(
"\n"
)
)
elif type == "region":
println(
f"""
setRegion("{replacement}");
""".strip(
"\n"
)
)
else:
assert type == "variant"
println(
f"""
if (!insertVariantSortedIfNotPresent("{replacement}")) {{
return false;
}}
""".strip(
"\n"
)
)
println(
"""
}
""".strip(
"\n"
)
)
println(
"""
else {
i++;
}
}
return true;
}
""".strip(
"\n"
)
)
def writeLegacyMappingsFunction(println, legacy_mappings, description, source, url):
"""Writes a function definition that maps legacy language tags."""
println("")
writeMappingHeader(println, description, source, url)
println(
"""\
bool mozilla::intl::Locale::updateLegacyMappings() {
// We're mapping legacy tags to non-legacy form here.
// Other tags remain unchanged.
//
// Legacy tags are either sign language tags ("sgn") or have one or multiple
// variant subtags. Therefore we can quickly exclude most tags by checking
// these two subtags.
MOZ_ASSERT(IsCanonicallyCasedLanguageTag(language().span()));
if (!language().equalTo("sgn") && variants_.length() == 0) {
return true;
}
#ifdef DEBUG
for (const auto& variant : variants()) {
MOZ_ASSERT(IsStructurallyValidVariantTag(variant));
MOZ_ASSERT(IsCanonicallyCasedVariantTag(variant));
}
#endif
// The variant subtags need to be sorted for binary search.
MOZ_ASSERT(std::is_sorted(variants_.begin(), variants_.end(),
IsLessThan<decltype(variants_)::ElementType>));
auto findVariant = [this](const char* variant) {
auto* p = std::lower_bound(variants_.begin(), variants_.end(), variant,
IsLessThan<decltype(variants_)::ElementType,
decltype(variant)>);
if (p != variants_.end() && strcmp(p->get(), variant) == 0) {
return p;
}
return static_cast<decltype(p)>(nullptr);
};
auto insertVariantSortedIfNotPresent = [&](const char* variant) {
auto* p = std::lower_bound(variants_.begin(), variants_.end(), variant,
IsLessThan<decltype(variants_)::ElementType,
decltype(variant)>);
// Don't insert the replacement when already present.
if (p != variants_.end() && strcmp(p->get(), variant) == 0) {
return true;
}
// Insert the preferred variant in sort order.
auto preferred = DuplicateStringToUniqueChars(variant);
return !!variants_.insert(p, std::move(preferred));
};
auto removeVariant = [&](auto* p) {
size_t index = std::distance(variants_.begin(), p);
variants_.erase(variants_.begin() + index);
};
auto removeVariants = [&](auto* p, auto* q) {
size_t pIndex = std::distance(variants_.begin(), p);
size_t qIndex = std::distance(variants_.begin(), q);
MOZ_ASSERT(pIndex < qIndex, "variant subtags are sorted");
variants_.erase(variants_.begin() + qIndex);
variants_.erase(variants_.begin() + pIndex);
};"""
)
# Helper class for pattern matching.
class AnyClass:
def __eq__(self, obj):
return obj is not None
Any = AnyClass()
# Group the mappings by language.
legacy_mappings_by_language = {}
for (type, replacement) in legacy_mappings.items():
(language, _, _, _) = type
legacy_mappings_by_language.setdefault(language, {})[type] = replacement
# Handle the empty language case first.
if None in legacy_mappings_by_language:
# Get the mappings and remove them from the dict.
mappings = legacy_mappings_by_language.pop(None)
# This case only applies for the "hepburn-heploc" -> "alalc97"
# mapping, so just inline it here.
from_tag = (None, None, None, "hepburn-heploc")
to_tag = (None, None, None, "alalc97")
assert len(mappings) == 1
assert mappings[from_tag] == to_tag
println(
"""
if (variants_.length() >= 2) {
if (auto* hepburn = findVariant("hepburn")) {
if (auto* heploc = findVariant("heploc")) {
removeVariants(hepburn, heploc);
if (!insertVariantSortedIfNotPresent("alalc97")) {
return false;
}
}
}
}
"""
)
# Handle sign languages next.
if "sgn" in legacy_mappings_by_language:
mappings = legacy_mappings_by_language.pop("sgn")
# Legacy sign language mappings have the form "sgn-XX" where "XX" is
# some region code.
assert all(type == ("sgn", None, Any, None) for type in mappings.keys())
# Legacy sign languages are mapped to a single language subtag.
assert all(
replacement == (Any, None, None, None) for replacement in mappings.values()
)
println(
"""
if (language().equalTo("sgn")) {
if (region().present() && signLanguageMapping(language_, region())) {
region_.set(mozilla::MakeStringSpan(""));
}
}
""".rstrip().lstrip(
"\n"
)
)
# Finally handle all remaining cases.
# The remaining mappings have neither script nor region subtags in the source locale.
assert all(
type == (Any, None, None, Any)
for mappings in legacy_mappings_by_language.values()
for type in mappings.keys()
)
# And they have neither script nor region nor variant subtags in the target locale.
assert all(
replacement == (Any, None, None, None)
for mappings in legacy_mappings_by_language.values()
for replacement in mappings.values()
)
# Compact the mappings table by removing empty fields.
legacy_mappings_by_language = {
lang: {
variants: r_language
for ((_, _, _, variants), (r_language, _, _, _)) in mappings.items()
}
for (lang, mappings) in legacy_mappings_by_language.items()
}
# Try to combine the remaining cases.
legacy_mappings_compact = {}
# Python can't hash dicts or lists, so use the string representation as the hash key.
def hash_key(mappings):
return str(sorted(mappings.items(), key=itemgetter(0)))
for (lang, mappings) in sorted(
legacy_mappings_by_language.items(), key=itemgetter(0)
):
key = hash_key(mappings)
legacy_mappings_compact.setdefault(key, []).append(lang)
for langs in legacy_mappings_compact.values():
language_equal_to = (
f"""language().equalTo("{lang}")""" for lang in sorted(langs)
)
cond = f""" ||\n{" " * len(" else if (")}""".join(language_equal_to)
println(
f"""
else if ({cond}) {{
""".rstrip().lstrip(
"\n"
)
)
mappings = legacy_mappings_by_language[langs[0]]
# Count the variant subtags to determine the sort order.
def variant_size(m):
(k, _) = m
return len(k.split("-"))
# Alias rules are applied by largest union size first.
for (size, mappings_by_size) in groupby(
sorted(mappings.items(), key=variant_size, reverse=True), key=variant_size
):
# Convert grouper object to dict.
mappings_by_size = dict(mappings_by_size)
is_first = True
chain_if = size == 1
# Alias rules are applied in alphabetical order
for (variants, r_language) in sorted(
mappings_by_size.items(), key=itemgetter(0)
):
sorted_variants = sorted(variants.split("-"))
len_variants = len(sorted_variants)
maybe_else = "else " if chain_if and not is_first else ""
is_first = False
for (i, variant) in enumerate(sorted_variants):
println(
f"""
{" " * i}{maybe_else}if (auto* {variant} = findVariant("{variant}")) {{
""".rstrip().lstrip(
"\n"
)
)
indent = " " * len_variants
println(
f"""
{indent}removeVariant{"s" if len_variants > 1 else ""}({", ".join(sorted_variants)});
{indent}setLanguage("{r_language}");
{indent}{"return true;" if not chain_if else ""}
""".rstrip().lstrip(
"\n"
)
)
for i in range(len_variants, 0, -1):
println(
f"""
{" " * (i - 1)}}}
""".rstrip().lstrip(
"\n"
)
)
println(
"""
}
""".rstrip().lstrip(
"\n"
)
)
println(
"""
return true;
}"""
)
def writeSignLanguageMappingsFunction(
println, legacy_mappings, description, source, url
):
"""Writes a function definition that maps legacy sign language tags."""
println("")
writeMappingHeader(println, description, source, url)
println(
"""\
bool mozilla::intl::Locale::signLanguageMapping(LanguageSubtag& language,
const RegionSubtag& region) {
MOZ_ASSERT(language.equalTo("sgn"));
MOZ_ASSERT(IsStructurallyValidRegionTag(region.span()));
MOZ_ASSERT(IsCanonicallyCasedRegionTag(region.span()));
""".rstrip()
)
region_mappings = {
rg: lg
for ((lang, _, rg, _), (lg, _, _, _)) in legacy_mappings.items()
if lang == "sgn"
}
source_name = "region"
target_name = "language"
tag_maxlength = 3
writeMappingsBinarySearchBody(
println, source_name, target_name, region_mappings, tag_maxlength
)
println(
"""
}""".lstrip()
)
def readSupplementalData(core_file):
"""Reads CLDR Supplemental Data and extracts information for Intl.js.
Information extracted:
- legacyMappings: mappings from legacy tags to preferred complete language tags
- languageMappings: mappings from language subtags to preferred subtags
- complexLanguageMappings: mappings from language subtags with complex rules
- regionMappings: mappings from region subtags to preferred subtags
- complexRegionMappings: mappings from region subtags with complex rules
- variantMappings: mappings from variant subtags to preferred subtags
- likelySubtags: likely subtags used for generating test data only
Returns these mappings as dictionaries.
"""
import xml.etree.ElementTree as ET
# From Unicode BCP 47 locale identifier <https://unicode.org/reports/tr35/>.
re_unicode_language_id = re.compile(
r"""
^
# unicode_language_id = unicode_language_subtag
# unicode_language_subtag = alpha{2,3} | alpha{5,8}
(?P<language>[a-z]{2,3}|[a-z]{5,8})
# (sep unicode_script_subtag)?
# unicode_script_subtag = alpha{4}
(?:-(?P<script>[a-z]{4}))?
# (sep unicode_region_subtag)?
# unicode_region_subtag = (alpha{2} | digit{3})
(?:-(?P<region>([a-z]{2}|[0-9]{3})))?
# (sep unicode_variant_subtag)*
# unicode_variant_subtag = (alphanum{5,8} | digit alphanum{3})
(?P<variants>(-([a-z0-9]{5,8}|[0-9][a-z0-9]{3}))+)?
$
""",
re.IGNORECASE | re.VERBOSE,
)
# CLDR uses "_" as the separator for some elements. Replace it with "-".
def bcp47_id(cldr_id):
return cldr_id.replace("_", "-")
# Return the tuple (language, script, region, variants) and assert all
# subtags are in canonical case.
def bcp47_canonical(language, script, region, variants):
# Canonical case for language subtags is lower case.
assert language is None or language.lower() == language
# Canonical case for script subtags is title case.
assert script is None or script.title() == script