Debian Codegraph @

js/src/builtin/intl/make_intl_data.py

raw
1 #!/usr/bin/env python
2 #
3 # This Source Code Form is subject to the terms of the Mozilla Public
4 # License, v. 2.0. If a copy of the MPL was not distributed with this
5 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 """ Usage:
8 make_intl_data.py langtags [cldr_common.zip]
9 make_intl_data.py tzdata
10 make_intl_data.py currency
11 make_intl_data.py units
12 make_intl_data.py numbering
13
14
15 Target "langtags":
16 This script extracts information about 1) mappings between deprecated and
17 current Unicode BCP 47 locale identifiers, and 2) deprecated and current
18 BCP 47 Unicode extension value from CLDR, and converts it to C++ mapping
19 code in intl/components/LocaleGenerated.cpp. The code is used in
20 intl/components/Locale.cpp.
21
22
23 Target "tzdata":
24 This script computes which time zone informations are not up-to-date in ICU
25 and provides the necessary mappings to workaround this problem.
26 https://ssl.icu-project.org/trac/ticket/12044
27
28
29 Target "currency":
30 Generates the mapping from currency codes to decimal digits used for them.
31
32
33 Target "units":
34 Generate source and test files using the list of so-called "sanctioned unit
35 identifiers" and verifies that the ICU data filter includes these units.
36
37
38 Target "numbering":
39 Generate source and test files using the list of numbering systems with
40 simple digit mappings and verifies that it's in sync with ICU/CLDR.
41 """
42
43 import io
44 import json
45 import os
46 import re
47 import tarfile
48 import tempfile
49 from contextlib import closing
50 from functools import partial, total_ordering
51 from itertools import chain, filterfalse, groupby, tee, zip_longest
52 from operator import attrgetter, itemgetter
53 from urllib.parse import urlsplit
54 from urllib.request import Request as UrlRequest
55 from urllib.request import urlopen
56 from zipfile import ZipFile
57
58 import yaml
59
60
61 # From https://docs.python.org/3/library/itertools.html
62 def grouper(iterable, n, fillvalue=None):
63 "Collect data into fixed-length chunks or blocks"
64 # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
65 args = [iter(iterable)] * n
66 return zip_longest(*args, fillvalue=fillvalue)
67
68
69 def writeMappingHeader(println, description, source, url):
70 if type(description) is not list:
71 description = [description]
72 for desc in description:
73 println(f"// {desc}")
74 println(f"// Derived from {source}.")
75 println(f"// {url}")
76
77
78 def writeMappingsVar(println, mapping, name, description, source, url):
79 """Writes a variable definition with a mapping table.
80
81 Writes the contents of dictionary |mapping| through the |println|
82 function with the given variable name and a comment with description,
83 fileDate, and URL.
84 """
85 println("")
86 writeMappingHeader(println, description, source, url)
87 println(f"var {name} = {{")
88 for key, value in sorted(mapping.items(), key=itemgetter(0)):
89 println(f' "{key}": "{value}",')
90 println("};")
91
92
93 def writeMappingsBinarySearch(
94 println,
95 fn_name,
96 type_name,
97 name,
98 validate_fn,
99 validate_case_fn,
100 mappings,
101 tag_maxlength,
102 description,
103 source,
104 url,
105 ):
106 """Emit code to perform a binary search on language tag subtags.
107
108 Uses the contents of |mapping|, which can either be a dictionary or set,
109 to emit a mapping function to find subtag replacements.
110 """
111 println("")
112 writeMappingHeader(println, description, source, url)
113 println(
114 f"""
115 bool mozilla::intl::Locale::{fn_name}({type_name} {name}) {{
116 MOZ_ASSERT({validate_fn}({name}.Span()));
117 MOZ_ASSERT({validate_case_fn}({name}.Span()));
118 """.strip()
119 )
120 writeMappingsBinarySearchBody(println, name, name, mappings, tag_maxlength)
121
122 println(
123 """
124 }""".lstrip(
125 "\n"
126 )
127 )
128
129
130 def writeMappingsBinarySearchBody(
131 println, source_name, target_name, mappings, tag_maxlength
132 ):
133 def write_array(subtags, name, length, fixed):
134 if fixed:
135 println(f" static const char {name}[{len(subtags)}][{length + 1}] = {{")
136 else:
137 println(f" static const char* {name}[{len(subtags)}] = {{")
138
139 # Group in pairs of ten to not exceed the 80 line column limit.
140 for entries in grouper(subtags, 10):
141 entries = (
142 f'"{tag}"'.rjust(length + 2) for tag in entries if tag is not None
143 )
144 println(" {},".format(", ".join(entries)))
145
146 println(" };")
147
148 trailing_return = True
149
150 # Sort the subtags by length. That enables using an optimized comparator
151 # for the binary search, which only performs a single |memcmp| for multiple
152 # of two subtag lengths.
153 mappings_keys = mappings.keys() if type(mappings) is dict else mappings
154 for length, subtags in groupby(sorted(mappings_keys, key=len), len):
155 # Omit the length check if the current length is the maximum length.
156 if length != tag_maxlength:
157 println(
158 f"""
159 if ({source_name}.Length() == {length}) {{
160 """.rstrip(
161 "\n"
162 )
163 )
164 else:
165 trailing_return = False
166 println(
167 """
168 {
169 """.rstrip(
170 "\n"
171 )
172 )
173
174 # The subtags need to be sorted for binary search to work.
175 subtags = sorted(subtags)
176
177 def equals(subtag):
178 return f"""{source_name}.EqualTo("{subtag}")"""
179
180 # Don't emit a binary search for short lists.
181 if len(subtags) == 1:
182 if type(mappings) is dict:
183 println(
184 f"""
185 if ({equals(subtags[0])}) {{
186 {target_name}.Set(mozilla::MakeStringSpan("{mappings[subtags[0]]}"));
187 return true;
188 }}
189 return false;
190 """.strip(
191 "\n"
192 )
193 )
194 else:
195 println(
196 f"""
197 return {equals(subtags[0])};
198 """.strip(
199 "\n"
200 )
201 )
202 elif len(subtags) <= 4:
203 if type(mappings) is dict:
204 for subtag in subtags:
205 println(
206 f"""
207 if ({equals(subtag)}) {{
208 {target_name}.Set("{mappings[subtag]}");
209 return true;
210 }}
211 """.strip(
212 "\n"
213 )
214 )
215
216 println(
217 """
218 return false;
219 """.strip(
220 "\n"
221 )
222 )
223 else:
224 cond = (equals(subtag) for subtag in subtags)
225 cond = (" ||\n" + " " * (4 + len("return "))).join(cond)
226 println(
227 f"""
228 return {cond};
229 """.strip(
230 "\n"
231 )
232 )
233 else:
234 write_array(subtags, source_name + "s", length, True)
235
236 if type(mappings) is dict:
237 write_array([mappings[k] for k in subtags], "aliases", length, False)
238
239 println(
240 f"""
241 if (const char* replacement = SearchReplacement({source_name}s, aliases, {source_name})) {{
242 {target_name}.Set(mozilla::MakeStringSpan(replacement));
243 return true;
244 }}
245 return false;
246 """.rstrip()
247 )
248 else:
249 println(
250 f"""
251 return HasReplacement({source_name}s, {source_name});
252 """.rstrip()
253 )
254
255 println(
256 """
257 }
258 """.strip(
259 "\n"
260 )
261 )
262
263 if trailing_return:
264 println(
265 """
266 return false;"""
267 )
268
269
270 def writeComplexLanguageTagMappings(
271 println, complex_language_mappings, description, source, url
272 ):
273 println("")
274 writeMappingHeader(println, description, source, url)
275 println(
276 """
277 void mozilla::intl::Locale::PerformComplexLanguageMappings() {
278 MOZ_ASSERT(IsStructurallyValidLanguageTag(Language().Span()));
279 MOZ_ASSERT(IsCanonicallyCasedLanguageTag(Language().Span()));
280 """.lstrip()
281 )
282
283 # Merge duplicate language entries.
284 language_aliases = {}
285 for deprecated_language, (language, script, region) in sorted(
286 complex_language_mappings.items(), key=itemgetter(0)
287 ):
288 key = (language, script, region)
289 if key not in language_aliases:
290 language_aliases[key] = []
291 else:
292 language_aliases[key].append(deprecated_language)
293
294 first_language = True
295 for deprecated_language, (language, script, region) in sorted(
296 complex_language_mappings.items(), key=itemgetter(0)
297 ):
298 key = (language, script, region)
299 if deprecated_language in language_aliases[key]:
300 continue
301
302 if_kind = "if" if first_language else "else if"
303 first_language = False
304
305 cond = (
306 f'Language().EqualTo("{lang}")'
307 for lang in [deprecated_language] + language_aliases[key]
308 )
309 cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond)
310
311 println(
312 f"""
313 {if_kind} ({cond}) {{""".strip(
314 "\n"
315 )
316 )
317
318 println(
319 f"""
320 SetLanguage("{language}");""".strip(
321 "\n"
322 )
323 )
324
325 if script is not None:
326 println(
327 f"""
328 if (Script().Missing()) {{
329 SetScript("{script}");
330 }}""".strip(
331 "\n"
332 )
333 )
334 if region is not None:
335 println(
336 f"""
337 if (Region().Missing()) {{
338 SetRegion("{region}");
339 }}""".strip(
340 "\n"
341 )
342 )
343 println(
344 """
345 }""".strip(
346 "\n"
347 )
348 )
349
350 println(
351 """
352 }
353 """.strip(
354 "\n"
355 )
356 )
357
358
359 def writeComplexRegionTagMappings(
360 println, complex_region_mappings, description, source, url
361 ):
362 println("")
363 writeMappingHeader(println, description, source, url)
364 println(
365 """
366 void mozilla::intl::Locale::PerformComplexRegionMappings() {
367 MOZ_ASSERT(IsStructurallyValidLanguageTag(Language().Span()));
368 MOZ_ASSERT(IsCanonicallyCasedLanguageTag(Language().Span()));
369 MOZ_ASSERT(IsStructurallyValidRegionTag(Region().Span()));
370 MOZ_ASSERT(IsCanonicallyCasedRegionTag(Region().Span()));
371 """.lstrip()
372 )
373
374 # |non_default_replacements| is a list and hence not hashable. Convert it
375 # to a string to get a proper hashable value.
376 def hash_key(default, non_default_replacements):
377 return (default, str(sorted(str(v) for v in non_default_replacements)))
378
379 # Merge duplicate region entries.
380 region_aliases = {}
381 for deprecated_region, (default, non_default_replacements) in sorted(
382 complex_region_mappings.items(), key=itemgetter(0)
383 ):
384 key = hash_key(default, non_default_replacements)
385 if key not in region_aliases:
386 region_aliases[key] = []
387 else:
388 region_aliases[key].append(deprecated_region)
389
390 first_region = True
391 for deprecated_region, (default, non_default_replacements) in sorted(
392 complex_region_mappings.items(), key=itemgetter(0)
393 ):
394 key = hash_key(default, non_default_replacements)
395 if deprecated_region in region_aliases[key]:
396 continue
397
398 if_kind = "if" if first_region else "else if"
399 first_region = False
400
401 cond = (
402 f'Region().EqualTo("{region}")'
403 for region in [deprecated_region] + region_aliases[key]
404 )
405 cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond)
406
407 println(
408 f"""
409 {if_kind} ({cond}) {{""".strip(
410 "\n"
411 )
412 )
413
414 replacement_regions = sorted(
415 {region for (_, _, region) in non_default_replacements}
416 )
417
418 first_case = True
419 for replacement_region in replacement_regions:
420 replacement_language_script = sorted(
421 (language, script)
422 for (language, script, region) in (non_default_replacements)
423 if region == replacement_region
424 )
425
426 if_kind = "if" if first_case else "else if"
427 first_case = False
428
429 def compare_tags(language, script):
430 if script is None:
431 return f'Language().EqualTo("{language}")'
432 return f'(Language().EqualTo("{language}") && Script().EqualTo("{script}"))'
433
434 cond = (
435 compare_tags(language, script)
436 for (language, script) in replacement_language_script
437 )
438 cond = (" ||\n" + " " * (4 + len(if_kind) + 2)).join(cond)
439
440 println(
441 f"""
442 {if_kind} ({cond}) {{
443 SetRegion("{replacement_region}");
444 }}""".rstrip().strip(
445 "\n"
446 )
447 )
448
449 println(
450 f"""
451 else {{
452 SetRegion("{default}");
453 }}
454 }}""".rstrip().strip(
455 "\n"
456 )
457 )
458
459 println(
460 """
461 }
462 """.strip(
463 "\n"
464 )
465 )
466
467
468 def writeVariantTagMappings(println, variant_mappings, description, source, url):
469 """Writes a function definition that maps variant subtags."""
470 println(
471 """
472 static const char* ToCharPointer(const char* str) {
473 return str;
474 }
475
476 static const char* ToCharPointer(const mozilla::intl::UniqueChars& str) {
477 return str.get();
478 }
479
480 template <typename T, typename U = T>
481 static bool IsLessThan(const T& a, const U& b) {
482 return strcmp(ToCharPointer(a), ToCharPointer(b)) < 0;
483 }
484 """
485 )
486 writeMappingHeader(println, description, source, url)
487 println(
488 """
489 bool mozilla::intl::Locale::PerformVariantMappings() {
490 // The variant subtags need to be sorted for binary search.
491 MOZ_ASSERT(std::is_sorted(mVariants.begin(), mVariants.end(),
492 IsLessThan<decltype(mVariants)::ElementType>));
493
494 auto removeVariantAt = [&](size_t index) {
495 mVariants.erase(mVariants.begin() + index);
496 };
497
498 auto insertVariantSortedIfNotPresent = [&](const char* variant) {
499 auto* p = std::lower_bound(
500 mVariants.begin(), mVariants.end(), variant,
501 IsLessThan<decltype(mVariants)::ElementType, decltype(variant)>);
502
503 // Don't insert the replacement when already present.
504 if (p != mVariants.end() && strcmp(p->get(), variant) == 0) {
505 return true;
506 }
507
508 // Insert the preferred variant in sort order.
509 auto preferred = DuplicateStringToUniqueChars(variant);
510 return !!mVariants.insert(p, std::move(preferred));
511 };
512
513 for (size_t i = 0; i < mVariants.length();) {
514 const char* variant = mVariants[i].get();
515 MOZ_ASSERT(IsCanonicallyCasedVariantTag(mozilla::MakeStringSpan(variant)));
516 """.lstrip()
517 )
518
519 (no_alias, with_alias) = partition(
520 variant_mappings.items(), lambda item: item[1] is None
521 )
522
523 no_replacements = " ||\n ".join(
524 f"""strcmp(variant, "{deprecated_variant}") == 0"""
525 for (deprecated_variant, _) in sorted(no_alias, key=itemgetter(0))
526 )
527
528 println(
529 f"""
530 if ({no_replacements}) {{
531 removeVariantAt(i);
532 }}
533 """.strip(
534 "\n"
535 )
536 )
537
538 for deprecated_variant, (type, replacement) in sorted(
539 with_alias, key=itemgetter(0)
540 ):
541 println(
542 f"""
543 else if (strcmp(variant, "{deprecated_variant}") == 0) {{
544 removeVariantAt(i);
545 """.strip(
546 "\n"
547 )
548 )
549
550 if type == "language":
551 println(
552 f"""
553 SetLanguage("{replacement}");
554 """.strip(
555 "\n"
556 )
557 )
558 elif type == "region":
559 println(
560 f"""
561 SetRegion("{replacement}");
562 """.strip(
563 "\n"
564 )
565 )
566 else:
567 assert type == "variant"
568 println(
569 f"""
570 if (!insertVariantSortedIfNotPresent("{replacement}")) {{
571 return false;
572 }}
573 """.strip(
574 "\n"
575 )
576 )
577
578 println(
579 """
580 }
581 """.strip(
582 "\n"
583 )
584 )
585
586 println(
587 """
588 else {
589 i++;
590 }
591 }
592 return true;
593 }
594 """.strip(
595 "\n"
596 )
597 )
598
599
600 def writeLegacyMappingsFunction(println, legacy_mappings, description, source, url):
601 """Writes a function definition that maps legacy language tags."""
602 println("")
603 writeMappingHeader(println, description, source, url)
604 println(
605 """\
606 bool mozilla::intl::Locale::UpdateLegacyMappings() {
607 // We're mapping legacy tags to non-legacy form here.
608 // Other tags remain unchanged.
609 //
610 // Legacy tags are either sign language tags ("sgn") or have one or multiple
611 // variant subtags. Therefore we can quickly exclude most tags by checking
612 // these two subtags.
613
614 MOZ_ASSERT(IsCanonicallyCasedLanguageTag(Language().Span()));
615
616 if (!Language().EqualTo("sgn") && mVariants.length() == 0) {
617 return true;
618 }
619
620 #ifdef DEBUG
621 for (const auto& variant : Variants()) {
622 MOZ_ASSERT(IsStructurallyValidVariantTag(variant));
623 MOZ_ASSERT(IsCanonicallyCasedVariantTag(variant));
624 }
625 #endif
626
627 // The variant subtags need to be sorted for binary search.
628 MOZ_ASSERT(std::is_sorted(mVariants.begin(), mVariants.end(),
629 IsLessThan<decltype(mVariants)::ElementType>));
630
631 auto findVariant = [this](const char* variant) {
632 auto* p = std::lower_bound(mVariants.begin(), mVariants.end(), variant,
633 IsLessThan<decltype(mVariants)::ElementType,
634 decltype(variant)>);
635
636 if (p != mVariants.end() && strcmp(p->get(), variant) == 0) {
637 return p;
638 }
639 return static_cast<decltype(p)>(nullptr);
640 };
641
642 auto insertVariantSortedIfNotPresent = [&](const char* variant) {
643 auto* p = std::lower_bound(mVariants.begin(), mVariants.end(), variant,
644 IsLessThan<decltype(mVariants)::ElementType,
645 decltype(variant)>);
646
647 // Don't insert the replacement when already present.
648 if (p != mVariants.end() && strcmp(p->get(), variant) == 0) {
649 return true;
650 }
651
652 // Insert the preferred variant in sort order.
653 auto preferred = DuplicateStringToUniqueChars(variant);
654 return !!mVariants.insert(p, std::move(preferred));
655 };
656
657 auto removeVariant = [&](auto* p) {
658 size_t index = std::distance(mVariants.begin(), p);
659 mVariants.erase(mVariants.begin() + index);
660 };
661
662 auto removeVariants = [&](auto* p, auto* q) {
663 size_t pIndex = std::distance(mVariants.begin(), p);
664 size_t qIndex = std::distance(mVariants.begin(), q);
665 MOZ_ASSERT(pIndex < qIndex, "variant subtags are sorted");
666
667 mVariants.erase(mVariants.begin() + qIndex);
668 mVariants.erase(mVariants.begin() + pIndex);
669 };"""
670 )
671
672 # Helper class for pattern matching.
673 class AnyClass:
674 def __eq__(self, obj):
675 return obj is not None
676
677 Any = AnyClass()
678
679 # Group the mappings by language.
680 legacy_mappings_by_language = {}
681 for type, replacement in legacy_mappings.items():
682 (language, _, _, _) = type
683 legacy_mappings_by_language.setdefault(language, {})[type] = replacement
684
685 # Handle the empty language case first.
686 if None in legacy_mappings_by_language:
687 # Get the mappings and remove them from the dict.
688 mappings = legacy_mappings_by_language.pop(None)
689
690 # This case only applies for the "hepburn-heploc" -> "alalc97"
691 # mapping, so just inline it here.
692 from_tag = (None, None, None, "hepburn-heploc")
693 to_tag = (None, None, None, "alalc97")
694
695 assert len(mappings) == 1
696 assert mappings[from_tag] == to_tag
697
698 println(
699 """
700 if (mVariants.length() >= 2) {
701 if (auto* hepburn = findVariant("hepburn")) {
702 if (auto* heploc = findVariant("heploc")) {
703 removeVariants(hepburn, heploc);
704
705 if (!insertVariantSortedIfNotPresent("alalc97")) {
706 return false;
707 }
708 }
709 }
710 }
711 """
712 )
713
714 # Handle sign languages next.
715 if "sgn" in legacy_mappings_by_language:
716 mappings = legacy_mappings_by_language.pop("sgn")
717
718 # Legacy sign language mappings have the form "sgn-XX" where "XX" is
719 # some region code.
720 assert all(type == ("sgn", None, Any, None) for type in mappings.keys())
721
722 # Legacy sign languages are mapped to a single language subtag.
723 assert all(
724 replacement == (Any, None, None, None) for replacement in mappings.values()
725 )
726
727 println(
728 """
729 if (Language().EqualTo("sgn")) {
730 if (Region().Present() && SignLanguageMapping(mLanguage, Region())) {
731 mRegion.Set(mozilla::MakeStringSpan(""));
732 }
733 }
734 """.rstrip().lstrip(
735 "\n"
736 )
737 )
738
739 # Finally handle all remaining cases.
740
741 # The remaining mappings have neither script nor region subtags in the source locale.
742 assert all(
743 type == (Any, None, None, Any)
744 for mappings in legacy_mappings_by_language.values()
745 for type in mappings.keys()
746 )
747
748 # And they have neither script nor region nor variant subtags in the target locale.
749 assert all(
750 replacement == (Any, None, None, None)
751 for mappings in legacy_mappings_by_language.values()
752 for replacement in mappings.values()
753 )
754
755 # Compact the mappings table by removing empty fields.
756 legacy_mappings_by_language = {
757 lang: {
758 variants: r_language
759 for ((_, _, _, variants), (r_language, _, _, _)) in mappings.items()
760 }
761 for (lang, mappings) in legacy_mappings_by_language.items()
762 }
763
764 # Try to combine the remaining cases.
765 legacy_mappings_compact = {}
766
767 # Python can't hash dicts or lists, so use the string representation as the hash key.
768 def hash_key(mappings):
769 return str(sorted(mappings.items(), key=itemgetter(0)))
770
771 for lang, mappings in sorted(
772 legacy_mappings_by_language.items(), key=itemgetter(0)
773 ):
774 key = hash_key(mappings)
775 legacy_mappings_compact.setdefault(key, []).append(lang)
776
777 for langs in legacy_mappings_compact.values():
778 language_equal_to = (
779 f"""Language().EqualTo("{lang}")""" for lang in sorted(langs)
780 )
781 cond = f""" ||\n{" " * len(" else if (")}""".join(language_equal_to)
782
783 println(
784 f"""
785 else if ({cond}) {{
786 """.rstrip().lstrip(
787 "\n"
788 )
789 )
790
791 mappings = legacy_mappings_by_language[langs[0]]
792
793 # Count the variant subtags to determine the sort order.
794 def variant_size(m):
795 (k, _) = m
796 return len(k.split("-"))
797
798 # Alias rules are applied by largest union size first.
799 for size, mappings_by_size in groupby(
800 sorted(mappings.items(), key=variant_size, reverse=True), key=variant_size
801 ):
802 # Convert grouper object to dict.
803 mappings_by_size = dict(mappings_by_size)
804
805 is_first = True
806 chain_if = size == 1
807
808 # Alias rules are applied in alphabetical order
809 for variants, r_language in sorted(
810 mappings_by_size.items(), key=itemgetter(0)
811 ):
812 sorted_variants = sorted(variants.split("-"))
813 len_variants = len(sorted_variants)
814
815 maybe_else = "else " if chain_if and not is_first else ""
816 is_first = False
817
818 for i, variant in enumerate(sorted_variants):
819 println(
820 f"""
821 {" " * i}{maybe_else}if (auto* {variant} = findVariant("{variant}")) {{
822 """.rstrip().lstrip(
823 "\n"
824 )
825 )
826
827 indent = " " * len_variants
828
829 println(
830 f"""
831 {indent}removeVariant{"s" if len_variants > 1 else ""}({", ".join(sorted_variants)});
832 {indent}SetLanguage("{r_language}");
833 {indent}{"return true;" if not chain_if else ""}
834 """.rstrip().lstrip(
835 "\n"
836 )
837 )
838
839 for i in range(len_variants, 0, -1):
840 println(
841 f"""
842 {" " * (i - 1)}}}
843 """.rstrip().lstrip(
844 "\n"
845 )
846 )
847
848 println(
849 """
850 }
851 """.rstrip().lstrip(
852 "\n"
853 )
854 )
855
856 println(
857 """
858 return true;
859 }"""
860 )
861
862
863 def writeSignLanguageMappingsFunction(
864 println, legacy_mappings, description, source, url
865 ):
866 """Writes a function definition that maps legacy sign language tags."""
867 println("")
868 writeMappingHeader(println, description, source, url)
869 println(
870 """\
871 bool mozilla::intl::Locale::SignLanguageMapping(LanguageSubtag& language,
872 const RegionSubtag& region) {
873 MOZ_ASSERT(language.EqualTo("sgn"));
874 MOZ_ASSERT(IsStructurallyValidRegionTag(region.Span()));
875 MOZ_ASSERT(IsCanonicallyCasedRegionTag(region.Span()));
876 """.rstrip()
877 )
878
879 region_mappings = {
880 rg: lg
881 for ((lang, _, rg, _), (lg, _, _, _)) in legacy_mappings.items()
882 if lang == "sgn"
883 }
884
885 source_name = "region"
886 target_name = "language"
887 tag_maxlength = 3
888 writeMappingsBinarySearchBody(
889 println, source_name, target_name, region_mappings, tag_maxlength
890 )
891
892 println(
893 """
894 }""".lstrip()
895 )
896
897
898 def readSupplementalData(core_file):
899 """Reads CLDR Supplemental Data and extracts information for Intl.js.
900
901 Information extracted:
902 - legacyMappings: mappings from legacy tags to preferred complete language tags
903 - languageMappings: mappings from language subtags to preferred subtags
904 - complexLanguageMappings: mappings from language subtags with complex rules
905 - regionMappings: mappings from region subtags to preferred subtags
906 - complexRegionMappings: mappings from region subtags with complex rules
907 - variantMappings: mappings from variant subtags to preferred subtags
908 - likelySubtags: likely subtags used for generating test data only
909 Returns these mappings as dictionaries.
910 """
911 import xml.etree.ElementTree as ET
912
913 # From Unicode BCP 47 locale identifier <https://unicode.org/reports/tr35/>.
914 re_unicode_language_id = re.compile(
915 r"""
916 ^
917 # unicode_language_id = unicode_language_subtag
918 # unicode_language_subtag = alpha{2,3} | alpha{5,8}
919 (?P<language>[a-z]{2,3}|[a-z]{5,8})
920
921 # (sep unicode_script_subtag)?
922 # unicode_script_subtag = alpha{4}
923 (?:-(?P<script>[a-z]{4}))?
924
925 # (sep unicode_region_subtag)?
926 # unicode_region_subtag = (alpha{2} | digit{3})
927 (?:-(?P<region>([a-z]{2}|[0-9]{3})))?
928
929 # (sep unicode_variant_subtag)*
930 # unicode_variant_subtag = (alphanum{5,8} | digit alphanum{3})
931 (?P<variants>(-([a-z0-9]{5,8}|[0-9][a-z0-9]{3}))+)?
932 $
933 """,
934 re.IGNORECASE | re.VERBOSE,
935 )
936
937 # CLDR uses "_" as the separator for some elements. Replace it with "-".
938 def bcp47_id(cldr_id):
939 return cldr_id.replace("_", "-")
940
941 # Return the tuple (language, script, region, variants) and assert all
942 # subtags are in canonical case.
943 def bcp47_canonical(language, script, region, variants):
944 # Canonical case for language subtags is lower case.
945 assert language is None or language.lower() == language
946
947 # Canonical case for script subtags is title case.
948 assert script is None or script.title() == script
949
950 # Canonical case for region subtags is upper case.
951 assert region is None or region.upper() == region
952
953 # Canonical case for variant subtags is lower case.
954 assert variants is None or variants.lower() == variants
955
956 return (language, script, region, variants[1:] if variants else None)
957
958 # Language ids are interpreted as multi-maps in
959 # <https://www.unicode.org/reports/tr35/#LocaleId_Canonicalization>.
960 #
961 # See UTS35, §Annex C, Definitions - 1. Multimap interpretation.
962 def language_id_to_multimap(language_id):
963 match = re_unicode_language_id.match(language_id)
964 assert (
965 match is not None
966 ), f"{language_id} invalid Unicode BCP 47 locale identifier"
967
968 canonical_language_id = bcp47_canonical(
969 *match.group("language", "script", "region", "variants")
970 )
971 (language, _, _, _) = canonical_language_id
972
973 # Normalize "und" language to None, but keep the rest as is.
974 return (language if language != "und" else None,) + canonical_language_id[1:]
975
976 rules = {}
977 territory_exception_rules = {}
978
979 tree = ET.parse(core_file.open("common/supplemental/supplementalMetadata.xml"))
980
981 # Load the rules from supplementalMetadata.xml.
982 #
983 # See UTS35, §Annex C, Definitions - 2. Alias elements.
984 # See UTS35, §Annex C, Preprocessing.
985 for alias_name in [
986 "languageAlias",
987 "scriptAlias",
988 "territoryAlias",
989 "variantAlias",
990 ]:
991 for alias in tree.iterfind(".//" + alias_name):
992 # Replace '_' by '-'.
993 type = bcp47_id(alias.get("type"))
994 replacement = bcp47_id(alias.get("replacement"))
995
996 # Prefix with "und-".
997 if alias_name != "languageAlias":
998 type = "und-" + type
999
1000 # Discard all rules where the type is an invalid languageId.
1001 if re_unicode_language_id.match(type) is None:
1002 continue
1003
1004 type = language_id_to_multimap(type)
1005
1006 # Multiple, whitespace-separated territory replacements may be present.
1007 if alias_name == "territoryAlias" and " " in replacement:
1008 replacements = replacement.split(" ")
1009 replacement_list = [
1010 language_id_to_multimap("und-" + r) for r in replacements
1011 ]
1012
1013 assert (
1014 type not in territory_exception_rules
1015 ), f"Duplicate alias rule: {type}"
1016
1017 territory_exception_rules[type] = replacement_list
1018
1019 # The first element is the default territory replacement.
1020 replacement = replacements[0]
1021
1022 # Prefix with "und-".
1023 if alias_name != "languageAlias":
1024 replacement = "und-" + replacement
1025
1026 replacement = language_id_to_multimap(replacement)
1027
1028 assert type not in rules, f"Duplicate alias rule: {type}"
1029
1030 rules[type] = replacement
1031
1032 # Helper class for pattern matching.
1033 class AnyClass:
1034 def __eq__(self, obj):
1035 return obj is not None
1036
1037 Any = AnyClass()
1038
1039 modified_rules = True
1040 loop_count = 0
1041
1042 while modified_rules:
1043 modified_rules = False
1044 loop_count += 1
1045
1046 # UTS 35 defines that canonicalization is applied until a fixed point has
1047 # been reached. This iterative application of the canonicalization algorithm
1048 # is only needed for a relatively small set of rules, so we can precompute
1049 # the transitive closure of all rules here and then perform a single pass
1050 # when canonicalizing language tags at runtime.
1051 transitive_rules = {}
1052
1053 # Compute the transitive closure.
1054 # Any case which currently doesn't occur in the CLDR sources isn't supported
1055 # and will lead to throwing an error.
1056 for type, replacement in rules.items():
1057 (language, script, region, variants) = type
1058 (r_language, r_script, r_region, r_variants) = replacement
1059
1060 for i_type, i_replacement in rules.items():
1061 (i_language, i_script, i_region, i_variants) = i_type
1062 (i_r_language, i_r_script, i_r_region, i_r_variants) = i_replacement
1063
1064 if i_language is not None and i_language == r_language:
1065 # This case currently only occurs when neither script nor region
1066 # subtags are present. A single variant subtags may be present
1067 # in |type|. And |i_type| definitely has a single variant subtag.
1068 # Should this ever change, update this code accordingly.
1069 assert type == (Any, None, None, None) or type == (
1070 Any,
1071 None,
1072 None,
1073 Any,
1074 )
1075 assert replacement == (Any, None, None, None)
1076 assert i_type == (Any, None, None, Any)
1077 assert i_replacement == (Any, None, None, None)
1078
1079 # This case happens for the rules
1080 # "zh-guoyu -> zh",
1081 # "zh-hakka -> hak", and
1082 # "und-hakka -> und".
1083 # Given the possible input "zh-guoyu-hakka", the first rule will
1084 # change it to "zh-hakka", and then the second rule can be
1085 # applied. (The third rule isn't applied ever.)
1086 #
1087 # Let's assume there's a hypothetical rule
1088 # "zh-aaaaa" -> "en"
1089 # And we have the input "zh-aaaaa-hakka", then "zh-aaaaa -> en"
1090 # is applied before "zh-hakka -> hak", because rules are sorted
1091 # alphabetically. That means the overall result is "en":
1092 # "zh-aaaaa-hakka" is first canonicalized to "en-hakka" and then
1093 # "hakka" is removed through the third rule.
1094 #
1095 # No current rule requires to handle this special case, so we
1096 # don't yet support it.
1097 assert variants is None or variants <= i_variants
1098
1099 # Combine all variants and remove duplicates.
1100 vars = set(
1101 i_variants.split("-")
1102 + (variants.split("-") if variants else [])
1103 )
1104
1105 # Add the variants alphabetically sorted.
1106 n_type = (language, None, None, "-".join(sorted(vars)))
1107
1108 assert (
1109 n_type not in transitive_rules
1110 or transitive_rules[n_type] == i_replacement
1111 )
1112 transitive_rules[n_type] = i_replacement
1113
1114 continue
1115
1116 if i_script is not None and i_script == r_script:
1117 # This case currently doesn't occur, so we don't yet support it.
1118 raise ValueError(
1119 f"{type} -> {replacement} :: {i_type} -> {i_replacement}"
1120 )
1121 if i_region is not None and i_region == r_region:
1122 # This case currently only applies for sign language
1123 # replacements. Similar to the language subtag case any other
1124 # combination isn't currently supported.
1125 assert type == (None, None, Any, None)
1126 assert replacement == (None, None, Any, None)
1127 assert i_type == ("sgn", None, Any, None)
1128 assert i_replacement == (Any, None, None, None)
1129
1130 n_type = ("sgn", None, region, None)
1131
1132 assert n_type not in transitive_rules
1133 transitive_rules[n_type] = i_replacement
1134
1135 continue
1136
1137 if i_variants is not None and i_variants == r_variants:
1138 # This case currently doesn't occur, so we don't yet support it.
1139 raise ValueError(
1140 f"{type} -> {replacement} :: {i_type} -> {i_replacement}"
1141 )
1142
1143 # Ensure there are no contradicting rules.
1144 assert all(
1145 rules[type] == replacement
1146 for (type, replacement) in transitive_rules.items()
1147 if type in rules
1148 )
1149
1150 # If |transitive_rules| is not a subset of |rules|, new rules will be added.
1151 modified_rules = not (transitive_rules.keys() <= rules.keys())
1152
1153 # Ensure we only have to iterate more than once for the "guoyo-{hakka,xiang}"
1154 # case. Failing this assertion means either there's a bug when computing the
1155 # stop condition of this loop or a new kind of legacy language tags was added.
1156 if modified_rules and loop_count > 1:
1157 new_rules = {k for k in transitive_rules.keys() if k not in rules}
1158 for k in new_rules:
1159 assert k == (Any, None, None, "guoyu-hakka") or k == (
1160 Any,
1161 None,
1162 None,
1163 "guoyu-xiang",
1164 )
1165
1166 # Merge the transitive rules.
1167 rules.update(transitive_rules)
1168
1169 # Computes the size of the union of all field value sets.
1170 def multi_map_size(locale_id):
1171 (language, script, region, variants) = locale_id
1172
1173 return (
1174 (1 if language is not None else 0)
1175 + (1 if script is not None else 0)
1176 + (1 if region is not None else 0)
1177 + (len(variants.split("-")) if variants is not None else 0)
1178 )
1179
1180 # Dictionary of legacy mappings, contains raw rules, e.g.
1181 # (None, None, None, "hepburn-heploc") -> (None, None, None, "alalc97").
1182 legacy_mappings = {}
1183
1184 # Dictionary of simple language subtag mappings, e.g. "in" -> "id".
1185 language_mappings = {}
1186
1187 # Dictionary of complex language subtag mappings, modifying more than one
1188 # subtag, e.g. "sh" -> ("sr", "Latn", None) and "cnr" -> ("sr", None, "ME").
1189 complex_language_mappings = {}
1190
1191 # Dictionary of simple script subtag mappings, e.g. "Qaai" -> "Zinh".
1192 script_mappings = {}
1193
1194 # Dictionary of simple region subtag mappings, e.g. "DD" -> "DE".
1195 region_mappings = {}
1196
1197 # Dictionary of complex region subtag mappings, containing more than one
1198 # replacement, e.g. "SU" -> ("RU", ["AM", "AZ", "BY", ...]).
1199 complex_region_mappings = {}
1200
1201 # Dictionary of aliased variant subtags to a tuple of preferred replacement
1202 # type and replacement, e.g. "arevela" -> ("language", "hy") or
1203 # "aaland" -> ("region", "AX") or "heploc" -> ("variant", "alalc97").
1204 variant_mappings = {}
1205
1206 # Preprocess all rules so we can perform a single lookup per subtag at runtime.
1207 for type, replacement in rules.items():
1208 (language, script, region, variants) = type
1209 (r_language, r_script, r_region, r_variants) = replacement
1210
1211 type_map_size = multi_map_size(type)
1212
1213 # Most mappings are one-to-one and can be encoded through lookup tables.
1214 if type_map_size == 1:
1215 if language is not None:
1216 assert r_language is not None, "Can't remove a language subtag"
1217
1218 # We don't yet support this case.
1219 assert (
1220 r_variants is None
1221 ), f"Unhandled variant replacement in language alias: {replacement}"
1222
1223 if replacement == (Any, None, None, None):
1224 language_mappings[language] = r_language
1225 else:
1226 complex_language_mappings[language] = replacement[:-1]
1227 elif script is not None:
1228 # We don't support removing script subtags.
1229 assert (
1230 r_script is not None
1231 ), f"Can't remove a script subtag: {replacement}"
1232
1233 # We only support one-to-one script mappings for now.
1234 assert replacement == (
1235 None,
1236 Any,
1237 None,
1238 None,
1239 ), f"Unhandled replacement in script alias: {replacement}"
1240
1241 script_mappings[script] = r_script
1242 elif region is not None:
1243 # We don't support removing region subtags.
1244 assert (
1245 r_region is not None
1246 ), f"Can't remove a region subtag: {replacement}"
1247
1248 # We only support one-to-one region mappings for now.
1249 assert replacement == (
1250 None,
1251 None,
1252 Any,
1253 None,
1254 ), f"Unhandled replacement in region alias: {replacement}"
1255
1256 if type not in territory_exception_rules:
1257 region_mappings[region] = r_region
1258 else:
1259 complex_region_mappings[region] = [
1260 r_region
1261 for (_, _, r_region, _) in territory_exception_rules[type]
1262 ]
1263 else:
1264 assert variants is not None
1265 assert len(variants.split("-")) == 1
1266
1267 # We only support one-to-one variant mappings for now.
1268 assert (
1269 multi_map_size(replacement) <= 1
1270 ), f"Unhandled replacement in variant alias: {replacement}"
1271
1272 if r_language is not None:
1273 variant_mappings[variants] = ("language", r_language)
1274 elif r_script is not None:
1275 variant_mappings[variants] = ("script", r_script)
1276 elif r_region is not None:
1277 variant_mappings[variants] = ("region", r_region)
1278 elif r_variants is not None:
1279 assert len(r_variants.split("-")) == 1
1280 variant_mappings[variants] = ("variant", r_variants)
1281 else:
1282 variant_mappings[variants] = None
1283 else:
1284 # Alias rules which have multiple input fields must be processed
1285 # first. This applies only to a handful of rules, so our generated
1286 # code adds fast paths to skip these rules in the common case.
1287
1288 # Case 1: Language and at least one variant subtag.
1289 if language is not None and variants is not None:
1290 pass
1291
1292 # Case 2: Sign language and a region subtag.
1293 elif language == "sgn" and region is not None:
1294 pass
1295
1296 # Case 3: "hepburn-heploc" to "alalc97" canonicalization.
1297 elif (
1298 language is None
1299 and variants is not None
1300 and len(variants.split("-")) == 2
1301 ):
1302 pass
1303
1304 # Any other combination is currently unsupported.
1305 else:
1306 raise ValueError(f"{type} -> {replacement}")
1307
1308 legacy_mappings[type] = replacement
1309
1310 tree = ET.parse(core_file.open("common/supplemental/likelySubtags.xml"))
1311
1312 likely_subtags = {}
1313
1314 for likely_subtag in tree.iterfind(".//likelySubtag"):
1315 from_tag = bcp47_id(likely_subtag.get("from"))
1316 from_match = re_unicode_language_id.match(from_tag)
1317 assert (
1318 from_match is not None
1319 ), f"{from_tag} invalid Unicode BCP 47 locale identifier"
1320 assert (
1321 from_match.group("variants") is None
1322 ), f"unexpected variant subtags in {from_tag}"
1323
1324 to_tag = bcp47_id(likely_subtag.get("to"))
1325 to_match = re_unicode_language_id.match(to_tag)
1326 assert (
1327 to_match is not None
1328 ), f"{to_tag} invalid Unicode BCP 47 locale identifier"
1329 assert (
1330 to_match.group("variants") is None
1331 ), f"unexpected variant subtags in {to_tag}"
1332
1333 from_canonical = bcp47_canonical(
1334 *from_match.group("language", "script", "region", "variants")
1335 )
1336
1337 to_canonical = bcp47_canonical(
1338 *to_match.group("language", "script", "region", "variants")
1339 )
1340
1341 # Remove the empty variant subtags.
1342 from_canonical = from_canonical[:-1]
1343 to_canonical = to_canonical[:-1]
1344
1345 likely_subtags[from_canonical] = to_canonical
1346
1347 complex_region_mappings_final = {}
1348
1349 for deprecated_region, replacements in complex_region_mappings.items():
1350 # Find all likely subtag entries which don't already contain a region
1351 # subtag and whose target region is in the list of replacement regions.
1352 region_likely_subtags = [
1353 (from_language, from_script, to_region)
1354 for (
1355 (from_language, from_script, from_region),
1356 (_, _, to_region),
1357 ) in likely_subtags.items()
1358 if from_region is None and to_region in replacements
1359 ]
1360
1361 # The first replacement entry is the default region.
1362 default = replacements[0]
1363
1364 # Find all likely subtag entries whose region matches the default region.
1365 default_replacements = {
1366 (language, script)
1367 for (language, script, region) in region_likely_subtags
1368 if region == default
1369 }
1370
1371 # And finally find those entries which don't use the default region.
1372 # These are the entries we're actually interested in, because those need
1373 # to be handled specially when selecting the correct preferred region.
1374 non_default_replacements = [
1375 (language, script, region)
1376 for (language, script, region) in region_likely_subtags
1377 if (language, script) not in default_replacements
1378 ]
1379
1380 # Remove redundant mappings.
1381 #
1382 # For example starting with CLDR 43, the deprecated region "SU" has the
1383 # following non-default replacement entries for "GE":
1384 # - ('sva', None, 'GE')
1385 # - ('sva', 'Cyrl', 'GE')
1386 # - ('sva', 'Latn', 'GE')
1387 #
1388 # The latter two entries are redundant, because they're already handled
1389 # by the first entry.
1390 non_default_replacements = [
1391 (language, script, region)
1392 for (language, script, region) in non_default_replacements
1393 if script is None
1394 or (language, None, region) not in non_default_replacements
1395 ]
1396
1397 # If there are no non-default replacements, we can handle the region as
1398 # part of the simple region mapping.
1399 if non_default_replacements:
1400 complex_region_mappings_final[deprecated_region] = (
1401 default,
1402 non_default_replacements,
1403 )
1404 else:
1405 region_mappings[deprecated_region] = default
1406
1407 return {
1408 "legacyMappings": legacy_mappings,
1409 "languageMappings": language_mappings,
1410 "complexLanguageMappings": complex_language_mappings,
1411 "scriptMappings": script_mappings,
1412 "regionMappings": region_mappings,
1413 "complexRegionMappings": complex_region_mappings_final,
1414 "variantMappings": variant_mappings,
1415 "likelySubtags": likely_subtags,
1416 }
1417
1418
1419 def readUnicodeExtensions(core_file):
1420 import xml.etree.ElementTree as ET
1421
1422 # Match all xml-files in the BCP 47 directory.
1423 bcpFileRE = re.compile(r"^common/bcp47/.+\.xml$")
1424
1425 # https://www.unicode.org/reports/tr35/#Unicode_locale_identifier
1426 #
1427 # type = alphanum{3,8} (sep alphanum{3,8})* ;
1428 typeRE = re.compile(r"^[a-z0-9]{3,8}(-[a-z0-9]{3,8})*$")
1429
1430 # https://www.unicode.org/reports/tr35/#Unicode_language_identifier
1431 #
1432 # unicode_region_subtag = alpha{2} ;
1433 alphaRegionRE = re.compile(r"^[A-Z]{2}$", re.IGNORECASE)
1434
1435 # Mapping from Unicode extension types to dict of deprecated to
1436 # preferred values.
1437 mapping = {
1438 # Unicode BCP 47 U Extension
1439 "u": {},
1440 # Unicode BCP 47 T Extension
1441 "t": {},
1442 }
1443
1444 def readBCP47File(file):
1445 tree = ET.parse(file)
1446 for keyword in tree.iterfind(".//keyword/key"):
1447 extension = keyword.get("extension", "u")
1448 assert (
1449 extension == "u" or extension == "t"
1450 ), f"unknown extension type: {extension}"
1451
1452 extension_name = keyword.get("name")
1453
1454 for type in keyword.iterfind("type"):
1455 # <https://unicode.org/reports/tr35/#Unicode_Locale_Extension_Data_Files>:
1456 #
1457 # The key or type name used by Unicode locale extension with 'u' extension
1458 # syntax or the 't' extensions syntax. When alias below is absent, this name
1459 # can be also used with the old style "@key=type" syntax.
1460 name = type.get("name")
1461
1462 # Ignore the special name:
1463 # - <https://unicode.org/reports/tr35/#CODEPOINTS>
1464 # - <https://unicode.org/reports/tr35/#REORDER_CODE>
1465 # - <https://unicode.org/reports/tr35/#RG_KEY_VALUE>
1466 # - <https://unicode.org/reports/tr35/#SCRIPT_CODE>
1467 # - <https://unicode.org/reports/tr35/#SUBDIVISION_CODE>
1468 # - <https://unicode.org/reports/tr35/#PRIVATE_USE>
1469 if name in (
1470 "CODEPOINTS",
1471 "REORDER_CODE",
1472 "RG_KEY_VALUE",
1473 "SCRIPT_CODE",
1474 "SUBDIVISION_CODE",
1475 "PRIVATE_USE",
1476 ):
1477 continue
1478
1479 # All other names should match the 'type' production.
1480 assert (
1481 typeRE.match(name) is not None
1482 ), f"{name} matches the 'type' production"
1483
1484 # <https://unicode.org/reports/tr35/#Unicode_Locale_Extension_Data_Files>:
1485 #
1486 # The preferred value of the deprecated key, type or attribute element.
1487 # When a key, type or attribute element is deprecated, this attribute is
1488 # used for specifying a new canonical form if available.
1489 preferred = type.get("preferred")
1490
1491 # <https://unicode.org/reports/tr35/#Unicode_Locale_Extension_Data_Files>:
1492 #
1493 # The BCP 47 form is the canonical form, and recommended. Other aliases are
1494 # included only for backwards compatibility.
1495 alias = type.get("alias")
1496
1497 # <https://unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers>
1498 #
1499 # Use the bcp47 data to replace keys, types, tfields, and tvalues by their
1500 # canonical forms. See Section 3.6.4 U Extension Data Files) and Section
1501 # 3.7.1 T Extension Data Files. The aliases are in the alias attribute
1502 # value, while the canonical is in the name attribute value.
1503
1504 # 'preferred' contains the new preferred name, 'alias' the compatibility
1505 # name, but then there's this entry where 'preferred' and 'alias' are the
1506 # same. So which one to choose? Assume 'preferred' is the actual canonical
1507 # name.
1508 #
1509 # <type name="islamicc"
1510 # description="Civil (algorithmic) Arabic calendar"
1511 # deprecated="true"
1512 # preferred="islamic-civil"
1513 # alias="islamic-civil"/>
1514
1515 if preferred is not None:
1516 assert typeRE.match(preferred), preferred
1517 mapping[extension].setdefault(extension_name, {})[name] = preferred
1518
1519 if alias is not None:
1520 for alias_name in alias.lower().split(" "):
1521 # Ignore alias entries which don't match the 'type' production.
1522 if typeRE.match(alias_name) is None:
1523 continue
1524
1525 # See comment above when 'alias' and 'preferred' are both present.
1526 if (
1527 preferred is not None
1528 and name in mapping[extension][extension_name]
1529 ):
1530 continue
1531
1532 # Skip over entries where 'name' and 'alias' are equal.
1533 #
1534 # <type name="pst8pdt"
1535 # description="POSIX style time zone for US Pacific Time"
1536 # alias="PST8PDT"
1537 # since="1.8"/>
1538 if name == alias_name:
1539 continue
1540
1541 mapping[extension].setdefault(extension_name, {})[
1542 alias_name
1543 ] = name
1544
1545 def readSupplementalMetadata(file):
1546 # Find subdivision and region replacements.
1547 #
1548 # <https://www.unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers>
1549 #
1550 # Replace aliases in special key values:
1551 # - If there is an 'sd' or 'rg' key, replace any subdivision alias
1552 # in its value in the same way, using subdivisionAlias data.
1553 tree = ET.parse(file)
1554 for alias in tree.iterfind(".//subdivisionAlias"):
1555 type = alias.get("type")
1556 assert (
1557 typeRE.match(type) is not None
1558 ), f"{type} matches the 'type' production"
1559
1560 # Take the first replacement when multiple ones are present.
1561 replacement = alias.get("replacement").split(" ")[0].lower()
1562
1563 # Append "zzzz" if the replacement is a two-letter region code.
1564 if alphaRegionRE.match(replacement) is not None:
1565 replacement += "zzzz"
1566
1567 # Assert the replacement is syntactically correct.
1568 assert (
1569 typeRE.match(replacement) is not None
1570 ), f"replacement {replacement} matches the 'type' production"
1571
1572 # 'subdivisionAlias' applies to 'rg' and 'sd' keys.
1573 mapping["u"].setdefault("rg", {})[type] = replacement
1574 mapping["u"].setdefault("sd", {})[type] = replacement
1575
1576 for name in core_file.namelist():
1577 if bcpFileRE.match(name):
1578 readBCP47File(core_file.open(name))
1579
1580 readSupplementalMetadata(
1581 core_file.open("common/supplemental/supplementalMetadata.xml")
1582 )
1583
1584 return {
1585 "unicodeMappings": mapping["u"],
1586 "transformMappings": mapping["t"],
1587 }
1588
1589
1590 def writeCLDRLanguageTagData(println, data, url):
1591 """Writes the language tag data to the Intl data file."""
1592
1593 println(generatedFileWarning)
1594 println("// Version: CLDR-{}".format(data["version"]))
1595 println(f"// URL: {url}")
1596
1597 println(
1598 """
1599 #include "mozilla/Assertions.h"
1600 #include "mozilla/Span.h"
1601 #include "mozilla/TextUtils.h"
1602
1603 #include <algorithm>
1604 #include <cstdint>
1605 #include <cstring>
1606 #include <iterator>
1607 #include <string>
1608 #include <type_traits>
1609
1610 #include "mozilla/intl/Locale.h"
1611
1612 using namespace mozilla::intl::LanguageTagLimits;
1613
1614 template <size_t Length, size_t TagLength, size_t SubtagLength>
1615 static inline bool HasReplacement(
1616 const char (&subtags)[Length][TagLength],
1617 const mozilla::intl::LanguageTagSubtag<SubtagLength>& subtag) {
1618 MOZ_ASSERT(subtag.Length() == TagLength - 1,
1619 "subtag must have the same length as the list of subtags");
1620
1621 const char* ptr = subtag.Span().data();
1622 return std::binary_search(std::begin(subtags), std::end(subtags), ptr,
1623 [](const char* a, const char* b) {
1624 return memcmp(a, b, TagLength - 1) < 0;
1625 });
1626 }
1627
1628 template <size_t Length, size_t TagLength, size_t SubtagLength>
1629 static inline const char* SearchReplacement(
1630 const char (&subtags)[Length][TagLength], const char* (&aliases)[Length],
1631 const mozilla::intl::LanguageTagSubtag<SubtagLength>& subtag) {
1632 MOZ_ASSERT(subtag.Length() == TagLength - 1,
1633 "subtag must have the same length as the list of subtags");
1634
1635 const char* ptr = subtag.Span().data();
1636 auto p = std::lower_bound(std::begin(subtags), std::end(subtags), ptr,
1637 [](const char* a, const char* b) {
1638 return memcmp(a, b, TagLength - 1) < 0;
1639 });
1640 if (p != std::end(subtags) && memcmp(*p, ptr, TagLength - 1) == 0) {
1641 return aliases[std::distance(std::begin(subtags), p)];
1642 }
1643 return nullptr;
1644 }
1645
1646 #ifdef DEBUG
1647 static bool IsAsciiLowercaseAlphanumeric(char c) {
1648 return mozilla::IsAsciiLowercaseAlpha(c) || mozilla::IsAsciiDigit(c);
1649 }
1650
1651 static bool IsAsciiLowercaseAlphanumericOrDash(char c) {
1652 return IsAsciiLowercaseAlphanumeric(c) || c == '-';
1653 }
1654
1655 static bool IsCanonicallyCasedLanguageTag(mozilla::Span<const char> span) {
1656 return std::all_of(span.begin(), span.end(),
1657 mozilla::IsAsciiLowercaseAlpha<char>);
1658 }
1659
1660 static bool IsCanonicallyCasedScriptTag(mozilla::Span<const char> span) {
1661 return mozilla::IsAsciiUppercaseAlpha(span[0]) &&
1662 std::all_of(span.begin() + 1, span.end(),
1663 mozilla::IsAsciiLowercaseAlpha<char>);
1664 }
1665
1666 static bool IsCanonicallyCasedRegionTag(mozilla::Span<const char> span) {
1667 return std::all_of(span.begin(), span.end(),
1668 mozilla::IsAsciiUppercaseAlpha<char>) ||
1669 std::all_of(span.begin(), span.end(), mozilla::IsAsciiDigit<char>);
1670 }
1671
1672 static bool IsCanonicallyCasedVariantTag(mozilla::Span<const char> span) {
1673 return std::all_of(span.begin(), span.end(), IsAsciiLowercaseAlphanumeric);
1674 }
1675
1676 static bool IsCanonicallyCasedUnicodeKey(mozilla::Span<const char> key) {
1677 return std::all_of(key.begin(), key.end(), IsAsciiLowercaseAlphanumeric);
1678 }
1679
1680 static bool IsCanonicallyCasedUnicodeType(mozilla::Span<const char> type) {
1681 return std::all_of(type.begin(), type.end(),
1682 IsAsciiLowercaseAlphanumericOrDash);
1683 }
1684
1685 static bool IsCanonicallyCasedTransformKey(mozilla::Span<const char> key) {
1686 return std::all_of(key.begin(), key.end(), IsAsciiLowercaseAlphanumeric);
1687 }
1688
1689 static bool IsCanonicallyCasedTransformType(mozilla::Span<const char> type) {
1690 return std::all_of(type.begin(), type.end(),
1691 IsAsciiLowercaseAlphanumericOrDash);
1692 }
1693 #endif
1694 """.rstrip()
1695 )
1696
1697 source = "CLDR Supplemental Data, version {}".format(data["version"])
1698 legacy_mappings = data["legacyMappings"]
1699 language_mappings = data["languageMappings"]
1700 complex_language_mappings = data["complexLanguageMappings"]
1701 script_mappings = data["scriptMappings"]
1702 region_mappings = data["regionMappings"]
1703 complex_region_mappings = data["complexRegionMappings"]
1704 variant_mappings = data["variantMappings"]
1705 unicode_mappings = data["unicodeMappings"]
1706 transform_mappings = data["transformMappings"]
1707
1708 # unicode_language_subtag = alpha{2,3} | alpha{5,8} ;
1709 language_maxlength = 8
1710
1711 # unicode_script_subtag = alpha{4} ;
1712 script_maxlength = 4
1713
1714 # unicode_region_subtag = (alpha{2} | digit{3}) ;
1715 region_maxlength = 3
1716
1717 writeMappingsBinarySearch(
1718 println,
1719 "LanguageMapping",
1720 "LanguageSubtag&",
1721 "language",
1722 "IsStructurallyValidLanguageTag",
1723 "IsCanonicallyCasedLanguageTag",
1724 language_mappings,
1725 language_maxlength,
1726 "Mappings from language subtags to preferred values.",
1727 source,
1728 url,
1729 )
1730 writeMappingsBinarySearch(
1731 println,
1732 "ComplexLanguageMapping",
1733 "const LanguageSubtag&",
1734 "language",
1735 "IsStructurallyValidLanguageTag",
1736 "IsCanonicallyCasedLanguageTag",
1737 complex_language_mappings.keys(),
1738 language_maxlength,
1739 "Language subtags with complex mappings.",
1740 source,
1741 url,
1742 )
1743 writeMappingsBinarySearch(
1744 println,
1745 "ScriptMapping",
1746 "ScriptSubtag&",
1747 "script",
1748 "IsStructurallyValidScriptTag",
1749 "IsCanonicallyCasedScriptTag",
1750 script_mappings,
1751 script_maxlength,
1752 "Mappings from script subtags to preferred values.",
1753 source,
1754 url,
1755 )
1756 writeMappingsBinarySearch(
1757 println,
1758 "RegionMapping",
1759 "RegionSubtag&",
1760 "region",
1761 "IsStructurallyValidRegionTag",
1762 "IsCanonicallyCasedRegionTag",
1763 region_mappings,
1764 region_maxlength,
1765 "Mappings from region subtags to preferred values.",
1766 source,
1767 url,
1768 )
1769 writeMappingsBinarySearch(
1770 println,
1771 "ComplexRegionMapping",
1772 "const RegionSubtag&",
1773 "region",
1774 "IsStructurallyValidRegionTag",
1775 "IsCanonicallyCasedRegionTag",
1776 complex_region_mappings.keys(),
1777 region_maxlength,
1778 "Region subtags with complex mappings.",
1779 source,
1780 url,
1781 )
1782
1783 writeComplexLanguageTagMappings(
1784 println,
1785 complex_language_mappings,
1786 "Language subtags with complex mappings.",
1787 source,
1788 url,
1789 )
1790 writeComplexRegionTagMappings(
1791 println,
1792 complex_region_mappings,
1793 "Region subtags with complex mappings.",
1794 source,
1795 url,
1796 )
1797
1798 writeVariantTagMappings(
1799 println,
1800 variant_mappings,
1801 "Mappings from variant subtags to preferred values.",
1802 source,
1803 url,
1804 )
1805
1806 writeLegacyMappingsFunction(
1807 println, legacy_mappings, "Canonicalize legacy locale identifiers.", source, url
1808 )
1809
1810 writeSignLanguageMappingsFunction(
1811 println, legacy_mappings, "Mappings from legacy sign languages.", source, url
1812 )
1813
1814 writeUnicodeExtensionsMappings(println, unicode_mappings, "Unicode")
1815 writeUnicodeExtensionsMappings(println, transform_mappings, "Transform")
1816
1817
1818 def writeCLDRLanguageTagLikelySubtagsTest(println, data, url):
1819 """Writes the likely-subtags test file."""
1820
1821 println(generatedFileWarning)
1822
1823 source = "CLDR Supplemental Data, version {}".format(data["version"])
1824 language_mappings = data["languageMappings"]
1825 complex_language_mappings = data["complexLanguageMappings"]
1826 script_mappings = data["scriptMappings"]
1827 region_mappings = data["regionMappings"]
1828 complex_region_mappings = data["complexRegionMappings"]
1829 likely_subtags = data["likelySubtags"]
1830
1831 def bcp47(tag):
1832 (language, script, region) = tag
1833 return "{}{}{}".format(
1834 language, "-" + script if script else "", "-" + region if region else ""
1835 )
1836
1837 def canonical(tag):
1838 (language, script, region) = tag
1839
1840 # Map deprecated language subtags.
1841 if language in language_mappings:
1842 language = language_mappings[language]
1843 elif language in complex_language_mappings:
1844 (language2, script2, region2) = complex_language_mappings[language]
1845 (language, script, region) = (
1846 language2,
1847 script if script else script2,
1848 region if region else region2,
1849 )
1850
1851 # Map deprecated script subtags.
1852 if script in script_mappings:
1853 script = script_mappings[script]
1854
1855 # Map deprecated region subtags.
1856 if region in region_mappings:
1857 region = region_mappings[region]
1858 else:
1859 # Assume no complex region mappings are needed for now.
1860 assert (
1861 region not in complex_region_mappings
1862 ), f"unexpected region with complex mappings: {region}"
1863
1864 return (language, script, region)
1865
1866 # https://unicode.org/reports/tr35/#Likely_Subtags
1867
1868 def addLikelySubtags(tag):
1869 # Step 1: Canonicalize.
1870 (language, script, region) = canonical(tag)
1871 if script == "Zzzz":
1872 script = None
1873 if region == "ZZ":
1874 region = None
1875
1876 # Step 2: Lookup.
1877 searches = (
1878 (language, script, region),
1879 (language, script, None),
1880 (language, None, region),
1881 (language, None, None),
1882 )
1883 search = next(search for search in searches if search in likely_subtags)
1884
1885 (language_s, script_s, region_s) = search
1886 (language_m, script_m, region_m) = likely_subtags[search]
1887
1888 # Step 3: Return.
1889 return (
1890 language if language != language_s else language_m,
1891 script if script != script_s else script_m,
1892 region if region != region_s else region_m,
1893 )
1894
1895 # https://unicode.org/reports/tr35/#Likely_Subtags
1896 def removeLikelySubtags(tag):
1897 # Step 1: Add likely subtags.
1898 max = addLikelySubtags(tag)
1899
1900 # Step 2: Remove variants (doesn't apply here).
1901
1902 # Step 3: Find a match.
1903 (language, script, region) = max
1904 for trial in (
1905 (language, None, None),
1906 (language, None, region),
1907 (language, script, None),
1908 ):
1909 if addLikelySubtags(trial) == max:
1910 return trial
1911
1912 # Step 4: Return maximized if no match found.
1913 return max
1914
1915 def likely_canonical(from_tag, to_tag):
1916 # Canonicalize the input tag.
1917 from_tag = canonical(from_tag)
1918
1919 # Update the expected result if necessary.
1920 if from_tag in likely_subtags:
1921 to_tag = likely_subtags[from_tag]
1922
1923 # Canonicalize the expected output.
1924 to_canonical = canonical(to_tag)
1925
1926 # Sanity check: This should match the result of |addLikelySubtags|.
1927 assert to_canonical == addLikelySubtags(from_tag)
1928
1929 return to_canonical
1930
1931 # |likely_subtags| contains non-canonicalized tags, so canonicalize it first.
1932 likely_subtags_canonical = {
1933 k: likely_canonical(k, v) for (k, v) in likely_subtags.items()
1934 }
1935
1936 # Add test data for |Intl.Locale.prototype.maximize()|.
1937 writeMappingsVar(
1938 println,
1939 {bcp47(k): bcp47(v) for (k, v) in likely_subtags_canonical.items()},
1940 "maxLikelySubtags",
1941 "Extracted from likelySubtags.xml.",
1942 source,
1943 url,
1944 )
1945
1946 # Use the maximalized tags as the input for the remove likely-subtags test.
1947 minimized = {
1948 tag: removeLikelySubtags(tag) for tag in likely_subtags_canonical.values()
1949 }
1950
1951 # Add test data for |Intl.Locale.prototype.minimize()|.
1952 writeMappingsVar(
1953 println,
1954 {bcp47(k): bcp47(v) for (k, v) in minimized.items()},
1955 "minLikelySubtags",
1956 "Extracted from likelySubtags.xml.",
1957 source,
1958 url,
1959 )
1960
1961 println(
1962 """
1963 for (let [tag, maximal] of Object.entries(maxLikelySubtags)) {
1964 assertEq(new Intl.Locale(tag).maximize().toString(), maximal);
1965 }"""
1966 )
1967
1968 println(
1969 """
1970 for (let [tag, minimal] of Object.entries(minLikelySubtags)) {
1971 assertEq(new Intl.Locale(tag).minimize().toString(), minimal);
1972 }"""
1973 )
1974
1975 println(
1976 """
1977 if (typeof reportCompare === "function")
1978 reportCompare(0, 0);"""
1979 )
1980
1981
1982 def readCLDRVersionFromICU():
1983 icuDir = os.path.join(topsrcdir, "intl/icu/source")
1984 if not os.path.isdir(icuDir):
1985 raise RuntimeError(f"not a directory: {icuDir}")
1986
1987 reVersion = re.compile(r'\s*cldrVersion\{"(\d+(?:\.\d+)?)"\}')
1988
1989 for line in flines(os.path.join(icuDir, "data/misc/supplementalData.txt")):
1990 m = reVersion.match(line)
1991 if m:
1992 version = m.group(1)
1993 break
1994
1995 if version is None:
1996 raise RuntimeError("can't resolve CLDR version")
1997
1998 return version
1999
2000
2001 def updateCLDRLangTags(args):
2002 """Update the LanguageTagGenerated.cpp file."""
2003 version = args.version
2004 url = args.url
2005 out = args.out
2006 filename = args.file
2007
2008 # Determine current CLDR version from ICU.
2009 if version is None:
2010 version = readCLDRVersionFromICU()
2011
2012 url = url.replace("<VERSION>", version)
2013
2014 print("Arguments:")
2015 print("\tCLDR version: %s" % version)
2016 print("\tDownload url: %s" % url)
2017 if filename is not None:
2018 print("\tLocal CLDR common.zip file: %s" % filename)
2019 print("\tOutput file: %s" % out)
2020 print("")
2021
2022 data = {
2023 "version": version,
2024 }
2025
2026 def readFiles(cldr_file):
2027 with ZipFile(cldr_file) as zip_file:
2028 data.update(readSupplementalData(zip_file))
2029 data.update(readUnicodeExtensions(zip_file))
2030
2031 print("Processing CLDR data...")
2032 if filename is not None:
2033 print("Always make sure you have the newest CLDR common.zip!")
2034 with open(filename, "rb") as cldr_file:
2035 readFiles(cldr_file)
2036 else:
2037 print("Downloading CLDR common.zip...")
2038 with closing(urlopen(url)) as cldr_file:
2039 cldr_data = io.BytesIO(cldr_file.read())
2040 readFiles(cldr_data)
2041
2042 print("Writing Intl data...")
2043 with open(out, mode="w", encoding="utf-8", newline="") as f:
2044 println = partial(print, file=f)
2045
2046 writeCLDRLanguageTagData(println, data, url)
2047
2048 print("Writing Intl test data...")
2049 js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
2050 test_file = os.path.join(
2051 js_src_builtin_intl_dir,
2052 "../../tests/non262/Intl/Locale/likely-subtags-generated.js",
2053 )
2054 with open(test_file, mode="w", encoding="utf-8", newline="") as f:
2055 println = partial(print, file=f)
2056
2057 println("// |reftest| skip-if(!this.hasOwnProperty('Intl'))")
2058 writeCLDRLanguageTagLikelySubtagsTest(println, data, url)
2059
2060
2061 def flines(filepath, encoding="utf-8"):
2062 """Open filepath and iterate over its content."""
2063 with open(filepath, encoding=encoding) as f:
2064 for line in f:
2065 yield line
2066
2067
2068 @total_ordering
2069 class Zone:
2070 """Time zone with optional file name."""
2071
2072 def __init__(self, name, filename=""):
2073 self.name = name
2074 self.filename = filename
2075
2076 def __eq__(self, other):
2077 return hasattr(other, "name") and self.name == other.name
2078
2079 def __lt__(self, other):
2080 return self.name < other.name
2081
2082 def __hash__(self):
2083 return hash(self.name)
2084
2085 def __str__(self):
2086 return self.name
2087
2088 def __repr__(self):
2089 return self.name
2090
2091
2092 class TzDataDir:
2093 """tzdata source from a directory."""
2094
2095 def __init__(self, obj):
2096 self.name = partial(os.path.basename, obj)
2097 self.resolve = partial(os.path.join, obj)
2098 self.basename = os.path.basename
2099 self.isfile = os.path.isfile
2100 self.listdir = partial(os.listdir, obj)
2101 self.readlines = flines
2102
2103
2104 class TzDataFile:
2105 """tzdata source from a file (tar or gzipped)."""
2106
2107 def __init__(self, obj):
2108 self.name = lambda: os.path.splitext(
2109 os.path.splitext(os.path.basename(obj))[0]
2110 )[0]
2111 self.resolve = obj.getmember
2112 self.basename = attrgetter("name")
2113 self.isfile = tarfile.TarInfo.isfile
2114 self.listdir = obj.getnames
2115 self.readlines = partial(self._tarlines, obj)
2116
2117 def _tarlines(self, tar, m):
2118 with closing(tar.extractfile(m)) as f:
2119 for line in f:
2120 yield line.decode("utf-8")
2121
2122
2123 def validateTimeZones(zones, links):
2124 """Validate the zone and link entries."""
2125 linkZones = set(links.keys())
2126 intersect = linkZones.intersection(zones)
2127 if intersect:
2128 raise RuntimeError("Links also present in zones: %s" % intersect)
2129
2130 zoneNames = {z.name for z in zones}
2131 linkTargets = set(links.values())
2132 if not linkTargets.issubset(zoneNames):
2133 raise RuntimeError(
2134 "Link targets not found: %s" % linkTargets.difference(zoneNames)
2135 )
2136
2137
2138 def partition(iterable, *predicates):
2139 def innerPartition(pred, it):
2140 it1, it2 = tee(it)
2141 return (filter(pred, it1), filterfalse(pred, it2))
2142
2143 if len(predicates) == 0:
2144 return iterable
2145 (left, right) = innerPartition(predicates[0], iterable)
2146 if len(predicates) == 1:
2147 return (left, right)
2148 return tuple([left] + list(partition(right, *predicates[1:])))
2149
2150
2151 def listIANAFiles(tzdataDir):
2152 def isTzFile(d, m, f):
2153 return m(f) and d.isfile(d.resolve(f))
2154
2155 return filter(
2156 partial(isTzFile, tzdataDir, re.compile("^[a-z0-9]+$").match),
2157 tzdataDir.listdir(),
2158 )
2159
2160
2161 def readIANAFiles(tzdataDir, files):
2162 """Read all IANA time zone files from the given iterable."""
2163 nameSyntax = r"[\w/+\-]+"
2164 pZone = re.compile(r"Zone\s+(?P<name>%s)\s+.*" % nameSyntax)
2165 pLink = re.compile(
2166 r"(#PACKRATLIST\s+zone.tab\s+)?Link\s+(?P<target>%s)\s+(?P<name>%s)(?:\s+#.*)?"
2167 % (nameSyntax, nameSyntax)
2168 )
2169
2170 def createZone(line, fname):
2171 match = pZone.match(line)
2172 name = match.group("name")
2173 return Zone(name, fname)
2174
2175 def createLink(line, fname):
2176 match = pLink.match(line)
2177 (name, target) = match.group("name", "target")
2178 return (Zone(name, fname), target)
2179
2180 zones = set()
2181 links = dict()
2182 packrat_links = dict()
2183 for filename in files:
2184 filepath = tzdataDir.resolve(filename)
2185 for line in tzdataDir.readlines(filepath):
2186 if line.startswith("Zone"):
2187 zones.add(createZone(line, filename))
2188 if line.startswith("Link"):
2189 (link, target) = createLink(line, filename)
2190 links[link] = target
2191 if line.startswith("#PACKRATLIST zone.tab Link"):
2192 (link, target) = createLink(line, filename)
2193 packrat_links[link] = target
2194
2195 return (zones, links, packrat_links)
2196
2197
2198 def readIANATimeZones(tzdataDir, ignoreFactory):
2199 """Read the IANA time zone information from `tzdataDir`."""
2200
2201 files_to_ignore = ["backzone"]
2202
2203 # Ignore the placeholder time zone "Factory".
2204 if ignoreFactory:
2205 files_to_ignore.append("factory")
2206
2207 tzfiles = (file for file in listIANAFiles(tzdataDir) if file not in files_to_ignore)
2208
2209 # Read zone and link infos.
2210 (zones, links, _) = readIANAFiles(tzdataDir, tzfiles)
2211
2212 validateTimeZones(zones, links)
2213
2214 return (zones, links)
2215
2216
2217 def readICUResourceFile(filename):
2218 """Read an ICU resource file.
2219
2220 Yields (<table-name>, <startOrEnd>, <value>) for each table.
2221 """
2222
2223 numberValue = r"-?\d+"
2224 stringValue = r'".+?"'
2225
2226 def asVector(val):
2227 return r"%s(?:\s*,\s*%s)*" % (val, val)
2228
2229 numberVector = asVector(numberValue)
2230 stringVector = asVector(stringValue)
2231
2232 reNumberVector = re.compile(numberVector)
2233 reStringVector = re.compile(stringVector)
2234 reNumberValue = re.compile(numberValue)
2235 reStringValue = re.compile(stringValue)
2236
2237 def parseValue(value):
2238 m = reNumberVector.match(value)
2239 if m:
2240 return [int(v) for v in reNumberValue.findall(value)]
2241 m = reStringVector.match(value)
2242 if m:
2243 return [v[1:-1] for v in reStringValue.findall(value)]
2244 raise RuntimeError("unknown value type: %s" % value)
2245
2246 def extractValue(values):
2247 if len(values) == 0:
2248 return None
2249 if len(values) == 1:
2250 return values[0]
2251 return values
2252
2253 def line(*args):
2254 maybeMultiComments = r"(?:/\*[^*]*\*/)*"
2255 maybeSingleComment = r"(?://.*)?"
2256 lineStart = "^%s" % maybeMultiComments
2257 lineEnd = r"%s\s*%s$" % (maybeMultiComments, maybeSingleComment)
2258 return re.compile(r"\s*".join(chain([lineStart], args, [lineEnd])))
2259
2260 tableName = r'(?P<quote>"?)(?P<name>.+?)(?P=quote)'
2261 tableValue = r"(?P<value>%s|%s)" % (numberVector, stringVector)
2262
2263 reStartTable = line(tableName, r"\{")
2264 reEndTable = line(r"\}")
2265 reSingleValue = line(r",?", tableValue, r",?")
2266 reCompactTable = line(tableName, r"\{", tableValue, r"\}")
2267 reEmptyLine = line()
2268
2269 tables = []
2270
2271 def currentTable():
2272 return "|".join(tables)
2273
2274 values = []
2275 for line in flines(filename, "utf-8-sig"):
2276 line = line.strip()
2277 if line == "":
2278 continue
2279
2280 m = reEmptyLine.match(line)
2281 if m:
2282 continue
2283
2284 m = reStartTable.match(line)
2285 if m:
2286 assert len(values) == 0
2287 tables.append(m.group("name"))
2288 continue
2289
2290 m = reEndTable.match(line)
2291 if m:
2292 yield (currentTable(), extractValue(values))
2293 tables.pop()
2294 values = []
2295 continue
2296
2297 m = reCompactTable.match(line)
2298 if m:
2299 assert len(values) == 0
2300 tables.append(m.group("name"))
2301 yield (currentTable(), extractValue(parseValue(m.group("value"))))
2302 tables.pop()
2303 continue
2304
2305 m = reSingleValue.match(line)
2306 if m and tables:
2307 values.extend(parseValue(m.group("value")))
2308 continue
2309
2310 raise RuntimeError("unknown entry: %s" % line)
2311
2312
2313 def readICUTimeZonesFromTimezoneTypes(icuTzDir):
2314 """Read the ICU time zone information from `icuTzDir`/timezoneTypes.txt
2315 and returns the tuple (zones, links).
2316 """
2317 typeMapTimeZoneKey = "timezoneTypes:table(nofallback)|typeMap|timezone|"
2318 typeAliasTimeZoneKey = "timezoneTypes:table(nofallback)|typeAlias|timezone|"
2319
2320 def toTimeZone(name):
2321 return Zone(name.replace(":", "/"))
2322
2323 zones = set()
2324 links = dict()
2325
2326 for name, value in readICUResourceFile(os.path.join(icuTzDir, "timezoneTypes.txt")):
2327 if name.startswith(typeMapTimeZoneKey):
2328 zones.add(toTimeZone(name[len(typeMapTimeZoneKey) :]))
2329 if name.startswith(typeAliasTimeZoneKey):
2330 links[toTimeZone(name[len(typeAliasTimeZoneKey) :])] = value
2331
2332 validateTimeZones(zones, links)
2333
2334 return (zones, links)
2335
2336
2337 def readICUTimeZonesFromZoneInfo(icuTzDir):
2338 """Read the ICU time zone information from `icuTzDir`/zoneinfo64.txt
2339 and returns the tuple (zones, links).
2340 """
2341 zoneKey = "zoneinfo64:table(nofallback)|Zones:array|:table"
2342 linkKey = "zoneinfo64:table(nofallback)|Zones:array|:int"
2343 namesKey = "zoneinfo64:table(nofallback)|Names"
2344
2345 tzId = 0
2346 tzLinks = dict()
2347 tzNames = []
2348
2349 for name, value in readICUResourceFile(os.path.join(icuTzDir, "zoneinfo64.txt")):
2350 if name == zoneKey:
2351 tzId += 1
2352 elif name == linkKey:
2353 tzLinks[tzId] = int(value)
2354 tzId += 1
2355 elif name == namesKey:
2356 tzNames.extend(value)
2357
2358 links = {Zone(tzNames[zone]): tzNames[target] for (zone, target) in tzLinks.items()}
2359 zones = {Zone(v) for v in tzNames if Zone(v) not in links}
2360
2361 validateTimeZones(zones, links)
2362
2363 return (zones, links)
2364
2365
2366 def readICUTimeZones(icuDir, icuTzDir, ignoreFactory):
2367 # zoneinfo64.txt contains the supported time zones by ICU. This data is
2368 # generated from tzdata files, it doesn't include "backzone" in stock ICU.
2369 (zoneinfoZones, zoneinfoLinks) = readICUTimeZonesFromZoneInfo(icuTzDir)
2370
2371 # timezoneTypes.txt contains the canonicalization information for ICU. This
2372 # data is generated from CLDR files. It includes data about time zones from
2373 # tzdata's "backzone" file.
2374 (typesZones, typesLinks) = readICUTimeZonesFromTimezoneTypes(icuTzDir)
2375
2376 # Remove the placeholder time zone "Factory".
2377 # See also <https://github.com/eggert/tz/blob/master/factory>.
2378 if ignoreFactory:
2379 assert Zone("Factory") in zoneinfoZones
2380 assert Zone("Factory") not in zoneinfoLinks
2381 assert Zone("Factory") not in typesZones
2382 assert Zone("Factory") in typesLinks
2383
2384 zoneinfoZones.remove(Zone("Factory"))
2385 del typesLinks[Zone("Factory")]
2386
2387 # Remove the ICU placeholder time zone "Etc/Unknown".
2388 # See also <https://unicode.org/reports/tr35/#Time_Zone_Identifiers>.
2389 for zones in (zoneinfoZones, typesZones):
2390 zones.remove(Zone("Etc/Unknown"))
2391
2392 # Remove any outdated ICU links.
2393 for links in (zoneinfoLinks, typesLinks):
2394 for zone in otherICULegacyLinks().keys():
2395 if zone not in links:
2396 raise KeyError(f"Can't remove non-existent link from '{zone}'")
2397 del links[zone]
2398
2399 # Information in zoneinfo64 should be a superset of timezoneTypes.
2400 def inZoneInfo64(zone):
2401 return zone in zoneinfoZones or zone in zoneinfoLinks
2402
2403 notFoundInZoneInfo64 = [zone for zone in typesZones if not inZoneInfo64(zone)]
2404 if notFoundInZoneInfo64:
2405 raise RuntimeError(
2406 "Missing time zones in zoneinfo64.txt: %s" % notFoundInZoneInfo64
2407 )
2408
2409 notFoundInZoneInfo64 = [
2410 zone for zone in typesLinks.keys() if not inZoneInfo64(zone)
2411 ]
2412 if notFoundInZoneInfo64:
2413 raise RuntimeError(
2414 "Missing time zones in zoneinfo64.txt: %s" % notFoundInZoneInfo64
2415 )
2416
2417 # zoneinfo64.txt only defines the supported time zones by ICU, the canonicalization
2418 # rules are defined through timezoneTypes.txt. Merge both to get the actual zones
2419 # and links used by ICU.
2420 icuZones = set(
2421 chain(
2422 (zone for zone in zoneinfoZones if zone not in typesLinks),
2423 (zone for zone in typesZones),
2424 )
2425 )
2426 icuLinks = dict(
2427 chain(
2428 (
2429 (zone, target)
2430 for (zone, target) in zoneinfoLinks.items()
2431 if zone not in typesZones
2432 ),
2433 ((zone, target) for (zone, target) in typesLinks.items()),
2434 )
2435 )
2436
2437 return (icuZones, icuLinks)
2438
2439
2440 def readICULegacyZones(icuDir):
2441 """Read the ICU legacy time zones from `icuTzDir`/tools/tzcode/icuzones
2442 and returns the tuple (zones, links).
2443 """
2444 tzdir = TzDataDir(os.path.join(icuDir, "tools/tzcode"))
2445
2446 # Per spec we must recognize only IANA time zones and links, but ICU
2447 # recognizes various legacy, non-IANA time zones and links. Compute these
2448 # non-IANA time zones and links.
2449
2450 # Most legacy, non-IANA time zones and links are in the icuzones file.
2451 (zones, links, _) = readIANAFiles(tzdir, ["icuzones"])
2452
2453 # Remove the ICU placeholder time zone "Etc/Unknown".
2454 # See also <https://unicode.org/reports/tr35/#Time_Zone_Identifiers>.
2455 zones.remove(Zone("Etc/Unknown"))
2456
2457 # A handful of non-IANA zones/links are not in icuzones and must be added
2458 # manually so that we won't invoke ICU with them.
2459 for zone, target in otherICULegacyLinks().items():
2460 if zone in links:
2461 if links[zone] != target:
2462 raise KeyError(
2463 f"Can't overwrite link '{zone} -> {links[zone]}' with '{target}'"
2464 )
2465 else:
2466 print(
2467 f"Info: Link '{zone} -> {target}' can be removed from otherICULegacyLinks()"
2468 )
2469 links[zone] = target
2470
2471 return (zones, links)
2472
2473
2474 def otherICULegacyLinks():
2475 """The file `icuTzDir`/tools/tzcode/icuzones contains all ICU legacy time
2476 zones with the exception of time zones which are removed by IANA after an
2477 ICU release.
2478
2479 For example ICU 67 uses tzdata2018i, but tzdata2020b removed the link from
2480 "US/Pacific-New" to "America/Los_Angeles". ICU standalone tzdata updates
2481 don't include modified icuzones files, so we must manually record any IANA
2482 modifications here.
2483
2484 After an ICU update, we can remove any no longer needed entries from this
2485 function by checking if the relevant entries are now included in icuzones.
2486 """
2487
2488 return {
2489 # Current ICU is up-to-date with IANA, so this dict is empty.
2490 }
2491
2492
2493 def icuTzDataVersion(icuTzDir):
2494 """Read the ICU time zone version from `icuTzDir`/zoneinfo64.txt."""
2495
2496 def searchInFile(pattern, f):
2497 p = re.compile(pattern)
2498 for line in flines(f, "utf-8-sig"):
2499 m = p.search(line)
2500 if m:
2501 return m.group(1)
2502 return None
2503
2504 zoneinfo = os.path.join(icuTzDir, "zoneinfo64.txt")
2505 if not os.path.isfile(zoneinfo):
2506 raise RuntimeError("file not found: %s" % zoneinfo)
2507 version = searchInFile(r"^//\s+tz version:\s+([0-9]{4}[a-z])$", zoneinfo)
2508 if version is None:
2509 raise RuntimeError(
2510 "%s does not contain a valid tzdata version string" % zoneinfo
2511 )
2512 return version
2513
2514
2515 def findIncorrectICUZones(ianaZones, ianaLinks, icuZones, icuLinks):
2516 """Find incorrect ICU zone entries."""
2517
2518 def isIANATimeZone(zone):
2519 return zone in ianaZones or zone in ianaLinks
2520
2521 def isICUTimeZone(zone):
2522 return zone in icuZones or zone in icuLinks
2523
2524 def isICULink(zone):
2525 return zone in icuLinks
2526
2527 # All IANA zones should be present in ICU.
2528 missingTimeZones = [zone for zone in ianaZones if not isICUTimeZone(zone)]
2529 if missingTimeZones:
2530 raise RuntimeError(
2531 "Not all zones are present in ICU, did you forget "
2532 "to run intl/update-tzdata.sh? %s" % missingTimeZones
2533 )
2534
2535 # Zones which are only present in ICU?
2536 additionalTimeZones = [zone for zone in icuZones if not isIANATimeZone(zone)]
2537 if additionalTimeZones:
2538 raise RuntimeError(
2539 "Additional zones present in ICU, did you forget "
2540 "to run intl/update-tzdata.sh? %s" % additionalTimeZones
2541 )
2542
2543 # Zones which are marked as links in ICU.
2544 result = ((zone, icuLinks[zone]) for zone in ianaZones if isICULink(zone))
2545
2546 # Remove unnecessary UTC mappings.
2547 utcnames = ["Etc/UTC", "Etc/UCT", "Etc/GMT"]
2548 result = ((zone, target) for (zone, target) in result if zone.name not in utcnames)
2549
2550 return sorted(result, key=itemgetter(0))
2551
2552
2553 def findIncorrectICULinks(ianaZones, ianaLinks, icuZones, icuLinks):
2554 """Find incorrect ICU link entries."""
2555
2556 def isIANATimeZone(zone):
2557 return zone in ianaZones or zone in ianaLinks
2558
2559 def isICUTimeZone(zone):
2560 return zone in icuZones or zone in icuLinks
2561
2562 def isICULink(zone):
2563 return zone in icuLinks
2564
2565 def isICUZone(zone):
2566 return zone in icuZones
2567
2568 # All links should be present in ICU.
2569 missingTimeZones = [zone for zone in ianaLinks.keys() if not isICUTimeZone(zone)]
2570 if missingTimeZones:
2571 raise RuntimeError(
2572 "Not all zones are present in ICU, did you forget "
2573 "to run intl/update-tzdata.sh? %s" % missingTimeZones
2574 )
2575
2576 # Links which are only present in ICU?
2577 additionalTimeZones = [zone for zone in icuLinks.keys() if not isIANATimeZone(zone)]
2578 if additionalTimeZones:
2579 raise RuntimeError(
2580 "Additional links present in ICU, did you forget "
2581 "to run intl/update-tzdata.sh? %s" % additionalTimeZones
2582 )
2583
2584 result = chain(
2585 # IANA links which have a different target in ICU.
2586 (
2587 (zone, target, icuLinks[zone])
2588 for (zone, target) in ianaLinks.items()
2589 if isICULink(zone) and target != icuLinks[zone]
2590 ),
2591 # IANA links which are zones in ICU.
2592 (
2593 (zone, target, zone.name)
2594 for (zone, target) in ianaLinks.items()
2595 if isICUZone(zone)
2596 ),
2597 )
2598
2599 # Remove unnecessary UTC mappings.
2600 utcnames = ["Etc/UTC", "Etc/UCT", "Etc/GMT"]
2601 result = (
2602 (zone, target, icuTarget)
2603 for (zone, target, icuTarget) in result
2604 if target not in utcnames or icuTarget not in utcnames
2605 )
2606
2607 return sorted(result, key=itemgetter(0))
2608
2609
2610 def readZoneTab(tzdataDir):
2611 zone_country = dict()
2612
2613 zonetab_path = tzdataDir.resolve("zone.tab")
2614 for line in tzdataDir.readlines(zonetab_path):
2615 if line.startswith("#"):
2616 continue
2617 (country, coords, zone, *comments) = line.strip().split("\t")
2618 assert zone not in zone_country
2619 zone_country[zone] = country
2620
2621 return zone_country
2622
2623
2624 # 6.5.1 AvailableNamedTimeZoneIdentifiers ( )
2625 #
2626 # https://tc39.es/ecma402/#sup-availablenamedtimezoneidentifiers
2627 def availableNamedTimeZoneIdentifiers(tzdataDir, ignoreFactory):
2628 js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
2629
2630 with open(
2631 os.path.join(js_src_builtin_intl_dir, "TimeZoneMapping.yaml"),
2632 encoding="utf-8",
2633 ) as f:
2634 time_zone_mapping = yaml.safe_load(f)
2635
2636 zone_country = readZoneTab(tzdataDir)
2637
2638 def country_code_for(name):
2639 if name in zone_country:
2640 return zone_country[name]
2641 return time_zone_mapping[name]
2642
2643 (ianaZones, ianaLinks) = readIANATimeZones(tzdataDir, ignoreFactory)
2644
2645 (backzones, backlinks, packratlinks) = readIANAFiles(tzdataDir, ["backzone"])
2646 all_backzone_links = {**backlinks, **packratlinks}
2647
2648 # Steps 1-3. (Not applicable)
2649
2650 # Step 4.
2651 zones = set()
2652 links = dict()
2653
2654 # Step 5. (Partial, only zones)
2655 for zone in ianaZones:
2656 # Step 5.a.
2657 primary = zone
2658
2659 # Step 5.b. (Not applicable for zones)
2660
2661 # Step 5.c.
2662 if primary.name in ["Etc/UTC", "Etc/GMT", "GMT"]:
2663 primary = Zone("UTC", primary.filename)
2664
2665 # Step 5.d. (Not applicable)
2666
2667 # Steps 5.e-f.
2668 if primary == zone:
2669 assert zone not in zones
2670 zones.add(primary)
2671 else:
2672 assert zone not in links
2673 links[zone] = primary.name
2674
2675 # Step 5. (Partial, only links)
2676 for zone, target in ianaLinks.items():
2677 identifier = zone.name
2678
2679 # Step 5.a.
2680 primary = identifier
2681
2682 # Step 5.b.
2683 if identifier not in zone_country:
2684 # Step 5.b.i. (Not applicable)
2685
2686 # Steps 5.b.ii-iii.
2687 if target.startswith("Etc/"):
2688 primary = target
2689 else:
2690 # Step 5.b.iii.1.
2691 identifier_code_code = country_code_for(identifier)
2692
2693 # Step 5.b.iii.2.
2694 target_code_code = country_code_for(target)
2695
2696 # Steps 5.b.iii.3-4
2697 if identifier_code_code == target_code_code:
2698 primary = target
2699 else:
2700 # Step 5.b.iii.4.a.
2701 country_code_line_count = [
2702 zone
2703 for (zone, code) in zone_country.items()
2704 if code == identifier_code_code
2705 ]
2706
2707 # Steps 5.b.iii.4.b-c.
2708 if len(country_code_line_count) == 1:
2709 primary = country_code_line_count[0]
2710 else:
2711 assert Zone(identifier) in all_backzone_links
2712 primary = all_backzone_links[Zone(identifier)]
2713 assert identifier_code_code == country_code_for(primary)
2714
2715 # Step 5.c.
2716 if primary in ["Etc/UTC", "Etc/GMT", "GMT"]:
2717 primary = "UTC"
2718
2719 # Step 5.d. (Not applicable)
2720
2721 # Steps 5.e-f.
2722 if primary == identifier:
2723 assert zone not in zones
2724 zones.add(zone)
2725 else:
2726 assert zone not in links
2727 links[zone] = primary
2728
2729 # Ensure all zones and links are valid.
2730 validateTimeZones(zones, links)
2731
2732 # Step 6.
2733 assert Zone("UTC") in zones
2734
2735 # Step 7.
2736 return (zones, links)
2737
2738
2739 generatedFileWarning = "// Generated by make_intl_data.py. DO NOT EDIT."
2740 tzdataVersionComment = "// tzdata version = {0}"
2741
2742
2743 def processTimeZones(tzdataDir, icuDir, icuTzDir, version, ignoreFactory, out):
2744 """Read the time zone info and create a new time zone cpp file."""
2745 print("Processing tzdata mapping...")
2746 (ianaZones, ianaLinks) = availableNamedTimeZoneIdentifiers(tzdataDir, ignoreFactory)
2747 (icuZones, icuLinks) = readICUTimeZones(icuDir, icuTzDir, ignoreFactory)
2748 (legacyZones, legacyLinks) = readICULegacyZones(icuDir)
2749
2750 if ignoreFactory:
2751 legacyZones.add(Zone("Factory"))
2752
2753 # Remove all legacy ICU time zones.
2754 icuZones = {zone for zone in icuZones if zone not in legacyZones}
2755 icuLinks = {
2756 zone: target for (zone, target) in icuLinks.items() if zone not in legacyLinks
2757 }
2758
2759 incorrectZones = findIncorrectICUZones(ianaZones, ianaLinks, icuZones, icuLinks)
2760 if not incorrectZones:
2761 print("<<< No incorrect ICU time zones found, please update Intl.js! >>>")
2762 print("<<< Maybe https://ssl.icu-project.org/trac/ticket/12044 was fixed? >>>")
2763
2764 incorrectLinks = findIncorrectICULinks(ianaZones, ianaLinks, icuZones, icuLinks)
2765 if not incorrectLinks:
2766 print("<<< No incorrect ICU time zone links found, please update Intl.js! >>>")
2767 print("<<< Maybe https://ssl.icu-project.org/trac/ticket/12044 was fixed? >>>")
2768
2769 print("Writing Intl tzdata file...")
2770 with open(out, mode="w", encoding="utf-8", newline="") as f:
2771 println = partial(print, file=f)
2772
2773 println(generatedFileWarning)
2774 println(tzdataVersionComment.format(version))
2775 println("")
2776
2777 println("#ifndef builtin_intl_TimeZoneDataGenerated_h")
2778 println("#define builtin_intl_TimeZoneDataGenerated_h")
2779 println("")
2780
2781 println("namespace js {")
2782 println("namespace timezone {")
2783 println("")
2784
2785 println("// Format:")
2786 println('// "ZoneName" // ICU-Name [time zone file]')
2787 println("const char* const ianaZonesTreatedAsLinksByICU[] = {")
2788 for zone, icuZone in incorrectZones:
2789 println(' "%s", // %s [%s]' % (zone, icuZone, zone.filename))
2790 println("};")
2791 println("")
2792
2793 println("// Format:")
2794 println('// "LinkName", "Target" // ICU-Target [time zone file]')
2795 println("struct LinkAndTarget")
2796 println("{")
2797 println(" const char* const link;")
2798 println(" const char* const target;")
2799 println("};")
2800 println("")
2801 println("const LinkAndTarget ianaLinksCanonicalizedDifferentlyByICU[] = {")
2802 for zone, target, icuTarget in incorrectLinks:
2803 println(
2804 ' { "%s", "%s" }, // %s [%s]'
2805 % (zone, target, icuTarget, zone.filename)
2806 )
2807 println("};")
2808 println("")
2809
2810 println(
2811 "// Legacy ICU time zones, these are not valid IANA time zone names. We also"
2812 )
2813 println("// disallow the old and deprecated System V time zones.")
2814 println(
2815 "// https://ssl.icu-project.org/repos/icu/trunk/icu4c/source/tools/tzcode/icuzones"
2816 ) # NOQA: E501
2817 println("const char* const legacyICUTimeZones[] = {")
2818 for zone in chain(sorted(legacyLinks.keys()), sorted(legacyZones)):
2819 println(' "%s",' % zone)
2820 println("};")
2821 println("")
2822
2823 println("} // namespace timezone")
2824 println("} // namespace js")
2825 println("")
2826 println("#endif /* builtin_intl_TimeZoneDataGenerated_h */")
2827
2828
2829 def generateTzDataTestLinks(tzdataDir, version, ignoreFactory, testDir):
2830 fileName = "timeZone_links.js"
2831
2832 # Read zone and link infos.
2833 (_, links) = availableNamedTimeZoneIdentifiers(tzdataDir, ignoreFactory)
2834
2835 with open(
2836 os.path.join(testDir, fileName), mode="w", encoding="utf-8", newline=""
2837 ) as f:
2838 println = partial(print, file=f)
2839
2840 println('// |reftest| skip-if(!this.hasOwnProperty("Intl"))')
2841 println("")
2842 println(generatedFileWarning)
2843 println(tzdataVersionComment.format(version))
2844 println(
2845 """
2846 const tzMapper = [
2847 x => x,
2848 x => x.toUpperCase(),
2849 x => x.toLowerCase(),
2850 ];
2851 """
2852 )
2853
2854 println("// Link names derived from IANA Time Zone Database.")
2855 println("const links = {")
2856 for zone, target in sorted(links.items(), key=itemgetter(0)):
2857 println(' "%s": "%s",' % (zone, target))
2858 println("};")
2859
2860 println(
2861 """
2862 for (let [linkName, target] of Object.entries(links)) {
2863 if (target === "Etc/UTC" || target === "Etc/GMT")
2864 target = "UTC";
2865
2866 for (let map of tzMapper) {
2867 let dtf = new Intl.DateTimeFormat(undefined, {timeZone: map(linkName)});
2868 let resolvedTimeZone = dtf.resolvedOptions().timeZone;
2869 assertEq(resolvedTimeZone, target, `${linkName} -> ${target}`);
2870 }
2871 }
2872 """
2873 )
2874 println(
2875 """
2876 if (typeof reportCompare === "function")
2877 reportCompare(0, 0, "ok");
2878 """
2879 )
2880
2881
2882 def generateTzDataTestVersion(tzdataDir, version, testDir):
2883 fileName = "timeZone_version.js"
2884
2885 with open(
2886 os.path.join(testDir, fileName), mode="w", encoding="utf-8", newline=""
2887 ) as f:
2888 println = partial(print, file=f)
2889
2890 println('// |reftest| skip-if(!this.hasOwnProperty("Intl"))')
2891 println("")
2892 println(generatedFileWarning)
2893 println(tzdataVersionComment.format(version))
2894 println(f"""const tzdata = "{version}";""")
2895
2896 println(
2897 """
2898 if (typeof getICUOptions === "undefined") {
2899 var getICUOptions = SpecialPowers.Cu.getJSTestingFunctions().getICUOptions;
2900 }
2901
2902 var options = getICUOptions();
2903
2904 assertEq(options.tzdata, tzdata);
2905
2906 if (typeof reportCompare === "function")
2907 reportCompare(0, 0, "ok");
2908 """
2909 )
2910
2911
2912 def generateTzDataTestCanonicalZones(tzdataDir, version, ignoreFactory, testDir):
2913 fileName = "supportedValuesOf-timeZones-canonical.js"
2914
2915 # Read zone and link infos.
2916 (zones, _) = availableNamedTimeZoneIdentifiers(tzdataDir, ignoreFactory)
2917
2918 with open(
2919 os.path.join(testDir, fileName), mode="w", encoding="utf-8", newline=""
2920 ) as f:
2921 println = partial(print, file=f)
2922
2923 println('// |reftest| skip-if(!this.hasOwnProperty("Intl"))')
2924 println("")
2925 println(generatedFileWarning)
2926 println(tzdataVersionComment.format(version))
2927
2928 println("const zones = [")
2929 for zone in sorted(zones):
2930 println(f' "{zone}",')
2931 println("];")
2932
2933 println(
2934 """
2935 let supported = Intl.supportedValuesOf("timeZone");
2936
2937 assertEqArray(supported, zones);
2938
2939 if (typeof reportCompare === "function")
2940 reportCompare(0, 0, "ok");
2941 """
2942 )
2943
2944
2945 def generateTzDataTestZones(tzdataDir, version, ignoreFactory, testDir):
2946 fileName = "zones-and-links.js"
2947
2948 # Read zone and link infos.
2949 (zones, links) = availableNamedTimeZoneIdentifiers(tzdataDir, ignoreFactory)
2950
2951 with open(
2952 os.path.join(testDir, fileName), mode="w", encoding="utf-8", newline=""
2953 ) as f:
2954 println = partial(print, file=f)
2955
2956 println(
2957 '// |reftest| shell-option(--enable-temporal) skip-if(!this.hasOwnProperty("Temporal"))'
2958 )
2959 println("")
2960 println(generatedFileWarning)
2961 println(tzdataVersionComment.format(version))
2962
2963 println("const zones = [")
2964 for zone in sorted(zones):
2965 println(f' "{zone}",')
2966 println("];")
2967
2968 println("const links = {")
2969 for link, target in sorted(links.items(), key=itemgetter(0)):
2970 println(f' "{link}": "{target}",')
2971 println("};")
2972
2973 println(
2974 """
2975 let epochNanoseconds = [
2976 new Temporal.PlainDate(1900, 1, 1).toZonedDateTime("UTC").epochNanoseconds,
2977 new Temporal.PlainDate(1950, 1, 1).toZonedDateTime("UTC").epochNanoseconds,
2978 new Temporal.PlainDate(1960, 1, 1).toZonedDateTime("UTC").epochNanoseconds,
2979 new Temporal.PlainDate(1970, 1, 1).toZonedDateTime("UTC").epochNanoseconds,
2980 new Temporal.PlainDate(1980, 1, 1).toZonedDateTime("UTC").epochNanoseconds,
2981 new Temporal.PlainDate(1990, 1, 1).toZonedDateTime("UTC").epochNanoseconds,
2982 new Temporal.PlainDate(2000, 1, 1).toZonedDateTime("UTC").epochNanoseconds,
2983 new Temporal.PlainDate(2010, 1, 1).toZonedDateTime("UTC").epochNanoseconds,
2984 new Temporal.PlainDate(2020, 1, 1).toZonedDateTime("UTC").epochNanoseconds,
2985 new Temporal.PlainDate(2030, 1, 1).toZonedDateTime("UTC").epochNanoseconds,
2986 ];
2987
2988 function timeZoneId(zdt) {
2989 let str = zdt.toString();
2990 let m = str.match(/(?<=\\[)[\\w\\/_+-]+(?=\\])/);
2991 assertEq(m !== null, true, str);
2992 return m[0];
2993 }
2994
2995 for (let zone of zones) {
2996 let zdt = new Temporal.ZonedDateTime(0n, zone);
2997
2998 assertEq(zdt.timeZoneId, zone);
2999 assertEq(timeZoneId(zdt), zone);
3000 }
3001
3002 for (let [link, zone] of Object.entries(links)) {
3003 assertEq(link === zone, false, `link=${link}, zone=${zone}`);
3004 assertEq(zones.includes(zone), true, `zone=${zone}`);
3005
3006 let zdtLink = new Temporal.ZonedDateTime(0n, link);
3007 let zdtZone = new Temporal.ZonedDateTime(0n, zone);
3008
3009 assertEq(zdtLink.timeZoneId, link);
3010 assertEq(timeZoneId(zdtLink), link);
3011
3012 assertEq(zdtZone.timeZoneId, zone);
3013 assertEq(timeZoneId(zdtZone), zone);
3014
3015 assertEq(zdtLink.equals(zdtZone), true, `link=${link}, zone=${zone}`);
3016
3017 assertEq(
3018 zdtLink.offsetNanoseconds,
3019 zdtZone.offsetNanoseconds,
3020 `link=${link}, zone=${zone}`
3021 );
3022
3023 for (let epochNs of epochNanoseconds) {
3024 assertEq(
3025 new Temporal.ZonedDateTime(epochNs, link).offsetNanoseconds,
3026 new Temporal.ZonedDateTime(epochNs, zone).offsetNanoseconds,
3027 `link=${link}, zone=${zone}, epochNs=${epochNs}`
3028 );
3029 }
3030 }
3031
3032 if (typeof reportCompare === "function")
3033 reportCompare(0, 0, "ok");
3034 """
3035 )
3036
3037
3038 def generateTzDataTests(tzdataDir, version, ignoreFactory, testDir):
3039 dtfTestDir = os.path.join(testDir, "DateTimeFormat")
3040 if not os.path.isdir(dtfTestDir):
3041 raise RuntimeError("not a directory: %s" % dtfTestDir)
3042
3043 zdtTestDir = os.path.join(testDir, "../Temporal/ZonedDateTime")
3044 if not os.path.isdir(zdtTestDir):
3045 raise RuntimeError("not a directory: %s" % zdtTestDir)
3046
3047 generateTzDataTestLinks(tzdataDir, version, ignoreFactory, dtfTestDir)
3048 generateTzDataTestVersion(tzdataDir, version, dtfTestDir)
3049 generateTzDataTestCanonicalZones(tzdataDir, version, ignoreFactory, testDir)
3050 generateTzDataTestZones(tzdataDir, version, ignoreFactory, zdtTestDir)
3051
3052
3053 def updateTzdata(topsrcdir, args):
3054 """Update the time zone cpp file."""
3055
3056 icuDir = os.path.join(topsrcdir, "intl/icu/source")
3057 if not os.path.isdir(icuDir):
3058 raise RuntimeError("not a directory: %s" % icuDir)
3059
3060 icuTzDir = os.path.join(topsrcdir, "intl/tzdata/source")
3061 if not os.path.isdir(icuTzDir):
3062 raise RuntimeError("not a directory: %s" % icuTzDir)
3063
3064 intlTestDir = os.path.join(topsrcdir, "js/src/tests/non262/Intl")
3065 if not os.path.isdir(intlTestDir):
3066 raise RuntimeError("not a directory: %s" % intlTestDir)
3067
3068 tzDir = args.tz
3069 if tzDir is not None and not (os.path.isdir(tzDir) or os.path.isfile(tzDir)):
3070 raise RuntimeError("not a directory or file: %s" % tzDir)
3071 out = args.out
3072
3073 # Ignore the placeholder time zone "Factory".
3074 ignoreFactory = True
3075
3076 version = icuTzDataVersion(icuTzDir)
3077 url = (
3078 "https://www.iana.org/time-zones/repository/releases/tzdata%s.tar.gz" % version
3079 )
3080
3081 print("Arguments:")
3082 print("\ttzdata version: %s" % version)
3083 print("\ttzdata URL: %s" % url)
3084 print("\ttzdata directory|file: %s" % tzDir)
3085 print("\tICU directory: %s" % icuDir)
3086 print("\tICU timezone directory: %s" % icuTzDir)
3087 print("\tOutput file: %s" % out)
3088 print("")
3089
3090 def updateFrom(f):
3091 if os.path.isfile(f) and tarfile.is_tarfile(f):
3092 with tarfile.open(f, "r:*") as tar:
3093 processTimeZones(
3094 TzDataFile(tar),
3095 icuDir,
3096 icuTzDir,
3097 version,
3098 ignoreFactory,
3099 out,
3100 )
3101 generateTzDataTests(
3102 TzDataFile(tar), version, ignoreFactory, intlTestDir
3103 )
3104 elif os.path.isdir(f):
3105 processTimeZones(
3106 TzDataDir(f),
3107 icuDir,
3108 icuTzDir,
3109 version,
3110 ignoreFactory,
3111 out,
3112 )
3113 generateTzDataTests(TzDataDir(f), version, ignoreFactory, intlTestDir)
3114 else:
3115 raise RuntimeError("unknown format")
3116
3117 if tzDir is None:
3118 print("Downloading tzdata file...")
3119 with closing(urlopen(url)) as tzfile:
3120 fname = urlsplit(tzfile.geturl()).path.split("/")[-1]
3121 with tempfile.NamedTemporaryFile(suffix=fname) as tztmpfile:
3122 print("File stored in %s" % tztmpfile.name)
3123 tztmpfile.write(tzfile.read())
3124 tztmpfile.flush()
3125 updateFrom(tztmpfile.name)
3126 else:
3127 updateFrom(tzDir)
3128
3129
3130 def readCurrencyFile(tree):
3131 reCurrency = re.compile(r"^[A-Z]{3}$")
3132 reIntMinorUnits = re.compile(r"^\d+$")
3133
3134 for country in tree.iterfind(".//CcyNtry"):
3135 # Skip entry if no currency information is available.
3136 currency = country.findtext("Ccy")
3137 if currency is None:
3138 continue
3139 assert reCurrency.match(currency)
3140
3141 minorUnits = country.findtext("CcyMnrUnts")
3142 assert minorUnits is not None
3143
3144 # Skip all entries without minorUnits or which use the default minorUnits.
3145 if reIntMinorUnits.match(minorUnits) and int(minorUnits) != 2:
3146 currencyName = country.findtext("CcyNm")
3147 countryName = country.findtext("CtryNm")
3148 yield (currency, int(minorUnits), currencyName, countryName)
3149
3150
3151 def writeCurrencyFile(published, currencies, out):
3152 with open(out, mode="w", encoding="utf-8", newline="") as f:
3153 println = partial(print, file=f)
3154
3155 println(generatedFileWarning)
3156 println(f"// Version: {published}")
3157
3158 println(
3159 """
3160 /**
3161 * Mapping from currency codes to the number of decimal digits used for them.
3162 * Default is 2 digits.
3163 *
3164 * Spec: ISO 4217 Currency and Funds Code List.
3165 * http://www.currency-iso.org/en/home/tables/table-a1.html
3166 */"""
3167 )
3168 println("var currencyDigits = {")
3169 for currency, entries in groupby(
3170 sorted(currencies, key=itemgetter(0)), itemgetter(0)
3171 ):
3172 for _, minorUnits, currencyName, countryName in entries:
3173 println(f" // {currencyName} ({countryName})")
3174 println(f" {currency}: {minorUnits},")
3175 println("};")
3176
3177
3178 def updateCurrency(topsrcdir, args):
3179 """Update the CurrencyDataGenerated.js file."""
3180 import xml.etree.ElementTree as ET
3181 from random import randint
3182
3183 url = args.url
3184 out = args.out
3185 filename = args.file
3186
3187 print("Arguments:")
3188 print("\tDownload url: %s" % url)
3189 print("\tLocal currency file: %s" % filename)
3190 print("\tOutput file: %s" % out)
3191 print("")
3192
3193 def updateFrom(currencyFile):
3194 print("Processing currency code list file...")
3195 tree = ET.parse(currencyFile)
3196 published = tree.getroot().attrib["Pblshd"]
3197 currencies = readCurrencyFile(tree)
3198
3199 print("Writing CurrencyData file...")
3200 writeCurrencyFile(published, currencies, out)
3201
3202 if filename is not None:
3203 print("Always make sure you have the newest currency code list file!")
3204 updateFrom(filename)
3205 else:
3206 print("Downloading currency & funds code list...")
3207 request = UrlRequest(url)
3208 request.add_header(
3209 "User-agent",
3210 "Mozilla/5.0 (Mobile; rv:{0}.0) Gecko/{0}.0 Firefox/{0}.0".format(
3211 randint(1, 999)
3212 ),
3213 )
3214 with closing(urlopen(request)) as currencyFile:
3215 fname = urlsplit(currencyFile.geturl()).path.split("/")[-1]
3216 with tempfile.NamedTemporaryFile(suffix=fname) as currencyTmpFile:
3217 print("File stored in %s" % currencyTmpFile.name)
3218 currencyTmpFile.write(currencyFile.read())
3219 currencyTmpFile.flush()
3220 updateFrom(currencyTmpFile.name)
3221
3222
3223 def writeUnicodeExtensionsMappings(println, mapping, extension):
3224 println(
3225 f"""
3226 template <size_t Length>
3227 static inline bool Is{extension}Key(mozilla::Span<const char> key, const char (&str)[Length]) {{
3228 static_assert(Length == {extension}KeyLength + 1,
3229 "{extension} extension key is two characters long");
3230 return memcmp(key.data(), str, Length - 1) == 0;
3231 }}
3232
3233 template <size_t Length>
3234 static inline bool Is{extension}Type(mozilla::Span<const char> type, const char (&str)[Length]) {{
3235 static_assert(Length > {extension}KeyLength + 1,
3236 "{extension} extension type contains more than two characters");
3237 return type.size() == (Length - 1) &&
3238 memcmp(type.data(), str, Length - 1) == 0;
3239 }}
3240 """.rstrip(
3241 "\n"
3242 )
3243 )
3244
3245 linear_search_max_length = 4
3246
3247 needs_binary_search = any(
3248 len(replacements.items()) > linear_search_max_length
3249 for replacements in mapping.values()
3250 )
3251
3252 if needs_binary_search:
3253 println(
3254 f"""
3255 static int32_t Compare{extension}Type(const char* a, mozilla::Span<const char> b) {{
3256 MOZ_ASSERT(!std::char_traits<char>::find(b.data(), b.size(), '\\0'),
3257 "unexpected null-character in string");
3258
3259 using UnsignedChar = unsigned char;
3260 for (size_t i = 0; i < b.size(); i++) {{
3261 // |a| is zero-terminated and |b| doesn't contain a null-terminator. So if
3262 // we've reached the end of |a|, the below if-statement will always be true.
3263 // That ensures we don't read past the end of |a|.
3264 if (int32_t r = UnsignedChar(a[i]) - UnsignedChar(b[i])) {{
3265 return r;
3266 }}
3267 }}
3268
3269 // Return zero if both strings are equal or a positive number if |b| is a
3270 // prefix of |a|.
3271 return int32_t(UnsignedChar(a[b.size()]));
3272 }}
3273
3274 template <size_t Length>
3275 static inline const char* Search{extension}Replacement(
3276 const char* (&types)[Length], const char* (&aliases)[Length],
3277 mozilla::Span<const char> type) {{
3278
3279 auto p = std::lower_bound(std::begin(types), std::end(types), type,
3280 [](const auto& a, const auto& b) {{
3281 return Compare{extension}Type(a, b) < 0;
3282 }});
3283 if (p != std::end(types) && Compare{extension}Type(*p, type) == 0) {{
3284 return aliases[std::distance(std::begin(types), p)];
3285 }}
3286 return nullptr;
3287 }}
3288 """.rstrip(
3289 "\n"
3290 )
3291 )
3292
3293 println(
3294 f"""
3295 /**
3296 * Mapping from deprecated BCP 47 {extension} extension types to their preferred
3297 * values.
3298 *
3299 * Spec: https://www.unicode.org/reports/tr35/#Unicode_Locale_Extension_Data_Files
3300 * Spec: https://www.unicode.org/reports/tr35/#t_Extension
3301 */
3302 const char* mozilla::intl::Locale::Replace{extension}ExtensionType(
3303 mozilla::Span<const char> key, mozilla::Span<const char> type) {{
3304 MOZ_ASSERT(key.size() == {extension}KeyLength);
3305 MOZ_ASSERT(IsCanonicallyCased{extension}Key(key));
3306
3307 MOZ_ASSERT(type.size() > {extension}KeyLength);
3308 MOZ_ASSERT(IsCanonicallyCased{extension}Type(type));
3309 """
3310 )
3311
3312 def to_hash_key(replacements):
3313 return str(sorted(replacements.items()))
3314
3315 def write_array(subtags, name, length):
3316 max_entries = (80 - len(" ")) // (length + len('"", '))
3317
3318 println(f" static const char* {name}[{len(subtags)}] = {{")
3319
3320 for entries in grouper(subtags, max_entries):
3321 entries = (
3322 f'"{tag}"'.center(length + 2) for tag in entries if tag is not None
3323 )
3324 println(" {},".format(", ".join(entries)))
3325
3326 println(" };")
3327
3328 # Merge duplicate keys.
3329 key_aliases = {}
3330 for key, replacements in sorted(mapping.items(), key=itemgetter(0)):
3331 hash_key = to_hash_key(replacements)
3332 if hash_key not in key_aliases:
3333 key_aliases[hash_key] = []
3334 else:
3335 key_aliases[hash_key].append(key)
3336
3337 first_key = True
3338 for key, replacements in sorted(mapping.items(), key=itemgetter(0)):
3339 hash_key = to_hash_key(replacements)
3340 if key in key_aliases[hash_key]:
3341 continue
3342
3343 cond = (f'Is{extension}Key(key, "{k}")' for k in [key] + key_aliases[hash_key])
3344
3345 if_kind = "if" if first_key else "else if"
3346 cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond)
3347 println(
3348 f"""
3349 {if_kind} ({cond}) {{""".strip(
3350 "\n"
3351 )
3352 )
3353 first_key = False
3354
3355 replacements = sorted(replacements.items(), key=itemgetter(0))
3356
3357 if len(replacements) > linear_search_max_length:
3358 types = [t for (t, _) in replacements]
3359 preferred = [r for (_, r) in replacements]
3360 max_len = max(len(k) for k in types + preferred)
3361
3362 write_array(types, "types", max_len)
3363 write_array(preferred, "aliases", max_len)
3364 println(
3365 f"""
3366 return Search{extension}Replacement(types, aliases, type);
3367 """.strip(
3368 "\n"
3369 )
3370 )
3371 else:
3372 for type, replacement in replacements:
3373 println(
3374 f"""
3375 if (Is{extension}Type(type, "{type}")) {{
3376 return "{replacement}";
3377 }}""".strip(
3378 "\n"
3379 )
3380 )
3381
3382 println(
3383 """
3384 }""".lstrip(
3385 "\n"
3386 )
3387 )
3388
3389 println(
3390 """
3391 return nullptr;
3392 }
3393 """.strip(
3394 "\n"
3395 )
3396 )
3397
3398
3399 def readICUUnitResourceFile(filepath):
3400 """Return a set of unit descriptor pairs where the first entry denotes the unit type and the
3401 second entry the unit name.
3402
3403 Example:
3404
3405 root{
3406 units{
3407 compound{
3408 }
3409 coordinate{
3410 }
3411 length{
3412 meter{
3413 }
3414 }
3415 }
3416 unitsNarrow:alias{"/LOCALE/unitsShort"}
3417 unitsShort{
3418 duration{
3419 day{
3420 }
3421 day-person:alias{"/LOCALE/unitsShort/duration/day"}
3422 }
3423 length{
3424 meter{
3425 }
3426 }
3427 }
3428 }
3429
3430 Returns {("length", "meter"), ("duration", "day"), ("duration", "day-person")}
3431 """
3432
3433 start_table_re = re.compile(r"^([\w\-%:\"]+)\{$")
3434 end_table_re = re.compile(r"^\}$")
3435 table_entry_re = re.compile(r"^([\w\-%:\"]+)\{\"(.*?)\"\}$")
3436
3437 # The current resource table.
3438 table = {}
3439
3440 # List of parent tables when parsing.
3441 parents = []
3442
3443 # Track multi-line comments state.
3444 in_multiline_comment = False
3445
3446 for line in flines(filepath, "utf-8-sig"):
3447 # Remove leading and trailing whitespace.
3448 line = line.strip()
3449
3450 # Skip over comments.
3451 if in_multiline_comment:
3452 if line.endswith("*/"):
3453 in_multiline_comment = False
3454 continue
3455
3456 if line.startswith("//"):
3457 continue
3458
3459 if line.startswith("/*"):
3460 in_multiline_comment = True
3461 continue
3462
3463 # Try to match the start of a table, e.g. `length{` or `meter{`.
3464 match = start_table_re.match(line)
3465 if match:
3466 parents.append(table)
3467 table_name = match.group(1)
3468 new_table = {}
3469 table[table_name] = new_table
3470 table = new_table
3471 continue
3472
3473 # Try to match the end of a table.
3474 match = end_table_re.match(line)
3475 if match:
3476 table = parents.pop()
3477 continue
3478
3479 # Try to match a table entry, e.g. `dnam{"meter"}`.
3480 match = table_entry_re.match(line)
3481 if match:
3482 entry_key = match.group(1)
3483 entry_value = match.group(2)
3484 table[entry_key] = entry_value
3485 continue
3486
3487 raise Exception(f"unexpected line: '{line}' in {filepath}")
3488
3489 assert len(parents) == 0, "Not all tables closed"
3490 assert len(table) == 1, "More than one root table"
3491
3492 # Remove the top-level language identifier table.
3493 (_, unit_table) = table.popitem()
3494
3495 # Add all units for the three display formats "units", "unitsNarrow", and "unitsShort".
3496 # But exclude the pseudo-units "compound" and "ccoordinate".
3497 return {
3498 (unit_type, unit_name if not unit_name.endswith(":alias") else unit_name[:-6])
3499 for unit_display in ("units", "unitsNarrow", "unitsShort")
3500 if unit_display in unit_table
3501 for (unit_type, unit_names) in unit_table[unit_display].items()
3502 if unit_type != "compound" and unit_type != "coordinate"
3503 for unit_name in unit_names.keys()
3504 }
3505
3506
3507 def computeSupportedUnits(all_units, sanctioned_units):
3508 """Given the set of all possible ICU unit identifiers and the set of sanctioned unit
3509 identifiers, compute the set of effectively supported ICU unit identifiers.
3510 """
3511
3512 def find_match(unit):
3513 unit_match = [
3514 (unit_type, unit_name)
3515 for (unit_type, unit_name) in all_units
3516 if unit_name == unit
3517 ]
3518 if unit_match:
3519 assert len(unit_match) == 1
3520 return unit_match[0]
3521 return None
3522
3523 def compound_unit_identifiers():
3524 for numerator in sanctioned_units:
3525 for denominator in sanctioned_units:
3526 yield f"{numerator}-per-{denominator}"
3527
3528 supported_simple_units = {find_match(unit) for unit in sanctioned_units}
3529 assert None not in supported_simple_units
3530
3531 supported_compound_units = {
3532 unit_match
3533 for unit_match in (find_match(unit) for unit in compound_unit_identifiers())
3534 if unit_match
3535 }
3536
3537 return supported_simple_units | supported_compound_units
3538
3539
3540 def readICUDataFilterForUnits(data_filter_file):
3541 with open(data_filter_file, encoding="utf-8") as f:
3542 data_filter = json.load(f)
3543
3544 # Find the rule set for the "unit_tree".
3545 unit_tree_rules = [
3546 entry["rules"]
3547 for entry in data_filter["resourceFilters"]
3548 if entry["categories"] == ["unit_tree"]
3549 ]
3550 assert len(unit_tree_rules) == 1
3551
3552 # Compute the list of included units from that rule set. The regular expression must match
3553 # "+/*/length/meter" and mustn't match either "-/*" or "+/*/compound".
3554 included_unit_re = re.compile(r"^\+/\*/(.+?)/(.+)$")
3555 filtered_units = (included_unit_re.match(unit) for unit in unit_tree_rules[0])
3556
3557 return {(unit.group(1), unit.group(2)) for unit in filtered_units if unit}
3558
3559
3560 def writeSanctionedSimpleUnitIdentifiersFiles(all_units, sanctioned_units):
3561 js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
3562 intl_components_src_dir = os.path.join(
3563 js_src_builtin_intl_dir, "../../../../intl/components/src"
3564 )
3565
3566 def find_unit_type(unit):
3567 result = [
3568 unit_type for (unit_type, unit_name) in all_units if unit_name == unit
3569 ]
3570 assert result and len(result) == 1
3571 return result[0]
3572
3573 sanctioned_js_file = os.path.join(
3574 js_src_builtin_intl_dir, "SanctionedSimpleUnitIdentifiersGenerated.js"
3575 )
3576 with open(sanctioned_js_file, mode="w", encoding="utf-8", newline="") as f:
3577 println = partial(print, file=f)
3578
3579 sanctioned_units_object = json.dumps(
3580 {unit: True for unit in sorted(sanctioned_units)},
3581 sort_keys=True,
3582 indent=2,
3583 separators=(",", ": "),
3584 )
3585
3586 println(generatedFileWarning)
3587
3588 println(
3589 """
3590 /**
3591 * The list of currently supported simple unit identifiers.
3592 *
3593 * Intl.NumberFormat Unified API Proposal
3594 */"""
3595 )
3596
3597 println("// prettier-ignore")
3598 println(f"var sanctionedSimpleUnitIdentifiers = {sanctioned_units_object};")
3599
3600 sanctioned_h_file = os.path.join(intl_components_src_dir, "MeasureUnitGenerated.h")
3601 with open(sanctioned_h_file, mode="w", encoding="utf-8", newline="") as f:
3602 println = partial(print, file=f)
3603
3604 println(generatedFileWarning)
3605
3606 println(
3607 """
3608 #ifndef intl_components_MeasureUnitGenerated_h
3609 #define intl_components_MeasureUnitGenerated_h
3610
3611 namespace mozilla::intl {
3612
3613 struct SimpleMeasureUnit {
3614 const char* const type;
3615 const char* const name;
3616 };
3617
3618 /**
3619 * The list of currently supported simple unit identifiers.
3620 *
3621 * The list must be kept in alphabetical order of |name|.
3622 */
3623 inline constexpr SimpleMeasureUnit simpleMeasureUnits[] = {
3624 // clang-format off"""
3625 )
3626
3627 for unit_name in sorted(sanctioned_units):
3628 println(f' {{"{find_unit_type(unit_name)}", "{unit_name}"}},')
3629
3630 println(
3631 """
3632 // clang-format on
3633 };
3634
3635 } // namespace mozilla::intl
3636
3637 #endif
3638 """.strip(
3639 "\n"
3640 )
3641 )
3642
3643 writeUnitTestFiles(all_units, sanctioned_units)
3644
3645
3646 def writeUnitTestFiles(all_units, sanctioned_units):
3647 """Generate test files for unit number formatters."""
3648
3649 js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
3650 test_dir = os.path.join(
3651 js_src_builtin_intl_dir, "../../tests/non262/Intl/NumberFormat"
3652 )
3653
3654 def write_test(file_name, test_content, indent=4):
3655 file_path = os.path.join(test_dir, file_name)
3656 with open(file_path, mode="w", encoding="utf-8", newline="") as f:
3657 println = partial(print, file=f)
3658
3659 println('// |reftest| skip-if(!this.hasOwnProperty("Intl"))')
3660 println("")
3661 println(generatedFileWarning)
3662 println("")
3663
3664 sanctioned_units_array = json.dumps(
3665 [unit for unit in sorted(sanctioned_units)],
3666 indent=indent,
3667 separators=(",", ": "),
3668 )
3669
3670 println(
3671 f"const sanctionedSimpleUnitIdentifiers = {sanctioned_units_array};"
3672 )
3673
3674 println(test_content)
3675
3676 println(
3677 """
3678 if (typeof reportCompare === "function")
3679 {}reportCompare(true, true);""".format(
3680 " " * indent
3681 )
3682 )
3683
3684 write_test(
3685 "unit-compound-combinations.js",
3686 """
3687 // Test all simple unit identifier combinations are allowed.
3688
3689 for (const numerator of sanctionedSimpleUnitIdentifiers) {
3690 for (const denominator of sanctionedSimpleUnitIdentifiers) {
3691 const unit = `${numerator}-per-${denominator}`;
3692 const nf = new Intl.NumberFormat("en", {style: "unit", unit});
3693
3694 assertEq(nf.format(1), nf.formatToParts(1).map(p => p.value).join(""));
3695 }
3696 }""",
3697 )
3698
3699 all_units_array = json.dumps(
3700 ["-".join(unit) for unit in sorted(all_units)], indent=4, separators=(",", ": ")
3701 )
3702
3703 write_test(
3704 "unit-well-formed.js",
3705 f"""
3706 const allUnits = {all_units_array};
3707 """
3708 + r"""
3709 // Test only sanctioned unit identifiers are allowed.
3710
3711 for (const typeAndUnit of allUnits) {
3712 const [_, type, unit] = typeAndUnit.match(/(\w+)-(.+)/);
3713
3714 let allowed;
3715 if (unit.includes("-per-")) {
3716 const [numerator, denominator] = unit.split("-per-");
3717 allowed = sanctionedSimpleUnitIdentifiers.includes(numerator) &&
3718 sanctionedSimpleUnitIdentifiers.includes(denominator);
3719 } else {
3720 allowed = sanctionedSimpleUnitIdentifiers.includes(unit);
3721 }
3722
3723 if (allowed) {
3724 const nf = new Intl.NumberFormat("en", {style: "unit", unit});
3725 assertEq(nf.format(1), nf.formatToParts(1).map(p => p.value).join(""));
3726 } else {
3727 assertThrowsInstanceOf(() => new Intl.NumberFormat("en", {style: "unit", unit}),
3728 RangeError, `Missing error for "${typeAndUnit}"`);
3729 }
3730 }""",
3731 )
3732
3733 write_test(
3734 "unit-formatToParts-has-unit-field.js",
3735 """
3736 // Test only English and Chinese to keep the overall runtime reasonable.
3737 //
3738 // Chinese is included because it contains more than one "unit" element for
3739 // certain unit combinations.
3740 const locales = ["en", "zh"];
3741
3742 // Plural rules for English only differentiate between "one" and "other". Plural
3743 // rules for Chinese only use "other". That means we only need to test two values
3744 // per unit.
3745 const values = [0, 1];
3746
3747 // Ensure unit formatters contain at least one "unit" element.
3748
3749 for (const locale of locales) {
3750 for (const unit of sanctionedSimpleUnitIdentifiers) {
3751 const nf = new Intl.NumberFormat(locale, {style: "unit", unit});
3752
3753 for (const value of values) {
3754 assertEq(nf.formatToParts(value).some(e => e.type === "unit"), true,
3755 `locale=${locale}, unit=${unit}`);
3756 }
3757 }
3758
3759 for (const numerator of sanctionedSimpleUnitIdentifiers) {
3760 for (const denominator of sanctionedSimpleUnitIdentifiers) {
3761 const unit = `${numerator}-per-${denominator}`;
3762 const nf = new Intl.NumberFormat(locale, {style: "unit", unit});
3763
3764 for (const value of values) {
3765 assertEq(nf.formatToParts(value).some(e => e.type === "unit"), true,
3766 `locale=${locale}, unit=${unit}`);
3767 }
3768 }
3769 }
3770 }""",
3771 indent=2,
3772 )
3773
3774
3775 def updateUnits(topsrcdir, args):
3776 js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
3777 icu_path = os.path.join(topsrcdir, "intl", "icu")
3778 icu_unit_path = os.path.join(icu_path, "source", "data", "unit")
3779
3780 with open(
3781 os.path.join(js_src_builtin_intl_dir, "SanctionedSimpleUnitIdentifiers.yaml"),
3782 encoding="utf-8",
3783 ) as f:
3784 sanctioned_units = yaml.safe_load(f)
3785
3786 # Read all possible ICU unit identifiers from the "unit/root.txt" resource.
3787 unit_root_file = os.path.join(icu_unit_path, "root.txt")
3788 all_units = readICUUnitResourceFile(unit_root_file)
3789
3790 # Compute the set of effectively supported ICU unit identifiers.
3791 supported_units = computeSupportedUnits(all_units, sanctioned_units)
3792
3793 # Read the list of units we're including into the ICU data file.
3794 data_filter_file = os.path.join(icu_path, "data_filter.json")
3795 filtered_units = readICUDataFilterForUnits(data_filter_file)
3796
3797 # Both sets must match to avoid resource loading errors at runtime.
3798 if supported_units != filtered_units:
3799
3800 def units_to_string(units):
3801 return ", ".join("/".join(u) for u in units)
3802
3803 missing = supported_units - filtered_units
3804 if missing:
3805 raise RuntimeError(f"Missing units: {units_to_string(missing)}")
3806
3807 # Not exactly an error, but we currently don't have a use case where we need to support
3808 # more units than required by ECMA-402.
3809 extra = filtered_units - supported_units
3810 if extra:
3811 raise RuntimeError(f"Unnecessary units: {units_to_string(extra)}")
3812
3813 writeSanctionedSimpleUnitIdentifiersFiles(all_units, sanctioned_units)
3814
3815
3816 def readICUNumberingSystemsResourceFile(filepath):
3817 """Returns a dictionary of numbering systems where the key denotes the numbering system name
3818 and the value a dictionary with additional numbering system data.
3819
3820 Example:
3821
3822 numberingSystems:table(nofallback){
3823 numberingSystems{
3824 latn{
3825 algorithmic:int{0}
3826 desc{"0123456789"}
3827 radix:int{10}
3828 }
3829 roman{
3830 algorithmic:int{1}
3831 desc{"%roman-upper"}
3832 radix:int{10}
3833 }
3834 }
3835 }
3836
3837 Returns {"latn": {"digits": "0123456789", "algorithmic": False},
3838 "roman": {"algorithmic": True}}
3839 """
3840
3841 start_table_re = re.compile(r"^(\w+)(?:\:[\w\(\)]+)?\{$")
3842 end_table_re = re.compile(r"^\}$")
3843 table_entry_re = re.compile(r"^(\w+)(?:\:[\w\(\)]+)?\{(?:(?:\"(.*?)\")|(\d+))\}$")
3844
3845 # The current resource table.
3846 table = {}
3847
3848 # List of parent tables when parsing.
3849 parents = []
3850
3851 # Track multi-line comments state.
3852 in_multiline_comment = False
3853
3854 for line in flines(filepath, "utf-8-sig"):
3855 # Remove leading and trailing whitespace.
3856 line = line.strip()
3857
3858 # Skip over comments.
3859 if in_multiline_comment:
3860 if line.endswith("*/"):
3861 in_multiline_comment = False
3862 continue
3863
3864 if line.startswith("//"):
3865 continue
3866
3867 if line.startswith("/*"):
3868 in_multiline_comment = True
3869 continue
3870
3871 # Try to match the start of a table, e.g. `latn{`.
3872 match = start_table_re.match(line)
3873 if match:
3874 parents.append(table)
3875 table_name = match.group(1)
3876 new_table = {}
3877 table[table_name] = new_table
3878 table = new_table
3879 continue
3880
3881 # Try to match the end of a table.
3882 match = end_table_re.match(line)
3883 if match:
3884 table = parents.pop()
3885 continue
3886
3887 # Try to match a table entry, e.g. `desc{"0123456789"}`.
3888 match = table_entry_re.match(line)
3889 if match:
3890 entry_key = match.group(1)
3891 entry_value = (
3892 match.group(2) if match.group(2) is not None else int(match.group(3))
3893 )
3894 table[entry_key] = entry_value
3895 continue
3896
3897 raise Exception(f"unexpected line: '{line}' in {filepath}")
3898
3899 assert len(parents) == 0, "Not all tables closed"
3900 assert len(table) == 1, "More than one root table"
3901
3902 # Remove the two top-level "numberingSystems" tables.
3903 (_, numbering_systems) = table.popitem()
3904 (_, numbering_systems) = numbering_systems.popitem()
3905
3906 # Assert all numbering systems use base 10.
3907 assert all(ns["radix"] == 10 for ns in numbering_systems.values())
3908
3909 # Return the numbering systems.
3910 return {
3911 key: (
3912 {"digits": value["desc"], "algorithmic": False}
3913 if not bool(value["algorithmic"])
3914 else {"algorithmic": True}
3915 )
3916 for (key, value) in numbering_systems.items()
3917 }
3918
3919
3920 def writeNumberingSystemFiles(numbering_systems):
3921 js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
3922
3923 numbering_systems_js_file = os.path.join(
3924 js_src_builtin_intl_dir, "NumberingSystemsGenerated.h"
3925 )
3926 with open(numbering_systems_js_file, mode="w", encoding="utf-8", newline="") as f:
3927 println = partial(print, file=f)
3928
3929 println(generatedFileWarning)
3930
3931 println(
3932 """
3933 /**
3934 * The list of numbering systems with simple digit mappings.
3935 */
3936
3937 #ifndef builtin_intl_NumberingSystemsGenerated_h
3938 #define builtin_intl_NumberingSystemsGenerated_h
3939 """
3940 )
3941
3942 simple_numbering_systems = sorted(
3943 name
3944 for (name, value) in numbering_systems.items()
3945 if not value["algorithmic"]
3946 )
3947
3948 println("// clang-format off")
3949 println("#define NUMBERING_SYSTEMS_WITH_SIMPLE_DIGIT_MAPPINGS \\")
3950 println(
3951 "{}".format(
3952 ", \\\n".join(f' "{name}"' for name in simple_numbering_systems)
3953 )
3954 )
3955 println("// clang-format on")
3956 println("")
3957
3958 println("#endif // builtin_intl_NumberingSystemsGenerated_h")
3959
3960 js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
3961 test_dir = os.path.join(js_src_builtin_intl_dir, "../../tests/non262/Intl")
3962
3963 intl_shell_js_file = os.path.join(test_dir, "shell.js")
3964
3965 with open(intl_shell_js_file, mode="w", encoding="utf-8", newline="") as f:
3966 println = partial(print, file=f)
3967
3968 println(generatedFileWarning)
3969
3970 println(
3971 f"""
3972 // source: CLDR file common/bcp47/number.xml; version CLDR {readCLDRVersionFromICU()}.
3973 // https://github.com/unicode-org/cldr/blob/master/common/bcp47/number.xml
3974 // https://github.com/unicode-org/cldr/blob/master/common/supplemental/numberingSystems.xml
3975 """.rstrip()
3976 )
3977
3978 numbering_systems_object = json.dumps(
3979 numbering_systems,
3980 indent=2,
3981 separators=(",", ": "),
3982 sort_keys=True,
3983 ensure_ascii=False,
3984 )
3985 println(f"const numberingSystems = {numbering_systems_object};")
3986
3987
3988 def updateNumberingSystems(topsrcdir, args):
3989 js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
3990 icu_path = os.path.join(topsrcdir, "intl", "icu")
3991 icu_misc_path = os.path.join(icu_path, "source", "data", "misc")
3992
3993 with open(
3994 os.path.join(js_src_builtin_intl_dir, "NumberingSystems.yaml"),
3995 encoding="utf-8",
3996 ) as f:
3997 numbering_systems = yaml.safe_load(f)
3998
3999 # Read all possible ICU unit identifiers from the "misc/numberingSystems.txt" resource.
4000 misc_ns_file = os.path.join(icu_misc_path, "numberingSystems.txt")
4001 all_numbering_systems = readICUNumberingSystemsResourceFile(misc_ns_file)
4002
4003 all_numbering_systems_simple_digits = {
4004 name
4005 for (name, value) in all_numbering_systems.items()
4006 if not value["algorithmic"]
4007 }
4008
4009 # Assert ICU includes support for all required numbering systems. If this assertion fails,
4010 # something is broken in ICU.
4011 assert all_numbering_systems_simple_digits.issuperset(
4012 numbering_systems
4013 ), f"{numbering_systems.difference(all_numbering_systems_simple_digits)}"
4014
4015 # Assert the spec requires support for all numbering systems with simple digit mappings. If
4016 # this assertion fails, file a PR at <https://github.com/tc39/ecma402> to include any new
4017 # numbering systems.
4018 assert all_numbering_systems_simple_digits.issubset(
4019 numbering_systems
4020 ), f"{all_numbering_systems_simple_digits.difference(numbering_systems)}"
4021
4022 writeNumberingSystemFiles(all_numbering_systems)
4023
4024
4025 if __name__ == "__main__":
4026 import argparse
4027
4028 # This script must reside in js/src/builtin/intl to work correctly.
4029 (thisDir, thisFile) = os.path.split(os.path.abspath(__file__))
4030 dirPaths = os.path.normpath(thisDir).split(os.sep)
4031 if "/".join(dirPaths[-4:]) != "js/src/builtin/intl":
4032 raise RuntimeError("%s must reside in js/src/builtin/intl" % __file__)
4033 topsrcdir = "/".join(dirPaths[:-4])
4034
4035 def EnsureHttps(v):
4036 if not v.startswith("https:"):
4037 raise argparse.ArgumentTypeError("URL protocol must be https: " % v)
4038 return v
4039
4040 parser = argparse.ArgumentParser(description="Update intl data.")
4041 subparsers = parser.add_subparsers(help="Select update mode")
4042
4043 parser_cldr_tags = subparsers.add_parser(
4044 "langtags", help="Update CLDR language tags data"
4045 )
4046 parser_cldr_tags.add_argument(
4047 "--version", metavar="VERSION", help="CLDR version number"
4048 )
4049 parser_cldr_tags.add_argument(
4050 "--url",
4051 metavar="URL",
4052 default="https://unicode.org/Public/cldr/<VERSION>/cldr-common-<VERSION>.zip",
4053 type=EnsureHttps,
4054 help="Download url CLDR data (default: %(default)s)",
4055 )
4056 parser_cldr_tags.add_argument(
4057 "--out",
4058 default=os.path.join(
4059 topsrcdir, "intl", "components", "src", "LocaleGenerated.cpp"
4060 ),
4061 help="Output file (default: %(default)s)",
4062 )
4063 parser_cldr_tags.add_argument(
4064 "file", nargs="?", help="Local cldr-common.zip file, if omitted uses <URL>"
4065 )
4066 parser_cldr_tags.set_defaults(func=updateCLDRLangTags)
4067
4068 parser_tz = subparsers.add_parser("tzdata", help="Update tzdata")
4069 parser_tz.add_argument(
4070 "--tz",
4071 help="Local tzdata directory or file, if omitted downloads tzdata "
4072 "distribution from https://www.iana.org/time-zones/",
4073 )
4074 parser_tz.add_argument(
4075 "--out",
4076 default=os.path.join(thisDir, "TimeZoneDataGenerated.h"),
4077 help="Output file (default: %(default)s)",
4078 )
4079 parser_tz.set_defaults(func=partial(updateTzdata, topsrcdir))
4080
4081 parser_currency = subparsers.add_parser(
4082 "currency", help="Update currency digits mapping"
4083 )
4084 parser_currency.add_argument(
4085 "--url",
4086 metavar="URL",
4087 default="https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml", # NOQA: E501
4088 type=EnsureHttps,
4089 help="Download url for the currency & funds code list (default: "
4090 "%(default)s)",
4091 )
4092 parser_currency.add_argument(
4093 "--out",
4094 default=os.path.join(thisDir, "CurrencyDataGenerated.js"),
4095 help="Output file (default: %(default)s)",
4096 )
4097 parser_currency.add_argument(
4098 "file", nargs="?", help="Local currency code list file, if omitted uses <URL>"
4099 )
4100 parser_currency.set_defaults(func=partial(updateCurrency, topsrcdir))
4101
4102 parser_units = subparsers.add_parser(
4103 "units", help="Update sanctioned unit identifiers mapping"
4104 )
4105 parser_units.set_defaults(func=partial(updateUnits, topsrcdir))
4106
4107 parser_numbering_systems = subparsers.add_parser(
4108 "numbering", help="Update numbering systems with simple digit mappings"
4109 )
4110 parser_numbering_systems.set_defaults(
4111 func=partial(updateNumberingSystems, topsrcdir)
4112 )
4113
4114 args = parser.parse_args()
4115 args.func(args)