oxml 0.0.11

A pure Rust XML toolkit with zero unsafe code: parsing, an ergonomic tree, and XPath
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 oxml. All rights reserved.

//! The parser: XML text in, [`Document`] out.
//!
//! A single forward pass over the input, byte-oriented on the hot
//! paths and `char`-aware only where XML actually requires it (name
//! characters). No backtracking, no intermediate token vector — the
//! tree is built directly as the scan proceeds.

use alloc::borrow::{Cow, ToOwned};
use alloc::boxed::Box;
use alloc::collections::BTreeSet;
use alloc::string::String;
use alloc::vec::Vec;

use crate::error::{Error, ErrorKind, Result};
use crate::limits::Limits;
use crate::tree::{Chars, Document, ExpandedName, NameId, NodeData, NodeId};
use crate::xml::is_xml_char_for;
pub(crate) use crate::xml::{
    Version, is_literal_char_for, is_name_char, is_name_start,
};

/// Namespace bindings in scope, as a stack of (prefix, uri) frames.
///
/// A `Vec` searched backwards rather than a map: scopes are tiny in
/// practice (a handful of bindings), and this keeps push/pop free of
/// allocation and hashing on the hot path.
#[derive(Debug, Default, Clone)]
pub(crate) struct Namespaces {
    bindings: Vec<(String, String)>,
    marks: Vec<usize>,
    /// One id per binding, parallel to `bindings`, each greater than
    /// every id handed out before it.
    ids: Vec<u64>,
    next_id: u64,
}

impl Namespaces {
    fn push_scope(&mut self) {
        self.marks.push(self.bindings.len());
    }

    pub(crate) fn pop_scope(&mut self) {
        if let Some(mark) = self.marks.pop() {
            self.bindings.truncate(mark);
            self.ids.truncate(mark);
        }
    }

    fn bind(&mut self, prefix: String, uri: String) {
        self.next_id += 1;
        self.bindings.push((prefix, uri));
        self.ids.push(self.next_id);
    }

    /// An id that identifies the whole stack of bindings in force.
    ///
    /// Bindings form a stack and ids only ever grow, so two moments
    /// with the same innermost id have the same stack beneath it:
    /// everything under a binding was pushed before it and cannot
    /// change while it is live. That makes the innermost id a sound
    /// key for anything that depends on the full scope, at the cost
    /// of one integer rather than a clone of the stack.
    fn scope_id(&self) -> u64 {
        self.ids.last().copied().unwrap_or(0)
    }

    /// How many bindings and scopes are open, for [`Self::truncate_to`].
    fn depths(&self) -> (usize, usize) {
        (self.bindings.len(), self.marks.len())
    }

    /// Discard every binding and scope pushed since [`Self::depths`]
    /// reported these counts.
    fn truncate_to(&mut self, bindings: usize, marks: usize) {
        self.bindings.truncate(bindings);
        self.ids.truncate(bindings);
        self.marks.truncate(marks);
    }

    fn resolve(&self, prefix: &str) -> Option<&str> {
        self.bindings
            .iter()
            .rev()
            .find(|(p, _)| p == prefix)
            .map(|(_, u)| u.as_str())
    }
}

/// The attribute names an element has declared so far, for the
/// `WFC: Unique Att Spec` check.
///
/// Comparison is by *expanded* name (namespace and local part), never
/// by id: `p:a` and `q:a` with both prefixes bound to one namespace are
/// the same attribute however they are spelled. A linear scan over the
/// earlier names costs O(n²) string comparisons per element, which is
/// the shape of RUSTSEC-2026-0194; past a handful of attributes the
/// names go into a set instead.
#[derive(Default)]
struct SeenAttributes {
    /// The first few, compared by a scan. An array rather than a
    /// `Vec`: the parse is held to half an allocation per node, and a
    /// `Vec` here would spend one on every element with an attribute.
    linear: [u32; Self::LINEAR],
    len: usize,
    /// Every name once the element is wide, by expanded name.
    wide: Option<BTreeSet<(Option<String>, String)>>,
}

impl SeenAttributes {
    /// Attributes an element may carry before the set is worth its
    /// allocations.
    const LINEAR: usize = 16;

    /// Record `name`; `false` if an attribute with the same expanded
    /// name was already recorded. `names` resolves ids to names.
    fn insert(&mut self, name: NameId, names: &[ExpandedName]) -> bool {
        let expanded = &names[name.0 as usize];
        if let Some(set) = self.wide.as_mut() {
            return set.insert(Self::key(expanded));
        }
        let seen = &self.linear[..self.len];
        if seen.iter().any(|n| names[*n as usize] == *expanded) {
            return false;
        }
        if self.len < Self::LINEAR {
            self.linear[self.len] = name.0;
            self.len += 1;
        } else {
            self.widen(expanded, names);
        }
        true
    }

    /// The element is wide: move the names seen so far into a set.
    fn widen(&mut self, latest: &ExpandedName, names: &[ExpandedName]) {
        let mut set: BTreeSet<_> = self.linear[..self.len]
            .iter()
            .map(|n| Self::key(&names[*n as usize]))
            .collect();
        let _ = set.insert(Self::key(latest));
        self.wide = Some(set);
    }

    fn key(name: &ExpandedName) -> (Option<String>, String) {
        (name.namespace.clone(), name.local.clone())
    }
}

/// How many arena slots to reserve before parsing `input`.
///
/// Every element, comment and processing instruction begins with `<`
/// and text nodes are bounded by them, so twice the count of `<` is a
/// good guess that saves the reallocate-and-copy as the tree grows.
/// It is a guess about a document that has not been checked yet,
/// though: 4 MB of `<` bytes would reserve 450 MB before the first
/// limit was consulted, so the reservation is capped by `max_nodes`
/// and by a fixed ceiling, and the `Vec` grows past it if a document
/// genuinely needs more.
fn arena_capacity(input: &str, limits: &Limits) -> usize {
    const CEILING: usize = 1 << 20;
    let guess = input.bytes().filter(|b| *b == b'<').count() * 2;
    let cap = limits.max_nodes.map_or(CEILING, |n| n.min(CEILING));
    guess.min(cap)
}

const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";

/// The prefix an attribute declares, if it is a namespace
/// declaration: `""` for `xmlns`, `p` for `xmlns:p`, `None` otherwise.
fn declared_prefix(name: &str) -> Option<&str> {
    if name == "xmlns" {
        Some("")
    } else {
        name.strip_prefix("xmlns:")
    }
}

/// Namespaces in XML, sections 3 and 6: what a declaration may bind.
///
/// `xml` may be bound only to the XML namespace and nothing else may
/// be bound to it; `xmlns` may not be declared at all; the `xmlns`
/// namespace may not be bound by anyone. The default declaration was
/// once checked against neither reserved URI, so
/// `xmlns="http://www.w3.org/XML/1998/namespace"` went through.
fn check_declaration(
    name: &str,
    prefix: &str,
    value: &str,
    version: Version,
) -> core::result::Result<(), ErrorKind> {
    if value == XMLNS_NS || (prefix != "xml" && value == XML_NS) {
        return Err(ErrorKind::ReservedNamespace);
    }
    // `xmlns:` with nothing after it parses as a name, but
    // `PrefixedAttName ::= 'xmlns:' NCName` needs a prefix to declare.
    if prefix.is_empty() {
        return if name == "xmlns" {
            Ok(())
        } else {
            Err(ErrorKind::ReservedNamespace)
        };
    }
    check_prefix_declaration(prefix, value, version)
}

/// The rules that apply to `xmlns:prefix` and not to `xmlns`.
fn check_prefix_declaration(
    prefix: &str,
    value: &str,
    version: Version,
) -> core::result::Result<(), ErrorKind> {
    let malformed = prefix == "xmlns" || prefix.contains(':');
    let xml_rebound = prefix == "xml" && value != XML_NS;
    // Undeclaring a prefix -- binding it to the empty string -- is
    // XML 1.1 only. In a 1.0 document it is an error, not a no-op,
    // and treating it as one silently changed which namespace the
    // element was in.
    let undeclared_in_10 = value.is_empty() && version == Version::V10;
    if malformed || xml_rebound || undeclared_in_10 {
        return Err(ErrorKind::ReservedNamespace);
    }
    Ok(())
}

pub(crate) struct Parser<'a> {
    pub(crate) input: &'a str,
    pub(crate) bytes: &'a [u8],
    pub(crate) pos: usize,
    /// Boxed so the streaming reader can lend it to a parser per event
    /// by moving a pointer.
    pub(crate) doc: Box<Document>,
    pub(crate) ns: Namespaces,
    /// How many elements are currently open. Bounded by
    /// [`Limits::max_depth`] so the recursion cannot exhaust the stack.
    pub(crate) depth: usize,
    /// Resource bounds for this parse.
    pub(crate) limits: Limits,
    /// Declarations from the document type declaration, once seen.
    pub(crate) dtd: Option<crate::dtd::Dtd>,
    /// The version the XML declaration names.
    ///
    /// 1.1 differs from 1.0 in three ways that matter here: NEL and
    /// LINE SEPARATOR normalise to LF, C1 controls must be escaped
    /// rather than appearing literally, and the `Char` production
    /// admits C0 controls when written as character references.
    pub(crate) version: Version,
    /// Element names seen so far, keyed on the local part.
    ///
    /// Keyed on the local part rather than the whole name so that a
    /// document with many distinct names does not degrade to a linear
    /// scan of the table; the few sharing a local part are compared on
    /// their namespace.
    pub(crate) name_index: alloc::collections::BTreeMap<String, Vec<u32>>,
    /// Where external content comes from, if anywhere.
    ///
    /// Never a file or a socket: the caller supplies it, so the parser
    /// performs no I/O whatever this is.
    pub(crate) external: &'a dyn crate::external::ExternalSource,
    /// Characters of entity expansion still permitted **for the whole
    /// document**.
    ///
    /// Per-document rather than per-reference. A per-reference budget
    /// bounds the exponential billion-laughs shape but not the
    /// quadratic one: referencing a single 100 KB entity a thousand
    /// times at depth one produced 100 MB from 100 KB of input while
    /// every individual expansion stayed within its allowance.
    pub(crate) entity_budget: usize,
    /// How many entity replacement texts are being parsed above this
    /// one, so a self-referential entity terminates.
    pub(crate) entity_depth: usize,
    /// Whether the document said `standalone="yes"`.
    ///
    /// When it did, an entity declared outside the internal subset may
    /// not be referenced: the document promised it needs nothing from
    /// out there.
    pub(crate) standalone: bool,
    /// Validated entity replacement texts, keyed by entity name and
    /// the namespace scope in force when referenced.
    ///
    /// The scope is the id of the innermost binding (see
    /// [`Namespaces::scope_id`]). Keying on a clone of the whole
    /// binding stack cost a `Vec<(String, String)>` per reference:
    /// 20,000 references under 800 bindings took 711 ms, and nothing
    /// in `Limits` bounded it.
    pub(crate) entity_cache: BTreeSet<(String, u64)>,
}

/// Parse an XML document.
///
/// # Errors
///
/// Returns [`Error`] if the input is not well-formed, or uses a
/// namespace prefix that was never declared.
pub fn parse(input: &str) -> Result<Document> {
    parse_with(input, Limits::default())
}

/// Parse an XML document from bytes.
///
/// Prefer [`parse`] when you already have a `&str`: it avoids encoding
/// detection and transcoding. Both entry points return an owned document.
///
/// # Errors
///
/// As [`parse`], and additionally if the bytes are not valid in their
/// declared encoding.
pub fn parse_bytes(input: &[u8]) -> Result<Document> {
    parse_bytes_with(input, Limits::default())
}

/// Parse from bytes, decoding the encoding the document declares,
/// under explicit resource bounds.
///
/// A byte-order mark wins, then the `encoding` pseudo-attribute of the
/// XML declaration, then UTF-8. UTF-8 decoding borrows the source;
/// constructing the document still copies its normalized text.
///
/// # Errors
///
/// As [`parse_with`], and additionally if the bytes are not valid in
/// their declared encoding or that encoding is not supported.
pub fn parse_bytes_with(input: &[u8], limits: Limits) -> Result<Document> {
    limits.check_input(input.len())?;
    let text =
        crate::encoding::decode_bounded(input, limits.max_document_bytes)?;
    parse_decoded(&text, limits, &crate::external::NoExternal)
}

/// Parse an XML document under explicit resource bounds.
///
/// Use this for input from an untrusted source, where the defaults may
/// be more generous than you want. See [`Limits`].
///
/// # Errors
///
/// Returns [`Error`] if the input is not well-formed, uses an
/// undeclared namespace prefix, contains a character the `Char`
/// production forbids, or exceeds one of `limits`. Each bound has its
/// own [`ErrorKind`], so a caller can tell which one was hit.
pub fn parse_with(input: &str, limits: Limits) -> Result<Document> {
    parse_with_external(input, limits, &crate::external::NoExternal)
}

/// Parse with external content the caller supplies.
///
/// oxml never performs I/O, so a document that names an external entity
/// or subset gets nothing unless the caller provides it. With a source,
/// the same parse can also check the rules only the external content
/// can settle -- chiefly that a text declaration is well formed, names
/// an encoding, and does not claim a version later than the document's.
///
/// # Errors
///
/// Returns [`Error`] if the input is not well-formed, or if content the
/// source supplies is not.
pub fn parse_with_external(
    input: &str,
    limits: Limits,
    external: &dyn crate::external::ExternalSource,
) -> Result<Document> {
    limits.check_input(input.len())?;
    parse_decoded(input, limits, external)
}

fn parse_decoded(
    input: &str,
    limits: Limits,
    external: &dyn crate::external::ExternalSource,
) -> Result<Document> {
    limits.check_document(input.len(), 0)?;
    #[cfg(feature = "tracing")]
    let _span =
        tracing::trace_span!("oxml.parse", input_len = input.len()).entered();

    // End-of-line normalisation happens before anything else, because
    // the specification defines it as something the processor behaves
    // as though it had done "on input, before parsing". Doing it later
    // means every rule that inspects whitespace has to know about it,
    // and the thirteenth such rule is the one that forgets.
    let version = declared_version(input)?;
    // The document owns its text, because text nodes, comments and
    // attribute values are ranges into it rather than strings of their
    // own. That costs one copy of the input for a document whose line
    // endings needed no rewriting -- against one allocation per text
    // node and per attribute value, which is what it replaces.
    //
    // The ranges are recorded against exactly this buffer, and moving
    // a `String` does not move the bytes it points at, so handing it
    // to the document afterwards leaves every range valid.
    let text = normalize_line_endings(input, version).into_owned();
    let mut doc = parse_normalized(&text, limits, version, external)?;
    let whole = text.len();
    doc.input = text;
    let root = doc.root();
    doc.set_span(root, 0, whole);
    Ok(doc)
}

/// Everything that happens to a document before any of it is scanned.
///
/// The version it declares, its line endings normalised, and the
/// `Char` production checked over the whole input. Shared with
/// [`crate::stream::Reader`] so a streaming caller cannot be given a
/// document the tree parser would have refused.
///
/// Returns owned text because normalisation may rewrite it, and a
/// reader that borrowed the caller's string could not hold the
/// rewritten form.
///
/// # Errors
///
/// Returns [`Error`] if the declaration is malformed or a character is
/// one XML forbids.
pub(crate) fn prepare(
    input: &str,
    limits: Limits,
) -> Result<(String, Version)> {
    limits.check_input(input.len())?;
    limits.check_document(input.len(), 0)?;
    let version = declared_version(input)?;
    let text = normalize_line_endings(input, version).into_owned();
    check_prolog_shape(&text)?;
    check_characters(&text, version, 0)?;
    Ok((text, version))
}

/// A character-data run being accumulated.
///
/// Almost every text node in almost every document is exactly a slice
/// of the input: no references, no `CDATA`, nothing merged. That case
/// must not allocate, so a run remembers where it started and only
/// materialises a `String` when something forces it to -- an entity
/// expanded, or a second piece that is not contiguous with the first.
#[derive(Debug, Default)]
pub(crate) struct Run {
    /// Where the verbatim part starts in the input.
    start: usize,
    /// How much of the input it covers.
    len: usize,
    /// Set once the run stopped being expressible as a slice.
    owned: Option<String>,
}

impl Run {
    /// Add a piece that *is* a slice of the input, at `at`.
    pub(crate) fn push_slice(&mut self, at: usize, text: &str, input: &str) {
        if let Some(owned) = &mut self.owned {
            owned.push_str(text);
        } else if self.len == 0 {
            self.start = at;
            self.len = text.len();
        } else if self.start + self.len == at {
            // Contiguous with what is already here, so the two are one
            // slice and the run is still free.
            self.len += text.len();
        } else {
            // A gap -- a `CDATA` delimiter, most likely. From here the
            // run is no longer a range into anything.
            self.push_owned(text, input);
        }
    }

    /// Add a piece the input does not contain, such as an expansion.
    pub(crate) fn push_owned(&mut self, text: &str, input: &str) {
        if let Some(owned) = &mut self.owned {
            owned.push_str(text);
            return;
        }
        let mut buffer = String::with_capacity(self.len + text.len());
        buffer.push_str(
            input
                .get(self.start..self.start + self.len)
                .unwrap_or_default(),
        );
        buffer.push_str(text);
        self.owned = Some(buffer);
    }

    /// The run's text, borrowed from wherever it lives.
    pub(crate) fn as_str<'a>(&'a self, input: &'a str) -> &'a str {
        self.owned.as_deref().unwrap_or_else(|| {
            input
                .get(self.start..self.start + self.len)
                .unwrap_or_default()
        })
    }

    /// How many bytes the run holds, for the length limit.
    pub(crate) fn len(&self) -> usize {
        self.owned.as_ref().map_or(self.len, String::len)
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Where the run sits in the input, if it is still a slice.
    pub(crate) fn as_span(&self) -> Option<(usize, usize)> {
        if self.owned.is_some() {
            None
        } else {
            Some((self.start, self.len))
        }
    }
}

/// Every character in `text` must be one the version permits.
///
/// `base` is added to the reported offset, so a reader working
/// through a document a buffer at a time can point at the document
/// rather than at its window on it.
pub(crate) fn check_characters(
    text: &str,
    version: Version,
    base: usize,
) -> Result<()> {
    if let Some((offset, c)) = text
        .char_indices()
        .find(|(_, c)| !is_literal_char_for(*c, version))
    {
        return Err(Error::new(ErrorKind::IllegalCharacter(c), base + offset));
    }
    Ok(())
}

/// Whitespace before an XML declaration is a malformed document, not
/// `Misc` appearing early.
///
/// Whitespace is XML's `S`, not Rust's: `trim_start` also took a form
/// feed, so ` \x0c<?xml ...?>` was a misplaced declaration in memory
/// and an illegal character to the streaming reader, whose prelude
/// decides there is no declaration once the bytes after the leading
/// `S` stop matching `<?xml`.
pub(crate) fn check_prolog_shape(input: &str) -> Result<()> {
    let trimmed = input.trim_start_matches([' ', '\t', '\r', '\n']);
    if trimmed.len() != input.len() && trimmed.starts_with("<?xml") {
        let after = &trimmed["<?xml".len()..];
        // `<?xmlfoo?>` is a processing instruction with a reserved
        // target, reported elsewhere; only a real declaration counts.
        if after.starts_with([' ', '\t', '\r', '\n']) {
            return Err(Error::new(ErrorKind::MalformedDeclaration, 0));
        }
    }
    Ok(())
}

/// Translate line endings to `\n`, per XML 1.0 and 1.1 section 2.11.
///
/// XML 1.0 collapses `\r\n` and a lone `\r`. XML 1.1 adds NEL
/// (U+0085) and LINE SEPARATOR (U+2028), and treats `\r` followed by
/// NEL as one ending rather than two.
///
/// Borrows when there is nothing to change, which is the common case:
/// a document written on a Unix-like system contains no carriage
/// return at all and pays only for the scan.
///
/// Character references are untouched, which is what the
/// specification requires. `&#xD;` is still markup at this point and
/// becomes a carriage return when the reference is expanded -- it is
/// the only way to write one that survives.
/// Append `text` to an attribute value, normalising whitespace.
///
/// XML section 3.3.3 requires each whitespace character in an
/// attribute value to be replaced by a space. Line endings are already
/// `\n` by the time this runs, so in practice this converts `\n` and
/// `\t`; `\r` only reaches here from a character reference, which is
/// exempt and never passed to this function.
///
/// Without it, an attribute written across two lines came back
/// containing the newline and the indentation of the next line -- so
/// `title="a\n    b"` rather than `title="a     b"`, and two documents
/// that differ only in line wrapping produced different values.
/// The offset of the next `&` that is a reference rather than text.
///
/// Skips over CDATA sections, inside which `&` introduces nothing.
/// What a start tag yields, before anything is done with it.
pub(crate) struct StartTag<'a> {
    /// The element's name, as written.
    pub(crate) qname: &'a str,
    /// Attributes, as written, with entities resolved in the values.
    pub(crate) raw_attrs: Vec<(&'a str, Run)>,
    /// Namespaces this tag declares, as `(prefix, uri)`.
    pub(crate) declared: Vec<(String, String)>,
    /// Whether the tag closed itself.
    pub(crate) self_closing: bool,
    /// Where the tag began, for an error offset.
    pub(crate) tag_start: usize,
}

fn next_reference(text: &str) -> Option<usize> {
    let mut at = 0;
    while at < text.len() {
        let rest = &text[at..];
        let amp = rest.find('&');
        let cdata = rest.find("<![CDATA[");
        match (amp, cdata) {
            (Some(a), Some(c)) if c < a => {
                // Skip the whole section; an unterminated one is left
                // for the parser proper to report.
                let after = at + c + "<![CDATA[".len();
                let end = text[after..].find("]]>")?;
                at = after + end + "]]>".len();
            }
            (Some(a), _) => return Some(at + a),
            (None, _) => return None,
        }
    }
    None
}

/// The further normalisation XML 1.0 section 3.3.3 gives a value whose
/// declared type is not `CDATA`.
///
/// Leading and trailing spaces are discarded and runs of spaces
/// collapse to one. Only `#x20` counts here: tabs and line breaks
/// became spaces in the first pass, so by this point there is nothing
/// else left to collapse.
///
/// This is not cosmetic. `xmlns:b=" urn:x "` declared `NMTOKEN`
/// normalises to `urn:x` and binds that prefix to the same namespace
/// as one declared without the spaces; two attributes whose expanded
/// names then collide make the document not well-formed. Skipping this
/// pass hides the collision entirely.
fn collapse(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for part in text.split(' ').filter(|p| !p.is_empty()) {
        if !out.is_empty() {
            out.push(' ');
        }
        out.push_str(part);
    }
    out
}

fn push_attribute_normalized(out: &mut String, text: &str) {
    // The overwhelmingly common case is a value with no whitespace to
    // replace, which copies in one go.
    if !text.contains(['\n', '\t', '\r']) {
        out.push_str(text);
        return;
    }
    for c in text.chars() {
        out.push(match c {
            '\n' | '\t' | '\r' => ' ',
            other => other,
        });
    }
}

pub(crate) fn normalize_line_endings(
    input: &str,
    version: Version,
) -> Cow<'_, str> {
    let terminator = |c: char| {
        c == '\r'
            || (version == Version::V11 && (c == '\u{85}' || c == '\u{2028}'))
    };
    if !input.chars().any(terminator) {
        return Cow::Borrowed(input);
    }

    let mut out = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\r' => {
                let paired = matches!(chars.peek(), Some('\n'))
                    || (version == Version::V11
                        && matches!(chars.peek(), Some('\u{85}')));
                if paired {
                    // The pair is one line ending; drop the second half.
                    let _ = chars.next();
                }
                out.push('\n');
            }
            '\u{85}' | '\u{2028}' if version == Version::V11 => {
                out.push('\n');
            }
            other => out.push(other),
        }
    }
    Cow::Owned(out)
}

/// Parse a document whose line endings are already normalised.
fn parse_normalized(
    input: &str,
    limits: Limits,
    version: Version,
    external: &dyn crate::external::ExternalSource,
) -> Result<Document> {
    limits.check_nodes(0, 1, 0)?;
    // `document ::= prolog element Misc*` with
    // `prolog ::= XMLDecl? Misc*` -- the declaration comes first or not
    // at all. Whitespace before it is not `Misc` appearing early, it is
    // a malformed document, and skipping leading whitespace before
    // looking for `<?xml` accepted it. The check is the one `prepare`
    // makes for the streaming reader: this copy kept trimming Rust's
    // whitespace after that one moved to XML's.
    check_prolog_shape(input)?;
    // Checked once over the whole input rather than at each construct.
    // The `Char` production applies everywhere — content, attribute
    // values, comments, even the DTD — so a per-construct check would
    // have to be repeated in a dozen places and would be forgotten in
    // the thirteenth. One pass is also faster than one branch per
    // character in the hot loops.
    if let Some((offset, c)) = input
        .char_indices()
        .find(|(_, c)| !is_literal_char_for(*c, version))
    {
        return Err(Error::new(ErrorKind::IllegalCharacter(c), offset));
    }

    let mut p = Parser {
        input,
        bytes: input.as_bytes(),
        pos: 0,
        // One byte-scan to size the arena. Every element, comment and
        // processing instruction begins with `<`, and text nodes are
        // bounded by them. Counting runs at memory speed; the
        // reallocate-and-copy it avoids does not.
        doc: Box::new(Document::with_capacity(arena_capacity(input, &limits))),
        name_index: alloc::collections::BTreeMap::new(),
        external,
        ns: Namespaces::default(),
        depth: 0,
        limits,
        dtd: None,
        version,
        entity_budget: limits.max_entity_expansion,
        entity_depth: 0,
        standalone: declared_standalone(input),
        entity_cache: BTreeSet::new(),
    };
    p.parse_document()?;
    Ok(*p.doc)
}

type ResolvedAttributes = (Vec<(NameId, Chars)>, Vec<String>);

enum ChildStep {
    Element,
    Continue,
    Done,
}

impl<'a> Parser<'a> {
    fn parse_document(&mut self) -> Result<()> {
        let root = self.doc.root();
        let mark = self.doc.scratch_mark();
        self.skip_prolog()?;

        let mut seen_root = false;
        loop {
            self.skip_whitespace();
            if self.pos >= self.bytes.len() {
                break;
            }
            if self.peek_is(b'<') {
                if self.starts_with("<!--") {
                    self.push_comment(root)?;
                } else if self.starts_with("<?") {
                    self.push_pi(root)?;
                } else if self.starts_with("<!DOCTYPE") {
                    self.late_doctype(seen_root)?;
                } else if self.starts_with("</") {
                    let name = self.peek_end_tag_name();
                    return Err(Error::new(
                        ErrorKind::UnexpectedEndTag(name),
                        self.pos,
                    ));
                } else {
                    if seen_root {
                        return Err(Error::new(
                            ErrorKind::TrailingContent,
                            self.pos,
                        ));
                    }
                    self.parse_element(root)?;
                    seen_root = true;
                }
            } else {
                // Non-whitespace character data outside the root
                // element is never well-formed.
                return Err(Error::new(ErrorKind::TrailingContent, self.pos));
            }
        }

        if seen_root {
            self.doc.finish_children(root, mark);
            Ok(())
        } else {
            Err(Error::new(ErrorKind::NoRootElement, self.pos))
        }
    }

    /// Skip the XML declaration, doctype, and any leading misc.
    ///
    /// The declaration is consumed rather than modelled: nothing in the
    /// tree depends on it, and preserving it would mean a node kind
    /// that `XPath` has no concept of.
    pub(crate) fn skip_prolog(&mut self) -> Result<()> {
        self.skip_whitespace();
        if self.starts_with("<?xml")
            && !matches!(
                self.bytes.get(self.pos + 5),
                Some(c) if is_name_char(char::from(*c))
            )
        {
            let end = self.input[self.pos..].find("?>").ok_or_else(|| {
                Error::new(ErrorKind::Unterminated("XML declaration"), self.pos)
            })?;
            let decl = &self.input[self.pos + 5..self.pos + end];
            validate_xml_declaration(decl, self.pos, true)?;
            self.pos += end + 2;
        }
        loop {
            self.skip_whitespace();
            if self.starts_with("<!DOCTYPE") {
                self.skip_doctype()?;
            } else {
                break;
            }
        }
        Ok(())
    }

    /// Skip a doctype, tracking bracket depth so an internal subset
    /// containing `>` does not end it early.
    pub(crate) fn skip_doctype(&mut self) -> Result<()> {
        // Parsed rather than skipped. Well-formedness constraints live
        // inside the DTD — a malformed `<!ATTLIST>` makes a document not
        // well-formed for *every* parser, validating or not — and the
        // general entity declarations are needed so that a document
        // using `&chapter1;` is not rejected as undeclared.
        let mut p = crate::dtd::DtdParser::with_limits(
            self.input,
            self.pos,
            &self.limits,
        )
        // So an external parameter entity the caller supplied can be
        // read. Without this the DTD parser sees no source at all and
        // `%pExternal;` pulls in nothing.
        .with_external(self.external, self.version);
        match p.parse_doctype() {
            Ok(mut dtd) => {
                self.pos = p.pos;
                // The external subset, if the caller can supply it.
                // Parsed *after* the internal one, because the internal
                // subset takes precedence: "the first declaration
                // binds", and `or_insert` in the entity map already
                // implements that.
                if let Some((system, public)) = dtd.external_subset.clone()
                    && let Some(content) =
                        self.external.fetch(&system, public.as_deref())
                {
                    self.read_external_subset(&mut dtd, content)?;
                }
                // An external entity is checked when it is
                // *referenced*, not when it is declared. A processor
                // need not read an entity nothing uses, so validating
                // eagerly rejected a valid document whose unreferenced
                // entity had no `encoding` -- a rule that only applies
                // to content you actually read.
                self.dtd = Some(dtd);
                Ok(())
            }
            Err((offset, reason)) => {
                Err(Error::new(ErrorKind::MalformedDtd(reason), offset))
            }
        }
    }

    /// Read the external DTD subset `content` into `dtd`, after the
    /// internal subset, so the internal declarations keep precedence.
    fn read_external_subset(
        &self,
        dtd: &mut crate::dtd::Dtd,
        content: &str,
    ) -> Result<()> {
        self.limits.check_document(content.len(), self.pos)?;
        if self
            .limits
            .max_dtd_bytes
            .is_some_and(|max| content.len() > max)
        {
            return Err(Error::new(ErrorKind::DtdTooLarge, self.pos));
        }
        let version = entity_version(content, self.version);
        let normalized = normalize_line_endings(content, version);
        check_text_decl_position(&normalized, self.pos)?;
        check_text_decl(&normalized, self.version, self.pos)?;
        let body = strip_text_decl(&normalized);
        // Judged by **both** versions, and it has to
        // be both.
        //
        // The subset's own version rules it: a DTD
        // declaring 1.0 may not contain characters only
        // 1.1 allows, which is what carrying a version
        // per entity is for. But the including
        // document's version rules it too. XML 1.1
        // section 4.3.4: a 1.0 external DTD may hold
        // `#x7F`, legal in 1.0, and pulling it into a
        // document declaring 1.1 puts a character there
        // that 1.1 requires to be escaped. Checking
        // only the entity's version accepted seven
        // documents the suite calls not well-formed.
        if let Some((_, c)) = body.char_indices().find(|(_, c)| {
            !is_literal_char_for(*c, version)
                || !is_literal_char_for(*c, self.version)
        }) {
            return Err(Error::new(ErrorKind::IllegalCharacter(c), self.pos));
        }
        self.read_subset_declarations(dtd, body, version)
    }

    fn read_subset_declarations(
        &self,
        dtd: &mut crate::dtd::Dtd,
        body: &str,
        version: Version,
    ) -> Result<()> {
        let mut sub = crate::dtd::DtdParser::with_limits(body, 0, &self.limits)
            .with_external(self.external, version);
        // Which names arrive from out here, so that
        // `standalone="yes"` can refuse them. Taken as
        // a before-and-after rather than threaded
        // through the DTD parser: the boundary is
        // exactly this call.
        let before: alloc::collections::BTreeSet<String> =
            dtd.general.keys().cloned().collect();
        if let Err((offset, reason)) = sub.parse_external_subset(dtd) {
            let _ = offset;
            return Err(Error::new(ErrorKind::MalformedDtd(reason), self.pos));
        }
        dtd.declared_externally = dtd
            .general
            .keys()
            .filter(|k| !before.contains(*k))
            .cloned()
            .collect();
        // The declarations are now known, so an entity
        // that is still missing really is undeclared.
        dtd.incomplete = false;
        Ok(())
    }

    fn parse_element(&mut self, parent: NodeId) -> Result<()> {
        // Checked on entry so the frame that would overflow is never
        // pushed. See `crate::MAX_DEPTH`.
        if self.depth >= self.limits.max_depth {
            return Err(Error::new(ErrorKind::DepthLimitExceeded, self.pos));
        }
        self.depth += 1;
        let result = self.parse_element_inner(parent);
        self.depth -= 1;
        result
    }

    /// Apply the `xmlns` declarations on a start tag.
    ///
    /// Split out of `parse_element_inner` because it is where the
    /// Namespaces specification's rules live, and it had grown twice --
    /// once for prefixed reserved URIs, once for the default
    /// declaration, which had been missed.
    /// Bind the `xmlns` declarations on a start tag, and report them
    /// as `(prefix, uri)` pairs in source order.
    ///
    /// The pairs become namespace nodes. An *undeclaration* -- an
    /// empty URI, which is XML 1.1 only -- is reported too, even
    /// though it names no namespace: it has to shadow the same prefix
    /// declared on an ancestor, and a prefix that is simply absent
    /// here would leave the ancestor's binding in scope.
    pub(crate) fn bind_namespaces(
        &mut self,
        element: &str,
        raw_attrs: &[(&'a str, Run)],
    ) -> Result<Vec<(String, String)>> {
        let mut declared: Vec<(String, String)> = Vec::new();
        // Copied out so resolving a run does not borrow `self` while
        // the loop binds into `self.ns`.
        let input = self.input;
        for (name, run) in raw_attrs {
            let Some(prefix) = declared_prefix(name) else {
                continue;
            };
            // A namespace declaration is an attribute, and `WFC:
            // Unique Att Spec` applies to it. The general duplicate
            // check skips `xmlns` attributes, so this is the only place
            // `<a xmlns:p="u1" xmlns:p="u2"/>` can be caught.
            if declared.iter().any(|(p, _)| p == prefix) {
                return Err(Error::new(
                    ErrorKind::DuplicateAttribute((*name).to_owned()),
                    self.pos,
                ));
            }
            // An `xmlns` attribute is an attribute, so a declaration
            // giving it a non-`CDATA` type normalises its value like
            // any other -- and the *binding* must use the normalised
            // form. `xmlns:b=" urn:x "` declared `NMTOKEN` binds
            // `urn:x`, the same namespace as an unspaced declaration
            // elsewhere, which is how two attributes come to share one
            // expanded name. Binding the raw value hid that.
            let tokenized = self
                .dtd
                .as_ref()
                .is_some_and(|d| d.is_tokenized_attribute(element, name));
            let collapsed;
            let value = if tokenized {
                collapsed = collapse(run.as_str(input));
                collapsed.as_str()
            } else {
                run.as_str(input)
            };
            check_declaration(name, prefix, value, self.version)
                .map_err(|kind| Error::new(kind, self.pos))?;
            self.ns.bind(prefix.to_owned(), value.to_owned());
            declared.push((prefix.to_owned(), value.to_owned()));
        }
        Ok(declared)
    }

    /// Read a start tag: its name, its attributes, the namespaces it
    /// declares, and whether it closed itself.
    ///
    /// Extracted so the streaming reader runs the *same* scanner. Two
    /// implementations of XML start-tag scanning would diverge, and
    /// the one with fewer users would be the one that was wrong.
    ///
    /// A namespace scope is pushed on success and left for the caller
    /// to pop when the element ends. On failure it is popped here, so
    /// a rejected tag leaves no scope behind.
    pub(crate) fn scan_start_tag(&mut self) -> Result<StartTag<'a>> {
        let tag_start = self.pos;
        self.pos += 1; // '<'
        let qname = self.parse_name()?;

        // Attributes are collected before the element node is created:
        // namespace declarations among them must be in scope for the
        // element's *own* name to resolve.
        self.ns.push_scope();
        let raw_attrs = self.parse_attributes()?;
        let declared = self.bind_namespaces(qname, &raw_attrs)?;
        let self_closing = if self.starts_with("/>") {
            self.pos += 2;
            true
        } else if self.peek_is(b'>') {
            self.pos += 1;
            false
        } else {
            self.ns.pop_scope();
            return Err(Error::new(
                ErrorKind::Unterminated("start tag"),
                tag_start,
            ));
        };
        Ok(StartTag {
            qname,
            raw_attrs,
            declared,
            self_closing,
            tag_start,
        })
    }

    fn parse_element_inner(&mut self, parent: NodeId) -> Result<()> {
        let StartTag {
            qname,
            raw_attrs,
            declared,
            self_closing,
            tag_start,
        } = self.scan_start_tag()?;

        let (resolved, id_values) =
            self.resolve_attributes(qname, raw_attrs, tag_start)?;
        let name_id = self.intern_qname(qname, true, tag_start)?;
        let additional = 1
            + resolved.len()
            + declared.len()
            + usize::from(parent == self.doc.root());
        self.check_nodes(additional)?;
        let node = self.doc.push(
            NodeData::Element {
                name: name_id,
                attributes: (0, 0),
                namespaces: (0, 0),
            },
            parent,
        );
        // Provisionally the start tag alone; the end tag extends it.
        self.doc.set_span(node, tag_start, self.pos);
        self.attach_attributes(node, resolved, id_values, declared);

        if self_closing {
            self.ns.pop_scope();
            return Ok(());
        }

        self.parse_children(node, qname)?;
        self.ns.pop_scope();
        Ok(())
    }

    /// Resolve a start tag's attributes to interned names and stored
    /// values, before any node exists.
    ///
    /// Done first so a duplicate is detected before the element is
    /// created -- otherwise a rejected element would already be in
    /// the arena. Returns the attributes in document order and the
    /// values of the element's `ID`-typed attributes, which are held
    /// until the element node exists to point them at.
    fn resolve_attributes(
        &mut self,
        qname: &str,
        raw_attrs: Vec<(&'a str, Run)>,
        tag_start: usize,
    ) -> Result<ResolvedAttributes> {
        let mut resolved: Vec<(NameId, Chars)> =
            Vec::with_capacity(raw_attrs.len());
        let mut seen = SeenAttributes::default();
        let input = self.input;
        let mut id_values: Vec<String> = Vec::new();
        for (raw, run) in raw_attrs {
            if raw == "xmlns" || raw.starts_with("xmlns:") {
                continue;
            }
            let an = self.intern_qname(raw, false, tag_start)?;
            // Compared by *expanded* name, not by id. Namespaces in
            // XML forbids two attributes with the same expanded name
            // however they are spelled, so `p:a` and `q:a` with `p` and
            // `q` bound to one namespace collide. Ids no longer settle
            // that on their own: they distinguish prefixes, so the two
            // get different ids and an id comparison would let the pair
            // through.
            if !seen.insert(an, &self.doc.names) {
                self.ns.pop_scope();
                return Err(Error::new(
                    ErrorKind::DuplicateAttribute(raw.to_owned()),
                    tag_start,
                ));
            }
            if self
                .dtd
                .as_ref()
                .is_some_and(|d| d.is_id_attribute(qname, raw))
            {
                id_values.push(run.as_str(input).to_owned());
            }
            let value = self.store_attribute_value(qname, raw, &run);
            resolved.push((an, value));
        }

        Ok((resolved, id_values))
    }

    /// Where an attribute's value lives: a range into the input when
    /// the scanned slice still says it, the side table otherwise.
    ///
    /// XML 1.0 section 3.3.3: a value whose declared type is not
    /// `CDATA` gets a second pass -- leading and trailing spaces
    /// discarded, runs of spaces collapsed to one. Only the
    /// declaration says which values those are, so this cannot be
    /// decided by looking at the value.
    fn store_attribute_value(
        &mut self,
        qname: &str,
        raw: &str,
        run: &Run,
    ) -> Chars {
        let input = self.input;
        let tokenized = self
            .dtd
            .as_ref()
            .is_some_and(|d| d.is_tokenized_attribute(qname, raw));
        let collapsed = tokenized.then(|| collapse(run.as_str(input)));
        match (&collapsed, run.as_span()) {
            // Collapsing changed nothing, so the slice still says it:
            // the common case, and it stays free.
            (Some(text), Some((start, len))) if text == run.as_str(input) => {
                self.verbatim(start, len)
            }
            (Some(text), _) => self.doc.push_expanded(text),
            (None, Some((start, len))) => self.verbatim(start, len),
            (None, None) => self.doc.push_expanded(run.as_str(input)),
        }
    }

    /// Attach resolved attributes, `ID` values and namespace nodes to
    /// the element node that now exists.
    fn attach_attributes(
        &mut self,
        node: NodeId,
        resolved: Vec<(NameId, Chars)>,
        id_values: Vec<String>,
        declared: Vec<(String, String)>,
    ) {
        // Attribute nodes are parented to the element but kept out of
        // its `children`, so `child::` cannot see them. They are pushed
        // consecutively, so they are already contiguous in `attr_ids`
        // and need no scratch buffer.
        let start = self.doc.attr_ids.len();
        for (name, value) in resolved {
            let id =
                self.doc.push_detached(NodeData::Attr { name, value }, node);
            self.doc.attr_ids.push(id);
        }
        for value in id_values {
            // Two elements sharing an ID makes the document invalid,
            // which this parser does not enforce. `id()` still has to
            // answer with one node, so the first declaration wins
            // rather than the last silently replacing it.
            let _ = self.doc.ids.entry(value).or_insert(node);
        }

        let len = self.doc.attr_ids.len() - start;

        // Namespace nodes, like attribute nodes: parented to the
        // element, kept out of `children`, contiguous in their own
        // arena. `xml` is bound by specification and never declared,
        // so the root element carries a node for it and every element
        // inherits it by the same ancestor walk as any other prefix.
        let (ns_start, ns_len) = self.push_namespace_nodes(node, declared);

        if let Some(NodeData::Element {
            attributes,
            namespaces,
            ..
        }) = self.doc.data_mut(node)
        {
            *attributes = (
                u32::try_from(start).unwrap_or(u32::MAX),
                u32::try_from(len).unwrap_or(u32::MAX),
            );
            *namespaces = (
                u32::try_from(ns_start).unwrap_or(u32::MAX),
                u32::try_from(ns_len).unwrap_or(u32::MAX),
            );
        }
    }

    /// Attach an element's namespace nodes, returning their
    /// `(start, len)` range in the shared arena.
    ///
    /// `xml` is bound by specification and never declared, so the root
    /// element carries a node for it and every element inherits it
    /// through the same ancestor walk as any other prefix -- one node
    /// per document rather than one per element.
    fn push_namespace_nodes(
        &mut self,
        node: NodeId,
        declared: Vec<(String, String)>,
    ) -> (usize, usize) {
        let start = self.doc.ns_ids.len();
        if self.doc.nodes[node.index()].parent == Some(self.doc.root()) {
            // Namespace nodes go in the side table rather than
            // being ranges. There is one per *declaration*, not per
            // element -- a document usually has a handful, all on the
            // root -- so the plumbing to span them would cost more
            // than it saves.
            let prefix = self.doc.push_expanded("xml");
            let uri = self
                .doc
                .push_expanded("http://www.w3.org/XML/1998/namespace");
            let id = self
                .doc
                .push_detached(NodeData::Namespace { prefix, uri }, node);
            self.doc.ns_ids.push(id);
        }
        for (prefix, uri) in declared {
            let prefix = self.doc.push_expanded(&prefix);
            let uri = self.doc.push_expanded(&uri);
            let id = self
                .doc
                .push_detached(NodeData::Namespace { prefix, uri }, node);
            self.doc.ns_ids.push(id);
        }
        (start, self.doc.ns_ids.len() - start)
    }

    /// A `<!DOCTYPE` met in the document loop rather than the prolog.
    ///
    /// Handled here as well as in `skip_prolog`, because the prolog is
    /// `Misc* doctypedecl? Misc*` -- a comment or PI may precede the
    /// declaration. The prolog loop breaks on anything that is not a
    /// DOCTYPE, so a leading comment left the DOCTYPE to be parsed as
    /// an element and reported as `expected a name`. A second DOCTYPE,
    /// or one after the root element, is trailing content.
    fn late_doctype(&mut self, seen_root: bool) -> Result<()> {
        if seen_root || self.dtd.is_some() {
            return Err(Error::new(ErrorKind::TrailingContent, self.pos));
        }
        self.skip_doctype()
    }

    fn parse_children(&mut self, node: NodeId, open_qname: &str) -> Result<()> {
        let mark = self.doc.scratch_mark();
        let mut text = Run::default();
        loop {
            match self.child_step(node, open_qname, mark, &mut text)? {
                ChildStep::Element => self.parse_element(node)?,
                ChildStep::Continue => {}
                ChildStep::Done => return Ok(()),
            }
        }
    }

    /// This frame returns before descending into a child element.
    fn child_step(
        &mut self,
        node: NodeId,
        open_qname: &str,
        mark: usize,
        text: &mut Run,
    ) -> Result<ChildStep> {
        if self.read_text_piece(text)? {
            return Ok(ChildStep::Continue);
        }
        self.flush_text(text, node)?;
        if self.starts_with("</") {
            self.parse_end_tag(node, open_qname, mark)?;
            return Ok(ChildStep::Done);
        }
        Ok(if self.push_misc(node)? {
            ChildStep::Continue
        } else {
            ChildStep::Element
        })
    }

    fn read_text_piece(&mut self, text: &mut Run) -> Result<bool> {
        if self.pos >= self.bytes.len() {
            return Err(Error::new(ErrorKind::UnexpectedEof, self.pos));
        }
        if !self.peek_is(b'<') {
            self.parse_text_run(text)?;
            return Ok(true);
        }
        if self.starts_with("<![CDATA[") {
            self.parse_cdata(text)?;
            return Ok(true);
        }
        Ok(false)
    }

    fn push_misc(&mut self, node: NodeId) -> Result<bool> {
        if self.starts_with("<!--") {
            self.push_comment(node)?;
            return Ok(true);
        }
        if self.starts_with("<?") {
            self.push_pi(node)?;
            return Ok(true);
        }
        Ok(false)
    }

    /// `</name>`: it must match the open tag, and it closes `node`, so
    /// the children gathered since `mark` move into the flat arena as
    /// one contiguous block.
    fn parse_end_tag(
        &mut self,
        node: NodeId,
        open_qname: &str,
        mark: usize,
    ) -> Result<()> {
        let start = self.pos;
        self.pos += 2;
        let close = self.parse_name()?;
        self.skip_whitespace();
        if !self.peek_is(b'>') {
            return Err(Error::new(ErrorKind::Unterminated("end tag"), start));
        }
        self.pos += 1;
        if close != open_qname {
            return Err(Error::new(
                ErrorKind::MismatchedEndTag {
                    expected: open_qname.to_owned(),
                    found: close.to_owned(),
                },
                start,
            ));
        }
        self.doc.finish_children(node, mark);
        self.doc.set_span_end(node, self.pos);
        Ok(())
    }

    /// Scan a comment at the cursor and attach it to `parent`, with
    /// the range it came from.
    fn push_comment(&mut self, parent: NodeId) -> Result<()> {
        self.check_nodes(1)?;
        let at = self.pos;
        let c = self.parse_comment()?;
        let id = self.doc.push(NodeData::Comment(c), parent);
        self.doc.set_span(id, at, self.pos);
        Ok(())
    }

    /// Scan a processing instruction at the cursor and attach it to
    /// `parent`, with the range it came from.
    fn push_pi(&mut self, parent: NodeId) -> Result<()> {
        self.check_nodes(1)?;
        let at = self.pos;
        let (target, data) = self.parse_pi()?;
        let id = self
            .doc
            .push(NodeData::ProcessingInstruction { target, data }, parent);
        self.doc.set_span(id, at, self.pos);
        Ok(())
    }

    fn flush_text(&mut self, text: &mut Run, node: NodeId) -> Result<()> {
        if !text.is_empty() {
            self.check_nodes(1)?;
            let run = core::mem::take(text);
            if self.limits.max_text_length.is_some_and(|m| run.len() > m) {
                return Err(Error::new(ErrorKind::TextTooLong, self.pos));
            }
            // A run still expressible as a slice becomes a range; one
            // that is not joins the side table.
            let chars = if let Some((start, len)) = run.as_span() {
                self.verbatim(start, len)
            } else {
                let text = run.as_str(self.input);
                self.doc.push_expanded(text)
            };
            let id = self.doc.push(NodeData::Text(chars), node);
            self.doc.set_span(id, run.start, self.pos);
        }
        Ok(())
    }

    fn check_nodes(&self, additional: usize) -> Result<()> {
        self.limits
            .check_nodes(self.doc.len(), additional, self.pos)
    }

    #[inline]
    const fn has_byte(v: u64, b: u8) -> bool {
        let splat = u64::from_ne_bytes([b; 8]);
        let x = v ^ splat;
        (x.wrapping_sub(0x0101_0101_0101_0101) & !x & 0x8080_8080_8080_8080)
            != 0
    }

    #[inline]
    const fn has_text_delimiter(v: u64) -> bool {
        Self::has_byte(v, b'<') || Self::has_byte(v, b'&')
    }

    #[inline]
    const fn has_attr_delimiter(v: u64, quote: u8) -> bool {
        Self::has_byte(v, quote)
            || Self::has_byte(v, b'&')
            || Self::has_byte(v, b'<')
    }

    pub(crate) fn parse_text_run(&mut self, out: &mut Run) -> Result<()> {
        while self.pos < self.bytes.len() {
            // `CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)`. The
            // sequence is forbidden literally so that a reader can
            // always tell where a CDATA section ends; it must be
            // written `]]&gt;`.
            if self.starts_with("]]>") {
                return Err(Error::new(ErrorKind::IllegalCdataEnd, self.pos));
            }
            match self.bytes[self.pos] {
                b'<' => break,
                b'&' => self.text_reference(out)?,
                _ => self.text_chars(out)?,
            }
        }
        Ok(())
    }

    /// The length of the reference name that starts at `self.pos`,
    /// just after its `&`: up to the `;` that ends it, which must come
    /// before the next `<` and before `stop`, the quote that closes an
    /// attribute value. `None` when it does not.
    ///
    /// Searching the rest of the input found a `;` past the markup or
    /// the quote that ends the text or the value, so the reader that
    /// holds the whole document reported an unknown entity whose name
    /// spanned tags, where the streaming reader, which holds one
    /// construct, reported the reference unterminated.
    fn reference_len(&self, stop: u8) -> Option<usize> {
        let rest = &self.bytes[self.pos..];
        rest.iter()
            .position(|&b| matches!(b, b';' | b'<') || b == stop)
            .filter(|&i| rest[i] == b';')
    }

    /// A reference in character data, at `&`, expanded into `out`.
    fn text_reference(&mut self, out: &mut Run) -> Result<()> {
        let s = self.pos;
        self.pos += 1;
        let end = self
            .reference_len(b'<')
            .ok_or_else(|| Error::new(ErrorKind::Unterminated("entity"), s))?;
        let ent = &self.input[self.pos..self.pos + end];
        // Element content, not an attribute value: section 3.3.3 does
        // not apply, and a newline in content is content.
        let expanded = self.expand_entity(ent, s, false)?;
        // The one thing in a text run the input does not hold
        // verbatim: this is where a run stops being a slice and starts
        // being a string.
        out.push_owned(&expanded, self.input);
        self.pos += end + 1;
        Ok(())
    }

    /// Literal character data up to the next `<` or `&`, joined to
    /// `out` as a slice of the input.
    fn text_chars(&mut self, out: &mut Run) -> Result<()> {
        let start = self.pos;
        while self.pos + 8 <= self.bytes.len() {
            let Ok(chunk) = self.bytes[self.pos..self.pos + 8].try_into()
            else {
                break;
            };
            let v = u64::from_ne_bytes(chunk);
            if Self::has_text_delimiter(v) {
                break;
            }
            self.pos += 8;
        }
        while self.pos < self.bytes.len()
            && self.bytes[self.pos] != b'<'
            && self.bytes[self.pos] != b'&'
        {
            self.pos += 1;
        }
        // The check at the top of the run's loop only sees the first
        // byte of a run. Everything after it was consumed here without
        // being looked at, so `]]]>`, `abc]]>def` and the text left
        // over after a nested CDATA section all passed.
        let run = &self.input[start..self.pos];
        if let Some(at) = run.find("]]>") {
            return Err(Error::new(ErrorKind::IllegalCdataEnd, start + at));
        }
        out.push_slice(start, run, self.input);
        Ok(())
    }

    /// Consumes a `CDATA` section into a character-data run.
    ///
    /// CDATA is character data, so it joins the run rather than
    /// becoming a node of its own -- `a<![CDATA[b]]>c` is the single
    /// text `abc`. Extracted so the streaming reader consumes CDATA
    /// exactly as the tree parser does; when it had its own copy, the
    /// copy did not advance and read the section forever.
    pub(crate) fn parse_cdata(&mut self, out: &mut Run) -> Result<()> {
        self.pos += "<![CDATA[".len();
        let end = self.input[self.pos..].find("]]>").ok_or_else(|| {
            Error::new(ErrorKind::Unterminated("CDATA"), self.pos)
        })?;
        // The body is itself a slice of the input, so a text node that
        // is *only* a `CDATA` section still costs nothing. One mixed
        // with adjacent text does, because the delimiters sit between
        // them and the pieces are no longer contiguous.
        let body = &self.input[self.pos..self.pos + end];
        out.push_slice(self.pos, body, self.input);
        self.pos += end + 3;
        Ok(())
    }

    /// An entity's replacement text: character references included,
    /// general entity references left alone.
    ///
    /// XML 1.0 section 4.4: inside an `EntityValue`, character
    /// references are *included* -- expanded there and then -- while
    /// general entity references are *bypassed* and left for the point
    /// of use. That distinction is the whole of why
    /// `<!ENTITY e "&#38;">` is a trap and `<!ENTITY e "&amp;">` is
    /// not: the first has the single character `&` as its replacement
    /// text, which is markup wherever it lands and starts no
    /// reference, while the second still holds a reference that
    /// resolves cleanly when it is used.
    ///
    /// This parser stores entity values as written, so the inclusion
    /// is done here instead, for the benefit of the checks below.
    fn replacement_text(&self, text: &str, offset: usize) -> Result<String> {
        let mut out = String::with_capacity(text.len());
        let mut rest = text;
        while let Some(amp) = rest.find('&') {
            out.push_str(&rest[..amp]);
            let tail = &rest[amp..];
            let Some(semi) = tail.find(';') else {
                // Not a reference at all. Left as written so the
                // content check reports it.
                out.push_str(tail);
                return Ok(out);
            };
            let name = &tail[1..semi];
            if let Some(rest_name) = name.strip_prefix('#') {
                let _ = rest_name;
                match decode_predefined(name) {
                    Some(direct) => {
                        if let Some(bad) = direct
                            .chars()
                            .find(|c| !is_xml_char_for(*c, self.version))
                        {
                            return Err(Error::new(
                                ErrorKind::IllegalCharacter(bad),
                                offset,
                            ));
                        }
                        out.push_str(&direct);
                    }
                    None => out.push_str(&tail[..=semi]),
                }
            } else {
                // Bypassed: a general entity reference stays a
                // reference until it is used.
                out.push_str(&tail[..=semi]);
            }
            rest = &tail[semi + 1..];
        }
        out.push_str(rest);
        Ok(out)
    }

    /// Check replacement text included in an attribute value.
    ///
    /// XML 1.0 section 4.4.5, *Included in Literal*: the replacement
    /// text is parsed as though it were the literal, so `<` is
    /// forbidden and `&` must begin a reference. `<!ENTITY e "&#38;">`
    /// used as `a="&e;"` therefore fails, while `a="&amp;"` -- a
    /// predefined reference, not an entity's replacement text --
    /// does not.
    fn check_entity_in_attribute(text: &str, offset: usize) -> Result<()> {
        let bytes = text.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            match bytes[i] {
                b'<' => {
                    return Err(Error::new(
                        ErrorKind::IllegalCharacter('<'),
                        offset,
                    ));
                }
                b'&' => {
                    // Must be a complete reference *within* the
                    // replacement text: a document may not assemble one
                    // out of an entity plus the characters after it.
                    let rest = &text[i + 1..];
                    let Some(semi) = rest.find(';') else {
                        return Err(Error::new(
                            ErrorKind::Unterminated("entity"),
                            offset,
                        ));
                    };
                    if semi == 0 {
                        return Err(Error::new(ErrorKind::InvalidName, offset));
                    }
                    i += semi + 2;
                }
                _ => i += 1,
            }
        }
        Ok(())
    }

    /// Check an entity's replacement text as though it were markup.
    ///
    /// XML 1.0 section 4.4.2: a general entity referenced from content
    /// is *included*, which means its replacement text is parsed as
    /// content -- not substituted as characters. So
    /// `<!ENTITY e "</foo><foo>">` closes an element it never opened,
    /// `<!ENTITY e "&#60;foo>">` opens one it never closes, and
    /// `<!ENTITY e "&#38;">` yields a bare `&` where a reference is
    /// required. All three are documents this parser used to accept.
    ///
    /// Character references and the five predefined entities do **not**
    /// go through here. `&#38;` in content is the character `&` and is
    /// text; it is only when that `&` arrives as the replacement text
    /// of a declared entity that it has to be markup.
    ///
    /// The replacement text is parsed with this same parser into a
    /// document that is then thrown away. Reusing the scanner rather
    /// than writing a second one is the point: attribute-value rules,
    /// reserved processing-instruction targets, name validity and
    /// comment termination are all enforced here without being
    /// restated, and cannot drift from what the tree parser does.
    ///
    /// # Cost
    ///
    /// This runs once per *reference*, not once per entity, so a
    /// document that references one entity a thousand times parses its
    /// replacement text a thousand times. That cost is real and is not
    /// quantified here: the machine available while this was written
    /// measured the same benchmark between 1.45 and 3.76 ms in one
    /// state, so no honest before-and-after could be taken. See
    /// `doc/BENCHMARKS.md` for why an absolute figure is not published.
    ///
    /// Memoising by entity name is the obvious fix and is **not**
    /// obviously sound: validity depends on the namespace bindings in
    /// scope, so `<!ENTITY e "<p:x/>">` is well-formed where `p` is
    /// bound and not where it is not. A cache would have to key on the
    /// scope as well as the name, and a wrong key here accepts
    /// documents that should be refused -- which is the bug this
    /// function exists to fix. Left undone deliberately.
    fn check_entity_as_content(
        &mut self,
        text: &str,
        offset: usize,
    ) -> Result<()> {
        if self.entity_depth >= self.limits.max_entity_depth {
            return Err(Error::new(ErrorKind::EntityLimitExceeded, offset));
        }
        // The sub-parser *borrows* the DTD, the namespace stack and
        // the validation cache by moving them out and back, rather
        // than cloning them: a clone of the DTD per entity reference
        // made a document with 4,000 2 KB entities take 2.7 s, and a
        // clone of the cache per validation grew with every entity
        // seen. Bindings the entity makes are discarded afterwards by
        // truncating the stack to where it stood, so they still do
        // not escape.
        let (bindings_before, marks_before) = self.ns.depths();
        let mut sub = Parser {
            input: text,
            bytes: text.as_bytes(),
            pos: 0,
            // Thrown away: only whether it parses matters, so the
            // ranges it records point nowhere and are never read.
            doc: Box::new(Document::with_capacity(0)),
            ns: core::mem::take(&mut self.ns),
            depth: self.depth,
            limits: self.limits,
            dtd: self.dtd.take(),
            version: self.version,
            name_index: alloc::collections::BTreeMap::new(),
            external: self.external,
            entity_budget: self.entity_budget,
            entity_depth: self.entity_depth + 1,
            standalone: self.standalone,
            entity_cache: core::mem::take(&mut self.entity_cache),
        };
        let result = sub.parse_entity_body();
        self.ns = sub.ns;
        self.ns.truncate_to(bindings_before, marks_before);
        self.dtd = sub.dtd;
        self.entity_cache = sub.entity_cache;
        // The budget is per document, so what the check spent counts.
        self.entity_budget = sub.entity_budget;
        // An offset into the replacement text means nothing to a
        // caller holding the document, so errors are reported at the
        // reference that pulled the text in.
        result.map_err(|e| Error::new(e.kind, offset))
    }

    /// Parse replacement text as `content`, to the end of it.
    ///
    /// Differs from [`Parser::parse_children`] in where it stops: this
    /// ends at the end of the text rather than at an end tag, and an
    /// end tag with nothing open is an error rather than the signal to
    /// return.
    fn parse_entity_body(&mut self) -> Result<()> {
        let root = self.doc.root();
        let mark = self.doc.scratch_mark();
        while self.pos < self.bytes.len() {
            if !self.peek_is(b'<') {
                let mut run = Run::default();
                self.parse_text_run(&mut run)?;
                continue;
            }
            if self.starts_with("</") {
                // The entity closes an element it did not open, so the
                // replacement text is not `content` and including it
                // would unbalance the document around it.
                let name = self.peek_end_tag_name();
                return Err(Error::new(
                    ErrorKind::UnexpectedEndTag(name),
                    self.pos,
                ));
            }
            if self.starts_with("<!--") {
                let _ = self.parse_comment()?;
            } else if self.starts_with("<![CDATA[") {
                let mut run = Run::default();
                self.parse_cdata(&mut run)?;
            } else if self.starts_with("<?") {
                let _ = self.parse_pi()?;
            } else {
                // `parse_element` requires a matching end tag, so an
                // element opened here and left open is reported.
                self.parse_element(root)?;
            }
        }
        self.doc.finish_children(root, mark);
        Ok(())
    }

    /// Resolve stored character data against the text being scanned.
    ///
    /// The streaming reader needs the text itself rather than a range,
    /// because an event outlives the scan that produced it.
    pub(crate) fn owned(&self, c: Chars) -> &str {
        match c {
            Chars::Span(start, len) => {
                let (start, len) = (start as usize, len as usize);
                self.input.get(start..start + len).unwrap_or_default()
            }
            Chars::Expanded(i) => self
                .doc
                .expanded
                .get(i as usize)
                .map_or("", alloc::string::String::as_str),
        }
    }

    /// Record a verbatim slice of the input as a range into it.
    ///
    /// This is where an allocation used to be. The document owns the
    /// text already; a node that repeats it owns nothing.
    pub(crate) fn verbatim(&mut self, start: usize, len: usize) -> Chars {
        if let (Ok(s), Ok(l)) = (u32::try_from(start), u32::try_from(len)) {
            return Chars::Span(s, l);
        }
        // Past what a 32-bit range can address. Keep the text in the
        // side table rather than truncate the document.
        let text = &self.input[start..start + len];
        self.doc.push_expanded(text)
    }

    pub(crate) fn parse_comment(&mut self) -> Result<Chars> {
        let start = self.pos;
        self.pos += "<!--".len();
        let end = self.input[self.pos..].find("-->").ok_or_else(|| {
            Error::new(ErrorKind::Unterminated("comment"), start)
        })?;
        let body = &self.input[self.pos..self.pos + end];
        // `Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'`
        // — `--` may not appear inside, and the body may not end with a
        // single `-` (which would make the terminator `--->`).
        if body.contains("--") || body.ends_with('-') {
            return Err(Error::new(ErrorKind::MalformedComment, start));
        }
        let at = self.pos;
        let len = body.len();
        self.pos += end + 3;
        Ok(self.verbatim(at, len))
    }

    pub(crate) fn parse_pi(&mut self) -> Result<(Chars, Chars)> {
        let start = self.pos;
        self.pos += 2; // '<?'
        let target_at = self.pos;
        let target = self.parse_name()?;
        let target_len = target.len();
        // `PITarget ::= Name - (('X'|'x')('M'|'m')('L'|'l'))`. The name
        // `xml` in any case is reserved, so a second XML declaration
        // later in the document is not merely misplaced — it is not a
        // legal processing instruction at all.
        if target.eq_ignore_ascii_case("xml") {
            return Err(Error::new(ErrorKind::ReservedPiTarget, self.pos));
        }
        // Namespaces in XML narrows `PITarget` from `Name` to `NCName`,
        // which has no colon. A namespace-aware parser must reject
        // `<?a:b ?>`; `Name` alone would allow it, which is why this is
        // easy to miss.
        if target.contains(':') {
            return Err(Error::new(ErrorKind::InvalidName, self.pos));
        }
        // The target must be followed by whitespace or `?>`; anything
        // else means the name stopped early on an illegal character.
        if !matches!(
            self.bytes.get(self.pos),
            Some(b' ' | b'\t' | b'\r' | b'\n')
        ) && !self.starts_with("?>")
        {
            return Err(Error::new(ErrorKind::InvalidName, self.pos));
        }
        let end = self.input[self.pos..].find("?>").ok_or_else(|| {
            Error::new(ErrorKind::Unterminated("processing instruction"), start)
        })?;
        // Trimming a slice yields a slice of the same buffer, so the
        // trimmed data is still a range into the input rather than
        // anything that has to be built.
        let raw = &self.input[self.pos..self.pos + end];
        let lead = raw.len() - raw.trim_start().len();
        let data_at = self.pos + lead;
        let data_len = raw.trim().len();
        self.pos += end + 2;
        let target = self.verbatim(target_at, target_len);
        let data = self.verbatim(data_at, data_len);
        Ok((target, data))
    }

    fn parse_attributes(&mut self) -> Result<Vec<(&'a str, Run)>> {
        let mut out = Vec::new();
        loop {
            self.skip_whitespace();
            if self.pos >= self.bytes.len() {
                return Err(Error::new(ErrorKind::UnexpectedEof, self.pos));
            }
            let b = self.bytes[self.pos];
            if b == b'>' || b == b'/' {
                return Ok(out);
            }
            let name = self.parse_name()?;
            self.skip_whitespace();
            if !self.peek_is(b'=') {
                return Err(Error::new(
                    ErrorKind::UnquotedAttributeValue,
                    self.pos,
                ));
            }
            self.pos += 1;
            self.skip_whitespace();
            let value = self.parse_attribute_value()?;
            // `STag ::= '<' Name (S Attribute)* S? '>'` — attributes are
            // separated by whitespace, so `<a b="c"d="e"/>` is not
            // well-formed even though both attributes parse.
            // `None` falls through: running out of input is unexpected
            // EOF, reported by the loop above, not a missing separator.
            if !matches!(
                self.bytes.get(self.pos),
                None | Some(b' ' | b'\t' | b'\r' | b'\n' | b'>' | b'/')
            ) {
                return Err(Error::new(
                    ErrorKind::UnquotedAttributeValue,
                    self.pos,
                ));
            }
            if value.len() > self.limits.max_attribute_size {
                return Err(Error::new(ErrorKind::AttributeTooLarge, self.pos));
            }
            if out.len() >= self.limits.max_attributes_per_element {
                return Err(Error::new(ErrorKind::TooManyAttributes, self.pos));
            }
            out.push((name, value));
        }
    }

    /// `AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'"`
    ///
    /// A literal `<` is forbidden — it must be written `&lt;` — because
    /// otherwise an unclosed tag inside a value is indistinguishable
    /// from markup.
    fn parse_attribute_value(&mut self) -> Result<Run> {
        let start = self.pos;
        let quote = self.attribute_quote()?;
        let mut out = Run::default();
        loop {
            match self.bytes.get(self.pos).copied() {
                None => {
                    return Err(Error::new(
                        ErrorKind::Unterminated("attribute value"),
                        start,
                    ));
                }
                Some(b) if b == quote => {
                    self.pos += 1;
                    return Ok(out);
                }
                Some(b'<') => {
                    return Err(Error::new(
                        ErrorKind::IllegalCharacter('<'),
                        self.pos,
                    ));
                }
                Some(b'&') => self.value_reference(quote, &mut out)?,
                Some(_) => self.value_chars(quote, &mut out),
            }
        }
    }

    /// The quote that opens an attribute value, consumed.
    fn attribute_quote(&mut self) -> Result<u8> {
        match self.bytes.get(self.pos).copied() {
            None => Err(Error::new(ErrorKind::UnexpectedEof, self.pos)),
            Some(quote @ (b'"' | b'\'')) => {
                self.pos += 1;
                Ok(quote)
            }
            Some(_) => {
                Err(Error::new(ErrorKind::UnquotedAttributeValue, self.pos))
            }
        }
    }

    /// A reference in an attribute value, at `&`, expanded into `out`.
    fn value_reference(&mut self, quote: u8, out: &mut Run) -> Result<()> {
        let s = self.pos;
        self.pos += 1;
        let end = self
            .reference_len(quote)
            .ok_or_else(|| Error::new(ErrorKind::Unterminated("entity"), s))?;
        let ent = &self.input[self.pos..self.pos + end];
        // Normalisation happens inside the expansion, so that a
        // character reference within an entity's replacement text
        // stays exempt.
        let expanded = self.expand_entity(ent, s, true)?;
        out.push_owned(&expanded, self.input);
        self.pos += end + 1;
        Ok(())
    }

    /// Literal characters of an attribute value up to its closing
    /// `quote`, a `&` or a `<`, joined to `out` normalised.
    fn value_chars(&mut self, quote: u8, out: &mut Run) {
        // Stopping at `<` as well lets the caller report it. Without
        // this the run swallowed it, so `a="<x"` was rejected and
        // `a="1 < 2"` was not.
        let s = self.pos;
        while self.pos + 8 <= self.bytes.len() {
            let Ok(chunk) = self.bytes[self.pos..self.pos + 8].try_into()
            else {
                break;
            };
            let v = u64::from_ne_bytes(chunk);
            if Self::has_attr_delimiter(v, quote) {
                break;
            }
            self.pos += 8;
        }
        while self.pos < self.bytes.len()
            && self.bytes[self.pos] != quote
            && self.bytes[self.pos] != b'&'
            && self.bytes[self.pos] != b'<'
        {
            self.pos += 1;
        }
        // Normalisation only rewrites a value that contains a tab or a
        // line break, which almost none do. When it would change
        // nothing, the value is a slice of the input and costs nothing.
        let raw = &self.input[s..self.pos];
        if raw.bytes().any(|b| matches!(b, b'\t' | b'\n' | b'\r')) {
            let mut normalized = String::new();
            push_attribute_normalized(&mut normalized, raw);
            out.push_owned(&normalized, self.input);
        } else {
            out.push_slice(s, raw, self.input);
        }
    }

    pub(crate) fn parse_name(&mut self) -> Result<&'a str> {
        let name = self.parse_name_unchecked()?;
        if name.len() > self.limits.max_name_length {
            return Err(Error::new(ErrorKind::NameTooLong, self.pos));
        }
        Ok(name)
    }

    /// A name, borrowed from the input.
    ///
    /// Every name in a document is a slice of the input already, and
    /// copying each one out cost an allocation per element and per
    /// attribute -- roughly 12,000 on a 16,002-node document, all of
    /// them discarded immediately after the name was interned.
    ///
    /// The returned slice borrows the input rather than the parser, so
    /// it outlives the `&mut self` that produced it.
    fn parse_name_unchecked(&mut self) -> Result<&'a str> {
        // Copy the reference, so the result does not reborrow `self`.
        let input: &'a str = self.input;
        let start = self.pos;
        let rest = &input[self.pos..];
        let mut chars = rest.char_indices();
        match chars.next() {
            Some((_, c)) if self.is_name_start(c) => {}
            _ => {
                return Err(Error::new(ErrorKind::InvalidName, start));
            }
        }
        let mut end = rest.len();
        for (i, c) in rest.char_indices() {
            if !self.is_name_char(c) {
                end = i;
                break;
            }
        }
        self.pos = start + end;
        Ok(&rest[..end])
    }

    /// Split a `QName` and resolve its prefix.
    ///
    /// `is_element` matters: an unprefixed *element* name takes the
    /// default namespace, an unprefixed *attribute* name is in no
    /// namespace at all. Conflating the two is the classic namespace
    /// bug, so the distinction is a parameter rather than an
    /// assumption.
    /// Resolve a qualified name to borrowed parts, without allocating.
    ///
    /// The namespace URI is borrowed from the in-scope declarations and
    /// the local part from the input, so a name that has been seen
    /// before costs nothing to look up.
    fn resolve_parts<'q>(
        &'q self,
        qname: &'q str,
        is_element: bool,
        offset: usize,
    ) -> Result<(&'q str, Option<&'q str>)> {
        match qname.split_once(':') {
            Some((prefix, local)) => {
                // `xml` is bound by specification and never declared.
                if prefix == "xml" {
                    return Ok((
                        local,
                        Some("http://www.w3.org/XML/1998/namespace"),
                    ));
                }
                let uri = self.ns.resolve(prefix).ok_or_else(|| {
                    Error::new(
                        ErrorKind::UnboundPrefix(prefix.to_owned()),
                        offset,
                    )
                })?;
                Ok((local, Some(uri)))
            }
            None if is_element => match self.ns.resolve("") {
                Some(uri) if !uri.is_empty() => Ok((qname, Some(uri))),
                _ => Ok((qname, None)),
            },
            // An unprefixed *attribute* is in no namespace even when a
            // default namespace is declared. That asymmetry with
            // elements comes from the specification.
            None => Ok((qname, None)),
        }
    }

    /// Resolve a qualified name and intern it, in one step.
    ///
    /// Going through `expand` first allocated an `ExpandedName` for
    /// every element and attribute *before* the lookup, so interning
    /// reduced what the document retained and not what it allocated --
    /// the figure did not move at all. Looking up by borrowed parts
    /// means a repeated name costs a map probe and nothing else, and
    /// only a genuinely new name allocates.
    pub(crate) fn intern_qname(
        &mut self,
        qname: &str,
        is_element: bool,
        offset: usize,
    ) -> Result<crate::tree::NameId> {
        let prefix = qname.split_once(':').map(|(p, _)| p);
        {
            let (local, namespace) =
                self.resolve_parts(qname, is_element, offset)?;
            if let Some(candidates) = self.name_index.get(local) {
                for &id in candidates {
                    // The prefix has to match as well as the namespace.
                    // Two prefixes bound to one namespace expand to the
                    // same name, so keying on the expansion alone gave
                    // them one id -- and then `name()` had to report a
                    // single prefix for both, which is wrong for one of
                    // them. Distinct prefixes get distinct ids; the
                    // cost is one extra entry per prefix actually used.
                    if self.doc.names[id as usize].namespace.as_deref()
                        == namespace
                        && self.doc.name_prefixes[id as usize].as_deref()
                            == prefix
                    {
                        return Ok(crate::tree::NameId(id));
                    }
                }
            }
        }
        // Cold path: a name this document has not used before.
        let name = self.expand(qname, is_element, offset)?;
        Ok(self.intern(&name, prefix))
    }

    fn expand(
        &self,
        qname: &str,
        is_element: bool,
        offset: usize,
    ) -> Result<ExpandedName> {
        match qname.split_once(':') {
            Some((prefix, local)) => {
                // `xml` is bound by specification and never declared.
                if prefix == "xml" {
                    return Ok(ExpandedName::qualified(
                        "http://www.w3.org/XML/1998/namespace",
                        local,
                    ));
                }
                let uri = self.ns.resolve(prefix).ok_or_else(|| {
                    Error::new(
                        ErrorKind::UnboundPrefix(prefix.to_owned()),
                        offset,
                    )
                })?;
                Ok(ExpandedName::qualified(uri, local))
            }
            None => {
                if is_element {
                    match self.ns.resolve("") {
                        Some(uri) if !uri.is_empty() => {
                            Ok(ExpandedName::qualified(uri, qname))
                        }
                        _ => Ok(ExpandedName::local(qname)),
                    }
                } else {
                    Ok(ExpandedName::local(qname))
                }
            }
        }
    }

    pub(crate) fn peek_end_tag_name(&self) -> String {
        self.input[self.pos + 2..]
            .split(['>', ' ', '\t', '\n', '\r'])
            .next()
            .unwrap_or_default()
            .to_owned()
    }

    pub(crate) fn starts_with(&self, s: &str) -> bool {
        self.input[self.pos..].starts_with(s)
    }

    pub(crate) fn peek_is(&self, b: u8) -> bool {
        self.bytes.get(self.pos) == Some(&b)
    }

    pub(crate) fn skip_whitespace(&mut self) {
        while self.pos < self.bytes.len()
            && matches!(self.bytes[self.pos], b' ' | b'\t' | b'\r' | b'\n')
        {
            self.pos += 1;
        }
    }

    /// `NameStartChar`, for the edition in force.
    fn is_name_start(&self, c: char) -> bool {
        match self.limits.edition {
            crate::Edition::Fourth => crate::names4e::is_name_start_4e(c),
            _ => is_name_start(c),
        }
    }

    /// `NameChar`, for the edition in force.
    fn is_name_char(&self, c: char) -> bool {
        match self.limits.edition {
            crate::Edition::Fourth => crate::names4e::is_name_char_4e(c),
            _ => is_name_char(c),
        }
    }

    /// Resolve one entity reference, consulting the DTD.
    ///
    /// The five predefined entities and numeric character references
    /// resolve directly. Anything else must have been declared, and
    /// only *internal* declarations carry replacement text — `oxml`
    /// never fetches an external resource, which is what makes XXE
    /// structurally impossible rather than merely mitigated.
    ///
    /// An undeclared entity is an error only when the declaration was
    /// complete enough to be sure. If it had an external subset or
    /// referenced a parameter entity, the declaration may exist
    /// somewhere we did not read, and rejecting would be wrong.
    /// Expand one reference.
    ///
    /// `in_attribute` carries XML section 3.3.3 through the recursion:
    /// inside an attribute value, literal whitespace in an entity's
    /// replacement text becomes a space, but a **character reference**
    /// anywhere in it is exempt. Normalising the finished expansion
    /// instead would lose that distinction, because by then `&#xA;`
    /// and a literal newline are the same character.
    fn expand_entity(
        &mut self,
        ent: &str,
        offset: usize,
        in_attribute: bool,
    ) -> Result<String> {
        if let Some(direct) = self.predefined_reference(ent, offset)? {
            return Ok(direct);
        }
        let dtd = self.entity_declarations(ent, offset)?;
        match dtd.entity(ent) {
            Some(crate::dtd::EntityValue::Internal(text)) => {
                let text = text.clone();
                self.expand_internal_entity(ent, &text, offset, in_attribute)
            }
            // `WFC: No External Entity References`. In content an
            // external parsed entity expands to nothing, because
            // nothing is ever fetched; in an attribute value the
            // reference itself is forbidden.
            Some(crate::dtd::EntityValue::External { system, public }) => {
                let (system, public) = (system.clone(), public.clone());
                self.expand_external_entity(
                    ent,
                    &system,
                    public.as_deref(),
                    offset,
                    in_attribute,
                )
            }
            // `WFC: Parsed Entity`. An unparsed entity may not be
            // referenced anywhere -- it is not text and has no
            // replacement. Naming it as the value of an `ENTITY`-typed
            // attribute is a different construct and still allowed.
            Some(crate::dtd::EntityValue::Unparsed) => Err(Error::new(
                ErrorKind::ForbiddenEntityReference(ent.to_owned()),
                offset,
            )),
            // An entity we never found is normally forgiven: the
            // declaration may well be in a subset the caller did not
            // supply, and rejecting would fail valid documents.
            //
            // `standalone="yes"` withdraws that excuse. The document
            // has said there is nothing outside it depends on, so an
            // entity that is not declared inside it is undeclared --
            // whether or not an external subset exists and whether or
            // not it could be read.
            None => self.unresolved_entity(ent, offset, dtd.incomplete),
        }
    }

    fn entity_declarations(
        &self,
        ent: &str,
        offset: usize,
    ) -> Result<&crate::dtd::Dtd> {
        let dtd = self.dtd.as_ref().ok_or_else(|| {
            Error::new(ErrorKind::UnknownEntity(ent.to_owned()), offset)
        })?;
        // `WFC: Entity Declared`. With `standalone="yes"` the document
        // has promised it depends on nothing outside its internal
        // subset, so referencing an entity declared out there
        // contradicts the promise even when its declaration was found.
        if self.standalone && dtd.declared_externally.contains(ent) {
            return Err(Error::new(
                ErrorKind::ForbiddenEntityReference(ent.to_owned()),
                offset,
            ));
        }
        Ok(dtd)
    }

    fn unresolved_entity(
        &self,
        ent: &str,
        offset: usize,
        incomplete: bool,
    ) -> Result<String> {
        if incomplete && !self.standalone {
            return Ok(String::new());
        }
        Err(Error::new(ErrorKind::UnknownEntity(ent.to_owned()), offset))
    }

    fn predefined_reference(
        &self,
        ent: &str,
        offset: usize,
    ) -> Result<Option<String>> {
        let Some(direct) = decode_predefined(ent) else {
            return Ok(None);
        };
        // A character *reference* may not name a character the
        // `Char` production forbids. `&#0;` is illegal in both 1.0
        // and 1.1; the C0 controls are legal as references in 1.1
        // only. Decoding without this check accepted 65 documents
        // that are not well-formed.
        if let Some(bad) =
            direct.chars().find(|c| !is_xml_char_for(*c, self.version))
        {
            return Err(Error::new(ErrorKind::IllegalCharacter(bad), offset));
        }
        Ok(Some(direct))
    }

    fn expand_internal_entity(
        &mut self,
        ent: &str,
        text: &str,
        offset: usize,
        in_attribute: bool,
    ) -> Result<String> {
        // Included, not substituted: the replacement text of a
        // declared entity is markup where it lands.
        let replacement = self.replacement_text(text, offset)?;
        if in_attribute {
            Self::check_entity_in_attribute(&replacement, offset)?;
        } else {
            let key = (ent.to_owned(), self.ns.scope_id());
            if !self.entity_cache.contains(&key) {
                self.check_entity_as_content(&replacement, offset)?;
                let _ = self.entity_cache.insert(key);
            }
        }
        let mut budget = self.entity_budget;
        let out = self.expand_text(text, offset, 1, &mut budget, in_attribute);
        self.entity_budget = budget;
        out
    }

    fn expand_external_entity(
        &mut self,
        ent: &str,
        system: &str,
        public: Option<&str>,
        offset: usize,
        in_attribute: bool,
    ) -> Result<String> {
        if in_attribute {
            return Err(Error::new(
                ErrorKind::ForbiddenEntityReference(ent.to_owned()),
                offset,
            ));
        }
        // Whatever the caller made available, minus its text
        // declaration, which is markup about the entity rather
        // than part of it. Without a source this is `None` and
        // the reference expands to nothing, as before.

        match self.external.fetch(system, public) {
            Some(content) => self.expand_external_content(content, offset),
            None => Ok(String::new()),
        }
    }

    fn expand_external_content(
        &mut self,
        content: &str,
        offset: usize,
    ) -> Result<String> {
        self.limits.check_document(content.len(), offset)?;
        // Each external parsed entity has its own
        // version and is normalised independently. An
        // entity declaring 1.1 may use U+2028 as
        // whitespace -- including inside its own text
        // declaration, which is where this first showed
        // up: the declaration was reported malformed
        // because the separator had not been
        // normalised yet.
        let entity_version = entity_version(content, self.version);
        let normalized = normalize_line_endings(content, entity_version);
        let content: &str = &normalized;
        check_text_decl_position(content, offset)?;
        check_text_decl(content, self.version, offset)?;
        let body = strip_text_decl(content);
        // The content is parsed for illegal characters
        // the same way the document was; it arrived
        // from outside and is no more trusted.
        if let Some((at, c)) = body
            .char_indices()
            .find(|(_, c)| !is_literal_char_for(*c, self.version))
        {
            let _ = at;
            return Err(Error::new(ErrorKind::IllegalCharacter(c), offset));
        }
        // An external parsed entity is *included*
        // exactly as an internal one is, so its
        // replacement text is content and not
        // characters. Checking only internal entities
        // left `<root&#x85;/>` -- NEL, whitespace in
        // 1.1 and not in 1.0 -- accepted inside a 1.0
        // document, because nothing ever read the
        // replacement text as a tag.
        self.check_entity_as_content(body, offset)?;
        let mut budget = self.entity_budget;
        let out = self.expand_text(body, offset, 1, &mut budget, false);
        self.entity_budget = budget;
        out
    }

    /// Expand entity references inside replacement text.
    ///
    /// Bounded on both axes, because either alone is insufficient:
    /// depth stops the exponential billion-laughs shape, and the
    /// character budget stops the quadratic variant where one large
    /// entity is referenced many times at depth one.
    /// Append a run of literal text, normalising it when it is part of
    /// an attribute value.
    /// Intern an element name, returning a handle to it.
    ///
    /// Names repeat heavily -- a catalogue of 2,000 items has a handful
    /// of distinct element names -- so storing an `ExpandedName` per
    /// element allocated thousands of strings to hold a few values.
    fn intern(
        &mut self,
        name: &ExpandedName,
        prefix: Option<&str>,
    ) -> crate::tree::NameId {
        if let Some(candidates) = self.name_index.get(name.local.as_str()) {
            for &id in candidates {
                if self.doc.names[id as usize].namespace == name.namespace
                    && self.doc.name_prefixes[id as usize].as_deref() == prefix
                {
                    return crate::tree::NameId(id);
                }
            }
        }
        let id = u32::try_from(self.doc.names.len()).unwrap_or(u32::MAX);
        self.doc.names.push(name.clone());
        self.doc.name_prefixes.push(prefix.map(str::to_owned));
        self.name_index
            .entry(name.local.clone())
            .or_default()
            .push(id);
        crate::tree::NameId(id)
    }

    fn push_run(
        out: &mut String,
        text: &str,
        offset: usize,
        budget: &mut usize,
        in_attribute: bool,
    ) -> Result<()> {
        // `WFC: No < in Attribute Values`. A literal `<` is legal in an
        // entity's *value*, and illegal in an attribute value -- so an
        // entity whose replacement text contains one may not be
        // referenced from an attribute, however indirectly. Checking
        // here rather than on the finished expansion catches it at any
        // depth, and leaves `&#60;` alone: a character reference stands
        // for the character and is permitted.
        if in_attribute && text.contains('<') {
            return Err(Error::new(ErrorKind::IllegalCharacter('<'), offset));
        }
        if in_attribute && text.contains(['\n', '\t', '\r']) {
            let mut buf = String::with_capacity(text.len());
            push_attribute_normalized(&mut buf, text);
            return Self::push_bounded(out, &buf, offset, budget);
        }
        Self::push_bounded(out, text, offset, budget)
    }

    fn expand_text(
        &mut self,
        text: &str,
        offset: usize,
        depth: usize,
        budget: &mut usize,
        in_attribute: bool,
    ) -> Result<String> {
        if depth > self.limits.max_entity_depth {
            return Err(Error::new(ErrorKind::EntityLimitExceeded, offset));
        }
        let mut out = String::new();
        let mut rest = text;
        // A `&` inside a CDATA section is text, not a reference.
        // Scanning for `&` without knowing that reported
        // `<![CDATA[&foo;]]>` as a reference to an undeclared entity --
        // which is how enforcing `Entity Declared` here first broke a
        // document that was correct.
        while let Some(amp) = next_reference(rest) {
            let (before, tail) = rest.split_at(amp);
            Self::push_run(&mut out, before, offset, budget, in_attribute)?;
            let Some(semi) = tail.find(';') else {
                return Err(Error::new(
                    ErrorKind::UnknownEntity(tail.to_owned()),
                    offset,
                ));
            };
            let name = &tail[1..semi];
            rest = &tail[semi + 1..];
            if let Some(direct) = decode_predefined(name) {
                // A character reference is exempt from attribute-value
                // normalisation; the five named entities expand to
                // characters that normalisation would not touch, so
                // both take the literal path.
                Self::push_bounded(&mut out, &direct, offset, budget)?;
                continue;
            }
            let inner = match self.dtd.as_ref().and_then(|d| d.entity(name)) {
                Some(crate::dtd::EntityValue::Internal(t)) => t.clone(),
                // An indirect reference is still a reference: an
                // internal entity whose text names an external one is
                // forbidden in an attribute value just as a direct
                // reference is.
                Some(crate::dtd::EntityValue::External { .. })
                    if in_attribute =>
                {
                    return Err(Error::new(
                        ErrorKind::ForbiddenEntityReference(name.to_owned()),
                        offset,
                    ));
                }
                Some(crate::dtd::EntityValue::Unparsed) => {
                    return Err(Error::new(
                        ErrorKind::ForbiddenEntityReference(name.to_owned()),
                        offset,
                    ));
                }
                // An entity named inside another entity's replacement
                // text must itself be declared. Skipping the reference
                // silently produced a document missing the content it
                // asked for, with nothing to say so.
                None if self.standalone
                    || !self.dtd.as_ref().is_some_and(|d| d.incomplete) =>
                {
                    return Err(Error::new(
                        ErrorKind::UnknownEntity(name.to_owned()),
                        offset,
                    ));
                }
                _ => continue,
            };
            // Already normalised by the recursive call if needed.
            let expanded = self.expand_text(
                &inner,
                offset,
                depth + 1,
                budget,
                in_attribute,
            )?;
            Self::push_bounded(&mut out, &expanded, offset, budget)?;
        }
        Self::push_run(&mut out, rest, offset, budget, in_attribute)?;
        Ok(out)
    }

    fn push_bounded(
        out: &mut String,
        text: &str,
        offset: usize,
        budget: &mut usize,
    ) -> Result<()> {
        if *budget < text.len() {
            return Err(Error::new(ErrorKind::EntityLimitExceeded, offset));
        }
        *budget -= text.len();
        out.push_str(text);
        Ok(())
    }
}

/// Resolve one entity reference.
///
/// Returns `None` when `ent` is a declared-entity name rather than one
/// of the five predefined entities or a numeric character reference —
/// resolving those needs the DTD, and is done by `expand_entity`.
fn decode_predefined(ent: &str) -> Option<String> {
    let out = match ent {
        "lt" => "<".to_owned(),
        "gt" => ">".to_owned(),
        "amp" => "&".to_owned(),
        "apos" => "'".to_owned(),
        "quot" => "\"".to_owned(),
        _ => {
            // Not a character reference at all means it is a declared
            // name, and resolving that needs the DTD.
            let cp = match ent.strip_prefix("#x") {
                Some(hex) => u32::from_str_radix(hex, 16).ok()?,
                None => ent.strip_prefix('#')?.parse::<u32>().ok()?,
            };
            let ch = char::from_u32(cp)?;
            let mut s = String::new();
            s.push(ch);
            s
        }
    };
    Some(out)
}

/// Check the structure of an XML declaration.
///
/// ```text
/// XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
/// ```
///
/// The pseudo-attributes are **ordered** and each must be preceded by
/// whitespace. Scanning to `?>` without checking accepts
/// `version="1.0"standalone="yes"`, which has no separating space, and
/// accepts them in the wrong order.
/// Whether `value` matches `VersionNum ::= '1.' [0-9]+`.
///
/// Which version the parser then *implements* is a separate question,
/// answered by [`declared_version`]: `1.2` is a well-formed version
/// number naming a version this crate does not support, and the two
/// failures are different.
fn is_legal_version(value: &str) -> bool {
    value.strip_prefix("1.").is_some_and(|digits| {
        !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
    })
}

/// An external entity's content without its text declaration.
///
/// The declaration describes the entity; it is not part of it, and
/// leaving it in would put `<?xml …?>` into the document as text.
/// The version an external entity declares, or the document's.
///
/// An entity with no text declaration inherits the document's version;
/// one that declares its own uses that. The distinction matters before
/// normalisation, because which characters are line terminators
/// depends on it.
pub(crate) fn entity_version(content: &str, document: Version) -> Version {
    let Some(rest) = content.strip_prefix("<?xml") else {
        return document;
    };
    if !rest.starts_with([' ', '\t', '\r', '\n']) {
        return document;
    }
    match declared_version(content) {
        // No `version` pseudo-attribute: `declared_version` answers
        // 1.0 by default, but an entity without one inherits.
        Ok(Version::V10) if !rest.contains("version") => document,
        Ok(version) => version,
        Err(_) => document,
    }
}

/// Reject a text declaration that is not where one may be.
///
/// `extParsedEnt ::= TextDecl? content` -- the declaration comes first
/// or not at all. A blank line before it, or content before it, makes
/// it an ordinary processing instruction with the reserved target
/// `xml`, which is not legal anywhere.
///
/// The target is reserved case-insensitively, so `<?XML …?>` is an
/// error even at the start: `TextDecl` spells it in lower case.
pub(crate) fn check_text_decl_position(
    content: &str,
    offset: usize,
) -> Result<()> {
    let mut at = 0;
    while let Some(i) = content[at..].find("<?") {
        let start = at + i;
        let after = &content[start + 2..];
        let end = after
            .find(|c: char| c.is_whitespace() || c == '?')
            .unwrap_or(after.len());
        let target = &after[..end];
        if target.eq_ignore_ascii_case("xml") && (start != 0 || target != "xml")
        {
            return Err(Error::new(ErrorKind::ReservedPiTarget, offset));
        }
        at = start + 2;
    }
    Ok(())
}

pub(crate) fn strip_text_decl(content: &str) -> &str {
    let Some(rest) = content.strip_prefix("<?xml") else {
        return content;
    };
    if !rest.starts_with([' ', '\t', '\r', '\n']) {
        return content;
    }
    match rest.find("?>") {
        Some(end) => &rest[end + 2..],
        None => content,
    }
}

/// Trim leading **XML** whitespace, which is not Rust's.
///
/// `S ::= (#x20 | #x9 | #xD | #xA)+` — four characters, in both 1.0
/// and 1.1. Rust's `trim_start` follows Unicode and also strips NEL
/// (#x85) and LSEP (#x2028), which is exactly wrong here: XML 1.1
/// treats those two as *line ends* and normalises them to #xA before
/// anything is parsed, so one that survives to be read as a separator
/// is in 1.0 content, where it is not whitespace at all.
///
/// Using Rust's version accepted
/// `<?xml version='1.0'<LSEP>encoding='UTF-8'?>` in an entity
/// declaring 1.0.
fn trim_xml_start(s: &str) -> &str {
    s.trim_start_matches([' ', '\t', '\r', '\n'])
}

/// Check the text declaration at the head of an external entity.
///
/// `TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>'`, and it
/// differs from a document's XML declaration in three ways that the
/// conformance suite tests heavily:
///
/// * `encoding` is **mandatory** here and optional there;
/// * `standalone` is **forbidden** here -- only a document may say it;
/// * the version, if given, may not be later than the document's. A
///   1.1 document may include a 1.0 entity; a 1.0 document may not
///   include a 1.1 one.
pub(crate) fn check_text_decl(
    content: &str,
    document_version: Version,
    offset: usize,
) -> Result<()> {
    let Some(rest) = content.strip_prefix("<?xml") else {
        // A text declaration is optional; its absence says nothing.
        return Ok(());
    };
    // `<?xmlfoo?>` is a processing instruction, not a declaration --
    // and a reserved target, which the parser proper reports.
    if !rest.starts_with([' ', '\t', '\r', '\n']) {
        return Ok(());
    }
    let Some(end) = rest.find("?>") else {
        return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
    };
    let decl = &rest[..end];

    // The same grammar as a document's declaration, so the same
    // checker: order, duplicates, quoting, legal values.
    validate_xml_declaration(decl, offset, false)?;

    let field = |name: &str| -> Option<&str> {
        let at = decl.find(name)?;
        let after = trim_xml_start(&decl[at + name.len()..]);
        let after = trim_xml_start(after.strip_prefix('=')?);
        let quote = after.chars().next()?;
        let body = after.get(1..)?;
        let close = body.find(quote)?;
        body.get(..close)
    };

    if field("encoding").is_none() {
        return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
    }
    if field("standalone").is_some() {
        return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
    }
    if let Some(version) = field("version") {
        let entity_is_11 = version == "1.1";
        if entity_is_11 && document_version == Version::V10 {
            return Err(Error::new(ErrorKind::UnsupportedVersion, offset));
        }
    }
    Ok(())
}

fn validate_xml_declaration(
    decl: &str,
    offset: usize,
    require_version: bool,
) -> Result<()> {
    let mut rest = decl;
    let mut seen: Vec<&str> = Vec::new();

    loop {
        let trimmed = trim_xml_start(rest);
        if trimmed.is_empty() {
            break;
        }
        // Each pseudo-attribute must be separated from what precedes it
        // by whitespace.
        if trimmed.len() == rest.len() {
            return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
        }
        rest = trimmed;

        let name_end = rest
            .find(|c: char| !c.is_ascii_alphabetic())
            .unwrap_or(rest.len());
        let name = &rest[..name_end];
        if !matches!(name, "version" | "encoding" | "standalone") {
            return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
        }
        if seen.contains(&name) {
            return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
        }
        // Order is fixed by the grammar, not merely conventional.
        let rank = |n: &str| match n {
            "version" => 0u8,
            "encoding" => 1,
            _ => 2,
        };
        if seen.last().is_some_and(|prev| rank(name) <= rank(prev)) {
            return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
        }
        seen.push(name);

        let after = trim_xml_start(&rest[name_end..]);
        let Some(after) = after.strip_prefix('=') else {
            return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
        };
        let after = trim_xml_start(after);
        let Some(quote) =
            after.chars().next().filter(|c| *c == '"' || *c == '\'')
        else {
            return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
        };
        let body = &after[1..];
        let Some(close) = body.find(quote) else {
            return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
        };
        let value = &body[..close];
        match name {
            // `VersionNum ::= '1.' [0-9]+`. There was no arm for this
            // at all, so `version="1.0 "`, `"1.0?"` and `"1.0^"` were
            // accepted -- the declaration's own version string was the
            // one field nothing checked.
            "version" if !is_legal_version(value) => {
                return Err(Error::new(
                    ErrorKind::MalformedDeclaration,
                    offset,
                ));
            }
            "standalone" if !matches!(value, "yes" | "no") => {
                return Err(Error::new(
                    ErrorKind::MalformedDeclaration,
                    offset,
                ));
            }
            "encoding" if !crate::encoding::is_legal_encoding_name(value) => {
                return Err(Error::new(
                    ErrorKind::MalformedDeclaration,
                    offset,
                ));
            }
            _ => {}
        }
        rest = &body[close + 1..];
    }

    // `VersionInfo` is required in a document's XML declaration and
    // **optional** in an external entity's text declaration --
    // `TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>'`. Reusing
    // this checker without the distinction rejected
    // `<?xml encoding="UTF-8"?>`, which is a perfectly ordinary way to
    // begin an entity.
    if require_version && seen.first() != Some(&"version") {
        return Err(Error::new(ErrorKind::MalformedDeclaration, offset));
    }
    Ok(())
}

/// The XML version the declaration names, defaulting to 1.0.
///
/// # Errors
///
/// Returns [`Error`] if the version is not one this parser implements.
/// Whether the document declares `standalone="yes"`.
///
/// It is not merely a hint to the application. XML 1.0 section 2.9
/// makes it a well-formedness matter: with `yes`, the *WFC: Entity
/// Declared* constraint stops being relaxed for declarations that came
/// from outside the internal subset, because the document has promised
/// there is nothing out there it depends on.
pub(crate) fn declared_standalone(input: &str) -> bool {
    let Some(decl) = xml_declaration(input) else {
        return false;
    };
    let Some(at) = decl.find("standalone") else {
        return false;
    };
    let after = trim_xml_start(&decl[at + "standalone".len()..]);
    let Some(after) = after.strip_prefix('=') else {
        return false;
    };
    let after = trim_xml_start(after);
    let Some(quote) = after.chars().next() else {
        return false;
    };
    if quote != '"' && quote != '\'' {
        return false;
    }
    let body = &after[1..];
    body.find(quote)
        .is_some_and(|close| &body[..close] == "yes")
}

/// The body of the XML declaration at the start of `input`, if there
/// is one: the text between `<?xml` and `?>`.
///
/// `<?xml` must be followed by XML whitespace. A processing
/// instruction whose target merely *starts* with `xml` --
/// `<?xml-stylesheet ...?>` is the common one, and it is legal at
/// offset 0 when the document has no declaration -- is not a
/// declaration, and reading it as one let its attribute values act as
/// `version`, `standalone` and `encoding` pseudo-attributes.
pub(crate) fn xml_declaration(input: &str) -> Option<&str> {
    let rest = input.strip_prefix("<?xml")?;
    if !rest.starts_with([' ', '\t', '\r', '\n']) {
        return None;
    }
    let end = rest.find("?>")?;
    Some(&rest[..end])
}

pub(crate) fn declared_version(input: &str) -> Result<Version> {
    let Some(decl) = xml_declaration(input) else {
        return Ok(Version::V10);
    };
    let Some(at) = decl.find("version") else {
        return Ok(Version::V10);
    };
    let after = decl[at + "version".len()..].trim_start();
    let Some(after) = after.strip_prefix('=') else {
        return Ok(Version::V10);
    };
    let after = after.trim_start();
    let Some(quote) = after.chars().next() else {
        return Ok(Version::V10);
    };
    if quote != '"' && quote != '\'' {
        return Ok(Version::V10);
    }
    let body = &after[1..];
    let Some(close) = body.find(quote) else {
        return Ok(Version::V10);
    };
    match &body[..close] {
        "1.0" => Ok(Version::V10),
        "1.1" => Ok(Version::V11),
        // XML 1.0 5th edition made an unrecognised 1.x version a
        // *forwards-compatibility* matter rather than an error: a 1.0
        // processor should accept the document and process it as 1.0.
        v if v.starts_with("1.") => Ok(Version::V10),
        _ => Err(Error::new(ErrorKind::UnsupportedVersion, 0)),
    }
}