libxml-rs 0.1.0-alpha.50

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure; three-DSO ELF packaging (libxml2.so.16 core + libxslt.so.1/libexslt.so.0 facades, upstream NEEDED chain); fail-closed oracle-isolated ABI-FUNCTION-SIGNATURE plane (SOURCE_PROTOTYPE + MACHINE_ABI fingerprints, zero silent omissions); Phase-12 real downstream substitution (binary/static/docker substitution, export-surface disposition, ELF version graphs); Phase-13 hostile audit courts (ABI/ownership/allocator/callbacks/failure/threads/oracle-contamination) byte-identical vs the system oracle incl. the upstream thread-local globals model; Phase-14 downstream custodian validation courts (lxml/Nokogiri/PHP/Debian). Test counts live in atlas/TEST_COUNTS.json, residuals in atlas/RESIDUAL_LEDGER.json (generated evidence).
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
//! Default SAX2 handler — builds a DOM tree from SAX events (§20, §85 Phase 3).
//!
//! These are the default implementations that populate a `_xmlSAXHandler` when
//! `xmlSAX2InitDefaultSAXHandler` is called. They reconstruct the document tree
//! from the sequence of SAX callbacks, mirroring the upstream behavior of
//! `xmlSAX2DefaultSAXHandler` / `xmlSAX2*` functions in libxml2's `SAX2.c`.
//!
//! # Upstream contract
//!
//! The parity target is the SAX2 default-handler path of libxml2 2.15.3
//! (`SRC-LIBXML2-2.15.0-SAX2-C`). A consumer that installs the default SAX
//! handler and feeds it events must see the same tree topology that upstream
//! builds: element/attribute/namespace wiring, entity substitution, text
//! compaction, and the namespace-declaration list all come from these
//! handlers.
//!
//! # Architecture
//!
//! The parser context (`_xmlParserCtxt`) is stored as `userData` (the `ctx`
//! pointer passed to every SAX callback). The default handlers use this context to:
//!
//! - Access the document being built (`myDoc`)
//! - Manage the element stack (`nodeTab`, `nodeNr`, `nodeMax`)
//! - Access the current element (`node`)
//!
//! # UPSTREAM-PARITY
//!
//! These functions correspond to the `xmlSAX2*` function family in upstream
//! libxml2 (`SAX2.c`), which are the default SAX2 handlers installed by
//! `xmlSAX2InitDefaultSAXHandler`.
//!
//! # Historical quirks & epochs
//!
//! The namespace-aware SAX2 callback surface became the default parser path
//! in the 2.5 era (HISTORY.md); since then the tree-building contract has
//! been stable through 2.15.3. R-000147 (11.1-L) established that the
//! tree namespace model is populated here — the handler must resolve
//! attribute prefixes against the parser namespace scope, never against the
//! node current tree state.
//!
//! # Proving courts
//!
//! The PARSER, TREE-STRUCTURE and CALLBACK court families exercise this
//! surface; the CLI-XMLLINT corpus (47 byte-identical cases) builds trees
//! through the default handlers, and the callback-family probe requires
//! byte-identical handler-slot patterns against the oracle DSO.
//!
//! # Tempting simplifications that would break parity
//!
//! A tempting simplification is to build attributes/namespaces directly from
//! the element properties when handling StartElementNS. R-000147 proved the
//! prefix resolution must consult the parser namespace scope (ancestor
//! declarations), not the partially-built node — otherwise
//! namespace-declaration order and undefined-prefix behavior diverge from
//! the oracle and the CLI corpus regresses.

#![allow(non_snake_case)]

use core::ffi::c_void;
use core::ptr;
use std::os::raw::{c_char, c_int};

use crate::abi::allocator;
use crate::abi::callbacks::*;
use crate::abi::structs::*;
use crate::abi::types::xmlChar;
use crate::abi::types::xmlDocProperties::{XML_DOC_DTDVALID, XML_DOC_NSVALID, XML_DOC_WELLFORMED};
use crate::abi::types::xmlElementType::*;
use crate::abi::types::XML_PARSE_COMPACT;
use crate::xml::tree;

/// Default SAX2 handlers that build a DOM tree from SAX events.
pub(crate) mod default_sax_handler {
    use super::*;

    // ═══════════════════════════════════════════════════════════════════════
    // Helper: extract the parser context from the SAX user data pointer
    // ═══════════════════════════════════════════════════════════════════════

    /// Extract the parser context from the SAX callback `ctx` pointer.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt` that was passed
    ///   as `userData` to the SAX handler.
    /// - The caller must ensure the context is still alive and valid.
    const unsafe fn ctxt_from_ctx(ctx: *mut c_void) -> *mut _xmlParserCtxt {
        ctx as *mut _xmlParserCtxt
    }

    /// Current source line from the parser input (0 when unavailable).
    unsafe fn current_line(ctxt: *mut _xmlParserCtxt) -> u16 {
        if ctxt.is_null() || (*ctxt).input.is_null() {
            return 0;
        }
        let l = (*(*ctxt).input).line;
        if l < 0 {
            0
        } else {
            l as u16
        }
    }

    /// Raise a NON-fatal parser error at the current input position through
    /// the parser's generic/streamed error channel (upstream `xmlCtxtVErr`),
    /// used by the default tree-builder callbacks (e.g. the duplicate-ID
    /// report from SAX2 attribute registration, which upstream raises via
    /// `xmlAddID(&ctxt->vctxt, ...)` at the attribute's line).
    ///
    /// # Safety
    ///
    /// - `ctxt` must be a valid parser context; `msg` a valid C string.
    #[allow(clippy::too_many_arguments)]
    unsafe fn raise_ctxt_validity_error(
        ctxt: *mut _xmlParserCtxt,
        code: c_int,
        msg: *const c_char,
    ) {
        unsafe {
            let mut file_ptr: *const c_char = ptr::null();
            let mut line: c_int = 0;
            let mut col: c_int = 0;
            let mut window: Option<(Vec<u8>, usize)> = None;
            if !(*ctxt).input.is_null() {
                let inp = &*(*ctxt).input;
                file_ptr = inp.filename as *const c_char;
                line = inp.line;
                col = inp.col;
                if !inp.base.is_null()
                    && !inp.end.is_null()
                    && (inp.end as usize) >= (inp.base as usize)
                {
                    let len = inp.end.offset_from(inp.base) as usize;
                    let data = core::slice::from_raw_parts(inp.base, len);
                    let byte_pos = if !inp.cur.is_null() {
                        inp.cur.offset_from(inp.base) as usize
                    } else {
                        0
                    };
                    window = crate::xml::parser::tokenizer::window_at_data(data, byte_pos);
                }
            }
            (*ctxt).nbErrors = (*ctxt).nbErrors.wrapping_add(1);
            let delivery = crate::xml::errors::parser_delivery(ctxt);
            let window_ref = window.as_ref().map(|(w, caret)| (w.as_slice(), *caret));
            crate::xml::errors::raise_error_streamed(
                ctxt as *mut c_void,
                crate::abi::types::XML_FROM_VALID,
                code,
                crate::abi::types::xmlErrorLevel::XML_ERR_ERROR as c_int,
                file_ptr,
                line,
                col,
                ptr::null(),
                ptr::null(),
                ptr::null(),
                0,
                msg,
                window_ref,
                None,
                delivery,
                None,
            );
        }
    }

    /// Merge character data into an existing text node (upstream
    /// `xmlNodeAddContent` semantics): the bytes are appended to the node's
    /// own content buffer, keeping the tree flat (a single text node).
    ///
    /// Compact (inline) content is promoted to a heap allocation on the first
    /// merge — an interrupted character-data stream (e.g. an entity
    /// reference) is never compact, matching the oracle's debug output.
    ///
    /// # Safety
    ///
    /// - `node` must be NULL or a valid `_xmlNode` that stays alive for the
    ///   call; `ch` must be NULL or a valid buffer of at least `len` bytes;
    ///   when the node's content is heap-allocated it must be an
    ///   `xmlReallocImpl`-compatible allocation; the caller must not mutate
    ///   the node or `ch` concurrently.
    unsafe fn merge_into_text_node(node: *mut _xmlNode, ch: *const xmlChar, len: c_int) {
        if node.is_null() || ch.is_null() || len <= 0 {
            return;
        }
        unsafe {
            let existing_len = crate::xml::string::xml_strlen((*node).content);
            let total = existing_len + len as usize;
            if content_is_inline(node) {
                // The current content lives inside the node struct; promote
                // it to a heap buffer before appending.
                let merged = allocator::xmlMallocImpl(total + 1) as *mut xmlChar;
                if merged.is_null() {
                    return;
                }
                ptr::copy_nonoverlapping((*node).content, merged, existing_len);
                ptr::copy_nonoverlapping(ch, merged.add(existing_len), len as usize);
                *merged.add(total) = 0;
                (*node).content = merged;
            } else {
                let new = allocator::xmlReallocImpl((*node).content as *mut c_void, total + 1)
                    as *mut xmlChar;
                if new.is_null() {
                    return;
                }
                ptr::copy_nonoverlapping(ch, new.add(existing_len), len as usize);
                *new.add(total) = 0;
                (*node).content = new;
            }
        }
    }

    /// True when the node's `content` points into its own struct (compact
    /// text storage, as produced by the parser under `XML_PARSE_COMPACT`).
    ///
    /// UPSTREAM-PARITY: `debugXML.c` identifies compact text via
    /// `node->content == (xmlChar *) &(node->properties)`; the parser stores
    /// short strings in the memory occupied by the unused `properties` field.
    ///
    /// # Safety
    ///
    /// - `node` must be NULL or a valid, initialized `_xmlNode` that stays
    ///   alive for the call; the `content` and `properties` fields are only
    ///   read and compared as addresses.
    unsafe fn content_is_inline(node: *mut _xmlNode) -> bool {
        if node.is_null() {
            return false;
        }
        unsafe {
            let inline_addr =
                std::ptr::addr_of_mut!((*node).properties) as *mut xmlChar as *const c_void;
            (*node).content as *const c_void == inline_addr
        }
    }

    /// Create a parser text node holding `len` bytes of character data.
    ///
    /// UPSTREAM-PARITY: `xmlSAX2TextNode` (SAX2.c) stores short strings
    /// (`len < 2 * sizeof(void*)`) inside the node struct, overriding the
    /// unused `properties` and `nsDef` fields, when `XML_PARSE_COMPACT` is
    /// set:
    ///
    /// ```c
    /// if ((len < (int) (2 * sizeof(void *))) &&
    ///     (ctxt->options & XML_PARSE_COMPACT)) {
    ///     xmlChar *tmp = (xmlChar *) &(ret->properties);
    ///     memcpy(tmp, str, len);
    ///     tmp[len] = 0;
    ///     intern = tmp;
    /// }
    /// ```
    ///
    /// Returns the new node, or NULL on allocation failure.
    ///
    /// # Safety
    ///
    /// - `ctxt` must be NULL or a valid `_xmlParserCtxt` that stays alive
    ///   for the call; `ch` must be a valid buffer of at least `len` bytes;
    ///   the returned node owns its allocations and must eventually be
    ///   freed through the tree ownership contract; the caller must not
    ///   race this call with mutation of `ctxt`.
    unsafe fn parser_new_text_node(
        ctxt: *mut _xmlParserCtxt,
        ch: *const xmlChar,
        len: c_int,
        force_noncompact: bool,
    ) -> *mut _xmlNode {
        unsafe {
            let compact = !force_noncompact
                && !ctxt.is_null()
                && ((*ctxt).options & XML_PARSE_COMPACT) != 0
                && (len as usize) < 16;
            if compact {
                let node = allocator::xmlMallocZero(size_of::<_xmlNode>()) as *mut _xmlNode;
                if !node.is_null() {
                    (*node).type_ = XML_TEXT_NODE as c_int;
                    (*node).name = allocator::xmlMemStrdupImpl(c"text".as_ptr() as *const c_char)
                        as *mut xmlChar;
                    let inline = std::ptr::addr_of_mut!((*node).properties) as *mut xmlChar;
                    ptr::copy_nonoverlapping(ch, inline, len as usize);
                    *inline.add(len as usize) = 0;
                    (*node).content = inline;
                    // UPSTREAM-PARITY (tree.c): registration hook fires
                    // after the node is fully initialised.
                    crate::abi::data_globals::register_node_hook(node);
                }
                node
            } else {
                // Create a null-terminated copy of the character data.
                let content = allocator::xmlMallocImpl((len + 1) as usize) as *mut xmlChar;
                if content.is_null() {
                    return ptr::null_mut();
                }
                ptr::copy_nonoverlapping(ch, content, len as usize);
                *content.add(len as usize) = 0;

                let text = tree::new_text(content as *const xmlChar);
                allocator::xmlFreeImpl(content as *mut c_void);
                text
            }
        }
    }

    /// Build the attribute's value children from a (reference-substituted)
    /// value string, mirroring upstream tree.c `xmlNodeParseAttValue` at the
    /// tree layer. The tokenizer already resolved character references,
    /// predefined entities and (under XML_PARSE_NOENT) declared entities, so
    /// the value can only contain plain text and UNSUBSTITUTED general
    /// entity references `&name;` — those become XML_ENTITY_REF_NODE
    /// children (with the entity attached), text runs become text nodes, and
    /// any other stray `&` (resolved-text from `&amp;`, or a `&#...`-looking
    /// run) stays text. Upstream keeps declared-entity references in
    /// attribute values as entity-ref children and every serializer
    /// re-emits them as `&name;` (gh19612 / the modern serialize_entity_reference
    /// family); with NOENT the refs are already gone and a single text node
    /// results.
    ///
    /// `attr->children`/`last` must already be NULL.
    ///
    /// # Safety
    ///
    /// - `ctxt`/`attr` must be valid; `value` must be readable for `len`
    ///   bytes (NUL-termination not required).
    unsafe fn parser_build_attr_children(
        ctxt: *mut _xmlParserCtxt,
        attr: *mut _xmlAttr,
        value: *const xmlChar,
        len: c_int,
        had_ref: bool,
    ) {
        if attr.is_null() || value.is_null() || len <= 0 {
            return;
        }
        let bytes = unsafe { core::slice::from_raw_parts(value, len as usize) };
        let mut head: *mut _xmlNode = ptr::null_mut();
        let mut last: *mut _xmlNode = ptr::null_mut();
        let mut i = 0usize;
        let mut run_start = 0usize;
        let mut any_ref = false;
        let doc = unsafe { (*ctxt).myDoc };

        macro_rules! flush_text_run {
            ($end:expr) => {{
                let run_len = $end - run_start;
                if run_len > 0 {
                    let text = unsafe {
                        parser_new_text_node(
                            ctxt,
                            value.add(run_start),
                            run_len as c_int,
                            // had-ref values never compact (R-000120); the
                            // multi-node builder only runs for them.
                            true,
                        )
                    };
                    if !text.is_null() {
                        unsafe {
                            (*text).parent = attr as *mut _xmlNode;
                            (*text).doc = doc;
                            if last.is_null() {
                                head = text;
                            } else {
                                (*last).next = text;
                                (*text).prev = last;
                            }
                            last = text;
                        }
                    }
                }
            }};
        }

        while i < bytes.len() {
            if bytes[i] == b'&' {
                // Scan for the terminating ';' of a possible reference.
                let mut j = i + 1;
                while j < bytes.len() && bytes[j] != b';' {
                    j += 1;
                }
                let name_is_ref =
                    j < bytes.len() && j > i + 1 && bytes[i + 1] != b'#' && bytes[i + 1] != b'&';
                if name_is_ref {
                    any_ref = true;
                    flush_text_run!(i);
                    // Create the ENTITY_REF node (upstream xmlNodeParseAttValue
                    // general-entity branch; the node borrows the entity's
                    // content and links the declaration as its only child).
                    let name = &bytes[i + 1..j];
                    let mut name_c = name.to_vec();
                    name_c.push(0);
                    let ent = unsafe {
                        crate::xml::entities::get_entity(doc, name_c.as_ptr() as *const xmlChar)
                    };
                    let is_predef = !ent.is_null()
                        && (*ent).etype
                            == crate::abi::types::xmlEntityType::XML_INTERNAL_PREDEFINED_ENTITY
                                as c_int;
                    // Candidate flag convention (parser/state.rs
                    // parse_entity_content): XML_ENT_PARSED = 1 << 0,
                    // XML_ENT_EXPANDING = 1 << 3.
                    const XML_ENT_PARSED: c_int = 1 << 0;
                    const XML_ENT_EXPANDING: c_int = 1 << 3;
                    if !ent.is_null() && !is_predef && (*ent).flags & XML_ENT_EXPANDING != 0 {
                        // Cycle guard: an entity whose replacement is being
                        // materialized right now does not create a reference
                        // node at all (upstream xmlNodeParseAttValue).
                        i = j + 1;
                        run_start = i;
                        continue;
                    }
                    // UPSTREAM-PARITY (tree.c xmlNodeParseAttValue): when an
                    // internal entity is referenced in an attribute value the
                    // declaration's CHILD tree is materialized from its
                    // content once (XML_ENT_PARSED), so the value reader can
                    // expand the reference through the declaration children
                    // (css_selectors/entities, token_list/entities — the tree
                    // keeps `&name;` for round-trip serialization while
                    // getAttribute reads the expanded value).
                    if !ent.is_null()
                        && !is_predef
                        && (*ent).flags & XML_ENT_PARSED == 0
                        && !(*ent).content.is_null()
                    {
                        (*ent).flags |= XML_ENT_EXPANDING;
                        let c = (*ent).content;
                        let clen = unsafe { libc::strlen(c as *const c_char) } as c_int;
                        if clen > 0 {
                            let ent_attr = ent as *mut _xmlAttr;
                            // Parse the entity content into the declaration's
                            // children (self-recursion; the EXPANDING flag
                            // prevents cycles).
                            parser_build_attr_children(ctxt, ent_attr, c, clen, true);
                        }
                        (*ent).flags &= !XML_ENT_EXPANDING;
                        (*ent).flags |= XML_ENT_PARSED;
                    }
                    let node = unsafe {
                        crate::abi::allocator::xmlMallocZero(core::mem::size_of::<_xmlNode>())
                            as *mut _xmlNode
                    };
                    if !node.is_null() {
                        unsafe {
                            (*node).type_ = XML_ENTITY_REF_NODE as c_int;
                            (*node).name = crate::xml::string::xml_strndup(
                                name_c.as_ptr() as *const xmlChar,
                                name.len(),
                            );
                            (*node).doc = doc;
                            (*node).parent = attr as *mut _xmlNode;
                            if !ent.is_null() {
                                (*node).content = (*ent).content;
                                (*node).children = ent as *mut _xmlNode;
                                (*node).last = ent as *mut _xmlNode;
                            }
                            if last.is_null() {
                                head = node;
                            } else {
                                (*last).next = node;
                                (*node).prev = last;
                            }
                            last = node;
                            crate::abi::data_globals::register_node_hook(node);
                        }
                    }
                    i = j + 1;
                    run_start = i;
                    continue;
                }
            }
            i += 1;
        }
        flush_text_run!(bytes.len());

        if any_ref && !head.is_null() {
            unsafe {
                (*attr).children = head;
                (*attr).last = last;
            }
        } else if head.is_null() {
            // No general reference survived substitution (e.g. `&amp;` only)
            // AND no text run was flushed — build a single text node,
            // non-compact because the raw value had a reference (upstream's
            // dup'd-value text node, R-000120).
            let text = unsafe { parser_new_text_node(ctxt, value, len, had_ref) };
            if !text.is_null() {
                unsafe {
                    (*text).parent = attr as *mut _xmlNode;
                    (*text).doc = doc;
                    (*attr).children = text;
                    (*attr).last = text;
                }
            }
        } else {
            // any_ref == false: the final flush_text_run! above already built
            // exactly one full-length text node into head/last (no reference
            // boundaries were crossed). Reusing it avoids leaking that node
            // (Phase 16 ASan fuzz finding: one _xmlNode per entity-bearing
            // attribute value whose substitution contained no general
            // reference, e.g. `x="&amp;"`).
            unsafe {
                (*attr).children = head;
                (*attr).last = last;
            }
        }
    }
    /// Set an attribute on `node` with `len` bytes of value, mirroring
    /// `tree::set_prop` but building the value text node with
    /// `parser_new_text_node` so short attribute values are compact under
    /// `XML_PARSE_COMPACT` (upstream `xmlSAX2AttributeNs` behavior).
    ///
    /// `had_ref` mirrors upstream's dup-detection: when the raw attribute
    /// value contained an entity/character reference, the parser passes a
    /// non-NULL valueEnd (the value was duplicated and null-terminated) and
    /// `xmlSAX2AttributeNs` builds the value through `xmlNodeParseAttValue`,
    /// which never produces compact text. The candidate's tokenizer decodes
    /// references before this layer, so the signal is carried explicitly and
    /// forces the non-compact path (R-000120); surviving general references
    /// become entity-ref children (`parser_build_attr_children`).
    ///
    /// Returns the attribute, or NULL on failure.
    ///
    /// # Safety
    ///
    /// - `ctxt` must be a valid `_xmlParserCtxt`; `node` must be a valid
    ///   `_xmlNode`; `name`, `prefix` and `value` must be NULL or valid
    ///   NUL-terminated strings, and `value` must be readable for
    ///   `value_len` bytes; the node, its namespace chain and the parser
    ///   context must stay alive for the call; created attributes are
    ///   owned by the node's property list.
    unsafe fn parser_set_prop(
        ctxt: *mut _xmlParserCtxt,
        node: *mut _xmlNode,
        name: *const xmlChar,
        prefix: *const xmlChar,
        value: *const xmlChar,
        value_len: isize,
        had_ref: bool,
    ) -> *mut _xmlAttr {
        // A negative length is invalid; an EMPTY value (len 0) is a real
        // attribute (`bar=""`) and must be created (upstream
        // xmlSAX2AttributeNs) — xmlGetProp reports childless attributes as
        // "".
        if node.is_null() || name.is_null() || value.is_null() || value_len < 0 {
            return ptr::null_mut();
        }
        unsafe {
            let n = &mut *node;

            // UPSTREAM-PARITY (xmlSAX2AttributeNs): the attribute namespace is
            // resolved by prefix against the parser's namespace scope — the
            // element's own declarations plus its ancestors. The new element is
            // not yet linked to its parent (add_child runs after attributes),
            // so the own-decl chain is scanned directly and the ancestor scope
            // via ctxt->node (the parent before the element push).
            let ns = if prefix.is_null() {
                ptr::null_mut()
            } else {
                let mut found = ptr::null_mut();
                let mut own = (*node).nsDef;
                while !own.is_null() {
                    let d = &*own;
                    if !d.prefix.is_null()
                        && crate::abi::exports_xml2::xmlStrEqual(d.prefix, prefix) != 0
                    {
                        found = own;
                        break;
                    }
                    own = (*own).next;
                }
                if found.is_null() {
                    // UPSTREAM-PARITY (SAX2.c xmlSAX2AttributeNs): the
                    // ancestor scope is the parser context's current node;
                    // for the root element that is the document itself, so a
                    // NULL ctxt->node falls back to the document (which
                    // carries the materialized xml namespace and any
                    // document-level declarations). Without this, xml:lang
                    // on the root element would lose its binding (R-000166).
                    let scope = if (*ctxt).node.is_null() {
                        (*ctxt).myDoc as *mut _xmlNode
                    } else {
                        (*ctxt).node
                    };
                    if !scope.is_null() {
                        found = tree::search_ns(n.doc, scope, prefix);
                    }
                }
                found
            };

            // Update an existing attribute with the same name and namespace.
            let mut existing = n.properties;
            while !existing.is_null() {
                let attr = &*existing;
                let same_name = !attr.name.is_null()
                    && crate::abi::exports_xml2::xmlStrEqual(attr.name, name) != 0;
                let same_ns = match (attr.ns, ns) {
                    (a, b) if a == b => true,
                    (a, b) if a.is_null() || b.is_null() => false,
                    (a, b) => {
                        let (ah, bh) = ((*a).href, (*b).href);
                        !ah.is_null()
                            && !bh.is_null()
                            && crate::abi::exports_xml2::xmlStrEqual(ah, bh) != 0
                    }
                };
                if same_name && same_ns {
                    if !attr.children.is_null() {
                        tree::free_node_list(attr.children);
                        let attr_mut = existing;
                        (*attr_mut).children = ptr::null_mut();
                        (*attr_mut).last = ptr::null_mut();
                    }
                    // Reference-bearing values build entity-ref children
                    // (upstream xmlNodeParseAttValue).
                    if had_ref {
                        let attr_mut = existing;
                        parser_build_attr_children(ctxt, attr_mut, value, value_len as c_int, true);
                    } else {
                        let text = parser_new_text_node(ctxt, value, value_len as c_int, false);
                        if !text.is_null() {
                            let attr_mut = existing;
                            (*attr_mut).children = text;
                            (*attr_mut).last = text;
                            (*text).parent = existing as *mut _xmlNode;
                            (*text).doc = (*ctxt).myDoc;
                        }
                    }
                    return existing;
                }
                existing = (*existing).next;
            }

            // Create a new attribute.
            let attr = allocator::xmlMallocZero(size_of::<_xmlAttr>() as usize) as *mut _xmlAttr;
            if attr.is_null() {
                return ptr::null_mut();
            }
            (*attr).type_ = XML_ATTRIBUTE_NODE as c_int;
            // UPSTREAM-PARITY (SAX2.c xmlSAX2AttributeNs): with dictNames
            // the attribute name is the dict-interned string (borrowed,
            // never freed by xmlFreeProp — DICT_FREE); otherwise it is
            // duplicated.
            (*attr).name = if (*ctxt).dictNames != 0 && !(*ctxt).dict.is_null() {
                crate::abi::exports_xml2::xmlDictLookup((*ctxt).dict, name, -1)
            } else {
                crate::xml::string::xml_strdup(name) as *const xmlChar
            };
            (*attr).ns = ns;
            (*attr).parent = node;
            // UPSTREAM-PARITY (SAX2.c xmlSAX2AttributeNs): the attribute
            // belongs to the parser's document (the element's own doc pointer
            // is only propagated when the node is linked into the tree).
            (*attr).doc = (*ctxt).myDoc;
            // UPSTREAM-PARITY (tree.c xmlNewProp): atype is left at the
            // zero-initialised value (0) for instance attributes; the
            // XML_ATTRIBUTE_* values are used by DTD attribute declarations.

            // Reference-bearing values build entity-ref children (upstream
            // xmlSAX2AttributeNs -> xmlNodeParseAttValue, gh19612); a plain
            // value is a single (possibly compact) text node.
            if had_ref {
                parser_build_attr_children(ctxt, attr, value, value_len as c_int, true);
            } else {
                let text = parser_new_text_node(ctxt, value, value_len as c_int, false);
                if !text.is_null() {
                    (*attr).children = text;
                    (*attr).last = text;
                    (*text).parent = attr as *mut _xmlNode;
                    (*text).doc = (*ctxt).myDoc;
                }
            }

            // Add to the node's property list.
            if n.properties.is_null() {
                n.properties = attr;
            } else {
                let mut last = n.properties;
                while !(*last).next.is_null() {
                    last = (*last).next;
                }
                (*last).next = attr;
                (*attr).prev = last;
            }
            attr
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // Document lifecycle
    // ═══════════════════════════════════════════════════════════════════════

    /// Default `startDocument` handler.
    ///
    /// Creates a new document and stores it in the parser context.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    pub unsafe extern "C" fn startDocument(ctx: *mut c_void) {
        // SAFETY: Caller guarantees `ctx` is a valid parser context.
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &mut *ctxt;

            // Create a new document with default version "1.0".
            let doc = tree::new_doc(ptr::null());
            if doc.is_null() {
                return;
            }

            c.myDoc = doc;
            c.wellFormed = 1;

            // UPSTREAM-PARITY (SAX2.c xmlSAX2StartDocument): the document
            // records the current input's filename as its URL, so consumers
            // (debug dumps, error messages, XSLT runtime diagnostics) see the
            // source name.
            if !c.input.is_null() && !(*c.input).filename.is_null() {
                (*doc).URL = crate::xml::string::xml_strdup(
                    (*c.input).filename as *const crate::abi::types::xmlChar,
                );
            }

            // UPSTREAM-PARITY (SAX2.c xmlSAX2StartDocument): the parser
            // owns the document properties; the flags are set at
            // endDocument. parseFlags mirrors the parse options, and the
            // document shares the parser's dictionary (refcounted).
            (*doc).properties = 0;
            (*doc).parseFlags = c.options;
            (*doc).standalone = c.standalone;
            if c.dictNames != 0 {
                if c.dict.is_null() {
                    c.dict = crate::abi::exports_xml2::xmlDictCreate();
                }
                if !c.dict.is_null() {
                    (*doc).dict = c.dict;
                    crate::abi::exports_hash::xmlDictReference(c.dict);
                }
            }
        }
    }

    /// Default `endDocument` handler.
    ///
    /// Finalizes the document (marks it well-formed if applicable).
    /// Propagates version/encoding from the parser context to the document.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    pub unsafe extern "C" fn endDocument(ctx: *mut c_void) {
        // SAFETY: Caller guarantees `ctx` is a valid parser context.
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;
            if !c.myDoc.is_null() {
                // Propagate version from context to document.
                if !c.version.is_null() && (*c.myDoc).version.is_null() {
                    let dup = allocator::xmlMemStrdupImpl(c.version as *const c_char);
                    (*c.myDoc).version = dup as *mut xmlChar;
                }

                // Propagate encoding from context to document. UPSTREAM-PARITY
                // (SAX2.c xmlSAX2EndDocument): the document encoding is the
                // ACTUAL encoding (xmlGetActualEncoding — the input encoder's
                // name when the caller installed one), never a declaration the
                // caller asked to ignore. Under XML_PARSE_IGNORE_ENC the
                // context copy would shadow the override (PHP Dom\XMLDocument
                // overrideEncoding fills doc->encoding itself when NULL).
                if c.encoding.is_null() || c.options & crate::abi::types::XML_PARSE_IGNORE_ENC == 0
                {
                    if !c.encoding.is_null() && (*c.myDoc).encoding.is_null() {
                        let dup = allocator::xmlMemStrdupImpl(c.encoding as *const c_char);
                        (*c.myDoc).encoding = dup as *mut xmlChar;
                    }
                }

                // Mark the document as well-formed if no errors occurred
                // (upstream xmlSAX2EndDocument flag set).
                if c.wellFormed != 0 {
                    (*(c.myDoc)).properties |= XML_DOC_WELLFORMED as c_int;
                    if c.valid != 0 {
                        (*(c.myDoc)).properties |= XML_DOC_DTDVALID as c_int;
                    }
                    if c.nsWellFormed != 0 {
                        (*(c.myDoc)).properties |= XML_DOC_NSVALID as c_int;
                    }
                }
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // Element stack operations (SAX2)
    // ═══════════════════════════════════════════════════════════════════════

    /// Default `startElementNs` handler.
    ///
    /// Creates a new element node, sets up namespaces, processes attributes,
    /// and pushes the node onto the element stack.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `localname` must be a valid null-terminated string.
    /// - `prefix` and `URI` may be NULL.
    /// - `namespaces` points to an array of `2 * nb_namespaces` pointers, or NULL.
    /// - `attributes` points to an array of `5 * nb_attributes` pointers, or NULL.
    #[allow(clippy::too_many_arguments)]
    pub unsafe extern "C" fn startElementNs(
        ctx: *mut c_void,
        localname: *const xmlChar,
        prefix: *const xmlChar,
        URI: *const xmlChar,
        nb_namespaces: c_int,
        namespaces: *mut *const xmlChar,
        nb_attributes: c_int,
        nb_defaulted: c_int,
        attributes: *mut *const xmlChar,
    ) {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || localname.is_null() {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &mut *ctxt;

            // UPSTREAM-PARITY (SAX2.c xmlSAX2StartElementNs): DTD defaulted
            // attributes are only materialised as real attribute nodes when
            // XML_COMPLETE_ATTRS is requested (XML_PARSE_DTDATTR / the
            // xmlLoadExtDtdDefaultValue global); otherwise they are subtracted
            // from the attribute count so the tree keeps only the tag's own
            // attributes (DOM loadXML with an ATTLIST default must NOT create
            // the default as a real attribute — php removeAttribute/toggle
            // rely on xmlHasProp reporting the DTD declaration instead).
            let mut effective_nb_attributes = nb_attributes;
            if nb_defaulted != 0
                && (c.options & crate::abi::types::XML_PARSE_DTDATTR == 0)
                && (c.loadsubset & crate::abi::constants::XML_COMPLETE_ATTRS == 0)
            {
                effective_nb_attributes -= nb_defaulted;
            }

            // Determine the parent node for this element.
            let parent = if c.nodeNr > 0 && !c.nodeTab.is_null() {
                let idx = (c.nodeNr - 1) as usize;
                *c.nodeTab.add(idx)
            } else {
                // No parent — this is the root element. Add it to the document.
                ptr::null_mut()
            };

            // Create the element node.
            // UPSTREAM-PARITY (SAX2.c xmlSAX2StartElementNs): when the
            // element's prefix is not bound to any namespace (URI == NULL),
            // the raw QName is kept as the node name and the namespace stays
            // NULL (the 'rare case of an undefined namespace prefix'
            // handling with xmlBuildQName). This keeps `<p:b/>` serializing
            // as `<p:b/>` instead of dropping the prefix.
            let name_owned: Vec<u8>;
            let (node_name, ns) = if URI.is_null() && !prefix.is_null() {
                let mut q = Vec::new();
                q.extend_from_slice({
                    core::slice::from_raw_parts(
                        prefix,
                        crate::xml::tree::xml_strlen(prefix) as usize,
                    )
                });
                q.push(b':');
                q.extend_from_slice({
                    core::slice::from_raw_parts(
                        localname,
                        crate::xml::tree::xml_strlen(localname) as usize,
                    )
                });
                q.push(0);
                name_owned = q;
                (name_owned.as_ptr() as *const xmlChar, ptr::null_mut())
            } else if URI.is_null() && prefix.is_null() {
                (localname, ptr::null_mut())
            } else {
                // Search for an existing namespace declaration on the parent
                // chain that matches this prefix/URI combination.
                (localname, tree::search_ns(c.myDoc, parent, prefix))
            };

            let node = if c.dictNames != 0 && !c.dict.is_null() {
                // UPSTREAM-PARITY (parser.c xmlParseStartTag2 + SAX2.c
                // xmlSAX2StartElementNs): with dictNames the parser interns
                // the element name in the context dictionary and the node
                // BORROWS the interned string (xmlNewDocNodeEatName).
                // Consumers (lxml objectify `_tagMatches`, `xmlDictExists`
                // probes) rely on node names being pointer-identical to
                // dict lookup results.
                let interned = crate::abi::exports_xml2::xmlDictLookup(c.dict, node_name, -1);
                if interned.is_null() {
                    tree::new_node(ns, node_name)
                } else {
                    tree::new_node_eat_name(ns, interned)
                }
            } else {
                tree::new_node(ns, node_name)
            };
            if node.is_null() {
                return;
            }

            // UPSTREAM-PARITY (SAX2.c xmlSAX2StartElementNs builds the node
            // with xmlNewDocNodeEatName(ctxt->myDoc, ...)): the element is
            // created as a child of the parser's document. Without this the
            // node's doc stays NULL until it is linked into a tree, which
            // never happens for unlinked fragments (xmlParseInNodeContext
            // unlinks the parsed list — nokogiri's `noko_xml_document_pin_node`
            // then dereferences a NULL node->doc).
            (*node).doc = c.myDoc;

            // UPSTREAM-PARITY: nodes carry the line of their construct.
            (*node).line = current_line(ctxt);

            // UPSTREAM-PARITY (SAX2.c xmlSAX2StartElementNs): namespace
            // declarations are built from the namespaces array only; the
            // node's namespace is resolved against its own declarations
            // first, then the parent chain (already searched above). This
            // avoids double-registering the default namespace declaration.
            let mut own_ns: *mut _xmlNs = ptr::null_mut();
            if nb_namespaces > 0 && !namespaces.is_null() {
                let mut i: c_int = 0;
                while i < nb_namespaces {
                    let ns_prefix = *namespaces.add((i * 2) as usize);
                    let ns_uri = *namespaces.add((i * 2 + 1) as usize);
                    let new_ns = tree::new_ns(node, ns_uri, ns_prefix);
                    if own_ns.is_null() && !URI.is_null() && !new_ns.is_null() {
                        let same = if ns_prefix.is_null() {
                            prefix.is_null()
                        } else if prefix.is_null() {
                            false
                        } else {
                            crate::abi::exports_xml2::xmlStrEqual(ns_prefix, prefix) != 0
                        };
                        if same {
                            own_ns = new_ns;
                        }
                    }
                    i += 1;
                }
            }
            if !own_ns.is_null() {
                (*node).ns = own_ns;
            }

            // Process attributes.
            if effective_nb_attributes > 0 && !attributes.is_null() {
                let mut i: c_int = 0;
                while i < effective_nb_attributes {
                    let attr_idx = (i * 5) as usize;
                    let attr_name = *attributes.add(attr_idx); // localname
                    let attr_prefix = *attributes.add(attr_idx + 1); // prefix (or NULL)
                    let attr_uri = *attributes.add(attr_idx + 2); // URI (or NULL)
                    let attr_value_start = *attributes.add(attr_idx + 3); // start of value
                    let attr_value_end = *attributes.add(attr_idx + 4); // past end of value

                    if !attr_name.is_null() && !attr_value_start.is_null() {
                        // Compute attribute value length.
                        // If value_end is NULL, the value is null-terminated;
                        // otherwise, value_end points past the last character.
                        // UPSTREAM-PARITY (SAX2.c xmlSAX2AttributeNs): a
                        // non-NULL value_end means the parser duplicated the
                        // value because it contained an entity/character
                        // reference (the raw string is null-terminated there)
                        // — the value node is then built through
                        // xmlNodeParseAttValue and is never compact
                        // (R-000120).
                        let had_ref = !attr_value_end.is_null();
                        let value_len = if attr_value_end.is_null() {
                            // Compute length from null-terminated string
                            let mut len: isize = 0;
                            {
                                while *attr_value_start.offset(len) != 0 {
                                    len += 1;
                                }
                            }
                            len
                        } else {
                            attr_value_end.offset_from(attr_value_start)
                        };
                        // UPSTREAM-PARITY: xmlSAX2AttributeNs builds the
                        // attribute value text with xmlSAX2TextNode, so
                        // short values are compact under XML_PARSE_COMPACT.
                        //
                        // UPSTREAM-PARITY (SAX2.c xmlSAX2StartElementNs):
                        // an attribute whose prefix is not bound (URI ==
                        // NULL) keeps the raw QName as its name with a
                        // NULL namespace (xmlBuildQName), so `<a p:x="1"/>`
                        // serializes as `p:x` rather than losing the
                        // prefix.
                        let qname_owned: Vec<u8>;
                        let (attr_name_eff, attr_prefix_eff) =
                            if !attr_prefix.is_null() && attr_uri.is_null() {
                                let mut q: Vec<u8> = Vec::new();
                                q.extend_from_slice({
                                    core::slice::from_raw_parts(
                                        attr_prefix,
                                        crate::xml::tree::xml_strlen(attr_prefix) as usize,
                                    )
                                });
                                q.push(b':');
                                q.extend_from_slice({
                                    core::slice::from_raw_parts(
                                        attr_name,
                                        crate::xml::tree::xml_strlen(attr_name) as usize,
                                    )
                                });
                                q.push(0);
                                qname_owned = q;
                                (qname_owned.as_ptr() as *const xmlChar, ptr::null())
                            } else {
                                (attr_name, attr_prefix)
                            };
                        // UPSTREAM-PARITY (SAX2.c xmlSAX2AttributeNs): the
                        // attribute is created even for an EMPTY value
                        // (`bar=""` — value_len 0 yields an attribute with
                        // no text child, which xmlGetProp reports as "").
                        let attr = parser_set_prop(
                            ctxt,
                            node,
                            attr_name_eff,
                            attr_prefix_eff,
                            attr_value_start,
                            value_len,
                            had_ref,
                        );
                        // UPSTREAM-PARITY (SAX2.c xmlSAX2AttributeNs tail):
                        // ID/IDREF attributes are registered against the
                        // DTD attribute declarations.
                        if !attr.is_null() {
                            let av = (*attr).children;
                            let v = if av.is_null() || (*av).content.is_null() {
                                ptr::null()
                            } else {
                                (*av).content
                            };
                            if !v.is_null() {
                                let res = crate::xml::validation::is_id(c.myDoc, node, attr);
                                if res > 0 {
                                    let reg = crate::xml::validation::add_id(
                                        ptr::null_mut(),
                                        c.myDoc,
                                        v,
                                        attr,
                                    );
                                    // UPSTREAM-PARITY (SAX2.c
                                    // xmlSAX2AttributeNs tail): a duplicate
                                    // ID value is reported through the
                                    // parser's validation context —
                                    // "ID %s already defined" at the
                                    // attribute's position (php surfaces it as
                                    // a warning; Dom\XMLDocument
                                    // createFromString bug79701 expects it).
                                    if reg.is_null() {
                                        let msg = format!(
                                            "ID {} already defined\n\0",
                                            crate::xml::string::xmlstr_to_string(v)
                                        );
                                        default_sax_handler::raise_ctxt_validity_error(
                                            ctxt,
                                            513, // XML_DTD_ID_REDEFINED
                                            msg.as_ptr() as *const c_char,
                                        );
                                    }
                                } else if crate::xml::validation::is_ref(c.myDoc, node, attr) > 0 {
                                    crate::xml::validation::add_ref(
                                        ptr::null_mut(),
                                        c.myDoc,
                                        v,
                                        attr,
                                    );
                                }
                            }
                        }
                    }
                    i += 1;
                }
            }

            // Add the node to the tree.
            if !parent.is_null() {
                tree::add_child(parent, node);
            } else {
                // This is the root element — attach it to the document.
                if !c.myDoc.is_null() {
                    tree::add_child(c.myDoc as *mut _xmlNode, node);
                }
            }

            // Push the node onto the element stack.
            c.node = node;
            // UPSTREAM-PARITY (parser.c nodePush): hard depth cap —
            // "Excessive depth in document" with XML_ERR_RESOURCE_LIMIT,
            // lifted to 2048 by XML_PARSE_HUGE (2.15 default 256).
            let max_depth = if (c.options & crate::abi::types::XML_PARSE_HUGE) != 0 {
                2048
            } else {
                256
            };
            if c.nodeNr >= max_depth {
                // UPSTREAM-PARITY (parserInternals.c nodePush): stream the
                // error through the parser's fragment channel with the
                // current input's file/line/col and source window
                // (HOSTILE-FAILURE F1).
                let msg = format!(
                    "Excessive depth in document: {}, use XML_PARSE_HUGE option\n",
                    c.nodeNr
                );
                let msg_c = std::ffi::CString::new(msg).unwrap_or_default();
                let mut file_ptr = ptr::null();
                let mut line = 0i32;
                let mut col = 0i32;
                let mut window: Option<(Vec<u8>, usize)> = None;
                if !c.input.is_null() {
                    let inp = &*c.input;
                    file_ptr = inp.filename;
                    line = inp.line;
                    col = inp.col;
                    if !inp.base.is_null()
                        && !inp.end.is_null()
                        && (inp.end as usize) >= (inp.base as usize)
                    {
                        // SAFETY: the input's base/end point into the live
                        // parser InputBuffer (alive for the whole parse).
                        let len = inp.end.offset_from(inp.base) as usize;
                        let data = core::slice::from_raw_parts(inp.base, len);
                        let byte_pos = if !inp.cur.is_null() {
                            inp.cur.offset_from(inp.base) as usize
                        } else {
                            0
                        };
                        window = crate::xml::parser::tokenizer::window_at_data(data, byte_pos);
                    }
                }
                c.errNo = crate::abi::types::XML_ERR_RESOURCE_LIMIT;
                c.wellFormed = 0;
                c.nbErrors = c.nbErrors.wrapping_add(1);
                // UPSTREAM-PARITY (xmlCtxtVErr): RESOURCE_LIMIT is a
                // catastrophic error — disableSAX = 2 really stops the parser.
                c.disableSAX = 2;
                let delivery = crate::xml::errors::parser_delivery(ctxt);
                let window_ref = window.as_ref().map(|(w, caret)| (w.as_slice(), *caret));
                crate::xml::errors::raise_error_streamed(
                    ctxt as *mut c_void,
                    crate::abi::types::XML_FROM_PARSER,
                    crate::abi::types::XML_ERR_RESOURCE_LIMIT,
                    crate::abi::types::xmlErrorLevel::XML_ERR_FATAL as c_int,
                    file_ptr,
                    line,
                    col,
                    ptr::null(),
                    ptr::null(),
                    ptr::null(),
                    0,
                    msg_c.as_ptr(),
                    window_ref,
                    None,
                    delivery,
                    None,
                );
                return;
            }
            // Extend nodeTab if needed.
            if c.nodeNr >= c.nodeMax {
                let new_max = if c.nodeMax == 0 { 8 } else { c.nodeMax * 2 };
                let new_size = (new_max as usize) * size_of::<*mut _xmlNode>();
                let new_tab = allocator::xmlReallocImpl(c.nodeTab as *mut c_void, new_size)
                    as *mut *mut _xmlNode;
                if !new_tab.is_null() {
                    c.nodeTab = new_tab;
                    c.nodeMax = new_max;
                }
            }
            if c.nodeNr < c.nodeMax && !c.nodeTab.is_null() {
                *c.nodeTab.add(c.nodeNr as usize) = node;
                c.nodeNr += 1;
            }
        }
    }

    /// Default `endElementNs` handler.
    ///
    /// Pops the current element from the element stack.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    pub unsafe extern "C" fn endElementNs(
        ctx: *mut c_void,
        _localname: *const xmlChar,
        _prefix: *const xmlChar,
        _URI: *const xmlChar,
    ) {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &mut *ctxt;

            // Pop the element stack.
            if c.nodeNr > 0 {
                c.nodeNr -= 1;
            }

            // Update the current node pointer to the new top of stack.
            if c.nodeNr > 0 && !c.nodeTab.is_null() {
                let idx = (c.nodeNr - 1) as usize;
                c.node = *c.nodeTab.add(idx);
            } else {
                c.node = ptr::null_mut();
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // Content handlers
    // ═══════════════════════════════════════════════════════════════════════

    /// Default `characters` handler.
    ///
    /// Creates a text node and adds it to the current element.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `ch` must be a valid pointer to a buffer of at least `len` bytes.
    pub unsafe extern "C" fn characters(ctx: *mut c_void, ch: *const xmlChar, len: c_int) {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || ch.is_null() || len <= 0 {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;

            // Determine the parent node (current element or document).
            let parent = if c.nodeNr > 0 && !c.nodeTab.is_null() {
                let idx = (c.nodeNr - 1) as usize;
                *c.nodeTab.add(idx)
            } else {
                c.myDoc as *mut _xmlNode
            };

            if parent.is_null() {
                return;
            }

            // UPSTREAM-PARITY: xmlSAX2Characters merges character data into
            // the parent's LAST child when it is a text node (xmlNodeAddContent).
            // An interrupted character-data stream (e.g. an entity reference)
            // is never compact, so the merge promotes compact content to heap.
            // §16.5: the last child is parent->last — O(1) — never a sibling
            // walk (a root with N element children + inter-element whitespace
            // runs was O(N) per text event = O(N²) per document).
            let last = (*parent).last;
            if !last.is_null() && (*last).type_ == XML_TEXT_NODE as c_int {
                merge_into_text_node(last, ch, len);
                return;
            }

            let text = parser_new_text_node(ctxt, ch, len, false);

            if !text.is_null() {
                (*text).line = current_line(ctxt);
                tree::add_child(parent, text);
            }
        }
    }

    /// Default `ignorableWhitespace` handler.
    ///
    /// Behaves like `characters` — creates a text node from whitespace content.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `ch` must be a valid pointer to a buffer of at least `len` bytes.
    pub unsafe extern "C" fn ignorableWhitespace(ctx: *mut c_void, ch: *const xmlChar, len: c_int) {
        // Delegate to characters handler — upstream libxml2 treats ignorable
        // whitespace the same as regular character data by default.
        // SAFETY: Same safety requirements as `characters`.
        unsafe { characters(ctx, ch, len) };
    }

    // ═══════════════════════════════════════════════════════════════════════
    // Comment and PI handlers
    // ═══════════════════════════════════════════════════════════════════════

    /// Default `comment` handler.
    ///
    /// Creates a comment node and adds it to the current element or document.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `value` must be a valid null-terminated string or NULL.
    pub unsafe extern "C" fn comment(ctx: *mut c_void, value: *const xmlChar) {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;

            let parent = if c.nodeNr > 0 && !c.nodeTab.is_null() {
                let idx = (c.nodeNr - 1) as usize;
                *c.nodeTab.add(idx)
            } else {
                c.myDoc as *mut _xmlNode
            };

            if parent.is_null() {
                return;
            }

            let comment_node = tree::new_comment(value);
            if !comment_node.is_null() {
                (*comment_node).line = current_line(ctxt);
                tree::add_child(parent, comment_node);
            }
        }
    }

    /// Default `processingInstruction` handler.
    ///
    /// Creates a PI node and adds it to the current element or document.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `target` and `data` must be valid null-terminated strings or NULL.
    pub unsafe extern "C" fn processingInstruction(
        ctx: *mut c_void,
        target: *const xmlChar,
        data: *const xmlChar,
    ) {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || target.is_null() {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;

            let parent = if c.nodeNr > 0 && !c.nodeTab.is_null() {
                let idx = (c.nodeNr - 1) as usize;
                *c.nodeTab.add(idx)
            } else {
                c.myDoc as *mut _xmlNode
            };

            if parent.is_null() {
                return;
            }

            let pi_node = tree::new_pi(target, data);
            if !pi_node.is_null() {
                (*pi_node).line = current_line(ctxt);
                tree::add_child(parent, pi_node);
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // CDATA handler
    // ═══════════════════════════════════════════════════════════════════════

    /// Default `cdataBlock` handler.
    ///
    /// Creates a CDATA section node and adds it to the current element.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `value` must be a valid pointer to a buffer of at least `len` bytes.
    pub unsafe extern "C" fn cdataBlock(ctx: *mut c_void, value: *const xmlChar, len: c_int) {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || value.is_null() || len <= 0 {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;

            let parent = if c.nodeNr > 0 && !c.nodeTab.is_null() {
                let idx = (c.nodeNr - 1) as usize;
                *c.nodeTab.add(idx)
            } else {
                c.myDoc as *mut _xmlNode
            };

            if parent.is_null() {
                return;
            }

            let cdata = tree::new_cdata_block(c.myDoc, value, len);
            if !cdata.is_null() {
                (*cdata).line = current_line(ctxt);
                tree::add_child(parent, cdata);
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // DTD / Subset handlers
    // ═══════════════════════════════════════════════════════════════════════

    /// Default `internalSubset` handler.
    ///
    /// Creates a DTD node for the internal subset.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `name`, `ext_id`, `sys_id` must be valid null-terminated strings or NULL.
    pub unsafe extern "C" fn internalSubset(
        ctx: *mut c_void,
        name: *const xmlChar,
        ext_id: *const xmlChar,
        sys_id: *const xmlChar,
    ) {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || name.is_null() {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &mut *ctxt;

            if c.myDoc.is_null() {
                return;
            }

            // UPSTREAM-PARITY (SAX2.c xmlSAX2InternalSubset): a pre-existing
            // internal subset is unlinked and freed before the new one is
            // created with xmlCreateIntSubset (which links the DTD node into
            // the document's child list before the first element node).
            let old = (*(c.myDoc)).intSubset;
            if !old.is_null() {
                tree::unlink_node(old as *mut crate::abi::structs::_xmlNode);
                crate::xml::dtd::free_dtd(old);
                (*(c.myDoc)).intSubset = ptr::null_mut();
            }
            crate::xml::dtd::create_int_subset(c.myDoc, name, ext_id, sys_id);
        }
    }

    /// Default `externalSubset` handler.
    ///
    /// Records the external subset reference.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `name`, `ext_id`, `sys_id` must be valid null-terminated strings or NULL.
    pub unsafe extern "C" fn externalSubset(
        ctx: *mut c_void,
        name: *const xmlChar,
        ext_id: *const xmlChar,
        sys_id: *const xmlChar,
    ) {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || name.is_null() {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &mut *ctxt;

            if c.myDoc.is_null() {
                return;
            }

            // If no internal subset was created, create a DTD with the external info.
            if (*(c.myDoc)).intSubset.is_null() {
                let dtd = tree::new_dtd(c.myDoc, name, ext_id, sys_id);
                if !dtd.is_null() {
                    (*(c.myDoc)).extSubset = dtd;
                }
            } else {
                // Update the external IDs on the existing DTD.
                let dtd = (*(c.myDoc)).intSubset;
                if !ext_id.is_null() {
                    let ext_copy = tree::xml_strlen(ext_id);
                    // Only set if non-empty.
                    if ext_copy > 0 {
                        (*(c.myDoc)).extSubset = dtd;
                    }
                }
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // Entity handlers
    // ═══════════════════════════════════════════════════════════════════════

    /// Default `entityDecl` handler.
    ///
    /// Creates an entity node and adds it to the document's entity table.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - All pointer arguments must be valid null-terminated strings or NULL.
    pub unsafe extern "C" fn entityDecl(
        ctx: *mut c_void,
        name: *const xmlChar,
        type_: c_int,
        pub_id: *const xmlChar,
        sys_id: *const xmlChar,
        content: *mut xmlChar,
    ) {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || name.is_null() {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;
            if c.myDoc.is_null() {
                return;
            }

            let _entity = tree::new_entity(
                c.myDoc,
                name,
                type_,
                pub_id,
                sys_id,
                content as *const xmlChar,
            );
            // The entity is added to the document's entities hash by new_entity.
            // Nothing further to do here.
        }
    }

    /// Default `attributeDecl` handler.
    ///
    /// Records an attribute declaration for the given element.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - All pointer arguments must be valid null-terminated strings or NULL.
    pub const unsafe extern "C" fn attributeDecl(
        _ctx: *mut c_void,
        _elem: *const xmlChar,
        _fullname: *const xmlChar,
        _type_: c_int,
        _def: c_int,
        _default_value: *const xmlChar,
        _tree: *mut _xmlEnumeration,
    ) {
        // In the default handler, attribute declarations are recorded for DTD
        // validation purposes. For now, this is a no-op — the DTD validation
        // infrastructure is not yet implemented.
        //
        // # UPSTREAM-PARITY
        //
        // Upstream libxml2's xmlSAX2AttributeDecl creates an xmlAttribute node
        // and adds it to the DTD's attribute declaration table. This will be
        // implemented when DTD validation is added.
    }

    /// Default `elementDecl` handler.
    ///
    /// Records an element declaration for the given element.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `name` must be a valid null-terminated string.
    /// - `content` must be a valid pointer or NULL.
    pub const unsafe extern "C" fn elementDecl(
        _ctx: *mut c_void,
        _name: *const xmlChar,
        _type_: c_int,
        _content: *mut _xmlElementContent,
    ) {
        // No-op in the default handler — element declaration recording will be
        // implemented alongside DTD validation.
    }

    /// Default `notationDecl` handler.
    ///
    /// Records a notation declaration.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - All pointer arguments must be valid null-terminated strings or NULL.
    pub const unsafe extern "C" fn notationDecl(
        _ctx: *mut c_void,
        _name: *const xmlChar,
        _pub_id: *const xmlChar,
        _sys_id: *const xmlChar,
    ) {
        // No-op in the default handler — notation declarations will be
        // implemented when DTD support is fully operational.
    }

    /// Default `unparsedEntityDecl` handler.
    ///
    /// Records an unparsed entity declaration.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - All pointer arguments must be valid null-terminated strings or NULL.
    pub const unsafe extern "C" fn unparsedEntityDecl(
        _ctx: *mut c_void,
        _name: *const xmlChar,
        _pub_id: *const xmlChar,
        _sys_id: *const xmlChar,
        _notation: *const xmlChar,
    ) {
        // No-op in the default handler — unparsed entity declarations will be
        // implemented when DTD support is fully operational.
    }

    // ═══════════════════════════════════════════════════════════════════════
    // Entity resolution
    // ═══════════════════════════════════════════════════════════════════════

    /// Default `resolveEntity` handler.
    ///
    /// Returns NULL — no external entity resolution by default.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `pub_id` and `sys_id` must be valid null-terminated strings or NULL.
    pub const unsafe extern "C" fn resolveEntity(
        _ctx: *mut c_void,
        _pub_id: *const xmlChar,
        _sys_id: *const xmlChar,
    ) -> *mut _xmlParserInput {
        // Default handler does not resolve entities — return NULL.
        ptr::null_mut()
    }

    // ═══════════════════════════════════════════════════════════════════════
    // Stub handlers (minimal implementations)
    // ═══════════════════════════════════════════════════════════════════════

    /// Default `isStandalone` handler.
    ///
    /// Returns -1 (standalone status unknown/not declared).
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    pub const unsafe extern "C" fn isStandalone(_ctx: *mut c_void) -> c_int {
        -1
    }

    /// Default `hasInternalSubset` handler.
    ///
    /// Returns 1 if the document has an internal subset, 0 otherwise.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    pub unsafe extern "C" fn hasInternalSubset(ctx: *mut c_void) -> c_int {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() {
            return 0;
        }
        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;
            if c.myDoc.is_null() {
                return 0;
            }
            if (*(c.myDoc)).intSubset.is_null() {
                0
            } else {
                1
            }
        }
    }

    /// Default `hasExternalSubset` handler.
    ///
    /// Returns 1 if the document has an external subset, 0 otherwise.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    pub unsafe extern "C" fn hasExternalSubset(ctx: *mut c_void) -> c_int {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() {
            return 0;
        }
        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;
            if c.myDoc.is_null() {
                return 0;
            }
            if (*(c.myDoc)).extSubset.is_null() {
                0
            } else {
                1
            }
        }
    }

    /// Default `getEntity` handler.
    ///
    /// Looks up an entity in the document's entity table.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `name` must be a valid null-terminated string.
    pub unsafe extern "C" fn getEntity(ctx: *mut c_void, name: *const xmlChar) -> *mut _xmlEntity {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || name.is_null() {
            return ptr::null_mut();
        }
        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;
            if c.myDoc.is_null() {
                return ptr::null_mut();
            }
            tree::get_doc_entity(c.myDoc, name)
        }
    }

    /// Default `getParameterEntity` handler.
    ///
    /// Looks up a parameter entity in the document's entity table.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `name` must be a valid null-terminated string.
    pub unsafe extern "C" fn getParameterEntity(
        ctx: *mut c_void,
        name: *const xmlChar,
    ) -> *mut _xmlEntity {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || name.is_null() {
            return ptr::null_mut();
        }
        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;
            if c.myDoc.is_null() {
                return ptr::null_mut();
            }
            tree::get_parameter_entity(c.myDoc, name)
        }
    }

    /// Default `setDocumentLocator` handler.
    ///
    /// No-op — the default handler does not use the locator.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `loc` must be a valid pointer to an `_xmlSAXLocator`.
    pub const unsafe extern "C" fn setDocumentLocator(
        _ctx: *mut c_void,
        _loc: *mut _xmlSAXLocator,
    ) {
        // No-op in the default handler.
    }

    /// Default `reference` handler.
    ///
    /// No-op — entity references are expanded by the parser before reaching
    /// the default handler.
    ///
    /// # SAFETY
    ///
    /// Default `reference` handler.
    ///
    /// Creates an ENTITY_REF node in the tree (upstream default behavior when
    /// entity substitution is off).
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `name` must be a valid null-terminated string.
    ///
    /// SAX locator callback: public ID (upstream SAX2.c
    ///
    /// `xmlSAX2GetPublicId` returns NULL).
    pub const unsafe extern "C" fn getPublicId(_ctx: *mut c_void) -> *const xmlChar {
        ptr::null()
    }

    /// SAX locator callback: system ID (upstream SAX2.c
    /// `xmlSAX2GetSystemId` returns the input filename).
    pub unsafe extern "C" fn getSystemId(ctx: *mut c_void) -> *const xmlChar {
        if ctx.is_null() {
            return ptr::null();
        }
        // SAFETY: ctx is a valid parser context.
        let ctxt = ctx as *mut crate::abi::structs::_xmlParserCtxt;
        unsafe {
            if (*ctxt).input.is_null() {
                return ptr::null();
            }
            let filename = (*(*ctxt).input).filename;
            if filename.is_null() {
                ptr::null()
            } else {
                filename as *const xmlChar
            }
        }
    }

    /// SAX locator callback: current line (upstream SAX2.c
    /// `xmlSAX2GetLineNumber` returns the input stream's line).
    pub unsafe extern "C" fn getLineNumber(ctx: *mut c_void) -> c_int {
        if ctx.is_null() {
            return 0;
        }
        // SAFETY: ctx is a valid parser context.
        let ctxt = ctx as *mut crate::abi::structs::_xmlParserCtxt;
        unsafe {
            if (*ctxt).input.is_null() {
                0
            } else {
                (*(*ctxt).input).line
            }
        }
    }

    /// SAX locator callback: current column (upstream SAX2.c
    /// `xmlSAX2GetColumnNumber` returns the input stream's column).
    pub unsafe extern "C" fn getColumnNumber(ctx: *mut c_void) -> c_int {
        if ctx.is_null() {
            return 0;
        }
        // SAFETY: ctx is a valid parser context.
        let ctxt = ctx as *mut crate::abi::structs::_xmlParserCtxt;
        unsafe {
            if (*ctxt).input.is_null() {
                0
            } else {
                (*(*ctxt).input).col
            }
        }
    }

    /// Handle an entity reference by creating an `XML_ENTITY_REF_NODE`.
    ///
    /// # Safety
    ///
    /// - `ctx` must be NULL or a valid pointer to an `_xmlParserCtxt` that
    ///   stays alive for the call; `name` must be NULL or a valid
    ///   NUL-terminated string; the context's `nodeTab`, `myDoc` and entity
    ///   table must be consistent while the reference node is created and
    ///   linked into the tree.
    pub unsafe extern "C" fn reference(ctx: *mut c_void, name: *const xmlChar) {
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || name.is_null() {
            return;
        }

        // SAFETY: The context is guaranteed valid by the caller.
        unsafe {
            let c = &*ctxt;

            let parent = if c.nodeNr > 0 && !c.nodeTab.is_null() {
                let idx = (c.nodeNr - 1) as usize;
                *c.nodeTab.add(idx)
            } else {
                c.myDoc as *mut _xmlNode
            };

            if parent.is_null() {
                return;
            }

            // UPSTREAM-PARITY (tree.c xmlNewReference): the reference node
            // carries the entity's content (shared pointer) and points its
            // child list at the entity declaration node itself.
            let ent = crate::xml::entities::get_entity(c.myDoc, name);

            let ref_node = allocator::xmlMallocZero(size_of::<_xmlNode>()) as *mut _xmlNode;
            if !ref_node.is_null() {
                (*ref_node).type_ = XML_ENTITY_REF_NODE as c_int;
                (*ref_node).name = crate::xml::string::xml_strdup(name);
                (*ref_node).doc = c.myDoc;
                (*ref_node).line = current_line(ctxt);
                if !ent.is_null() {
                    (*ref_node).content = (*ent).content;
                    (*ref_node).children = ent as *mut _xmlNode;
                    (*ref_node).last = ent as *mut _xmlNode;
                }
                tree::add_child(parent, ref_node);
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════
    // Error handlers
    // ═══════════════════════════════════════════════════════════════════════

    /// Default `warning` handler.
    ///
    /// Logs a warning message via the error reporting infrastructure.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `msg` must be a valid null-terminated C string.
    #[allow(dead_code)]
    pub unsafe extern "C" fn warning(ctx: *mut c_void, msg: *const c_char) {
        // SAFETY: The context is guaranteed valid by the caller.
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || msg.is_null() {
            return;
        }

        // SAFETY: The message string is guaranteed valid by the caller.
        unsafe {
            let c = &mut *ctxt;
            c.nbWarnings += 1;
            // In Phase 3, this will route through the structured error system.
            // For now, the parser context tracks the error count.
        }
    }

    /// Default `error` handler.
    ///
    /// Logs an error message via the error reporting infrastructure.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `msg` must be a valid null-terminated C string.
    pub unsafe extern "C" fn error(ctx: *mut c_void, msg: *const c_char) {
        // SAFETY: The context is guaranteed valid by the caller.
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || msg.is_null() {
            return;
        }

        // SAFETY: The message string is guaranteed valid by the caller.
        unsafe {
            let c = &mut *ctxt;
            c.nbErrors += 1;
            c.wellFormed = 0;
            // In Phase 3, this will route through the structured error system.
        }
    }

    /// Default `fatalError` handler.
    ///
    /// Logs a fatal error message and marks the document as not well-formed.
    ///
    /// # SAFETY
    ///
    /// - `ctx` must be a valid pointer to an `_xmlParserCtxt`.
    /// - `msg` must be a valid null-terminated C string.
    #[allow(dead_code)]
    pub unsafe extern "C" fn fatalError(ctx: *mut c_void, msg: *const c_char) {
        // SAFETY: The context is guaranteed valid by the caller.
        let ctxt = unsafe { ctxt_from_ctx(ctx) };
        if ctxt.is_null() || msg.is_null() {
            return;
        }

        // SAFETY: The message string is guaranteed valid by the caller.
        unsafe {
            let c = &mut *ctxt;
            c.nbErrors += 1;
            c.wellFormed = 0;
            // In Phase 3, this will route through the structured error system.
        }
    }
}