All files / xml / _parse_sync.ts

93.45% Branches 471/504
91.25% Lines 960/1052
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
x4
x4
x4
x4
x4
x4
x4
x4
x4
x4
x4
x4
 
 
x4
x4
x4
x4
x4
x4
x4
x4
x4
x4
x4
 
 
 
 
 
 
 
 
 
 
x4
x4
x4
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
x151
x151
x151
 
x151
x151
x151
 
 
x151
 
 
x151
x151
x151
x151
 
 
 
 
x453
 
 
x151
 
x151
 
 
x151
x167
x885
x177
x167
x167
 
 
 
 
 
 
 
 
 
x151
 
 
 
 
x244
x1225
x245
x336
x336
x336
x244
x341
x341
x346
x346
x346
x346
x336
x336
x336
x336
x336
x244
 
x151
x244
x244
 
x151
x154
x154
x154
 
x151
x540
x1181
x1181
x1437
x1181
x1566
x1566
x1181
x540
 
x151
x878
x878
 
 
 
 
 
x151
x196
x290
 
x290
x303
x303
x303
 
x290
 
x325
x325
x325
 
x290
x331
x331
x332
x332
 
x371
x331
x369
x369
x331
x334
 
x334
x349
x349
x349
x349
x349
x350
x350
x350
x363
x363
x334
x334
x334
x344
x344
 
x290
 
x291
x291
 
x291
 
 
 
x290
x293
 
x293
x328
x328
x330
x330
x330
 
x328
x328
x328
x328
x328
 
 
x360
x360
x360
x329
x329
x295
x295
 
x291
x291
x197
x196
 
 
 
 
x151
x189
x190
x190
 
 
x189
x194
x194
x195
x195
x198
 
x194
x281
x281
x281
x281
x281
x284
x284
x285
x285
x286
x286
x286
x365
x365
x195
x195
 
 
x221
x189
x189
x189
 
x189
x383
x383
x221
 
x189
x189
x189
x189
x191
x191
 
 
x189
x190
x190
 
 
x189
x213
x189
 
x194
x194
x189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x151
 
x175
 
 
x175
x175
x178
 
x178
x179
x179
x180
x180
 
 
x198
x175
x176
x176
 
 
x175
x176
x176
x196
 
 
x196
x175
 
x180
 
 
x180
x180
x180
x180
x180
x180
x181
x181
 
x181
x175
 
x191
x191
x191
x191
x191
x191
x288
x288
x191
x191
 
 
x191
x192
x191
x207
x207
 
x191
 
x198
x199
x199
x204
x204
x198
 
x204
x205
x205
x209
x209
 
 
x204
x206
x206
 
x206
x206
 
 
x206
x204
x205
x205
 
x205
x205
x198
 
 
 
 
 
x199
 
 
x198
x191
 
x196
x196
x196
x196
x200
x201
x201
x203
 
x200
x201
x201
x202
 
x202
x200
x201
x201
x196
 
 
x197
 
 
 
x197
x197
x196
x191
 
 
x181
x175
x176
x176
x180
x175
 
 
 
 
 
x151
x168
 
 
 
x168
x168
x168
x168
x369
x369
x168
x169
x169
 
x168
x173
x173
x183
x168
 
 
 
 
 
 
 
x151
x157
x223
x223
 
 
 
 
x223
x223
x223
x223
x223
x223
 
 
 
 
 
 
 
x223
x224
x224
x224
x224
 
x224
x223
x157
 
 
 
 
 
x151
x156
x156
 
x156
x237
 
x237
x242
x242
x242
 
x237
x250
x250
x250
x250
 
x237
 
 
 
 
x238
x238
x238
x247
x247
 
 
 
x238
x238
x238
x238
 
x237
 
 
 
 
 
x240
x240
x240
x240
x240
 
x237
 
 
 
x240
x240
x240
x240
x240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x237
 
 
 
 
x240
x240
x240
x240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x237
x237
x237
 
x237
x237
x237
x237
 
 
x289
x289
x289
x289
 
 
 
 
 
 
 
 
 
x238
x238
x238
x238
 
 
 
 
 
 
 
 
x151
x416
 
 
x416
x416
 
x416
x416
x416
x416
x416
x416
x675
 
 
 
 
 
 
 
 
 
 
 
 
 
x422
x422
x416
 
 
x416
x1654
 
x1654
x1654
x1654
x1654
x1654
x1654
x1654
x1654
x1654
x2634
x2634
x2634
 
 
 
 
 
 
 
 
 
x1912
x1912
x675
x416
 
x151
x186
x186
x187
x187
x220
x220
 
x220
x186
x187
x187
x187
 
x219
 
x219
x186
 
x187
x187
x187
 
x218
 
x218
 
x218
x186
 
x151
x225
x225
x225
 
x225
 
 
x225
x595
x595
x596
x596
x596
x596
x596
 
x596
x595
 
x298
 
 
x298
 
x298
 
x298
x225
x226
x226
x226
 
 
x297
x225
 
x151
x201
x239
x239
x201
 
 
x151
 
x496
x570
x570
x570
 
x570
 
 
x570
x570
 
x588
x588
x590
x590
x590
 
x590
 
x588
x591
x591
x593
x593
 
x591
x592
x592
 
x592
x591
x588
 
x570
x2460
x615
x637
x637
 
x767
 
x496
x497
x497
 
x766
 
 
x496
x544
x544
x544
x545
x545
x591
x544
x546
x546
x589
 
x589
x544
x545
x545
 
 
 
x544
x546
x546
 
x546
 
 
x586
x544
x552
x552
x561
x567
x561
x564
x564
x561
x552
 
 
x544
x568
x568
x586
x586
 
 
x496
x564
 
 
x564
x564
x564
x564
x564
x572
x572
 
x572
x572
 
x579
x579
 
 
x572
x573
x573
x573
 
x572
x572
x572
x572
x573
x573
x573
 
x577
x572
x620
x620
x621
x621
x621
x621
x621
 
x621
x620
 
x576
x2316
x579
x576
x576
x576
 
 
x564
x570
x570
x571
x571
x571
 
x571
x570
x571
x571
x571
 
x571
 
x574
x574
 
x574
x570
 
x573
x570
x596
x596
x597
x597
x597
x597
x597
 
x597
x596
 
x2288
x572
x572
x572
 
 
x564
x682
 
 
x682
x682
x682
x683
x683
 
 
x734
x682
x938
x938
x1142
x1142
x682
x683
x683
 
 
x733
x733
x682
x792
 
x792
x847
x847
 
x892
x892
x892
x892
x847
 
x862
x863
x863
 
x863
x866
x866
x866
x866
x862
x862
x863
x863
 
x862
x863
x863
x863
x865
x862
x862
x862
x862
x863
x863
x863
x862
x862
x862
x862
x868
 
x868
x868
x868
x868
x868
 
x869
x869
 
x869
x869
x869
x869
 
x869
x869
 
 
 
 
 
x792
x697
x697
x697
 
x630
x630
 
 
x496
 
 
x517
x517
x517
x517
x518
x518
 
x537
x517
x518
x518
x518
 
x518
 
x536
 
x536
x536
x536
x536
x536
x536
x537
x537
x537
x537
 
x537
x536
 
x535
 
x535
x517
x518
x518
 
x534
x517
x838
x838
x839
x839
x839
x839
x839
 
x839
x838
 
x533
x533
 
x533
 
x517
x528
 
 
x529
x529
x529
 
x529
 
 
x538
x528
x529
x529
x529
 
x537
x537
x537
 
 
x528
x1586
x528
x532
x532
x528
x517
x524
x524
x524
x524
 
x524
 
x529
x529
 
 
x629
x496
x497
x497
 
x628
x628
x628
x496
x499
x499
x499
 
 
x496
x497
x497
x497
 
x624
x496
x497
x497
x497
 
 
 
x965
x965
 
 
 
x965
 
x838
x995
x995
x995
 
x995
x996
x996
 
x1151
 
x995
x1058
x1058
x1058
 
x1150
x1204
x1204
x1205
x1205
x1257
x1257
x1257
x1257
 
x1189
x995
x1151
x1151
 
 
x1188
x1150
x1151
x1151
 
x1151
 
x1187
x1187
x1187
x1150
x1151
x1151
x1151
 
x1186
x1150
x1151
x1151
x1315
x1315
 
x1315
 
 
x995
x1168
x1168
x1169
x1169
x1168
 
x1181
 
 
x1150
x1151
x1151
x1180
 
 
x1180
x1180
 
 
 
x612
 
 
x496
x524
 
x525
x525
x524
x540
x540
x540
 
x2160
x540
x540
x524
 
 
x838
 
x901
x901
 
x901
 
 
x612
x496
x512
 
x512
x527
x528
x528
x528
x541
x512
x513
x513
x512
 
 
x611
 
 
 
x611
 
x496
x524
x524
x545
 
 
x545
x548
x549
x549
 
x549
 
x550
x548
x549
x549
x550
x548
x549
x549
x1647
x549
x548
x545
x524
 
x610
 
x496
x497
x497
x497
 
x497
x497
x499
x499
x500
x500
 
x500
x500
x500
 
x497
 
 
 
x609
x609
x609
x609
x609
x609
 
x496
x875
x835
x908
x908
 
 
x838
x901
x496
 
x576
x576
 
 
x496
x499
x499
x500
x499
x501
x501
x499
x499
x496
 
 
x151
x154
x154
 
x151
x155
x155
x155
x620
 
 
x155
 
x201
x461
x151
x151
x151































































































































































































































































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 synchronous XML parser for non-streaming use.
 *
 * This module provides a high-performance single-pass parser that directly
 * builds the XML tree without intermediate tokens or events. It is used by
 * the `parse()` function for parsing complete XML strings.
 *
 * For streaming parsing, use {@linkcode parseXmlStream} from `parse_stream.ts`.
 *
 * @module
 */

import type {
  ParseOptions,
  XmlCDataNode,
  XmlCommentNode,
  XmlDeclarationEvent,
  XmlDocument,
  XmlElement,
  XmlName,
  XmlNode,
  XmlTextNode,
} from "./types.ts";
import { XmlSyntaxError } from "./types.ts";
import { decodeEntities } from "./_entities.ts";
import {
  isReservedPiTarget,
  LINE_ENDING_RE,
  parseName,
  validateNamespaceBinding,
  validateQName,
  validateXmlDeclaration,
  WHITESPACE_ONLY_RE,
  XML_NAMESPACE,
} from "./_common.ts";
import { isNameChar, isNameStartChar } from "./_name_chars.ts";

// 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_LBRACKET = 91; // [
const CC_RBRACKET = 93; // ]
const CC_DASH = 45; // -

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

/** Internal mutable type for building the tree. */
type MutableElement = {
  type: "element";
  name: XmlName;
  attributes: Record<string, string>;
  children: XmlNode[];
};

/**
 * Synchronous single-pass XML parser.
 *
 * Directly builds the XML tree without intermediate tokens or events,
 * providing significant performance improvements over the streaming parser
 * for non-streaming use cases.
 *
 * Uses lazy position tracking: line/column are only computed when an error
 * occurs, eliminating tracking overhead during successful parsing.
 *
 * @param xml The XML string to parse.
 * @param options Options to control parsing behavior.
 * @returns The parsed document.
 * @throws {XmlSyntaxError} If the XML is malformed.
 */
export function parseSync(xml: string, options?: ParseOptions): XmlDocument {
  const ignoreWhitespace = options?.ignoreWhitespace ?? false;
  const ignoreComments = options?.ignoreComments ?? false;
  const trackPosition = options?.trackPosition ?? true;

  // Normalize line endings (XML 1.0 §2.11)
  const input = xml.includes("\r") ? xml.replace(LINE_ENDING_RE, "\n") : xml;
  const len = input.length;

  // Parser state - only track position offset, not line/column
  let pos = 0;

  // Tree building state
  const stack: MutableElement[] = [];
  let root: MutableElement | undefined;
  let declaration: XmlDeclarationEvent | undefined;
  let rootClosed = false; // Track whether root element has been closed

  // Namespace tracking (lazy initialization for performance)
  // Only created when first namespace prefix is encountered
  // Using object wrapper to avoid TypeScript control flow narrowing issues with error()
  const ns: { bindings: Map<string, string> | null } = { bindings: null };
  // Stack of namespace bindings per element scope (array of [prefix, previousUri] tuples)
  // Used to restore bindings when element closes
  const nsStack: Array<Array<[string, string | undefined]>> = [];
  // Reusable empty array to avoid allocations for elements without namespace bindings
  const EMPTY_NS_SCOPE: Array<[string, string | undefined]> = [];

  /** Get or create namespace bindings map with xml prefix pre-bound */
  function getNsBindings(): Map<string, string> {
    if (!ns.bindings) {
      ns.bindings = new Map([["xml", XML_NAMESPACE]]);
    }
    return ns.bindings;
  }

  // Note: We do NOT expand custom entities from DTD.
  // We only support the 5 predefined XML entities: lt, gt, amp, apos, quot.
  // External entities (SYSTEM/PUBLIC) are also not supported.

  /**
   * Compute line and column from offset on-demand (lazy position tracking).
   * Only called when an error occurs, avoiding overhead during successful parsing.
   */
  function computePosition(offset: number): {
    line: number;
    column: number;
    offset: number;
  } {
    if (!trackPosition) {
      return { line: 0, column: 0, offset: 0 };
    }
    let line = 1;
    let lastNlPos = -1;
    let searchStart = 0;
    while (true) {
      const nlPos = input.indexOf("\n", searchStart);
      if (nlPos === -1 || nlPos >= offset) break;
      line++;
      lastNlPos = nlPos;
      searchStart = nlPos + 1;
    }
    return {
      line,
      column: offset - lastNlPos,
      offset,
    };
  }

  function error(message: string): never {
    throw new XmlSyntaxError(message, computePosition(pos));
  }

  function errorUnterminated(message: string): never {
    pos = len;
    error(message);
  }

  function skipWhitespace(): void {
    while (pos < len) {
      const code = input.charCodeAt(pos);
      if (code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d) {
        pos++;
      } else {
        break;
      }
    }
  }

  function isWhitespace(code: number): boolean {
    return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
  }

  /**
   * Parse DTD internal subset with validation.
   * Validates whitespace requirements per XML 1.0 spec.
   */
  function parseDTDInternalSubset(): void {
    while (pos < len) {
      const code = input.charCodeAt(pos);

      if (code === CC_RBRACKET) {
        pos++;
        return; // End of internal subset
      }

      if (isWhitespace(code)) {
        // Batch-skip whitespace for better performance
        skipWhitespace();
        continue;
      }

      if (code === CC_LT) {
        pos++;
        if (pos >= len) {
          error("Unexpected end of input in DTD");
        }

        const nextCode = input.charCodeAt(pos);
        if (nextCode === CC_BANG) {
          pos++;
          parseDTDMarkupDeclaration();
        } else if (nextCode === CC_QUESTION) {
          pos++;
          // Processing instruction in DTD
          while (pos < len) {
            if (
              input.charCodeAt(pos) === CC_QUESTION &&
              pos + 1 < len &&
              input.charCodeAt(pos + 1) === CC_GT
            ) {
              pos += 2;
              break;
            }
            pos++;
          }
        } else {
          error(`Unexpected character '${input[pos]}' after '<' in DTD`);
        }
        continue;
      }

      if (code === CC_LBRACKET) {
        // Conditional sections are not allowed in internal subset
        error(
          "Conditional sections (INCLUDE/IGNORE) are not allowed in internal DTD subset",
        );
      }

      // Parameter entity reference: %name;
      // These are valid in internal subset and must be skipped
      if (code === 37) { // %
        pos++; // Skip %
        // Read the entity name
        while (pos < len) {
          const c = input.charCodeAt(pos);
          if (c === 59) { // ;
            pos++;
            break;
          }
          // Name characters
          if (
            (c >= 97 && c <= 122) || // a-z
            (c >= 65 && c <= 90) || // A-Z
            (c >= 48 && c <= 57) || // 0-9
            c === 95 || c === 58 || c === 46 || c === 45 || // _ : . -
            (c > 127 && isNameChar(c))
          ) {
            pos++;
            continue;
          }
          error("Invalid character in parameter entity reference");
        }
        continue;
      }

      error(`Unexpected character '${input[pos]}' in DTD internal subset`);
    }
    error("Unterminated DTD internal subset");
  }

  /**
   * Parse a DTD markup declaration (<!ENTITY, <!ELEMENT, <!ATTLIST, <!NOTATION, or comment).
   */
  function parseDTDMarkupDeclaration(): void {
    if (pos >= len) {
      error("Unexpected end of input in DTD declaration");
    }

    // Check for comment
    if (input.charCodeAt(pos) === CC_DASH) {
      pos++;
      if (pos >= len || input.charCodeAt(pos) !== CC_DASH) {
        error("Expected '--' to start comment in DTD");
      }
      pos++;
      // Skip comment content
      while (pos < len) {
        if (
          input.charCodeAt(pos) === CC_DASH &&
          pos + 1 < len &&
          input.charCodeAt(pos + 1) === CC_DASH
        ) {
          pos += 2;
          if (pos >= len || input.charCodeAt(pos) !== CC_GT) {
            error("'--' is not allowed within XML comments (XML 1.0 §2.5)");
          }
          pos++;
          return;
        }
        pos++;
      }
      error("Unterminated comment in DTD");
    }

    // Read declaration keyword (ENTITY, ELEMENT, ATTLIST, NOTATION)
    const kwStart = pos;
    while (
      pos < len &&
      ((input.charCodeAt(pos) >= 65 && input.charCodeAt(pos) <= 90) || // A-Z
        (input.charCodeAt(pos) >= 97 && input.charCodeAt(pos) <= 122)) // a-z
    ) {
      pos++;
    }
    const keyword = input.slice(kwStart, pos);

    if (
      keyword !== "ENTITY" && keyword !== "ELEMENT" &&
      keyword !== "ATTLIST" && keyword !== "NOTATION"
    ) {
      error(`Unknown DTD declaration type '<!${keyword}'`);
    }

    // Must have whitespace after keyword
    if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
      error(`Missing whitespace after '<!${keyword}'`);
    }

    // For ENTITY declarations, extract the entity name and value
    if (keyword === "ENTITY") {
      parseEntityDeclaration();
    } else {
      // Parse the rest of the declaration with whitespace validation
      parseDTDDeclarationContent();
    }
  }

  /**
   * Parse and validate an ENTITY declaration syntax.
   *
   * We do NOT expand custom entities from DTD
   * We only support the 5 predefined XML entities (lt, gt, amp, apos, quot).
   * External entities (SYSTEM/PUBLIC) are also not supported.
   *
   * This function validates syntax but does not store entity definitions.
   *
   * EntityDecl ::= GEDecl | PEDecl
   * GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
   * PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
   * EntityDef ::= EntityValue | (ExternalID NDataDecl?)
   * PEDef ::= EntityValue | ExternalID
   * ExternalID ::= 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral
   * NDataDecl ::= S 'NDATA' S Name
   */
  function parseEntityDeclaration(): void {
    // Skip whitespace after ENTITY keyword (already validated by caller)
    skipWhitespace();

    // Check for parameter entity marker '%'
    const isParameterEntity = input.charCodeAt(pos) === 37; // %
    if (isParameterEntity) {
      pos++; // Skip '%'
      // Must have whitespace after '%'
      if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
        error("Missing whitespace after '%' in parameter entity declaration");
      }
      skipWhitespace();
    }

    // Read entity name
    const name = readName();
    if (name === "") {
      error("Missing entity name in ENTITY declaration");
    }

    // Must have whitespace after name
    if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
      error("Missing whitespace after entity name");
    }
    skipWhitespace();

    // Determine entity definition type
    const code = input.charCodeAt(pos);
    if (code === CC_DQUOTE || code === CC_SQUOTE) {
      // EntityValue - internal entity
      parseQuotedLiteral();

      // Check for SGML-style comment (-- after quoted value)
      skipWhitespace();
      if (
        pos + 1 < len &&
        input.charCodeAt(pos) === CC_DASH &&
        input.charCodeAt(pos + 1) === CC_DASH
      ) {
        error(
          "SGML-style comments (--) are not allowed in XML declarations",
        );
      }
    } else {
      // ExternalID - SYSTEM or PUBLIC
      const kwStart = pos;
      while (
        pos < len &&
        ((input.charCodeAt(pos) >= 65 && input.charCodeAt(pos) <= 90) || // A-Z
          (input.charCodeAt(pos) >= 97 && input.charCodeAt(pos) <= 122)) // a-z
      ) {
        pos++;
      }
      const keyword = input.slice(kwStart, pos);
      const keywordUpper = keyword.toUpperCase();

      // Check for case-sensitivity - must be uppercase
      if (keywordUpper === "SYSTEM" && keyword !== "SYSTEM") {
        error(`'${keyword}' must be uppercase 'SYSTEM'`);
      } else if (keywordUpper === "PUBLIC" && keyword !== "PUBLIC") {
        error(`'${keyword}' must be uppercase 'PUBLIC'`);
      }

      if (keyword === "SYSTEM") {
        // SYSTEM S SystemLiteral
        if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
          error("Missing whitespace after SYSTEM keyword");
        }
        skipWhitespace();
        parseQuotedLiteral();
      } else if (keyword === "PUBLIC") {
        // PUBLIC S PubidLiteral S SystemLiteral
        if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
          error("Missing whitespace after PUBLIC keyword");
        }
        skipWhitespace();
        parseQuotedLiteral(true); // PubidLiteral - validate characters

        // Must have whitespace before SystemLiteral
        if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
          error(
            "PUBLIC identifier requires both public ID and system ID literals",
          );
        }
        skipWhitespace();

        // SystemLiteral is required after PUBLIC
        const nextCode = input.charCodeAt(pos);
        if (nextCode !== CC_DQUOTE && nextCode !== CC_SQUOTE) {
          error(
            "PUBLIC identifier requires both public ID and system ID literals",
          );
        }
        parseQuotedLiteral();
      } else {
        error(
          `Expected SYSTEM, PUBLIC, or quoted string in ENTITY declaration, got '${
            keyword || input[pos]
          }'`,
        );
      }

      // Check for NDATA declaration (only for general entities, not parameter entities)
      skipWhitespace();
      if (pos < len && input.charCodeAt(pos) !== CC_GT) {
        // Check if we're about to see NDATA
        if (
          pos + 4 < len &&
          input.slice(pos, pos + 5) === "NDATA"
        ) {
          if (isParameterEntity) {
            error("Parameter entities cannot have NDATA declarations");
          }
          pos += 5; // Skip NDATA
          // Must have whitespace after NDATA
          if (pos >= len || !isWhitespace(input.charCodeAt(pos))) {
            error("Missing whitespace after NDATA keyword");
          }
          skipWhitespace();
          // Read notation name
          const notationName = readName();
          if (notationName === "") {
            error("Missing notation name after NDATA");
          }
        } else if (input.charCodeAt(pos) !== CC_GT) {
          // If not NDATA and not '>', check for missing whitespace before NDATA
          // This handles case like "foo.eps"NDATA (missing space)
          const remaining = input.slice(pos, Math.min(pos + 10, len));
          if (remaining.includes("NDATA")) {
            error("Missing whitespace before NDATA keyword");
          }
          error(`Unexpected content '${input[pos]}' in ENTITY declaration`);
        }
      }
    }

    // Skip optional trailing whitespace and expect '>'
    skipWhitespace();
    if (pos >= len || input.charCodeAt(pos) !== CC_GT) {
      error("Unterminated ENTITY declaration");
    }
    pos++; // Skip '>'
  }

  /**
   * Parse a quoted literal (single or double quoted).
   * @param validatePubid If true, validate as PubidLiteral per XML 1.0 §2.3
   */
  function parseQuotedLiteral(validatePubid = false): void {
    const quote = input.charCodeAt(pos);
    if (quote !== CC_DQUOTE && quote !== CC_SQUOTE) {
      error("Expected quoted string");
    }
    const quoteChar = String.fromCharCode(quote);
    pos++;
    const valueStart = pos;
    while (pos < len && input.charCodeAt(pos) !== quote) {
      pos++;
    }
    if (pos >= len) {
      error("Unterminated quoted string");
    }
    // Validate PubidLiteral if requested
    if (validatePubid) {
      validatePubidLiteral(input.slice(valueStart, pos), quoteChar);
    }
    pos++; // Skip closing quote
  }

  /**
   * 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 '.
   */
  function validatePubidLiteral(value: string, quoteChar: 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 === "'" && quoteChar === '"'); // ' only allowed if quoted with "

      if (!isValid) {
        error(
          `Invalid character '${ch}' (U+${
            code.toString(16).toUpperCase().padStart(4, "0")
          }) in public ID literal`,
        );
      }
    }
  }

  /**
   * Parse DTD declaration content with whitespace validation.
   * Validates that quoted strings and parenthesized groups have proper whitespace.
   */
  function parseDTDDeclarationContent(): void {
    let sawWhitespace = true; // Start true since we just saw whitespace after keyword
    let parenDepth = 0;

    while (pos < len) {
      const code = input.charCodeAt(pos);

      if (code === CC_GT && parenDepth === 0) {
        pos++;
        return; // End of declaration
      }

      if (isWhitespace(code)) {
        sawWhitespace = true;
        pos++;
        continue;
      }

      if (code === CC_DQUOTE || code === CC_SQUOTE) {
        // Quoted string - must have whitespace before (unless inside parens)
        if (!sawWhitespace && parenDepth === 0) {
          error("Missing whitespace before quoted string in DTD declaration");
        }
        const quote = code;
        pos++;
        while (pos < len && input.charCodeAt(pos) !== quote) {
          pos++;
        }
        if (pos >= len) {
          error("Unterminated string in DTD declaration");
        }
        pos++; // Skip closing quote
        sawWhitespace = false;
        continue;
      }

      if (code === 40) { // (
        // Opening paren - must have whitespace before FIRST paren only
        // Nested parens like ((a|b)) are valid without whitespace between them
        if (!sawWhitespace && parenDepth === 0) {
          error("Missing whitespace before '(' in DTD declaration");
        }
        parenDepth++;
        sawWhitespace = false;
        pos++;
        continue;
      }

      if (code === 41) { // )
        if (parenDepth === 0) {
          error("Unexpected ')' in DTD declaration");
        }
        parenDepth--;
        sawWhitespace = false;
        pos++;
        continue;
      }

      if (code === 124) { // |
        sawWhitespace = false;
        pos++;
        continue;
      }

      if (code === 44) { // ,
        // Comma is valid in element content models (sequence operator)
        sawWhitespace = false;
        pos++;
        continue;
      }

      if (code === 35) { // #
        // #PCDATA, #IMPLIED, #REQUIRED, #FIXED - must have whitespace before
        if (!sawWhitespace && parenDepth === 0) {
          error("Missing whitespace before '#' in DTD declaration");
        }
        sawWhitespace = false;
        pos++;
        continue;
      }

      if (code === 37) { // %
        // Parameter entity reference
        sawWhitespace = false;
        pos++;
        continue;
      }

      if (code === 59) { // ;
        // End of entity reference
        sawWhitespace = false;
        pos++;
        continue;
      }

      // Name characters
      if (
        (code >= 97 && code <= 122) || // a-z
        (code >= 65 && code <= 90) || // A-Z
        (code >= 48 && code <= 57) || // 0-9
        code === 95 || // _
        code === 58 || // :
        code === 46 || // .
        code === 45 || // -
        (code > 127 && isNameChar(code))
      ) {
        sawWhitespace = false;
        pos++;
        continue;
      }

      if (code === CC_LBRACKET || code === CC_RBRACKET) {
        sawWhitespace = false;
        pos++;
        continue;
      }

      // Content model operators: *, +, ?
      if (code === 42 || code === 43 || code === 63) { // * + ?
        sawWhitespace = false;
        pos++;
        continue;
      }

      error(
        `Unexpected character '${input[pos]}' in DTD declaration`,
      );
    }
    error("Unterminated DTD declaration");
  }

  function readName(): string {
    const start = pos;

    // First character must be NameStartChar
    if (pos < len) {
      const firstCode = input.charCodeAt(pos);
      // Fast ASCII NameStartChar check
      if (
        (firstCode >= 97 && firstCode <= 122) || // a-z
        (firstCode >= 65 && firstCode <= 90) || // A-Z
        firstCode === 95 || // _
        firstCode === 58 // :
      ) {
        pos++;
      } else if (firstCode > 127) {
        // Non-ASCII: use codePointAt for proper surrogate pair handling
        // Astral plane characters (U+10000+) are represented as surrogate pairs
        const codePoint = input.codePointAt(pos)!;
        if (isNameStartChar(codePoint)) {
          // Advance by 1 for BMP chars, 2 for astral plane (surrogate pairs)
          pos += codePoint > 0xFFFF ? 2 : 1;
        } else {
          // Not a valid name start character
          return "";
        }
      } else {
        // Not a valid name start character
        return "";
      }
    }

    // Remaining characters: NameChar
    while (pos < len) {
      const code = input.charCodeAt(pos);
      // Fast ASCII NameChar check (inline for performance)
      if (
        (code >= 97 && code <= 122) || // a-z
        (code >= 65 && code <= 90) || // A-Z
        (code >= 48 && code <= 57) || // 0-9
        code === 95 || // _
        code === 58 || // :
        code === 46 || // .
        code === 45 // -
      ) {
        pos++;
        continue;
      }
      // Non-ASCII: use codePointAt for proper surrogate pair handling
      if (code > 127) {
        const codePoint = input.codePointAt(pos)!;
        if (isNameChar(codePoint)) {
          // Advance by 1 for BMP chars, 2 for astral plane (surrogate pairs)
          pos += codePoint > 0xFFFF ? 2 : 1;
          continue;
        }
      }
      break;
    }
    return input.slice(start, pos);
  }

  function readQuotedValue(): string {
    const quoteCode = input.charCodeAt(pos);
    if (quoteCode !== CC_DQUOTE && quoteCode !== CC_SQUOTE) {
      error("Expected quote to start attribute value");
    }
    const quoteChar = input[pos]!;
    const start = pos + 1;

    const closeIdx = input.indexOf(quoteChar, start);
    if (closeIdx === -1) {
      pos = len;
      error("Unterminated attribute value");
    }

    const raw = input.slice(start, closeIdx);

    // Validate: '<' not allowed in attribute values (XML 1.0 §3.1)
    if (raw.includes("<")) {
      // Find exact position for error reporting
      pos = start + raw.indexOf("<");
      error("'<' not allowed in attribute value");
    }

    pos = closeIdx + 1;

    // Normalize whitespace (§3.3.3) and decode entities
    // Note: Only predefined entities are expanded
    return decodeEntities(raw.replace(/[\t\n]/g, " "));
  }

  function readText(): string {
    const start = pos;
    const idx = input.indexOf("<", pos);
    const end = idx === -1 ? len : idx;

    // XML 1.0 §2.2: Validate characters are legal XML Char
    // Only check C0 control characters (0x00-0x1F) as they're the common issue
    // and checking every character would be too expensive
    for (let i = start; i < end; i++) {
      const code = input.charCodeAt(i);
      if (code < 0x20 && C0_VALID[code] !== 1) {
        pos = i;
        error(
          `Illegal XML character U+${
            code.toString(16).toUpperCase().padStart(4, "0")
          } (XML 1.0 §2.2)`,
        );
      }
    }

    pos = end;

    // Slice text once (reused for ]]> check and entity decoding)
    const text = input.slice(start, end);

    // XML 1.0 §2.4: The literal string "]]>" is not allowed in text content
    // Fast path: only check for ]]> if text contains ']' (rare in real XML)
    // This avoids O(n) indexOf scan per text node which caused O(n²) overall
    if (text.includes("]") && text.includes("]]>")) {
      pos = start + text.indexOf("]]>");
      error("']]>' is not allowed in text content (XML 1.0 §2.4)");
    }

    // Note: Only predefined entities are expanded
    return decodeEntities(text);
  }

  function addNode(node: XmlTextNode | XmlCDataNode | XmlCommentNode): void {
    if (stack.length > 0) {
      stack[stack.length - 1]!.children.push(node);
    }
  }

  // Main parsing loop
  while (pos < len) {
    // Handle text content first (early continue)
    if (input.charCodeAt(pos) !== CC_LT) {
      const textStart = pos;
      const text = readText();
      const textEnd = pos;

      // XML 1.0 §2.8: Prolog and epilog only allow Misc, where:
      // Misc ::= Comment | PI | S
      // S is LITERAL whitespace only, not character/entity references
      const outsideRoot = !root || rootClosed;
      if (outsideRoot) {
        // Check raw text for any entity/character references
        const rawText = input.slice(textStart, textEnd);
        if (rawText.includes("&")) {
          pos = textStart + rawText.indexOf("&");
          error(
            "Character/entity references are not allowed in prolog/epilog (XML 1.0 §2.8)",
          );
        }
        // Check for non-whitespace content
        if (!WHITESPACE_ONLY_RE.test(text)) {
          pos = textStart;
          if (!root) {
            error(
              "Content is not allowed before the root element (XML 1.0 §2.8)",
            );
          } else {
            error(
              "Content is not allowed after the root element (XML 1.0 §2.8)",
            );
          }
        }
      }

      if (!(ignoreWhitespace && WHITESPACE_ONLY_RE.test(text))) {
        addNode({ type: "text", text });
      }
      continue;
    }

    pos++; // Skip '<'

    if (pos >= len) {
      error("Unexpected end of input after '<'");
    }

    const code = input.charCodeAt(pos);

    // End tag: </name>
    if (code === CC_SLASH) {
      pos++; // Skip '/'
      const name = readName();
      if (name === "") {
        error("Invalid character in end tag name");
      }
      skipWhitespace();
      if (input.charCodeAt(pos) !== CC_GT) {
        error("Expected '>' in end tag");
      }
      pos++; // Skip '>'

      const expected = stack.pop();
      if (!expected) {
        error(`Unexpected closing tag </${name}>`);
      }

      // Compare raw strings directly - equivalent to comparing prefix+local
      // since XmlName.raw preserves the exact input to parseName()
      if (expected.name.raw !== name) {
        error(
          `Mismatched closing tag: expected </${expected.name.raw}> but found </${name}>`,
        );
      }

      // Restore namespace bindings from this element's scope
      const elementBindings = nsStack.pop();
      if (elementBindings && ns.bindings) {
        const bindings = ns.bindings; // Capture for TypeScript narrowing
        for (const [prefix, previousUri] of elementBindings) {
          if (previousUri === undefined) {
            bindings.delete(prefix);
          } else {
            bindings.set(prefix, previousUri);
          }
        }
      }

      // Track when root element closes
      if (stack.length === 0 && root) {
        rootClosed = true;
      }
      continue;
    }

    // Comment, CDATA, or DOCTYPE
    if (code === CC_BANG) {
      pos++; // Skip '!'

      // Comment: <!--...-->
      if (
        pos + 1 < len &&
        input.charCodeAt(pos) === CC_DASH &&
        input.charCodeAt(pos + 1) === CC_DASH
      ) {
        pos += 2; // Skip '--'
        const start = pos;

        const endIdx = input.indexOf("-->", pos);
        if (endIdx === -1) errorUnterminated("Unterminated comment");

        const content = input.slice(start, endIdx);
        // XML 1.0 §2.5: "--" is not permitted within comments
        // Also, a single "-" cannot appear immediately before "-->"
        // (grammar: Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->')
        if (content.includes("--")) {
          pos = start + content.indexOf("--");
          error("'--' is not permitted within comments (XML 1.0 §2.5)");
        }
        // Check trailing dash before --> (e.g., "<!--->" or "<!-- comment --->")
        if (
          content.length > 0 &&
          content.charCodeAt(content.length - 1) === CC_DASH
        ) {
          pos = endIdx - 1; // Point to the trailing dash
          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 = start; i < endIdx; i++) {
          const charCode = input.charCodeAt(i);
          if (charCode < 0x20 && C0_VALID[charCode] !== 1) {
            pos = i;
            error(
              `Illegal XML character U+${
                charCode.toString(16).toUpperCase().padStart(4, "0")
              } (XML 1.0 §2.2)`,
            );
          }
        }

        if (!ignoreComments) {
          addNode({ type: "comment", text: content });
        }
        pos = endIdx + 3;
        continue;
      }

      // CDATA: <![CDATA[...]]>
      if (pos + 6 < len && input.slice(pos, pos + 7) === "[CDATA[") {
        // XML 1.0 §2.8: CDATA sections are only allowed within elements
        if (!root) {
          pos -= 2; // Point back to '<!'
          error(
            "CDATA section is not allowed before the root element (XML 1.0 §2.8)",
          );
        }
        if (rootClosed) {
          pos -= 2; // Point back to '<!'
          error(
            "CDATA section is not allowed after the root element (XML 1.0 §2.8)",
          );
        }

        pos += 7; // Skip '[CDATA['
        const start = pos;

        const endIdx = input.indexOf("]]>", pos);
        if (endIdx === -1) errorUnterminated("Unterminated CDATA section");

        // XML 1.0 §2.2: Validate characters are legal XML Char
        for (let i = start; i < endIdx; i++) {
          const charCode = input.charCodeAt(i);
          if (charCode < 0x20 && C0_VALID[charCode] !== 1) {
            pos = i;
            error(
              `Illegal XML character U+${
                charCode.toString(16).toUpperCase().padStart(4, "0")
              } (XML 1.0 §2.2)`,
            );
          }
        }

        addNode({ type: "cdata", text: input.slice(start, endIdx) });
        pos = endIdx + 3;
        continue;
      }

      // DOCTYPE: <!DOCTYPE...>
      if (pos + 6 < len && input.slice(pos, pos + 7) === "DOCTYPE") {
        pos += 7; // Skip 'DOCTYPE'

        // Skip whitespace before name (required)
        const wsBeforeName = pos;
        while (pos < len && isWhitespace(input.charCodeAt(pos))) pos++;
        if (pos === wsBeforeName) {
          error("Expected whitespace after DOCTYPE");
        }

        // Read DOCTYPE name (required)
        const nameStart = pos;
        while (pos < len) {
          const dc = input.charCodeAt(pos);
          if (isWhitespace(dc) || dc === CC_GT || dc === CC_LBRACKET) break;
          pos++;
        }
        if (pos === nameStart) {
          error("Missing name in DOCTYPE declaration");
        }

        // Skip whitespace and handle PUBLIC/SYSTEM or internal subset
        let expectPubidLiteral = false;
        let sawExternalIdKeyword = false; // Track if we've seen PUBLIC or SYSTEM
        while (pos < len && input.charCodeAt(pos) !== CC_GT) {
          const dc = input.charCodeAt(pos);

          if (isWhitespace(dc)) {
            pos++;
          } else if (dc === CC_LBRACKET) {
            // Internal subset - parse with validation
            pos++;
            parseDTDInternalSubset();
            expectPubidLiteral = false;
            sawExternalIdKeyword = false;
          } else if (dc === CC_DQUOTE || dc === CC_SQUOTE) {
            // Quoted string (public/system ID) - only allowed after PUBLIC/SYSTEM
            if (!sawExternalIdKeyword) {
              error(
                "Unexpected quoted string in DOCTYPE - expected PUBLIC or SYSTEM",
              );
            }
            const quote = dc;
            const quoteChar = String.fromCharCode(quote);
            pos++;
            const valueStart = pos;
            while (pos < len && input.charCodeAt(pos) !== quote) pos++;
            if (pos >= len) {
              error("Unterminated quoted string in DOCTYPE");
            }
            // Validate PubidLiteral if this is a PUBLIC ID
            if (expectPubidLiteral) {
              validatePubidLiteral(input.slice(valueStart, pos), quoteChar);
              expectPubidLiteral = false;
            }
            pos++; // Skip closing quote
          } else if (
            input.slice(pos, pos + 6) === "PUBLIC" &&
            (pos + 6 >= len || isWhitespace(input.charCodeAt(pos + 6)))
          ) {
            pos += 6;
            expectPubidLiteral = true;
            sawExternalIdKeyword = true;
          } else if (
            input.slice(pos, pos + 6) === "SYSTEM" &&
            (pos + 6 >= len || isWhitespace(input.charCodeAt(pos + 6)))
          ) {
            pos += 6;
            // SystemLiteral follows, but we don't need to validate it
            sawExternalIdKeyword = true;
          } else if (
            input.slice(pos, pos + 6).toUpperCase() === "PUBLIC" &&
            (pos + 6 >= len || isWhitespace(input.charCodeAt(pos + 6)))
          ) {
            // Case-insensitive match but wrong case
            error(
              `'${input.slice(pos, pos + 6)}' must be uppercase 'PUBLIC'`,
            );
          } else if (
            input.slice(pos, pos + 6).toUpperCase() === "SYSTEM" &&
            (pos + 6 >= len || isWhitespace(input.charCodeAt(pos + 6)))
          ) {
            // Case-insensitive match but wrong case
            error(
              `'${input.slice(pos, pos + 6)}' must be uppercase 'SYSTEM'`,
            );
          } else {
            // Other content
            pos++;
          }
        }
        if (pos < len) pos++; // Skip '>'
        continue;
      }

      error("Unsupported markup declaration");
    }

    // Processing instruction or XML declaration: <?target content?>
    if (code === CC_QUESTION) {
      // Save position of '<' for XML declaration position check
      // pos is currently pointing at '?', so '<' was at pos-1
      const ltPos = pos - 1;
      pos++; // Skip '?'
      const target = readName();
      if (target === "") {
        error("Invalid character in processing instruction target");
      }

      // XML Namespaces §3: PI targets must not contain colons
      if (target.includes(":")) {
        pos = ltPos + 2; // Point to start of target
        error(
          "Processing instruction target must not contain ':' (Namespaces §3)",
        );
      }

      // XML 1.0 §2.6: After PI target, must be whitespace, '?', or end
      // This catches invalid targets like "pitarget+++" where '+' is not a NameChar
      if (pos < len) {
        const afterTargetCode = input.charCodeAt(pos);
        if (
          afterTargetCode !== CC_QUESTION && // Not ?
          !isWhitespace(afterTargetCode) // Not whitespace
        ) {
          error(
            `Unexpected character '${
              String.fromCharCode(afterTargetCode)
            }' in processing instruction target`,
          );
        }
      }

      const contentStart = pos;

      const endIdx = input.indexOf("?>", pos);
      if (endIdx === -1) {
        errorUnterminated("Unterminated processing instruction");
      }

      // XML 1.0 §2.2: Validate characters in PI content are legal XML Char
      for (let i = contentStart; i < endIdx; i++) {
        const charCode = input.charCodeAt(i);
        if (charCode < 0x20 && C0_VALID[charCode] !== 1) {
          pos = i;
          error(
            `Illegal XML character U+${
              charCode.toString(16).toUpperCase().padStart(4, "0")
            } in processing instruction (XML 1.0 §2.2)`,
          );
        }
      }

      const content = input.slice(contentStart, endIdx).trim();
      pos = endIdx + 2;

      // XML 1.0 §2.6: PI targets that are case-variants of "xml" are reserved
      // Only exact lowercase "xml" is valid for XML declaration
      if (target === "xml") {
        // XML 1.0 §2.8: XML declaration must be at the very beginning
        // (only a UTF BOM may precede it)
        if (ltPos !== 0 && !(ltPos === 1 && input.charCodeAt(0) === 0xFEFF)) {
          pos = ltPos;
          error(
            "XML declaration must appear at the start of the document (XML 1.0 §2.8)",
          );
        }

        // Validate XML declaration syntax strictly
        const result = validateXmlDeclaration(content);
        if (!result.valid) {
          pos = ltPos;
          error(result.error);
        }

        declaration = {
          type: "declaration",
          version: result.version,
          line: trackPosition ? 1 : 0,
          column: trackPosition ? 1 : 0,
          offset: 0,
          ...(result.encoding !== undefined && { encoding: result.encoding }),
          ...(result.standalone !== undefined && {
            standalone: result.standalone,
          }),
        };
      } else if (isReservedPiTarget(target)) {
        // XML 1.0 §2.6: "xml" in any case variation is reserved
        pos = ltPos;
        error(
          `Processing instruction target '${target}' is reserved; 'xml' must be lowercase (XML 1.0 §2.6)`,
        );
      }
      // Other PIs are ignored for tree building
      continue;
    }

    // Start tag: <name attributes...> or <name attributes.../>
    const name = readName();
    if (name === "") {
      error(`Unexpected character '${String.fromCharCode(code)}' after '<'`);
    }

    // Validate QName syntax (Namespaces §3)
    const colonIndex = name.indexOf(":");
    const qnameError = validateQName(name, colonIndex);
    if (qnameError) {
      pos -= name.length;
      error(`Invalid element name '${name}': ${qnameError}`);
    }

    // Elements cannot use xmlns prefix (Namespaces 1.0 errata NE08)
    if (colonIndex !== -1 && name.slice(0, colonIndex) === "xmlns") {
      pos -= name.length;
      error("Element name cannot use the 'xmlns' prefix");
    }

    // XML 1.0 §2.8: Only one root element is allowed
    if (rootClosed) {
      pos -= name.length + 1; // Point back to '<'
      error("Only one root element is allowed (XML 1.0 §2.8)");
    }

    // Note: elementName is created after namespace processing below,
    // so we can include the resolved URI
    const attributes: Record<string, string> = {};
    let selfClosing = false;

    // Read attributes
    // Track if we need whitespace before the next attribute
    let needsWhitespace = false;

    while (true) {
      const posBeforeWs = pos;
      skipWhitespace();
      const sawWhitespace = pos > posBeforeWs;

      if (pos >= len) {
        error("Unexpected end of input in start tag");
      }

      const chCode = input.charCodeAt(pos);

      if (chCode === CC_GT) {
        pos++; // Skip '>'
        break;
      }

      if (chCode === CC_SLASH) {
        pos++; // Skip '/'
        if (input.charCodeAt(pos) !== CC_GT) {
          error("Expected '>' after '/' in self-closing tag");
        }
        pos++; // Skip '>'
        selfClosing = true;
        break;
      }

      // XML 1.0 §3.1: Whitespace is required between attributes
      if (needsWhitespace && !sawWhitespace) {
        error("Whitespace is required between attributes");
      }

      // Read attribute
      const attrName = readName();
      if (attrName === "") {
        error(
          `Unexpected character '${String.fromCharCode(chCode)}' in start tag`,
        );
      }

      // Validate QName syntax for attribute name (Namespaces §3)
      const attrColonIndex = attrName.indexOf(":");
      const attrQnameError = validateQName(attrName, attrColonIndex);
      if (attrQnameError) {
        pos -= attrName.length;
        error(`Invalid attribute name '${attrName}': ${attrQnameError}`);
      }

      skipWhitespace();
      if (input.charCodeAt(pos) !== CC_EQ) {
        error("Expected '=' after attribute name");
      }
      pos++; // Skip '='
      skipWhitespace();

      const attrValue = readQuotedValue();

      // Validate namespace binding if this is an xmlns attribute
      if (attrName === "xmlns" || attrName.startsWith("xmlns:")) {
        const nsError = validateNamespaceBinding(attrName, attrValue);
        if (nsError) {
          error(nsError);
        }
      }

      // XML 1.0 §3.1: Attribute names must be unique within a start-tag
      // Use full attribute name (with prefix) for duplicate detection to correctly
      // handle namespace-prefixed attributes like a:attr vs b:attr
      if (Object.hasOwn(attributes, attrName)) {
        error(`Duplicate attribute '${attrName}'`);
      }
      attributes[attrName] = attrValue;

      // After reading an attribute, whitespace is required before next attribute
      needsWhitespace = true;
    }

    // Process namespace declarations and validate prefix bindings
    // This must happen after all attributes are read
    const elementBindings: Array<[string, string | undefined]> = [];

    // First pass: collect namespace declarations from this element
    for (const attrName in attributes) {
      if (attrName === "xmlns") {
        // Default namespace - we don't track this for prefix validation
        continue;
      }
      if (attrName.startsWith("xmlns:")) {
        const prefix = attrName.slice(6); // After "xmlns:"
        const uri = attributes[attrName]!;
        const bindings = getNsBindings();
        // Save previous binding for restoration
        elementBindings.push([prefix, bindings.get(prefix)]);
        bindings.set(prefix, uri);
      }
    }

    // Push element's namespace scope (for restoration on close)
    if (!selfClosing) {
      // Use shared empty array to avoid allocation when no bindings
      nsStack.push(
        elementBindings.length > 0 ? elementBindings : EMPTY_NS_SCOPE,
      );
    }

    // Validate element prefix is bound (if it has one) and resolve URI
    let elementUri: string | undefined;
    if (colonIndex !== -1) {
      const prefix = name.slice(0, colonIndex);
      // xml prefix is always implicitly bound, xmlns prefix is handled separately
      if (prefix !== "xml" && prefix !== "xmlns") {
        if (!ns.bindings?.has(prefix)) {
          pos -= name.length;
          error(`Unbound namespace prefix '${prefix}' in element <${name}>`);
        }
        elementUri = ns.bindings!.get(prefix);
      } else if (prefix === "xml") {
        elementUri = XML_NAMESPACE;
      }
    }

    // Now create the element name with resolved URI
    const elementName = parseName(name, elementUri);

    // Validate attribute prefixes are bound and check for duplicate expanded names
    // Optimized: only do expensive expansion check when same local name appears with different prefixes
    let localNameToPrefixes: Map<string, string[]> | null = null;

    for (const attrName in attributes) {
      const attrColonIdx = attrName.indexOf(":");
      if (attrColonIdx !== -1) {
        const prefix = attrName.slice(0, attrColonIdx);
        // Skip xmlns: attributes (they declare, not use, prefixes)
        // xml prefix is always implicitly bound
        if (prefix !== "xmlns" && prefix !== "xml") {
          if (!ns.bindings?.has(prefix)) {
            error(
              `Unbound namespace prefix '${prefix}' in attribute '${attrName}'`,
            );
          }
          // Track local names for duplicate expanded name detection
          const localName = attrName.slice(attrColonIdx + 1);
          if (!localNameToPrefixes) {
            localNameToPrefixes = new Map();
          }
          const prefixes = localNameToPrefixes.get(localName);
          if (prefixes) {
            prefixes.push(prefix);
          } else {
            localNameToPrefixes.set(localName, [prefix]);
          }
        }
      }
    }

    // Check for duplicate expanded attribute names (Namespaces §6.3)
    // Only when same local name appears with multiple prefixes
    if (localNameToPrefixes && ns.bindings) {
      const bindings = ns.bindings; // Capture for TypeScript narrowing
      for (const [localName, prefixes] of localNameToPrefixes) {
        if (prefixes.length > 1) {
          // Multiple prefixes for same local name - check if any resolve to same URI
          const seenUris = new Set<string>();
          for (const prefix of prefixes) {
            const uri = bindings.get(prefix)!;
            if (seenUris.has(uri)) {
              error(
                `Duplicate expanded attribute name '{${uri}}${localName}'`,
              );
            }
            seenUris.add(uri);
          }
        }
      }
    }

    // Create element
    const element: MutableElement = {
      type: "element",
      name: elementName,
      attributes,
      children: [],
    };

    if (stack.length > 0) {
      stack[stack.length - 1]!.children.push(element as XmlElement);
    } else if (!root) {
      root = element;
    }

    // Only push non-self-closing elements to stack
    if (!selfClosing) {
      stack.push(element);
    } else if (stack.length === 0 && root === element) {
      // Self-closing root element
      rootClosed = true;
    }

    // For self-closing elements, restore namespace bindings immediately
    if (selfClosing && elementBindings.length > 0) {
      for (const [prefix, previousUri] of elementBindings) {
        if (previousUri === undefined) {
          ns.bindings!.delete(prefix);
        } else {
          ns.bindings!.set(prefix, previousUri);
        }
      }
    }
  }

  // Check for unclosed elements
  if (stack.length > 0) {
    error(`Unclosed element <${stack[stack.length - 1]!.name.raw}>`);
  }

  if (!root) {
    throw new XmlSyntaxError(
      "No root element found in XML document",
      trackPosition
        ? { line: 1, column: 1, offset: 0 }
        : { line: 0, column: 0, offset: 0 },
    );
  }

  return {
    ...(declaration !== undefined && { declaration }),
    root: root as XmlElement,
  };
}