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 |
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x6
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x339
x6
x6
x339
x339
x339
x6
x624
x519
x519
x519
x624
x6
x115
x115
x115
x115
x115
x115
x6
x327
x319
x319
x319
x319
x8
x327
x6
x549
x541
x541
x541
x541
x541
x541
x8
x549
x6
x6
x6
x16
x16
x4
x4
x4
x4
x4
x4
x12
x16
x6
x6
x6
x8
x8
x8
x6
x6
x6
x8
x8
x8
x6
x2272
x2272
x2272
x6
x853
x634
x634
x634
x634
x634
x69
x69
x1
x5
x5
x5
x5
x1
x1
x1
x1
x1
x5
x68
x69
x5
x5
x5
x63
x69
x69
x69
x69
x69
x69
x634
x853
x6
x136
x136
x136
x136
x136
x136
x6
x422
x422
x422
x422
x422
x422
x6
x143
x143
x143
x143
x143
x143
x6
x55
x55
x55
x55
x55
x55
x6
x436
x436
x436
x436
x436
x436
x436
x436
x436
x436
x371
x371
x65
x65
x385
x18
x18
x18
x385
x24
x24
x24
x385
x1
x1
x1
x385
x1
x1
x1
x65
x385
x385
x385
x385
x436
x6
x5753
x5250
x1
x1
x5250
x5249
x5249
x5250
x5250
x5753
x5753
x6
x245
x215
x215
x221
x221
x215
x215
x215
x6
x6
x6
x6
x215
x245
x6
x436
x436
x436
x436
x6
x37
x37
x37
x37
x5
x1
x1
x4
x4
x4
x37
x4
x1
x1
x3
x3
x3
x37
x2
x1
x1
x1
x1
x1
x1
x3
x37
x1
x37
x1
x1
x1
x1
x37
x6
x29
x29
x2
x2
x2
x27
x29
x2
x2
x2
x25
x23
x23
x25
x25
x29
x12
x12
x29
x29
x29
x29
x29
x29
x29
x29
x6
x13
x13
x13
x13
x13
x13
x13
x281
x281
x281
x13
x1
x1
x12
x12
x13
x6
x10
x178
x178
x178
x178
x178
x178
x178
x178
x178
x178
x178
x178
x178
x178
x178
x1
x1
x1
x1
x1
x178
x10
x6
x654
x636
x525
x525
x525
x525
x636
x636
x654
x531
x531
x531
x531
x531
x821
x821
x523
x523
x523
x523
x523
x523
x298
x821
x821
x821
x2
x2
x2
x2
x2
x2
x2
x2
x2
x818
x16
x16
x818
x280
x280
x296
x296
x296
x6
x6
x6
x6
x654
x123
x123
x109
x109
x109
x14
x14
x20
x654
x6
x591
x591
x2067
x2067
x2067
x1498
x1498
x591
x4
x12
x12
x4
x8
x8
x8
x12
x4
x591
x451
x451
x451
x451
x591
x591
x6
x32
x32
x21
x21
x21
x3
x3
x3
x21
x21
x21
x21
x1
x1
x1
x1
x17
x21
x1192
x1192
x2
x2
x2
x2
x2
x2
x1192
x15
x15
x15
x15
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x11
x32
x32
x32
x32
x8
x8
x8
x8
x8
x1
x1
x8
x11
x11
x11
x11
x11
x44
x44
x11
x11
x11
x11
x11
x11
x32
x6
x54
x54
x46
x46
x876
x876
x2
x2
x2
x2
x2
x2
x876
x44
x44
x44
x44
x46
x27
x46
x17
x17
x17
x17
x17
x17
x17
x17
x28
x28
x28
x28
x28
x28
x8
x54
x54
x54
x54
x5
x5
x8
x8
x8
x66
x66
x8
x8
x8
x8
x8
x8
x54
x6
x29
x29
x21
x21
x205
x205
x2
x2
x2
x2
x2
x2
x205
x19
x19
x19
x19
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
x8
x29
x29
x29
x29
x6
x6
x6
x6
x6
x2
x2
x6
x8
x8
x8
x25
x25
x8
x8
x8
x8
x8
x8
x29
x6
x6
x6
x6
x143
x143
x143
x143
x139
x139
x3
x3
x3
x136
x136
x136
x136
x4
x4
x4
x4
x4
x4
x4
x4
x143
x6
x436
x436
x436
x436
x436
x436
x436
x436
x436
x338
x338
x436
x5556
x5556
x5556
x654
x632
x632
x632
x632
x632
x644
x644
x5556
x310
x310
x10
x10
x300
x310
x67
x67
x67
x67
x67
x67
x67
x310
x145
x145
x145
x145
x145
x145
x145
x145
x233
x86
x86
x86
x86
x86
x86
x86
x88
x2
x2
x2
x2
x2
x295
x295
x5556
x137
x137
x137
x137
x127
x123
x1
x1
x1
x1
x1
x122
x127
x4
x4
x4
x4
x6
x6
x4
x127
x136
x137
x11
x11
x125
x137
x4
x4
x4
x4
x137
x120
x120
x120
x120
x120
x120
x120
x121
x1
x1
x1
x1
x1
x121
x121
x5556
x140
x134
x134
x134
x134
x134
x134
x134
x134
x133
x133
x5556
x277
x81
x81
x81
x81
x81
x81
x81
x81
x277
x11
x11
x11
x11
x194
x39
x39
x39
x185
x185
x185
x185
x185
x145
x145
x1
x1
x144
x144
x144
x144
x146
x1
x1
x1
x1
x1
x275
x275
x5556
x145
x145
x1
x1
x144
x145
x3
x3
x3
x3
x145
x140
x140
x140
x140
x141
x1
x1
x1
x1
x1
x143
x143
x5556
x623
x127
x127
x127
x127
x619
x135
x135
x496
x59
x59
x59
x59
x361
x298
x1
x1
x1
x297
x297
x297
x297
x302
x4
x4
x4
x4
x4
x4
x4
x6
x6
x4
x4
x622
x622
x5556
x147
x5
x147
x137
x137
x137
x137
x142
x3
x3
x3
x3
x5
x2
x2
x145
x145
x5556
x4
x1
x4
x2
x2
x3
x1
x1
x3
x3
x5556
x125
x124
x124
x124
x125
x1
x1
x120
x120
x5556
x6
x2
x6
x3
x3
x3
x3
x3
x3
x3
x3
x4
x1
x1
x1
x5
x5
x5556
x3
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x5556
x32
x15
x15
x29
x3
x3
x8
x8
x8
x8
x8
x8
x8
x8
x8
x5556
x29
x17
x17
x23
x2
x2
x6
x6
x6
x6
x6
x6
x6
x6
x6
x5556
x54
x28
x28
x43
x3
x3
x5
x5
x5
x5
x5
x5
x5
x5
x5556
x134
x29
x29
x134
x26
x26
x26
x105
x78
x78
x78
x79
x1
x1
x133
x133
x5556
x29
x28
x28
x28
x28
x29
x1
x1
x28
x28
x5556
x8
x6
x6
x6
x8
x2
x2
x2
x2
x2
x8
x8
x5556
x8
x4
x4
x4
x4
x4
x4
x4
x2
x2
x2
x2
x4
x4
x4
x4
x4
x4
x4
x4
x4
x4
x2
x2
x2
x2
x2
x2
x2
x4
x4
x5556
x155
x155
x155
x25
x25
x25
x155
x1
x1
x154
x154
x5556
x6
x4
x4
x4
x6
x2
x2
x2
x2
x6
x6
x5556
x4
x3
x3
x3
x3
x3
x3
x3
x3
x3
x1
x1
x1
x1
x4
x4
x5556
x251
x251
x251
x59
x59
x57
x59
x1
x1
x1
x1
x1
x1
x1
x251
x136
x192
x50
x50
x50
x50
x50
x50
x56
x5
x5
x5
x5
x6
x1
x1
x1
x1
x1
x248
x248
x5556
x4
x3
x1
x3
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x2
x4
x1
x1
x1
x1
x1
x2
x2
x5556
x5
x3
x1
x1
x1
x3
x2
x2
x2
x2
x2
x2
x2
x2
x3
x3
x3
x3
x2
x2
x2
x2
x2
x5
x5
x5556
x467
x467
x467
x76
x76
x76
x76
x467
x1
x1
x466
x466
x5556
x459
x147
x147
x71
x71
x459
x2
x2
x2
x2
x2
x2
x2
x2
x2
x312
x1
x1
x1
x310
x310
x310
x310
x308
x308
x309
x1
x1
x1
x1
x1
x458
x458
x5556
x31
x31
x31
x31
x31
x31
x31
x31
x31
x102
x52
x52
x52
x71
x9
x9
x9
x19
x4
x4
x4
x10
x3
x3
x3
x3
x3
x3
x3
x2
x2
x2
x2
x2
x1
x1
x3
x3
x3
x3
x3
x3
x3
x3
x2
x2
x2
x2
x2
x1
x1
x96
x96
x5556
x45
x45
x45
x8
x45
x1
x1
x44
x44
x5556
x16
x8
x8
x7
x7
x7
x7
x7
x7
x7
x8
x1
x1
x14
x14
x5556
x11
x5
x11
x4
x4
x4
x4
x6
x1
x1
x1
x1
x1
x1
x1
x1
x1
x1
x1
x1
x10
x10
x5556
x20
x20
x20
x3
x20
x1
x1
x19
x19
x5556
x6
x3
x3
x2
x2
x2
x2
x3
x1
x1
x4
x4
x5556
x81
x26
x26
x26
x26
x26
x81
x48
x48
x55
x1
x7
x1
x1
x6
x4
x4
x5
x1
x1
x1
x1
x1
x79
x79
x5556
x48
x42
x42
x42
x48
x5
x5
x6
x1
x1
x47
x47
x5556
x258
x8
x7
x7
x8
x1
x1
x1
x258
x32
x32
x32
x32
x32
x31
x31
x31
x31
x31
x31
x31
x31
x31
x31
x31
x32
x1
x1
x250
x250
x250
x250
x217
x217
x218
x1
x1
x1
x1
x1
x255
x255
x5556
x398
x19
x8
x8
x8
x8
x8
x1
x1
x1
x8
x7
x7
x7
x7
x8
x18
x18
x18
x398
x19
x1
x1
x1
x19
x15
x15
x18
x18
x18
x18
x19
x15
x15
x15
x15
x15
x3
x3
x15
x18
x379
x64
x14
x14
x57
x57
x360
x10
x1
x1
x1
x9
x9
x9
x296
x10
x1
x1
x9
x9
x9
x5
x5
x276
x4
x4
x271
x1
x1
x1
x1
x1
x1
x1
x1
x6
x6
x266
x266
x266
x256
x123
x42
x123
x81
x81
x123
x256
x256
x3
x3
x4
x1
x1
x1
x1
x1
x398
x398
x398
x398
x17
x17
x386
x386
x5556
x167
x17
x3
x3
x3
x3
x17
x13
x13
x17
x17
x17
x167
x150
x24
x24
x150
x150
x167
x167
x5556
x7
x6
x6
x7
x1
x1
x6
x6
x5556
x47
x7
x7
x47
x40
x40
x47
x47
x5556
x7
x5
x5
x7
x2
x2
x2
x7
x7
x5556
x5
x3
x3
x5
x2
x2
x2
x2
x3
x3
x5556
x76
x5
x5
x76
x71
x71
x76
x76
x5556
x8
x4
x4
x4
x3
x4
x1
x1
x1
x8
x8
x5556
x38
x2
x2
x38
x35
x36
x1
x1
x37
x37
x5556
x5556
x436
x6
x221
x221
x221
x17
x17
x17
x221
x6
x17
x17
x1
x17
x17
x17
x17
x17
x17
x1
x17
x17
x1
x17
x17
x1
x17
x17
x17
x17
x1
x17
x17
x17
x17
x1
x17
x17
x17
x17
x3
x17
x1
x17
x17
x17
x17
x17
x17
x17
x17
x17
x17
x17
x17
x17
x17
x4
x17
x17
x17
x17
x1
x17
x17
x1
x17
x1
x17
x17
x6 |
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
|
// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.
/**
* Internal XML tokenizer module.
*
* Implements a stateful streaming tokenizer that processes XML input chunk by chunk,
* handling chunk boundaries and tracking position information.
*
* @module
*/
import {
type XmlPosition,
XmlSyntaxError,
type XmlTokenCallbacks,
} from "./types.ts";
import {
isReservedPiTarget,
LINE_ENDING_REGEXP,
validateXmlDeclaration,
} from "./_common.ts";
import { isNameChar, isNameStartChar } from "./_name_chars.ts";
/** Options for the XML tokenizer. */
interface XmlTokenizerOptions {
/**
* If true, track line/column positions for tokens and error messages.
* Disabling position tracking improves performance by ~20%.
*
* @default {true}
*/
readonly trackPosition?: boolean;
/**
* If true, reject DOCTYPE declarations immediately.
*
* @default {false}
*/
readonly disallowDoctype?: boolean;
}
/** Tokenizer state machine states. */
const State = {
/** Waiting for < or text content */
INITIAL: 0,
/** Just saw <, determining tag type */
TAG_OPEN: 1,
/** Reading element name after < */
TAG_NAME: 2,
/** Reading </element name */
END_TAG_NAME: 3,
/** Between tag name and > or attributes */
AFTER_TAG_NAME: 4,
/** Reading attribute name */
ATTRIBUTE_NAME: 5,
/** After attribute name, expecting = */
AFTER_ATTRIBUTE_NAME: 6,
/** After =, expecting quote */
BEFORE_ATTRIBUTE_VALUE: 7,
/** Reading attribute value (double quoted) */
ATTRIBUTE_VALUE_DOUBLE: 8,
/** Reading attribute value (single quoted) */
ATTRIBUTE_VALUE_SINGLE: 9,
/** Inside <![CDATA[...]]> */
CDATA: 10,
/** Inside <!--...--> */
COMMENT: 11,
/** Reading PI target name */
PI_TARGET: 12,
/** Reading PI content */
PI_CONTENT: 13,
/** After <! */
MARKUP_DECLARATION: 14,
/** After <!- */
COMMENT_START: 15,
/** After <![, expecting CDATA[ */
CDATA_START: 16,
/** After </element name, expecting > */
AFTER_END_TAG_NAME: 17,
/** Reading <!DOCTYPE */
DOCTYPE_START: 18,
/** Reading DOCTYPE name */
DOCTYPE_NAME: 19,
/** After DOCTYPE name, before PUBLIC/SYSTEM or > */
DOCTYPE_AFTER_NAME: 20,
/** Reading PUBLIC keyword */
DOCTYPE_PUBLIC: 21,
/** Reading public ID literal */
DOCTYPE_PUBLIC_ID: 22,
/** After public ID, expecting system ID */
DOCTYPE_AFTER_PUBLIC_ID: 23,
/** Reading SYSTEM keyword */
DOCTYPE_SYSTEM: 24,
/** Reading system ID literal */
DOCTYPE_SYSTEM_ID: 25,
/** Inside internal subset [...] */
DOCTYPE_INTERNAL_SUBSET: 26,
/** Inside quoted string in internal subset */
DOCTYPE_INTERNAL_SUBSET_STRING: 27,
/** After / in start tag, expecting > for self-closing */
EXPECT_SELF_CLOSE_GT: 28,
/** Inside comment, seen one - */
COMMENT_DASH: 29,
/** Inside comment, seen -- (expecting > or spec violation) */
COMMENT_DASH_DASH: 30,
/** Inside CDATA, seen one ] */
CDATA_BRACKET: 31,
/** Inside CDATA, seen ]] */
CDATA_BRACKET_BRACKET: 32,
/** Inside PI target, seen ? (expecting > for empty PI) */
PI_TARGET_QUESTION: 33,
/** Inside PI content, seen ? */
PI_QUESTION: 34,
/** After <! in internal subset, determining declaration type */
DTD_DECL_START: 35,
/** Reading declaration keyword (ENTITY, ELEMENT, ATTLIST, NOTATION) */
DTD_DECL_KEYWORD: 36,
/** Inside DTD declaration, reading tokens */
DTD_DECL_CONTENT: 37,
/** Inside quoted string in DTD declaration */
DTD_DECL_STRING: 38,
/** Inside DTD comment */
DTD_COMMENT: 39,
/** After first - in DTD comment start */
DTD_COMMENT_START: 40,
/** After first - in DTD comment end */
DTD_COMMENT_DASH: 41,
/** After -- in DTD comment, expecting > */
DTD_COMMENT_DASH_DASH: 42,
/** Inside DTD PI */
DTD_PI: 43,
/** After ? in DTD PI, expecting > */
DTD_PI_QUESTION: 44,
/** Inside parameter entity reference %name; */
DTD_PE_REF: 45,
} as const;
type StateType = typeof State[keyof typeof State];
// Character codes for hot path optimization
const CC_LT = 60; // <
const CC_GT = 62; // >
const CC_SLASH = 47; // /
const CC_BANG = 33; // !
const CC_QUESTION = 63; // ?
const CC_EQ = 61; // =
const CC_DQUOTE = 34; // "
const CC_SQUOTE = 39; // '
const CC_SPACE = 32; // space
const CC_TAB = 9; // \t
const CC_LF = 10; // \n
const CC_CR = 13; // \r
const CC_DASH = 45; // -
const CC_LBRACKET = 91; // [
const CC_RBRACKET = 93; // ]
const CC_A_UPPER = 65; // A
const CC_Z_UPPER = 90; // Z
const CC_A_LOWER = 97; // a
const CC_Z_LOWER = 122; // z
const CC_D_UPPER = 68; // D
const CC_P_UPPER = 80; // P
const CC_S_UPPER = 83; // S
// Name character validation is provided by ./_name_chars.ts which implements
// XML 1.0 Fifth Edition NameStartChar/NameChar with optimized ASCII fast path.
// =============================================================================
// XML 1.0 CHARACTER VALIDATION
// =============================================================================
/**
* Lookup table for C0 control characters (0x00-0x1F).
* Valid XML 1.0 Char in this range: #x9 (TAB), #xA (LF), #xD (CR)
* All others are illegal.
*/
const C0_VALID = new Uint8Array(32);
C0_VALID[0x09] = 1; // TAB
C0_VALID[0x0A] = 1; // LF
C0_VALID[0x0D] = 1; // CR
/**
* Lookup table for ASCII NameChar (0x00-0x7F).
* Valid: [a-z] [A-Z] [0-9] _ : - .
* Replaces 10 chained comparisons in {@link XmlTokenizer.#captureNameChars}
* with a single array access.
*/
const ASCII_NAME_CHAR = new Uint8Array(128);
for (let i = 0x61; i <= 0x7A; i++) ASCII_NAME_CHAR[i] = 1; // a-z
for (let i = 0x41; i <= 0x5A; i++) ASCII_NAME_CHAR[i] = 1; // A-Z
for (let i = 0x30; i <= 0x39; i++) ASCII_NAME_CHAR[i] = 1; // 0-9
ASCII_NAME_CHAR[0x5F] = 1; // _
ASCII_NAME_CHAR[0x3A] = 1; // :
ASCII_NAME_CHAR[0x2D] = 1; // -
ASCII_NAME_CHAR[0x2E] = 1; // .
/**
* Lookup table for ASCII NameStartChar (0x00-0x7F).
* Valid: [a-z] [A-Z] _ :
* Used to inline the ASCII fast path at {@link XmlTokenizer.#isNameStartCharAt}
* call sites, avoiding tuple allocation for 99%+ of real XML.
*/
const ASCII_NAME_START_CHAR = new Uint8Array(128);
for (let i = 0x61; i <= 0x7A; i++) ASCII_NAME_START_CHAR[i] = 1; // a-z
for (let i = 0x41; i <= 0x5A; i++) ASCII_NAME_START_CHAR[i] = 1; // A-Z
ASCII_NAME_START_CHAR[0x5F] = 1; // _
ASCII_NAME_START_CHAR[0x3A] = 1; // :
/**
* Matches any C0 control character that is illegal in XML 1.0 content.
* Valid C0 chars: TAB (0x09), LF (0x0A), CR (0x0D). All others are illegal.
* Used as a fast native pre-check in {@link XmlTokenizer.#flushText}.
*/
// deno-lint-ignore no-control-regex
const ILLEGAL_XML_CHAR_REGEXP = /[\x00-\x08\x0B\x0C\x0E-\x1F]/;
/** Sentinel position used when position tracking is disabled. */
const NO_POSITION: XmlPosition = { line: 0, column: 0, offset: 0 };
/**
* Stateful XML Tokenizer.
*
* Processes XML input chunk by chunk, emitting tokens. Handles cross-chunk
* boundaries correctly for all XML constructs.
*/
export class XmlTokenizer {
#buffer = "";
#bufferIndex = 0;
#state: StateType = State.INITIAL;
#line = 1;
#column = 1;
#offset = 0;
#tokenLine = 1;
#tokenColumn = 1;
#tokenOffset = 0;
/** Whether to track line/column positions. */
readonly #trackPosition: boolean;
/** Whether to reject DOCTYPE declarations. */
readonly #disallowDoctype: boolean;
// Slice-based accumulators: track start index + partial for cross-chunk
#textStartIdx = -1;
#textPartial = "";
#cdataStartIdx = -1;
#cdataPartial = "";
#attrStartIdx = -1;
#attrPartial = "";
// Track if whitespace is required before next attribute (after reading a value)
#needsAttrWhitespace = false;
// Index-based accumulators for tag names, comments, PI, attr names
#tagNameStartIdx = -1;
#tagNamePartial = "";
#commentStartIdx = -1;
#commentPartial = "";
#piTargetStartIdx = -1;
#piTargetPartial = "";
#piContentStartIdx = -1;
#piContentPartial = "";
#attrNameStartIdx = -1;
#attrNamePartial = "";
// Short strings still use direct accumulation
#cdataCheck = "";
// DOCTYPE accumulators
#doctypeCheck = "";
#doctypeName = "";
#doctypePublicId = "";
#doctypeSystemId = "";
#doctypeQuoteChar = "";
// Track if first character was a BOM (for XML declaration position check)
#firstCharWasBOM = false;
#checkedFirstChar = false;
// Track if XML declaration is still allowed (no content has been emitted yet)
// This is tracked independently of position tracking for wellformedness checking
#xmlDeclAllowed = true;
#doctypeBracketDepth = 0;
// DTD declaration parsing state
#dtdDeclKeyword = "";
#dtdDeclParenDepth = 0;
#dtdDeclSawWhitespace = false;
#dtdDeclQuoteChar = "";
// ENTITY declaration parsing state
#isEntityDecl = false;
#isParameterEntity = false;
#entityName = "";
#entityParsePhase: "name" | "value" | "done" = "name";
#entityExternalType: "" | "SYSTEM" | "PUBLIC" = ""; // Track SYSTEM/PUBLIC keyword
#entityQuotedLiterals = 0; // Count quoted literals for PUBLIC validation
#entityCurrentKeyword = ""; // Accumulate current keyword (SYSTEM/PUBLIC/NDATA)
// DTD string literal tracking for PubidLiteral validation
#dtdStringValue = ""; // Accumulated value of current DTD string literal
#dtdStringIsPubid = false; // Whether current string is a PubidLiteral
// For tracking text start position
#textStartLine = 1;
#textStartColumn = 1;
#textStartOffset = 0;
/** Current callbacks for emission (set during process/finalize calls). */
#callbacks: XmlTokenCallbacks = {};
/** Constructs a new XmlTokenizer. */
constructor(options: XmlTokenizerOptions = {}) {
this.#trackPosition = options.trackPosition ?? true;
this.#disallowDoctype = options.disallowDoctype ?? false;
}
#saveTokenPosition(): void {
if (!this.#trackPosition) return;
this.#tokenLine = this.#line;
this.#tokenColumn = this.#column;
this.#tokenOffset = this.#offset;
}
#error(message: string): never {
throw new XmlSyntaxError(
message,
this.#trackPosition
? { line: this.#line, column: this.#column, offset: this.#offset }
: NO_POSITION,
);
}
// XML 1.0 Fifth Edition name character validation with inlined ASCII fast path
#isNameStartCharCode(code: number): boolean {
// Inline ASCII check for hot path (99%+ of real XML)
if (code < 0x80) {
return (code >= 0x61 && code <= 0x7A) || // a-z
(code >= 0x41 && code <= 0x5A) || // A-Z
code === 0x5F || code === 0x3A; // _ :
}
return isNameStartChar(code);
}
#isNameCharCode(code: number): boolean {
// Inline ASCII check for hot path (99%+ of real XML)
if (code < 0x80) {
return (code >= 0x61 && code <= 0x7A) || // a-z
(code >= 0x41 && code <= 0x5A) || // A-Z
(code >= 0x30 && code <= 0x39) || // 0-9
code === 0x5F || code === 0x3A || // _ :
code === 0x2D || code === 0x2E; // - .
}
return isNameChar(code);
}
/**
* Get the full Unicode code point at the current buffer position.
* Handles surrogate pairs for astral plane characters (U+10000+).
* Returns [codePoint, charCount] where charCount is 1 or 2.
*/
#getCodePoint(
buffer: string,
index: number,
): [codePoint: number, charCount: number] {
const code = buffer.charCodeAt(index);
// Check for high surrogate (0xD800-0xDBFF)
if (code >= 0xD800 && code <= 0xDBFF && index + 1 < buffer.length) {
const low = buffer.charCodeAt(index + 1);
// Check for valid low surrogate (0xDC00-0xDFFF)
if (low >= 0xDC00 && low <= 0xDFFF) {
// Decode surrogate pair: ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000
const codePoint = ((code - 0xD800) << 10) + (low - 0xDC00) + 0x10000;
return [codePoint, 2];
}
}
return [code, 1];
}
/**
* Check if the current buffer position has a valid NameStartChar.
* Properly handles astral plane characters via surrogate pair decoding.
* Returns [isValid, charCount] where charCount is 1 or 2.
*/
#isNameStartCharAt(
buffer: string,
index: number,
): [isValid: boolean, charCount: number] {
const [codePoint, charCount] = this.#getCodePoint(buffer, index);
return [this.#isNameStartCharCode(codePoint), charCount];
}
/**
* Check if the current buffer position has a valid NameChar.
* Properly handles astral plane characters via surrogate pair decoding.
* Returns [isValid, charCount] where charCount is 1 or 2.
*/
#isNameCharAt(
buffer: string,
index: number,
): [isValid: boolean, charCount: number] {
const [codePoint, charCount] = this.#getCodePoint(buffer, index);
return [this.#isNameCharCode(codePoint), charCount];
}
#isWhitespaceCode(code: number): boolean {
return code === CC_SPACE || code === CC_TAB || code === CC_LF ||
code === CC_CR;
}
#flushText(): void {
if (this.#textStartIdx !== -1) {
const content = this.#textPartial +
this.#buffer.slice(this.#textStartIdx, this.#bufferIndex);
this.#textStartIdx = -1;
this.#textPartial = "";
if (content.length > 0) {
// XML 1.0 §2.2: Reject illegal C0 control characters.
// The position-tracking path already validates inline in
// #captureText, so this native regex pre-check only runs for the
// no-position-tracking path (avoids redundant scan of every text
// node when positions are tracked).
if (!this.#trackPosition && ILLEGAL_XML_CHAR_REGEXP.test(content)) {
for (let i = 0; i < content.length; i++) {
const code = content.charCodeAt(i);
if (
code < 0x20 && code !== CC_TAB && code !== CC_LF && code !== CC_CR
) {
this.#error(
`Illegal XML character U+${
code.toString(16).toUpperCase().padStart(4, "0")
} (XML 1.0 §2.2)`,
);
}
}
}
// XML 1.0 §2.4: "]]>" is not allowed in text content.
// Catches both within-chunk and cross-chunk occurrences since
// #textPartial accumulates across chunks.
if (content.includes("]]>")) {
this.#error(
"Cannot use ']]>' in text content (XML 1.0 §2.4)",
);
}
// Any content before XML declaration invalidates XMLDecl position
this.#xmlDeclAllowed = false;
this.#callbacks.onText?.(
content,
this.#textStartLine,
this.#textStartColumn,
this.#textStartOffset,
);
}
}
}
#getAttrValue(): string {
const value = this.#attrPartial +
this.#buffer.slice(this.#attrStartIdx, this.#bufferIndex);
this.#attrStartIdx = -1;
this.#attrPartial = "";
return value;
}
#getTagName(): string {
const name = this.#tagNamePartial +
this.#buffer.slice(this.#tagNameStartIdx, this.#bufferIndex);
this.#tagNameStartIdx = -1;
this.#tagNamePartial = "";
return name;
}
#getAttrName(): string {
const name = this.#attrNamePartial +
this.#buffer.slice(this.#attrNameStartIdx, this.#bufferIndex);
this.#attrNameStartIdx = -1;
this.#attrNamePartial = "";
return name;
}
#getPiTarget(): string {
const target = this.#piTargetPartial +
this.#buffer.slice(this.#piTargetStartIdx, this.#bufferIndex);
this.#piTargetStartIdx = -1;
this.#piTargetPartial = "";
return target;
}
#savePartialsBeforeReset(): void {
// Early return if no accumulators are active (common case)
if (
this.#textStartIdx === -1 &&
this.#cdataStartIdx === -1 &&
this.#attrStartIdx === -1 &&
this.#tagNameStartIdx === -1 &&
this.#commentStartIdx === -1 &&
this.#piTargetStartIdx === -1 &&
this.#piContentStartIdx === -1 &&
this.#attrNameStartIdx === -1
) {
return;
}
// Cache private fields accessed multiple times
const buffer = this.#buffer;
const end = this.#bufferIndex;
// --- Accumulators that need their data saved ---
// Text, tag name, attribute name, and PI target accumulators track
// [startIdx, bufferIndex) ranges that haven't been copied to their
// partial strings yet. Save that data before the buffer changes.
if (this.#textStartIdx !== -1) {
this.#textPartial += buffer.slice(this.#textStartIdx, end);
this.#textStartIdx = 0;
}
if (this.#tagNameStartIdx !== -1) {
this.#tagNamePartial += buffer.slice(this.#tagNameStartIdx, end);
this.#tagNameStartIdx = 0;
}
if (this.#attrNameStartIdx !== -1) {
this.#attrNamePartial += buffer.slice(this.#attrNameStartIdx, end);
this.#attrNameStartIdx = 0;
}
if (this.#piTargetStartIdx !== -1) {
this.#piTargetPartial += buffer.slice(this.#piTargetStartIdx, end);
this.#piTargetStartIdx = 0;
}
// --- Accumulators that only need index reset ---
// Comment, CDATA, PI content, and attribute value accumulators save
// their data eagerly during batch scanning (#captureComment, etc.).
// At chunk boundaries their startIdx always equals bufferIndex (the
// main loop fully consumes the buffer), so the range is empty and
// there is nothing to copy — just reset the indices for the next chunk.
if (this.#cdataStartIdx !== -1) this.#cdataStartIdx = 0;
if (this.#commentStartIdx !== -1) this.#commentStartIdx = 0;
if (this.#piContentStartIdx !== -1) this.#piContentStartIdx = 0;
if (this.#attrStartIdx !== -1) this.#attrStartIdx = 0;
}
#advanceWithCode(code: number): void {
if (this.#trackPosition) {
if (code === CC_LF) {
this.#line++;
this.#column = 1;
} else {
this.#column++;
}
this.#offset++;
}
this.#bufferIndex++;
}
/**
* Update position tracking for a region of text using indexOf for newlines.
* This is more efficient than char-by-char for regions with sparse newlines.
*/
#updatePositionForRegion(buffer: string, start: number, end: number): void {
if (!this.#trackPosition) return;
let pos = start;
while (pos < end) {
const nlIdx = buffer.indexOf("\n", pos);
if (nlIdx === -1 || nlIdx >= end) {
// No more newlines in region
this.#column += end - pos;
break;
}
// Found a newline
this.#line++;
this.#column = 1;
pos = nlIdx + 1;
}
this.#offset += end - start;
}
#normalizeLineEndings(chunk: string): string {
return chunk.includes("\r")
? chunk.replace(LINE_ENDING_REGEXP, "\n")
: chunk;
}
/**
* Process accumulated keyword in ENTITY declaration.
* Validates SYSTEM/PUBLIC/NDATA keywords and updates state.
*/
#processEntityKeyword(): void {
const kw = this.#entityCurrentKeyword;
this.#entityCurrentKeyword = "";
if (!kw) return;
// Fast path: check exact matches first (most common case)
if (kw === "SYSTEM") {
if (this.#entityExternalType) {
this.#error("Duplicate external ID keyword in ENTITY declaration");
}
this.#entityExternalType = "SYSTEM";
return;
}
if (kw === "PUBLIC") {
if (this.#entityExternalType) {
this.#error("Duplicate external ID keyword in ENTITY declaration");
}
this.#entityExternalType = "PUBLIC";
return;
}
if (kw === "NDATA") {
// NDATA validation
if (this.#isParameterEntity) {
this.#error("Parameter entities cannot have NDATA declarations");
}
if (!this.#entityExternalType) {
this.#error(
"NDATA can only follow SYSTEM or PUBLIC in ENTITY declaration",
);
}
// Whitespace is required before NDATA - already handled by sawWhitespace check
return;
}
// Check for case-sensitive keywords only when exact match failed (rare case)
const kwUpper = kw.toUpperCase();
if (kwUpper === "SYSTEM") {
this.#error(`'${kw}' must be uppercase 'SYSTEM'`);
} else if (kwUpper === "PUBLIC") {
this.#error(`'${kw}' must be uppercase 'PUBLIC'`);
} else if (kwUpper === "NDATA") {
this.#error(`'${kw}' must be uppercase 'NDATA'`);
}
// Other keywords (like notation names after NDATA) are just ignored
}
#emitDeclaration(target: string, content: string): void {
// XML 1.0 §2.6: Only exact lowercase "xml" is valid for XML declaration
// Case variants like "XML", "xMl" are reserved and invalid
if (target !== "xml") {
this.#error(
`Processing instruction target '${target}' is reserved; 'xml' must be lowercase (XML 1.0 §2.6)`,
);
}
// XML 1.0 §2.8: XML declaration must be at the very beginning
// (only a UTF BOM may precede it)
// Check both: no content has been emitted, AND if position tracking is on,
// verify the offset is correct (handles BOM case)
if (!this.#xmlDeclAllowed) {
this.#error(
"XML declaration must appear at the start of the document (XML 1.0 §2.8)",
);
}
// If position tracking is enabled, also verify exact offset
if (this.#trackPosition) {
const allowedOffset = this.#firstCharWasBOM ? 1 : 0;
if (this.#tokenOffset !== allowedOffset) {
this.#error(
"XML declaration must appear at the start of the document (XML 1.0 §2.8)",
);
}
}
// After emitting declaration, no more XMLDecl is allowed
this.#xmlDeclAllowed = false;
// Validate XML declaration syntax strictly
const result = validateXmlDeclaration(content);
if (!result.valid) {
this.#error(result.error);
}
this.#callbacks.onDeclaration?.(
result.version,
result.encoding,
result.standalone,
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
}
/** Read a quoted string in DOCTYPE. Does not handle cross-chunk boundaries. */
#readDoctypeQuotedString(): string {
const quote = this.#doctypeQuoteChar;
const buffer = this.#buffer;
const bufferLen = buffer.length;
let value = "";
while (
this.#bufferIndex < bufferLen && buffer[this.#bufferIndex] !== quote
) {
value += buffer[this.#bufferIndex];
this.#advanceWithCode(buffer.charCodeAt(this.#bufferIndex));
}
if (this.#bufferIndex >= bufferLen) {
this.#error("Unterminated quoted string in DOCTYPE declaration");
}
this.#advanceWithCode(buffer.charCodeAt(this.#bufferIndex));
return value;
}
/**
* Validates a PubidLiteral per XML 1.0 §2.3.
* PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]
*
* Note: If quoted with ', the value cannot contain '.
*
* @param quote The quote character used (' or ").
*/
#validatePubidLiteral(value: string, quote: string): void {
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
const ch = value[i];
// Valid PubidChar:
// #x20 (space), #xD (CR), #xA (LF)
// [a-zA-Z0-9]
// [-'()+,./:=?;!*#@$_%]
const isValid = code === 0x20 || // space
code === 0x0D || // CR
code === 0x0A || // LF
(code >= 0x41 && code <= 0x5A) || // A-Z
(code >= 0x61 && code <= 0x7A) || // a-z
(code >= 0x30 && code <= 0x39) || // 0-9
ch === "-" || ch === "(" || ch === ")" || ch === "+" ||
ch === "," || ch === "." || ch === "/" || ch === ":" ||
ch === "=" || ch === "?" || ch === ";" || ch === "!" ||
ch === "*" || ch === "#" || ch === "@" || ch === "$" ||
ch === "_" || ch === "%" ||
(ch === "'" && quote === '"'); // ' only allowed if quoted with "
if (!isValid) {
this.#error(
`Invalid character '${ch}' (U+${
code.toString(16).toUpperCase().padStart(4, "0")
}) in public ID literal`,
);
}
}
}
// ========================================================================
// DEDICATED CAPTURE METHODS
// These tight loops avoid per-character switch overhead for hot paths.
// ========================================================================
/**
* Capture text content in a tight loop until '<' is found.
* Returns true if '<' was found, false if end of buffer reached.
*
* The "]]>" check (XML 1.0 §2.4) is deferred to {@link #flushText} where
* a single native `includes` covers both within-chunk and cross-chunk cases.
*
* Illegal C0 control characters (XML 1.0 §2.2) are checked inline in the
* position-tracking path (already iterating per char) and via a fast native
* regex pre-check in {@link #flushText} for the no-position-tracking path.
*/
#captureText(buffer: string, bufferLen: number): boolean {
// Initialize text tracking if this is the start of a new text node
if (this.#textStartIdx === -1) {
if (this.#trackPosition) {
this.#textStartLine = this.#line;
this.#textStartColumn = this.#column;
this.#textStartOffset = this.#offset;
}
this.#textStartIdx = this.#bufferIndex;
}
if (this.#trackPosition) {
// Scan for '<' while tracking line/column positions.
// Illegal C0 chars are checked here (we're already per-char).
let idx = this.#bufferIndex;
let line = this.#line;
let column = this.#column;
let offset = this.#offset;
while (idx < bufferLen) {
const code = buffer.charCodeAt(idx);
if (code === CC_LT) {
this.#bufferIndex = idx;
this.#line = line;
this.#column = column;
this.#offset = offset;
return true;
}
// XML 1.0 §2.2: Reject illegal C0 control characters.
// Valid: TAB (0x09), LF (0x0A), CR (0x0D).
if (
code < 0x20 && code !== CC_TAB && code !== CC_LF && code !== CC_CR
) {
this.#bufferIndex = idx;
this.#line = line;
this.#column = column;
this.#offset = offset;
this.#error(
`Illegal XML character U+${
code.toString(16).toUpperCase().padStart(4, "0")
} (XML 1.0 §2.2)`,
);
}
if (code === CC_LF) {
line++;
column = 1;
} else {
column++;
}
offset++;
idx++;
}
this.#bufferIndex = idx;
this.#line = line;
this.#column = column;
this.#offset = offset;
} else {
// Fast path: native indexOf is SIMD-optimized in V8.
// Illegal C0 chars are checked in #flushText via regex.
const ltIdx = buffer.indexOf("<", this.#bufferIndex);
if (ltIdx >= 0) {
this.#bufferIndex = ltIdx;
return true;
}
this.#bufferIndex = bufferLen;
}
return false;
}
/**
* Capture an XML name (element or attribute name) in a tight loop.
*
* Assumes the first character has already been validated as NameStartChar.
* Continues until a non-NameChar is encountered.
*
* Uses a pre-computed {@link ASCII_NAME_CHAR} lookup table (1 array access)
* instead of calling {@link #isNameCharCode} per char (10 comparisons).
* Local `idx` avoids private-field access in the loop. Position is updated
* in a single batch after the loop (names cannot contain newlines).
*/
#captureNameChars(buffer: string, bufferLen: number): void {
let idx = this.#bufferIndex;
// Tight ASCII loop: 1 charCodeAt + 1 comparison + 1 array access per char.
// No function calls, no private-field access.
while (idx < bufferLen) {
const code = buffer.charCodeAt(idx);
if (code >= 0x80) break;
if (!ASCII_NAME_CHAR[code]) break;
idx++;
}
// Non-ASCII tail (rare): surrogate-aware checking
if (idx < bufferLen && buffer.charCodeAt(idx) >= 0x80) {
while (idx < bufferLen) {
const code = buffer.charCodeAt(idx);
if (code < 0x80) {
if (!ASCII_NAME_CHAR[code]) break;
idx++;
} else {
const [isValid, charCount] = this.#isNameCharAt(buffer, idx);
if (!isValid) break;
idx += charCount;
}
}
}
// Batch position update: names never contain newlines, so column += length.
if (this.#trackPosition) {
const advance = idx - this.#bufferIndex;
this.#column += advance;
this.#offset += advance;
}
this.#bufferIndex = idx;
}
/**
* Batch-scan comment using indexOf("-->"). Returns true if complete and emitted.
* When incomplete, consumes safe content (excluding trailing -) for char-by-char.
*
* Validates XML 1.0 constraints:
* - §2.5: "--" is not permitted within comments, and "--" must be followed by ">"
* - §2.2: Illegal C0 control characters are rejected
*/
#captureComment(buffer: string, bufferLen: number): boolean {
const endIdx = buffer.indexOf("-->", this.#bufferIndex);
if (endIdx !== -1) {
// Fast path: found complete "-->" terminator
const newContent = buffer.slice(this.#commentStartIdx, endIdx);
// XML 1.0 §2.5: "--" is not permitted within comments
// Check both the accumulated partial and new content for "--"
if (this.#commentPartial.includes("--") || newContent.includes("--")) {
this.#error(
`Cannot use '--' within comments (XML 1.0 §2.5)`,
);
}
// Also check the boundary between partial and new content
if (
this.#commentPartial.endsWith("-") && newContent.startsWith("-")
) {
this.#error(
`Cannot use '--' within comments (XML 1.0 §2.5)`,
);
}
// Check for trailing dash immediately before "-->"
// (grammar requires every "-" to be followed by a non-dash char)
if (
newContent.length > 0 &&
newContent.charCodeAt(newContent.length - 1) === CC_DASH
) {
this.#bufferIndex = endIdx - 1;
this.#error(
`Cannot use '-' immediately before '-->' (XML 1.0 §2.5)`,
);
}
// Also check if partial ends with dash and new content is empty
if (
newContent.length === 0 &&
this.#commentPartial.length > 0 &&
this.#commentPartial.charCodeAt(
this.#commentPartial.length - 1,
) === CC_DASH
) {
this.#bufferIndex = endIdx - 1;
this.#error(
`Cannot use '-' immediately before '-->' (XML 1.0 §2.5)`,
);
}
// XML 1.0 §2.2: Validate characters are legal XML Char
for (let i = this.#commentStartIdx; i < endIdx; i++) {
const code = buffer.charCodeAt(i);
if (code < 0x20 && C0_VALID[code] !== 1) {
this.#bufferIndex = i;
this.#error(
`Illegal XML character U+${
code.toString(16).toUpperCase().padStart(4, "0")
} (XML 1.0 §2.2)`,
);
}
}
const content = this.#commentPartial + newContent;
// Update position for the content region + terminator
this.#updatePositionForRegion(buffer, this.#bufferIndex, endIdx + 3);
this.#bufferIndex = endIdx + 3;
// Any comment before XML declaration invalidates XMLDecl position
this.#xmlDeclAllowed = false;
this.#callbacks.onComment?.(
content,
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#commentStartIdx = -1;
this.#commentPartial = "";
this.#state = State.INITIAL;
return true; // Complete
}
// No "-->" found - consume as much as safely possible
// We must NOT consume trailing `-` or `--` as they might be part of the terminator
let safeEnd = bufferLen;
if (
safeEnd > this.#bufferIndex &&
buffer.charCodeAt(safeEnd - 1) === CC_DASH
) {
safeEnd--;
if (
safeEnd > this.#bufferIndex &&
buffer.charCodeAt(safeEnd - 1) === CC_DASH
) {
safeEnd--;
}
}
// Batch consume the safe region
if (safeEnd > this.#bufferIndex) {
const region = buffer.slice(this.#commentStartIdx, safeEnd);
// XML 1.0 §2.5: "--" is not permitted within comments
if (region.includes("--")) {
this.#error(
`Cannot use '--' within comments (XML 1.0 §2.5)`,
);
}
// XML 1.0 §2.2: Validate characters are legal XML Char
for (let i = this.#commentStartIdx; i < safeEnd; i++) {
const code = buffer.charCodeAt(i);
if (code < 0x20 && C0_VALID[code] !== 1) {
this.#bufferIndex = i;
this.#error(
`Illegal XML character U+${
code.toString(16).toUpperCase().padStart(4, "0")
} (XML 1.0 §2.2)`,
);
}
}
this.#commentPartial += region;
this.#updatePositionForRegion(buffer, this.#bufferIndex, safeEnd);
this.#bufferIndex = safeEnd;
this.#commentStartIdx = safeEnd;
}
return false; // Let char-by-char handle remaining characters
}
/**
* Batch-scan PI using indexOf("?>"). Returns true if complete and emitted.
* When incomplete, consumes safe content (excluding trailing ?) for char-by-char.
*/
#capturePI(buffer: string, bufferLen: number): boolean {
const endIdx = buffer.indexOf("?>", this.#bufferIndex);
if (endIdx !== -1) {
// Fast path: found complete "?>" terminator
// XML 1.0 §2.2: Validate characters in PI content are legal XML Char
for (let i = this.#piContentStartIdx; i < endIdx; i++) {
const charCode = buffer.charCodeAt(i);
if (charCode < 0x20 && C0_VALID[charCode] !== 1) {
this.#bufferIndex = i;
this.#error(
`Illegal XML character U+${
charCode.toString(16).toUpperCase().padStart(4, "0")
} in processing instruction (XML 1.0 §2.2)`,
);
}
}
const content = this.#piContentPartial +
buffer.slice(this.#piContentStartIdx, endIdx);
// Update position for the content region + terminator
this.#updatePositionForRegion(buffer, this.#bufferIndex, endIdx + 2);
this.#bufferIndex = endIdx + 2;
// Emit the appropriate token type
if (isReservedPiTarget(this.#piTargetPartial)) {
this.#emitDeclaration(this.#piTargetPartial, content);
} else {
// Any PI before XML declaration invalidates XMLDecl position
this.#xmlDeclAllowed = false;
this.#callbacks.onProcessingInstruction?.(
this.#piTargetPartial,
content.trim(),
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
}
this.#piTargetPartial = "";
this.#piContentStartIdx = -1;
this.#piContentPartial = "";
this.#state = State.INITIAL;
return true; // Complete
}
// No "?>" found - consume as much as safely possible
// We must NOT consume trailing `?` as it might be part of the terminator
let safeEnd = bufferLen;
if (
safeEnd > this.#bufferIndex &&
buffer.charCodeAt(safeEnd - 1) === CC_QUESTION
) {
safeEnd--;
}
// Batch consume the safe region, validating characters
if (safeEnd > this.#bufferIndex) {
// XML 1.0 §2.2: Validate characters in PI content
for (let i = this.#piContentStartIdx; i < safeEnd; i++) {
const charCode = buffer.charCodeAt(i);
if (charCode < 0x20 && C0_VALID[charCode] !== 1) {
this.#bufferIndex = i;
this.#error(
`Illegal XML character U+${
charCode.toString(16).toUpperCase().padStart(4, "0")
} in processing instruction (XML 1.0 §2.2)`,
);
}
}
this.#piContentPartial += buffer.slice(this.#piContentStartIdx, safeEnd);
this.#updatePositionForRegion(buffer, this.#bufferIndex, safeEnd);
this.#bufferIndex = safeEnd;
this.#piContentStartIdx = safeEnd;
}
return false; // Let char-by-char handle remaining characters
}
/**
* Batch-scan CDATA using indexOf("]]>"). Returns true if complete and emitted.
* When incomplete, consumes safe content (excluding trailing ] or ]]) for char-by-char.
*
* Validates XML 1.0 §2.2: Illegal C0 control characters are rejected.
*/
#captureCDATA(buffer: string, bufferLen: number): boolean {
const endIdx = buffer.indexOf("]]>", this.#bufferIndex);
if (endIdx !== -1) {
// Fast path: found complete "]]>" terminator
// XML 1.0 §2.2: Validate characters are legal XML Char
for (let i = this.#cdataStartIdx; i < endIdx; i++) {
const code = buffer.charCodeAt(i);
if (code < 0x20 && C0_VALID[code] !== 1) {
this.#bufferIndex = i;
this.#error(
`Illegal XML character U+${
code.toString(16).toUpperCase().padStart(4, "0")
} (XML 1.0 §2.2)`,
);
}
}
const content = this.#cdataPartial +
buffer.slice(this.#cdataStartIdx, endIdx);
// Update position for the content region + terminator
this.#updatePositionForRegion(buffer, this.#bufferIndex, endIdx + 3);
this.#bufferIndex = endIdx + 3;
this.#callbacks.onCData?.(
content,
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#cdataStartIdx = -1;
this.#cdataPartial = "";
this.#state = State.INITIAL;
return true; // Complete
}
// No "]]>" found - consume as much as safely possible
// We must NOT consume trailing `]` or `]]` as they might be part of the terminator
let safeEnd = bufferLen;
if (
safeEnd > this.#bufferIndex &&
buffer.charCodeAt(safeEnd - 1) === CC_RBRACKET
) {
safeEnd--;
if (
safeEnd > this.#bufferIndex &&
buffer.charCodeAt(safeEnd - 1) === CC_RBRACKET
) {
safeEnd--;
}
}
// Batch consume the safe region
if (safeEnd > this.#bufferIndex) {
// XML 1.0 §2.2: Validate characters are legal XML Char
for (let i = this.#cdataStartIdx; i < safeEnd; i++) {
const code = buffer.charCodeAt(i);
if (code < 0x20 && C0_VALID[code] !== 1) {
this.#bufferIndex = i;
this.#error(
`Illegal XML character U+${
code.toString(16).toUpperCase().padStart(4, "0")
} (XML 1.0 §2.2)`,
);
}
}
this.#cdataPartial += buffer.slice(this.#cdataStartIdx, safeEnd);
this.#updatePositionForRegion(buffer, this.#bufferIndex, safeEnd);
this.#bufferIndex = safeEnd;
this.#cdataStartIdx = safeEnd;
}
return false; // Let char-by-char handle remaining characters
}
/**
* Batch-scan attribute value using indexOf for the closing quote.
* Returns true if complete and ready for emission.
* Validates that '<' is not in the value.
*
* @param quoteCode The quote character code (CC_DQUOTE or CC_SQUOTE)
*/
#captureAttributeValue(
buffer: string,
bufferLen: number,
quoteCode: number,
): boolean {
const quoteChar = String.fromCharCode(quoteCode);
const idx = this.#bufferIndex;
const endIdx = buffer.indexOf(quoteChar, idx);
if (endIdx !== -1) {
// Found closing quote - validate and complete
// Check for '<' which is not allowed in attribute values (native indexOf)
const ltIdx = buffer.indexOf("<", this.#attrStartIdx);
if (ltIdx !== -1 && ltIdx < endIdx) {
this.#bufferIndex = ltIdx;
this.#error(`Cannot use '<' in attribute value`);
}
// Update position for the content region (not including closing quote)
this.#updatePositionForRegion(buffer, idx, endIdx);
this.#bufferIndex = endIdx;
return true; // Complete - ready to emit
}
// No closing quote found - consume as much as safely possible
// Check for '<' which is not allowed in attribute values (native indexOf)
const ltCheck = buffer.indexOf("<", this.#attrStartIdx);
if (ltCheck !== -1 && ltCheck < bufferLen) {
this.#bufferIndex = ltCheck;
this.#error(`Cannot use '<' in attribute value`);
}
// Batch consume the entire remaining buffer
if (bufferLen > idx) {
this.#attrPartial += buffer.slice(this.#attrStartIdx, bufferLen);
this.#updatePositionForRegion(buffer, idx, bufferLen);
this.#bufferIndex = bufferLen;
this.#attrStartIdx = bufferLen;
}
return false; // Incomplete - need more data
}
/**
* Process a chunk of XML text using callbacks.
*
* This method is synchronous and can be called multiple times with
* consecutive chunks of XML input. Callbacks are invoked for each
* token, enabling zero-allocation streaming.
*/
process(chunk: string, callbacks: XmlTokenCallbacks): void {
this.#callbacks = callbacks;
this.#savePartialsBeforeReset();
const normalized = this.#normalizeLineEndings(chunk);
// The main loop always fully consumes the buffer (bufferIndex reaches
// buffer.length), so the new chunk is assigned directly — no leftover
// to slice or concatenate.
this.#buffer = normalized;
this.#bufferIndex = 0;
// Cache hot variables locally to reduce private field access overhead.
const buffer = normalized;
const bufferLen = buffer.length;
// Check for BOM at the very first character (for XML declaration position check)
if (!this.#checkedFirstChar && bufferLen > 0) {
this.#checkedFirstChar = true;
if (buffer.charCodeAt(0) === 0xFEFF) {
this.#firstCharWasBOM = true;
}
}
while (this.#bufferIndex < bufferLen) {
// Use charCodeAt for faster character comparison in hot path
const code = buffer.charCodeAt(this.#bufferIndex);
// Switch cases ordered by frequency for better branch prediction.
switch (this.#state) {
// === HOT PATH: Most frequently hit states ===
case State.INITIAL: {
// Use dedicated capture method for tight-loop text scanning
if (this.#captureText(buffer, bufferLen)) {
// Found '<' - flush text and transition to TAG_OPEN
this.#flushText();
this.#saveTokenPosition();
this.#advanceWithCode(CC_LT);
this.#state = State.TAG_OPEN;
}
// If captureText returns false, we've consumed all input
// and will exit the main loop naturally
break;
}
case State.TAG_NAME: {
// Use dedicated capture method for tight-loop name scanning
this.#captureNameChars(buffer, bufferLen);
// Check what character ended the name (if any)
if (this.#bufferIndex >= bufferLen) {
// End of buffer - need more data, stay in TAG_NAME state
break;
}
// Get the terminating character
const termCode = buffer.charCodeAt(this.#bufferIndex);
if (this.#isWhitespaceCode(termCode)) {
this.#callbacks.onStartTagOpen?.(
this.#getTagName(),
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#advanceWithCode(termCode);
this.#state = State.AFTER_TAG_NAME;
} else if (termCode === CC_GT) {
this.#callbacks.onStartTagOpen?.(
this.#getTagName(),
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#callbacks.onStartTagClose?.(false);
this.#advanceWithCode(termCode);
this.#state = State.INITIAL;
} else if (termCode === CC_SLASH) {
this.#callbacks.onStartTagOpen?.(
this.#getTagName(),
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#advanceWithCode(termCode);
this.#state = State.EXPECT_SELF_CLOSE_GT;
} else {
this.#error(
`Unexpected character '${
String.fromCharCode(termCode)
}' in tag name`,
);
}
break;
}
case State.END_TAG_NAME: {
// Handle first character (must be NameStartChar)
if (
this.#tagNameStartIdx === this.#bufferIndex &&
this.#tagNamePartial === ""
) {
// ASCII fast path: lookup table avoids function call + tuple allocation
if (code < 0x80) {
if (!ASCII_NAME_START_CHAR[code]) {
this.#error(
`Unexpected character '${
String.fromCharCode(code)
}' in end tag`,
);
}
this.#advanceWithCode(code);
} else {
// Non-ASCII: surrogate-aware check (rare)
const [isValid, charCount] = this.#isNameStartCharAt(
buffer,
this.#bufferIndex,
);
if (!isValid) {
this.#error(
`Unexpected character '${
String.fromCharCode(code)
}' in end tag`,
);
}
for (let i = 0; i < charCount; i++) {
this.#advanceWithCode(buffer.charCodeAt(this.#bufferIndex));
}
}
}
// Use dedicated capture method for tight-loop name scanning
this.#captureNameChars(buffer, bufferLen);
// Check what character ended the name (if any)
if (this.#bufferIndex >= bufferLen) {
// End of buffer - need more data
break;
}
const termCode = buffer.charCodeAt(this.#bufferIndex);
if (this.#isWhitespaceCode(termCode)) {
const name = this.#getTagName();
this.#tagNamePartial = name; // Store temporarily
this.#advanceWithCode(termCode);
this.#state = State.AFTER_END_TAG_NAME;
} else if (termCode === CC_GT) {
this.#callbacks.onEndTag?.(
this.#getTagName(),
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#advanceWithCode(termCode);
this.#state = State.INITIAL;
} else {
this.#error(
`Unexpected character '${
String.fromCharCode(termCode)
}' in end tag`,
);
}
break;
}
case State.ATTRIBUTE_VALUE_DOUBLE: {
// Try batch scanning first - handles most cases efficiently
if (this.#captureAttributeValue(buffer, bufferLen, CC_DQUOTE)) {
// Found closing quote at bufferIndex
this.#callbacks.onAttribute?.(
this.#attrNamePartial,
this.#getAttrValue(),
);
this.#attrNamePartial = "";
this.#advanceWithCode(CC_DQUOTE);
// Whitespace is now required before next attribute
this.#needsAttrWhitespace = true;
this.#state = State.AFTER_TAG_NAME;
}
// If incomplete, buffer was consumed and we exit the loop naturally
break;
}
case State.AFTER_TAG_NAME: {
if (this.#isWhitespaceCode(code)) {
// Whitespace seen - no longer require whitespace before next attr
this.#needsAttrWhitespace = false;
this.#advanceWithCode(code);
// Tight loop: skip remaining whitespace without switch dispatch
while (this.#bufferIndex < bufferLen) {
const wsCode = buffer.charCodeAt(this.#bufferIndex);
if (
wsCode !== CC_SPACE && wsCode !== CC_TAB &&
wsCode !== CC_LF && wsCode !== CC_CR
) break;
this.#advanceWithCode(wsCode);
}
} else if (code === CC_GT) {
this.#needsAttrWhitespace = false;
this.#callbacks.onStartTagClose?.(false);
this.#advanceWithCode(code);
this.#state = State.INITIAL;
} else if (code === CC_SLASH) {
this.#needsAttrWhitespace = false;
this.#advanceWithCode(code);
this.#state = State.EXPECT_SELF_CLOSE_GT;
} else if (
code < 0x80
? ASCII_NAME_START_CHAR[code]
: this.#isNameStartCharCode(code)
) {
// XML 1.0 §3.1: Whitespace is required between attributes
if (this.#needsAttrWhitespace) {
this.#error("Missing whitespace between attributes");
}
this.#attrNameStartIdx = this.#bufferIndex;
this.#attrNamePartial = "";
this.#advanceWithCode(code);
this.#state = State.ATTRIBUTE_NAME;
} else {
this.#error(
`Unexpected character '${
String.fromCharCode(code)
}' after tag name`,
);
}
break;
}
case State.ATTRIBUTE_NAME: {
// Use dedicated capture method for tight-loop name scanning
this.#captureNameChars(buffer, bufferLen);
// Check what character ended the name (if any)
if (this.#bufferIndex >= bufferLen) {
// End of buffer - need more data
break;
}
const termCode = buffer.charCodeAt(this.#bufferIndex);
if (this.#isWhitespaceCode(termCode)) {
// Save the attribute name before transitioning
const name = this.#getAttrName();
this.#attrNamePartial = name; // Store temporarily
this.#advanceWithCode(termCode);
this.#state = State.AFTER_ATTRIBUTE_NAME;
} else if (termCode === CC_EQ) {
const name = this.#getAttrName();
this.#attrNamePartial = name; // Store temporarily
this.#advanceWithCode(termCode);
this.#state = State.BEFORE_ATTRIBUTE_VALUE;
} else {
this.#error(
`Unexpected character '${
String.fromCharCode(termCode)
}' in attribute name`,
);
}
break;
}
case State.TAG_OPEN: {
if (code === CC_SLASH) {
this.#advanceWithCode(code);
this.#tagNameStartIdx = this.#bufferIndex;
this.#tagNamePartial = "";
this.#state = State.END_TAG_NAME;
} else if (code === CC_BANG) {
this.#advanceWithCode(code);
this.#state = State.MARKUP_DECLARATION;
} else if (code === CC_QUESTION) {
this.#advanceWithCode(code);
this.#piTargetStartIdx = this.#bufferIndex;
this.#piTargetPartial = "";
this.#state = State.PI_TARGET;
} else if (code < 0x80) {
// ASCII fast path: lookup table avoids function call + tuple allocation
if (!ASCII_NAME_START_CHAR[code]) {
this.#error(
`Unexpected character '${String.fromCharCode(code)}' after '<'`,
);
}
this.#tagNameStartIdx = this.#bufferIndex;
this.#tagNamePartial = "";
this.#advanceWithCode(code);
this.#state = State.TAG_NAME;
} else {
// Non-ASCII: surrogate-aware check (rare)
const [isValid, charCount] = this.#isNameStartCharAt(
buffer,
this.#bufferIndex,
);
if (isValid) {
this.#tagNameStartIdx = this.#bufferIndex;
this.#tagNamePartial = "";
for (let i = 0; i < charCount; i++) {
this.#advanceWithCode(buffer.charCodeAt(this.#bufferIndex));
}
this.#state = State.TAG_NAME;
} else {
this.#error(
`Unexpected character '${String.fromCharCode(code)}' after '<'`,
);
}
}
break;
}
// === WARM PATH: Moderately common states ===
case State.BEFORE_ATTRIBUTE_VALUE: {
if (this.#isWhitespaceCode(code)) {
this.#advanceWithCode(code);
} else if (code === CC_DQUOTE) {
this.#advanceWithCode(code);
this.#attrStartIdx = this.#bufferIndex;
this.#attrPartial = "";
this.#state = State.ATTRIBUTE_VALUE_DOUBLE;
} else if (code === CC_SQUOTE) {
this.#advanceWithCode(code);
this.#attrStartIdx = this.#bufferIndex;
this.#attrPartial = "";
this.#state = State.ATTRIBUTE_VALUE_SINGLE;
} else {
this.#error(`Expected quote to start attribute value`);
}
break;
}
case State.AFTER_ATTRIBUTE_NAME: {
if (this.#isWhitespaceCode(code)) {
this.#advanceWithCode(code);
} else if (code === CC_EQ) {
this.#advanceWithCode(code);
this.#state = State.BEFORE_ATTRIBUTE_VALUE;
} else {
this.#error(`Expected '=' after attribute name`);
}
break;
}
case State.EXPECT_SELF_CLOSE_GT: {
if (code === CC_GT) {
this.#callbacks.onStartTagClose?.(true);
this.#advanceWithCode(code);
this.#state = State.INITIAL;
} else {
this.#error(`Expected '>' after '/' in self-closing tag`);
}
break;
}
case State.AFTER_END_TAG_NAME: {
if (this.#isWhitespaceCode(code)) {
this.#advanceWithCode(code);
} else if (code === CC_GT) {
this.#callbacks.onEndTag?.(
this.#tagNamePartial,
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#tagNamePartial = "";
this.#advanceWithCode(code);
this.#state = State.INITIAL;
} else {
this.#error(
`Unexpected character '${String.fromCharCode(code)}' in end tag`,
);
}
break;
}
case State.ATTRIBUTE_VALUE_SINGLE: {
// Try batch scanning first - handles most cases efficiently
if (this.#captureAttributeValue(buffer, bufferLen, CC_SQUOTE)) {
// Found closing quote at bufferIndex
this.#callbacks.onAttribute?.(
this.#attrNamePartial,
this.#getAttrValue(),
);
this.#attrNamePartial = "";
this.#advanceWithCode(CC_SQUOTE);
// Whitespace is now required before next attribute
this.#needsAttrWhitespace = true;
this.#state = State.AFTER_TAG_NAME;
}
// If incomplete, buffer was consumed and we exit the loop naturally
break;
}
// === COLD PATH: Rarely hit states (comments, CDATA, PI, DOCTYPE) ===
case State.COMMENT: {
// Try batch scanning first - handles most cases efficiently
if (this.#captureComment(buffer, bufferLen)) {
break; // Complete comment found and emitted
}
// Batch consumed what it could; handle remaining chars (0-2 dashes)
if (this.#bufferIndex >= bufferLen) {
break; // Buffer exhausted, need more data
}
// Re-read code since bufferIndex may have changed
const commentCode = buffer.charCodeAt(this.#bufferIndex);
// After batch capture, only trailing `-` chars remain
this.#commentPartial += buffer.slice(
this.#commentStartIdx,
this.#bufferIndex,
);
this.#advanceWithCode(commentCode);
this.#commentStartIdx = this.#bufferIndex;
this.#state = State.COMMENT_DASH;
break;
}
case State.CDATA: {
// Try batch scanning first - handles ~95% of cases efficiently
if (this.#captureCDATA(buffer, bufferLen)) {
break; // Complete CDATA found and emitted
}
// Batch consumed what it could; handle remaining chars (0-2 brackets)
if (this.#bufferIndex >= bufferLen) {
break; // Buffer exhausted, need more data
}
// Re-read code since bufferIndex may have changed
const cdataCode = buffer.charCodeAt(this.#bufferIndex);
// After batch capture, only trailing `]` chars remain
this.#cdataPartial += buffer.slice(
this.#cdataStartIdx,
this.#bufferIndex,
);
this.#advanceWithCode(cdataCode);
this.#cdataStartIdx = this.#bufferIndex;
this.#state = State.CDATA_BRACKET;
break;
}
case State.PI_CONTENT: {
// Try batch scanning first - handles most cases efficiently
if (this.#capturePI(buffer, bufferLen)) {
break; // Complete PI found and emitted
}
// Batch consumed what it could; handle remaining chars (0-1 question mark)
if (this.#bufferIndex >= bufferLen) {
break; // Buffer exhausted, need more data
}
// After batch capture, only a trailing `?` remains
this.#piContentPartial += buffer.slice(
this.#piContentStartIdx,
this.#bufferIndex,
);
this.#piContentStartIdx = -1;
this.#advanceWithCode(buffer.charCodeAt(this.#bufferIndex));
this.#state = State.PI_QUESTION;
break;
}
case State.MARKUP_DECLARATION: {
if (code === CC_DASH) {
this.#advanceWithCode(code);
this.#state = State.COMMENT_START;
} else if (code === CC_LBRACKET) {
this.#advanceWithCode(code);
this.#cdataCheck = "";
this.#state = State.CDATA_START;
} else if (code === CC_D_UPPER) {
this.#doctypeCheck = "D";
this.#advanceWithCode(code);
this.#state = State.DOCTYPE_START;
} else {
this.#error(`Unsupported markup declaration`);
}
break;
}
case State.COMMENT_START: {
if (code === CC_DASH) {
this.#advanceWithCode(code);
this.#commentStartIdx = this.#bufferIndex;
this.#commentPartial = "";
this.#state = State.COMMENT;
} else {
this.#error(`Expected '-' to start comment`);
}
break;
}
case State.COMMENT_DASH: {
if (code === CC_DASH) {
this.#advanceWithCode(code);
// Mark that we've consumed the --, no more content to capture
this.#commentStartIdx = -1;
this.#state = State.COMMENT_DASH_DASH;
} else {
this.#commentPartial += "-";
this.#commentStartIdx = this.#bufferIndex;
this.#advanceWithCode(code);
this.#state = State.COMMENT;
}
break;
}
case State.COMMENT_DASH_DASH: {
if (code === CC_GT) {
// XML 1.0 §2.5: "--" is not permitted within comments
// Also, a single "-" cannot appear immediately before "-->"
// Check before emitting
if (this.#commentPartial.includes("--")) {
this.#error(
`Cannot use '--' within comments (XML 1.0 §2.5)`,
);
}
// Check for trailing dash (e.g., "<!--->" or "<!-- comment --->")
if (
this.#commentPartial.length > 0 &&
this.#commentPartial.charCodeAt(
this.#commentPartial.length - 1,
) === CC_DASH
) {
this.#error(
`Cannot use '-' immediately before '-->' (XML 1.0 §2.5)`,
);
}
// Any comment before XML declaration invalidates XMLDecl position
this.#xmlDeclAllowed = false;
this.#callbacks.onComment?.(
this.#commentPartial,
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#commentStartIdx = -1;
this.#commentPartial = "";
this.#advanceWithCode(code);
this.#state = State.INITIAL;
} else if (code === CC_DASH) {
// Add one - to content, stay in COMMENT_DASH_DASH
// This handles cases like "---->" (content="--" which will be caught)
this.#commentPartial += "-";
this.#advanceWithCode(code);
} else {
// XML 1.0 §2.5: After "--", only ">" or "-" is allowed.
// Any other character means "--" appears within the comment content.
this.#error(
`Cannot use '--' within comments (XML 1.0 §2.5)`,
);
}
break;
}
case State.CDATA_START: {
this.#cdataCheck += String.fromCharCode(code);
this.#advanceWithCode(code);
if (this.#cdataCheck === "CDATA[") {
this.#cdataStartIdx = this.#bufferIndex;
this.#cdataPartial = "";
this.#state = State.CDATA;
} else if (!"CDATA[".startsWith(this.#cdataCheck)) {
this.#error(`Expected 'CDATA[' after '<![`);
}
break;
}
case State.CDATA_BRACKET: {
if (code === CC_RBRACKET) {
this.#advanceWithCode(code);
this.#cdataStartIdx = this.#bufferIndex;
this.#state = State.CDATA_BRACKET_BRACKET;
} else {
this.#cdataPartial += "]";
this.#advanceWithCode(code);
this.#state = State.CDATA;
}
break;
}
case State.CDATA_BRACKET_BRACKET: {
if (code === CC_GT) {
this.#callbacks.onCData?.(
this.#cdataPartial,
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#cdataStartIdx = -1;
this.#cdataPartial = "";
this.#advanceWithCode(code);
this.#state = State.INITIAL;
} else if (code === CC_RBRACKET) {
this.#cdataPartial += "]";
this.#advanceWithCode(code);
this.#cdataStartIdx = this.#bufferIndex;
} else {
this.#cdataPartial += "]]";
this.#advanceWithCode(code);
this.#state = State.CDATA;
}
break;
}
case State.PI_TARGET: {
// Check if this is the first character of the PI target
const isFirstChar = this.#piTargetStartIdx === this.#bufferIndex &&
this.#piTargetPartial === "";
if (isFirstChar) {
// First character must be NameStartChar (XML 1.0 §2.6)
if (this.#isNameStartCharCode(code)) {
this.#advanceWithCode(code);
} else if (this.#isWhitespaceCode(code) || code === CC_QUESTION) {
// Empty PI target is not allowed
this.#error("Missing processing instruction target");
} else {
this.#error(
`Invalid character '${
String.fromCharCode(code)
}' at start of processing instruction target`,
);
}
} else if (this.#isNameCharCode(code)) {
// Subsequent characters use NameChar
this.#advanceWithCode(code);
} else if (this.#isWhitespaceCode(code)) {
// Save target and transition to content
const target = this.#getPiTarget();
this.#piTargetPartial = target; // Store temporarily
this.#advanceWithCode(code);
this.#piContentStartIdx = this.#bufferIndex;
this.#piContentPartial = "";
this.#state = State.PI_CONTENT;
} else if (code === CC_QUESTION) {
const target = this.#getPiTarget();
this.#piTargetPartial = target; // Store temporarily
this.#advanceWithCode(code);
this.#state = State.PI_TARGET_QUESTION;
} else {
this.#error(
`Unexpected character '${
String.fromCharCode(code)
}' in processing instruction target`,
);
}
break;
}
case State.PI_TARGET_QUESTION: {
if (code === CC_GT) {
if (isReservedPiTarget(this.#piTargetPartial)) {
this.#emitDeclaration(this.#piTargetPartial, "");
} else {
// Any PI before XML declaration invalidates XMLDecl position
this.#xmlDeclAllowed = false;
this.#callbacks.onProcessingInstruction?.(
this.#piTargetPartial,
"",
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
}
this.#piTargetPartial = "";
this.#advanceWithCode(code);
this.#state = State.INITIAL;
} else {
this.#error(
`Expected '>' after '?' in processing instruction, got '${
String.fromCharCode(code)
}'`,
);
}
break;
}
case State.PI_QUESTION: {
if (code === CC_GT) {
if (isReservedPiTarget(this.#piTargetPartial)) {
this.#emitDeclaration(
this.#piTargetPartial,
this.#piContentPartial,
);
} else {
// Any PI before XML declaration invalidates XMLDecl position
this.#xmlDeclAllowed = false;
this.#callbacks.onProcessingInstruction?.(
this.#piTargetPartial,
this.#piContentPartial.trim(),
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
}
this.#piTargetPartial = "";
this.#piContentPartial = "";
this.#advanceWithCode(code);
this.#state = State.INITIAL;
} else if (code === CC_QUESTION) {
this.#piContentPartial += "?";
this.#advanceWithCode(code);
} else {
this.#piContentPartial += "?";
// Restart capturing from current position
this.#piContentStartIdx = this.#bufferIndex;
this.#advanceWithCode(code);
this.#state = State.PI_CONTENT;
}
break;
}
// === COLDEST PATH: DOCTYPE states (very rare) ===
case State.DOCTYPE_START: {
this.#doctypeCheck += String.fromCharCode(code);
this.#advanceWithCode(code);
if (this.#doctypeCheck === "DOCTYPE") {
if (this.#disallowDoctype) {
this.#error("DOCTYPE declarations are not allowed");
}
this.#doctypeName = "";
this.#doctypePublicId = "";
this.#doctypeSystemId = "";
this.#state = State.DOCTYPE_NAME;
} else if (!"DOCTYPE".startsWith(this.#doctypeCheck)) {
this.#error(`Expected DOCTYPE, got <!${this.#doctypeCheck}`);
}
break;
}
case State.DOCTYPE_NAME: {
if (this.#isWhitespaceCode(code)) {
this.#advanceWithCode(code);
if (this.#doctypeName !== "") {
this.#state = State.DOCTYPE_AFTER_NAME;
}
} else if (code === CC_GT) {
this.#callbacks.onDoctype?.(
this.#doctypeName,
undefined,
undefined,
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#advanceWithCode(code);
this.#state = State.INITIAL;
} else if (code === CC_LBRACKET) {
this.#advanceWithCode(code);
this.#doctypeBracketDepth = 1;
this.#state = State.DOCTYPE_INTERNAL_SUBSET;
} else if (
this.#isNameCharCode(code) ||
(this.#doctypeName === "" && this.#isNameStartCharCode(code))
) {
this.#doctypeName += String.fromCharCode(code);
this.#advanceWithCode(code);
} else {
this.#error(
`Unexpected character '${
String.fromCharCode(code)
}' in DOCTYPE name`,
);
}
break;
}
case State.DOCTYPE_AFTER_NAME: {
if (this.#isWhitespaceCode(code)) {
this.#advanceWithCode(code);
} else if (code === CC_GT) {
this.#callbacks.onDoctype?.(
this.#doctypeName,
this.#doctypePublicId || undefined,
this.#doctypeSystemId || undefined,
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#advanceWithCode(code);
this.#state = State.INITIAL;
} else if (code === CC_LBRACKET) {
this.#advanceWithCode(code);
this.#doctypeBracketDepth = 1;
this.#state = State.DOCTYPE_INTERNAL_SUBSET;
} else if (code === CC_P_UPPER) {
this.#doctypeCheck = "P";
this.#advanceWithCode(code);
this.#state = State.DOCTYPE_PUBLIC;
} else if (code === CC_S_UPPER) {
this.#doctypeCheck = "S";
this.#advanceWithCode(code);
this.#state = State.DOCTYPE_SYSTEM;
} else if (code === 112) { // 'p' lowercase
// Check if this is 'public' (wrong case)
if (
this.#bufferIndex + 5 < this.#buffer.length &&
this.#buffer.slice(
this.#bufferIndex,
this.#bufferIndex + 6,
).toLowerCase() === "public"
) {
this.#error(
`'${
this.#buffer.slice(this.#bufferIndex, this.#bufferIndex + 6)
}' must be uppercase 'PUBLIC'`,
);
}
this.#error(
`Unexpected character '${String.fromCharCode(code)}' in DOCTYPE`,
);
} else if (code === 115) { // 's' lowercase
// Check if this is 'system' (wrong case)
if (
this.#bufferIndex + 5 < this.#buffer.length &&
this.#buffer.slice(
this.#bufferIndex,
this.#bufferIndex + 6,
).toLowerCase() === "system"
) {
this.#error(
`'${
this.#buffer.slice(this.#bufferIndex, this.#bufferIndex + 6)
}' must be uppercase 'SYSTEM'`,
);
}
this.#error(
`Unexpected character '${String.fromCharCode(code)}' in DOCTYPE`,
);
} else {
this.#error(
`Unexpected character '${String.fromCharCode(code)}' in DOCTYPE`,
);
}
break;
}
case State.DOCTYPE_PUBLIC: {
this.#doctypeCheck += String.fromCharCode(code);
this.#advanceWithCode(code);
if (this.#doctypeCheck === "PUBLIC") {
this.#state = State.DOCTYPE_PUBLIC_ID;
} else if (!"PUBLIC".startsWith(this.#doctypeCheck)) {
this.#error(`Expected PUBLIC, got ${this.#doctypeCheck}`);
}
break;
}
case State.DOCTYPE_PUBLIC_ID: {
if (this.#isWhitespaceCode(code)) {
this.#advanceWithCode(code);
} else if (code === CC_DQUOTE || code === CC_SQUOTE) {
this.#doctypeQuoteChar = String.fromCharCode(code);
this.#advanceWithCode(code);
this.#doctypePublicId = this.#readDoctypeQuotedString();
// Validate PubidLiteral characters
this.#validatePubidLiteral(
this.#doctypePublicId,
this.#doctypeQuoteChar,
);
this.#state = State.DOCTYPE_AFTER_PUBLIC_ID;
} else {
this.#error(`Expected quote to start public ID`);
}
break;
}
case State.DOCTYPE_AFTER_PUBLIC_ID: {
if (this.#isWhitespaceCode(code)) {
this.#advanceWithCode(code);
} else if (code === CC_DQUOTE || code === CC_SQUOTE) {
this.#doctypeQuoteChar = String.fromCharCode(code);
this.#advanceWithCode(code);
this.#doctypeSystemId = this.#readDoctypeQuotedString();
this.#state = State.DOCTYPE_AFTER_NAME;
} else if (code === CC_GT) {
this.#callbacks.onDoctype?.(
this.#doctypeName,
this.#doctypePublicId,
undefined,
this.#tokenLine,
this.#tokenColumn,
this.#tokenOffset,
);
this.#advanceWithCode(code);
this.#state = State.INITIAL;
} else {
this.#error(`Expected system ID or '>' after public ID`);
}
break;
}
case State.DOCTYPE_SYSTEM: {
this.#doctypeCheck += String.fromCharCode(code);
this.#advanceWithCode(code);
if (this.#doctypeCheck === "SYSTEM") {
this.#state = State.DOCTYPE_SYSTEM_ID;
} else if (!"SYSTEM".startsWith(this.#doctypeCheck)) {
this.#error(`Expected SYSTEM, got ${this.#doctypeCheck}`);
}
break;
}
case State.DOCTYPE_SYSTEM_ID: {
if (this.#isWhitespaceCode(code)) {
this.#advanceWithCode(code);
} else if (code === CC_DQUOTE || code === CC_SQUOTE) {
this.#doctypeQuoteChar = String.fromCharCode(code);
this.#advanceWithCode(code);
this.#doctypeSystemId = this.#readDoctypeQuotedString();
this.#state = State.DOCTYPE_AFTER_NAME;
} else {
this.#error(`Expected quote to start system ID`);
}
break;
}
case State.DOCTYPE_INTERNAL_SUBSET: {
if (code === CC_RBRACKET) {
this.#doctypeBracketDepth--;
this.#advanceWithCode(code);
if (this.#doctypeBracketDepth === 0) {
this.#state = State.DOCTYPE_AFTER_NAME;
}
} else if (code === CC_LT) {
this.#advanceWithCode(code);
this.#state = State.DTD_DECL_START;
} else if (this.#isWhitespaceCode(code)) {
this.#advanceWithCode(code);
} else if (code === CC_LBRACKET) {
// Conditional sections (INCLUDE/IGNORE) are only allowed in external subset
this.#error(
"Conditional sections (INCLUDE/IGNORE) are not allowed in internal DTD subset",
);
} else if (code === 37) { // % - parameter entity reference
this.#advanceWithCode(code);
this.#state = State.DTD_PE_REF;
} else {
this.#error(
`Unexpected character '${
String.fromCharCode(code)
}' in DOCTYPE internal subset`,
);
}
break;
}
case State.DOCTYPE_INTERNAL_SUBSET_STRING: {
if (String.fromCharCode(code) === this.#doctypeQuoteChar) {
this.#advanceWithCode(code);
this.#state = State.DOCTYPE_INTERNAL_SUBSET;
} else {
this.#advanceWithCode(code);
}
break;
}
case State.DTD_DECL_START: {
if (code === CC_BANG) {
this.#advanceWithCode(code);
this.#dtdDeclKeyword = "";
this.#state = State.DTD_DECL_KEYWORD;
} else if (code === CC_QUESTION) {
this.#advanceWithCode(code);
this.#state = State.DTD_PI;
} else {
this.#error(`Expected '!' or '?' after '<' in DTD`);
}
break;
}
case State.DTD_DECL_KEYWORD: {
if (code === CC_DASH) {
// Could be start of comment
if (this.#dtdDeclKeyword === "") {
this.#advanceWithCode(code);
this.#state = State.DTD_COMMENT_START;
} else {
this.#error(
`Unexpected '-' in declaration keyword '${this.#dtdDeclKeyword}'`,
);
}
} else if (this.#isWhitespaceCode(code)) {
// End of keyword, validate and continue
const kw = this.#dtdDeclKeyword;
if (
kw === "ENTITY" || kw === "ELEMENT" || kw === "ATTLIST" ||
kw === "NOTATION"
) {
this.#advanceWithCode(code);
this.#dtdDeclParenDepth = 0;
this.#dtdDeclSawWhitespace = true;
// Initialize ENTITY declaration parsing state
this.#isEntityDecl = kw === "ENTITY";
this.#isParameterEntity = false;
this.#entityName = "";
this.#entityParsePhase = "name";
this.#entityExternalType = "";
this.#entityQuotedLiterals = 0;
this.#entityCurrentKeyword = "";
this.#state = State.DTD_DECL_CONTENT;
} else {
this.#error(`Unknown declaration type '<!${kw}'`);
}
} else if (
code >= CC_A_UPPER && code <= CC_Z_UPPER ||
code >= CC_A_LOWER && code <= CC_Z_LOWER
) {
this.#dtdDeclKeyword += String.fromCharCode(code);
this.#advanceWithCode(code);
} else {
this.#error(
`Unexpected character '${
String.fromCharCode(code)
}' in declaration keyword`,
);
}
break;
}
case State.DTD_DECL_CONTENT: {
if (code === CC_GT && this.#dtdDeclParenDepth === 0) {
// End of declaration - validate and emit entity if applicable
if (this.#isEntityDecl) {
// Process any pending keyword
this.#processEntityKeyword();
// Validate PUBLIC has both literals
if (
this.#entityExternalType === "PUBLIC" &&
this.#entityQuotedLiterals < 2
) {
this.#error(
"PUBLIC identifier requires both public ID and system ID literals",
);
}
// Emit entity if applicable
if (!this.#isParameterEntity && this.#entityName) {
this.#callbacks.onEntityDeclaration?.(
this.#entityName,
"",
);
}
}
this.#isEntityDecl = false;
this.#advanceWithCode(code);
this.#state = State.DOCTYPE_INTERNAL_SUBSET;
} else if (code === CC_DQUOTE || code === CC_SQUOTE) {
// String literal - must have whitespace before (except after opening paren)
if (!this.#dtdDeclSawWhitespace && this.#dtdDeclParenDepth === 0) {
this.#error(
`Missing whitespace before quoted string in DTD declaration`,
);
}
// Process any pending keyword before the quote
if (this.#isEntityDecl) {
this.#processEntityKeyword();
}
this.#dtdDeclQuoteChar = String.fromCharCode(code);
this.#advanceWithCode(code);
// Initialize string tracking
this.#dtdStringValue = "";
this.#dtdStringIsPubid = false;
// For ENTITY declarations, track quoted literals
if (this.#isEntityDecl) {
this.#entityQuotedLiterals++;
// First quoted literal after PUBLIC is PubidLiteral
if (
this.#entityExternalType === "PUBLIC" &&
this.#entityQuotedLiterals === 1
) {
this.#dtdStringIsPubid = true;
}
}
this.#state = State.DTD_DECL_STRING;
} else if (this.#isWhitespaceCode(code)) {
// Process any accumulated keyword before whitespace
if (this.#isEntityDecl && this.#entityCurrentKeyword) {
this.#processEntityKeyword();
}
this.#dtdDeclSawWhitespace = true;
this.#advanceWithCode(code);
} else if (code === 40) { // (
// Opening paren - must have whitespace before FIRST paren only
// Nested parens like ((a|b)) are valid without whitespace between them
if (!this.#dtdDeclSawWhitespace && this.#dtdDeclParenDepth === 0) {
this.#error(
`Missing whitespace before '(' in DTD declaration`,
);
}
this.#dtdDeclParenDepth++;
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (code === 41) { // )
if (this.#dtdDeclParenDepth === 0) {
this.#error(`Unexpected ')' in DTD declaration`);
}
this.#dtdDeclParenDepth--;
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (code === CC_LBRACKET) {
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (code === CC_RBRACKET) {
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (code === 124) { // |
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (code === 44) { // ,
// Comma is valid in element content models (sequence operator)
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (code === 37) { // %
// Parameter entity marker or reference
if (
this.#isEntityDecl && this.#entityParsePhase === "name" &&
this.#entityName === ""
) {
// This is a parameter entity declaration: <!ENTITY % name "value">
this.#isParameterEntity = true;
}
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (code === 59) { // ;
// End of entity reference
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (code === 35) { // #
// #PCDATA, #IMPLIED, #REQUIRED, #FIXED
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (
this.#isNameStartCharCode(code) || this.#isNameCharCode(code)
) {
// Name token - for ENTITY declarations, capture name or keyword
if (this.#isEntityDecl) {
if (this.#entityParsePhase === "name") {
// Accumulate entity name
this.#entityName += String.fromCharCode(code);
} else {
// In value phase, accumulate keyword (SYSTEM/PUBLIC/NDATA)
this.#entityCurrentKeyword += String.fromCharCode(code);
}
}
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (code === CC_DASH) {
// Check for SGML-style comment (--) which is invalid in XML
if (
this.#isEntityDecl &&
this.#dtdDeclParenDepth === 0 &&
this.#bufferIndex + 1 < this.#buffer.length &&
this.#buffer.charCodeAt(this.#bufferIndex + 1) === CC_DASH
) {
this.#error(
"SGML-style comments (--) are not allowed in XML declarations",
);
}
// Hyphen in name (valid in NameChar but not NameStartChar)
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else if (code === 42 || code === 43 || code === 63) {
// Content model operators: * + ?
this.#dtdDeclSawWhitespace = false;
this.#advanceWithCode(code);
} else {
this.#error(
`Unexpected character '${
String.fromCharCode(code)
}' in DTD declaration`,
);
}
// Transition from name to value phase when whitespace follows the name
if (
this.#isEntityDecl && this.#entityParsePhase === "name" &&
this.#dtdDeclSawWhitespace && this.#entityName !== ""
) {
this.#entityParsePhase = "value";
}
break;
}
case State.DTD_DECL_STRING: {
if (String.fromCharCode(code) === this.#dtdDeclQuoteChar) {
// Validate PubidLiteral if applicable
if (this.#dtdStringIsPubid) {
this.#validatePubidLiteral(
this.#dtdStringValue,
this.#dtdDeclQuoteChar,
);
}
// For ENTITY declarations, mark value capture as done
if (this.#isEntityDecl && this.#entityParsePhase === "value") {
this.#entityParsePhase = "done";
}
this.#advanceWithCode(code);
this.#dtdDeclSawWhitespace = false;
this.#state = State.DTD_DECL_CONTENT;
} else {
if (this.#dtdStringIsPubid) {
this.#dtdStringValue += String.fromCharCode(code);
}
this.#advanceWithCode(code);
}
break;
}
case State.DTD_COMMENT_START: {
if (code === CC_DASH) {
this.#advanceWithCode(code);
this.#state = State.DTD_COMMENT;
} else {
this.#error(`Expected '-' after '<!-' in DTD`);
}
break;
}
case State.DTD_COMMENT: {
if (code === CC_DASH) {
this.#advanceWithCode(code);
this.#state = State.DTD_COMMENT_DASH;
} else {
this.#advanceWithCode(code);
}
break;
}
case State.DTD_COMMENT_DASH: {
if (code === CC_DASH) {
this.#advanceWithCode(code);
this.#state = State.DTD_COMMENT_DASH_DASH;
} else {
this.#advanceWithCode(code);
this.#state = State.DTD_COMMENT;
}
break;
}
case State.DTD_COMMENT_DASH_DASH: {
if (code === CC_GT) {
this.#advanceWithCode(code);
this.#state = State.DOCTYPE_INTERNAL_SUBSET;
} else {
// Per XML 1.0 §2.5, after '--' only '>' is permitted.
// Any other character (including '-') means '--' appears
// within the comment content, which is not allowed.
this.#error(
`Cannot use '--' within XML comments (XML 1.0 §2.5)`,
);
}
break;
}
case State.DTD_PI: {
if (code === CC_QUESTION) {
this.#advanceWithCode(code);
this.#state = State.DTD_PI_QUESTION;
} else {
this.#advanceWithCode(code);
}
break;
}
case State.DTD_PI_QUESTION: {
if (code === CC_GT) {
this.#advanceWithCode(code);
this.#state = State.DOCTYPE_INTERNAL_SUBSET;
} else if (code === CC_QUESTION) {
// Multiple ? in a row
this.#advanceWithCode(code);
} else {
this.#advanceWithCode(code);
this.#state = State.DTD_PI;
}
break;
}
case State.DTD_PE_REF: {
// Parameter entity reference: %name;
// Skip the name and semicolon, then return to internal subset
if (code === 59) { // ;
this.#advanceWithCode(code);
this.#state = State.DOCTYPE_INTERNAL_SUBSET;
} else if (this.#isNameCharCode(code)) {
// Name characters are valid
this.#advanceWithCode(code);
} else {
this.#error("Invalid character in parameter entity reference");
}
break;
}
}
}
}
/**
* Finalize tokenization using callbacks.
*
* This method should be called after all chunks have been processed.
* It flushes any pending text content and validates that the tokenizer
* is in a valid end state.
*
* @throws {XmlSyntaxError} If the tokenizer is in an incomplete state.
*/
finalize(callbacks: XmlTokenCallbacks): void {
this.#callbacks = callbacks;
this.#flushText();
if (this.#state !== State.INITIAL) {
// Provide specific error messages based on state
const message = this.#getEndOfInputErrorMessage();
this.#error(message);
}
}
#getEndOfInputErrorMessage(): string {
switch (this.#state) {
// Unreachable - finalize() only calls this when state !== INITIAL.
// Included for compile-time exhaustiveness checking.
// deno-coverage-ignore-start
case State.INITIAL:
return "Unexpected end of input";
// deno-coverage-ignore-stop
case State.TAG_OPEN:
return "Unexpected end of input after '<'";
case State.TAG_NAME:
case State.AFTER_TAG_NAME:
case State.ATTRIBUTE_NAME:
case State.AFTER_ATTRIBUTE_NAME:
case State.BEFORE_ATTRIBUTE_VALUE:
case State.EXPECT_SELF_CLOSE_GT:
return "Unexpected end of input in start tag";
case State.ATTRIBUTE_VALUE_DOUBLE:
case State.ATTRIBUTE_VALUE_SINGLE:
return "Unterminated attribute value";
case State.END_TAG_NAME:
case State.AFTER_END_TAG_NAME:
return "Unexpected end of input in end tag";
case State.COMMENT:
case State.COMMENT_START:
case State.COMMENT_DASH:
case State.COMMENT_DASH_DASH:
return "Unterminated comment";
case State.CDATA:
case State.CDATA_START:
case State.CDATA_BRACKET:
case State.CDATA_BRACKET_BRACKET:
return "Unterminated CDATA section";
case State.PI_TARGET:
case State.PI_TARGET_QUESTION:
case State.PI_CONTENT:
case State.PI_QUESTION:
return "Unterminated processing instruction";
case State.MARKUP_DECLARATION:
return "Unexpected end of input in markup declaration";
case State.DOCTYPE_START:
case State.DOCTYPE_NAME:
case State.DOCTYPE_AFTER_NAME:
case State.DOCTYPE_PUBLIC:
case State.DOCTYPE_PUBLIC_ID:
case State.DOCTYPE_AFTER_PUBLIC_ID:
case State.DOCTYPE_SYSTEM:
case State.DOCTYPE_SYSTEM_ID:
case State.DOCTYPE_INTERNAL_SUBSET:
case State.DOCTYPE_INTERNAL_SUBSET_STRING:
case State.DTD_DECL_START:
case State.DTD_DECL_KEYWORD:
case State.DTD_DECL_CONTENT:
case State.DTD_DECL_STRING:
return "Unterminated DOCTYPE";
case State.DTD_COMMENT:
case State.DTD_COMMENT_START:
case State.DTD_COMMENT_DASH:
case State.DTD_COMMENT_DASH_DASH:
return "Unterminated comment in DOCTYPE";
case State.DTD_PI:
case State.DTD_PI_QUESTION:
return "Unterminated processing instruction in DOCTYPE";
case State.DTD_PE_REF:
return "Unterminated parameter entity reference in DOCTYPE";
}
// TypeScript ensures exhaustiveness - if a new State is added,
// compilation fails until it's handled above.
}
}
|