summaryrefslogtreecommitdiffstats
path: root/js/src/builtin/intl/make_intl_data.py
blob: 1f9d7ff30e472eca24dce88d4ac2ad30b4a7aebe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

""" Usage:
    make_intl_data.py langtags [cldr_core.zip]
    make_intl_data.py tzdata
    make_intl_data.py currency
    make_intl_data.py units
    make_intl_data.py numbering


    Target "langtags":
    This script extracts information about 1) mappings between deprecated and
    current Unicode BCP 47 locale identifiers, and 2) deprecated and current
    BCP 47 Unicode extension value from CLDR, and converts it to C++ mapping
    code in intl/components/LocaleGenerated.cpp. The code is used in
    intl/components/Locale.cpp.


    Target "tzdata":
    This script computes which time zone informations are not up-to-date in ICU
    and provides the necessary mappings to workaround this problem.
    https://ssl.icu-project.org/trac/ticket/12044


    Target "currency":
    Generates the mapping from currency codes to decimal digits used for them.


    Target "units":
    Generate source and test files using the list of so-called "sanctioned unit
    identifiers" and verifies that the ICU data filter includes these units.


    Target "numbering":
    Generate source and test files using the list of numbering systems with
    simple digit mappings and verifies that it's in sync with ICU/CLDR.
"""

import io
import json
import os
import re
import sys
import tarfile
import tempfile
from contextlib import closing
from functools import partial, total_ordering
from itertools import chain, groupby, tee
from operator import attrgetter, itemgetter
from zipfile import ZipFile

import yaml

if sys.version_info.major == 2:
    from itertools import ifilter as filter
    from itertools import ifilterfalse as filterfalse
    from itertools import imap as map
    from itertools import izip_longest as zip_longest

    from urllib2 import Request as UrlRequest
    from urllib2 import urlopen
    from urlparse import urlsplit
else:
    from itertools import filterfalse, zip_longest
    from urllib.parse import urlsplit
    from urllib.request import Request as UrlRequest
    from urllib.request import urlopen


# From https://docs.python.org/3/library/itertools.html
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)


def writeMappingHeader(println, description, source, url):
    if type(description) is not list:
        description = [description]
    for desc in description:
        println("// {0}".format(desc))
    println("// Derived from {0}.".format(source))
    println("// {0}".format(url))


def writeMappingsVar(println, mapping, name, description, source, url):
    """Writes a variable definition with a mapping table.

    Writes the contents of dictionary |mapping| through the |println|
    function with the given variable name and a comment with description,
    fileDate, and URL.
    """
    println("")
    writeMappingHeader(println, description, source, url)
    println("var {0} = {{".format(name))
    for (key, value) in sorted(mapping.items(), key=itemgetter(0)):
        println('    "{0}": "{1}",'.format(key, value))
    println("};")


def writeMappingsBinarySearch(
    println,
    fn_name,
    type_name,
    name,
    validate_fn,
    validate_case_fn,
    mappings,
    tag_maxlength,
    description,
    source,
    url,
):
    """Emit code to perform a binary search on language tag subtags.

    Uses the contents of |mapping|, which can either be a dictionary or set,
    to emit a mapping function to find subtag replacements.
    """
    println("")
    writeMappingHeader(println, description, source, url)
    println(
        """
bool mozilla::intl::Locale::{0}({1} {2}) {{
  MOZ_ASSERT({3}({2}.Span()));
  MOZ_ASSERT({4}({2}.Span()));
""".format(
            fn_name, type_name, name, validate_fn, validate_case_fn
        ).strip()
    )
    writeMappingsBinarySearchBody(println, name, name, mappings, tag_maxlength)

    println(
        """
}""".lstrip(
            "\n"
        )
    )


def writeMappingsBinarySearchBody(
    println, source_name, target_name, mappings, tag_maxlength
):
    def write_array(subtags, name, length, fixed):
        if fixed:
            println(
                "    static const char {}[{}][{}] = {{".format(
                    name, len(subtags), length + 1
                )
            )
        else:
            println("    static const char* {}[{}] = {{".format(name, len(subtags)))

        # Group in pairs of ten to not exceed the 80 line column limit.
        for entries in grouper(subtags, 10):
            entries = (
                '"{}"'.format(tag).rjust(length + 2)
                for tag in entries
                if tag is not None
            )
            println("      {},".format(", ".join(entries)))

        println("    };")

    trailing_return = True

    # Sort the subtags by length. That enables using an optimized comparator
    # for the binary search, which only performs a single |memcmp| for multiple
    # of two subtag lengths.
    mappings_keys = mappings.keys() if type(mappings) == dict else mappings
    for (length, subtags) in groupby(sorted(mappings_keys, key=len), len):
        # Omit the length check if the current length is the maximum length.
        if length != tag_maxlength:
            println(
                """
  if ({}.Length() == {}) {{
""".format(
                    source_name, length
                ).rstrip(
                    "\n"
                )
            )
        else:
            trailing_return = False
            println(
                """
  {
""".rstrip(
                    "\n"
                )
            )

        # The subtags need to be sorted for binary search to work.
        subtags = sorted(subtags)

        def equals(subtag):
            return """{}.EqualTo("{}")""".format(source_name, subtag)

        # Don't emit a binary search for short lists.
        if len(subtags) == 1:
            if type(mappings) == dict:
                println(
                    """
    if ({}) {{
      {}.Set(mozilla::MakeStringSpan("{}"));
      return true;
    }}
    return false;
""".format(
                        equals(subtags[0]), target_name, mappings[subtags[0]]
                    ).strip(
                        "\n"
                    )
                )
            else:
                println(
                    """
    return {};
""".format(
                        equals(subtags[0])
                    ).strip(
                        "\n"
                    )
                )
        elif len(subtags) <= 4:
            if type(mappings) == dict:
                for subtag in subtags:
                    println(
                        """
    if ({}) {{
      {}.Set("{}");
      return true;
    }}
""".format(
                            equals(subtag), target_name, mappings[subtag]
                        ).strip(
                            "\n"
                        )
                    )

                println(
                    """
    return false;
""".strip(
                        "\n"
                    )
                )
            else:
                cond = (equals(subtag) for subtag in subtags)
                cond = (" ||\n" + " " * (4 + len("return "))).join(cond)
                println(
                    """
    return {};
""".format(
                        cond
                    ).strip(
                        "\n"
                    )
                )
        else:
            write_array(subtags, source_name + "s", length, True)

            if type(mappings) == dict:
                write_array([mappings[k] for k in subtags], "aliases", length, False)

                println(
                    """
    if (const char* replacement = SearchReplacement({0}s, aliases, {0})) {{
      {1}.Set(mozilla::MakeStringSpan(replacement));
      return true;
    }}
    return false;
""".format(
                        source_name, target_name
                    ).rstrip()
                )
            else:
                println(
                    """
    return HasReplacement({0}s, {0});
""".format(
                        source_name
                    ).rstrip()
                )

        println(
            """
  }
""".strip(
                "\n"
            )
        )

    if trailing_return:
        println(
            """
  return false;"""
        )


def writeComplexLanguageTagMappings(
    println, complex_language_mappings, description, source, url
):
    println("")
    writeMappingHeader(println, description, source, url)
    println(
        """
void mozilla::intl::Locale::PerformComplexLanguageMappings() {
  MOZ_ASSERT(IsStructurallyValidLanguageTag(Language().Span()));
  MOZ_ASSERT(IsCanonicallyCasedLanguageTag(Language().Span()));
""".lstrip()
    )

    # Merge duplicate language entries.
    language_aliases = {}
    for (deprecated_language, (language, script, region)) in sorted(
        complex_language_mappings.items(), key=itemgetter(0)
    ):
        key = (language, script, region)
        if key not in language_aliases:
            language_aliases[key] = []
        else:
            language_aliases[key].append(deprecated_language)

    first_language = True
    for (deprecated_language, (language, script, region)) in sorted(
        complex_language_mappings.items(), key=itemgetter(0)
    ):
        key = (language, script, region)
        if deprecated_language in language_aliases[key]:
            continue

        if_kind = "if" if first_language else "else if"
        first_language = False

        cond = (
            'Language().EqualTo("{}")'.format(lang)
            for lang in [deprecated_language] + language_aliases[key]
        )
        cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond)

        println(
            """
  {} ({}) {{""".format(
                if_kind, cond
            ).strip(
                "\n"
            )
        )

        println(
            """
    SetLanguage("{}");""".format(
                language
            ).strip(
                "\n"
            )
        )

        if script is not None:
            println(
                """
    if (Script().Missing()) {{
      SetScript("{}");
    }}""".format(
                    script
                ).strip(
                    "\n"
                )
            )
        if region is not None:
            println(
                """
    if (Region().Missing()) {{
      SetRegion("{}");
    }}""".format(
                    region
                ).strip(
                    "\n"
                )
            )
        println(
            """
  }""".strip(
                "\n"
            )
        )

    println(
        """
}
""".strip(
            "\n"
        )
    )


def writeComplexRegionTagMappings(
    println, complex_region_mappings, description, source, url
):
    println("")
    writeMappingHeader(println, description, source, url)
    println(
        """
void mozilla::intl::Locale::PerformComplexRegionMappings() {
  MOZ_ASSERT(IsStructurallyValidLanguageTag(Language().Span()));
  MOZ_ASSERT(IsCanonicallyCasedLanguageTag(Language().Span()));
  MOZ_ASSERT(IsStructurallyValidRegionTag(Region().Span()));
  MOZ_ASSERT(IsCanonicallyCasedRegionTag(Region().Span()));
""".lstrip()
    )

    # |non_default_replacements| is a list and hence not hashable. Convert it
    # to a string to get a proper hashable value.
    def hash_key(default, non_default_replacements):
        return (default, str(sorted(str(v) for v in non_default_replacements)))

    # Merge duplicate region entries.
    region_aliases = {}
    for (deprecated_region, (default, non_default_replacements)) in sorted(
        complex_region_mappings.items(), key=itemgetter(0)
    ):
        key = hash_key(default, non_default_replacements)
        if key not in region_aliases:
            region_aliases[key] = []
        else:
            region_aliases[key].append(deprecated_region)

    first_region = True
    for (deprecated_region, (default, non_default_replacements)) in sorted(
        complex_region_mappings.items(), key=itemgetter(0)
    ):
        key = hash_key(default, non_default_replacements)
        if deprecated_region in region_aliases[key]:
            continue

        if_kind = "if" if first_region else "else if"
        first_region = False

        cond = (
            'Region().EqualTo("{}")'.format(region)
            for region in [deprecated_region] + region_aliases[key]
        )
        cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond)

        println(
            """
  {} ({}) {{""".format(
                if_kind, cond
            ).strip(
                "\n"
            )
        )

        replacement_regions = sorted(
            {region for (_, _, region) in non_default_replacements}
        )

        first_case = True
        for replacement_region in replacement_regions:
            replacement_language_script = sorted(
                (language, script)
                for (language, script, region) in (non_default_replacements)
                if region == replacement_region
            )

            if_kind = "if" if first_case else "else if"
            first_case = False

            def compare_tags(language, script):
                if script is None:
                    return 'Language().EqualTo("{}")'.format(language)
                return '(Language().EqualTo("{}") && Script().EqualTo("{}"))'.format(
                    language, script
                )

            cond = (
                compare_tags(language, script)
                for (language, script) in replacement_language_script
            )
            cond = (" ||\n" + " " * (4 + len(if_kind) + 2)).join(cond)

            println(
                """
    {} ({}) {{
      SetRegion("{}");
    }}""".format(
                    if_kind, cond, replacement_region
                )
                .rstrip()
                .strip("\n")
            )

        println(
            """
    else {{
      SetRegion("{}");
    }}
  }}""".format(
                default
            )
            .rstrip()
            .strip("\n")
        )

    println(
        """
}
""".strip(
            "\n"
        )
    )


def writeVariantTagMappings(println, variant_mappings, description, source, url):
    """Writes a function definition that maps variant subtags."""
    println(
        """
static const char* ToCharPointer(const char* str) {
  return str;
}

static const char* ToCharPointer(const mozilla::intl::UniqueChars& str) {
  return str.get();
}

template <typename T, typename U = T>
static bool IsLessThan(const T& a, const U& b) {
  return strcmp(ToCharPointer(a), ToCharPointer(b)) < 0;
}
"""
    )
    writeMappingHeader(println, description, source, url)
    println(
        """
bool mozilla::intl::Locale::PerformVariantMappings() {
  // The variant subtags need to be sorted for binary search.
  MOZ_ASSERT(std::is_sorted(mVariants.begin(), mVariants.end(),
                            IsLessThan<decltype(mVariants)::ElementType>));

  auto removeVariantAt = [&](size_t index) {
    mVariants.erase(mVariants.begin() + index);
  };

  auto insertVariantSortedIfNotPresent = [&](const char* variant) {
    auto* p = std::lower_bound(
        mVariants.begin(), mVariants.end(), variant,
        IsLessThan<decltype(mVariants)::ElementType, decltype(variant)>);

    // Don't insert the replacement when already present.
    if (p != mVariants.end() && strcmp(p->get(), variant) == 0) {
      return true;
    }

    // Insert the preferred variant in sort order.
    auto preferred = DuplicateStringToUniqueChars(variant);
    return !!mVariants.insert(p, std::move(preferred));
  };

  for (size_t i = 0; i < mVariants.length();) {
    const char* variant = mVariants[i].get();
    MOZ_ASSERT(IsCanonicallyCasedVariantTag(mozilla::MakeStringSpan(variant)));
""".lstrip()
    )

    (no_alias, with_alias) = partition(
        variant_mappings.items(), lambda item: item[1] is None
    )

    no_replacements = " ||\n        ".join(
        f"""strcmp(variant, "{deprecated_variant}") == 0"""
        for (deprecated_variant, _) in sorted(no_alias, key=itemgetter(0))
    )

    println(
        f"""
    if ({no_replacements}) {{
      removeVariantAt(i);
    }}
""".strip(
            "\n"
        )
    )

    for (deprecated_variant, (type, replacement)) in sorted(
        with_alias, key=itemgetter(0)
    ):
        println(
            f"""
    else if (strcmp(variant, "{deprecated_variant}") == 0) {{
      removeVariantAt(i);
""".strip(
                "\n"
            )
        )

        if type == "language":
            println(
                f"""
      SetLanguage("{replacement}");
""".strip(
                    "\n"
                )
            )
        elif type == "region":
            println(
                f"""
      SetRegion("{replacement}");
""".strip(
                    "\n"
                )
            )
        else:
            assert type == "variant"
            println(
                f"""
      if (!insertVariantSortedIfNotPresent("{replacement}")) {{
        return false;
      }}
""".strip(
                    "\n"
                )
            )

        println(
            """
    }
""".strip(
                "\n"
            )
        )

    println(
        """
    else {
      i++;
    }
  }
  return true;
}
""".strip(
            "\n"
        )
    )


def writeLegacyMappingsFunction(println, legacy_mappings, description, source, url):
    """Writes a function definition that maps legacy language tags."""
    println("")
    writeMappingHeader(println, description, source, url)
    println(
        """\
bool mozilla::intl::Locale::UpdateLegacyMappings() {
  // We're mapping legacy tags to non-legacy form here.
  // Other tags remain unchanged.
  //
  // Legacy tags are either sign language tags ("sgn") or have one or multiple
  // variant subtags. Therefore we can quickly exclude most tags by checking
  // these two subtags.

  MOZ_ASSERT(IsCanonicallyCasedLanguageTag(Language().Span()));

  if (!Language().EqualTo("sgn") && mVariants.length() == 0) {
    return true;
  }

#ifdef DEBUG
  for (const auto& variant : Variants()) {
    MOZ_ASSERT(IsStructurallyValidVariantTag(variant));
    MOZ_ASSERT(IsCanonicallyCasedVariantTag(variant));
  }
#endif

  // The variant subtags need to be sorted for binary search.
  MOZ_ASSERT(std::is_sorted(mVariants.begin(), mVariants.end(),
                            IsLessThan<decltype(mVariants)::ElementType>));

  auto findVariant = [this](const char* variant) {
    auto* p = std::lower_bound(mVariants.begin(), mVariants.end(), variant,
                               IsLessThan<decltype(mVariants)::ElementType,
                                          decltype(variant)>);

    if (p != mVariants.end() && strcmp(p->get(), variant) == 0) {
      return p;
    }
    return static_cast<decltype(p)>(nullptr);
  };

  auto insertVariantSortedIfNotPresent = [&](const char* variant) {
    auto* p = std::lower_bound(mVariants.begin(), mVariants.end(), variant,
                               IsLessThan<decltype(mVariants)::ElementType,
                                          decltype(variant)>);

    // Don't insert the replacement when already present.
    if (p != mVariants.end() && strcmp(p->get(), variant) == 0) {
      return true;
    }

    // Insert the preferred variant in sort order.
    auto preferred = DuplicateStringToUniqueChars(variant);
    return !!mVariants.insert(p, std::move(preferred));
  };

  auto removeVariant = [&](auto* p) {
    size_t index = std::distance(mVariants.begin(), p);
    mVariants.erase(mVariants.begin() + index);
  };

  auto removeVariants = [&](auto* p, auto* q) {
    size_t pIndex = std::distance(mVariants.begin(), p);
    size_t qIndex = std::distance(mVariants.begin(), q);
    MOZ_ASSERT(pIndex < qIndex, "variant subtags are sorted");

    mVariants.erase(mVariants.begin() + qIndex);
    mVariants.erase(mVariants.begin() + pIndex);
  };"""
    )

    # Helper class for pattern matching.
    class AnyClass:
        def __eq__(self, obj):
            return obj is not None

    Any = AnyClass()

    # Group the mappings by language.
    legacy_mappings_by_language = {}
    for (type, replacement) in legacy_mappings.items():
        (language, _, _, _) = type
        legacy_mappings_by_language.setdefault(language, {})[type] = replacement

    # Handle the empty language case first.
    if None in legacy_mappings_by_language:
        # Get the mappings and remove them from the dict.
        mappings = legacy_mappings_by_language.pop(None)

        # This case only applies for the "hepburn-heploc" -> "alalc97"
        # mapping, so just inline it here.
        from_tag = (None, None, None, "hepburn-heploc")
        to_tag = (None, None, None, "alalc97")

        assert len(mappings) == 1
        assert mappings[from_tag] == to_tag

        println(
            """
  if (mVariants.length() >= 2) {
    if (auto* hepburn = findVariant("hepburn")) {
      if (auto* heploc = findVariant("heploc")) {
        removeVariants(hepburn, heploc);

        if (!insertVariantSortedIfNotPresent("alalc97")) {
          return false;
        }
      }
    }
  }
"""
        )

    # Handle sign languages next.
    if "sgn" in legacy_mappings_by_language:
        mappings = legacy_mappings_by_language.pop("sgn")

        # Legacy sign language mappings have the form "sgn-XX" where "XX" is
        # some region code.
        assert all(type == ("sgn", None, Any, None) for type in mappings.keys())

        # Legacy sign languages are mapped to a single language subtag.
        assert all(
            replacement == (Any, None, None, None) for replacement in mappings.values()
        )

        println(
            """
  if (Language().EqualTo("sgn")) {
    if (Region().Present() && SignLanguageMapping(mLanguage, Region())) {
      mRegion.Set(mozilla::MakeStringSpan(""));
    }
  }
""".rstrip().lstrip(
                "\n"
            )
        )

    # Finally handle all remaining cases.

    # The remaining mappings have neither script nor region subtags in the source locale.
    assert all(
        type == (Any, None, None, Any)
        for mappings in legacy_mappings_by_language.values()
        for type in mappings.keys()
    )

    # And they have neither script nor region nor variant subtags in the target locale.
    assert all(
        replacement == (Any, None, None, None)
        for mappings in legacy_mappings_by_language.values()
        for replacement in mappings.values()
    )

    # Compact the mappings table by removing empty fields.
    legacy_mappings_by_language = {
        lang: {
            variants: r_language
            for ((_, _, _, variants), (r_language, _, _, _)) in mappings.items()
        }
        for (lang, mappings) in legacy_mappings_by_language.items()
    }

    # Try to combine the remaining cases.
    legacy_mappings_compact = {}

    # Python can't hash dicts or lists, so use the string representation as the hash key.
    def hash_key(mappings):
        return str(sorted(mappings.items(), key=itemgetter(0)))

    for (lang, mappings) in sorted(
        legacy_mappings_by_language.items(), key=itemgetter(0)
    ):
        key = hash_key(mappings)
        legacy_mappings_compact.setdefault(key, []).append(lang)

    for langs in legacy_mappings_compact.values():
        language_equal_to = (
            f"""Language().EqualTo("{lang}")""" for lang in sorted(langs)
        )
        cond = f""" ||\n{" " * len("  else if (")}""".join(language_equal_to)

        println(
            f"""
  else if ({cond}) {{
""".rstrip().lstrip(
                "\n"
            )
        )

        mappings = legacy_mappings_by_language[langs[0]]

        # Count the variant subtags to determine the sort order.
        def variant_size(m):
            (k, _) = m
            return len(k.split("-"))

        # Alias rules are applied by largest union size first.
        for (size, mappings_by_size) in groupby(
            sorted(mappings.items(), key=variant_size, reverse=True), key=variant_size
        ):

            # Convert grouper object to dict.
            mappings_by_size = dict(mappings_by_size)

            is_first = True
            chain_if = size == 1

            # Alias rules are applied in alphabetical order
            for (variants, r_language) in sorted(
                mappings_by_size.items(), key=itemgetter(0)
            ):
                sorted_variants = sorted(variants.split("-"))
                len_variants = len(sorted_variants)

                maybe_else = "else " if chain_if and not is_first else ""
                is_first = False

                for (i, variant) in enumerate(sorted_variants):
                    println(
                        f"""
    {"  " * i}{maybe_else}if (auto* {variant} = findVariant("{variant}")) {{
""".rstrip().lstrip(
                            "\n"
                        )
                    )

                indent = "  " * len_variants

                println(
                    f"""
    {indent}removeVariant{"s" if len_variants > 1 else ""}({", ".join(sorted_variants)});
    {indent}SetLanguage("{r_language}");
    {indent}{"return true;" if not chain_if else ""}
""".rstrip().lstrip(
                        "\n"
                    )
                )

                for i in range(len_variants, 0, -1):
                    println(
                        f"""
    {"  " * (i - 1)}}}
""".rstrip().lstrip(
                            "\n"
                        )
                    )

        println(
            """
  }
""".rstrip().lstrip(
                "\n"
            )
        )

    println(
        """
  return true;
}"""
    )


def writeSignLanguageMappingsFunction(
    println, legacy_mappings, description, source, url
):
    """Writes a function definition that maps legacy sign language tags."""
    println("")
    writeMappingHeader(println, description, source, url)
    println(
        """\
bool mozilla::intl::Locale::SignLanguageMapping(LanguageSubtag& language,
                                                const RegionSubtag& region) {
  MOZ_ASSERT(language.EqualTo("sgn"));
  MOZ_ASSERT(IsStructurallyValidRegionTag(region.Span()));
  MOZ_ASSERT(IsCanonicallyCasedRegionTag(region.Span()));
""".rstrip()
    )

    region_mappings = {
        rg: lg
        for ((lang, _, rg, _), (lg, _, _, _)) in legacy_mappings.items()
        if lang == "sgn"
    }

    source_name = "region"
    target_name = "language"
    tag_maxlength = 3
    writeMappingsBinarySearchBody(
        println, source_name, target_name, region_mappings, tag_maxlength
    )

    println(
        """
}""".lstrip()
    )


def readSupplementalData(core_file):
    """Reads CLDR Supplemental Data and extracts information for Intl.js.

    Information extracted:
    - legacyMappings: mappings from legacy tags to preferred complete language tags
    - languageMappings: mappings from language subtags to preferred subtags
    - complexLanguageMappings: mappings from language subtags with complex rules
    - regionMappings: mappings from region subtags to preferred subtags
    - complexRegionMappings: mappings from region subtags with complex rules
    - variantMappings: mappings from variant subtags to preferred subtags
    - likelySubtags: likely subtags used for generating test data only
    Returns these mappings as dictionaries.
    """
    import xml.etree.ElementTree as ET

    # From Unicode BCP 47 locale identifier <https://unicode.org/reports/tr35/>.
    re_unicode_language_id = re.compile(
        r"""
        ^
        # unicode_language_id = unicode_language_subtag
        #     unicode_language_subtag = alpha{2,3} | alpha{5,8}
        (?P<language>[a-z]{2,3}|[a-z]{5,8})

        # (sep unicode_script_subtag)?
        #     unicode_script_subtag = alpha{4}
        (?:-(?P<script>[a-z]{4}))?

        # (sep unicode_region_subtag)?
        #     unicode_region_subtag = (alpha{2} | digit{3})
        (?:-(?P<region>([a-z]{2}|[0-9]{3})))?

        # (sep unicode_variant_subtag)*
        #     unicode_variant_subtag = (alphanum{5,8} | digit alphanum{3})
        (?P<variants>(-([a-z0-9]{5,8}|[0-9][a-z0-9]{3}))+)?
        $
        """,
        re.IGNORECASE | re.VERBOSE,
    )

    # CLDR uses "_" as the separator for some elements. Replace it with "-".
    def bcp47_id(cldr_id):
        return cldr_id.replace("_", "-")

    # Return the tuple (language, script, region, variants) and assert all
    # subtags are in canonical case.
    def bcp47_canonical(language, script, region, variants):
        # Canonical case for language subtags is lower case.
        assert language is None or language.lower() == language

        # Canonical case for script subtags is title case.
        assert script is None or script.title() == script

        # Canonical case for region subtags is upper case.
        assert region is None or region.upper() == region

        # Canonical case for variant subtags is lower case.
        assert variants is None or variants.lower() == variants

        return (language, script, region, variants[1:] if variants else None)

    # Language ids are interpreted as multi-maps in
    # <https://www.unicode.org/reports/tr35/#LocaleId_Canonicalization>.
    #
    # See UTS35, §Annex C, Definitions - 1. Multimap interpretation.
    def language_id_to_multimap(language_id):
        match = re_unicode_language_id.match(language_id)
        assert (
            match is not None
        ), f"{language_id} invalid Unicode BCP 47 locale identifier"

        canonical_language_id = bcp47_canonical(
            *match.group("language", "script", "region", "variants")
        )
        (language, _, _, _) = canonical_language_id

        # Normalize "und" language to None, but keep the rest as is.
        return (language if language != "und" else None,) + canonical_language_id[1:]

    rules = {}
    territory_exception_rules = {}

    tree = ET.parse(core_file.open("common/supplemental/supplementalMetadata.xml"))

    # Load the rules from supplementalMetadata.xml.
    #
    # See UTS35, §Annex C, Definitions - 2. Alias elements.
    # See UTS35, §Annex C, Preprocessing.
    for alias_name in [
        "languageAlias",
        "scriptAlias",
        "territoryAlias",
        "variantAlias",
    ]:
        for alias in tree.iterfind(".//" + alias_name):
            # Replace '_' by '-'.
            type = bcp47_id(alias.get("type"))
            replacement = bcp47_id(alias.get("replacement"))

            # Prefix with "und-".
            if alias_name != "languageAlias":
                type = "und-" + type

            # Discard all rules where the type is an invalid languageId.
            if re_unicode_language_id.match(type) is None:
                continue

            type = language_id_to_multimap(type)

            # Multiple, whitespace-separated territory replacements may be present.
            if alias_name == "territoryAlias" and " " in replacement:
                replacements = replacement.split(" ")
                replacement_list = [
                    language_id_to_multimap("und-" + r) for r in replacements
                ]

                assert (
                    type not in territory_exception_rules
                ), f"Duplicate alias rule: {type}"

                territory_exception_rules[type] = replacement_list

                # The first element is the default territory replacement.
                replacement = replacements[0]

            # Prefix with "und-".
            if alias_name != "languageAlias":
                replacement = "und-" + replacement

            replacement = language_id_to_multimap(replacement)

            assert type not in rules, f"Duplicate alias rule: {type}"

            rules[type] = replacement

    # Helper class for pattern matching.
    class AnyClass:
        def __eq__(self, obj):
            return obj is not None

    Any = AnyClass()

    modified_rules = True
    loop_count = 0

    while modified_rules:
        modified_rules = False
        loop_count += 1

        # UTS 35 defines that canonicalization is applied until a fixed point has
        # been reached. This iterative application of the canonicalization algorithm
        # is only needed for a relatively small set of rules, so we can precompute
        # the transitive closure of all rules here and then perform a single pass
        # when canonicalizing language tags at runtime.
        transitive_rules = {}

        # Compute the transitive closure.
        # Any case which currently doesn't occur in the CLDR sources isn't supported
        # and will lead to throwing an error.
        for (type, replacement) in rules.items():
            (language, script, region, variants) = type
            (r_language, r_script, r_region, r_variants) = replacement

            for (i_type, i_replacement) in rules.items():
                (i_language, i_script, i_region, i_variants) = i_type
                (i_r_language, i_r_script, i_r_region, i_r_variants) = i_replacement

                if i_language is not None and i_language == r_language:
                    # This case currently only occurs when neither script nor region
                    # subtags are present. A single variant subtags may be present
                    # in |type|. And |i_type| definitely has a single variant subtag.
                    # Should this ever change, update this code accordingly.
                    assert type == (Any, None, None, None) or type == (
                        Any,
                        None,
                        None,
                        Any,
                    )
                    assert replacement == (Any, None, None, None)
                    assert i_type == (Any, None, None, Any)
                    assert i_replacement == (Any, None, None, None)

                    # This case happens for the rules
                    #   "zh-guoyu -> zh",
                    #   "zh-hakka -> hak", and
                    #   "und-hakka -> und".
                    # Given the possible input "zh-guoyu-hakka", the first rule will
                    # change it to "zh-hakka", and then the second rule can be
                    # applied. (The third rule isn't applied ever.)
                    #
                    # Let's assume there's a hypothetical rule
                    #   "zh-aaaaa" -> "en"
                    # And we have the input "zh-aaaaa-hakka", then "zh-aaaaa -> en"
                    # is applied before "zh-hakka -> hak", because rules are sorted
                    # alphabetically. That means the overall result is "en":
                    # "zh-aaaaa-hakka" is first canonicalized to "en-hakka" and then
                    # "hakka" is removed through the third rule.
                    #
                    # No current rule requires to handle this special case, so we
                    # don't yet support it.
                    assert variants is None or variants <= i_variants

                    # Combine all variants and remove duplicates.
                    vars = set(
                        i_variants.split("-")
                        + (variants.split("-") if variants else [])
                    )

                    # Add the variants alphabetically sorted.
                    n_type = (language, None, None, "-".join(sorted(vars)))

                    assert (
                        n_type not in transitive_rules
                        or transitive_rules[n_type] == i_replacement
                    )
                    transitive_rules[n_type] = i_replacement

                    continue

                if i_script is not None and i_script == r_script:
                    # This case currently doesn't occur, so we don't yet support it.
                    raise ValueError(
                        f"{type} -> {replacement} :: {i_type} -> {i_replacement}"
                    )
                if i_region is not None and i_region == r_region:
                    # This case currently only applies for sign language
                    # replacements. Similar to the language subtag case any other
                    # combination isn't currently supported.
                    assert type == (None, None, Any, None)
                    assert replacement == (None, None, Any, None)
                    assert i_type == ("sgn", None, Any, None)
                    assert i_replacement == (Any, None, None, None)

                    n_type = ("sgn", None, region, None)

                    assert n_type not in transitive_rules
                    transitive_rules[n_type] = i_replacement

                    continue

                if i_variants is not None and i_variants == r_variants:
                    # This case currently doesn't occur, so we don't yet support it.
                    raise ValueError(
                        f"{type} -> {replacement} :: {i_type} -> {i_replacement}"
                    )

        # Ensure there are no contradicting rules.
        assert all(
            rules[type] == replacement
            for (type, replacement) in transitive_rules.items()
            if type in rules
        )

        # If |transitive_rules| is not a subset of |rules|, new rules will be added.
        modified_rules = not (transitive_rules.keys() <= rules.keys())

        # Ensure we only have to iterate more than once for the "guoyo-{hakka,xiang}"
        # case. Failing this assertion means either there's a bug when computing the
        # stop condition of this loop or a new kind of legacy language tags was added.
        if modified_rules and loop_count > 1:
            new_rules = {k for k in transitive_rules.keys() if k not in rules}
            for k in new_rules:
                assert k == (Any, None, None, "guoyu-hakka") or k == (
                    Any,
                    None,
                    None,
                    "guoyu-xiang",
                )

        # Merge the transitive rules.
        rules.update(transitive_rules)

    # Computes the size of the union of all field value sets.
    def multi_map_size(locale_id):
        (language, script, region, variants) = locale_id

        return (
            (1 if language is not None else 0)
            + (1 if script is not None else 0)
            + (1 if region is not None else 0)
            + (len(variants.split("-")) if variants is not None else 0)
        )

    # Dictionary of legacy mappings, contains raw rules, e.g.
    # (None, None, None, "hepburn-heploc") -> (None, None, None, "alalc97").
    legacy_mappings = {}

    # Dictionary of simple language subtag mappings, e.g. "in" -> "id".
    language_mappings = {}

    # Dictionary of complex language subtag mappings, modifying more than one
    # subtag, e.g. "sh" -> ("sr", "Latn", None) and "cnr" -> ("sr", None, "ME").
    complex_language_mappings = {}

    # Dictionary of simple script subtag mappings, e.g. "Qaai" -> "Zinh".
    script_mappings = {}

    # Dictionary of simple region subtag mappings, e.g. "DD" -> "DE".
    region_mappings = {}

    # Dictionary of complex region subtag mappings, containing more than one
    # replacement, e.g. "SU" -> ("RU", ["AM", "AZ", "BY", ...]).
    complex_region_mappings = {}

    # Dictionary of aliased variant subtags to a tuple of preferred replacement
    # type and replacement, e.g. "arevela" -> ("language", "hy") or
    # "aaland" -> ("region", "AX") or "heploc" -> ("variant", "alalc97").
    variant_mappings = {}

    # Preprocess all rules so we can perform a single lookup per subtag at runtime.
    for (type, replacement) in rules.items():
        (language, script, region, variants) = type
        (r_language, r_script, r_region, r_variants) = replacement

        type_map_size = multi_map_size(type)

        # Most mappings are one-to-one and can be encoded through lookup tables.
        if type_map_size == 1:
            if language is not None:
                assert r_language is not None, "Can't remove a language subtag"

                # We don't yet support this case.
                assert (
                    r_variants is None
                ), f"Unhandled variant replacement in language alias: {replacement}"

                if replacement == (Any, None, None, None):
                    language_mappings[language] = r_language
                else:
                    complex_language_mappings[language] = replacement[:-1]
            elif script is not None:
                # We don't support removing script subtags.
                assert (
                    r_script is not None
                ), f"Can't remove a script subtag: {replacement}"

                # We only support one-to-one script mappings for now.
                assert replacement == (
                    None,
                    Any,
                    None,
                    None,
                ), f"Unhandled replacement in script alias: {replacement}"

                script_mappings[script] = r_script
            elif region is not None:
                # We don't support removing region subtags.
                assert (
                    r_region is not None
                ), f"Can't remove a region subtag: {replacement}"

                # We only support one-to-one region mappings for now.
                assert replacement == (
                    None,
                    None,
                    Any,
                    None,
                ), f"Unhandled replacement in region alias: {replacement}"

                if type not in territory_exception_rules:
                    region_mappings[region] = r_region
                else:
                    complex_region_mappings[region] = [
                        r_region
                        for (_, _, r_region, _) in territory_exception_rules[type]
                    ]
            else:
                assert variants is not None
                assert len(variants.split("-")) == 1

                # We only support one-to-one variant mappings for now.
                assert (
                    multi_map_size(replacement) <= 1
                ), f"Unhandled replacement in variant alias: {replacement}"

                if r_language is not None:
                    variant_mappings[variants] = ("language", r_language)
                elif r_script is not None:
                    variant_mappings[variants] = ("script", r_script)
                elif r_region is not None:
                    variant_mappings[variants] = ("region", r_region)
                elif r_variants is not None:
                    assert len(r_variants.split("-")) == 1
                    variant_mappings[variants] = ("variant", r_variants)
                else:
                    variant_mappings[variants] = None
        else:
            # Alias rules which have multiple input fields must be processed
            # first. This applies only to a handful of rules, so our generated
            # code adds fast paths to skip these rules in the common case.

            # Case 1: Language and at least one variant subtag.
            if language is not None and variants is not None:
                pass

            # Case 2: Sign language and a region subtag.
            elif language == "sgn" and region is not None:
                pass

            # Case 3: "hepburn-heploc" to "alalc97" canonicalization.
            elif (
                language is None
                and variants is not None
                and len(variants.split("-")) == 2
            ):
                pass

            # Any other combination is currently unsupported.
            else:
                raise ValueError(f"{type} -> {replacement}")

            legacy_mappings[type] = replacement

    tree = ET.parse(core_file.open("common/supplemental/likelySubtags.xml"))

    likely_subtags = {}

    for likely_subtag in tree.iterfind(".//likelySubtag"):
        from_tag = bcp47_id(likely_subtag.get("from"))
        from_match = re_unicode_language_id.match(from_tag)
        assert (
            from_match is not None
        ), f"{from_tag} invalid Unicode BCP 47 locale identifier"
        assert (
            from_match.group("variants") is None
        ), f"unexpected variant subtags in {from_tag}"

        to_tag = bcp47_id(likely_subtag.get("to"))
        to_match = re_unicode_language_id.match(to_tag)
        assert (
            to_match is not None
        ), f"{to_tag} invalid Unicode BCP 47 locale identifier"
        assert (
            to_match.group("variants") is None
        ), f"unexpected variant subtags in {to_tag}"

        from_canonical = bcp47_canonical(
            *from_match.group("language", "script", "region", "variants")
        )

        to_canonical = bcp47_canonical(
            *to_match.group("language", "script", "region", "variants")
        )

        # Remove the empty variant subtags.
        from_canonical = from_canonical[:-1]
        to_canonical = to_canonical[:-1]

        likely_subtags[from_canonical] = to_canonical

    complex_region_mappings_final = {}

    for (deprecated_region, replacements) in complex_region_mappings.items():
        # Find all likely subtag entries which don't already contain a region
        # subtag and whose target region is in the list of replacement regions.
        region_likely_subtags = [
            (from_language, from_script, to_region)
            for (
                (from_language, from_script, from_region),
                (_, _, to_region),
            ) in likely_subtags.items()
            if from_region is None and to_region in replacements
        ]

        # The first replacement entry is the default region.
        default = replacements[0]

        # Find all likely subtag entries whose region matches the default region.
        default_replacements = {
            (language, script)
            for (language, script, region) in region_likely_subtags
            if region == default
        }

        # And finally find those entries which don't use the default region.
        # These are the entries we're actually interested in, because those need
        # to be handled specially when selecting the correct preferred region.
        non_default_replacements = [
            (language, script, region)
            for (language, script, region) in region_likely_subtags
            if (language, script) not in default_replacements
        ]

        # If there are no non-default replacements, we can handle the region as
        # part of the simple region mapping.
        if non_default_replacements:
            complex_region_mappings_final[deprecated_region] = (
                default,
                non_default_replacements,
            )
        else:
            region_mappings[deprecated_region] = default

    return {
        "legacyMappings": legacy_mappings,
        "languageMappings": language_mappings,
        "complexLanguageMappings": complex_language_mappings,
        "scriptMappings": script_mappings,
        "regionMappings": region_mappings,
        "complexRegionMappings": complex_region_mappings_final,
        "variantMappings": variant_mappings,
        "likelySubtags": likely_subtags,
    }


def readUnicodeExtensions(core_file):
    import xml.etree.ElementTree as ET

    # Match all xml-files in the BCP 47 directory.
    bcpFileRE = re.compile(r"^common/bcp47/.+\.xml$")

    # https://www.unicode.org/reports/tr35/#Unicode_locale_identifier
    #
    # type = alphanum{3,8} (sep alphanum{3,8})* ;
    typeRE = re.compile(r"^[a-z0-9]{3,8}(-[a-z0-9]{3,8})*$")

    # https://www.unicode.org/reports/tr35/#Unicode_language_identifier
    #
    # unicode_region_subtag = alpha{2} ;
    alphaRegionRE = re.compile(r"^[A-Z]{2}$", re.IGNORECASE)

    # Mapping from Unicode extension types to dict of deprecated to
    # preferred values.
    mapping = {
        # Unicode BCP 47 U Extension
        "u": {},
        # Unicode BCP 47 T Extension
        "t": {},
    }

    def readBCP47File(file):
        tree = ET.parse(file)
        for keyword in tree.iterfind(".//keyword/key"):
            extension = keyword.get("extension", "u")
            assert (
                extension == "u" or extension == "t"
            ), "unknown extension type: {}".format(extension)

            extension_name = keyword.get("name")

            for type in keyword.iterfind("type"):
                # <https://unicode.org/reports/tr35/#Unicode_Locale_Extension_Data_Files>:
                #
                # The key or type name used by Unicode locale extension with 'u' extension
                # syntax or the 't' extensions syntax. When alias below is absent, this name
                # can be also used with the old style "@key=type" syntax.
                name = type.get("name")

                # Ignore the special name:
                # - <https://unicode.org/reports/tr35/#CODEPOINTS>
                # - <https://unicode.org/reports/tr35/#REORDER_CODE>
                # - <https://unicode.org/reports/tr35/#RG_KEY_VALUE>
                # - <https://unicode.org/reports/tr35/#SCRIPT_CODE>
                # - <https://unicode.org/reports/tr35/#SUBDIVISION_CODE>
                # - <https://unicode.org/reports/tr35/#PRIVATE_USE>
                if name in (
                    "CODEPOINTS",
                    "REORDER_CODE",
                    "RG_KEY_VALUE",
                    "SCRIPT_CODE",
                    "SUBDIVISION_CODE",
                    "PRIVATE_USE",
                ):
                    continue

                # All other names should match the 'type' production.
                assert (
                    typeRE.match(name) is not None
                ), "{} matches the 'type' production".format(name)

                # <https://unicode.org/reports/tr35/#Unicode_Locale_Extension_Data_Files>:
                #
                # The preferred value of the deprecated key, type or attribute element.
                # When a key, type or attribute element is deprecated, this attribute is
                # used for specifying a new canonical form if available.
                preferred = type.get("preferred")

                # <https://unicode.org/reports/tr35/#Unicode_Locale_Extension_Data_Files>:
                #
                # The BCP 47 form is the canonical form, and recommended. Other aliases are
                # included only for backwards compatibility.
                alias = type.get("alias")

                # <https://unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers>
                #
                # Use the bcp47 data to replace keys, types, tfields, and tvalues by their
                # canonical forms. See Section 3.6.4 U Extension Data Files) and Section
                # 3.7.1 T Extension Data Files. The aliases are in the alias attribute
                # value, while the canonical is in the name attribute value.

                # 'preferred' contains the new preferred name, 'alias' the compatibility
                # name, but then there's this entry where 'preferred' and 'alias' are the
                # same. So which one to choose? Assume 'preferred' is the actual canonical
                # name.
                #
                # <type name="islamicc"
                #       description="Civil (algorithmic) Arabic calendar"
                #       deprecated="true"
                #       preferred="islamic-civil"
                #       alias="islamic-civil"/>

                if preferred is not None:
                    assert typeRE.match(preferred), preferred
                    mapping[extension].setdefault(extension_name, {})[name] = preferred

                if alias is not None:
                    for alias_name in alias.lower().split(" "):
                        # Ignore alias entries which don't match the 'type' production.
                        if typeRE.match(alias_name) is None:
                            continue

                        # See comment above when 'alias' and 'preferred' are both present.
                        if (
                            preferred is not None
                            and name in mapping[extension][extension_name]
                        ):
                            continue

                        # Skip over entries where 'name' and 'alias' are equal.
                        #
                        # <type name="pst8pdt"
                        #       description="POSIX style time zone for US Pacific Time"
                        #       alias="PST8PDT"
                        #       since="1.8"/>
                        if name == alias_name:
                            continue

                        mapping[extension].setdefault(extension_name, {})[
                            alias_name
                        ] = name

    def readSupplementalMetadata(file):
        # Find subdivision and region replacements.
        #
        # <https://www.unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers>
        #
        # Replace aliases in special key values:
        #   - If there is an 'sd' or 'rg' key, replace any subdivision alias
        #     in its value in the same way, using subdivisionAlias data.
        tree = ET.parse(file)
        for alias in tree.iterfind(".//subdivisionAlias"):
            type = alias.get("type")
            assert (
                typeRE.match(type) is not None
            ), "{} matches the 'type' production".format(type)

            # Take the first replacement when multiple ones are present.
            replacement = alias.get("replacement").split(" ")[0].lower()

            # Append "zzzz" if the replacement is a two-letter region code.
            if alphaRegionRE.match(replacement) is not None:
                replacement += "zzzz"

            # Assert the replacement is syntactically correct.
            assert (
                typeRE.match(replacement) is not None
            ), "replacement {} matches the 'type' production".format(replacement)

            # 'subdivisionAlias' applies to 'rg' and 'sd' keys.
            mapping["u"].setdefault("rg", {})[type] = replacement
            mapping["u"].setdefault("sd", {})[type] = replacement

    for name in core_file.namelist():
        if bcpFileRE.match(name):
            readBCP47File(core_file.open(name))

    readSupplementalMetadata(
        core_file.open("common/supplemental/supplementalMetadata.xml")
    )

    return {
        "unicodeMappings": mapping["u"],
        "transformMappings": mapping["t"],
    }


def writeCLDRLanguageTagData(println, data, url):
    """Writes the language tag data to the Intl data file."""

    println(generatedFileWarning)
    println("// Version: CLDR-{}".format(data["version"]))
    println("// URL: {}".format(url))

    println(
        """
#include "mozilla/Assertions.h"
#include "mozilla/Span.h"
#include "mozilla/TextUtils.h"

#include <algorithm>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <string>
#include <type_traits>

#include "mozilla/intl/Locale.h"

using namespace mozilla::intl::LanguageTagLimits;

template <size_t Length, size_t TagLength, size_t SubtagLength>
static inline bool HasReplacement(
    const char (&subtags)[Length][TagLength],
    const mozilla::intl::LanguageTagSubtag<SubtagLength>& subtag) {
  MOZ_ASSERT(subtag.Length() == TagLength - 1,
             "subtag must have the same length as the list of subtags");

  const char* ptr = subtag.Span().data();
  return std::binary_search(std::begin(subtags), std::end(subtags), ptr,
                            [](const char* a, const char* b) {
                              return memcmp(a, b, TagLength - 1) < 0;
                            });
}

template <size_t Length, size_t TagLength, size_t SubtagLength>
static inline const char* SearchReplacement(
    const char (&subtags)[Length][TagLength], const char* (&aliases)[Length],
    const mozilla::intl::LanguageTagSubtag<SubtagLength>& subtag) {
  MOZ_ASSERT(subtag.Length() == TagLength - 1,
             "subtag must have the same length as the list of subtags");

  const char* ptr = subtag.Span().data();
  auto p = std::lower_bound(std::begin(subtags), std::end(subtags), ptr,
                            [](const char* a, const char* b) {
                              return memcmp(a, b, TagLength - 1) < 0;
                            });
  if (p != std::end(subtags) && memcmp(*p, ptr, TagLength - 1) == 0) {
    return aliases[std::distance(std::begin(subtags), p)];
  }
  return nullptr;
}

#ifdef DEBUG
static bool IsAsciiLowercaseAlphanumeric(char c) {
  return mozilla::IsAsciiLowercaseAlpha(c) || mozilla::IsAsciiDigit(c);
}

static bool IsAsciiLowercaseAlphanumericOrDash(char c) {
  return IsAsciiLowercaseAlphanumeric(c) || c == '-';
}

static bool IsCanonicallyCasedLanguageTag(mozilla::Span<const char> span) {
  return std::all_of(span.begin(), span.end(),
                     mozilla::IsAsciiLowercaseAlpha<char>);
}

static bool IsCanonicallyCasedScriptTag(mozilla::Span<const char> span) {
  return mozilla::IsAsciiUppercaseAlpha(span[0]) &&
         std::all_of(span.begin() + 1, span.end(),
                     mozilla::IsAsciiLowercaseAlpha<char>);
}

static bool IsCanonicallyCasedRegionTag(mozilla::Span<const char> span) {
  return std::all_of(span.begin(), span.end(),
                     mozilla::IsAsciiUppercaseAlpha<char>) ||
         std::all_of(span.begin(), span.end(), mozilla::IsAsciiDigit<char>);
}

static bool IsCanonicallyCasedVariantTag(mozilla::Span<const char> span) {
  return std::all_of(span.begin(), span.end(), IsAsciiLowercaseAlphanumeric);
}

static bool IsCanonicallyCasedUnicodeKey(mozilla::Span<const char> key) {
  return std::all_of(key.begin(), key.end(), IsAsciiLowercaseAlphanumeric);
}

static bool IsCanonicallyCasedUnicodeType(mozilla::Span<const char> type) {
  return std::all_of(type.begin(), type.end(),
                     IsAsciiLowercaseAlphanumericOrDash);
}

static bool IsCanonicallyCasedTransformKey(mozilla::Span<const char> key) {
  return std::all_of(key.begin(), key.end(), IsAsciiLowercaseAlphanumeric);
}

static bool IsCanonicallyCasedTransformType(mozilla::Span<const char> type) {
  return std::all_of(type.begin(), type.end(),
                     IsAsciiLowercaseAlphanumericOrDash);
}
#endif
""".rstrip()
    )

    source = "CLDR Supplemental Data, version {}".format(data["version"])
    legacy_mappings = data["legacyMappings"]
    language_mappings = data["languageMappings"]
    complex_language_mappings = data["complexLanguageMappings"]
    script_mappings = data["scriptMappings"]
    region_mappings = data["regionMappings"]
    complex_region_mappings = data["complexRegionMappings"]
    variant_mappings = data["variantMappings"]
    unicode_mappings = data["unicodeMappings"]
    transform_mappings = data["transformMappings"]

    # unicode_language_subtag = alpha{2,3} | alpha{5,8} ;
    language_maxlength = 8

    # unicode_script_subtag = alpha{4} ;
    script_maxlength = 4

    # unicode_region_subtag = (alpha{2} | digit{3}) ;
    region_maxlength = 3

    writeMappingsBinarySearch(
        println,
        "LanguageMapping",
        "LanguageSubtag&",
        "language",
        "IsStructurallyValidLanguageTag",
        "IsCanonicallyCasedLanguageTag",
        language_mappings,
        language_maxlength,
        "Mappings from language subtags to preferred values.",
        source,
        url,
    )
    writeMappingsBinarySearch(
        println,
        "ComplexLanguageMapping",
        "const LanguageSubtag&",
        "language",
        "IsStructurallyValidLanguageTag",
        "IsCanonicallyCasedLanguageTag",
        complex_language_mappings.keys(),
        language_maxlength,
        "Language subtags with complex mappings.",
        source,
        url,
    )
    writeMappingsBinarySearch(
        println,
        "ScriptMapping",
        "ScriptSubtag&",
        "script",
        "IsStructurallyValidScriptTag",
        "IsCanonicallyCasedScriptTag",
        script_mappings,
        script_maxlength,
        "Mappings from script subtags to preferred values.",
        source,
        url,
    )
    writeMappingsBinarySearch(
        println,
        "RegionMapping",
        "RegionSubtag&",
        "region",
        "IsStructurallyValidRegionTag",
        "IsCanonicallyCasedRegionTag",
        region_mappings,
        region_maxlength,
        "Mappings from region subtags to preferred values.",
        source,
        url,
    )
    writeMappingsBinarySearch(
        println,
        "ComplexRegionMapping",
        "const RegionSubtag&",
        "region",
        "IsStructurallyValidRegionTag",
        "IsCanonicallyCasedRegionTag",
        complex_region_mappings.keys(),
        region_maxlength,
        "Region subtags with complex mappings.",
        source,
        url,
    )

    writeComplexLanguageTagMappings(
        println,
        complex_language_mappings,
        "Language subtags with complex mappings.",
        source,
        url,
    )
    writeComplexRegionTagMappings(
        println,
        complex_region_mappings,
        "Region subtags with complex mappings.",
        source,
        url,
    )

    writeVariantTagMappings(
        println,
        variant_mappings,
        "Mappings from variant subtags to preferred values.",
        source,
        url,
    )

    writeLegacyMappingsFunction(
        println, legacy_mappings, "Canonicalize legacy locale identifiers.", source, url
    )

    writeSignLanguageMappingsFunction(
        println, legacy_mappings, "Mappings from legacy sign languages.", source, url
    )

    writeUnicodeExtensionsMappings(println, unicode_mappings, "Unicode")
    writeUnicodeExtensionsMappings(println, transform_mappings, "Transform")


def writeCLDRLanguageTagLikelySubtagsTest(println, data, url):
    """Writes the likely-subtags test file."""

    println(generatedFileWarning)

    source = "CLDR Supplemental Data, version {}".format(data["version"])
    language_mappings = data["languageMappings"]
    complex_language_mappings = data["complexLanguageMappings"]
    script_mappings = data["scriptMappings"]
    region_mappings = data["regionMappings"]
    complex_region_mappings = data["complexRegionMappings"]
    likely_subtags = data["likelySubtags"]

    def bcp47(tag):
        (language, script, region) = tag
        return "{}{}{}".format(
            language, "-" + script if script else "", "-" + region if region else ""
        )

    def canonical(tag):
        (language, script, region) = tag

        # Map deprecated language subtags.
        if language in language_mappings:
            language = language_mappings[language]
        elif language in complex_language_mappings:
            (language2, script2, region2) = complex_language_mappings[language]
            (language, script, region) = (
                language2,
                script if script else script2,
                region if region else region2,
            )

        # Map deprecated script subtags.
        if script in script_mappings:
            script = script_mappings[script]

        # Map deprecated region subtags.
        if region in region_mappings:
            region = region_mappings[region]
        else:
            # Assume no complex region mappings are needed for now.
            assert (
                region not in complex_region_mappings
            ), "unexpected region with complex mappings: {}".format(region)

        return (language, script, region)

    # https://unicode.org/reports/tr35/#Likely_Subtags

    def addLikelySubtags(tag):
        # Step 1: Canonicalize.
        (language, script, region) = canonical(tag)
        if script == "Zzzz":
            script = None
        if region == "ZZ":
            region = None

        # Step 2: Lookup.
        searches = (
            (language, script, region),
            (language, None, region),
            (language, script, None),
            (language, None, None),
            ("und", script, None),
        )
        search = next(search for search in searches if search in likely_subtags)

        (language_s, script_s, region_s) = search
        (language_m, script_m, region_m) = likely_subtags[search]

        # Step 3: Return.
        return (
            language if language != language_s else language_m,
            script if script != script_s else script_m,
            region if region != region_s else region_m,
        )

    # https://unicode.org/reports/tr35/#Likely_Subtags
    def removeLikelySubtags(tag):
        # Step 1: Add likely subtags.
        max = addLikelySubtags(tag)

        # Step 2: Remove variants (doesn't apply here).

        # Step 3: Find a match.
        (language, script, region) = max
        for trial in (
            (language, None, None),
            (language, None, region),
            (language, script, None),
        ):
            if addLikelySubtags(trial) == max:
                return trial

        # Step 4: Return maximized if no match found.
        return max

    def likely_canonical(from_tag, to_tag):
        # Canonicalize the input tag.
        from_tag = canonical(from_tag)

        # Update the expected result if necessary.
        if from_tag in likely_subtags:
            to_tag = likely_subtags[from_tag]

        # Canonicalize the expected output.
        to_canonical = canonical(to_tag)

        # Sanity check: This should match the result of |addLikelySubtags|.
        assert to_canonical == addLikelySubtags(from_tag)

        return to_canonical

    # |likely_subtags| contains non-canonicalized tags, so canonicalize it first.
    likely_subtags_canonical = {
        k: likely_canonical(k, v) for (k, v) in likely_subtags.items()
    }

    # Add test data for |Intl.Locale.prototype.maximize()|.
    writeMappingsVar(
        println,
        {bcp47(k): bcp47(v) for (k, v) in likely_subtags_canonical.items()},
        "maxLikelySubtags",
        "Extracted from likelySubtags.xml.",
        source,
        url,
    )

    # Use the maximalized tags as the input for the remove likely-subtags test.
    minimized = {
        tag: removeLikelySubtags(tag) for tag in likely_subtags_canonical.values()
    }

    # Add test data for |Intl.Locale.prototype.minimize()|.
    writeMappingsVar(
        println,
        {bcp47(k): bcp47(v) for (k, v) in minimized.items()},
        "minLikelySubtags",
        "Extracted from likelySubtags.xml.",
        source,
        url,
    )

    println(
        """
for (let [tag, maximal] of Object.entries(maxLikelySubtags)) {
    assertEq(new Intl.Locale(tag).maximize().toString(), maximal);
}"""
    )

    println(
        """
for (let [tag, minimal] of Object.entries(minLikelySubtags)) {
    assertEq(new Intl.Locale(tag).minimize().toString(), minimal);
}"""
    )

    println(
        """
if (typeof reportCompare === "function")
    reportCompare(0, 0);"""
    )


def readCLDRVersionFromICU():
    icuDir = os.path.join(topsrcdir, "intl/icu/source")
    if not os.path.isdir(icuDir):
        raise RuntimeError("not a directory: {}".format(icuDir))

    reVersion = re.compile(r'\s*cldrVersion\{"(\d+(?:\.\d+)?)"\}')

    for line in flines(os.path.join(icuDir, "data/misc/supplementalData.txt")):
        m = reVersion.match(line)
        if m:
            version = m.group(1)
            break

    if version is None:
        raise RuntimeError("can't resolve CLDR version")

    return version


def updateCLDRLangTags(args):
    """Update the LanguageTagGenerated.cpp file."""
    version = args.version
    url = args.url
    out = args.out
    filename = args.file

    # Determine current CLDR version from ICU.
    if version is None:
        version = readCLDRVersionFromICU()

    url = url.replace("<VERSION>", version)

    print("Arguments:")
    print("\tCLDR version: %s" % version)
    print("\tDownload url: %s" % url)
    if filename is not None:
        print("\tLocal CLDR core.zip file: %s" % filename)
    print("\tOutput file: %s" % out)
    print("")

    data = {
        "version": version,
    }

    def readFiles(cldr_file):
        with ZipFile(cldr_file) as zip_file:
            data.update(readSupplementalData(zip_file))
            data.update(readUnicodeExtensions(zip_file))

    print("Processing CLDR data...")
    if filename is not None:
        print("Always make sure you have the newest CLDR core.zip!")
        with open(filename, "rb") as cldr_file:
            readFiles(cldr_file)
    else:
        print("Downloading CLDR core.zip...")
        with closing(urlopen(url)) as cldr_file:
            cldr_data = io.BytesIO(cldr_file.read())
            readFiles(cldr_data)

    print("Writing Intl data...")
    with io.open(out, mode="w", encoding="utf-8", newline="") as f:
        println = partial(print, file=f)

        writeCLDRLanguageTagData(println, data, url)

    print("Writing Intl test data...")
    js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
    test_file = os.path.join(
        js_src_builtin_intl_dir,
        "../../tests/non262/Intl/Locale/likely-subtags-generated.js",
    )
    with io.open(test_file, mode="w", encoding="utf-8", newline="") as f:
        println = partial(print, file=f)

        println("// |reftest| skip-if(!this.hasOwnProperty('Intl'))")
        writeCLDRLanguageTagLikelySubtagsTest(println, data, url)


def flines(filepath, encoding="utf-8"):
    """Open filepath and iterate over its content."""
    with io.open(filepath, mode="r", encoding=encoding) as f:
        for line in f:
            yield line


@total_ordering
class Zone(object):
    """Time zone with optional file name."""

    def __init__(self, name, filename=""):
        self.name = name
        self.filename = filename

    def __eq__(self, other):
        return hasattr(other, "name") and self.name == other.name

    def __lt__(self, other):
        return self.name < other.name

    def __hash__(self):
        return hash(self.name)

    def __str__(self):
        return self.name

    def __repr__(self):
        return self.name


class TzDataDir(object):
    """tzdata source from a directory."""

    def __init__(self, obj):
        self.name = partial(os.path.basename, obj)
        self.resolve = partial(os.path.join, obj)
        self.basename = os.path.basename
        self.isfile = os.path.isfile
        self.listdir = partial(os.listdir, obj)
        self.readlines = flines


class TzDataFile(object):
    """tzdata source from a file (tar or gzipped)."""

    def __init__(self, obj):
        self.name = lambda: os.path.splitext(
            os.path.splitext(os.path.basename(obj))[0]
        )[0]
        self.resolve = obj.getmember
        self.basename = attrgetter("name")
        self.isfile = tarfile.TarInfo.isfile
        self.listdir = obj.getnames
        self.readlines = partial(self._tarlines, obj)

    def _tarlines(self, tar, m):
        with closing(tar.extractfile(m)) as f:
            for line in f:
                yield line.decode("utf-8")


def validateTimeZones(zones, links):
    """Validate the zone and link entries."""
    linkZones = set(links.keys())
    intersect = linkZones.intersection(zones)
    if intersect:
        raise RuntimeError("Links also present in zones: %s" % intersect)

    zoneNames = {z.name for z in zones}
    linkTargets = set(links.values())
    if not linkTargets.issubset(zoneNames):
        raise RuntimeError(
            "Link targets not found: %s" % linkTargets.difference(zoneNames)
        )


def partition(iterable, *predicates):
    def innerPartition(pred, it):
        it1, it2 = tee(it)
        return (filter(pred, it1), filterfalse(pred, it2))

    if len(predicates) == 0:
        return iterable
    (left, right) = innerPartition(predicates[0], iterable)
    if len(predicates) == 1:
        return (left, right)
    return tuple([left] + list(partition(right, *predicates[1:])))


def listIANAFiles(tzdataDir):
    def isTzFile(d, m, f):
        return m(f) and d.isfile(d.resolve(f))

    return filter(
        partial(isTzFile, tzdataDir, re.compile("^[a-z0-9]+$").match),
        tzdataDir.listdir(),
    )


def readIANAFiles(tzdataDir, files):
    """Read all IANA time zone files from the given iterable."""
    nameSyntax = "[\w/+\-]+"
    pZone = re.compile(r"Zone\s+(?P<name>%s)\s+.*" % nameSyntax)
    pLink = re.compile(
        r"Link\s+(?P<target>%s)\s+(?P<name>%s)(?:\s+#.*)?" % (nameSyntax, nameSyntax)
    )

    def createZone(line, fname):
        match = pZone.match(line)
        name = match.group("name")
        return Zone(name, fname)

    def createLink(line, fname):
        match = pLink.match(line)
        (name, target) = match.group("name", "target")
        return (Zone(name, fname), target)

    zones = set()
    links = dict()
    for filename in files:
        filepath = tzdataDir.resolve(filename)
        for line in tzdataDir.readlines(filepath):
            if line.startswith("Zone"):
                zones.add(createZone(line, filename))
            if line.startswith("Link"):
                (link, target) = createLink(line, filename)
                links[link] = target

    return (zones, links)


def readIANATimeZones(tzdataDir, ignoreBackzone, ignoreFactory):
    """Read the IANA time zone information from `tzdataDir`."""

    backzoneFiles = {"backzone"}
    (bkfiles, tzfiles) = partition(listIANAFiles(tzdataDir), backzoneFiles.__contains__)

    # Read zone and link infos.
    (zones, links) = readIANAFiles(tzdataDir, tzfiles)
    (backzones, backlinks) = readIANAFiles(tzdataDir, bkfiles)

    # Remove the placeholder time zone "Factory".
    if ignoreFactory:
        zones.remove(Zone("Factory"))

    # Merge with backzone data.
    if not ignoreBackzone:
        zones |= backzones
        links = {
            name: target for name, target in links.items() if name not in backzones
        }
        links.update(backlinks)

    validateTimeZones(zones, links)

    return (zones, links)


def readICUResourceFile(filename):
    """Read an ICU resource file.

    Yields (<table-name>, <startOrEnd>, <value>) for each table.
    """

    numberValue = r"-?\d+"
    stringValue = r'".+?"'

    def asVector(val):
        return r"%s(?:\s*,\s*%s)*" % (val, val)

    numberVector = asVector(numberValue)
    stringVector = asVector(stringValue)

    reNumberVector = re.compile(numberVector)
    reStringVector = re.compile(stringVector)
    reNumberValue = re.compile(numberValue)
    reStringValue = re.compile(stringValue)

    def parseValue(value):
        m = reNumberVector.match(value)
        if m:
            return [int(v) for v in reNumberValue.findall(value)]
        m = reStringVector.match(value)
        if m:
            return [v[1:-1] for v in reStringValue.findall(value)]
        raise RuntimeError("unknown value type: %s" % value)

    def extractValue(values):
        if len(values) == 0:
            return None
        if len(values) == 1:
            return values[0]
        return values

    def line(*args):
        maybeMultiComments = r"(?:/\*[^*]*\*/)*"
        maybeSingleComment = r"(?://.*)?"
        lineStart = "^%s" % maybeMultiComments
        lineEnd = "%s\s*%s$" % (maybeMultiComments, maybeSingleComment)
        return re.compile(r"\s*".join(chain([lineStart], args, [lineEnd])))

    tableName = r'(?P<quote>"?)(?P<name>.+?)(?P=quote)'
    tableValue = r"(?P<value>%s|%s)" % (numberVector, stringVector)

    reStartTable = line(tableName, r"\{")
    reEndTable = line(r"\}")
    reSingleValue = line(r",?", tableValue, r",?")
    reCompactTable = line(tableName, r"\{", tableValue, r"\}")
    reEmptyLine = line()

    tables = []

    def currentTable():
        return "|".join(tables)

    values = []
    for line in flines(filename, "utf-8-sig"):
        line = line.strip()
        if line == "":
            continue

        m = reEmptyLine.match(line)
        if m:
            continue

        m = reStartTable.match(line)
        if m:
            assert len(values) == 0
            tables.append(m.group("name"))
            continue

        m = reEndTable.match(line)
        if m:
            yield (currentTable(), extractValue(values))
            tables.pop()
            values = []
            continue

        m = reCompactTable.match(line)
        if m:
            assert len(values) == 0
            tables.append(m.group("name"))
            yield (currentTable(), extractValue(parseValue(m.group("value"))))
            tables.pop()
            continue

        m = reSingleValue.match(line)
        if m and tables:
            values.extend(parseValue(m.group("value")))
            continue

        raise RuntimeError("unknown entry: %s" % line)


def readICUTimeZonesFromTimezoneTypes(icuTzDir):
    """Read the ICU time zone information from `icuTzDir`/timezoneTypes.txt
    and returns the tuple (zones, links).
    """
    typeMapTimeZoneKey = "timezoneTypes:table(nofallback)|typeMap|timezone|"
    typeAliasTimeZoneKey = "timezoneTypes:table(nofallback)|typeAlias|timezone|"

    def toTimeZone(name):
        return Zone(name.replace(":", "/"))

    zones = set()
    links = dict()

    for name, value in readICUResourceFile(os.path.join(icuTzDir, "timezoneTypes.txt")):
        if name.startswith(typeMapTimeZoneKey):
            zones.add(toTimeZone(name[len(typeMapTimeZoneKey) :]))
        if name.startswith(typeAliasTimeZoneKey):
            links[toTimeZone(name[len(typeAliasTimeZoneKey) :])] = value

    validateTimeZones(zones, links)

    return (zones, links)


def readICUTimeZonesFromZoneInfo(icuTzDir):
    """Read the ICU time zone information from `icuTzDir`/zoneinfo64.txt
    and returns the tuple (zones, links).
    """
    zoneKey = "zoneinfo64:table(nofallback)|Zones:array|:table"
    linkKey = "zoneinfo64:table(nofallback)|Zones:array|:int"
    namesKey = "zoneinfo64:table(nofallback)|Names"

    tzId = 0
    tzLinks = dict()
    tzNames = []

    for name, value in readICUResourceFile(os.path.join(icuTzDir, "zoneinfo64.txt")):
        if name == zoneKey:
            tzId += 1
        elif name == linkKey:
            tzLinks[tzId] = int(value)
            tzId += 1
        elif name == namesKey:
            tzNames.extend(value)

    links = {Zone(tzNames[zone]): tzNames[target] for (zone, target) in tzLinks.items()}
    zones = {Zone(v) for v in tzNames if Zone(v) not in links}

    validateTimeZones(zones, links)

    return (zones, links)


def readICUTimeZones(icuDir, icuTzDir, ignoreFactory):
    # zoneinfo64.txt contains the supported time zones by ICU. This data is
    # generated from tzdata files, it doesn't include "backzone" in stock ICU.
    (zoneinfoZones, zoneinfoLinks) = readICUTimeZonesFromZoneInfo(icuTzDir)

    # timezoneTypes.txt contains the canonicalization information for ICU. This
    # data is generated from CLDR files. It includes data about time zones from
    # tzdata's "backzone" file.
    (typesZones, typesLinks) = readICUTimeZonesFromTimezoneTypes(icuTzDir)

    # Remove the placeholder time zone "Factory".
    # See also <https://github.com/eggert/tz/blob/master/factory>.
    if ignoreFactory:
        zoneinfoZones.remove(Zone("Factory"))

    # Remove the ICU placeholder time zone "Etc/Unknown".
    # See also <https://unicode.org/reports/tr35/#Time_Zone_Identifiers>.
    for zones in (zoneinfoZones, typesZones):
        zones.remove(Zone("Etc/Unknown"))

    # Remove any outdated ICU links.
    for links in (zoneinfoLinks, typesLinks):
        for zone in otherICULegacyLinks().keys():
            if zone not in links:
                raise KeyError(f"Can't remove non-existent link from '{zone}'")
            del links[zone]

    # Information in zoneinfo64 should be a superset of timezoneTypes.
    def inZoneInfo64(zone):
        return zone in zoneinfoZones or zone in zoneinfoLinks

    notFoundInZoneInfo64 = [zone for zone in typesZones if not inZoneInfo64(zone)]
    if notFoundInZoneInfo64:
        raise RuntimeError(
            "Missing time zones in zoneinfo64.txt: %s" % notFoundInZoneInfo64
        )

    notFoundInZoneInfo64 = [
        zone for zone in typesLinks.keys() if not inZoneInfo64(zone)
    ]
    if notFoundInZoneInfo64:
        raise RuntimeError(
            "Missing time zones in zoneinfo64.txt: %s" % notFoundInZoneInfo64
        )

    # zoneinfo64.txt only defines the supported time zones by ICU, the canonicalization
    # rules are defined through timezoneTypes.txt. Merge both to get the actual zones
    # and links used by ICU.
    icuZones = set(
        chain(
            (zone for zone in zoneinfoZones if zone not in typesLinks),
            (zone for zone in typesZones),
        )
    )
    icuLinks = dict(
        chain(
            (
                (zone, target)
                for (zone, target) in zoneinfoLinks.items()
                if zone not in typesZones
            ),
            ((zone, target) for (zone, target) in typesLinks.items()),
        )
    )

    return (icuZones, icuLinks)


def readICULegacyZones(icuDir):
    """Read the ICU legacy time zones from `icuTzDir`/tools/tzcode/icuzones
    and returns the tuple (zones, links).
    """
    tzdir = TzDataDir(os.path.join(icuDir, "tools/tzcode"))

    # Per spec we must recognize only IANA time zones and links, but ICU
    # recognizes various legacy, non-IANA time zones and links. Compute these
    # non-IANA time zones and links.

    # Most legacy, non-IANA time zones and links are in the icuzones file.
    (zones, links) = readIANAFiles(tzdir, ["icuzones"])

    # Remove the ICU placeholder time zone "Etc/Unknown".
    # See also <https://unicode.org/reports/tr35/#Time_Zone_Identifiers>.
    zones.remove(Zone("Etc/Unknown"))

    # A handful of non-IANA zones/links are not in icuzones and must be added
    # manually so that we won't invoke ICU with them.
    for (zone, target) in otherICULegacyLinks().items():
        if zone in links:
            if links[zone] != target:
                raise KeyError(
                    f"Can't overwrite link '{zone} -> {links[zone]}' with '{target}'"
                )
            else:
                print(
                    f"Info: Link '{zone} -> {target}' can be removed from otherICULegacyLinks()"
                )
        links[zone] = target

    return (zones, links)


def otherICULegacyLinks():
    """The file `icuTzDir`/tools/tzcode/icuzones contains all ICU legacy time
    zones with the exception of time zones which are removed by IANA after an
    ICU release.

    For example ICU 67 uses tzdata2018i, but tzdata2020b removed the link from
    "US/Pacific-New" to "America/Los_Angeles". ICU standalone tzdata updates
    don't include modified icuzones files, so we must manually record any IANA
    modifications here.

    After an ICU update, we can remove any no longer needed entries from this
    function by checking if the relevant entries are now included in icuzones.
    """

    return {
        # Current ICU is up-to-date with IANA, so this dict is empty.
    }


def icuTzDataVersion(icuTzDir):
    """Read the ICU time zone version from `icuTzDir`/zoneinfo64.txt."""

    def searchInFile(pattern, f):
        p = re.compile(pattern)
        for line in flines(f, "utf-8-sig"):
            m = p.search(line)
            if m:
                return m.group(1)
        return None

    zoneinfo = os.path.join(icuTzDir, "zoneinfo64.txt")
    if not os.path.isfile(zoneinfo):
        raise RuntimeError("file not found: %s" % zoneinfo)
    version = searchInFile("^//\s+tz version:\s+([0-9]{4}[a-z])$", zoneinfo)
    if version is None:
        raise RuntimeError(
            "%s does not contain a valid tzdata version string" % zoneinfo
        )
    return version


def findIncorrectICUZones(ianaZones, ianaLinks, icuZones, icuLinks, ignoreBackzone):
    """Find incorrect ICU zone entries."""

    def isIANATimeZone(zone):
        return zone in ianaZones or zone in ianaLinks

    def isICUTimeZone(zone):
        return zone in icuZones or zone in icuLinks

    def isICULink(zone):
        return zone in icuLinks

    # All IANA zones should be present in ICU.
    missingTimeZones = [zone for zone in ianaZones if not isICUTimeZone(zone)]
    # Normally zones in backzone are also present as links in one of the other
    # time zone files. The only exception to this rule is the Asia/Hanoi time
    # zone, this zone is only present in the backzone file.
    expectedMissing = [] if ignoreBackzone else [Zone("Asia/Hanoi")]
    if missingTimeZones != expectedMissing:
        raise RuntimeError(
            "Not all zones are present in ICU, did you forget "
            "to run intl/update-tzdata.sh? %s" % missingTimeZones
        )

    # Zones which are only present in ICU?
    additionalTimeZones = [zone for zone in icuZones if not isIANATimeZone(zone)]
    if additionalTimeZones:
        raise RuntimeError(
            "Additional zones present in ICU, did you forget "
            "to run intl/update-tzdata.sh? %s" % additionalTimeZones
        )

    # Zones which are marked as links in ICU.
    result = ((zone, icuLinks[zone]) for zone in ianaZones if isICULink(zone))

    # Remove unnecessary UTC mappings.
    utcnames = ["Etc/UTC", "Etc/UCT", "Etc/GMT"]
    result = ((zone, target) for (zone, target) in result if zone.name not in utcnames)

    return sorted(result, key=itemgetter(0))


def findIncorrectICULinks(ianaZones, ianaLinks, icuZones, icuLinks):
    """Find incorrect ICU link entries."""

    def isIANATimeZone(zone):
        return zone in ianaZones or zone in ianaLinks

    def isICUTimeZone(zone):
        return zone in icuZones or zone in icuLinks

    def isICULink(zone):
        return zone in icuLinks

    def isICUZone(zone):
        return zone in icuZones

    # All links should be present in ICU.
    missingTimeZones = [zone for zone in ianaLinks.keys() if not isICUTimeZone(zone)]
    if missingTimeZones:
        raise RuntimeError(
            "Not all zones are present in ICU, did you forget "
            "to run intl/update-tzdata.sh? %s" % missingTimeZones
        )

    # Links which are only present in ICU?
    additionalTimeZones = [zone for zone in icuLinks.keys() if not isIANATimeZone(zone)]
    if additionalTimeZones:
        raise RuntimeError(
            "Additional links present in ICU, did you forget "
            "to run intl/update-tzdata.sh? %s" % additionalTimeZones
        )

    result = chain(
        # IANA links which have a different target in ICU.
        (
            (zone, target, icuLinks[zone])
            for (zone, target) in ianaLinks.items()
            if isICULink(zone) and target != icuLinks[zone]
        ),
        # IANA links which are zones in ICU.
        (
            (zone, target, zone.name)
            for (zone, target) in ianaLinks.items()
            if isICUZone(zone)
        ),
    )

    # Remove unnecessary UTC mappings.
    utcnames = ["Etc/UTC", "Etc/UCT", "Etc/GMT"]
    result = (
        (zone, target, icuTarget)
        for (zone, target, icuTarget) in result
        if target not in utcnames or icuTarget not in utcnames
    )

    return sorted(result, key=itemgetter(0))


generatedFileWarning = "// Generated by make_intl_data.py. DO NOT EDIT."
tzdataVersionComment = "// tzdata version = {0}"


def processTimeZones(
    tzdataDir, icuDir, icuTzDir, version, ignoreBackzone, ignoreFactory, out
):
    """Read the time zone info and create a new time zone cpp file."""
    print("Processing tzdata mapping...")
    (ianaZones, ianaLinks) = readIANATimeZones(tzdataDir, ignoreBackzone, ignoreFactory)
    (icuZones, icuLinks) = readICUTimeZones(icuDir, icuTzDir, ignoreFactory)
    (legacyZones, legacyLinks) = readICULegacyZones(icuDir)

    # Remove all legacy ICU time zones.
    icuZones = {zone for zone in icuZones if zone not in legacyZones}
    icuLinks = {
        zone: target for (zone, target) in icuLinks.items() if zone not in legacyLinks
    }

    incorrectZones = findIncorrectICUZones(
        ianaZones, ianaLinks, icuZones, icuLinks, ignoreBackzone
    )
    if not incorrectZones:
        print("<<< No incorrect ICU time zones found, please update Intl.js! >>>")
        print("<<< Maybe https://ssl.icu-project.org/trac/ticket/12044 was fixed? >>>")

    incorrectLinks = findIncorrectICULinks(ianaZones, ianaLinks, icuZones, icuLinks)
    if not incorrectLinks:
        print("<<< No incorrect ICU time zone links found, please update Intl.js! >>>")
        print("<<< Maybe https://ssl.icu-project.org/trac/ticket/12044 was fixed? >>>")

    print("Writing Intl tzdata file...")
    with io.open(out, mode="w", encoding="utf-8", newline="") as f:
        println = partial(print, file=f)

        println(generatedFileWarning)
        println(tzdataVersionComment.format(version))
        println("")

        println("#ifndef builtin_intl_TimeZoneDataGenerated_h")
        println("#define builtin_intl_TimeZoneDataGenerated_h")
        println("")

        println("namespace js {")
        println("namespace timezone {")
        println("")

        println("// Format:")
        println('// "ZoneName" // ICU-Name [time zone file]')
        println("const char* const ianaZonesTreatedAsLinksByICU[] = {")
        for (zone, icuZone) in incorrectZones:
            println('    "%s", // %s [%s]' % (zone, icuZone, zone.filename))
        println("};")
        println("")

        println("// Format:")
        println('// "LinkName", "Target" // ICU-Target [time zone file]')
        println("struct LinkAndTarget")
        println("{")
        println("    const char* const link;")
        println("    const char* const target;")
        println("};")
        println("")
        println("const LinkAndTarget ianaLinksCanonicalizedDifferentlyByICU[] = {")
        for (zone, target, icuTarget) in incorrectLinks:
            println(
                '    { "%s", "%s" }, // %s [%s]'
                % (zone, target, icuTarget, zone.filename)
            )
        println("};")
        println("")

        println(
            "// Legacy ICU time zones, these are not valid IANA time zone names. We also"
        )
        println("// disallow the old and deprecated System V time zones.")
        println(
            "// https://ssl.icu-project.org/repos/icu/trunk/icu4c/source/tools/tzcode/icuzones"
        )  # NOQA: E501
        println("const char* const legacyICUTimeZones[] = {")
        for zone in chain(sorted(legacyLinks.keys()), sorted(legacyZones)):
            println('    "%s",' % zone)
        println("};")
        println("")

        println("} // namespace timezone")
        println("} // namespace js")
        println("")
        println("#endif /* builtin_intl_TimeZoneDataGenerated_h */")


def updateBackzoneLinks(tzdataDir, links):
    def withZone(fn):
        return lambda zone_target: fn(zone_target[0])

    (backzoneZones, backzoneLinks) = readIANAFiles(tzdataDir, ["backzone"])
    (stableZones, updatedLinks, updatedZones) = partition(
        links.items(),
        # Link not changed in backzone.
        withZone(lambda zone: zone not in backzoneLinks and zone not in backzoneZones),
        # Link has a new target.
        withZone(lambda zone: zone in backzoneLinks),
    )
    # Keep stable zones and links with updated target.
    return dict(
        chain(
            stableZones,
            map(withZone(lambda zone: (zone, backzoneLinks[zone])), updatedLinks),
        )
    )


def generateTzDataLinkTestContent(testDir, version, fileName, description, links):
    with io.open(
        os.path.join(testDir, fileName), mode="w", encoding="utf-8", newline=""
    ) as f:
        println = partial(print, file=f)

        println('// |reftest| skip-if(!this.hasOwnProperty("Intl"))')
        println("")
        println(generatedFileWarning)
        println(tzdataVersionComment.format(version))
        println(
            """
const tzMapper = [
    x => x,
    x => x.toUpperCase(),
    x => x.toLowerCase(),
];
"""
        )

        println(description)
        println("const links = {")
        for (zone, target) in sorted(links, key=itemgetter(0)):
            println('    "%s": "%s",' % (zone, target))
        println("};")

        println(
            """
for (let [linkName, target] of Object.entries(links)) {
    if (target === "Etc/UTC" || target === "Etc/GMT")
        target = "UTC";

    for (let map of tzMapper) {
        let dtf = new Intl.DateTimeFormat(undefined, {timeZone: map(linkName)});
        let resolvedTimeZone = dtf.resolvedOptions().timeZone;
        assertEq(resolvedTimeZone, target, `${linkName} -> ${target}`);
    }
}
"""
        )
        println(
            """
if (typeof reportCompare === "function")
    reportCompare(0, 0, "ok");
"""
        )


def generateTzDataTestBackwardLinks(tzdataDir, version, ignoreBackzone, testDir):
    (zones, links) = readIANAFiles(tzdataDir, ["backward"])
    assert len(zones) == 0

    if not ignoreBackzone:
        links = updateBackzoneLinks(tzdataDir, links)

    generateTzDataLinkTestContent(
        testDir,
        version,
        "timeZone_backward_links.js",
        "// Link names derived from IANA Time Zone Database, backward file.",
        links.items(),
    )


def generateTzDataTestNotBackwardLinks(tzdataDir, version, ignoreBackzone, testDir):
    tzfiles = filterfalse(
        {"backward", "backzone"}.__contains__, listIANAFiles(tzdataDir)
    )
    (zones, links) = readIANAFiles(tzdataDir, tzfiles)

    if not ignoreBackzone:
        links = updateBackzoneLinks(tzdataDir, links)

    generateTzDataLinkTestContent(
        testDir,
        version,
        "timeZone_notbackward_links.js",
        "// Link names derived from IANA Time Zone Database, excluding backward file.",
        links.items(),
    )


def generateTzDataTestBackzone(tzdataDir, version, ignoreBackzone, testDir):
    backzoneFiles = {"backzone"}
    (bkfiles, tzfiles) = partition(listIANAFiles(tzdataDir), backzoneFiles.__contains__)

    # Read zone and link infos.
    (zones, links) = readIANAFiles(tzdataDir, tzfiles)
    (backzones, backlinks) = readIANAFiles(tzdataDir, bkfiles)

    if not ignoreBackzone:
        comment = """\
// This file was generated with historical, pre-1970 backzone information
// respected. Therefore, every zone key listed below is its own Zone, not
// a Link to a modern-day target as IANA ignoring backzones would say.

"""
    else:
        comment = """\
// This file was generated while ignoring historical, pre-1970 backzone
// information. Therefore, every zone key listed below is part of a Link
// whose target is the corresponding value.

"""

    generateTzDataLinkTestContent(
        testDir,
        version,
        "timeZone_backzone.js",
        comment + "// Backzone zones derived from IANA Time Zone Database.",
        (
            (zone, zone if not ignoreBackzone else links[zone])
            for zone in backzones
            if zone in links
        ),
    )


def generateTzDataTestBackzoneLinks(tzdataDir, version, ignoreBackzone, testDir):
    backzoneFiles = {"backzone"}
    (bkfiles, tzfiles) = partition(listIANAFiles(tzdataDir), backzoneFiles.__contains__)

    # Read zone and link infos.
    (zones, links) = readIANAFiles(tzdataDir, tzfiles)
    (backzones, backlinks) = readIANAFiles(tzdataDir, bkfiles)

    if not ignoreBackzone:
        comment = """\
// This file was generated with historical, pre-1970 backzone information
// respected. Therefore, every zone key listed below points to a target
// in the backzone file and not to its modern-day target as IANA ignoring
// backzones would say.

"""
    else:
        comment = """\
// This file was generated while ignoring historical, pre-1970 backzone
// information. Therefore, every zone key listed below is part of a Link
// whose target is the corresponding value ignoring any backzone entries.

"""

    generateTzDataLinkTestContent(
        testDir,
        version,
        "timeZone_backzone_links.js",
        comment + "// Backzone links derived from IANA Time Zone Database.",
        (
            (zone, target if not ignoreBackzone else links[zone])
            for (zone, target) in backlinks.items()
        ),
    )


def generateTzDataTestVersion(tzdataDir, version, testDir):
    fileName = "timeZone_version.js"

    with io.open(
        os.path.join(testDir, fileName), mode="w", encoding="utf-8", newline=""
    ) as f:
        println = partial(print, file=f)

        println('// |reftest| skip-if(!this.hasOwnProperty("Intl"))')
        println("")
        println(generatedFileWarning)
        println(tzdataVersionComment.format(version))
        println("""const tzdata = "{0}";""".format(version))

        println(
            """
if (typeof getICUOptions === "undefined") {
    var getICUOptions = SpecialPowers.Cu.getJSTestingFunctions().getICUOptions;
}

var options = getICUOptions();

assertEq(options.tzdata, tzdata);

if (typeof reportCompare === "function")
    reportCompare(0, 0, "ok");
"""
        )


def generateTzDataTestCanonicalZones(
    tzdataDir, version, ignoreBackzone, ignoreFactory, testDir
):
    fileName = "supportedValuesOf-timeZones-canonical.js"

    # Read zone and link infos.
    (ianaZones, _) = readIANATimeZones(tzdataDir, ignoreBackzone, ignoreFactory)

    # Replace Etc/GMT and Etc/UTC with UTC.
    ianaZones.remove(Zone("Etc/GMT"))
    ianaZones.remove(Zone("Etc/UTC"))
    ianaZones.add(Zone("UTC"))

    # See findIncorrectICUZones() for why Asia/Hanoi has to be special-cased.
    ianaZones.remove(Zone("Asia/Hanoi"))

    if not ignoreBackzone:
        comment = """\
// This file was generated with historical, pre-1970 backzone information
// respected.
"""
    else:
        comment = """\
// This file was generated while ignoring historical, pre-1970 backzone
// information.
"""

    with io.open(
        os.path.join(testDir, fileName), mode="w", encoding="utf-8", newline=""
    ) as f:
        println = partial(print, file=f)

        println('// |reftest| skip-if(!this.hasOwnProperty("Intl"))')
        println("")
        println(generatedFileWarning)
        println(tzdataVersionComment.format(version))
        println("")
        println(comment)

        println("const zones = [")
        for zone in sorted(ianaZones):
            println(f'  "{zone}",')
        println("];")

        println(
            """
let supported = Intl.supportedValuesOf("timeZone");

assertEqArray(supported, zones);

if (typeof reportCompare === "function")
    reportCompare(0, 0, "ok");
"""
        )


def generateTzDataTests(tzdataDir, version, ignoreBackzone, ignoreFactory, testDir):
    dtfTestDir = os.path.join(testDir, "DateTimeFormat")
    if not os.path.isdir(dtfTestDir):
        raise RuntimeError("not a directory: %s" % dtfTestDir)

    generateTzDataTestBackwardLinks(tzdataDir, version, ignoreBackzone, dtfTestDir)
    generateTzDataTestNotBackwardLinks(tzdataDir, version, ignoreBackzone, dtfTestDir)
    generateTzDataTestBackzone(tzdataDir, version, ignoreBackzone, dtfTestDir)
    generateTzDataTestBackzoneLinks(tzdataDir, version, ignoreBackzone, dtfTestDir)
    generateTzDataTestVersion(tzdataDir, version, dtfTestDir)
    generateTzDataTestCanonicalZones(
        tzdataDir, version, ignoreBackzone, ignoreFactory, testDir
    )


def updateTzdata(topsrcdir, args):
    """Update the time zone cpp file."""

    icuDir = os.path.join(topsrcdir, "intl/icu/source")
    if not os.path.isdir(icuDir):
        raise RuntimeError("not a directory: %s" % icuDir)

    icuTzDir = os.path.join(topsrcdir, "intl/tzdata/source")
    if not os.path.isdir(icuTzDir):
        raise RuntimeError("not a directory: %s" % icuTzDir)

    intlTestDir = os.path.join(topsrcdir, "js/src/tests/non262/Intl")
    if not os.path.isdir(intlTestDir):
        raise RuntimeError("not a directory: %s" % intlTestDir)

    tzDir = args.tz
    if tzDir is not None and not (os.path.isdir(tzDir) or os.path.isfile(tzDir)):
        raise RuntimeError("not a directory or file: %s" % tzDir)
    ignoreBackzone = args.ignore_backzone
    # TODO: Accept or ignore the placeholder time zone "Factory"?
    ignoreFactory = False
    out = args.out

    version = icuTzDataVersion(icuTzDir)
    url = (
        "https://www.iana.org/time-zones/repository/releases/tzdata%s.tar.gz" % version
    )

    print("Arguments:")
    print("\ttzdata version: %s" % version)
    print("\ttzdata URL: %s" % url)
    print("\ttzdata directory|file: %s" % tzDir)
    print("\tICU directory: %s" % icuDir)
    print("\tICU timezone directory: %s" % icuTzDir)
    print("\tIgnore backzone file: %s" % ignoreBackzone)
    print("\tOutput file: %s" % out)
    print("")

    def updateFrom(f):
        if os.path.isfile(f) and tarfile.is_tarfile(f):
            with tarfile.open(f, "r:*") as tar:
                processTimeZones(
                    TzDataFile(tar),
                    icuDir,
                    icuTzDir,
                    version,
                    ignoreBackzone,
                    ignoreFactory,
                    out,
                )
                generateTzDataTests(
                    TzDataFile(tar), version, ignoreBackzone, ignoreFactory, intlTestDir
                )
        elif os.path.isdir(f):
            processTimeZones(
                TzDataDir(f),
                icuDir,
                icuTzDir,
                version,
                ignoreBackzone,
                ignoreFactory,
                out,
            )
            generateTzDataTests(
                TzDataDir(f), version, ignoreBackzone, ignoreFactory, intlTestDir
            )
        else:
            raise RuntimeError("unknown format")

    if tzDir is None:
        print("Downloading tzdata file...")
        with closing(urlopen(url)) as tzfile:
            fname = urlsplit(tzfile.geturl()).path.split("/")[-1]
            with tempfile.NamedTemporaryFile(suffix=fname) as tztmpfile:
                print("File stored in %s" % tztmpfile.name)
                tztmpfile.write(tzfile.read())
                tztmpfile.flush()
                updateFrom(tztmpfile.name)
    else:
        updateFrom(tzDir)


def readCurrencyFile(tree):
    reCurrency = re.compile(r"^[A-Z]{3}$")
    reIntMinorUnits = re.compile(r"^\d+$")

    for country in tree.iterfind(".//CcyNtry"):
        # Skip entry if no currency information is available.
        currency = country.findtext("Ccy")
        if currency is None:
            continue
        assert reCurrency.match(currency)

        minorUnits = country.findtext("CcyMnrUnts")
        assert minorUnits is not None

        # Skip all entries without minorUnits or which use the default minorUnits.
        if reIntMinorUnits.match(minorUnits) and int(minorUnits) != 2:
            currencyName = country.findtext("CcyNm")
            countryName = country.findtext("CtryNm")
            yield (currency, int(minorUnits), currencyName, countryName)


def writeCurrencyFile(published, currencies, out):
    with io.open(out, mode="w", encoding="utf-8", newline="") as f:
        println = partial(print, file=f)

        println(generatedFileWarning)
        println("// Version: {}".format(published))

        println(
            """
/**
 * Mapping from currency codes to the number of decimal digits used for them.
 * Default is 2 digits.
 *
 * Spec: ISO 4217 Currency and Funds Code List.
 * http://www.currency-iso.org/en/home/tables/table-a1.html
 */"""
        )
        println("var currencyDigits = {")
        for (currency, entries) in groupby(
            sorted(currencies, key=itemgetter(0)), itemgetter(0)
        ):
            for (_, minorUnits, currencyName, countryName) in entries:
                println("  // {} ({})".format(currencyName, countryName))
            println("  {}: {},".format(currency, minorUnits))
        println("};")


def updateCurrency(topsrcdir, args):
    """Update the CurrencyDataGenerated.js file."""
    import xml.etree.ElementTree as ET
    from random import randint

    url = args.url
    out = args.out
    filename = args.file

    print("Arguments:")
    print("\tDownload url: %s" % url)
    print("\tLocal currency file: %s" % filename)
    print("\tOutput file: %s" % out)
    print("")

    def updateFrom(currencyFile):
        print("Processing currency code list file...")
        tree = ET.parse(currencyFile)
        published = tree.getroot().attrib["Pblshd"]
        currencies = readCurrencyFile(tree)

        print("Writing CurrencyData file...")
        writeCurrencyFile(published, currencies, out)

    if filename is not None:
        print("Always make sure you have the newest currency code list file!")
        updateFrom(filename)
    else:
        print("Downloading currency & funds code list...")
        request = UrlRequest(url)
        request.add_header(
            "User-agent",
            "Mozilla/5.0 (Mobile; rv:{0}.0) Gecko/{0}.0 Firefox/{0}.0".format(
                randint(1, 999)
            ),
        )
        with closing(urlopen(request)) as currencyFile:
            fname = urlsplit(currencyFile.geturl()).path.split("/")[-1]
            with tempfile.NamedTemporaryFile(suffix=fname) as currencyTmpFile:
                print("File stored in %s" % currencyTmpFile.name)
                currencyTmpFile.write(currencyFile.read())
                currencyTmpFile.flush()
                updateFrom(currencyTmpFile.name)


def writeUnicodeExtensionsMappings(println, mapping, extension):
    println(
        """
template <size_t Length>
static inline bool Is{0}Key(mozilla::Span<const char> key, const char (&str)[Length]) {{
  static_assert(Length == {0}KeyLength + 1,
                "{0} extension key is two characters long");
  return memcmp(key.data(), str, Length - 1) == 0;
}}

template <size_t Length>
static inline bool Is{0}Type(mozilla::Span<const char> type, const char (&str)[Length]) {{
  static_assert(Length > {0}KeyLength + 1,
                "{0} extension type contains more than two characters");
  return type.size() == (Length - 1) &&
         memcmp(type.data(), str, Length - 1) == 0;
}}
""".format(
            extension
        ).rstrip(
            "\n"
        )
    )

    linear_search_max_length = 4

    needs_binary_search = any(
        len(replacements.items()) > linear_search_max_length
        for replacements in mapping.values()
    )

    if needs_binary_search:
        println(
            """
static int32_t Compare{0}Type(const char* a, mozilla::Span<const char> b) {{
  MOZ_ASSERT(!std::char_traits<char>::find(b.data(), b.size(), '\\0'),
             "unexpected null-character in string");

  using UnsignedChar = unsigned char;
  for (size_t i = 0; i < b.size(); i++) {{
    // |a| is zero-terminated and |b| doesn't contain a null-terminator. So if
    // we've reached the end of |a|, the below if-statement will always be true.
    // That ensures we don't read past the end of |a|.
    if (int32_t r = UnsignedChar(a[i]) - UnsignedChar(b[i])) {{
      return r;
    }}
  }}

  // Return zero if both strings are equal or a positive number if |b| is a
  // prefix of |a|.
  return int32_t(UnsignedChar(a[b.size()]));
}}

template <size_t Length>
static inline const char* Search{0}Replacement(
  const char* (&types)[Length], const char* (&aliases)[Length],
  mozilla::Span<const char> type) {{

  auto p = std::lower_bound(std::begin(types), std::end(types), type,
                            [](const auto& a, const auto& b) {{
                              return Compare{0}Type(a, b) < 0;
                            }});
  if (p != std::end(types) && Compare{0}Type(*p, type) == 0) {{
    return aliases[std::distance(std::begin(types), p)];
  }}
  return nullptr;
}}
""".format(
                extension
            ).rstrip(
                "\n"
            )
        )

    println(
        """
/**
 * Mapping from deprecated BCP 47 {0} extension types to their preferred
 * values.
 *
 * Spec: https://www.unicode.org/reports/tr35/#Unicode_Locale_Extension_Data_Files
 * Spec: https://www.unicode.org/reports/tr35/#t_Extension
 */
const char* mozilla::intl::Locale::Replace{0}ExtensionType(
    mozilla::Span<const char> key, mozilla::Span<const char> type) {{
  MOZ_ASSERT(key.size() == {0}KeyLength);
  MOZ_ASSERT(IsCanonicallyCased{0}Key(key));

  MOZ_ASSERT(type.size() > {0}KeyLength);
  MOZ_ASSERT(IsCanonicallyCased{0}Type(type));
""".format(
            extension
        )
    )

    def to_hash_key(replacements):
        return str(sorted(replacements.items()))

    def write_array(subtags, name, length):
        max_entries = (80 - len("    ")) // (length + len('"", '))

        println("    static const char* {}[{}] = {{".format(name, len(subtags)))

        for entries in grouper(subtags, max_entries):
            entries = (
                '"{}"'.format(tag).center(length + 2)
                for tag in entries
                if tag is not None
            )
            println("        {},".format(", ".join(entries)))

        println("    };")

    # Merge duplicate keys.
    key_aliases = {}
    for (key, replacements) in sorted(mapping.items(), key=itemgetter(0)):
        hash_key = to_hash_key(replacements)
        if hash_key not in key_aliases:
            key_aliases[hash_key] = []
        else:
            key_aliases[hash_key].append(key)

    first_key = True
    for (key, replacements) in sorted(mapping.items(), key=itemgetter(0)):
        hash_key = to_hash_key(replacements)
        if key in key_aliases[hash_key]:
            continue

        cond = (
            'Is{}Key(key, "{}")'.format(extension, k)
            for k in [key] + key_aliases[hash_key]
        )

        if_kind = "if" if first_key else "else if"
        cond = (" ||\n" + " " * (2 + len(if_kind) + 2)).join(cond)
        println(
            """
  {} ({}) {{""".format(
                if_kind, cond
            ).strip(
                "\n"
            )
        )
        first_key = False

        replacements = sorted(replacements.items(), key=itemgetter(0))

        if len(replacements) > linear_search_max_length:
            types = [t for (t, _) in replacements]
            preferred = [r for (_, r) in replacements]
            max_len = max(len(k) for k in types + preferred)

            write_array(types, "types", max_len)
            write_array(preferred, "aliases", max_len)
            println(
                """
    return Search{}Replacement(types, aliases, type);
""".format(
                    extension
                ).strip(
                    "\n"
                )
            )
        else:
            for (type, replacement) in replacements:
                println(
                    """
    if (Is{}Type(type, "{}")) {{
      return "{}";
    }}""".format(
                        extension, type, replacement
                    ).strip(
                        "\n"
                    )
                )

        println(
            """
  }""".lstrip(
                "\n"
            )
        )

    println(
        """
  return nullptr;
}
""".strip(
            "\n"
        )
    )


def readICUUnitResourceFile(filepath):
    """Return a set of unit descriptor pairs where the first entry denotes the unit type and the
    second entry the unit name.

    Example:

    root{
        units{
            compound{
            }
            coordinate{
            }
            length{
                meter{
                }
            }
        }
        unitsNarrow:alias{"/LOCALE/unitsShort"}
        unitsShort{
            duration{
                day{
                }
                day-person:alias{"/LOCALE/unitsShort/duration/day"}
            }
            length{
                meter{
                }
            }
        }
    }

    Returns {("length", "meter"), ("duration", "day"), ("duration", "day-person")}
    """

    start_table_re = re.compile(r"^([\w\-%:\"]+)\{$")
    end_table_re = re.compile(r"^\}$")
    table_entry_re = re.compile(r"^([\w\-%:\"]+)\{\"(.*?)\"\}$")

    # The current resource table.
    table = {}

    # List of parent tables when parsing.
    parents = []

    # Track multi-line comments state.
    in_multiline_comment = False

    for line in flines(filepath, "utf-8-sig"):
        # Remove leading and trailing whitespace.
        line = line.strip()

        # Skip over comments.
        if in_multiline_comment:
            if line.endswith("*/"):
                in_multiline_comment = False
            continue

        if line.startswith("//"):
            continue

        if line.startswith("/*"):
            in_multiline_comment = True
            continue

        # Try to match the start of a table, e.g. `length{` or `meter{`.
        match = start_table_re.match(line)
        if match:
            parents.append(table)
            table_name = match.group(1)
            new_table = {}
            table[table_name] = new_table
            table = new_table
            continue

        # Try to match the end of a table.
        match = end_table_re.match(line)
        if match:
            table = parents.pop()
            continue

        # Try to match a table entry, e.g. `dnam{"meter"}`.
        match = table_entry_re.match(line)
        if match:
            entry_key = match.group(1)
            entry_value = match.group(2)
            table[entry_key] = entry_value
            continue

        raise Exception("unexpected line: '{}' in {}".format(line, filepath))

    assert len(parents) == 0, "Not all tables closed"
    assert len(table) == 1, "More than one root table"

    # Remove the top-level language identifier table.
    (_, unit_table) = table.popitem()

    # Add all units for the three display formats "units", "unitsNarrow", and "unitsShort".
    # But exclude the pseudo-units "compound" and "ccoordinate".
    return {
        (unit_type, unit_name if not unit_name.endswith(":alias") else unit_name[:-6])
        for unit_display in ("units", "unitsNarrow", "unitsShort")
        if unit_display in unit_table
        for (unit_type, unit_names) in unit_table[unit_display].items()
        if unit_type != "compound" and unit_type != "coordinate"
        for unit_name in unit_names.keys()
    }


def computeSupportedUnits(all_units, sanctioned_units):
    """Given the set of all possible ICU unit identifiers and the set of sanctioned unit
    identifiers, compute the set of effectively supported ICU unit identifiers.
    """

    def find_match(unit):
        unit_match = [
            (unit_type, unit_name)
            for (unit_type, unit_name) in all_units
            if unit_name == unit
        ]
        if unit_match:
            assert len(unit_match) == 1
            return unit_match[0]
        return None

    def compound_unit_identifiers():
        for numerator in sanctioned_units:
            for denominator in sanctioned_units:
                yield "{}-per-{}".format(numerator, denominator)

    supported_simple_units = {find_match(unit) for unit in sanctioned_units}
    assert None not in supported_simple_units

    supported_compound_units = {
        unit_match
        for unit_match in (find_match(unit) for unit in compound_unit_identifiers())
        if unit_match
    }

    return supported_simple_units | supported_compound_units


def readICUDataFilterForUnits(data_filter_file):
    with io.open(data_filter_file, mode="r", encoding="utf-8") as f:
        data_filter = json.load(f)

    # Find the rule set for the "unit_tree".
    unit_tree_rules = [
        entry["rules"]
        for entry in data_filter["resourceFilters"]
        if entry["categories"] == ["unit_tree"]
    ]
    assert len(unit_tree_rules) == 1

    # Compute the list of included units from that rule set. The regular expression must match
    # "+/*/length/meter" and mustn't match either "-/*" or "+/*/compound".
    included_unit_re = re.compile(r"^\+/\*/(.+?)/(.+)$")
    filtered_units = (included_unit_re.match(unit) for unit in unit_tree_rules[0])

    return {(unit.group(1), unit.group(2)) for unit in filtered_units if unit}


def writeSanctionedSimpleUnitIdentifiersFiles(all_units, sanctioned_units):
    js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
    intl_components_src_dir = os.path.join(
        js_src_builtin_intl_dir, "../../../../intl/components/src"
    )

    def find_unit_type(unit):
        result = [
            unit_type for (unit_type, unit_name) in all_units if unit_name == unit
        ]
        assert result and len(result) == 1
        return result[0]

    sanctioned_js_file = os.path.join(
        js_src_builtin_intl_dir, "SanctionedSimpleUnitIdentifiersGenerated.js"
    )
    with io.open(sanctioned_js_file, mode="w", encoding="utf-8", newline="") as f:
        println = partial(print, file=f)

        sanctioned_units_object = json.dumps(
            {unit: True for unit in sorted(sanctioned_units)},
            sort_keys=True,
            indent=2,
            separators=(",", ": "),
        )

        println(generatedFileWarning)

        println(
            """
/**
 * The list of currently supported simple unit identifiers.
 *
 * Intl.NumberFormat Unified API Proposal
 */"""
        )

        println("/* eslint-disable prettier/prettier */")
        println(
            "var sanctionedSimpleUnitIdentifiers = {};".format(sanctioned_units_object)
        )
        println("/* eslint-enable prettier/prettier */")

    sanctioned_h_file = os.path.join(intl_components_src_dir, "MeasureUnitGenerated.h")
    with io.open(sanctioned_h_file, mode="w", encoding="utf-8", newline="") as f:
        println = partial(print, file=f)

        println(generatedFileWarning)

        println(
            """
#ifndef intl_components_MeasureUnitGenerated_h
#define intl_components_MeasureUnitGenerated_h

namespace mozilla::intl {

struct SimpleMeasureUnit {
  const char* const type;
  const char* const name;
};

/**
 * The list of currently supported simple unit identifiers.
 *
 * The list must be kept in alphabetical order of |name|.
 */
inline constexpr SimpleMeasureUnit simpleMeasureUnits[] = {
    // clang-format off"""
        )

        for unit_name in sorted(sanctioned_units):
            println('  {{"{}", "{}"}},'.format(find_unit_type(unit_name), unit_name))

        println(
            """
    // clang-format on
};

}  // namespace mozilla::intl

#endif
""".strip(
                "\n"
            )
        )

    writeUnitTestFiles(all_units, sanctioned_units)


def writeUnitTestFiles(all_units, sanctioned_units):
    """Generate test files for unit number formatters."""

    js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
    test_dir = os.path.join(
        js_src_builtin_intl_dir, "../../tests/non262/Intl/NumberFormat"
    )

    def write_test(file_name, test_content, indent=4):
        file_path = os.path.join(test_dir, file_name)
        with io.open(file_path, mode="w", encoding="utf-8", newline="") as f:
            println = partial(print, file=f)

            println('// |reftest| skip-if(!this.hasOwnProperty("Intl"))')
            println("")
            println(generatedFileWarning)
            println("")

            sanctioned_units_array = json.dumps(
                [unit for unit in sorted(sanctioned_units)],
                indent=indent,
                separators=(",", ": "),
            )

            println(
                "const sanctionedSimpleUnitIdentifiers = {};".format(
                    sanctioned_units_array
                )
            )

            println(test_content)

            println(
                """
if (typeof reportCompare === "function")
{}reportCompare(true, true);""".format(
                    " " * indent
                )
            )

    write_test(
        "unit-compound-combinations.js",
        """
// Test all simple unit identifier combinations are allowed.

for (const numerator of sanctionedSimpleUnitIdentifiers) {
    for (const denominator of sanctionedSimpleUnitIdentifiers) {
        const unit = `${numerator}-per-${denominator}`;
        const nf = new Intl.NumberFormat("en", {style: "unit", unit});

        assertEq(nf.format(1), nf.formatToParts(1).map(p => p.value).join(""));
    }
}""",
    )

    all_units_array = json.dumps(
        ["-".join(unit) for unit in sorted(all_units)], indent=4, separators=(",", ": ")
    )

    write_test(
        "unit-well-formed.js",
        """
const allUnits = {};
""".format(
            all_units_array
        )
        + """
// Test only sanctioned unit identifiers are allowed.

for (const typeAndUnit of allUnits) {
    const [_, type, unit] = typeAndUnit.match(/(\w+)-(.+)/);

    let allowed;
    if (unit.includes("-per-")) {
        const [numerator, denominator] = unit.split("-per-");
        allowed = sanctionedSimpleUnitIdentifiers.includes(numerator) &&
                  sanctionedSimpleUnitIdentifiers.includes(denominator);
    } else {
        allowed = sanctionedSimpleUnitIdentifiers.includes(unit);
    }

    if (allowed) {
        const nf = new Intl.NumberFormat("en", {style: "unit", unit});
        assertEq(nf.format(1), nf.formatToParts(1).map(p => p.value).join(""));
    } else {
        assertThrowsInstanceOf(() => new Intl.NumberFormat("en", {style: "unit", unit}),
                               RangeError, `Missing error for "${typeAndUnit}"`);
    }
}""",
    )

    write_test(
        "unit-formatToParts-has-unit-field.js",
        """
// Test only English and Chinese to keep the overall runtime reasonable.
//
// Chinese is included because it contains more than one "unit" element for
// certain unit combinations.
const locales = ["en", "zh"];

// Plural rules for English only differentiate between "one" and "other". Plural
// rules for Chinese only use "other". That means we only need to test two values
// per unit.
const values = [0, 1];

// Ensure unit formatters contain at least one "unit" element.

for (const locale of locales) {
  for (const unit of sanctionedSimpleUnitIdentifiers) {
    const nf = new Intl.NumberFormat(locale, {style: "unit", unit});

    for (const value of values) {
      assertEq(nf.formatToParts(value).some(e => e.type === "unit"), true,
               `locale=${locale}, unit=${unit}`);
    }
  }

  for (const numerator of sanctionedSimpleUnitIdentifiers) {
    for (const denominator of sanctionedSimpleUnitIdentifiers) {
      const unit = `${numerator}-per-${denominator}`;
      const nf = new Intl.NumberFormat(locale, {style: "unit", unit});

      for (const value of values) {
        assertEq(nf.formatToParts(value).some(e => e.type === "unit"), true,
                 `locale=${locale}, unit=${unit}`);
      }
    }
  }
}""",
        indent=2,
    )


def updateUnits(topsrcdir, args):
    js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
    icu_path = os.path.join(topsrcdir, "intl", "icu")
    icu_unit_path = os.path.join(icu_path, "source", "data", "unit")

    with io.open(
        os.path.join(js_src_builtin_intl_dir, "SanctionedSimpleUnitIdentifiers.yaml"),
        mode="r",
        encoding="utf-8",
    ) as f:
        sanctioned_units = yaml.safe_load(f)

    # Read all possible ICU unit identifiers from the "unit/root.txt" resource.
    unit_root_file = os.path.join(icu_unit_path, "root.txt")
    all_units = readICUUnitResourceFile(unit_root_file)

    # Compute the set of effectively supported ICU unit identifiers.
    supported_units = computeSupportedUnits(all_units, sanctioned_units)

    # Read the list of units we're including into the ICU data file.
    data_filter_file = os.path.join(icu_path, "data_filter.json")
    filtered_units = readICUDataFilterForUnits(data_filter_file)

    # Both sets must match to avoid resource loading errors at runtime.
    if supported_units != filtered_units:

        def units_to_string(units):
            return ", ".join("/".join(u) for u in units)

        missing = supported_units - filtered_units
        if missing:
            raise RuntimeError("Missing units: {}".format(units_to_string(missing)))

        # Not exactly an error, but we currently don't have a use case where we need to support
        # more units than required by ECMA-402.
        extra = filtered_units - supported_units
        if extra:
            raise RuntimeError("Unnecessary units: {}".format(units_to_string(extra)))

    writeSanctionedSimpleUnitIdentifiersFiles(all_units, sanctioned_units)


def readICUNumberingSystemsResourceFile(filepath):
    """Returns a dictionary of numbering systems where the key denotes the numbering system name
    and the value a dictionary with additional numbering system data.

    Example:

    numberingSystems:table(nofallback){
        numberingSystems{
            latn{
                algorithmic:int{0}
                desc{"0123456789"}
                radix:int{10}
            }
            roman{
                algorithmic:int{1}
                desc{"%roman-upper"}
                radix:int{10}
            }
        }
    }

    Returns {"latn": {"digits": "0123456789", "algorithmic": False},
             "roman": {"algorithmic": True}}
    """

    start_table_re = re.compile(r"^(\w+)(?:\:[\w\(\)]+)?\{$")
    end_table_re = re.compile(r"^\}$")
    table_entry_re = re.compile(r"^(\w+)(?:\:[\w\(\)]+)?\{(?:(?:\"(.*?)\")|(\d+))\}$")

    # The current resource table.
    table = {}

    # List of parent tables when parsing.
    parents = []

    # Track multi-line comments state.
    in_multiline_comment = False

    for line in flines(filepath, "utf-8-sig"):
        # Remove leading and trailing whitespace.
        line = line.strip()

        # Skip over comments.
        if in_multiline_comment:
            if line.endswith("*/"):
                in_multiline_comment = False
            continue

        if line.startswith("//"):
            continue

        if line.startswith("/*"):
            in_multiline_comment = True
            continue

        # Try to match the start of a table, e.g. `latn{`.
        match = start_table_re.match(line)
        if match:
            parents.append(table)
            table_name = match.group(1)
            new_table = {}
            table[table_name] = new_table
            table = new_table
            continue

        # Try to match the end of a table.
        match = end_table_re.match(line)
        if match:
            table = parents.pop()
            continue

        # Try to match a table entry, e.g. `desc{"0123456789"}`.
        match = table_entry_re.match(line)
        if match:
            entry_key = match.group(1)
            entry_value = (
                match.group(2) if match.group(2) is not None else int(match.group(3))
            )
            table[entry_key] = entry_value
            continue

        raise Exception("unexpected line: '{}' in {}".format(line, filepath))

    assert len(parents) == 0, "Not all tables closed"
    assert len(table) == 1, "More than one root table"

    # Remove the two top-level "numberingSystems" tables.
    (_, numbering_systems) = table.popitem()
    (_, numbering_systems) = numbering_systems.popitem()

    # Assert all numbering systems use base 10.
    assert all(ns["radix"] == 10 for ns in numbering_systems.values())

    # Return the numbering systems.
    return {
        key: {"digits": value["desc"], "algorithmic": False}
        if not bool(value["algorithmic"])
        else {"algorithmic": True}
        for (key, value) in numbering_systems.items()
    }


def writeNumberingSystemFiles(numbering_systems):
    js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))

    numbering_systems_js_file = os.path.join(
        js_src_builtin_intl_dir, "NumberingSystemsGenerated.h"
    )
    with io.open(
        numbering_systems_js_file, mode="w", encoding="utf-8", newline=""
    ) as f:
        println = partial(print, file=f)

        println(generatedFileWarning)

        println(
            """
/**
 * The list of numbering systems with simple digit mappings.
 */

#ifndef builtin_intl_NumberingSystemsGenerated_h
#define builtin_intl_NumberingSystemsGenerated_h
"""
        )

        simple_numbering_systems = sorted(
            name
            for (name, value) in numbering_systems.items()
            if not value["algorithmic"]
        )

        println("// clang-format off")
        println("#define NUMBERING_SYSTEMS_WITH_SIMPLE_DIGIT_MAPPINGS \\")
        println(
            "{}".format(
                ", \\\n".join(
                    '  "{}"'.format(name) for name in simple_numbering_systems
                )
            )
        )
        println("// clang-format on")
        println("")

        println("#endif  // builtin_intl_NumberingSystemsGenerated_h")

    js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
    test_dir = os.path.join(js_src_builtin_intl_dir, "../../tests/non262/Intl")

    intl_shell_js_file = os.path.join(test_dir, "shell.js")

    with io.open(intl_shell_js_file, mode="w", encoding="utf-8", newline="") as f:
        println = partial(print, file=f)

        println(generatedFileWarning)

        println(
            """
// source: CLDR file common/bcp47/number.xml; version CLDR {}.
// https://github.com/unicode-org/cldr/blob/master/common/bcp47/number.xml
// https://github.com/unicode-org/cldr/blob/master/common/supplemental/numberingSystems.xml
""".format(
                readCLDRVersionFromICU()
            ).rstrip()
        )

        numbering_systems_object = json.dumps(
            numbering_systems,
            indent=2,
            separators=(",", ": "),
            sort_keys=True,
            ensure_ascii=False,
        )
        println("const numberingSystems = {};".format(numbering_systems_object))


def updateNumberingSystems(topsrcdir, args):
    js_src_builtin_intl_dir = os.path.dirname(os.path.abspath(__file__))
    icu_path = os.path.join(topsrcdir, "intl", "icu")
    icu_misc_path = os.path.join(icu_path, "source", "data", "misc")

    with io.open(
        os.path.join(js_src_builtin_intl_dir, "NumberingSystems.yaml"),
        mode="r",
        encoding="utf-8",
    ) as f:
        numbering_systems = yaml.safe_load(f)

    # Read all possible ICU unit identifiers from the "misc/numberingSystems.txt" resource.
    misc_ns_file = os.path.join(icu_misc_path, "numberingSystems.txt")
    all_numbering_systems = readICUNumberingSystemsResourceFile(misc_ns_file)

    all_numbering_systems_simple_digits = {
        name
        for (name, value) in all_numbering_systems.items()
        if not value["algorithmic"]
    }

    # Assert ICU includes support for all required numbering systems. If this assertion fails,
    # something is broken in ICU.
    assert all_numbering_systems_simple_digits.issuperset(
        numbering_systems
    ), "{}".format(numbering_systems.difference(all_numbering_systems_simple_digits))

    # Assert the spec requires support for all numbering systems with simple digit mappings. If
    # this assertion fails, file a PR at <https://github.com/tc39/ecma402> to include any new
    # numbering systems.
    assert all_numbering_systems_simple_digits.issubset(numbering_systems), "{}".format(
        all_numbering_systems_simple_digits.difference(numbering_systems)
    )

    writeNumberingSystemFiles(all_numbering_systems)


if __name__ == "__main__":
    import argparse

    # This script must reside in js/src/builtin/intl to work correctly.
    (thisDir, thisFile) = os.path.split(os.path.abspath(__file__))
    dirPaths = os.path.normpath(thisDir).split(os.sep)
    if "/".join(dirPaths[-4:]) != "js/src/builtin/intl":
        raise RuntimeError("%s must reside in js/src/builtin/intl" % __file__)
    topsrcdir = "/".join(dirPaths[:-4])

    def EnsureHttps(v):
        if not v.startswith("https:"):
            raise argparse.ArgumentTypeError("URL protocol must be https: " % v)
        return v

    parser = argparse.ArgumentParser(description="Update intl data.")
    subparsers = parser.add_subparsers(help="Select update mode")

    parser_cldr_tags = subparsers.add_parser(
        "langtags", help="Update CLDR language tags data"
    )
    parser_cldr_tags.add_argument(
        "--version", metavar="VERSION", help="CLDR version number"
    )
    parser_cldr_tags.add_argument(
        "--url",
        metavar="URL",
        default="https://unicode.org/Public/cldr/<VERSION>/core.zip",
        type=EnsureHttps,
        help="Download url CLDR data (default: %(default)s)",
    )
    parser_cldr_tags.add_argument(
        "--out",
        default=os.path.join(
            topsrcdir, "intl", "components", "src", "LocaleGenerated.cpp"
        ),
        help="Output file (default: %(default)s)",
    )
    parser_cldr_tags.add_argument(
        "file", nargs="?", help="Local cldr-core.zip file, if omitted uses <URL>"
    )
    parser_cldr_tags.set_defaults(func=updateCLDRLangTags)

    parser_tz = subparsers.add_parser("tzdata", help="Update tzdata")
    parser_tz.add_argument(
        "--tz",
        help="Local tzdata directory or file, if omitted downloads tzdata "
        "distribution from https://www.iana.org/time-zones/",
    )
    # ICU doesn't include the backzone file by default, but we still like to
    # use the backzone time zone names to avoid user confusion. This does lead
    # to formatting "historic" dates (pre-1970 era) with the wrong time zone,
    # but that's probably acceptable for now.
    parser_tz.add_argument(
        "--ignore-backzone",
        action="store_true",
        help="Ignore tzdata's 'backzone' file. Can be enabled to generate more "
        "accurate time zone canonicalization reflecting the actual time "
        "zones as used by ICU.",
    )
    parser_tz.add_argument(
        "--out",
        default=os.path.join(thisDir, "TimeZoneDataGenerated.h"),
        help="Output file (default: %(default)s)",
    )
    parser_tz.set_defaults(func=partial(updateTzdata, topsrcdir))

    parser_currency = subparsers.add_parser(
        "currency", help="Update currency digits mapping"
    )
    parser_currency.add_argument(
        "--url",
        metavar="URL",
        default="https://www.currency-iso.org/dam/downloads/lists/list_one.xml",  # NOQA: E501
        type=EnsureHttps,
        help="Download url for the currency & funds code list (default: "
        "%(default)s)",
    )
    parser_currency.add_argument(
        "--out",
        default=os.path.join(thisDir, "CurrencyDataGenerated.js"),
        help="Output file (default: %(default)s)",
    )
    parser_currency.add_argument(
        "file", nargs="?", help="Local currency code list file, if omitted uses <URL>"
    )
    parser_currency.set_defaults(func=partial(updateCurrency, topsrcdir))

    parser_units = subparsers.add_parser(
        "units", help="Update sanctioned unit identifiers mapping"
    )
    parser_units.set_defaults(func=partial(updateUnits, topsrcdir))

    parser_numbering_systems = subparsers.add_parser(
        "numbering", help="Update numbering systems with simple digit mappings"
    )
    parser_numbering_systems.set_defaults(
        func=partial(updateNumberingSystems, topsrcdir)
    )

    args = parser.parse_args()
    args.func(args)