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
|
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
*
* Copyright (C) 1998-2015, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
*
* File parse.cpp
*
* Modification History:
*
* Date Name Description
* 05/26/99 stephen Creation.
* 02/25/00 weiv Overhaul to write udata
* 5/10/01 Ram removed ustdio dependency
* 06/10/2001 Dominic Ludlam <dom@recoil.org> Rewritten
*******************************************************************************
*/
// Safer use of UnicodeString.
#include <cstdint>
#include "unicode/umachine.h"
#ifndef UNISTR_FROM_CHAR_EXPLICIT
# define UNISTR_FROM_CHAR_EXPLICIT explicit
#endif
// Less important, but still a good idea.
#ifndef UNISTR_FROM_STRING_EXPLICIT
# define UNISTR_FROM_STRING_EXPLICIT explicit
#endif
#include <assert.h>
#include "parse.h"
#include "errmsg.h"
#include "uhash.h"
#include "cmemory.h"
#include "cstring.h"
#include "uinvchar.h"
#include "read.h"
#include "ustr.h"
#include "reslist.h"
#include "rbt_pars.h"
#include "genrb.h"
#include "unicode/normalizer2.h"
#include "unicode/stringpiece.h"
#include "unicode/unistr.h"
#include "unicode/ustring.h"
#include "unicode/uscript.h"
#include "unicode/utf16.h"
#include "unicode/putil.h"
#include "charstr.h"
#include "collationbuilder.h"
#include "collationdata.h"
#include "collationdatareader.h"
#include "collationdatawriter.h"
#include "collationfastlatinbuilder.h"
#include "collationinfo.h"
#include "collationroot.h"
#include "collationruleparser.h"
#include "collationtailoring.h"
#include <stdio.h>
#include "writesrc.h"
/* Number of tokens to read ahead of the current stream position */
#define MAX_LOOKAHEAD 3
#define CR 0x000D
#define LF 0x000A
#define SPACE 0x0020
#define TAB 0x0009
#define ESCAPE 0x005C
#define HASH 0x0023
#define QUOTE 0x0027
#define ZERO 0x0030
#define STARTCOMMAND 0x005B
#define ENDCOMMAND 0x005D
#define OPENSQBRACKET 0x005B
#define CLOSESQBRACKET 0x005D
#define ICU4X_DIACRITIC_BASE 0x0300
#define ICU4X_DIACRITIC_LIMIT 0x034F
using icu::CharString;
using icu::LocalMemory;
using icu::LocalPointer;
using icu::LocalUCHARBUFPointer;
using icu::StringPiece;
using icu::UnicodeString;
struct Lookahead
{
enum ETokenType type;
struct UString value;
struct UString comment;
uint32_t line;
};
/* keep in sync with token defines in read.h */
const char *tokenNames[TOK_TOKEN_COUNT] =
{
"string", /* A string token, such as "MonthNames" */
"'{'", /* An opening brace character */
"'}'", /* A closing brace character */
"','", /* A comma */
"':'", /* A colon */
"<end of file>", /* End of the file has been reached successfully */
"<end of line>"
};
/* Just to store "TRUE" */
//static const char16_t trueValue[] = {0x0054, 0x0052, 0x0055, 0x0045, 0x0000};
typedef struct {
struct Lookahead lookahead[MAX_LOOKAHEAD + 1];
uint32_t lookaheadPosition;
UCHARBUF *buffer;
struct SRBRoot *bundle;
const char *inputdir;
uint32_t inputdirLength;
const char *outputdir;
uint32_t outputdirLength;
const char *filename;
UBool makeBinaryCollation;
UBool omitCollationRules;
UBool icu4xMode;
} ParseState;
typedef struct SResource *
ParseResourceFunction(ParseState* state, char *tag, uint32_t startline, const struct UString* comment, UErrorCode *status);
static struct SResource *parseResource(ParseState* state, char *tag, const struct UString *comment, UErrorCode *status);
/* The nature of the lookahead buffer:
There are MAX_LOOKAHEAD + 1 slots, used as a circular buffer. This provides
MAX_LOOKAHEAD lookahead tokens and a slot for the current token and value.
When getToken is called, the current pointer is moved to the next slot and the
old slot is filled with the next token from the reader by calling getNextToken.
The token values are stored in the slot, which means that token values don't
survive a call to getToken, ie.
UString *value;
getToken(&value, nullptr, status);
getToken(nullptr, nullptr, status); bad - value is now a different string
*/
static void
initLookahead(ParseState* state, UCHARBUF *buf, UErrorCode *status)
{
static uint32_t initTypeStrings = 0;
uint32_t i;
if (!initTypeStrings)
{
initTypeStrings = 1;
}
state->lookaheadPosition = 0;
state->buffer = buf;
resetLineNumber();
for (i = 0; i < MAX_LOOKAHEAD; i++)
{
state->lookahead[i].type = getNextToken(state->buffer, &state->lookahead[i].value, &state->lookahead[i].line, &state->lookahead[i].comment, status);
if (U_FAILURE(*status))
{
return;
}
}
*status = U_ZERO_ERROR;
}
static void
cleanupLookahead(ParseState* state)
{
uint32_t i;
for (i = 0; i <= MAX_LOOKAHEAD; i++)
{
ustr_deinit(&state->lookahead[i].value);
ustr_deinit(&state->lookahead[i].comment);
}
}
static enum ETokenType
getToken(ParseState* state, struct UString **tokenValue, struct UString* comment, uint32_t *linenumber, UErrorCode *status)
{
enum ETokenType result;
uint32_t i;
result = state->lookahead[state->lookaheadPosition].type;
if (tokenValue != nullptr)
{
*tokenValue = &state->lookahead[state->lookaheadPosition].value;
}
if (linenumber != nullptr)
{
*linenumber = state->lookahead[state->lookaheadPosition].line;
}
if (comment != nullptr)
{
ustr_cpy(comment, &(state->lookahead[state->lookaheadPosition].comment), status);
}
i = (state->lookaheadPosition + MAX_LOOKAHEAD) % (MAX_LOOKAHEAD + 1);
state->lookaheadPosition = (state->lookaheadPosition + 1) % (MAX_LOOKAHEAD + 1);
ustr_setlen(&state->lookahead[i].comment, 0, status);
ustr_setlen(&state->lookahead[i].value, 0, status);
state->lookahead[i].type = getNextToken(state->buffer, &state->lookahead[i].value, &state->lookahead[i].line, &state->lookahead[i].comment, status);
/* printf("getToken, returning %s\n", tokenNames[result]); */
return result;
}
static enum ETokenType
peekToken(ParseState* state, uint32_t lookaheadCount, struct UString **tokenValue, uint32_t *linenumber, struct UString *comment, UErrorCode *status)
{
uint32_t i = (state->lookaheadPosition + lookaheadCount) % (MAX_LOOKAHEAD + 1);
if (U_FAILURE(*status))
{
return TOK_ERROR;
}
if (lookaheadCount >= MAX_LOOKAHEAD)
{
*status = U_INTERNAL_PROGRAM_ERROR;
return TOK_ERROR;
}
if (tokenValue != nullptr)
{
*tokenValue = &state->lookahead[i].value;
}
if (linenumber != nullptr)
{
*linenumber = state->lookahead[i].line;
}
if(comment != nullptr){
ustr_cpy(comment, &(state->lookahead[state->lookaheadPosition].comment), status);
}
return state->lookahead[i].type;
}
static void
expect(ParseState* state, enum ETokenType expectedToken, struct UString **tokenValue, struct UString *comment, uint32_t *linenumber, UErrorCode *status)
{
uint32_t line;
enum ETokenType token = getToken(state, tokenValue, comment, &line, status);
if (linenumber != nullptr)
{
*linenumber = line;
}
if (U_FAILURE(*status))
{
return;
}
if (token != expectedToken)
{
*status = U_INVALID_FORMAT_ERROR;
error(line, "expecting %s, got %s", tokenNames[expectedToken], tokenNames[token]);
}
else
{
*status = U_ZERO_ERROR;
}
}
static char *getInvariantString(ParseState* state, uint32_t *line, struct UString *comment,
int32_t &stringLength, UErrorCode *status)
{
struct UString *tokenValue;
char *result;
expect(state, TOK_STRING, &tokenValue, comment, line, status);
if (U_FAILURE(*status))
{
return nullptr;
}
if(!uprv_isInvariantUString(tokenValue->fChars, tokenValue->fLength)) {
*status = U_INVALID_FORMAT_ERROR;
error(*line, "invariant characters required for table keys, binary data, etc.");
return nullptr;
}
result = static_cast<char *>(uprv_malloc(tokenValue->fLength+1));
if (result == nullptr)
{
*status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
u_UCharsToChars(tokenValue->fChars, result, tokenValue->fLength+1);
stringLength = tokenValue->fLength;
return result;
}
static struct SResource *
parseUCARules(ParseState* state, char *tag, uint32_t startline, const struct UString* /*comment*/, UErrorCode *status)
{
struct SResource *result = nullptr;
struct UString *tokenValue;
FileStream *file = nullptr;
char filename[256] = { '\0' };
char cs[128] = { '\0' };
uint32_t line;
UBool quoted = false;
UCHARBUF *ucbuf=nullptr;
UChar32 c = 0;
const char* cp = nullptr;
char16_t *pTarget = nullptr;
char16_t *target = nullptr;
char16_t *targetLimit = nullptr;
int32_t size = 0;
expect(state, TOK_STRING, &tokenValue, nullptr, &line, status);
if(isVerbose()){
printf(" %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
if (U_FAILURE(*status))
{
return nullptr;
}
/* make the filename including the directory */
if (state->inputdir != nullptr)
{
uprv_strcat(filename, state->inputdir);
if (state->inputdir[state->inputdirLength - 1] != U_FILE_SEP_CHAR)
{
uprv_strcat(filename, U_FILE_SEP_STRING);
}
}
u_UCharsToChars(tokenValue->fChars, cs, tokenValue->fLength);
expect(state, TOK_CLOSE_BRACE, nullptr, nullptr, nullptr, status);
if (U_FAILURE(*status))
{
return nullptr;
}
uprv_strcat(filename, cs);
if(state->omitCollationRules) {
return res_none();
}
ucbuf = ucbuf_open(filename, &cp, getShowWarning(),false, status);
if (U_FAILURE(*status)) {
error(line, "An error occurred while opening the input file %s\n", filename);
return nullptr;
}
/* We allocate more space than actually required
* since the actual size needed for storing UChars
* is not known in UTF-8 byte stream
*/
size = ucbuf_size(ucbuf) + 1;
pTarget = (char16_t*) uprv_malloc(U_SIZEOF_UCHAR * size);
uprv_memset(pTarget, 0, size*U_SIZEOF_UCHAR);
target = pTarget;
targetLimit = pTarget+size;
/* read the rules into the buffer */
while (target < targetLimit)
{
c = ucbuf_getc(ucbuf, status);
if(c == QUOTE) {
quoted = (UBool)!quoted;
}
/* weiv (06/26/2002): adding the following:
* - preserving spaces in commands [...]
* - # comments until the end of line
*/
if (c == STARTCOMMAND && !quoted)
{
/* preserve commands
* closing bracket will be handled by the
* append at the end of the loop
*/
while(c != ENDCOMMAND) {
U_APPEND_CHAR32_ONLY(c, target);
c = ucbuf_getc(ucbuf, status);
}
}
else if (c == HASH && !quoted) {
/* skip comments */
while(c != CR && c != LF) {
c = ucbuf_getc(ucbuf, status);
}
continue;
}
else if (c == ESCAPE)
{
c = unescape(ucbuf, status);
if (c == (UChar32)U_ERR)
{
uprv_free(pTarget);
T_FileStream_close(file);
return nullptr;
}
}
else if (!quoted && (c == SPACE || c == TAB || c == CR || c == LF))
{
/* ignore spaces carriage returns
* and line feed unless in the form \uXXXX
*/
continue;
}
/* Append char16_t * after dissembling if c > 0xffff*/
if (c != (UChar32)U_EOF)
{
U_APPEND_CHAR32_ONLY(c, target);
}
else
{
break;
}
}
/* terminate the string */
if(target < targetLimit){
*target = 0x0000;
}
result = string_open(state->bundle, tag, pTarget, (int32_t)(target - pTarget), nullptr, status);
ucbuf_close(ucbuf);
uprv_free(pTarget);
T_FileStream_close(file);
return result;
}
static struct SResource *
parseTransliterator(ParseState* state, char *tag, uint32_t startline, const struct UString* /*comment*/, UErrorCode *status)
{
struct SResource *result = nullptr;
struct UString *tokenValue;
FileStream *file = nullptr;
char filename[256] = { '\0' };
char cs[128] = { '\0' };
uint32_t line;
UCHARBUF *ucbuf=nullptr;
const char* cp = nullptr;
char16_t *pTarget = nullptr;
const char16_t *pSource = nullptr;
int32_t size = 0;
expect(state, TOK_STRING, &tokenValue, nullptr, &line, status);
if(isVerbose()){
printf(" %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
if (U_FAILURE(*status))
{
return nullptr;
}
/* make the filename including the directory */
if (state->inputdir != nullptr)
{
uprv_strcat(filename, state->inputdir);
if (state->inputdir[state->inputdirLength - 1] != U_FILE_SEP_CHAR)
{
uprv_strcat(filename, U_FILE_SEP_STRING);
}
}
u_UCharsToChars(tokenValue->fChars, cs, tokenValue->fLength);
expect(state, TOK_CLOSE_BRACE, nullptr, nullptr, nullptr, status);
if (U_FAILURE(*status))
{
return nullptr;
}
uprv_strcat(filename, cs);
ucbuf = ucbuf_open(filename, &cp, getShowWarning(),false, status);
if (U_FAILURE(*status)) {
error(line, "An error occurred while opening the input file %s\n", filename);
return nullptr;
}
/* We allocate more space than actually required
* since the actual size needed for storing UChars
* is not known in UTF-8 byte stream
*/
pSource = ucbuf_getBuffer(ucbuf, &size, status);
pTarget = (char16_t*) uprv_malloc(U_SIZEOF_UCHAR * (size + 1));
uprv_memset(pTarget, 0, size*U_SIZEOF_UCHAR);
#if !UCONFIG_NO_TRANSLITERATION
size = utrans_stripRules(pSource, size, pTarget, status);
#else
size = 0;
fprintf(stderr, " Warning: writing empty transliteration data ( UCONFIG_NO_TRANSLITERATION ) \n");
#endif
result = string_open(state->bundle, tag, pTarget, size, nullptr, status);
ucbuf_close(ucbuf);
uprv_free(pTarget);
T_FileStream_close(file);
return result;
}
static ArrayResource* dependencyArray = nullptr;
static struct SResource *
parseDependency(ParseState* state, char *tag, uint32_t startline, const struct UString* comment, UErrorCode *status)
{
struct SResource *result = nullptr;
struct SResource *elem = nullptr;
struct UString *tokenValue;
uint32_t line;
char filename[256] = { '\0' };
char cs[128] = { '\0' };
expect(state, TOK_STRING, &tokenValue, nullptr, &line, status);
if(isVerbose()){
printf(" %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
if (U_FAILURE(*status))
{
return nullptr;
}
/* make the filename including the directory */
if (state->outputdir != nullptr)
{
uprv_strcat(filename, state->outputdir);
if (state->outputdir[state->outputdirLength - 1] != U_FILE_SEP_CHAR)
{
uprv_strcat(filename, U_FILE_SEP_STRING);
}
}
u_UCharsToChars(tokenValue->fChars, cs, tokenValue->fLength);
if (U_FAILURE(*status))
{
return nullptr;
}
uprv_strcat(filename, cs);
if(!T_FileStream_file_exists(filename)){
if(isStrict()){
error(line, "The dependency file %s does not exist. Please make sure it exists.\n",filename);
}else{
warning(line, "The dependency file %s does not exist. Please make sure it exists.\n",filename);
}
}
if(dependencyArray==nullptr){
dependencyArray = array_open(state->bundle, "%%DEPENDENCY", nullptr, status);
}
if(tag!=nullptr){
result = string_open(state->bundle, tag, tokenValue->fChars, tokenValue->fLength, comment, status);
}
elem = string_open(state->bundle, nullptr, tokenValue->fChars, tokenValue->fLength, comment, status);
dependencyArray->add(elem);
if (U_FAILURE(*status))
{
return nullptr;
}
expect(state, TOK_CLOSE_BRACE, nullptr, nullptr, nullptr, status);
return result;
}
static struct SResource *
parseString(ParseState* state, char *tag, uint32_t startline, const struct UString* comment, UErrorCode *status)
{
struct UString *tokenValue;
struct SResource *result = nullptr;
/* if (tag != nullptr && uprv_strcmp(tag, "%%UCARULES") == 0)
{
return parseUCARules(tag, startline, status);
}*/
if(isVerbose()){
printf(" string %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
expect(state, TOK_STRING, &tokenValue, nullptr, nullptr, status);
if (U_SUCCESS(*status))
{
/* create the string now - tokenValue doesn't survive a call to getToken (and therefore
doesn't survive expect either) */
result = string_open(state->bundle, tag, tokenValue->fChars, tokenValue->fLength, comment, status);
if(U_SUCCESS(*status) && result) {
expect(state, TOK_CLOSE_BRACE, nullptr, nullptr, nullptr, status);
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
}
}
return result;
}
static struct SResource *
parseAlias(ParseState* state, char *tag, uint32_t startline, const struct UString *comment, UErrorCode *status)
{
struct UString *tokenValue;
struct SResource *result = nullptr;
expect(state, TOK_STRING, &tokenValue, nullptr, nullptr, status);
if(isVerbose()){
printf(" alias %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
if (U_SUCCESS(*status))
{
/* create the string now - tokenValue doesn't survive a call to getToken (and therefore
doesn't survive expect either) */
result = alias_open(state->bundle, tag, tokenValue->fChars, tokenValue->fLength, comment, status);
expect(state, TOK_CLOSE_BRACE, nullptr, nullptr, nullptr, status);
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
}
return result;
}
#if !UCONFIG_NO_COLLATION
namespace {
static struct SResource* resLookup(struct SResource* res, const char* key){
if (res == res_none() || !res->isTable()) {
return nullptr;
}
TableResource *list = static_cast<TableResource *>(res);
SResource *current = list->fFirst;
while (current != nullptr) {
if (uprv_strcmp(((list->fRoot->fKeys) + (current->fKey)), key) == 0) {
return current;
}
current = current->fNext;
}
return nullptr;
}
class GenrbImporter : public icu::CollationRuleParser::Importer {
public:
GenrbImporter(const char *in, const char *out) : inputDir(in), outputDir(out) {}
virtual ~GenrbImporter();
virtual void getRules(
const char *localeID, const char *collationType,
UnicodeString &rules,
const char *&errorReason, UErrorCode &errorCode) override;
private:
const char *inputDir;
const char *outputDir;
};
GenrbImporter::~GenrbImporter() {}
void
GenrbImporter::getRules(
const char *localeID, const char *collationType,
UnicodeString &rules,
const char *& /*errorReason*/, UErrorCode &errorCode) {
CharString filename(localeID, errorCode);
for(int32_t i = 0; i < filename.length(); i++){
if(filename[i] == '-'){
filename.data()[i] = '_';
}
}
filename.append(".txt", errorCode);
if (U_FAILURE(errorCode)) {
return;
}
CharString inputDirBuf;
CharString openFileName;
if(inputDir == nullptr) {
const char *filenameBegin = uprv_strrchr(filename.data(), U_FILE_SEP_CHAR);
if (filenameBegin != nullptr) {
/*
* When a filename ../../../data/root.txt is specified,
* we presume that the input directory is ../../../data
* This is very important when the resource file includes
* another file, like UCARules.txt or thaidict.brk.
*/
StringPiece dir = filename.toStringPiece();
const char *filenameLimit = filename.data() + filename.length();
dir.remove_suffix((int32_t)(filenameLimit - filenameBegin));
inputDirBuf.append(dir, errorCode);
inputDir = inputDirBuf.data();
}
}else{
int32_t dirlen = (int32_t)uprv_strlen(inputDir);
if((filename[0] != U_FILE_SEP_CHAR) && (inputDir[dirlen-1] !='.')) {
/*
* append the input dir to openFileName if the first char in
* filename is not file separator char and the last char input directory is not '.'.
* This is to support :
* genrb -s. /home/icu/data
* genrb -s. icu/data
* The user cannot mix notations like
* genrb -s. /icu/data --- the absolute path specified. -s redundant
* user should use
* genrb -s. icu/data --- start from CWD and look in icu/data dir
*/
openFileName.append(inputDir, dirlen, errorCode);
if(inputDir[dirlen-1] != U_FILE_SEP_CHAR) {
openFileName.append(U_FILE_SEP_CHAR, errorCode);
}
}
}
openFileName.append(filename, errorCode);
if(U_FAILURE(errorCode)) {
return;
}
// printf("GenrbImporter::getRules(%s, %s) reads %s\n", localeID, collationType, openFileName.data());
const char* cp = "";
LocalUCHARBUFPointer ucbuf(
ucbuf_open(openFileName.data(), &cp, getShowWarning(), true, &errorCode));
if(errorCode == U_FILE_ACCESS_ERROR) {
fprintf(stderr, "couldn't open file %s\n", openFileName.data());
return;
}
if (ucbuf.isNull() || U_FAILURE(errorCode)) {
fprintf(stderr, "An error occurred processing file %s. Error: %s\n", openFileName.data(), u_errorName(errorCode));
return;
}
/* Parse the data into an SRBRoot */
LocalPointer<SRBRoot> data(
parse(ucbuf.getAlias(), inputDir, outputDir, filename.data(), false, false, false, &errorCode));
if (U_FAILURE(errorCode)) {
return;
}
struct SResource *root = data->fRoot;
struct SResource *collations = resLookup(root, "collations");
if (collations != nullptr) {
struct SResource *collation = resLookup(collations, collationType);
if (collation != nullptr) {
struct SResource *sequence = resLookup(collation, "Sequence");
if (sequence != nullptr && sequence->isString()) {
// No string pointer aliasing so that we need not hold onto the resource bundle.
StringResource *sr = static_cast<StringResource *>(sequence);
rules = sr->fString;
}
}
}
}
// Quick-and-dirty escaping function.
// Assumes that we are on an ASCII-based platform.
static void
escape(const char16_t *s, char *buffer, size_t n) {
int32_t length = u_strlen(s);
int32_t i = 0;
for (;;) {
UChar32 c;
U16_NEXT(s, i, length, c);
if (c == 0) {
*buffer = 0;
return;
} else if (0x20 <= c && c <= 0x7e) {
// printable ASCII
*buffer++ = (char)c; // assumes ASCII-based platform
} else {
buffer += snprintf(buffer, n, "\\u%04X", (int)c);
}
}
}
} // namespace
static FILE*
openTOML(const char* outputdir, const char* name, const char* collationType, const char* structType, UErrorCode *status) {
CharString baseName;
baseName.append(name, *status);
baseName.append("_", *status);
baseName.append(collationType, *status);
baseName.append("_", *status);
baseName.append(structType, *status);
CharString outFileName;
if (outputdir && *outputdir) {
outFileName.append(outputdir, *status).ensureEndsWithFileSeparator(*status);
}
outFileName.append(baseName, *status);
outFileName.append(".toml", *status);
if (U_FAILURE(*status)) {
return nullptr;
}
FILE* f = fopen(outFileName.data(), "w");
if (!f) {
*status = U_FILE_ACCESS_ERROR;
return nullptr;
}
usrc_writeFileNameGeneratedBy(f, "#", baseName.data(), "genrb -X");
return f;
}
static void
writeCollationMetadataTOML(const char* outputdir, const char* name, const char* collationType, const uint32_t metadataBits, UErrorCode *status) {
FILE* f = openTOML(outputdir, name, collationType, "meta", status);
if (!f) {
return;
}
// printf("writeCollationMetadataTOML %s %s\n", name, collationType);
fprintf(f, "bits = 0x%X\n", metadataBits);
fclose(f);
}
static UChar32
writeCollationDiacriticsTOML(const char* outputdir, const char* name, const char* collationType, const icu::CollationData* data, UErrorCode *status) {
UChar32 limit = ICU4X_DIACRITIC_LIMIT;
FILE* f = openTOML(outputdir, name, collationType, "dia", status);
if (!f) {
return limit;
}
// printf("writeCollationDiacriticsTOML %s %s\n", name, collationType);
uint16_t secondaries[ICU4X_DIACRITIC_LIMIT-ICU4X_DIACRITIC_BASE];
for (UChar32 c = ICU4X_DIACRITIC_BASE; c < ICU4X_DIACRITIC_LIMIT; ++c) {
uint16_t secondary = 0;
uint32_t ce32 = data->getCE32(c);
if (ce32 == icu::Collation::FALLBACK_CE32) {
ce32 = data->base->getCE32(c);
}
if (c == 0x0340 || c == 0x0341 || c == 0x0343 || c == 0x0344) {
// These never occur in NFD data
} else if (!icu::Collation::isSimpleOrLongCE32(ce32)) {
if (uprv_strcmp(name, "root") == 0) {
printf("UNSUPPORTED DIACRITIC CE32 in root: TAG: %X CE32: %X char: %X\n", icu::Collation::tagFromCE32(ce32), ce32, c);
fclose(f);
*status = U_INTERNAL_PROGRAM_ERROR;
return limit;
}
limit = c;
break;
} else {
uint64_t ce = uint64_t(icu::Collation::ceFromCE32(ce32));
if ((ce & 0xFFFFFFFF0000FFFF) != uint64_t(icu::Collation::COMMON_TERTIARY_CE)) {
// Not a CE where only the secondary weight differs from the expected
// pattern.
limit = c;
break;
}
secondary = uint16_t(ce >> 16);
}
secondaries[c - ICU4X_DIACRITIC_BASE] = secondary;
}
usrc_writeArray(f, "secondaries = [\n ", secondaries, 16, limit-ICU4X_DIACRITIC_BASE, " ", "\n]\n");
fclose(f);
return limit;
}
static void
writeCollationReorderingTOML(const char* outputdir, const char* name, const char* collationType, const icu::CollationSettings* settings, UErrorCode *status) {
FILE* f = openTOML(outputdir, name, collationType, "reord", status);
if (!f) {
return;
}
// printf("writeCollationReorderingTOML %s %s\n", name, collationType);
fprintf(f, "min_high_no_reorder = 0x%X\n", settings->minHighNoReorder);
usrc_writeArray(f, "reorder_table = [\n ", settings->reorderTable, 8, 256, " ", "\n]\n");
usrc_writeArray(f, "reorder_ranges = [\n ", settings->reorderRanges, 32, settings->reorderRangesLength, " ", "\n]\n");
fclose(f);
}
static void
writeCollationJamoTOML(const char* outputdir, const char* name, const char* collationType, const icu::CollationData* data, UErrorCode *status) {
FILE* f = openTOML(outputdir, name, collationType, "jamo", status);
if (!f) {
printf("writeCollationJamoTOML FAILED TO OPEN FILE %s %s\n", name, collationType);
return;
}
uint32_t jamo[0x1200-0x1100];
for (UChar32 c = 0x1100; c < 0x1200; ++c) {
uint32_t ce32 = data->getCE32(c);
if (ce32 == icu::Collation::FALLBACK_CE32) {
ce32 = data->base->getCE32(c);
}
// Can't reject complex CE32s, because search collations have expansions.
// These expansions refer to the tailoring, which foils the reuse of the
// these jamo tables.
// XXX Figure out what to do. Perhaps instead of having Latin mini expansions,
// there should be Hangul mini expansions.
// XXX in any case, validate that modern jamo are self-contained.
jamo[c - 0x1100] = ce32;
}
usrc_writeArray(f, "ce32s = [\n ", jamo, 32, 0x1200-0x1100, " ", "\n]\n");
fclose(f);
}
static UBool
convertTrie(const void *context, UChar32 start, UChar32 end, uint32_t value) {
if (start >= 0x1100 && start < 0x1200 && end >= 0x1100 && end < 0x1200) {
// Range entirely in conjoining jamo block.
return true;
}
icu::IcuToolErrorCode status("genrb: convertTrie");
umutablecptrie_setRange((UMutableCPTrie*)context, start, end, value, status);
return !U_FAILURE(*status);
}
static void
writeCollationDataTOML(const char* outputdir, const char* name, const char* collationType, const icu::CollationData* data, UBool root, UChar32 diacriticLimit, UErrorCode *status) {
FILE* f = openTOML(outputdir, name, collationType, "data", status);
if (!f) {
return;
}
// printf("writeCollationDataTOML %s %s\n", name, collationType);
icu::UnicodeSet tailoringSet;
if (data->base) {
tailoringSet.addAll(*(data->unsafeBackwardSet));
tailoringSet.removeAll(*(data->base->unsafeBackwardSet));
} else {
tailoringSet.addAll(*(data->unsafeBackwardSet));
}
// Use the same value for out-of-range and default in the hope of not having to allocate
// different blocks, since ICU4X never does out-of-range queries.
uint32_t trieDefault = root ? icu::Collation::UNASSIGNED_CE32 : icu::Collation::FALLBACK_CE32;
icu::LocalUMutableCPTriePointer builder(umutablecptrie_open(trieDefault, trieDefault, status));
utrie2_enum(data->trie, nullptr, &convertTrie, builder.getAlias());
// If the diacritic table was cut short, copy CE32s between the lowered
// limit and the max limit from the root to the tailoring. As of June 2022,
// no collation in CLDR needs this.
for (UChar32 c = diacriticLimit; c < ICU4X_DIACRITIC_LIMIT; ++c) {
if (c == 0x0340 || c == 0x0341 || c == 0x0343 || c == 0x0344) {
// These never occur in NFD data.
continue;
}
uint32_t ce32 = data->getCE32(c);
if (ce32 == icu::Collation::FALLBACK_CE32) {
ce32 = data->base->getCE32(c);
umutablecptrie_set(builder.getAlias(), c, ce32, status);
}
}
// Ensure that the range covered by the diacritic table isn't duplicated
// in the trie.
for (UChar32 c = ICU4X_DIACRITIC_BASE; c < diacriticLimit; ++c) {
if (umutablecptrie_get(builder.getAlias(), c) != trieDefault) {
umutablecptrie_set(builder.getAlias(), c, trieDefault, status);
}
}
icu::LocalUCPTriePointer utrie(umutablecptrie_buildImmutable(
builder.getAlias(),
UCPTRIE_TYPE_SMALL,
UCPTRIE_VALUE_BITS_32,
status));
usrc_writeArray(f, "contexts = [\n ", data->contexts, 16, data->contextsLength, " ", "\n]\n");
usrc_writeArray(f, "ce32s = [\n ", data->ce32s, 32, data->ce32sLength, " ", "\n]\n");
usrc_writeArray(f, "ces = [\n ", data->ces, 64, data->cesLength, " ", "\n]\n");
fprintf(f, "[trie]\n");
usrc_writeUCPTrie(f, "trie", utrie.getAlias(), UPRV_TARGET_SYNTAX_TOML);
fclose(f);
}
static void
writeCollationSpecialPrimariesTOML(const char* outputdir, const char* name, const char* collationType, const icu::CollationData* data, UErrorCode *status) {
FILE* f = openTOML(outputdir, name, collationType, "prim", status);
if (!f) {
return;
}
// printf("writeCollationSpecialPrimariesTOML %s %s\n", name, collationType);
uint16_t lastPrimaries[4];
for (int32_t i = 0; i < 4; ++i) {
// getLastPrimaryForGroup subtracts one from a 16-bit value, so we add one
// back to get a value that fits in 16 bits.
lastPrimaries[i] = (uint16_t)((data->getLastPrimaryForGroup(UCOL_REORDER_CODE_FIRST + i) + 1) >> 16);
}
uint32_t numericPrimary = data->numericPrimary;
if (numericPrimary & 0xFFFFFF) {
printf("Lower 24 bits set in numeric primary");
*status = U_INTERNAL_PROGRAM_ERROR;
return;
}
usrc_writeArray(f, "last_primaries = [\n ", lastPrimaries, 16, 4, " ", "\n]\n");
fprintf(f, "numeric_primary = 0x%X\n", numericPrimary >> 24);
fclose(f);
}
static void
writeCollationTOML(const char* outputdir, const char* name, const char* collationType, const icu::CollationData* data, const icu::CollationSettings* settings, UErrorCode *status) {
UBool tailored = false;
UBool tailoredDiacritics = false;
UBool lithuanianDotAbove = (uprv_strcmp(name, "lt") == 0);
UBool reordering = false;
UBool isRoot = uprv_strcmp(name, "root") == 0;
UChar32 diacriticLimit = ICU4X_DIACRITIC_LIMIT;
if (!data->base && isRoot) {
diacriticLimit = writeCollationDiacriticsTOML(outputdir, name, collationType, data, status);
if (U_FAILURE(*status)) {
return;
}
writeCollationJamoTOML(outputdir, name, collationType, data, status);
if (U_FAILURE(*status)) {
return;
}
writeCollationSpecialPrimariesTOML(outputdir, name, collationType, data, status);
if (U_FAILURE(*status)) {
return;
}
} else if (data->base && !lithuanianDotAbove) {
for (UChar32 c = ICU4X_DIACRITIC_BASE; c < ICU4X_DIACRITIC_LIMIT; ++c) {
if (c == 0x0340 || c == 0x0341 || c == 0x0343 || c == 0x0344) {
// These never occur in NFD data.
continue;
}
uint32_t ce32 = data->getCE32(c);
if ((ce32 != icu::Collation::FALLBACK_CE32) && (ce32 != data->base->getCE32(c))) {
tailoredDiacritics = true;
diacriticLimit = writeCollationDiacriticsTOML(outputdir, name, collationType, data, status);
if (U_FAILURE(*status)) {
return;
}
break;
}
}
}
if (settings->hasReordering()) {
reordering = true;
// Note: There are duplicate reorderings. Expecting the ICU4X provider
// to take care of deduplication.
writeCollationReorderingTOML(outputdir, name, collationType, settings, status);
if (U_FAILURE(*status)) {
return;
}
}
// Write collation data if either base is non-null or the name is root.
// Languages that only reorder scripts are otherwise root-like and have
// null base.
if (data->base || isRoot) {
tailored = !isRoot;
writeCollationDataTOML(outputdir, name, collationType, data, (!data->base && isRoot), diacriticLimit, status);
if (U_FAILURE(*status)) {
return;
}
}
uint32_t maxVariable = (uint32_t)settings->getMaxVariable();
if (maxVariable >= 4) {
printf("Max variable out of range");
*status = U_INTERNAL_PROGRAM_ERROR;
return;
}
uint32_t metadataBits = maxVariable;
if (tailored) {
metadataBits |= (1 << 3);
}
if (tailoredDiacritics) {
metadataBits |= (1 << 4);
}
if (reordering) {
metadataBits |= (1 << 5);
}
if (lithuanianDotAbove) {
metadataBits |= (1 << 6);
}
if ((settings->options & icu::CollationSettings::BACKWARD_SECONDARY) != 0) {
metadataBits |= (1 << 7);
}
if (settings->getAlternateHandling() == UCOL_SHIFTED) {
metadataBits |= (1 << 8);
}
switch (settings->getCaseFirst()) {
case UCOL_OFF:
break;
case UCOL_UPPER_FIRST:
metadataBits |= (1 << 9);
metadataBits |= (1 << 10);
break;
case UCOL_LOWER_FIRST:
metadataBits |= (1 << 9);
break;
default:
*status = U_INTERNAL_PROGRAM_ERROR;
return;
}
writeCollationMetadataTOML(outputdir, name, collationType, metadataBits, status);
}
#endif // !UCONFIG_NO_COLLATION
static TableResource *
addCollation(ParseState* state, TableResource *result, const char *collationType,
uint32_t startline, UErrorCode *status)
{
// TODO: Use LocalPointer for result, or make caller close it when there is a failure.
struct SResource *member = nullptr;
struct UString *tokenValue;
struct UString comment;
enum ETokenType token;
char subtag[1024];
UnicodeString rules;
UBool haveRules = false;
UVersionInfo version;
uint32_t line;
/* '{' . (name resource)* '}' */
version[0]=0; version[1]=0; version[2]=0; version[3]=0;
for (;;)
{
ustr_init(&comment);
token = getToken(state, &tokenValue, &comment, &line, status);
if (token == TOK_CLOSE_BRACE)
{
break;
}
if (token != TOK_STRING)
{
res_close(result);
*status = U_INVALID_FORMAT_ERROR;
if (token == TOK_EOF)
{
error(startline, "unterminated table");
}
else
{
error(line, "Unexpected token %s", tokenNames[token]);
}
return nullptr;
}
u_UCharsToChars(tokenValue->fChars, subtag, u_strlen(tokenValue->fChars) + 1);
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
member = parseResource(state, subtag, nullptr, status);
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
if (result == nullptr)
{
// Ignore the parsed resources, continue parsing.
}
else if (uprv_strcmp(subtag, "Version") == 0 && member->isString())
{
StringResource *sr = static_cast<StringResource *>(member);
char ver[40];
int32_t length = sr->length();
if (length >= UPRV_LENGTHOF(ver))
{
length = UPRV_LENGTHOF(ver) - 1;
}
sr->fString.extract(0, length, ver, UPRV_LENGTHOF(ver), US_INV);
u_versionFromString(version, ver);
result->add(member, line, *status);
member = nullptr;
}
else if(uprv_strcmp(subtag, "%%CollationBin")==0)
{
/* discard duplicate %%CollationBin if any*/
}
else if (uprv_strcmp(subtag, "Sequence") == 0 && member->isString())
{
StringResource *sr = static_cast<StringResource *>(member);
rules = sr->fString;
haveRules = true;
// Defer building the collator until we have seen
// all sub-elements of the collation table, including the Version.
/* in order to achieve smaller data files, we can direct genrb */
/* to omit collation rules */
if(!state->omitCollationRules) {
result->add(member, line, *status);
member = nullptr;
}
}
else // Just copy non-special items.
{
result->add(member, line, *status);
member = nullptr;
}
res_close(member); // TODO: use LocalPointer
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
}
if (!haveRules) { return result; }
#if UCONFIG_NO_COLLATION || UCONFIG_NO_FILE_IO
warning(line, "Not building collation elements because of UCONFIG_NO_COLLATION and/or UCONFIG_NO_FILE_IO, see uconfig.h");
(void)collationType;
#else
// CLDR ticket #3949, ICU ticket #8082:
// Do not build collation binary data for for-import-only "private" collation rule strings.
if (uprv_strncmp(collationType, "private-", 8) == 0) {
if(isVerbose()) {
printf("Not building %s~%s collation binary\n", state->filename, collationType);
}
return result;
}
if(!state->makeBinaryCollation) {
if(isVerbose()) {
printf("Not building %s~%s collation binary\n", state->filename, collationType);
}
return result;
}
UErrorCode intStatus = U_ZERO_ERROR;
UParseError parseError;
uprv_memset(&parseError, 0, sizeof(parseError));
GenrbImporter importer(state->inputdir, state->outputdir);
const icu::CollationTailoring *base = icu::CollationRoot::getRoot(intStatus);
if(U_FAILURE(intStatus)) {
error(line, "failed to load root collator (ucadata.icu) - %s", u_errorName(intStatus));
res_close(result);
return nullptr; // TODO: use LocalUResourceBundlePointer for result
}
icu::CollationBuilder builder(base, state->icu4xMode, intStatus);
if(state->icu4xMode || (uprv_strncmp(collationType, "search", 6) == 0)) {
builder.disableFastLatin(); // build fast-Latin table unless search collator or ICU4X
}
LocalPointer<icu::CollationTailoring> t(
builder.parseAndBuild(rules, version, &importer, &parseError, intStatus));
if(U_FAILURE(intStatus)) {
const char *reason = builder.getErrorReason();
if(reason == nullptr) { reason = ""; }
error(line, "CollationBuilder failed at %s~%s/Sequence rule offset %ld: %s %s",
state->filename, collationType,
(long)parseError.offset, u_errorName(intStatus), reason);
if(parseError.preContext[0] != 0 || parseError.postContext[0] != 0) {
// Print pre- and post-context.
char preBuffer[100], postBuffer[100];
escape(parseError.preContext, preBuffer, sizeof(preBuffer));
escape(parseError.postContext, postBuffer, sizeof(postBuffer));
error(line, " error context: \"...%s\" ! \"%s...\"", preBuffer, postBuffer);
}
if(isStrict() || t.isNull()) {
*status = intStatus;
res_close(result);
return nullptr;
}
}
if (state->icu4xMode) {
char *nameWithoutSuffix = static_cast<char *>(uprv_malloc(uprv_strlen(state->filename) + 1));
if (nameWithoutSuffix == nullptr) {
*status = U_MEMORY_ALLOCATION_ERROR;
res_close(result);
return nullptr;
}
uprv_strcpy(nameWithoutSuffix, state->filename);
*uprv_strrchr(nameWithoutSuffix, '.') = 0;
writeCollationTOML(state->outputdir, nameWithoutSuffix, collationType, t->data, t->settings, status);
uprv_free(nameWithoutSuffix);
}
icu::LocalMemory<uint8_t> buffer;
int32_t capacity = 100000;
uint8_t *dest = buffer.allocateInsteadAndCopy(capacity);
if(dest == nullptr) {
fprintf(stderr, "memory allocation (%ld bytes) for file contents failed\n",
(long)capacity);
*status = U_MEMORY_ALLOCATION_ERROR;
res_close(result);
return nullptr;
}
int32_t indexes[icu::CollationDataReader::IX_TOTAL_SIZE + 1];
int32_t totalSize = icu::CollationDataWriter::writeTailoring(
*t, *t->settings, indexes, dest, capacity, intStatus);
if(intStatus == U_BUFFER_OVERFLOW_ERROR) {
intStatus = U_ZERO_ERROR;
capacity = totalSize;
dest = buffer.allocateInsteadAndCopy(capacity);
if(dest == nullptr) {
fprintf(stderr, "memory allocation (%ld bytes) for file contents failed\n",
(long)capacity);
*status = U_MEMORY_ALLOCATION_ERROR;
res_close(result);
return nullptr;
}
totalSize = icu::CollationDataWriter::writeTailoring(
*t, *t->settings, indexes, dest, capacity, intStatus);
}
if(U_FAILURE(intStatus)) {
fprintf(stderr, "CollationDataWriter::writeTailoring() failed: %s\n",
u_errorName(intStatus));
res_close(result);
return nullptr;
}
if(isVerbose()) {
printf("%s~%s collation tailoring part sizes:\n", state->filename, collationType);
icu::CollationInfo::printSizes(totalSize, indexes);
if(t->settings->hasReordering()) {
printf("%s~%s collation reordering ranges:\n", state->filename, collationType);
icu::CollationInfo::printReorderRanges(
*t->data, t->settings->reorderCodes, t->settings->reorderCodesLength);
}
#if 0 // debugging output
} else {
printf("%s~%s collation tailoring part sizes:\n", state->filename, collationType);
icu::CollationInfo::printSizes(totalSize, indexes);
#endif
}
struct SResource *collationBin = bin_open(state->bundle, "%%CollationBin", totalSize, dest, nullptr, nullptr, status);
result->add(collationBin, line, *status);
if (U_FAILURE(*status)) {
res_close(result);
return nullptr;
}
#endif
return result;
}
static UBool
keepCollationType(const char * /*type*/) {
return true;
}
static struct SResource *
parseCollationElements(ParseState* state, char *tag, uint32_t startline, UBool newCollation, UErrorCode *status)
{
TableResource *result = nullptr;
struct SResource *member = nullptr;
struct UString *tokenValue;
struct UString comment;
enum ETokenType token;
char subtag[1024], typeKeyword[1024];
uint32_t line;
result = table_open(state->bundle, tag, nullptr, status);
if (result == nullptr || U_FAILURE(*status))
{
return nullptr;
}
if(isVerbose()){
printf(" collation elements %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
if(!newCollation) {
return addCollation(state, result, "(no type)", startline, status);
}
else {
for(;;) {
ustr_init(&comment);
token = getToken(state, &tokenValue, &comment, &line, status);
if (token == TOK_CLOSE_BRACE)
{
return result;
}
if (token != TOK_STRING)
{
res_close(result);
*status = U_INVALID_FORMAT_ERROR;
if (token == TOK_EOF)
{
error(startline, "unterminated table");
}
else
{
error(line, "Unexpected token %s", tokenNames[token]);
}
return nullptr;
}
u_UCharsToChars(tokenValue->fChars, subtag, u_strlen(tokenValue->fChars) + 1);
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
if (uprv_strcmp(subtag, "default") == 0)
{
member = parseResource(state, subtag, nullptr, status);
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
result->add(member, line, *status);
}
else
{
token = peekToken(state, 0, &tokenValue, &line, &comment, status);
/* this probably needs to be refactored or recursively use the parser */
/* first we assume that our collation table won't have the explicit type */
/* then, we cannot handle aliases */
if(token == TOK_OPEN_BRACE) {
token = getToken(state, &tokenValue, &comment, &line, status);
TableResource *collationRes;
if (keepCollationType(subtag)) {
collationRes = table_open(state->bundle, subtag, nullptr, status);
} else {
collationRes = nullptr;
}
// need to parse the collation data regardless
collationRes = addCollation(state, collationRes, subtag, startline, status);
if (collationRes != nullptr) {
result->add(collationRes, startline, *status);
}
} else if(token == TOK_COLON) { /* right now, we'll just try to see if we have aliases */
/* we could have a table too */
token = peekToken(state, 1, &tokenValue, &line, &comment, status);
u_UCharsToChars(tokenValue->fChars, typeKeyword, u_strlen(tokenValue->fChars) + 1);
if(uprv_strcmp(typeKeyword, "alias") == 0) {
member = parseResource(state, subtag, nullptr, status);
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
result->add(member, line, *status);
} else {
res_close(result);
*status = U_INVALID_FORMAT_ERROR;
return nullptr;
}
} else {
res_close(result);
*status = U_INVALID_FORMAT_ERROR;
return nullptr;
}
}
/*member = string_open(bundle, subtag, tokenValue->fChars, tokenValue->fLength, status);*/
/*expect(TOK_CLOSE_BRACE, nullptr, nullptr, status);*/
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
}
}
}
/* Necessary, because CollationElements requires the bundle->fRoot member to be present which,
if this weren't special-cased, wouldn't be set until the entire file had been processed. */
static struct SResource *
realParseTable(ParseState* state, TableResource *table, char *tag, uint32_t startline, UErrorCode *status)
{
struct SResource *member = nullptr;
struct UString *tokenValue=nullptr;
struct UString comment;
enum ETokenType token;
char subtag[1024];
uint32_t line;
UBool readToken = false;
/* '{' . (name resource)* '}' */
if(isVerbose()){
printf(" parsing table %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
for (;;)
{
ustr_init(&comment);
token = getToken(state, &tokenValue, &comment, &line, status);
if (token == TOK_CLOSE_BRACE)
{
if (!readToken && isVerbose()) {
warning(startline, "Encountered empty table");
}
return table;
}
if (token != TOK_STRING)
{
*status = U_INVALID_FORMAT_ERROR;
if (token == TOK_EOF)
{
error(startline, "unterminated table");
}
else
{
error(line, "unexpected token %s", tokenNames[token]);
}
return nullptr;
}
if(uprv_isInvariantUString(tokenValue->fChars, -1)) {
u_UCharsToChars(tokenValue->fChars, subtag, u_strlen(tokenValue->fChars) + 1);
} else {
*status = U_INVALID_FORMAT_ERROR;
error(line, "invariant characters required for table keys");
return nullptr;
}
if (U_FAILURE(*status))
{
error(line, "parse error. Stopped parsing tokens with %s", u_errorName(*status));
return nullptr;
}
member = parseResource(state, subtag, &comment, status);
if (member == nullptr || U_FAILURE(*status))
{
error(line, "parse error. Stopped parsing resource with %s", u_errorName(*status));
return nullptr;
}
table->add(member, line, *status);
if (U_FAILURE(*status))
{
error(line, "parse error. Stopped parsing table with %s", u_errorName(*status));
return nullptr;
}
readToken = true;
ustr_deinit(&comment);
}
/* not reached */
/* A compiler warning will appear if all paths don't contain a return statement. */
/* *status = U_INTERNAL_PROGRAM_ERROR;
return nullptr;*/
}
static struct SResource *
parseTable(ParseState* state, char *tag, uint32_t startline, const struct UString *comment, UErrorCode *status)
{
if (tag != nullptr && uprv_strcmp(tag, "CollationElements") == 0)
{
return parseCollationElements(state, tag, startline, false, status);
}
if (tag != nullptr && uprv_strcmp(tag, "collations") == 0)
{
return parseCollationElements(state, tag, startline, true, status);
}
if(isVerbose()){
printf(" table %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
TableResource *result = table_open(state->bundle, tag, comment, status);
if (result == nullptr || U_FAILURE(*status))
{
return nullptr;
}
return realParseTable(state, result, tag, startline, status);
}
static struct SResource *
parseArray(ParseState* state, char *tag, uint32_t startline, const struct UString *comment, UErrorCode *status)
{
struct SResource *member = nullptr;
struct UString *tokenValue;
struct UString memberComments;
enum ETokenType token;
UBool readToken = false;
ArrayResource *result = array_open(state->bundle, tag, comment, status);
if (result == nullptr || U_FAILURE(*status))
{
return nullptr;
}
if(isVerbose()){
printf(" array %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
ustr_init(&memberComments);
/* '{' . resource [','] '}' */
for (;;)
{
/* reset length */
ustr_setlen(&memberComments, 0, status);
/* check for end of array, but don't consume next token unless it really is the end */
token = peekToken(state, 0, &tokenValue, nullptr, &memberComments, status);
if (token == TOK_CLOSE_BRACE)
{
getToken(state, nullptr, nullptr, nullptr, status);
if (!readToken) {
warning(startline, "Encountered empty array");
}
break;
}
if (token == TOK_EOF)
{
res_close(result);
*status = U_INVALID_FORMAT_ERROR;
error(startline, "unterminated array");
return nullptr;
}
/* string arrays are a special case */
if (token == TOK_STRING)
{
getToken(state, &tokenValue, &memberComments, nullptr, status);
member = string_open(state->bundle, nullptr, tokenValue->fChars, tokenValue->fLength, &memberComments, status);
}
else
{
member = parseResource(state, nullptr, &memberComments, status);
}
if (member == nullptr || U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
result->add(member);
/* eat optional comma if present */
token = peekToken(state, 0, nullptr, nullptr, nullptr, status);
if (token == TOK_COMMA)
{
getToken(state, nullptr, nullptr, nullptr, status);
}
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
readToken = true;
}
ustr_deinit(&memberComments);
return result;
}
static struct SResource *
parseIntVector(ParseState* state, char *tag, uint32_t startline, const struct UString *comment, UErrorCode *status)
{
enum ETokenType token;
char *string;
int32_t value;
UBool readToken = false;
char *stopstring;
struct UString memberComments;
IntVectorResource *result = intvector_open(state->bundle, tag, comment, status);
if (result == nullptr || U_FAILURE(*status))
{
return nullptr;
}
if(isVerbose()){
printf(" vector %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
ustr_init(&memberComments);
/* '{' . string [','] '}' */
for (;;)
{
ustr_setlen(&memberComments, 0, status);
/* check for end of array, but don't consume next token unless it really is the end */
token = peekToken(state, 0, nullptr, nullptr,&memberComments, status);
if (token == TOK_CLOSE_BRACE)
{
/* it's the end, consume the close brace */
getToken(state, nullptr, nullptr, nullptr, status);
if (!readToken) {
warning(startline, "Encountered empty int vector");
}
ustr_deinit(&memberComments);
return result;
}
int32_t stringLength;
string = getInvariantString(state, nullptr, nullptr, stringLength, status);
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
/* For handling illegal char in the Intvector */
value = uprv_strtoul(string, &stopstring, 0);/* make intvector support decimal,hexdigit,octal digit ranging from -2^31-2^32-1*/
int32_t len = (int32_t)(stopstring-string);
if(len==stringLength)
{
result->add(value, *status);
uprv_free(string);
token = peekToken(state, 0, nullptr, nullptr, nullptr, status);
}
else
{
uprv_free(string);
*status=U_INVALID_CHAR_FOUND;
}
if (U_FAILURE(*status))
{
res_close(result);
return nullptr;
}
/* the comma is optional (even though it is required to prevent the reader from concatenating
consecutive entries) so that a missing comma on the last entry isn't an error */
if (token == TOK_COMMA)
{
getToken(state, nullptr, nullptr, nullptr, status);
}
readToken = true;
}
/* not reached */
/* A compiler warning will appear if all paths don't contain a return statement. */
/* intvector_close(result, status);
*status = U_INTERNAL_PROGRAM_ERROR;
return nullptr;*/
}
static struct SResource *
parseBinary(ParseState* state, char *tag, uint32_t startline, const struct UString *comment, UErrorCode *status)
{
uint32_t line;
int32_t stringLength;
LocalMemory<char> string(getInvariantString(state, &line, nullptr, stringLength, status));
if (string.isNull() || U_FAILURE(*status))
{
return nullptr;
}
expect(state, TOK_CLOSE_BRACE, nullptr, nullptr, nullptr, status);
if (U_FAILURE(*status))
{
return nullptr;
}
if(isVerbose()){
printf(" binary %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
LocalMemory<uint8_t> value;
int32_t count = 0;
if (stringLength > 0 && value.allocateInsteadAndCopy(stringLength) == nullptr)
{
*status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
char toConv[3] = {'\0', '\0', '\0'};
for (int32_t i = 0; i < stringLength;)
{
// Skip spaces (which may have been line endings).
char c0 = string[i++];
if (c0 == ' ') { continue; }
if (i == stringLength) {
*status=U_INVALID_CHAR_FOUND;
error(line, "Encountered invalid binary value (odd number of hex digits)");
return nullptr;
}
toConv[0] = c0;
toConv[1] = string[i++];
char *stopstring;
value[count++] = (uint8_t) uprv_strtoul(toConv, &stopstring, 16);
uint32_t len=(uint32_t)(stopstring-toConv);
if(len!=2)
{
*status=U_INVALID_CHAR_FOUND;
error(line, "Encountered invalid binary value (not all pairs of hex digits)");
return nullptr;
}
}
if (count == 0) {
warning(startline, "Encountered empty binary value");
return bin_open(state->bundle, tag, 0, nullptr, "", comment, status);
} else {
return bin_open(state->bundle, tag, count, value.getAlias(), nullptr, comment, status);
}
}
static struct SResource *
parseInteger(ParseState* state, char *tag, uint32_t startline, const struct UString *comment, UErrorCode *status)
{
struct SResource *result = nullptr;
int32_t value;
char *string;
char *stopstring;
int32_t stringLength;
string = getInvariantString(state, nullptr, nullptr, stringLength, status);
if (string == nullptr || U_FAILURE(*status))
{
return nullptr;
}
expect(state, TOK_CLOSE_BRACE, nullptr, nullptr, nullptr, status);
if (U_FAILURE(*status))
{
uprv_free(string);
return nullptr;
}
if(isVerbose()){
printf(" integer %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
if (stringLength == 0)
{
warning(startline, "Encountered empty integer. Default value is 0.");
}
/* Allow integer support for hexdecimal, octal digit and decimal*/
/* and handle illegal char in the integer*/
value = uprv_strtoul(string, &stopstring, 0);
int32_t len = (int32_t)(stopstring-string);
if(len==stringLength)
{
result = int_open(state->bundle, tag, value, comment, status);
}
else
{
*status=U_INVALID_CHAR_FOUND;
}
uprv_free(string);
return result;
}
static struct SResource *
parseImport(ParseState* state, char *tag, uint32_t startline, const struct UString* comment, UErrorCode *status)
{
uint32_t line;
int32_t stringLength;
LocalMemory<char> filename(getInvariantString(state, &line, nullptr, stringLength, status));
if (U_FAILURE(*status))
{
return nullptr;
}
expect(state, TOK_CLOSE_BRACE, nullptr, nullptr, nullptr, status);
if (U_FAILURE(*status))
{
return nullptr;
}
if(isVerbose()){
printf(" import %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
/* Open the input file for reading */
CharString fullname;
if (state->inputdir != nullptr) {
fullname.append(state->inputdir, *status);
}
fullname.appendPathPart(filename.getAlias(), *status);
if (U_FAILURE(*status)) {
return nullptr;
}
FileStream *file = T_FileStream_open(fullname.data(), "rb");
if (file == nullptr)
{
error(line, "couldn't open input file %s", filename.getAlias());
*status = U_FILE_ACCESS_ERROR;
return nullptr;
}
int32_t len = T_FileStream_size(file);
LocalMemory<uint8_t> data;
if(data.allocateInsteadAndCopy(len) == nullptr)
{
*status = U_MEMORY_ALLOCATION_ERROR;
T_FileStream_close (file);
return nullptr;
}
/* int32_t numRead = */ T_FileStream_read(file, data.getAlias(), len);
T_FileStream_close (file);
return bin_open(state->bundle, tag, len, data.getAlias(), fullname.data(), comment, status);
}
static struct SResource *
parseInclude(ParseState* state, char *tag, uint32_t startline, const struct UString* comment, UErrorCode *status)
{
struct SResource *result;
int32_t len=0;
char *filename;
uint32_t line;
char16_t *pTarget = nullptr;
UCHARBUF *ucbuf;
char *fullname = nullptr;
const char* cp = nullptr;
const char16_t* uBuffer = nullptr;
int32_t stringLength;
filename = getInvariantString(state, &line, nullptr, stringLength, status);
if (U_FAILURE(*status))
{
return nullptr;
}
expect(state, TOK_CLOSE_BRACE, nullptr, nullptr, nullptr, status);
if (U_FAILURE(*status))
{
uprv_free(filename);
return nullptr;
}
if(isVerbose()){
printf(" include %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
fullname = (char *) uprv_malloc(state->inputdirLength + stringLength + 2);
/* test for nullptr */
if(fullname == nullptr)
{
*status = U_MEMORY_ALLOCATION_ERROR;
uprv_free(filename);
return nullptr;
}
if(state->inputdir!=nullptr){
if (state->inputdir[state->inputdirLength - 1] != U_FILE_SEP_CHAR)
{
uprv_strcpy(fullname, state->inputdir);
fullname[state->inputdirLength] = U_FILE_SEP_CHAR;
fullname[state->inputdirLength + 1] = '\0';
uprv_strcat(fullname, filename);
}
else
{
uprv_strcpy(fullname, state->inputdir);
uprv_strcat(fullname, filename);
}
}else{
uprv_strcpy(fullname,filename);
}
ucbuf = ucbuf_open(fullname, &cp,getShowWarning(),false,status);
if (U_FAILURE(*status)) {
error(line, "couldn't open input file %s\n", filename);
return nullptr;
}
uBuffer = ucbuf_getBuffer(ucbuf,&len,status);
result = string_open(state->bundle, tag, uBuffer, len, comment, status);
ucbuf_close(ucbuf);
uprv_free(pTarget);
uprv_free(filename);
uprv_free(fullname);
return result;
}
U_STRING_DECL(k_type_string, "string", 6);
U_STRING_DECL(k_type_binary, "binary", 6);
U_STRING_DECL(k_type_bin, "bin", 3);
U_STRING_DECL(k_type_table, "table", 5);
U_STRING_DECL(k_type_table_no_fallback, "table(nofallback)", 17);
U_STRING_DECL(k_type_int, "int", 3);
U_STRING_DECL(k_type_integer, "integer", 7);
U_STRING_DECL(k_type_array, "array", 5);
U_STRING_DECL(k_type_alias, "alias", 5);
U_STRING_DECL(k_type_intvector, "intvector", 9);
U_STRING_DECL(k_type_import, "import", 6);
U_STRING_DECL(k_type_include, "include", 7);
/* Various non-standard processing plugins that create one or more special resources. */
U_STRING_DECL(k_type_plugin_uca_rules, "process(uca_rules)", 18);
U_STRING_DECL(k_type_plugin_collation, "process(collation)", 18);
U_STRING_DECL(k_type_plugin_transliterator, "process(transliterator)", 23);
U_STRING_DECL(k_type_plugin_dependency, "process(dependency)", 19);
typedef enum EResourceType
{
RESTYPE_UNKNOWN,
RESTYPE_STRING,
RESTYPE_BINARY,
RESTYPE_TABLE,
RESTYPE_TABLE_NO_FALLBACK,
RESTYPE_INTEGER,
RESTYPE_ARRAY,
RESTYPE_ALIAS,
RESTYPE_INTVECTOR,
RESTYPE_IMPORT,
RESTYPE_INCLUDE,
RESTYPE_PROCESS_UCA_RULES,
RESTYPE_PROCESS_COLLATION,
RESTYPE_PROCESS_TRANSLITERATOR,
RESTYPE_PROCESS_DEPENDENCY,
RESTYPE_RESERVED
} EResourceType;
static struct {
const char *nameChars; /* only used for debugging */
const char16_t *nameUChars;
ParseResourceFunction *parseFunction;
} gResourceTypes[] = {
{"Unknown", nullptr, nullptr},
{"string", k_type_string, parseString},
{"binary", k_type_binary, parseBinary},
{"table", k_type_table, parseTable},
{"table(nofallback)", k_type_table_no_fallback, nullptr}, /* parseFunction will never be called */
{"integer", k_type_integer, parseInteger},
{"array", k_type_array, parseArray},
{"alias", k_type_alias, parseAlias},
{"intvector", k_type_intvector, parseIntVector},
{"import", k_type_import, parseImport},
{"include", k_type_include, parseInclude},
{"process(uca_rules)", k_type_plugin_uca_rules, parseUCARules},
{"process(collation)", k_type_plugin_collation, nullptr /* not implemented yet */},
{"process(transliterator)", k_type_plugin_transliterator, parseTransliterator},
{"process(dependency)", k_type_plugin_dependency, parseDependency},
{"reserved", nullptr, nullptr}
};
void initParser()
{
U_STRING_INIT(k_type_string, "string", 6);
U_STRING_INIT(k_type_binary, "binary", 6);
U_STRING_INIT(k_type_bin, "bin", 3);
U_STRING_INIT(k_type_table, "table", 5);
U_STRING_INIT(k_type_table_no_fallback, "table(nofallback)", 17);
U_STRING_INIT(k_type_int, "int", 3);
U_STRING_INIT(k_type_integer, "integer", 7);
U_STRING_INIT(k_type_array, "array", 5);
U_STRING_INIT(k_type_alias, "alias", 5);
U_STRING_INIT(k_type_intvector, "intvector", 9);
U_STRING_INIT(k_type_import, "import", 6);
U_STRING_INIT(k_type_include, "include", 7);
U_STRING_INIT(k_type_plugin_uca_rules, "process(uca_rules)", 18);
U_STRING_INIT(k_type_plugin_collation, "process(collation)", 18);
U_STRING_INIT(k_type_plugin_transliterator, "process(transliterator)", 23);
U_STRING_INIT(k_type_plugin_dependency, "process(dependency)", 19);
}
static inline UBool isTable(enum EResourceType type) {
return (UBool)(type==RESTYPE_TABLE || type==RESTYPE_TABLE_NO_FALLBACK);
}
static enum EResourceType
parseResourceType(ParseState* state, UErrorCode *status)
{
struct UString *tokenValue;
struct UString comment;
enum EResourceType result = RESTYPE_UNKNOWN;
uint32_t line=0;
ustr_init(&comment);
expect(state, TOK_STRING, &tokenValue, &comment, &line, status);
if (U_FAILURE(*status))
{
return RESTYPE_UNKNOWN;
}
*status = U_ZERO_ERROR;
/* Search for normal types */
result=RESTYPE_UNKNOWN;
while ((result=(EResourceType)(result+1)) < RESTYPE_RESERVED) {
if (u_strcmp(tokenValue->fChars, gResourceTypes[result].nameUChars) == 0) {
break;
}
}
/* Now search for the aliases */
if (u_strcmp(tokenValue->fChars, k_type_int) == 0) {
result = RESTYPE_INTEGER;
}
else if (u_strcmp(tokenValue->fChars, k_type_bin) == 0) {
result = RESTYPE_BINARY;
}
else if (result == RESTYPE_RESERVED) {
char tokenBuffer[1024];
u_austrncpy(tokenBuffer, tokenValue->fChars, sizeof(tokenBuffer));
tokenBuffer[sizeof(tokenBuffer) - 1] = 0;
*status = U_INVALID_FORMAT_ERROR;
error(line, "unknown resource type '%s'", tokenBuffer);
}
return result;
}
/* parse a non-top-level resource */
static struct SResource *
parseResource(ParseState* state, char *tag, const struct UString *comment, UErrorCode *status)
{
enum ETokenType token;
enum EResourceType resType = RESTYPE_UNKNOWN;
ParseResourceFunction *parseFunction = nullptr;
struct UString *tokenValue;
uint32_t startline;
uint32_t line;
token = getToken(state, &tokenValue, nullptr, &startline, status);
if(isVerbose()){
printf(" resource %s at line %i \n", (tag == nullptr) ? "(null)" : tag, (int)startline);
}
/* name . [ ':' type ] '{' resource '}' */
/* This function parses from the colon onwards. If the colon is present, parse the
type then try to parse a resource of that type. If there is no explicit type,
work it out using the lookahead tokens. */
switch (token)
{
case TOK_EOF:
*status = U_INVALID_FORMAT_ERROR;
error(startline, "Unexpected EOF encountered");
return nullptr;
case TOK_ERROR:
*status = U_INVALID_FORMAT_ERROR;
return nullptr;
case TOK_COLON:
resType = parseResourceType(state, status);
expect(state, TOK_OPEN_BRACE, &tokenValue, nullptr, &startline, status);
if (U_FAILURE(*status))
{
return nullptr;
}
break;
case TOK_OPEN_BRACE:
break;
default:
*status = U_INVALID_FORMAT_ERROR;
error(startline, "syntax error while reading a resource, expected '{' or ':'");
return nullptr;
}
if (resType == RESTYPE_UNKNOWN)
{
/* No explicit type, so try to work it out. At this point, we've read the first '{'.
We could have any of the following:
{ { => array (nested)
{ :/} => array
{ string , => string array
{ string { => table
{ string :/{ => table
{ string } => string
*/
token = peekToken(state, 0, nullptr, &line, nullptr,status);
if (U_FAILURE(*status))
{
return nullptr;
}
if (token == TOK_OPEN_BRACE || token == TOK_COLON ||token ==TOK_CLOSE_BRACE )
{
resType = RESTYPE_ARRAY;
}
else if (token == TOK_STRING)
{
token = peekToken(state, 1, nullptr, &line, nullptr, status);
if (U_FAILURE(*status))
{
return nullptr;
}
switch (token)
{
case TOK_COMMA: resType = RESTYPE_ARRAY; break;
case TOK_OPEN_BRACE: resType = RESTYPE_TABLE; break;
case TOK_CLOSE_BRACE: resType = RESTYPE_STRING; break;
case TOK_COLON: resType = RESTYPE_TABLE; break;
default:
*status = U_INVALID_FORMAT_ERROR;
error(line, "Unexpected token after string, expected ',', '{' or '}'");
return nullptr;
}
}
else
{
*status = U_INVALID_FORMAT_ERROR;
error(line, "Unexpected token after '{'");
return nullptr;
}
/* printf("Type guessed as %s\n", resourceNames[resType]); */
} else if(resType == RESTYPE_TABLE_NO_FALLBACK) {
*status = U_INVALID_FORMAT_ERROR;
error(startline, "error: %s resource type not valid except on top bundle level", gResourceTypes[resType].nameChars);
return nullptr;
}
/* We should now know what we need to parse next, so call the appropriate parser
function and return. */
parseFunction = gResourceTypes[resType].parseFunction;
if (parseFunction != nullptr) {
return parseFunction(state, tag, startline, comment, status);
}
else {
*status = U_INTERNAL_PROGRAM_ERROR;
error(startline, "internal error: %s resource type found and not handled", gResourceTypes[resType].nameChars);
}
return nullptr;
}
/* parse the top-level resource */
struct SRBRoot *
parse(UCHARBUF *buf, const char *inputDir, const char *outputDir, const char *filename,
UBool makeBinaryCollation, UBool omitCollationRules, UBool icu4xMode, UErrorCode *status)
{
struct UString *tokenValue;
struct UString comment;
uint32_t line;
enum EResourceType bundleType;
enum ETokenType token;
ParseState state;
uint32_t i;
for (i = 0; i < MAX_LOOKAHEAD + 1; i++)
{
ustr_init(&state.lookahead[i].value);
ustr_init(&state.lookahead[i].comment);
}
initLookahead(&state, buf, status);
state.inputdir = inputDir;
state.inputdirLength = (state.inputdir != nullptr) ? (uint32_t)uprv_strlen(state.inputdir) : 0;
state.outputdir = outputDir;
state.outputdirLength = (state.outputdir != nullptr) ? (uint32_t)uprv_strlen(state.outputdir) : 0;
state.filename = filename;
state.makeBinaryCollation = makeBinaryCollation;
state.omitCollationRules = omitCollationRules;
state.icu4xMode = icu4xMode;
ustr_init(&comment);
expect(&state, TOK_STRING, &tokenValue, &comment, nullptr, status);
state.bundle = new SRBRoot(&comment, false, *status);
if (state.bundle == nullptr || U_FAILURE(*status))
{
delete state.bundle;
return nullptr;
}
state.bundle->setLocale(tokenValue->fChars, *status);
/* The following code is to make Empty bundle work no matter with :table specifer or not */
token = getToken(&state, nullptr, nullptr, &line, status);
if(token==TOK_COLON) {
*status=U_ZERO_ERROR;
bundleType=parseResourceType(&state, status);
if(isTable(bundleType))
{
expect(&state, TOK_OPEN_BRACE, nullptr, nullptr, &line, status);
}
else
{
*status=U_PARSE_ERROR;
error(line, "parse error. Stopped parsing with %s", u_errorName(*status));
}
}
else
{
/* not a colon */
if(token==TOK_OPEN_BRACE)
{
*status=U_ZERO_ERROR;
bundleType=RESTYPE_TABLE;
}
else
{
/* neither colon nor open brace */
*status=U_PARSE_ERROR;
bundleType=RESTYPE_UNKNOWN;
error(line, "parse error, did not find open-brace '{' or colon ':', stopped with %s", u_errorName(*status));
}
}
if (U_FAILURE(*status))
{
delete state.bundle;
return nullptr;
}
if(bundleType==RESTYPE_TABLE_NO_FALLBACK) {
/*
* Parse a top-level table with the table(nofallback) declaration.
* This is the same as a regular table, but also sets the
* URES_ATT_NO_FALLBACK flag in indexes[URES_INDEX_ATTRIBUTES] .
*/
state.bundle->fNoFallback=true;
}
/* top-level tables need not handle special table names like "collations" */
assert(!state.bundle->fIsPoolBundle);
assert(state.bundle->fRoot->fType == URES_TABLE);
TableResource *rootTable = static_cast<TableResource *>(state.bundle->fRoot);
realParseTable(&state, rootTable, nullptr, line, status);
if(dependencyArray!=nullptr){
rootTable->add(dependencyArray, 0, *status);
dependencyArray = nullptr;
}
if (U_FAILURE(*status))
{
delete state.bundle;
res_close(dependencyArray);
return nullptr;
}
if (getToken(&state, nullptr, nullptr, &line, status) != TOK_EOF)
{
warning(line, "extraneous text after resource bundle (perhaps unmatched braces)");
if(isStrict()){
*status = U_INVALID_FORMAT_ERROR;
return nullptr;
}
}
cleanupLookahead(&state);
ustr_deinit(&comment);
return state.bundle;
}
|