All files / xml / _tokenizer.ts

94.63% Branches 634/670
92.49% Lines 1797/1943
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
 
 
 
 
 
 
 
 
 
 
 
 
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
 
 
x30
 
 
 
 
 
 
 
x6
x6
x324
x324
x324
x324
x324
 
x324
x324
x324
 
 
x324
 
 
x324
x324
x324
x324
x324
x324
 
x324
 
 
x324
x324
x324
x324
x324
x324
x324
x324
x324
x324
 
 
x324
 
 
x324
x324
x324
x324
x324
 
 
x324
x324
 
 
x324
x324
 
 
x324
x324
x324
x324
 
 
x324
x324
x324
x324
x324
x324
x324
x324
 
 
x324
x324
 
 
x324
x324
x324
 
 
x6
 
 
 
 
 
 
x6
x324
x324
 
x6
x598
x1085
x1085
x1085
x598
 
x6
x112
x112
x112
x869
x112
 
x112
 
 
x6
 
x798
x1582
x1582
x1582
x1582
x806
x798
 
x6
 
x2336
x4658
x4658
x4658
x4658
x4658
x4658
x2344
x2336
 
 
 
 
 
 
x6
x6
x6
 
x420
 
x420
x424
 
x424
 
x424
x1696
x424
x424
x3320
x420
 
 
 
 
 
 
x6
x6
x6
 
x412
x1648
x412
 
 
 
 
 
 
x6
x6
x6
 
x14
x56
x14
 
x6
x1911
x1911
x1911
 
x6
x813
x1409
x1409
x1409
x1409
x1409
 
x1472
x1472
x1472
x1472
x1472
x1472
 
x1472
x1409
x813
 
x6
x65
x65
x65
x65
x65
x65
 
x6
x405
x405
x405
x405
x405
x405
 
x6
x72
x72
x72
x72
x72
x72
 
x6
x59
x59
x59
x59
x59
x59
 
x6
 
x413
x413
x413
x413
x413
x413
x413
x413
x413
x413
x762
x762
 
x778
x792
x792
x792
 
x792
x792
x778
x784
x784
x784
 
x784
x784
x778
x780
x780
x780
 
x780
x780
x778
x802
x802
x802
 
x802
x802
x778
x786
x786
x786
 
x786
x786
x778
x779
x779
x779
 
x779
x779
x778
x780
x780
x780
 
x780
x780
x778
x779
x779
x779
 
x779
x779
x413
 
x6
x5170
x9831
x9832
x9832
x9831
x14491
x14491
x9831
x9831
x5170
x5170
 
 
 
 
 
x6
x169
 
x302
x302
x441
x441
 
x574
x574
x574
 
x447
x447
x447
x447
x302
x169
 
x6
x413
x413
 
 
 
 
 
x6
x43
x43
 
x43
 
 
x43
x48
x49
x49
x52
x52
x52
x43
x47
x48
x48
x50
x50
x50
x43
 
x45
x46
x46
x46
x46
x46
 
x46
 
 
 
 
 
x46
x43
x44
x43
x46
x46
x46
x46
 
x43
 
x6
x35
 
x35
x37
x37
 
x37
 
x62
 
 
 
x35
x37
x37
 
x37
 
x60
 
 
 
 
 
 
x83
 
x60
 
 
x60
x35
x47
x47
 
x35
x35
x35
x35
x35
x35
x35
 
x35
 
 
x6
x18
x18
x18
x18
x18
x18
x18
x287
x287
x287
x18
x18
x18
 
 
 
 
 
 
 
 
 
 
x6
x16
x194
x194
 
 
 
 
x194
x194
x194
x194
x194
x194
x194
x194
x194
x194
x194
x194
 
x194
x195
x195
x195
x195
 
x195
x194
x16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x6
 
x621
x1222
x1712
x1712
x1712
x1712
x1222
x1222
 
 
x621
x1113
x1858
x1858
x2345
x2345
 
x2858
 
x1858
x1858
x1858
x2602
x2602
x2602
x2602
 
x2602
 
x2856
 
x1858
x1858
x1858
x1858
x1858
x1858
x2601
x2601
 
x2600
x2616
x2616
x2600
x2839
x2839
x2855
x2855
x2855
x621
 
x1284
x1540
x1540
x1647
x1647
 
x1689
 
x1540
x1540
x1540
x1541
x1541
x1541
x1541
 
x1541
 
x1688
x1540
x1540
x1540
x1540
x1540
x1540
x1541
x1541
 
x1687
x1687
x1284
 
x1177
x621
 
 
 
 
 
 
 
 
x6
 
 
x497
x848
x2090
 
x2090
x3328
x3674
x3674
x4220
x4220
x4220
x2090
 
x2094
x2094
x2094
 
 
 
 
x2094
x2094
x2094
x2094
x2090
x497
 
x637
x1217
 
x1217
x1793
x1916
x1916
x2246
x1217
 
x1221
x1221
x1221
 
 
 
 
x1221
x1221
x1217
x637
x497
 
 
 
 
 
 
 
 
 
x6
x37
 
x37
 
x58
 
x58
 
x58
x61
x61
 
x61
 
 
 
 
 
 
 
 
 
 
 
 
x58
x58
x58
x58
x59
x59
x59
 
x59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x75
x58
x1250
x1250
x1252
x1252
x1252
x1252
x1252
 
x1252
x1250
 
x73
 
 
x73
x73
 
 
x73
 
x58
x58
x58
x58
x58
 
 
x58
x58
x58
x58
x58
 
 
 
x47
x37
x37
x37
x37
x72
x72
x72
x72
x72
x73
x73
x72
 
 
x75
x75
 
x75
 
 
 
 
 
 
x75
x75
x116
 
 
 
 
 
 
 
 
x116
 
x75
x75
x75
x75
x75
 
x75
x37
 
 
 
 
 
x6
x58
 
x58
 
 
x103
x103
x975
x975
x977
x977
x977
x977
x977
 
x977
x975
 
x146
x146
 
 
x146
x146
 
 
x103
x130
x103
 
x119
x119
x119
x119
x119
x119
x119
 
x119
 
x131
x131
x131
x131
x131
x131
 
 
 
x65
x58
x58
x58
x58
x104
x104
 
 
x107
x107
x107
x170
 
 
 
 
 
 
 
 
x170
 
x107
x107
x107
x107
x107
 
x107
x58
 
 
 
 
 
 
 
x6
x34
 
x34
 
 
x55
x55
x260
x260
x262
x262
x262
x262
x262
 
x262
x260
 
x74
x74
 
 
x74
x74
 
x55
x55
x55
x55
x55
 
 
x55
x55
x55
x55
x55
 
 
 
x41
x34
x34
x34
x34
x61
x61
x61
x61
x61
x63
x63
x61
 
 
x63
x63
x63
x85
 
 
 
 
 
 
 
 
x85
 
x63
x63
x63
x63
x63
 
x63
x34
 
 
 
 
 
 
 
 
x6
x6
x6
x6
 
x71
x71
 
x71
 
 
x133
x673
x673
x676
x676
x676
x673
 
 
x192
x192
x192
x192
 
 
 
x119
x132
 
 
 
 
x132
 
 
x122
x122
x122
x122
x122
x122
 
x122
x71
 
 
 
 
 
 
 
 
 
 
 
x6
x413
x413
x413
x413
x413
 
 
 
x413
x413
 
 
x413
x731
 
 
 
x731
 
x413
 
x5381
 
 
x5381
 
 
x11377
 
x5996
 
x6590
x6590
x6590
x6590
x6590
 
 
x6604
x6604
 
x11055
 
x5674
 
 
x5674
 
x5684
x5684
 
 
x5957
x5674
x5735
x5735
x5735
x5735
x5735
 
x5735
x5735
x5674
x6030
x6030
x6030
x6030
x6030
 
x6030
x6030
x6030
x5896
x6070
x6070
x6070
x6070
x6070
 
x6070
x6070
x5984
x5986
x5986
x5986
x5986
 
x5986
x5953
x5953
 
x10893
 
x5512
x5512
x5512
x5512
 
x5633
x5633
x5633
 
x5633
x5634
x5634
x5634
x5634
 
x5634
 
x5633
x5755
x5755
x5753
 
 
x5642
 
 
x5512
 
x5523
x5523
 
x5631
x5512
x5516
x5516
x5516
x5516
x5512
x5741
x5741
x5741
x5741
x5741
 
x5741
x5741
x5627
x5628
x5628
x5628
x5628
 
x5628
x5627
x5627
 
x10824
 
x5443
 
x5500
x5500
x5500
 
x5500
x5500
 
x5500
x5500
x5500
 
x5500
x5500
 
x10887
x5506
 
x5516
x5516
x5506
x5745
x5745
x5745
x5745
x5734
x5873
x5873
x5873
x5838
x5975
x5975
x5976
x5976
x6042
x6042
x6042
x6042
x5907
x5908
x5908
x5908
x5908
 
x5908
x5629
x5629
 
x10830
 
x5449
 
 
x5449
 
x5450
x5450
 
x5516
x5449
 
x5452
x5452
x5452
x5452
x5449
x5576
x5576
x5576
x5576
x5513
x5514
x5514
x5514
x5514
 
x5514
x5515
x5515
 
x11353
x5972
x6680
x6680
x6680
x6680
x6559
x7157
x7157
x7029
x7428
x7428
x7428
x7428
x7371
 
x7656
x7656
x7656
 
x7656
x7940
x7940
 
x7940
x8226
x8226
x7940
x7656
x7657
x7657
 
x7657
x7656
x6562
x6562
 
 
 
x10832
x5451
x5456
x5451
x5576
x5576
x5576
x5576
x5516
x5524
x5524
x5524
x5524
x5521
x5523
x5523
x5519
x5519
 
x10766
x5385
x5386
x5385
x5390
x5390
x5388
x5389
x5389
x5388
x5388
 
x10883
x5502
x5622
x5622
x5622
x5502
x5503
x5503
x5618
x5618
 
x10768
x5387
x5389
x5387
x5394
x5394
x5394
x5394
x5394
 
x5394
x5394
x5394
x5391
x5392
x5392
 
x5392
x5392
x5392
 
x10765
 
x5384
 
x5386
x5386
x5386
 
x5386
x5386
 
x5386
x5386
x5386
 
x5386
x5386
 
 
 
x10793
 
x5412
x5427
x5427
 
x5440
x5443
x5443
 
x5447
 
x5447
x5447
x5447
x5447
 
x5447
x5447
x5447
 
 
 
x5447
x5447
 
x10790
 
x5409
x5426
x5426
 
x5431
x5433
x5433
 
x5436
 
x5436
x5436
x5436
x5436
 
x5436
x5436
x5436
 
 
 
x5436
x5436
 
x10814
 
x5433
x5461
x5461
 
x5475
x5478
x5478
 
x5479
x5479
 
 
 
 
 
 
 
 
x5479
x5479
x5479
x5479
 
x5479
x5479
x5479
 
 
 
x5479
x5479
 
x10889
x5508
x5536
x5536
x5508
x5632
x5632
x5632
x5607
x5754
x5754
x5754
x5681
x5682
x5682
x5634
x5634
 
x10790
x5409
x5436
x5436
x5436
x5436
x5409
x5410
x5410
x5436
x5436
 
x10769
x5388
x5393
 
x5393
x5393
x5388
x5390
x5390
x5390
x5390
x5390
x5388
x5388
 
x10769
x5388
x5391
 
 
 
 
 
 
 
 
x5391
x5391
x5391
x5391
x5391
x5391
x5393
x5393
 
x5393
 
x5392
x5391
x5391
x5391
x5391
x5391
 
x5391
x5391
x5391
x5391
x5388
 
 
x5394
x5394
x5394
x5394
 
x5394
x5394
 
x5394
x5391
x5391
 
x10911
x5530
x5530
x5530
x5554
x5554
x5554
x5530
x5656
x5656
x5678
x5678
 
x10767
x5386
x5389
x5389
x5389
x5386
x5388
x5388
x5388
x5388
x5386
x5386
 
x10765
x5384
x5386
x5386
x5386
x5386
x5386
 
x5386
x5386
x5386
x5386
 
 
 
 
 
x5385
x5385
x5385
x5385
x5384
x5384
 
x10998
 
x5617
x5617
 
x5617
x5674
x5674
x5729
x5674
 
x5677
x5677
x5677
x5677
x5677
x5677
 
x5677
x5617
 
x5921
x5796
 
x5898
x5898
x5898
x5898
x5898
x5898
x5850
x5861
x5861
x5861
x5861
x5856
x5857
x5857
x5857
x5857
 
x5857
x5850
x5850
 
x10766
x5385
x5388
x5389
x5388
 
x5390
x5390
x5390
x5390
x5390
x5390
x5390
 
x5390
x5390
x5390
x5390
x5385
x5386
x5386
x5386
x5386
 
x5386
x5387
x5387
 
x10766
x5385
x5387
x5388
x5388
x5388
 
x5388
 
x5388
x5388
x5388
x5388
x5388
x5388
x5388
 
x5388
x5387
x5387
x5387
x5387
 
 
 
 
x5387
 
x5387
x5387
x5387
x5387
x5385
x5385
 
 
 
x11199
x5818
x5818
x5818
x5889
x5889
x5889
x5889
x5818
x6185
x6185
x6254
x6254
 
x11191
x5810
x5947
x5947
x6013
x6013
x5810
x6104
x6104
x6104
x6104
x6104
x6104
x6104
 
x6104
x6104
x6102
x6393
x6393
x6393
 
 
 
 
x6969
x6969
x6681
x6682
x6682
x6682
x6682
 
x6682
x6238
x6238
 
x10860
 
 
 
x5511
x5511
x5511
x5511
x5511
x5511
x5511
 
x5511
x5511
x5479
x5597
x5597
x5597
x5545
x5568
x5568
x5568
x5559
x5567
x5567
x5567
x5564
 
x5567
x5567
x5567
x5567
x5567
x5567
x5567
x5567
x5567
x5567
x5567
 
x5567
 
 
 
 
 
x5567
x5567
x5567
x5567
x5567
x5567
x5567
x5567
x5567
x5567
x5567
 
x5567
 
 
 
 
 
 
 
 
x5575
x5575
 
x10807
x5426
x5426
x5426
x5434
x5426
x5464
x5464
x5470
x5470
 
x10778
x5397
x5405
x5405
x5412
x5412
x5412
 
x5412
x5412
x5412
 
x5412
x5405
x5406
x5406
x5411
x5411
 
x10773
x5392
x5397
x5392
x5402
x5402
x5402
x5402
x5398
x5401
x5401
x5401
x5401
x5401
x5401
x5401
 
x5401
x5401
x5401
x5401
x5401
x5402
x5402
 
x10777
x5396
x5396
x5396
x5398
x5396
x5410
x5410
x5410
x5410
 
x10766
x5385
x5387
x5387
x5388
x5388
x5388
x5388
x5388
x5388
x5388
x5388
x5388
 
x10844
x5463
x5490
x5490
x5490
x5490
x5490
x5463
x5566
x5566
x5518
x5526
x5525
 
x5532
x5532
 
x5531
x5540
x5540
x5536
x5537
x5537
x5537
x5537
 
x5537
x5543
x5543
 
 
 
 
 
 
 
 
 
 
 
x10810
x5429
x5471
x5471
x5471
x5429
x5440
x5440
x5435
x5436
x5436
x5476
x5476
 
x11020
x5639
 
x5647
x5654
x5654
x5647
x5648
x5648
 
x5648
x5639
 
x5921
x5921
x5921
x5921
x5921
x5952
x5952
x5952
 
x5952
x5952
x5952
x5952
x5952
x5952
x5952
x5952
x5952
x5921
x5922
x5922
 
 
 
 
x6324
x6324
x6107
x6108
x6108
x6108
x6108
 
x6108
x5894
x5894
 
x11160
x5779
 
x5798
 
x5806
 
x5806
x5806
x5806
x5806
x5807
x5807
 
x5807
 
x5806
x5806
x5806
x5806
 
 
 
 
x5813
x5806
x5816
x5816
x5816
x5779
 
x6177
x6178
x6178
 
x6178
 
x6177
x6192
x6192
x6195
x6195
 
x6195
x6195
 
x6177
x6192
x6206
x6206
x6192
 
x6192
x6192
x6192
x6192
x6195
x6195
x6192
x6195
x6158
 
x6582
x6596
x6596
x6639
x6639
x6518
 
 
x6824
x6825
x6825
 
x6825
x6833
x6833
x6833
x6814
x7110
x7111
x7111
x7119
x7119
x7119
 
 
 
 
 
 
 
x7381
x7381
x7376
 
x7651
x7651
x7647
 
x7915
x7915
x7915
x7915
 
x7915
x7915
x7915
x7915
 
 
 
 
 
 
x8186
x8186
x8180
x8180
x8180
 
x8696
x8819
 
x8861
x8819
 
x8900
x8900
x8819
x8696
x8696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x8447
x8447
x8444
x8445
x8445
x8445
x8445
 
x8445
 
x5779
x5779
x5779
x5779
x5796
x5796
x6165
x6165
 
x10929
x5548
 
x5565
x5568
x5568
x5568
 
x5568
 
x5565
x5578
x5578
x5565
x5565
x5565
x5548
 
x5698
 
x5698
x5804
x5804
x5698
x5698
x5548
x5548
 
x10769
x5388
x5394
x5394
x5388
x5389
x5389
x5394
x5394
 
x10809
x5428
x5435
x5435
x5428
x5468
x5468
x5428
x5428
 
x10769
x5388
x5393
x5393
x5388
x5390
x5390
x5390
x5388
x5388
 
x10769
x5388
x5392
x5392
x5388
 
x5393
x5391
 
x5392
x5392
 
x5392
x5394
x5394
 
x10838
x5457
x5462
x5462
x5457
x5528
x5528
x5457
x5457
 
x10770
x5389
x5393
x5393
x5393
 
x5396
x5393
x5394
x5394
x5394
x5389
x5389
 
x10800
 
 
x5419
x5421
x5421
x5419
 
x5490
x5455
x5456
x5456
x5456
x5456
x5381
x5381
x413
 
 
 
 
 
 
 
 
 
 
 
x6
x219
x219
 
x219
 
x236
x236
x236
x219
 
x6
x23
 
 
 
 
 
 
x23
x24
x23
x23
x23
x23
x23
x23
x24
x23
x23
x24
x23
x23
x24
x23
x23
x23
x23
x24
x23
x23
x23
x23
x24
x23
x23
x23
x23
x26
x23
x24
x23
x23
x23
x23
x23
x23
x23
x23
x23
x23
x23
x23
x23
x23
x27
x23
x23
x23
x23
x24
x23
x23
x24
x23
x24
x23
 
 
x23
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


















































































































































































































































// 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_RE,
  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;
}

/** 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

/** 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;

  // 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 = "";
  #entityValue = "";
  #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.
   *
   * @param options Options for tokenizer behavior.
   */
  constructor(options: XmlTokenizerOptions = {}) {
    this.#trackPosition = options.trackPosition ?? true;
  }

  #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) {
        // 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;
    }

    if (this.#textStartIdx !== -1) {
      this.#textPartial += this.#buffer.slice(
        this.#textStartIdx,
        this.#bufferIndex,
      );
      this.#textStartIdx = 0;
    }
    if (this.#cdataStartIdx !== -1) {
      this.#cdataPartial += this.#buffer.slice(
        this.#cdataStartIdx,
        this.#bufferIndex,
      );
      this.#cdataStartIdx = 0;
    }
    if (this.#attrStartIdx !== -1) {
      this.#attrPartial += this.#buffer.slice(
        this.#attrStartIdx,
        this.#bufferIndex,
      );
      this.#attrStartIdx = 0;
    }
    if (this.#tagNameStartIdx !== -1) {
      this.#tagNamePartial += this.#buffer.slice(
        this.#tagNameStartIdx,
        this.#bufferIndex,
      );
      this.#tagNameStartIdx = 0;
    }
    if (this.#commentStartIdx !== -1) {
      this.#commentPartial += this.#buffer.slice(
        this.#commentStartIdx,
        this.#bufferIndex,
      );
      this.#commentStartIdx = 0;
    }
    if (this.#piTargetStartIdx !== -1) {
      this.#piTargetPartial += this.#buffer.slice(
        this.#piTargetStartIdx,
        this.#bufferIndex,
      );
      this.#piTargetStartIdx = 0;
    }
    if (this.#piContentStartIdx !== -1) {
      this.#piContentPartial += this.#buffer.slice(
        this.#piContentStartIdx,
        this.#bufferIndex,
      );
      this.#piContentStartIdx = 0;
    }
    if (this.#attrNameStartIdx !== -1) {
      this.#attrNamePartial += this.#buffer.slice(
        this.#attrNameStartIdx,
        this.#bufferIndex,
      );
      this.#attrNameStartIdx = 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_RE, "\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));
    }
    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 value The public ID value (without quotes)
   * @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.
   *
   * Validates XML 1.0 constraints:
   * - §2.4: "]]>" is not allowed in text content
   * - §2.2: Illegal C0 control characters are rejected
   */
  #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;
    }

    // Tight loop: scan for '<', validating characters as we go
    if (this.#trackPosition) {
      while (this.#bufferIndex < bufferLen) {
        const code = buffer.charCodeAt(this.#bufferIndex);
        if (code === CC_LT) {
          return true;
        }

        // XML 1.0 §2.2: Check for illegal C0 control characters
        // Valid: TAB (0x09), LF (0x0A), CR (0x0D)
        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: Check for "]]>" in text content
        // Only check when we see ']' to avoid overhead
        if (
          code === CC_RBRACKET &&
          this.#bufferIndex + 2 < bufferLen &&
          buffer.charCodeAt(this.#bufferIndex + 1) === CC_RBRACKET &&
          buffer.charCodeAt(this.#bufferIndex + 2) === CC_GT
        ) {
          this.#error("']]>' is not allowed in text content (XML 1.0 §2.4)");
        }

        if (code === CC_LF) {
          this.#line++;
          this.#column = 1;
        } else {
          this.#column++;
        }
        this.#offset++;
        this.#bufferIndex++;
      }
    } else {
      // Fast path without position tracking
      while (this.#bufferIndex < bufferLen) {
        const code = buffer.charCodeAt(this.#bufferIndex);
        if (code === CC_LT) {
          return true;
        }

        // XML 1.0 §2.2: Check for illegal C0 control characters
        // Valid: TAB (0x09), LF (0x0A), CR (0x0D) - inlined for performance
        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: Check for "]]>" in text content
        if (
          code === CC_RBRACKET &&
          this.#bufferIndex + 2 < bufferLen &&
          buffer.charCodeAt(this.#bufferIndex + 1) === CC_RBRACKET &&
          buffer.charCodeAt(this.#bufferIndex + 2) === CC_GT
        ) {
          this.#error("']]>' is not allowed in text content (XML 1.0 §2.4)");
        }

        this.#bufferIndex++;
      }
    }

    return false;
  }

  /**
   * Capture an XML name (element or attribute name) in a tight loop.
   * Returns the captured name, or empty string if no valid name found.
   *
   * Assumes the first character has already been validated as NameStartChar.
   * Continues until a non-NameChar is encountered.
   */
  #captureNameChars(buffer: string, bufferLen: number): void {
    // Tight loop: scan NameChar characters
    // Handles surrogate pairs for astral plane characters (U+10000+)
    if (this.#trackPosition) {
      while (this.#bufferIndex < bufferLen) {
        const code = buffer.charCodeAt(this.#bufferIndex);
        // Fast path for ASCII (99%+ of real XML)
        if (code < 0x80) {
          if (!this.#isNameCharCode(code)) {
            return; // End of name
          }
          this.#column++;
          this.#offset++;
          this.#bufferIndex++;
        } else {
          // Non-ASCII: use surrogate-aware checking
          const [isValid, charCount] = this.#isNameCharAt(
            buffer,
            this.#bufferIndex,
          );
          if (!isValid) {
            return; // End of name
          }
          this.#column += charCount;
          this.#offset += charCount;
          this.#bufferIndex += charCount;
        }
      }
    } else {
      // Fast path without position tracking
      while (this.#bufferIndex < bufferLen) {
        const code = buffer.charCodeAt(this.#bufferIndex);
        // Fast path for ASCII
        if (code < 0x80) {
          if (!this.#isNameCharCode(code)) {
            return;
          }
          this.#bufferIndex++;
        } else {
          // Non-ASCII: use surrogate-aware checking
          const [isValid, charCount] = this.#isNameCharAt(
            buffer,
            this.#bufferIndex,
          );
          if (!isValid) {
            return;
          }
          this.#bufferIndex += charCount;
        }
      }
    }
  }

  /**
   * 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(
          `'--' is not permitted within comments (XML 1.0 §2.5)`,
        );
      }

      // Also check the boundary between partial and new content
      if (
        this.#commentPartial.endsWith("-") && newContent.startsWith("-")
      ) {
        this.#error(
          `'--' is not permitted 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(
          `'-' is not permitted 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(
          `'-' is not permitted 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(
          `'--' is not permitted 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 endIdx = buffer.indexOf(quoteChar, this.#bufferIndex);

    if (endIdx !== -1) {
      // Found closing quote - validate and complete
      // Check for '<' which is not allowed in attribute values
      for (let i = this.#attrStartIdx; i < endIdx; i++) {
        const code = buffer.charCodeAt(i);
        if (code === CC_LT) {
          this.#bufferIndex = i;
          this.#error(`'<' not allowed in attribute value`);
        }
      }

      // Update position for the content region (not including closing quote)
      this.#updatePositionForRegion(buffer, this.#bufferIndex, endIdx);
      this.#bufferIndex = endIdx;
      return true; // Complete - ready to emit
    }

    // No closing quote found - consume as much as safely possible
    // Check for '<' and batch consume the region
    for (let i = this.#attrStartIdx; i < bufferLen; i++) {
      const code = buffer.charCodeAt(i);
      if (code === CC_LT) {
        this.#bufferIndex = i;
        this.#error(`'<' not allowed in attribute value`);
      }
    }

    // Batch consume the entire remaining buffer
    if (bufferLen > this.#bufferIndex) {
      this.#attrPartial += buffer.slice(this.#attrStartIdx, bufferLen);
      this.#updatePositionForRegion(buffer, this.#bufferIndex, 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.
   *
   * @param chunk The XML text chunk to process.
   * @param callbacks Callbacks to invoke for each token.
   */
  process(chunk: string, callbacks: XmlTokenCallbacks): void {
    this.#callbacks = callbacks;
    this.#savePartialsBeforeReset();
    this.#buffer = this.#buffer.slice(this.#bufferIndex) +
      this.#normalizeLineEndings(chunk);
    this.#bufferIndex = 0;

    // Cache hot variables locally to reduce private field access overhead.
    // Private field access (#) can be slower than local variable access.
    const buffer = this.#buffer;
    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 === ""
          ) {
            // Check for valid NameStartChar (handles astral plane via surrogate pairs)
            const [isValid, charCount] = this.#isNameStartCharAt(
              buffer,
              this.#bufferIndex,
            );
            if (!isValid) {
              this.#error(
                `Unexpected character '${
                  String.fromCharCode(code)
                }' in end tag`,
              );
            }
            // Advance by charCount (1 for BMP, 2 for astral plane)
            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);
          } 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 (this.#isNameStartCharCode(code)) {
            // XML 1.0 §3.1: Whitespace is required between attributes
            if (this.#needsAttrWhitespace) {
              this.#error("Whitespace is required 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 {
            // Check for valid NameStartChar (handles astral plane via surrogate pairs)
            const [isValid, charCount] = this.#isNameStartCharAt(
              buffer,
              this.#bufferIndex,
            );
            if (isValid) {
              this.#tagNameStartIdx = this.#bufferIndex;
              this.#tagNamePartial = "";
              // Advance by charCount (1 for BMP, 2 for astral plane)
              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);
          // Fall through to char-by-char for trailing `-` characters
          if (commentCode === CC_DASH) {
            this.#commentPartial += buffer.slice(
              this.#commentStartIdx,
              this.#bufferIndex,
            );
            this.#advanceWithCode(commentCode);
            this.#commentStartIdx = this.#bufferIndex;
            this.#state = State.COMMENT_DASH;
          } else {
            this.#advanceWithCode(commentCode);
          }
          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);
          // Fall through to char-by-char for trailing `]` characters
          if (cdataCode === CC_RBRACKET) {
            this.#cdataPartial += buffer.slice(
              this.#cdataStartIdx,
              this.#bufferIndex,
            );
            this.#advanceWithCode(cdataCode);
            this.#cdataStartIdx = this.#bufferIndex;
            this.#state = State.CDATA_BRACKET;
          } else {
            this.#advanceWithCode(cdataCode);
          }
          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
          }
          // Re-read code since bufferIndex may have changed
          const piCode = buffer.charCodeAt(this.#bufferIndex);
          // XML 1.0 §2.2: Validate character
          if (piCode < 0x20 && C0_VALID[piCode] !== 1) {
            this.#error(
              `Illegal XML character U+${
                piCode.toString(16).toUpperCase().padStart(4, "0")
              } in processing instruction (XML 1.0 §2.2)`,
            );
          }
          // Fall through to char-by-char for trailing `?` character
          if (piCode === CC_QUESTION) {
            this.#piContentPartial += buffer.slice(
              this.#piContentStartIdx,
              this.#bufferIndex,
            );
            this.#piContentStartIdx = -1;
            this.#advanceWithCode(piCode);
            this.#state = State.PI_QUESTION;
          } else {
            this.#advanceWithCode(piCode);
          }
          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(
                `'--' is not permitted 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(
                `'-' is not permitted 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(
              `'--' is not permitted 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("Processing instruction target is required");
            } 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") {
            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.#entityValue = "";
              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.#entityValue !== undefined
              ) {
                this.#callbacks.onEntityDeclaration?.(
                  this.#entityName,
                  this.#entityValue,
                );
              }
            }
            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) {
              if (this.#entityParsePhase === "value") {
                this.#entityValue = "";
              }
              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 {
            // Accumulate string value for validation
            this.#dtdStringValue += String.fromCharCode(code);
            // For ENTITY declarations in value phase, capture the value
            if (this.#isEntityDecl && this.#entityParsePhase === "value") {
              this.#entityValue += 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 if (code === CC_DASH) {
            // Stay in DASH_DASH state, ----> is valid ending
            this.#advanceWithCode(code);
          } else {
            // Per spec, -- is not allowed within comments
            this.#error(
              `'--' is not allowed 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.
   *
   * @param callbacks Callbacks to invoke for remaining tokens.
   * @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.
  }
}