exml 0.7.2

Pure Rust XML library based on libxml2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
//! Provide methods and data structures for XInclude.
//!
//! This module is based on `libxml/xinclude.h`, `xinclude.c`, and so on in `libxml2-v2.11.8`.  
//! Please refer to original libxml2 documents also.

// Copyright of the original code is the following.
// --------
// Summary: implementation of XInclude
// Description: API to handle XInclude processing,
// implements the
// World Wide Web Consortium Last Call Working Draft 10 November 2003
// http://www.w3.org/TR/2003/WD-xinclude-20031110
//
// Copy: See Copyright for the status of this software.
//
// Author: Daniel Veillard
// --------
// xinclude.c : Code to implement XInclude processing
//
// World Wide Web Consortium W3C Last Call Working Draft 10 November 2003
// http://www.w3.org/TR/2003/WD-xinclude-20031110
//
// See Copyright for the status of this software.
//
// daniel@veillard.com

use std::{borrow::Cow, mem::take, os::raw::c_void, ptr::null_mut};

use crate::{
    chvalid::XmlCharValid,
    encoding::{XmlCharEncoding, get_encoding_handler},
    error::{__xml_raise_error, XmlErrorDomain, XmlErrorLevel, XmlParserErrors},
    io::xml_parser_get_directory,
    parser::{
        XML_DETECT_IDS, XmlParserCtxt, XmlParserOption, xml_init_parser, xml_load_external_entity,
    },
    tree::{
        NodeCommon, XML_XML_NAMESPACE, XmlDocPtr, XmlElementType, XmlEntityPtr, XmlEntityType,
        XmlGenericNodePtr, XmlNodePtr, xml_add_doc_entity, xml_create_int_subset,
        xml_doc_copy_node, xml_free_doc, xml_free_node, xml_free_node_list, xml_get_doc_entity,
        xml_new_doc_node, xml_new_doc_text, xml_static_copy_node, xml_static_copy_node_list,
    },
    uri::{XmlURI, build_relative_uri, build_uri, escape_url},
    xpath::{XmlXPathObject, XmlXPathObjectType},
    xpointer::{xml_xptr_eval, xml_xptr_new_context},
};

/// A constant defining the Xinclude namespace: `http://www.w3.org/2003/XInclude`
pub const XINCLUDE_NS: &str = "http://www.w3.org/2003/XInclude";
/// A constant defining the draft Xinclude namespace: `http://www.w3.org/2001/XInclude`
pub const XINCLUDE_OLD_NS: &str = "http://www.w3.org/2001/XInclude";
/// A constant defining "include"
pub const XINCLUDE_NODE: &str = "include";
/// A constant defining "fallback"
pub const XINCLUDE_FALLBACK: &str = "fallback";
/// A constant defining "href"
pub const XINCLUDE_HREF: &str = "href";
/// A constant defining "parse"
pub const XINCLUDE_PARSE: &str = "parse";
/// A constant defining "xml"
pub const XINCLUDE_PARSE_XML: &str = "xml";
/// A constant defining "text"
pub const XINCLUDE_PARSE_TEXT: &str = "text";
/// A constant defining "encoding"
pub const XINCLUDE_PARSE_ENCODING: &str = "encoding";
/// A constant defining "xpointer"
pub const XINCLUDE_PARSE_XPOINTER: &str = "xpointer";

/// Handle an XInclude error
#[doc(alias = "xmlXIncludeErr")]
macro_rules! xml_xinclude_err {
    ($ctxt:expr, $node:expr, $error:expr, $msg:expr) => {
        xml_xinclude_err!(@inner, $ctxt, $node, $error, $msg, None);
    };
    ($ctxt:expr, $node:expr, $error:expr, $msg:expr, $extra:expr) => {
        let msg = format!($msg, $extra);
        xml_xinclude_err!(@inner, $ctxt, $node, $error, &msg, Some($extra.to_owned().into()));
    };
    (@inner, $ctxt:expr, $node:expr, $error:expr, $msg:expr, $extra:expr) => {
        let ctxt = $ctxt as *mut XmlXIncludeCtxt;
        if !ctxt.is_null() {
            (*ctxt).nb_errors += 1;
        }
        __xml_raise_error!(
            None,
            None,
            None,
            ctxt as _,
            $node,
            XmlErrorDomain::XmlFromXInclude,
            $error,
            XmlErrorLevel::XmlErrError,
            None,
            0,
            $extra,
            None,
            None,
            0,
            0,
            Some($msg),
        );
    };
}

#[doc(alias = "xmlXIncludeRef")]
#[repr(C)]
#[derive(Default)]
pub struct XmlXIncludeRef {
    uri: Option<Box<str>>,      /* the fully resolved resource URL */
    fragment: Option<Box<str>>, /* the fragment in the URI */
    elem: Option<XmlNodePtr>,   /* the xi:include element */
    inc: Option<XmlNodePtr>,    /* the included copy */
    xml: i32,                   /* xml or txt */
    fallback: i32,              /* fallback was loaded */
    empty_fb: i32,              /* flag to show fallback empty */
    expanding: i32,             /* flag to detect inclusion loops */
    replace: i32,               /* should the node be replaced? */
}

#[doc(alias = "xmlXIncludeDoc")]
#[repr(C)]
pub struct XmlXIncludeDoc {
    doc: Option<XmlDocPtr>, /* the parsed document */
    url: Box<str>,          /* the URL */
    expanding: i32,         /* flag to detect inclusion loops */
}

#[doc(alias = "xmlXIncludeTxt")]
#[repr(C)]
pub struct XmlXIncludeTxt {
    text: Box<str>, /* text string */
    url: Box<str>,  /* the URL */
}

/// An XInclude context
#[doc(alias = "xmlXIncludeCtxt")]
#[repr(C)]
pub struct XmlXIncludeCtxt {
    doc: XmlDocPtr,               /* the source document */
    inc_tab: Vec<XmlXIncludeRef>, /* array of included references */

    txt_tab: Vec<XmlXIncludeTxt>, /* array of unparsed documents */

    url_tab: Vec<XmlXIncludeDoc>, /* document stack */

    nb_errors: i32,         /* the number of errors detected */
    fatal_err: i32,         /* abort processing */
    legacy: i32,            /* using XINCLUDE_OLD_NS */
    parse_flags: i32,       /* the flags used for parsing XML documents */
    base: Option<Box<str>>, /* the current xml:base */

    _private: *mut c_void, /* application data */

    depth: i32,     /* recursion depth */
    is_stream: i32, /* streaming mode */
}

impl XmlXIncludeCtxt {
    /// Creates a new XInclude context
    ///
    /// Returns the new set
    #[doc(alias = "xmlXIncludeNewContext")]
    pub fn new(doc: XmlDocPtr) -> Self {
        XmlXIncludeCtxt {
            doc,
            inc_tab: vec![],
            txt_tab: vec![],
            url_tab: vec![],
            nb_errors: 0,
            fatal_err: 0,
            legacy: 0,
            parse_flags: 0,
            base: None,
            _private: null_mut(),
            depth: 0,
            is_stream: 0,
        }
    }

    /// Get an XInclude attribute
    ///
    /// Returns the value (to be freed) or NULL if not found
    #[doc(alias = "xmlXIncludeGetProp")]
    fn get_prop(&self, cur: XmlNodePtr, name: &str) -> Option<String> {
        if let Some(ret) = cur.get_ns_prop(XINCLUDE_NS, Some(name)) {
            return Some(ret);
        }
        if self.legacy != 0 {
            if let Some(ret) = cur.get_ns_prop(XINCLUDE_OLD_NS, Some(name)) {
                return Some(ret);
            }
        }
        cur.get_prop(name)
    }

    /// In streaming mode, XPointer expressions aren't allowed.
    ///
    /// Returns 0 in case of success and -1 in case of error.
    #[doc(alias = "xmlXIncludeSetStreamingMode")]
    pub(crate) fn set_streaming_mode(&mut self, mode: i32) -> i32 {
        self.is_stream = (mode != 0) as i32;
        0
    }

    /// Set the flags used for further processing of XML resources.
    ///
    /// Returns 0 in case of success and -1 in case of error.
    #[doc(alias = "xmlXIncludeSetFlags")]
    pub fn set_flags(&mut self, flags: i32) -> i32 {
        self.parse_flags = flags;
        0
    }

    /// Add a new node to process to an XInclude context
    #[doc(alias = "xmlXIncludeAddNode")]
    unsafe fn add_node(&mut self, cur: XmlNodePtr) -> usize {
        unsafe {
            let mut xml: i32 = 1;
            let mut local: i32 = 0;

            // read the attributes
            let href = self.get_prop(cur, XINCLUDE_HREF).unwrap_or("".to_owned());
            let parse = self.get_prop(cur, XINCLUDE_PARSE);
            if let Some(parse) = parse {
                if parse == XINCLUDE_PARSE_XML {
                    xml = 1;
                } else if parse == XINCLUDE_PARSE_TEXT {
                    xml = 0;
                } else {
                    xml_xinclude_err!(
                        self,
                        Some(cur.into()),
                        XmlParserErrors::XmlXIncludeParseValue,
                        "invalid value {} for 'parse'\n",
                        parse
                    );
                    return usize::MAX;
                }
            }

            // compute the URI
            let mut base = None;
            let mut uri = if let Some(b) = cur.get_base(Some(self.doc)) {
                base = Some(b);
                build_uri(&href, base.as_deref().unwrap())
            } else {
                self.doc
                    .url
                    .as_deref()
                    .and_then(|base| build_uri(&href, base))
            };
            if uri.is_none() {
                if let Some(base) = base.as_deref() {
                    // Some escaping may be needed
                    if let (Some(escbase), Some(eschref)) = (escape_url(base), escape_url(&href)) {
                        uri = build_uri(&eschref, &escbase);
                    }
                }
            }
            let Some(uri) = uri else {
                xml_xinclude_err!(
                    self,
                    Some(cur.into()),
                    XmlParserErrors::XmlXIncludeHrefURI,
                    "failed build URL\n"
                );
                return usize::MAX;
            };
            let mut fragment = self.get_prop(cur, XINCLUDE_PARSE_XPOINTER);

            // Check the URL and remove any fragment identifier
            let Some(mut parsed_uri) = XmlURI::parse(&uri) else {
                xml_xinclude_err!(
                    self,
                    Some(cur.into()),
                    XmlParserErrors::XmlXIncludeHrefURI,
                    "invalid value URI {}\n",
                    uri
                );
                return usize::MAX;
            };

            if parsed_uri.fragment.is_some() {
                if self.legacy != 0 {
                    if fragment.is_none() {
                        fragment = parsed_uri.fragment.as_deref().map(|f| f.to_owned());
                    }
                } else {
                    xml_xinclude_err!(
                        self,
                        Some(cur.into()),
                        XmlParserErrors::XmlXIncludeFragmentID,
                        "Invalid fragment identifier in URI {} use the xpointer attribute\n",
                        uri
                    );
                    return usize::MAX;
                }
                parsed_uri.fragment = None;
            }
            let url = parsed_uri.save();

            if self.doc.url.as_deref() == Some(url.as_str()) {
                local = 1;
            }

            // If local and xml then we need a fragment
            if local == 1 && xml == 1 && fragment.as_deref().is_none_or(|f| f.is_empty()) {
                xml_xinclude_err!(
                    self,
                    Some(cur.into()),
                    XmlParserErrors::XmlXIncludeRecursion,
                    "detected a local recursion with no xpointer in {}\n",
                    url
                );
                return usize::MAX;
            }

            let refe = self.add_ref(Some(&url), cur);
            self.inc_tab[refe].fragment = fragment.map(|fragment| fragment.into());
            self.inc_tab[refe].xml = xml;
            refe
        }
    }

    /// Creates a new reference within an XInclude context
    ///
    /// Returns the new set
    #[doc(alias = "xmlXIncludeNewRef")]
    fn add_ref(&mut self, uri: Option<&str>, elem: XmlNodePtr) -> usize {
        self.inc_tab.push(XmlXIncludeRef {
            uri: uri.map(|uri| uri.into()),
            fragment: None,
            elem: Some(elem),
            xml: 0,
            inc: None,
            ..Default::default()
        });
        self.inc_tab.len() - 1
    }

    /// Make a copy of the node while expanding nested XIncludes.
    ///
    /// Returns a node list, not a single node.
    #[doc(alias = "xmlXIncludeCopyNode")]
    unsafe fn copy_node(&mut self, elem: XmlNodePtr, copy_children: i32) -> Option<XmlNodePtr> {
        unsafe {
            let mut result: Option<XmlNodePtr> = None;
            let mut insert_parent: Option<XmlNodePtr> = None;
            let mut insert_last: Option<XmlNodePtr> = None;

            let mut cur = if copy_children != 0 {
                elem.children.map(|c| XmlNodePtr::try_from(c).unwrap())?
            } else {
                elem
            };

            loop {
                let mut copy = None;
                let mut recurse: i32 = 0;

                if matches!(
                    cur.element_type(),
                    XmlElementType::XmlDocumentNode | XmlElementType::XmlDTDNode
                ) {
                } else if cur.element_type() == XmlElementType::XmlElementNode
                    && cur.name().as_deref() == Some(XINCLUDE_NODE)
                    && cur.ns.is_some_and(|ns| {
                        ns.href().as_deref() == Some(XINCLUDE_NS)
                            || ns.href().as_deref() == Some(XINCLUDE_OLD_NS)
                    })
                {
                    let ref_index = self.expand_node(cur);

                    if ref_index == usize::MAX {
                        // goto error;
                        xml_free_node_list(result);
                        return None;
                    }
                    // TODO: Insert xmlElementType::XML_XINCLUDE_START and xmlElementType::XML_XINCLUDE_END nodes
                    if let Some(inc) = self.inc_tab[ref_index].inc {
                        let Some(res) = xml_static_copy_node_list(
                            Some(XmlGenericNodePtr::from(inc)),
                            Some(self.doc),
                            insert_parent.map(|parent| parent.into()),
                        ) else {
                            // goto error;
                            xml_free_node_list(result);
                            return None;
                        };
                        copy = Some(XmlNodePtr::try_from(res).unwrap());
                    }
                } else {
                    let Some(res) = xml_static_copy_node(
                        XmlGenericNodePtr::from(cur),
                        Some(self.doc),
                        insert_parent.map(|parent| parent.into()),
                        2,
                    ) else {
                        // goto error;
                        xml_free_node_list(result);
                        return None;
                    };
                    copy = Some(XmlNodePtr::try_from(res).unwrap());

                    recurse = (cur.element_type() != XmlElementType::XmlEntityRefNode
                        && cur.children().is_some()) as i32;
                }

                if let Some(mut copy) = copy {
                    if result.is_none() {
                        result = Some(copy);
                    }
                    if let Some(mut insert_last) = insert_last {
                        insert_last.next = Some(copy.into());
                        copy.prev = Some(insert_last.into());
                    } else if let Some(mut insert_parent) = insert_parent {
                        insert_parent.children = Some(copy.into());
                    }
                    let mut now = copy;
                    while let Some(next) = now.next.map(|node| XmlNodePtr::try_from(node).unwrap())
                    {
                        now = next;
                    }
                    insert_last = Some(now);
                }

                if recurse != 0 {
                    cur = cur
                        .children
                        .map(|c| XmlNodePtr::try_from(c).unwrap())
                        .unwrap();
                    insert_parent = insert_last.take();
                    continue;
                }

                if cur == elem {
                    return result;
                }

                while cur.next.is_none() {
                    if let Some(mut insert_parent) = insert_parent {
                        insert_parent.last = insert_last.map(|node| node.into());
                    }
                    cur = cur
                        .parent
                        .map(|p| XmlNodePtr::try_from(p).unwrap())
                        .unwrap();
                    if cur == elem {
                        return result;
                    }
                    insert_last = insert_parent;
                    insert_parent = insert_parent
                        .unwrap()
                        .parent
                        .map(|p| XmlNodePtr::try_from(p).unwrap());
                }

                cur = cur
                    .next
                    .map(|node| XmlNodePtr::try_from(node).unwrap())
                    .unwrap();
            }

            // error:
            // xmlFreeNodeList(result);
            // return null_mut();
        }
    }

    /// Test if the node is an XInclude node
    ///
    /// Returns 1 true, 0 otherwise
    #[doc(alias = "xmlXIncludeTestNode")]
    unsafe fn test_node(&mut self, node: XmlNodePtr) -> i32 {
        unsafe {
            if node.element_type() != XmlElementType::XmlElementNode {
                return 0;
            }
            let Some(node_ns) = node.ns else {
                return 0;
            };
            if node_ns.href().as_deref() == Some(XINCLUDE_NS)
                || node_ns.href().as_deref() == Some(XINCLUDE_OLD_NS)
            {
                if node_ns.href().as_deref() == Some(XINCLUDE_OLD_NS) && self.legacy == 0 {
                    self.legacy = 1;
                }
                if node.name().as_deref() == Some(XINCLUDE_NODE) {
                    let mut child = node.children.map(|c| XmlNodePtr::try_from(c).unwrap());
                    let mut nb_fallback: i32 = 0;

                    while let Some(cur_node) = child {
                        if cur_node.element_type() == XmlElementType::XmlElementNode
                            && cur_node.ns.is_some_and(|ns| {
                                ns.href().as_deref() == Some(XINCLUDE_NS)
                                    || ns.href().as_deref() == Some(XINCLUDE_OLD_NS)
                            })
                        {
                            if cur_node.name().as_deref() == Some(XINCLUDE_NODE) {
                                xml_xinclude_err!(
                                    self,
                                    Some(node.into()),
                                    XmlParserErrors::XmlXIncludeIncludeInInclude,
                                    "{} has an 'include' child\n",
                                    XINCLUDE_NODE
                                );
                                return 0;
                            }
                            if cur_node.name().as_deref() == Some(XINCLUDE_FALLBACK) {
                                nb_fallback += 1;
                            }
                        }
                        child = cur_node
                            .next
                            .map(|node| XmlNodePtr::try_from(node).unwrap());
                    }
                    if nb_fallback > 1 {
                        xml_xinclude_err!(
                            self,
                            Some(node.into()),
                            XmlParserErrors::XmlXIncludeFallbacksInInclude,
                            "{} has multiple fallback children\n",
                            XINCLUDE_NODE
                        );
                        return 0;
                    }
                    return 1;
                }
                if node.name().as_deref() == Some(XINCLUDE_FALLBACK)
                    && (node.parent().is_none()
                        || node.parent().unwrap().element_type() != XmlElementType::XmlElementNode
                        || XmlNodePtr::try_from(node.parent().unwrap())
                            .unwrap()
                            .ns
                            .is_none_or(|ns| {
                                ns.href().as_deref() != Some(XINCLUDE_NS)
                                    && ns.href().as_deref() != Some(XINCLUDE_OLD_NS)
                            })
                        || node.parent().unwrap().name().as_deref() != Some(XINCLUDE_NODE))
                {
                    xml_xinclude_err!(
                        self,
                        Some(node.into()),
                        XmlParserErrors::XmlXIncludeFallbackNotInInclude,
                        "{} is not the child of an 'include'\n",
                        XINCLUDE_FALLBACK
                    );
                }
            }
            0
        }
    }

    /// If the XInclude node wasn't processed yet, create a new RefPtr,
    /// add it to self.incTab and load the included items.
    ///
    /// Returns the index of new or existing `XmlXIncludeRef` or `usize::MAX` in case of error.
    #[doc(alias = "xmlXIncludeExpandNode")]
    unsafe fn expand_node(&mut self, node: XmlNodePtr) -> usize {
        unsafe {
            if self.fatal_err != 0 {
                return usize::MAX;
            }
            if self.depth >= XINCLUDE_MAX_DEPTH {
                xml_xinclude_err!(
                    self,
                    Some(node.into()),
                    XmlParserErrors::XmlXIncludeRecursion,
                    "maximum recursion depth exceeded\n"
                );
                self.fatal_err = 1;
                return usize::MAX;
            }

            for (i, inc) in self.inc_tab.iter().enumerate() {
                if inc.elem == Some(node) {
                    if inc.expanding != 0 {
                        xml_xinclude_err!(
                            self,
                            Some(node.into()),
                            XmlParserErrors::XmlXIncludeRecursion,
                            "inclusion loop detected\n"
                        );
                        return usize::MAX;
                    }
                    return i;
                }
            }

            let refe = self.add_node(node);
            if refe == usize::MAX {
                return usize::MAX;
            }
            self.inc_tab[refe].expanding = 1;
            self.depth += 1;
            self.load_node(refe);
            self.depth -= 1;
            self.inc_tab[refe].expanding = 0;

            refe
        }
    }

    /// Implement the infoset replacement for the given node
    ///
    /// Returns 0 if substitution succeeded, -1 if some processing failed
    #[doc(alias = "xmlXIncludeIncludeNode")]
    unsafe fn include_node(&mut self, ref_index: usize) -> i32 {
        unsafe {
            if ref_index == usize::MAX {
                return -1;
            }
            let cur = self.inc_tab[ref_index].elem;
            let Some(mut cur) =
                cur.filter(|cur| cur.element_type() != XmlElementType::XmlNamespaceDecl)
            else {
                return -1;
            };

            let mut list = self.inc_tab[ref_index].inc.take();
            self.inc_tab[ref_index].empty_fb = 0;

            // Check against the risk of generating a multi-rooted document
            if cur
                .parent()
                .filter(|p| p.element_type() != XmlElementType::XmlElementNode)
                .is_some()
            {
                let mut nb_elem: i32 = 0;

                let mut tmp = list;
                while let Some(cur) = tmp {
                    if cur.element_type() == XmlElementType::XmlElementNode {
                        nb_elem += 1;
                    }
                    tmp = cur.next.map(|node| XmlNodePtr::try_from(node).unwrap());
                }
                if nb_elem > 1 {
                    xml_xinclude_err!(
                        self,
                        self.inc_tab[ref_index].elem.map(|node| node.into()),
                        XmlParserErrors::XmlXIncludeMultipleRoot,
                        "XInclude error: would result in multiple root nodes\n"
                    );
                    xml_free_node_list(list);
                    return -1;
                }
            }

            if self.parse_flags & XmlParserOption::XmlParseNoXIncnode as i32 != 0 {
                // Add the list of nodes
                while let Some(cur_node) = list {
                    list = cur_node
                        .next
                        .map(|node| XmlNodePtr::try_from(node).unwrap());

                    cur.add_prev_sibling(XmlGenericNodePtr::from(cur_node));
                }
                // FIXME: xmlUnlinkNode doesn't coalesce text nodes.
                cur.unlink();
                xml_free_node(cur);
            } else {
                // Change the current node as an XInclude start one, and add an XInclude end one
                if self.inc_tab[ref_index].fallback != 0 {
                    cur.unset_prop("href");
                }
                cur.typ = XmlElementType::XmlXIncludeStart;
                // Remove fallback children
                let mut child = cur.children();
                while let Some(mut now) = child {
                    let next = now.next();
                    now.unlink();
                    xml_free_node(now);
                    child = next;
                }
                let Some(mut end) = xml_new_doc_node(cur.doc, cur.ns, &cur.name().unwrap(), None)
                else {
                    xml_xinclude_err!(
                        self,
                        self.inc_tab[ref_index].elem.map(|node| node.into()),
                        XmlParserErrors::XmlXIncludeBuildFailed,
                        "failed to build node\n"
                    );
                    xml_free_node_list(list);
                    return -1;
                };
                end.typ = XmlElementType::XmlXIncludeEnd;
                cur.add_next_sibling(end.into());

                // Add the list of nodes
                while let Some(cur_node) = list {
                    list = cur_node
                        .next
                        .map(|node| XmlNodePtr::try_from(node).unwrap());

                    end.add_prev_sibling(XmlGenericNodePtr::from(cur_node));
                }
            }

            0
        }
    }

    /// Implements the entity merge
    ///
    /// Returns 0 if merge succeeded, -1 if some processing failed
    #[doc(alias = "xmlXIncludeMergeEntities")]
    unsafe fn merge_entities(&mut self, doc: XmlDocPtr, from: XmlDocPtr) -> i32 {
        unsafe {
            if from.int_subset.is_none() {
                return 0;
            }

            let Some(target) = doc.int_subset.or_else(|| {
                let cur = doc.get_root_element()?;
                xml_create_int_subset(Some(doc), cur.name().as_deref(), None, None)
            }) else {
                return -1;
            };

            let source = from.int_subset;
            if let Some(source) = source {
                for &entity in source.entities.values() {
                    self.merge_entity(entity, doc);
                }
            }
            let source = from.ext_subset;
            if let Some(source) = source {
                // don't duplicate existing stuff when external subsets are the same
                if target.external_id != source.external_id && target.system_id != source.system_id
                {
                    for &entity in source.entities.values() {
                        self.merge_entity(entity, doc);
                    }
                }
            }
            0
        }
    }

    /// Implements the merge of one entity
    #[doc(alias = "xmlXIncludeMergeOneEntity")]
    unsafe fn merge_entity(&mut self, ent: XmlEntityPtr, doc: XmlDocPtr) {
        unsafe {
            match ent.etype {
                XmlEntityType::XmlInternalParameterEntity
                | XmlEntityType::XmlExternalParameterEntity
                | XmlEntityType::XmlInternalPredefinedEntity => return,
                XmlEntityType::XmlInternalGeneralEntity
                | XmlEntityType::XmlExternalGeneralParsedEntity
                | XmlEntityType::XmlExternalGeneralUnparsedEntity => {}
            }

            let ret = xml_add_doc_entity(
                doc,
                &ent.name().unwrap(),
                ent.etype,
                ent.external_id.as_deref(),
                ent.system_id.as_deref(),
                ent.content.as_deref(),
            );
            if let Some(mut ret) = ret {
                ret.uri = ent.uri.clone();
                return;
            }

            'error: {
                let prev = xml_get_doc_entity(Some(doc), &ent.name().unwrap());
                if let Some(prev) = prev {
                    if ent.etype != prev.etype {
                        break 'error;
                    }

                    if ent.system_id.is_some() && prev.system_id.is_some() {
                        if ent.system_id != prev.system_id {
                            break 'error;
                        }
                    } else if ent.external_id.is_some() && prev.external_id.is_some() {
                        if ent.external_id != prev.external_id {
                            break 'error;
                        }
                    } else if ent.content.is_some() && prev.content.is_some() {
                        if ent.content != prev.content {
                            break 'error;
                        }
                    } else {
                        break 'error;
                    }
                }
                return;
            }
            match ent.etype {
                XmlEntityType::XmlInternalParameterEntity
                | XmlEntityType::XmlExternalParameterEntity
                | XmlEntityType::XmlInternalPredefinedEntity
                | XmlEntityType::XmlInternalGeneralEntity
                | XmlEntityType::XmlExternalGeneralParsedEntity => return,
                XmlEntityType::XmlExternalGeneralUnparsedEntity => {}
            }
            xml_xinclude_err!(
                self,
                Some(ent.into()),
                XmlParserErrors::XmlXIncludeEntityDefMismatch,
                "mismatch in redefinition of entity {}\n",
                ent.name().unwrap().into_owned()
            );
        }
    }

    /// Build a node list tree copy of the XPointer result.
    /// This will drop Attributes and Namespace declarations.
    ///
    /// Returns an xmlNodePtr list or NULL.
    /// The caller has to free the node tree.
    #[doc(alias = "xmlXIncludeCopyXPointer")]
    unsafe fn copy_xpointer(&mut self, obj: &XmlXPathObject) -> Option<XmlNodePtr> {
        unsafe {
            let mut list: Option<XmlNodePtr> = None;

            match obj.typ {
                XmlXPathObjectType::XPathNodeset => {
                    let set = obj.nodesetval.as_deref()?;
                    let mut last: Option<XmlNodePtr> = None;
                    for &now in &set.node_tab {
                        let node = match now.element_type() {
                            XmlElementType::XmlDocumentNode
                            | XmlElementType::XmlHTMLDocumentNode => {
                                let Some(node) =
                                    XmlDocPtr::try_from(now).unwrap().get_root_element()
                                else {
                                    xml_xinclude_err!(
                                        self,
                                        Some(now),
                                        XmlParserErrors::XmlErrInternalError,
                                        "document without root\n"
                                    );
                                    continue;
                                };
                                node
                            }
                            XmlElementType::XmlTextNode
                            | XmlElementType::XmlCDATASectionNode
                            | XmlElementType::XmlElementNode
                            | XmlElementType::XmlPINode
                            | XmlElementType::XmlCommentNode => XmlNodePtr::try_from(now).unwrap(),
                            _ => {
                                xml_xinclude_err!(
                                    self,
                                    Some(now),
                                    XmlParserErrors::XmlXIncludeXPtrResult,
                                    "invalid node type in XPtr result\n"
                                );
                                continue;
                            }
                        };
                        // OPTIMIZE TODO: External documents should already be
                        // expanded, so xmlDocCopyNode should work as well.
                        // xmlXIncludeCopyNode is only required for the initial document.
                        let Some(mut copy) = self.copy_node(node, 0) else {
                            xml_free_node_list(list);
                            return None;
                        };
                        if let Some(mut last) = last {
                            while let Some(next) =
                                last.next.map(|node| XmlNodePtr::try_from(node).unwrap())
                            {
                                last = next;
                            }
                            copy.prev = Some(last.into());
                            last.next = Some(copy.into());
                        } else {
                            list = Some(copy);
                        }
                        last = Some(copy);
                    }
                }
                #[cfg(feature = "libxml_xptr_locs")]
                XmlXPathObjectType::XPathLocationset => {
                    let set = obj.user.as_ref().and_then(|user| user.as_location_set())?;

                    let mut last: Option<XmlNodePtr> = None;
                    for loc in &set.loc_tab {
                        if let Some(mut last) = last {
                            last.add_next_sibling(self.copy_xpointer(loc).unwrap().into());
                        } else {
                            list = self.copy_xpointer(loc);
                            last = list;
                        }
                        if let Some(mut l) = last {
                            while let Some(next) =
                                l.next.map(|node| XmlNodePtr::try_from(node).unwrap())
                            {
                                l = next;
                            }
                            last = Some(l);
                        }
                    }
                }
                #[cfg(feature = "libxml_xptr_locs")]
                XmlXPathObjectType::XPathRange => {
                    return self
                        .copy_range(obj)
                        .map(|node| XmlNodePtr::try_from(node).unwrap());
                }
                #[cfg(feature = "libxml_xptr_locs")]
                XmlXPathObjectType::XPathPoint => { /* points are ignored in XInclude */ }
                _ => {}
            }
            list
        }
    }

    /// Build a node list tree copy of the XPointer result.
    ///
    /// Returns an xmlNodePtr list or NULL.
    /// The caller has to free the node tree.
    #[doc(alias = "xmlXIncludeCopyRange")]
    #[cfg(feature = "libxml_xptr_locs")]
    unsafe fn copy_range(&self, range: &XmlXPathObject) -> Option<XmlGenericNodePtr> {
        unsafe {
            use crate::{tree::xml_new_doc_text, xpointer::xml_xptr_advance_node};

            // pointers to generated nodes
            let mut list = None;
            let mut last = None;
            let mut list_parent = None;
            let mut level: i32 = 0;
            let mut last_level: i32 = 0;
            let mut end_level: i32 = 0;
            let mut end_flag: i32 = 0;

            if range.typ != XmlXPathObjectType::XPathRange {
                return None;
            }
            let start = range
                .user
                .as_ref()
                .and_then(|user| user.as_node())
                .copied()
                .filter(|node| node.element_type() != XmlElementType::XmlNamespaceDecl)?;

            let Some(mut end) = range
                .user2
                .as_ref()
                .and_then(|user| user.as_node())
                .copied()
            else {
                return xml_doc_copy_node(start, Some(self.doc), 1);
            };
            if end.element_type() == XmlElementType::XmlNamespaceDecl {
                return None;
            }

            let mut cur = Some(start);
            let mut index1 = range.index;
            let mut index2 = range.index2;
            // level is depth of the current node under consideration
            // list is the pointer to the root of the output tree
            // listParent is a pointer to the parent of output tree (within
            // the included file) in case we need to add another level
            // last is a pointer to the last node added to the output tree
            // lastLevel is the depth of last (relative to the root)
            while let Some(cur_node) = cur {
                // Check if our output tree needs a parent
                if level < 0 {
                    while level < 0 {
                        // copy must include namespaces and properties
                        let mut tmp2 =
                            xml_doc_copy_node(list_parent.unwrap(), Some(self.doc), 2).unwrap();
                        tmp2.add_child(list.unwrap());
                        list = Some(tmp2);
                        list_parent = list_parent.unwrap().parent();
                        level += 1;
                    }
                    last = list;
                    last_level = 0;
                }
                // Check whether we need to change our insertion point
                while level < last_level {
                    last = last.unwrap().parent();
                    last_level -= 1;
                }
                if cur_node == end {
                    // Are we at the end of the range?
                    if cur_node.element_type() == XmlElementType::XmlTextNode {
                        let cur_node = XmlNodePtr::try_from(cur_node).unwrap();

                        let tmp = if let Some(mut content) = cur_node.content.as_deref() {
                            let mut len = index2 as usize;
                            if start == XmlGenericNodePtr::from(cur_node) && index1 > 1 {
                                content = &content[index1 as usize - 1..];
                                len -= index1 as usize - 1;
                            }
                            xml_new_doc_text(Some(self.doc), Some(&content[..len]))
                        } else {
                            xml_new_doc_text(Some(self.doc), None)
                        };
                        // single sub text node selection
                        if list.is_none() {
                            return tmp.map(|node| node.into());
                        }
                        // prune and return full set
                        if level == last_level {
                            last.unwrap().add_next_sibling(tmp.unwrap().into());
                        } else {
                            last.unwrap().add_child(tmp.unwrap().into());
                        }
                        return list;
                    } else {
                        // ending node not a text node
                        end_level = level; /* remember the level of the end node */
                        end_flag = 1;
                        // last node - need to take care of properties + namespaces
                        let tmp = xml_doc_copy_node(cur_node, Some(self.doc), 2);
                        if list.is_none() {
                            list = tmp;
                            list_parent = cur_node.parent();
                            last = tmp;
                        } else if level == last_level {
                            last = last.unwrap().add_next_sibling(tmp.unwrap());
                        } else {
                            last = last.unwrap().add_child(tmp.unwrap());
                            last_level = level;
                        }

                        if index2 > 1 {
                            end = xml_xinclude_get_nth_child(cur_node, index2 - 1).unwrap();
                            index2 = 0;
                        }
                        if cur_node == start && index1 > 1 {
                            cur = xml_xinclude_get_nth_child(cur_node, index1 - 1);
                            index1 = 0;
                        } else {
                            cur = cur_node.children();
                        }
                        // increment level to show change
                        level += 1;
                        // Now gather the remaining nodes from cur to end
                        continue; /* while */
                    }
                } else if cur_node == start {
                    // Not at the end, are we at start?
                    if matches!(
                        cur_node.element_type(),
                        XmlElementType::XmlTextNode | XmlElementType::XmlCDATASectionNode
                    ) {
                        let cur_node = XmlNodePtr::try_from(cur_node).unwrap();

                        let tmp = if let Some(mut content) = cur_node.content.as_deref() {
                            if index1 > 1 {
                                content = &content[index1 as usize - 1..];
                                index1 = 0;
                            }
                            xml_new_doc_text(Some(self.doc), Some(content))
                        } else {
                            xml_new_doc_text(Some(self.doc), None)
                        };
                        last = tmp.map(|node| node.into());
                        list = tmp.map(|node| node.into());
                        list_parent = cur_node.parent();
                    } else {
                        // Not text node

                        // start of the range - need to take care of
                        // properties and namespaces
                        let tmp = xml_doc_copy_node(cur_node, Some(self.doc), 2);
                        list = tmp;
                        last = tmp;
                        list_parent = cur_node.parent();
                        if index1 > 1 {
                            // Do we need to position?
                            cur = xml_xinclude_get_nth_child(cur_node, index1 - 1);
                            level = 1;
                            last_level = 1;
                            index1 = 0;
                            // Now gather the remaining nodes from cur to end
                            continue; /* while */
                        }
                    }
                } else {
                    let mut tmp = None;
                    match cur_node.element_type() {
                        XmlElementType::XmlDTDNode
                        | XmlElementType::XmlElementDecl
                        | XmlElementType::XmlAttributeDecl
                        | XmlElementType::XmlEntityNode => { /* Do not copy DTD information */ }
                        XmlElementType::XmlEntityDecl => { /* handle crossing entities -> stack needed */
                        }
                        XmlElementType::XmlXIncludeStart | XmlElementType::XmlXIncludeEnd => {
                            // don't consider it part of the tree content
                        }
                        XmlElementType::XmlAttributeNode => { /* Humm, should not happen ! */ }
                        _ => {
                            // Middle of the range - need to take care of
                            // properties and namespaces
                            tmp = xml_doc_copy_node(cur_node, Some(self.doc), 2);
                        }
                    }
                    if let Some(tmp) = tmp {
                        if level == last_level {
                            last = last.unwrap().add_next_sibling(tmp);
                        } else {
                            last = last.unwrap().add_child(tmp);
                            last_level = level;
                        }
                    }
                }
                // Skip to next node in document order
                cur = xml_xptr_advance_node(cur_node, &mut level);
                if end_flag != 0 && level >= end_level {
                    break;
                }
            }
            list
        }
    }

    /// The XInclude recursive nature is handled at this point.
    #[doc(alias = "xmlXIncludeRecurseDoc")]
    unsafe fn recurse_doc(&mut self, doc: XmlDocPtr, _url: &str) {
        unsafe {
            let old_doc = self.doc;
            let old_inc_tab = take(&mut self.inc_tab);
            let old_is_stream: i32 = self.is_stream;
            self.doc = doc;
            self.is_stream = 0;

            self.do_process(doc.get_root_element().unwrap());

            self.doc = old_doc;
            self.inc_tab = old_inc_tab;
            self.is_stream = old_is_stream;
        }
    }

    /// Load the document, and store the result in the XInclude context
    ///
    /// Returns 0 in case of success, -1 in case of failure
    #[doc(alias = "xmlXIncludeLoadDoc")]
    unsafe fn load_doc(&mut self, url: &str, ref_index: usize) -> i32 {
        unsafe {
            let ret: i32 = -1;
            #[cfg(feature = "xpointer")]
            let save_flags: i32;

            // Check the URL and remove any fragment identifier
            let Some(mut uri) = XmlURI::parse(url) else {
                xml_xinclude_err!(
                    self,
                    self.inc_tab[ref_index].elem.map(|node| node.into()),
                    XmlParserErrors::XmlXIncludeHrefURI,
                    "invalid value URI {}\n",
                    url
                );
                return ret;
            };
            let mut fragment = uri.fragment.take();
            if let Some(frag) = self.inc_tab[ref_index].fragment.as_deref() {
                fragment = Some(Cow::Owned(frag.to_owned()));
            }
            let mut url = uri.save();

            // Handling of references to the local document are done
            // directly through (*ctxt).doc.
            let doc = 'load: {
                if url.is_empty() || url.starts_with('#') || self.doc.url.as_deref() == Some(&url) {
                    break 'load self.doc;
                }
                // Prevent reloading the document twice.
                for inc_doc in &self.url_tab {
                    if *url == *inc_doc.url {
                        if inc_doc.expanding != 0 {
                            xml_xinclude_err!(
                                self,
                                self.inc_tab[ref_index].elem.map(|node| node.into()),
                                XmlParserErrors::XmlXIncludeRecursion,
                                "inclusion loop detected\n"
                            );
                            return ret;
                        }
                        let Some(doc) = inc_doc.doc else {
                            return ret;
                        };
                        break 'load doc;
                    }
                }

                // Load it.
                #[cfg(feature = "xpointer")]
                {
                    // If this is an XPointer evaluation, we want to assure that
                    // all entities have been resolved prior to processing the
                    // referenced document
                    save_flags = self.parse_flags;
                    if fragment.is_some() {
                        // if this is an XPointer eval
                        self.parse_flags |= XmlParserOption::XmlParseNoEnt as i32;
                    }
                }

                let doc = self.parse_file(&url);
                #[cfg(feature = "xpointer")]
                {
                    self.parse_flags = save_flags;
                }

                // Also cache NULL docs
                let cache_nr = self.url_tab.len();
                self.url_tab.push(XmlXIncludeDoc {
                    doc,
                    url: url.clone().into_boxed_str(),
                    expanding: 0,
                });

                let Some(doc) = doc else {
                    return ret;
                };
                // It's possible that the requested URL has been mapped to a
                // completely different location (e.g. through a catalog entry).
                // To check for this, we compare the URL with that of the doc
                // and change it if they disagree (bug 146988).
                if doc.url.as_deref() != Some(&url) {
                    url = doc.url.clone().unwrap();
                }

                // Make sure we have all entities fixed up
                self.merge_entities(self.doc, doc);

                // We don't need the DTD anymore, free up space
                // if ((*doc).intSubset != null_mut()) {
                //     xmlUnlinkNode((xmlNodePtr) (*doc).intSubset);
                //     xmlFreeNode((xmlNodePtr) (*doc).intSubset);
                //     (*doc).intSubset = NULL;
                // }
                // if ((*doc).extSubset != null_mut()) {
                //     xmlUnlinkNode((xmlNodePtr) (*doc).extSubset);
                //     xmlFreeNode((xmlNodePtr) (*doc).extSubset);
                //     (*doc).extSubset = NULL;
                // }
                self.url_tab[cache_nr].expanding = 1;
                self.recurse_doc(doc, &url);
                // urlTab might be reallocated.
                self.url_tab[cache_nr].expanding = 0;
                doc
            };

            // loaded:
            if let Some(fragment) = fragment {
                #[cfg(feature = "xpointer")]
                {
                    // Computes the XPointer expression and make a copy used
                    // as the replacement copy.

                    if self.is_stream != 0 && doc == self.doc {
                        xml_xinclude_err!(
                            self,
                            self.inc_tab[ref_index].elem.map(|node| node.into()),
                            XmlParserErrors::XmlXIncludeXPtrFailed,
                            "XPointer expressions not allowed in streaming mode\n"
                        );
                        return ret;
                    }

                    let mut xptrctxt = xml_xptr_new_context(Some(doc), None, None);
                    let Some(mut xptr) = xml_xptr_eval(&fragment, &mut xptrctxt) else {
                        xml_xinclude_err!(
                            self,
                            self.inc_tab[ref_index].elem.map(|node| node.into()),
                            XmlParserErrors::XmlXIncludeXPtrFailed,
                            "XPointer evaluation failed: #{}\n",
                            fragment
                        );
                        return ret;
                    };
                    match xptr.typ {
                        XmlXPathObjectType::XPathUndefined
                        | XmlXPathObjectType::XPathBoolean
                        | XmlXPathObjectType::XPathNumber
                        | XmlXPathObjectType::XPathString
                        | XmlXPathObjectType::XPathUsers
                        | XmlXPathObjectType::XPathXSLTTree => {
                            xml_xinclude_err!(
                                self,
                                self.inc_tab[ref_index].elem.map(|node| node.into()),
                                XmlParserErrors::XmlXIncludeXPtrResult,
                                "XPointer is not a range: #{}\n",
                                fragment
                            );
                            return ret;
                        }
                        #[cfg(feature = "libxml_xptr_locs")]
                        XmlXPathObjectType::XPathPoint => {
                            xml_xinclude_err!(
                                self,
                                self.inc_tab[ref_index].elem.map(|node| node.into()),
                                XmlParserErrors::XmlXIncludeXPtrResult,
                                "XPointer is not a range: #{}\n",
                                fragment
                            );
                            return ret;
                        }
                        XmlXPathObjectType::XPathNodeset => {
                            if xptr.nodesetval.as_deref().is_none_or(|n| n.is_empty()) {
                                return ret;
                            }
                        }
                        #[cfg(feature = "libxml_xptr_locs")]
                        XmlXPathObjectType::XPathRange | XmlXPathObjectType::XPathLocationset => {} // _ => {}
                    }
                    if let Some(set) = xptr.nodesetval.as_deref_mut() {
                        let mut i = 0;
                        while i < set.node_tab.len() {
                            let node = set.node_tab[i];
                            match node.element_type() {
                                XmlElementType::XmlElementNode
                                | XmlElementType::XmlTextNode
                                | XmlElementType::XmlCDATASectionNode
                                | XmlElementType::XmlEntityRefNode
                                | XmlElementType::XmlEntityNode
                                | XmlElementType::XmlPINode
                                | XmlElementType::XmlCommentNode
                                | XmlElementType::XmlDocumentNode
                                | XmlElementType::XmlHTMLDocumentNode => {
                                    // continue to next loop
                                }

                                XmlElementType::XmlAttributeNode => {
                                    xml_xinclude_err!(
                                        self,
                                        self.inc_tab[ref_index].elem.map(|node| node.into()),
                                        XmlParserErrors::XmlXIncludeXPtrResult,
                                        "XPointer selects an attribute: #{}\n",
                                        fragment
                                    );
                                    set.node_tab.swap_remove(i);
                                    continue;
                                }
                                XmlElementType::XmlNamespaceDecl => {
                                    xml_xinclude_err!(
                                        self,
                                        self.inc_tab[ref_index].elem.map(|node| node.into()),
                                        XmlParserErrors::XmlXIncludeXPtrResult,
                                        "XPointer selects a namespace: #{}\n",
                                        fragment
                                    );
                                    set.node_tab.swap_remove(i);
                                    continue;
                                }
                                XmlElementType::XmlDocumentTypeNode
                                | XmlElementType::XmlDocumentFragNode
                                | XmlElementType::XmlNotationNode
                                | XmlElementType::XmlDTDNode
                                | XmlElementType::XmlElementDecl
                                | XmlElementType::XmlAttributeDecl
                                | XmlElementType::XmlEntityDecl
                                | XmlElementType::XmlXIncludeStart
                                | XmlElementType::XmlXIncludeEnd => {
                                    xml_xinclude_err!(
                                        self,
                                        self.inc_tab[ref_index].elem.map(|node| node.into()),
                                        XmlParserErrors::XmlXIncludeXPtrResult,
                                        "XPointer selects unexpected nodes: #{}\n",
                                        fragment
                                    );
                                    set.node_tab.swap_remove(i);
                                    continue; /* for */
                                }
                                _ => unreachable!(),
                            }
                            i += 1;
                        }
                    }
                    self.inc_tab[ref_index].inc = self.copy_xpointer(&xptr);
                }
            } else {
                // Add the top children list as the replacement copy.
                self.inc_tab[ref_index].inc =
                    xml_doc_copy_node(doc.get_root_element().unwrap().into(), Some(self.doc), 1)
                        .and_then(|node| XmlNodePtr::try_from(node).ok());
            }

            // Do the xml:base fixup if needed
            if doc.parse_flags & XmlParserOption::XmlParseNoBasefix as i32 == 0
                && self.parse_flags & XmlParserOption::XmlParseNoBasefix as i32 == 0
            {
                // The base is only adjusted if "necessary", i.e. if the xinclude node
                // has a base specified, or the URL is relative
                let mut base = self.inc_tab[ref_index]
                    .elem
                    .unwrap()
                    .get_ns_prop("base", Some(XML_XML_NAMESPACE));
                if base.is_none() {
                    // No xml:base on the xinclude node, so we check whether the
                    // URI base is different than (relative to) the context base
                    if let Some(cur_base) = build_relative_uri(&url, self.base.as_deref()) {
                        // If the URI doesn't contain a slash, it's not relative
                        if cur_base.contains('/') {
                            base = Some(cur_base.into_owned());
                        }
                    } else {
                        // Error return
                        xml_xinclude_err!(
                            self,
                            self.inc_tab[ref_index].elem.map(|node| node.into()),
                            XmlParserErrors::XmlXIncludeHrefURI,
                            "trying to build relative URI from {}\n",
                            url
                        );
                    }
                }
                if let Some(base) = base {
                    // Adjustment may be needed
                    let mut node = self.inc_tab[ref_index].inc;
                    while let Some(mut cur_node) = node {
                        // Only work on element nodes
                        if cur_node.element_type() == XmlElementType::XmlElementNode {
                            if let Some(cur_base) = cur_node.get_base(cur_node.doc) {
                                // If the current base is the same as the
                                // URL of the document, then reset it to be
                                // the specified xml:base or the relative URI
                                if cur_node.doc.as_deref().and_then(|doc| doc.url.as_deref())
                                    == Some(cur_base.as_str())
                                {
                                    cur_node.set_base(Some(&base));
                                } else {
                                    // If the element already has an xml:base set,
                                    // then relativise it if necessary

                                    if let Some(xml_base) =
                                        cur_node.get_ns_prop("base", Some(XML_XML_NAMESPACE))
                                    {
                                        let rel_base = build_uri(&xml_base, &base);
                                        if let Some(rel_base) = rel_base {
                                            cur_node.set_base(Some(&rel_base));
                                        } else {
                                            // error
                                            xml_xinclude_err!(
                                                self,
                                                self.inc_tab[ref_index]
                                                    .elem
                                                    .map(|node| node.into()),
                                                XmlParserErrors::XmlXIncludeHrefURI,
                                                "trying to rebuild base from {}\n",
                                                xml_base
                                            );
                                        }
                                    }
                                }
                            } else {
                                // If no current base, set it
                                cur_node.set_base(Some(&base));
                            }
                        }
                        node = cur_node
                            .next
                            .map(|node| XmlNodePtr::try_from(node).unwrap());
                    }
                }
            }
            0
        }
    }

    /// Load the content, and store the result in the XInclude context
    ///
    /// Returns 0 in case of success, -1 in case of failure
    #[doc(alias = "xmlXIncludeLoadTxt")]
    unsafe fn load_txt(&mut self, mut url: &str, ref_index: usize) -> i32 {
        unsafe {
            let ret: i32 = -1;
            let mut enc = XmlCharEncoding::None;

            // Don't read from stdin.
            if url == "-" {
                url = "./-";
            }

            // Check the URL and remove any fragment identifier
            let Some(uri) = XmlURI::parse(url) else {
                xml_xinclude_err!(
                    self,
                    self.inc_tab[ref_index].elem.map(|node| node.into()),
                    XmlParserErrors::XmlXIncludeHrefURI,
                    "invalid value URI {}\n",
                    url
                );
                return ret;
            };
            if let Some(fragment) = uri.fragment.as_deref() {
                xml_xinclude_err!(
                    self,
                    self.inc_tab[ref_index].elem.map(|node| node.into()),
                    XmlParserErrors::XmlXIncludeTextFragment,
                    "fragment identifier forbidden for text: {}\n",
                    fragment
                );
                return ret;
            }
            let url = uri.save();

            // Handling of references to the local document are done directly through (*ctxt).doc.
            if url.is_empty() {
                xml_xinclude_err!(
                    self,
                    self.inc_tab[ref_index].elem.map(|node| node.into()),
                    XmlParserErrors::XmlXIncludeTextDocument,
                    "text serialization of document not available\n"
                );
                return ret;
            }

            // Prevent reloading the document twice.
            for txt in &self.txt_tab {
                if *url == *txt.url {
                    let node = xml_new_doc_text(Some(self.doc), Some(&txt.text));
                    self.inc_tab[ref_index].inc = node;
                    return 0;
                }
            }

            // Try to get the encoding if available
            let mut encoding = None;
            if let Some(elem) = self.inc_tab[ref_index].elem {
                encoding = elem.get_prop(XINCLUDE_PARSE_ENCODING);
            }
            if let Some(encoding) = encoding {
                // TODO: we should not have to remap to the xmlCharEncoding
                //       predefined set, a better interface than
                //       xmlParserInputBufferCreateFilename should allow any
                //       encoding supported by iconv
                match encoding.parse::<XmlCharEncoding>() {
                    Ok(e) => enc = e,
                    _ => {
                        xml_xinclude_err!(
                            self,
                            self.inc_tab[ref_index].elem.map(|node| node.into()),
                            XmlParserErrors::XmlXIncludeUnknownEncoding,
                            "encoding {} not supported\n",
                            encoding
                        );
                        return ret;
                    }
                }
            }

            // Load it.
            let mut pctxt = XmlParserCtxt::new().unwrap();
            let Some(mut input_stream) = xml_load_external_entity(Some(&url), None, &mut pctxt)
            else {
                return ret;
            };
            let Some(buf) = input_stream.buf.as_mut() else {
                return ret;
            };
            buf.encoder = get_encoding_handler(enc);
            let Some(mut node) = xml_new_doc_text(Some(self.doc), None) else {
                let node = self.inc_tab[ref_index].elem.map(|node| node.into());
                xml_xinclude_err_memory(Some(self), node, None);
                return ret;
            };

            // Scan all chars from the resource and add the to the node
            while buf.grow(4096) > 0 {}

            let content = buf.buffer.as_ref();
            match std::str::from_utf8(content) {
                Ok(content) if content.chars().all(|c| c.is_xml_char()) => {
                    node.add_content(content);
                }
                _ => {
                    xml_xinclude_err!(
                        self,
                        self.inc_tab[ref_index].elem.map(|node| node.into()),
                        XmlParserErrors::XmlXIncludeInvalidChar,
                        "{} contains invalid char\n",
                        url
                    );
                    // goto error;
                    xml_free_node(node);
                    return ret;
                }
            }

            self.txt_tab.push(XmlXIncludeTxt {
                text: node.content.as_deref().unwrap().into(),
                url: url.into_boxed_str(),
            });

            // loaded:
            // Add the element as the replacement copy.
            self.inc_tab[ref_index].inc = Some(node);
            0
        }
    }

    /// Load the content of the fallback node, and store the result in the XInclude context
    ///
    /// Returns 0 in case of success, -1 in case of failure
    #[doc(alias = "xmlXIncludeLoadFallback")]
    unsafe fn load_fallback(&mut self, fallback: XmlNodePtr, ref_index: usize) -> i32 {
        unsafe {
            let mut ret: i32 = 0;

            if fallback.element_type() == XmlElementType::XmlNamespaceDecl {
                return -1;
            }
            if fallback.children().is_some() {
                // It's possible that the fallback also has 'includes'
                // (Bug 129969), so we re-process the fallback just in case
                let old_nb_errors = self.nb_errors;
                self.inc_tab[ref_index].inc = self.copy_node(fallback, 1);
                if self.nb_errors > old_nb_errors {
                    ret = -1;
                } else if self.inc_tab[ref_index].inc.is_none() {
                    self.inc_tab[ref_index].empty_fb = 1;
                }
            } else {
                self.inc_tab[ref_index].inc = None;
                self.inc_tab[ref_index].empty_fb = 1; /* flag empty callback */
            }
            self.inc_tab[ref_index].fallback = 1;
            ret
        }
    }

    /// Find and load the infoset replacement for the given node.
    ///
    /// Returns 0 if substitution succeeded, -1 if some processing failed
    #[doc(alias = "xmlXIncludeLoadNode")]
    unsafe fn load_node(&mut self, ref_index: usize) -> i32 {
        unsafe {
            let mut xml: i32 = 1; /* default Issue 64 */
            let mut ret: i32;

            if ref_index == usize::MAX {
                return -1;
            }
            let Some(cur) = self.inc_tab[ref_index].elem else {
                return -1;
            };

            // read the attributes
            let href = self.get_prop(cur, XINCLUDE_HREF).unwrap_or("".to_owned());
            let parse = self.get_prop(cur, XINCLUDE_PARSE);
            if let Some(parse) = parse {
                if parse == XINCLUDE_PARSE_XML {
                    xml = 1;
                } else if parse == XINCLUDE_PARSE_TEXT {
                    xml = 0;
                } else {
                    xml_xinclude_err!(
                        self,
                        Some(cur.into()),
                        XmlParserErrors::XmlXIncludeParseValue,
                        "invalid value {} for 'parse'\n",
                        parse
                    );
                    return -1;
                }
            }

            // compute the URI
            let mut base = None;
            let mut uri = if let Some(b) = cur.get_base(Some(self.doc)) {
                base = Some(b);
                build_uri(&href, base.as_deref().unwrap())
            } else {
                self.doc
                    .url
                    .as_deref()
                    .and_then(|base| build_uri(&href, base))
            };
            if uri.is_none() {
                if let Some(base) = base.as_deref() {
                    // Some escaping may be needed
                    if let (Some(escbase), Some(eschref)) = (escape_url(base), escape_url(&href)) {
                        uri = build_uri(&eschref, &escbase);
                    }
                }
            }
            let Some(uri) = uri else {
                xml_xinclude_err!(
                    self,
                    Some(cur.into()),
                    XmlParserErrors::XmlXIncludeHrefURI,
                    "failed build URL\n"
                );
                return -1;
            };

            // Save the base for this include (saving the current one)
            let old_base = self.base.take();
            self.base = base.map(|base| base.into());

            if xml != 0 {
                ret = self.load_doc(&uri, ref_index);
                // xmlXIncludeGetFragment(self, cur, URI);
            } else {
                ret = self.load_txt(&uri, ref_index);
            }

            // Restore the original base before checking for fallback
            self.base = old_base;

            if ret < 0 {
                // Time to try a fallback if available
                let mut children = cur.children.map(|c| XmlNodePtr::try_from(c).unwrap());
                while let Some(cur_node) = children {
                    if cur_node.element_type() == XmlElementType::XmlElementNode
                        && cur_node.name().as_deref() == Some(XINCLUDE_FALLBACK)
                        && cur_node.ns.is_some_and(|ns| {
                            ns.href().as_deref() == Some(XINCLUDE_NS)
                                || ns.href().as_deref() == Some(XINCLUDE_OLD_NS)
                        })
                    {
                        ret = self.load_fallback(cur_node, ref_index);
                        break;
                    }
                    children = cur_node
                        .next
                        .map(|node| XmlNodePtr::try_from(node).unwrap());
                }
            }
            if ret < 0 {
                xml_xinclude_err!(
                    self,
                    Some(cur.into()),
                    XmlParserErrors::XmlXIncludeNoFallback,
                    "could not load {}, and no fallback was found\n",
                    uri
                );
            }

            0
        }
    }

    /// Parse a document for XInclude
    #[doc(alias = "xmlXIncludeParseFile")]
    unsafe fn parse_file(&mut self, mut url: &str) -> Option<XmlDocPtr> {
        unsafe {
            xml_init_parser();

            let Some(mut pctxt) = XmlParserCtxt::new() else {
                xml_xinclude_err_memory(Some(self), None, Some("cannot allocate parser context"));
                return None;
            };

            // pass in the application data to the parser context.
            pctxt._private = self._private;

            pctxt.use_options(self.parse_flags | XmlParserOption::XmlParseDTDLoad as i32);

            // Don't read from stdin.
            if url == "-" {
                url = "./-";
            }

            let input_stream = xml_load_external_entity(Some(url), None, &mut pctxt)?;
            pctxt.input_push(input_stream);

            if pctxt.directory.is_none() {
                if let Some(dir) = xml_parser_get_directory(url) {
                    pctxt.directory = Some(dir.to_string_lossy().into_owned());
                }
            }

            pctxt.loadsubset |= XML_DETECT_IDS as i32;
            pctxt.parse_document();

            if pctxt.well_formed {
                pctxt.my_doc
            } else {
                if let Some(my_doc) = pctxt.my_doc.take() {
                    xml_free_doc(my_doc);
                }
                None
            }
        }
    }

    /// Implement the XInclude substitution on the XML document @doc
    ///
    /// Returns 0 if no substitution were done, -1 if some processing failed
    /// or the number of substitutions done.
    #[doc(alias = "xmlXIncludeDoProcess")]
    unsafe fn do_process(&mut self, tree: XmlNodePtr) -> i32 {
        unsafe {
            let mut ret: i32 = 0;

            if tree.element_type() == XmlElementType::XmlNamespaceDecl {
                return -1;
            }

            // First phase: lookup the elements in the document
            let start = self.inc_tab.len();
            let mut cur = tree;
            'main: while {
                'inner: {
                    // TODO: need to work on entities -> stack
                    if self.test_node(cur) == 1 {
                        let ref_index = self.expand_node(cur);
                        // Mark direct includes.
                        if ref_index != usize::MAX {
                            self.inc_tab[ref_index].replace = 1;
                        }
                    } else if let Some(children) = cur
                        .children()
                        .filter(|_| {
                            matches!(
                                cur.element_type(),
                                XmlElementType::XmlDocumentNode | XmlElementType::XmlElementNode
                            )
                        })
                        .map(|children| XmlNodePtr::try_from(children).unwrap())
                    {
                        cur = children;
                        break 'inner;
                    }
                    'b: loop {
                        if cur == tree {
                            break 'main;
                        }
                        if let Some(next) = cur.next.map(|node| XmlNodePtr::try_from(node).unwrap())
                        {
                            cur = next;
                            break 'b;
                        }
                        let Some(next) = cur.parent.map(|p| XmlNodePtr::try_from(p).unwrap())
                        else {
                            break 'main;
                        };

                        cur = next;
                    }
                }

                cur != tree
            } {}

            // Second phase: extend the original document infoset.
            let len = self.inc_tab.len();
            for i in start..len {
                if self.inc_tab[i].replace != 0 {
                    if self.inc_tab[i].inc.is_some() || self.inc_tab[i].empty_fb != 0 {
                        // (empty fallback)
                        self.include_node(i);
                    }
                    self.inc_tab[i].replace = 0;
                } else {
                    // Ignore includes which were added indirectly, for example
                    // inside xi:fallback elements.
                    if let Some(inc) = self.inc_tab[i].inc.take() {
                        xml_free_node_list(Some(inc));
                    }
                }
                ret += 1;
            }

            if self.is_stream != 0 {
                // incTab references nodes which will eventually be deleted in
                // streaming mode. The table is only required for XPointer
                // expressions which aren't allowed in streaming mode.
                self.inc_tab.clear();
            }

            ret
        }
    }

    /// Implement the XInclude substitution for the given subtree reusing
    /// the information and data coming from the given context.
    ///
    /// Returns 0 if no substitution were done, -1 if some processing failed
    /// or the number of substitutions done.
    #[doc(alias = "xmlXIncludeProcessNode")]
    pub unsafe fn process_node(&mut self, node: XmlNodePtr) -> i32 {
        unsafe {
            if node.element_type() == XmlElementType::XmlNamespaceDecl || node.doc.is_none() {
                return -1;
            }
            let mut ret = self.do_process(node);
            if ret >= 0 && self.nb_errors > 0 {
                ret = -1;
            }
            ret
        }
    }
}

impl Drop for XmlXIncludeCtxt {
    /// Free an XInclude context
    #[doc(alias = "xmlXIncludeFreeContext")]
    fn drop(&mut self) {
        for inc_doc in self.url_tab.drain(..) {
            if let Some(doc) = inc_doc.doc {
                unsafe {
                    xml_free_doc(doc);
                }
            }
        }
    }
}

/// Implement the XInclude substitution on the XML document @doc
///
/// Returns 0 if no substitution were done, -1 if some processing failed
/// or the number of substitutions done.
#[doc(alias = "xmlXIncludeProcess")]
pub unsafe fn xml_xinclude_process(doc: XmlDocPtr) -> i32 {
    unsafe { xml_xinclude_process_flags(doc, 0) }
}

/// Implement the XInclude substitution on the XML document @doc
///
/// Returns 0 if no substitution were done, -1 if some processing failed
/// or the number of substitutions done.
#[doc(alias = "xmlXIncludeProcessFlags")]
pub unsafe fn xml_xinclude_process_flags(doc: XmlDocPtr, flags: i32) -> i32 {
    unsafe { xml_xinclude_process_flags_data(doc, flags, null_mut()) }
}

/// Implement the XInclude substitution on the XML document @doc
///
/// Returns 0 if no substitution were done, -1 if some processing failed
/// or the number of substitutions done.
#[doc(alias = "xmlXIncludeProcessFlagsData")]
pub unsafe fn xml_xinclude_process_flags_data(
    doc: XmlDocPtr,
    flags: i32,
    data: *mut c_void,
) -> i32 {
    unsafe {
        let Some(tree) = doc.get_root_element() else {
            return -1;
        };
        xml_xinclude_process_tree_flags_data(tree, flags, data)
    }
}

const XINCLUDE_MAX_DEPTH: i32 = 40;

/// Handle an out of memory condition
#[doc(alias = "xmlXIncludeErrMemory")]
unsafe fn xml_xinclude_err_memory(
    ctxt: Option<&mut XmlXIncludeCtxt>,
    node: Option<XmlGenericNodePtr>,
    extra: Option<&str>,
) {
    let mut ptr = null_mut();
    if let Some(ctxt) = ctxt {
        ctxt.nb_errors += 1;
        ptr = ctxt as *mut XmlXIncludeCtxt;
    }
    if let Some(extra) = extra {
        __xml_raise_error!(
            None,
            None,
            None,
            ptr as _,
            node,
            XmlErrorDomain::XmlFromXInclude,
            XmlParserErrors::XmlErrNoMemory,
            XmlErrorLevel::XmlErrError,
            None,
            0,
            Some(extra.to_owned().into()),
            None,
            None,
            0,
            0,
            "Memory allocation failed : {}\n",
            extra
        );
    } else {
        __xml_raise_error!(
            None,
            None,
            None,
            ptr as _,
            node,
            XmlErrorDomain::XmlFromXInclude,
            XmlParserErrors::XmlErrNoMemory,
            XmlErrorLevel::XmlErrError,
            None,
            0,
            None,
            None,
            None,
            0,
            0,
            "Memory allocation failed\n",
        );
    }
}

/// Returns the @n'th element child of @cur or NULL
#[doc(alias = "xmlXIncludeGetNthChild")]
#[cfg(feature = "libxml_xptr_locs")]
fn xml_xinclude_get_nth_child(cur: XmlGenericNodePtr, no: i32) -> Option<XmlGenericNodePtr> {
    if cur.element_type() == XmlElementType::XmlNamespaceDecl {
        return None;
    }
    let mut cur = cur.children();
    let mut i = 0;
    while i <= no {
        let now = cur?;
        if matches!(
            now.element_type(),
            XmlElementType::XmlElementNode
                | XmlElementType::XmlDocumentNode
                | XmlElementType::XmlHTMLDocumentNode
        ) {
            i += 1;
            if i == no {
                break;
            }
        }

        cur = now.next();
    }
    cur
}

/// Implement the XInclude substitution on the XML node @tree
///
/// Returns 0 if no substitution were done, -1 if some processing failed
/// or the number of substitutions done.
#[doc(alias = "xmlXIncludeProcessTreeFlagsData")]
pub unsafe fn xml_xinclude_process_tree_flags_data(
    tree: XmlNodePtr,
    flags: i32,
    data: *mut c_void,
) -> i32 {
    unsafe {
        if tree.element_type() == XmlElementType::XmlNamespaceDecl {
            return -1;
        }
        let Some(doc) = tree.doc else {
            return -1;
        };

        let mut ctxt = XmlXIncludeCtxt::new(doc);
        ctxt._private = data;
        ctxt.base = doc.url.as_deref().map(|url| url.into());
        ctxt.set_flags(flags);
        let mut ret = ctxt.do_process(tree);
        if ret >= 0 && ctxt.nb_errors > 0 {
            ret = -1;
        }

        ret
    }
}

/// Implement the XInclude substitution for the given subtree
///
/// Returns 0 if no substitution were done, -1 if some processing failed
/// or the number of substitutions done.
#[doc(alias = "xmlXIncludeProcessTree")]
pub unsafe fn xml_xinclude_process_tree(tree: XmlNodePtr) -> i32 {
    unsafe { xml_xinclude_process_tree_flags(tree, 0) }
}

/// Implement the XInclude substitution for the given subtree
///
/// Returns 0 if no substitution were done, -1 if some processing failed
/// or the number of substitutions done.
#[doc(alias = "xmlXIncludeProcessTreeFlags")]
pub unsafe fn xml_xinclude_process_tree_flags(tree: XmlNodePtr, flags: i32) -> i32 {
    unsafe {
        if tree.element_type() == XmlElementType::XmlNamespaceDecl {
            return -1;
        }
        let Some(doc) = tree.doc else {
            return -1;
        };
        let mut ctxt = XmlXIncludeCtxt::new(doc);
        ctxt.base = tree.get_base(Some(doc)).map(|base| base.into());
        ctxt.set_flags(flags);
        let mut ret = ctxt.do_process(tree);
        if ret >= 0 && ctxt.nb_errors > 0 {
            ret = -1;
        }

        ret
    }
}