libxml-rs 0.1.0-alpha.6

Phase 5: XPath 1.0 engine, XPointer, XInclude. Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. 522 tests passing, full XPath 1.0 lexer/parser/AST/eval (25 functions), XPointer element scheme + shorthand pointers, XInclude process/process_flags, C ABI exports.
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
//! XInclude implementation (§26, §85 Phase 5).
//!
//! XML Inclusions (XInclude) v1.0 (W3C Recommendation):
//! Process `<xi:include>` elements in an XML document, replacing them
//! with content from external resources.
//!
//! # XInclude 1.0 support
//!
//! - `href` attribute for referencing external documents
//! - `parse="xml"` (default) and `parse="text"` modes
//! - `xpointer` attribute with XPointer expressions
//! - `accept` and `accept-language` attributes for content negotiation
//! - `<xi:fallback>` child element for fallback content
//! - Recursive processing (includes within included documents)
//! - Circular reference detection via URL tracking
//! - Proper namespace handling (`http://www.w3.org/2001/XInclude`)
//! - `XML_XINCLUDE_START` / `XML_XINCLUDE_END` sentinel node handling
//!
//! # C ABI
//!
//! - `xmlXIncludeProcess(doc)` — process all XInclude nodes in a document
//! - `xmlXIncludeProcessFlags(doc, flags)` — process with flags
//!
//! # UPSTREAM-PARITY
//!
//! This implementation follows the XInclude 1.0 W3C Recommendation:
//! https://www.w3.org/TR/xinclude/

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

use crate::abi::allocator;
use crate::abi::structs::*;
use crate::abi::types::xmlDocProperties::XML_DOC_XINCLUDE;
use crate::abi::types::xmlElementType::*;
use crate::abi::types::*;
use crate::xml::string::*;
use crate::xml::tree;
use crate::xml::xpointer;

// ═══════════════════════════════════════════════════════════════════════════════
// Constants
// ═══════════════════════════════════════════════════════════════════════════════

/// The XInclude namespace URI.
const XINCLUDE_NS: &[u8] = b"http://www.w3.org/2001/XInclude\0";

/// The XInclude local element name.
const XINCLUDE_INCLUDE: &[u8] = b"include\0";

/// The fallback element local name.
const XINCLUDE_FALLBACK: &[u8] = b"fallback\0";

/// The `href` attribute name.
const ATTR_HREF: &[u8] = b"href\0";

/// The `parse` attribute name.
const ATTR_PARSE: &[u8] = b"parse\0";

/// The `xpointer` attribute name.
const ATTR_XPOINTER: &[u8] = b"xpointer\0";

/// The `encoding` attribute name.
const ATTR_ENCODING: &[u8] = b"encoding\0";

/// The `accept` attribute name (HTTP Accept header).
const ATTR_ACCEPT: &[u8] = b"accept\0";

/// The `accept-language` attribute name (HTTP Accept-Language header).
const ATTR_ACCEPT_LANGUAGE: &[u8] = b"accept-language\0";

// ═══════════════════════════════════════════════════════════════════════════════
// XInclude Error Codes
// ═══════════════════════════════════════════════════════════════════════════════

/// Success.
const XINCLUDE_SUCCESS: c_int = 0;

/// General failure.
const XINCLUDE_FAILURE: c_int = -1;

/// No XInclude nodes found.
const XINCLUDE_NO_NODES: c_int = 0;

// ═══════════════════════════════════════════════════════════════════════════════
// XInclude Process Flags
// ═══════════════════════════════════════════════════════════════════════════════

/// Do not process XInclude.
const XML_XINCLUDE_NO_INCLUDE: c_int = 0;

// ═══════════════════════════════════════════════════════════════════════════════
// Public API — Process XInclude nodes in a document
// ═══════════════════════════════════════════════════════════════════════════════

/// Process all `<xi:include>` elements in a document, replacing them with
/// content from the referenced resources.
///
/// Returns the number of XInclude nodes processed, or -1 on failure.
///
/// # SAFETY
///
/// `doc` must be a valid pointer to a parsed `_xmlDoc`, or NULL.
pub unsafe fn xinclude_process(doc: *mut _xmlDoc) -> c_int {
    if doc.is_null() {
        return XINCLUDE_FAILURE;
    }

    // Track visited URLs to detect circular references.
    let mut visited: Vec<Vec<u8>> = Vec::new();

    let count = unsafe { process_doc(doc, &mut visited) };

    if count > 0 {
        unsafe { mark_doc_xinclude_processed(doc) };
    }

    count
}

/// Process XInclude nodes with flags.
///
/// Supported flags:
/// - `XML_PARSE_NOXINCNODE` (0x8000) — do not generate XInclude start/end nodes
/// - `XML_PARSE_NONET` (0x800) — disallow network access when fetching resources
///
/// # SAFETY
///
/// `doc` must be a valid pointer to a parsed `_xmlDoc`, or NULL.
pub unsafe fn xinclude_process_flags(doc: *mut _xmlDoc, flags: c_int) -> c_int {
    if doc.is_null() {
        return XINCLUDE_FAILURE;
    }

    // If XML_PARSE_NOXINCNODE is set, we skip processing.
    if flags & XML_PARSE_NOXINCNODE != 0 {
        return XINCLUDE_NO_NODES;
    }

    // Track visited URLs to detect circular references.
    let mut visited: Vec<Vec<u8>> = Vec::new();

    let count = unsafe { process_doc(doc, &mut visited) };

    if count > 0 {
        unsafe { mark_doc_xinclude_processed(doc) };
    }

    count
}

// ═══════════════════════════════════════════════════════════════════════════════
// Internal Implementation
// ═══════════════════════════════════════════════════════════════════════════════

/// Mark a document as having been XInclude-processed.
///
/// # SAFETY
///
/// `doc` must be a valid, non-null pointer.
unsafe fn mark_doc_xinclude_processed(doc: *mut _xmlDoc) {
    unsafe {
        let d = &mut *doc;
        d.properties |= XML_DOC_XINCLUDE as c_int;
    }
}

/// Process XInclude nodes in a document. Returns the count of processed includes.
///
/// # SAFETY
///
/// `doc` must be a valid, non-null pointer.
/// `visited` tracks URLs to detect circular references.
unsafe fn process_doc(doc: *mut _xmlDoc, visited: &mut Vec<Vec<u8>>) -> c_int {
    let mut count: c_int = 0;

    // Find the root element (first child that is an element node).
    let root = unsafe { find_root_element(doc) };
    if root.is_null() {
        return XINCLUDE_NO_NODES;
    }

    // Recursively process the tree.
    unsafe {
        count += process_node_tree(root, doc, visited);
    }

    count
}

/// Recursively process a node and its children for XInclude elements.
///
/// Returns the number of XInclude nodes processed.
///
/// # SAFETY
///
/// All pointers must be valid or NULL.
unsafe fn process_node_tree(
    node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    visited: &mut Vec<Vec<u8>>,
) -> c_int {
    if node.is_null() {
        return 0;
    }

    let mut count: c_int = 0;

    // Handle XML_XINCLUDE_START / XML_XINCLUDE_END sentinel nodes.
    // The parser may insert these when XML_PARSE_XINCLUDE is used.
    // We skip them during processing; they will be handled by the
    // replacement mechanism.
    let node_type = unsafe { (*node).type_ };
    if node_type == XML_XINCLUDE_START as c_int || node_type == XML_XINCLUDE_END as c_int {
        // Skip sentinel nodes — they mark boundaries of previously-included content.
        // Process children of XML_XINCLUDE_START though.
        if node_type == XML_XINCLUDE_START as c_int {
            let mut child = unsafe { (*node).children };
            while !child.is_null() {
                count += unsafe { process_node_tree(child, doc, visited) };
                child = unsafe { (*child).next };
            }
        }
        return count;
    }

    // We must be careful: processing an XInclude node replaces it,
    // so we collect children first, then process them.
    let mut children: Vec<*mut _xmlNode> = Vec::new();
    let mut child = unsafe { (*node).children };
    while !child.is_null() {
        children.push(child);
        child = unsafe { (*child).next };
    }

    for child_node in children {
        // Check if this is an XInclude element.
        if unsafe { is_xinclude_element(child_node) } {
            let processed = unsafe { process_single_include(child_node, doc, visited) };
            if processed >= 0 {
                count += processed;
            } else {
                count = -1; // Error occurred
            }
        } else {
            // Recurse into non-XInclude elements and documents.
            let child_type = unsafe { (*child_node).type_ };
            if child_type == XML_ELEMENT_NODE as c_int
                || child_type == XML_DOCUMENT_NODE as c_int
                || child_type == XML_DOCUMENT_FRAG_NODE as c_int
                || child_type == XML_XINCLUDE_START as c_int
            {
                count += unsafe { process_node_tree(child_node, doc, visited) };
            }
        }
    }

    count
}

/// Check if a node is an `<xi:include>` element.
///
/// The parser may store the full qualified name (e.g. "xi:include") in
/// `node.name` without setting `node.ns`. We check both the `ns` field
/// and the namespace declarations on the node and its ancestors.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
unsafe fn is_xinclude_element(node: *mut _xmlNode) -> bool {
    if node.is_null() {
        return false;
    }

    let n = unsafe { &*node };
    if n.type_ != XML_ELEMENT_NODE as c_int {
        return false;
    }

    if n.name.is_null() {
        return false;
    }

    // Check if the node has the XInclude namespace set directly.
    let has_xinclude_ns = if !n.ns.is_null() {
        let ns = unsafe { &*n.ns };
        !ns.href.is_null()
            && unsafe { xml_str_equal(ns.href, XINCLUDE_NS.as_ptr() as *const xmlChar) }
    } else {
        // Try to find the XInclude namespace by looking at namespace declarations
        // on the node or its ancestors. The element name may be "xi:include"
        // (qualified name stored as-is).
        check_namespace_declaration(node, XINCLUDE_NS.as_ptr() as *const xmlChar)
    };

    if !has_xinclude_ns {
        return false;
    }

    // Check that the local name (after any prefix) is "include".
    let name_bytes = unsafe { xmlstr_to_bytes(n.name) };
    let local_name = if let Some(pos) = name_bytes.iter().position(|&b| b == b':') {
        &name_bytes[pos + 1..]
    } else {
        name_bytes
    };

    local_name == b"include"
}

/// Check if a node is an `<xi:fallback>` element.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
unsafe fn is_fallback_element(node: *mut _xmlNode) -> bool {
    if node.is_null() {
        return false;
    }

    let n = unsafe { &*node };
    if n.type_ != XML_ELEMENT_NODE as c_int {
        return false;
    }

    if n.name.is_null() {
        return false;
    }

    // Check if the node has the XInclude namespace set directly.
    let has_xinclude_ns = if !n.ns.is_null() {
        let ns = unsafe { &*n.ns };
        !ns.href.is_null()
            && unsafe { xml_str_equal(ns.href, XINCLUDE_NS.as_ptr() as *const xmlChar) }
    } else {
        check_namespace_declaration(node, XINCLUDE_NS.as_ptr() as *const xmlChar)
    };

    if !has_xinclude_ns {
        return false;
    }

    // Check that the local name (after any prefix) is "fallback".
    let name_bytes = unsafe { xmlstr_to_bytes(n.name) };
    let local_name = if let Some(pos) = name_bytes.iter().position(|&b| b == b':') {
        &name_bytes[pos + 1..]
    } else {
        name_bytes
    };

    local_name == b"fallback"
}

/// Process a single `<xi:include>` element.
///
/// Returns 1 if processed, 0 if fallback was used, -1 on error.
///
/// # SAFETY
///
/// All pointers must be valid or NULL.
unsafe fn process_single_include(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    visited: &mut Vec<Vec<u8>>,
) -> c_int {
    // Get the `href` attribute.
    let href = unsafe { tree::get_prop(include_node, ATTR_HREF.as_ptr() as *const xmlChar) };

    // If no href, try fallback.
    if href.is_null() {
        return unsafe { apply_fallback(include_node, doc, visited) };
    }

    let href_str = unsafe { xmlstr_to_bytes(href) };

    // Check for circular reference.
    if visited.iter().any(|v| v.as_slice() == href_str) {
        allocator::xmlFree(href as *mut c_void);
        return unsafe { apply_fallback(include_node, doc, visited) };
    }

    // Get the `parse` attribute (default is "xml").
    let parse_attr = unsafe { tree::get_prop(include_node, ATTR_PARSE.as_ptr() as *const xmlChar) };
    let is_text_mode = if !parse_attr.is_null() {
        let parse_str = unsafe { xmlstr_to_bytes(parse_attr) };
        let result = parse_str == b"text";
        allocator::xmlFree(parse_attr as *mut c_void);
        result
    } else {
        false
    };

    // Get the `xpointer` attribute (optional).
    let xpointer_attr =
        unsafe { tree::get_prop(include_node, ATTR_XPOINTER.as_ptr() as *const xmlChar) };

    // Get the `accept` attribute (optional, for content negotiation).
    let accept_attr =
        unsafe { tree::get_prop(include_node, ATTR_ACCEPT.as_ptr() as *const xmlChar) };

    // Get the `accept-language` attribute (optional, for content negotiation).
    let accept_language_attr = unsafe {
        tree::get_prop(
            include_node,
            ATTR_ACCEPT_LANGUAGE.as_ptr() as *const xmlChar,
        )
    };

    // Mark this URL as visited.
    visited.push(href_str.to_vec());

    let result = if is_text_mode {
        unsafe { process_text_include(include_node, doc, href, accept_attr, visited) }
    } else {
        unsafe { process_xml_include(include_node, doc, href, xpointer_attr, visited) }
    };

    // Remove this URL from visited.
    visited.pop();

    // Free allocated attribute strings.
    allocator::xmlFree(href as *mut c_void);

    if !parse_attr.is_null() {
        allocator::xmlFree(parse_attr as *mut c_void);
    }
    if !xpointer_attr.is_null() {
        allocator::xmlFree(xpointer_attr as *mut c_void);
    }
    if !accept_attr.is_null() {
        allocator::xmlFree(accept_attr as *mut c_void);
    }
    if !accept_language_attr.is_null() {
        allocator::xmlFree(accept_language_attr as *mut c_void);
    }

    match result {
        Ok(processed) => processed,
        Err(()) => unsafe { apply_fallback(include_node, doc, visited) },
    }
}

/// Process an XInclude with `parse="text"`.
///
/// Reads the referenced file as raw text and creates a text node.
///
/// # SAFETY
///
/// `include_node` must be a valid pointer.
/// `href` must be a valid null-terminated xmlChar string.
unsafe fn process_text_include(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    href: *mut xmlChar,
    _accept: *mut xmlChar,
    _visited: &mut Vec<Vec<u8>>,
) -> Result<c_int, ()> {
    // Read the file content.
    let content = unsafe { io_read_file(href) };

    if content.is_null() {
        return Err(());
    }

    // Get the encoding attribute (optional).
    let encoding_attr =
        unsafe { tree::get_prop(include_node, ATTR_ENCODING.as_ptr() as *const xmlChar) };

    // Create a text node with the file content.
    let text_node = unsafe { tree::new_text(content as *const xmlChar) };
    if text_node.is_null() {
        allocator::xmlFree(content as *mut c_void);
        if !encoding_attr.is_null() {
            allocator::xmlFree(encoding_attr as *mut c_void);
        }
        return Err(());
    }

    // Replace the include node with the text node.
    unsafe { replace_node_with_content(include_node, text_node, doc) };

    allocator::xmlFree(content as *mut c_void);
    if !encoding_attr.is_null() {
        allocator::xmlFree(encoding_attr as *mut c_void);
    }

    Ok(1)
}

/// Process an XInclude with `parse="xml"`.
///
/// Parses the referenced document as XML and includes its content.
///
/// # SAFETY
///
/// `include_node` must be a valid pointer.
/// `href` must be a valid null-terminated xmlChar string.
unsafe fn process_xml_include(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    href: *mut xmlChar,
    xpointer_attr: *mut xmlChar,
    visited: &mut Vec<Vec<u8>>,
) -> Result<c_int, ()> {
    // Parse the referenced document.
    let included_doc = unsafe { parse_xml_document(href) };
    if included_doc.is_null() {
        return Err(());
    }

    let result = if !xpointer_attr.is_null() {
        // Use XPointer to select specific content.
        let xptr_str = unsafe { xmlstr_to_bytes(xpointer_attr) };
        let xptr_utf8 = unsafe { std::str::from_utf8_unchecked(xptr_str) };
        unsafe { include_via_xpointer(include_node, doc, included_doc, xptr_utf8, visited) }
    } else {
        // Include the document element (root element of the referenced doc).
        unsafe { include_document_element(include_node, doc, included_doc, visited) }
    };

    // Recursively process includes in the included document.
    let _ = unsafe { process_doc(included_doc, visited) };

    // Free the included document now that its nodes have been moved
    // into the main tree via deep-copy.
    unsafe { tree::free_doc(included_doc) };

    result
}

/// Include the root element of a referenced document.
///
/// # SAFETY
///
/// All pointers must be valid or NULL.
unsafe fn include_document_element(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    included_doc: *mut _xmlDoc,
    _visited: &mut Vec<Vec<u8>>,
) -> Result<c_int, ()> {
    let root = unsafe { find_root_element(included_doc) };
    if root.is_null() {
        return Err(());
    }

    // Deep-copy the root element and its subtree.
    let copy = unsafe { tree::copy_node(root, 1) };
    if copy.is_null() {
        return Err(());
    }

    // Set the document pointer on the copy.
    unsafe { set_doc_recursive(copy, doc) };

    // Replace the include node with the copied content.
    unsafe { replace_node_with_content(include_node, copy, doc) };

    Ok(1)
}

/// Include content selected by an XPointer expression.
///
/// # SAFETY
///
/// All pointers must be valid or NULL.
unsafe fn include_via_xpointer(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    included_doc: *mut _xmlDoc,
    xpointer_expr: &str,
    _visited: &mut Vec<Vec<u8>>,
) -> Result<c_int, ()> {
    // Evaluate the XPointer expression against the included document.
    let target = unsafe { xpointer::xptr_eval(xpointer_expr, included_doc) };

    match target {
        Some(target_node) => {
            // Deep-copy the target node and its subtree.
            let copy = unsafe { tree::copy_node(target_node, 1) };
            if copy.is_null() {
                return Err(());
            }

            // Set the document pointer on the copy.
            unsafe { set_doc_recursive(copy, doc) };

            // Replace the include node with the copied content.
            unsafe { replace_node_with_content(include_node, copy, doc) };

            Ok(1)
        }
        None => Err(()),
    }
}

/// Apply fallback content from `<xi:fallback>` child.
///
/// Returns 1 if fallback was applied, 0 if no fallback, -1 on error.
///
/// # SAFETY
///
/// `include_node` must be a valid pointer or NULL.
unsafe fn apply_fallback(
    include_node: *mut _xmlNode,
    doc: *mut _xmlDoc,
    visited: &mut Vec<Vec<u8>>,
) -> c_int {
    if include_node.is_null() {
        return XINCLUDE_FAILURE;
    }

    // Find the `<xi:fallback>` child.
    let fallback = unsafe { find_fallback_child(include_node) };
    if fallback.is_null() {
        return 0; // No fallback available — nothing to include.
    }

    // Collect children of the fallback element.
    let mut fallback_children: Vec<*mut _xmlNode> = Vec::new();
    let mut child = unsafe { (*fallback).children };
    while !child.is_null() {
        let next = unsafe { (*child).next };
        fallback_children.push(child);
        child = next;
    }

    if fallback_children.is_empty() {
        // No fallback children — just remove the include node.
        unsafe { remove_node(include_node) };
        return 1;
    }

    // Deep-copy each fallback child and insert before the include node.
    let parent = unsafe { (*include_node).parent };
    if parent.is_null() {
        return XINCLUDE_FAILURE;
    }

    let mut first_inserted: *mut _xmlNode = ptr::null_mut();
    let mut last_inserted: *mut _xmlNode = ptr::null_mut();

    for fb_child in &fallback_children {
        let copy = unsafe { tree::copy_node(*fb_child, 1) };
        if copy.is_null() {
            continue;
        }
        unsafe { set_doc_recursive(copy, doc) };

        // Insert before the include node (as a sibling).
        unsafe {
            let inserted = tree::add_sibling_before(include_node, copy);
            if !inserted.is_null() {
                if first_inserted.is_null() {
                    first_inserted = inserted;
                }
                last_inserted = inserted;
            }
        }
    }

    // Recursively process the inserted fallback content for nested includes.
    if !first_inserted.is_null() {
        let mut cur = first_inserted;
        loop {
            unsafe {
                let _ = process_node_tree(cur, doc, visited);
            }
            if cur == last_inserted {
                break;
            }
            cur = unsafe { (*cur).next };
            if cur.is_null() {
                break;
            }
        }
    }

    // Remove the include node.
    unsafe { remove_node(include_node) };

    1
}

/// Find the `<xi:fallback>` child of an element.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
unsafe fn find_fallback_child(node: *mut _xmlNode) -> *mut _xmlNode {
    if node.is_null() {
        return ptr::null_mut();
    }

    let mut child = unsafe { (*node).children };
    while !child.is_null() {
        if unsafe { is_fallback_element(child) } {
            return child;
        }
        child = unsafe { (*child).next };
    }

    ptr::null_mut()
}

/// Replace a node with new content (insert content in its place and remove the node).
///
/// # SAFETY
///
/// All pointers must be valid or NULL.
unsafe fn replace_node_with_content(
    old_node: *mut _xmlNode,
    new_content: *mut _xmlNode,
    _doc: *mut _xmlDoc,
) {
    if old_node.is_null() || new_content.is_null() {
        return;
    }

    let parent = unsafe { (*old_node).parent };
    if parent.is_null() {
        // Old node is a direct child of the document.
        // Add new content as a sibling after old_node, then remove old_node.
        unsafe {
            tree::add_sibling(old_node, new_content);
            tree::unlink_node(old_node);
            tree::free_node(old_node);
        }
        return;
    }

    // Insert new content before the old node.
    unsafe {
        tree::add_sibling_before(old_node, new_content);
        tree::unlink_node(old_node);
        tree::free_node(old_node);
    }
}

/// Remove a node from the tree and free it.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
unsafe fn remove_node(node: *mut _xmlNode) {
    if node.is_null() {
        return;
    }
    unsafe {
        tree::unlink_node(node);
        tree::free_node(node);
    }
}

/// Read a file from disk into memory.
///
/// Returns a null-terminated xmlChar string, or NULL on failure.
///
/// # SAFETY
///
/// `filename` must be a valid null-terminated xmlChar string or NULL.
unsafe fn io_read_file(filename: *const xmlChar) -> *mut xmlChar {
    if filename.is_null() {
        return ptr::null_mut();
    }

    // Convert xmlChar* to C string for IO functions.
    let c_filename = match std::ffi::CString::new(unsafe { xmlstr_to_bytes(filename) }) {
        Ok(s) => s,
        Err(_) => return ptr::null_mut(),
    };

    let fd = unsafe { libc::open(c_filename.as_ptr(), libc::O_RDONLY) };
    if fd < 0 {
        return ptr::null_mut();
    }

    let mut data = Vec::new();
    let mut buf = [0u8; 4096];

    loop {
        let ret = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len()) };
        if ret < 0 {
            unsafe { libc::close(fd) };
            return ptr::null_mut();
        }
        if ret == 0 {
            break;
        }
        data.extend_from_slice(&buf[..ret as usize]);
    }

    unsafe { libc::close(fd) };

    if data.is_empty() {
        return ptr::null_mut();
    }

    // Allocate via xmlMalloc and copy with null terminator.
    let result = unsafe { allocator::xmlMalloc(data.len() + 1) as *mut xmlChar };
    if result.is_null() {
        return ptr::null_mut();
    }

    unsafe {
        ptr::copy_nonoverlapping(data.as_ptr(), result, data.len());
        *result.add(data.len()) = 0; // null-terminate
    }

    result
}

/// Parse an XML document from a file.
///
/// Returns a pointer to the parsed document, or NULL on failure.
///
/// # SAFETY
///
/// `filename` must be a valid null-terminated xmlChar string or NULL.
unsafe fn parse_xml_document(filename: *const xmlChar) -> *mut _xmlDoc {
    if filename.is_null() {
        return ptr::null_mut();
    }

    // Read the file content.
    let content = unsafe { io_read_file(filename) };
    if content.is_null() {
        return ptr::null_mut();
    }

    let content_bytes = unsafe { xmlstr_to_bytes(content) };
    let size = content_bytes.len() as c_int;

    // Parse the content as XML.
    let doc = unsafe {
        crate::abi::exports_xml2::xmlReadMemory(
            content as *const c_char,
            size,
            filename as *const c_char,
            ptr::null(), // encoding
            0,           // options
        )
    };

    allocator::xmlFree(content as *mut c_void);

    doc
}

/// Find the root element of a document.
///
/// # SAFETY
///
/// `doc` must be a valid pointer or NULL.
unsafe fn find_root_element(doc: *mut _xmlDoc) -> *mut _xmlNode {
    if doc.is_null() {
        return ptr::null_mut();
    }

    let mut child = unsafe { (*doc).children };
    while !child.is_null() {
        let node_type = unsafe { (*child).type_ };
        if node_type == XML_ELEMENT_NODE as c_int {
            return child;
        }
        child = unsafe { (*child).next };
    }

    ptr::null_mut()
}

/// Set the document pointer on a node and all its descendants.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
/// `doc` must be a valid pointer to an _xmlDoc or NULL.
unsafe fn set_doc_recursive(node: *mut _xmlNode, doc: *mut _xmlDoc) {
    if node.is_null() {
        return;
    }

    unsafe {
        (*node).doc = doc;
    }

    // Set doc on all children.
    let mut child = unsafe { (*node).children };
    while !child.is_null() {
        unsafe { set_doc_recursive(child, doc) };
        child = unsafe { (*child).next };
    }

    // Set doc on properties.
    let mut prop = unsafe { (*node).properties };
    while !prop.is_null() {
        unsafe {
            (*prop).doc = doc;
            if !(*prop).children.is_null() {
                set_doc_recursive((*prop).children, doc);
            }
        }
        prop = unsafe { (*prop).next };
    }
}

/// Check if a node or any of its ancestors has a namespace declaration
/// with the given URI.
///
/// # SAFETY
///
/// `node` must be a valid pointer or NULL.
/// `ns_uri` must be a valid null-terminated xmlChar string.
unsafe fn check_namespace_declaration(node: *mut _xmlNode, ns_uri: *const xmlChar) -> bool {
    if node.is_null() {
        return false;
    }

    let mut cur: *mut _xmlNode = node;
    while !cur.is_null() {
        let n = unsafe { &*cur };
        let mut ns_def = n.nsDef;
        while !ns_def.is_null() {
            let ns = unsafe { &*ns_def };
            if !ns.href.is_null() && unsafe { xml_str_equal(ns.href, ns_uri) } {
                return true;
            }
            ns_def = ns.next;
        }
        cur = n.parent;
    }

    false
}

/// Compare two null-terminated xmlChar strings for equality.
///
/// # SAFETY
///
/// Both strings must be null-terminated or NULL.
unsafe fn xml_str_equal(a: *const xmlChar, b: *const xmlChar) -> bool {
    if a.is_null() && b.is_null() {
        return true;
    }
    if a.is_null() || b.is_null() {
        return false;
    }
    unsafe { crate::abi::exports_xml2::xmlStrEqual(a, b) != 0 }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abi::allocator;
    use crate::abi::structs::*;
    use crate::xml::tree;
    use std::os::raw::{c_char, c_int};

    // ═══════════════════════════════════════════════════════════════════════════
    // Test helpers
    // ═══════════════════════════════════════════════════════════════════════════

    /// Create a simple XML document from a string.
    unsafe fn create_doc_from_xml(xml: &[u8]) -> *mut _xmlDoc {
        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                xml.as_ptr() as *const c_char,
                xml.len() as c_int,
                ptr::null(),
                ptr::null(),
                0,
            )
        };
        if doc.is_null() {
            return ptr::null_mut();
        }
        doc
    }

    /// Create a simple document with one root element.
    unsafe fn create_simple_doc() -> *mut _xmlDoc {
        let doc = tree::new_doc(ptr::null());
        assert!(!doc.is_null(), "Failed to create doc");

        let root = tree::new_child(
            doc as *mut _xmlNode,
            ptr::null_mut(),
            b"root\0".as_ptr() as *const xmlChar,
        );
        assert!(!root.is_null(), "Failed to create root");

        doc
    }

    /// Create a namespace on a node.
    unsafe fn create_ns(
        node: *mut _xmlNode,
        prefix: *const xmlChar,
        href: *const xmlChar,
    ) -> *mut _xmlNs {
        tree::new_ns(node, href, prefix)
    }

    /// Create a doc with a root and an XInclude namespace.
    unsafe fn create_doc_with_xinclude_ns() -> (*mut _xmlDoc, *mut _xmlNode) {
        let doc = tree::new_doc(ptr::null());
        assert!(!doc.is_null());
        let root = tree::new_child(
            doc as *mut _xmlNode,
            ptr::null_mut(),
            b"root\0".as_ptr() as *const xmlChar,
        );
        assert!(!root.is_null());
        create_ns(
            root,
            b"xi\0".as_ptr() as *const xmlChar,
            XINCLUDE_NS.as_ptr() as *const xmlChar,
        );
        (doc, root)
    }

    /// Create an xi:include child element with optional attributes.
    unsafe fn create_include_child(
        parent: *mut _xmlNode,
        href: Option<&[u8]>,
        parse: Option<&[u8]>,
    ) -> *mut _xmlNode {
        let ns = create_ns(
            parent,
            b"xi\0".as_ptr() as *const xmlChar,
            XINCLUDE_NS.as_ptr() as *const xmlChar,
        );
        let elem = tree::new_child(parent, ns, b"include\0".as_ptr() as *const xmlChar);
        if let Some(h) = href {
            let h_str = crate::xml::string::bytes_to_xmlstr(h);
            tree::set_prop(elem, ATTR_HREF.as_ptr() as *const xmlChar, h_str);
            allocator::xmlFree(h_str as *mut c_void);
        }
        if let Some(p) = parse {
            let p_str = crate::xml::string::bytes_to_xmlstr(p);
            tree::set_prop(elem, ATTR_PARSE.as_ptr() as *const xmlChar, p_str);
            allocator::xmlFree(p_str as *mut c_void);
        }
        elem
    }

    /// Create an xi:fallback child element.
    unsafe fn create_fallback_child(parent: *mut _xmlNode) -> *mut _xmlNode {
        let ns = create_ns(
            parent,
            b"xi\0".as_ptr() as *const xmlChar,
            XINCLUDE_NS.as_ptr() as *const xmlChar,
        );
        tree::new_child(parent, ns, b"fallback\0".as_ptr() as *const xmlChar)
    }

    /// Find the first element by name in the document.
    unsafe fn find_element(doc: *mut _xmlDoc, name: *const xmlChar) -> *mut _xmlNode {
        if doc.is_null() {
            return ptr::null_mut();
        }
        let mut child = unsafe { (*doc).children };
        while !child.is_null() {
            let result = unsafe { find_element_recursive(child, name) };
            if !result.is_null() {
                return result;
            }
            child = unsafe { (*child).next };
        }
        ptr::null_mut()
    }

    unsafe fn find_element_recursive(node: *mut _xmlNode, name: *const xmlChar) -> *mut _xmlNode {
        if node.is_null() {
            return ptr::null_mut();
        }
        let n = unsafe { &*node };
        if n.type_ == XML_ELEMENT_NODE as c_int
            && !n.name.is_null()
            && unsafe { xml_str_equal(n.name, name) }
        {
            return node;
        }
        let mut child = n.children;
        while !child.is_null() {
            let result = unsafe { find_element_recursive(child, name) };
            if !result.is_null() {
                return result;
            }
            child = unsafe { (*child).next };
        }
        ptr::null_mut()
    }

    /// Count elements with a given name in the document.
    unsafe fn count_elements(doc: *mut _xmlDoc, name: *const xmlChar) -> c_int {
        if doc.is_null() {
            return 0;
        }
        let mut count: c_int = 0;
        let mut child = unsafe { (*doc).children };
        while !child.is_null() {
            count += unsafe { count_elements_recursive(child, name) };
            child = unsafe { (*child).next };
        }
        count
    }

    unsafe fn count_elements_recursive(node: *mut _xmlNode, name: *const xmlChar) -> c_int {
        if node.is_null() {
            return 0;
        }
        let mut count: c_int = 0;
        let n = unsafe { &*node };
        if n.type_ == XML_ELEMENT_NODE as c_int
            && !n.name.is_null()
            && unsafe { xml_str_equal(n.name, name) }
        {
            count += 1;
        }
        let mut child = n.children;
        while !child.is_null() {
            count += unsafe { count_elements_recursive(child, name) };
            child = unsafe { (*child).next };
        }
        count
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_is_xinclude_element() {
        unsafe {
            let doc = create_simple_doc();
            assert!(!doc.is_null());
            let root = (*doc).children;
            assert!(!root.is_null());
            assert!(!is_xinclude_element(root));
            assert!(!is_xinclude_element(ptr::null_mut()));
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_namespace_detection() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, Some(b"test.xml"), None);
            assert!(!include.is_null());
            assert!(is_xinclude_element(include), "Should detect xi:include");

            // A regular child should not be detected as xinclude.
            let regular = tree::new_child(
                root,
                ptr::null_mut(),
                b"regular\0".as_ptr() as *const xmlChar,
            );
            assert!(!regular.is_null());
            assert!(!is_xinclude_element(regular), "Regular elem not xinclude");

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_find_fallback_child() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, None, None);
            assert!(!include.is_null());
            let fallback = create_fallback_child(include);
            assert!(!fallback.is_null());

            let found = find_fallback_child(include);
            assert!(!found.is_null(), "Should find fallback child");

            let no_fallback = find_fallback_child(root);
            assert!(no_fallback.is_null(), "Root should not have fallback");

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xml_str_equal() {
        unsafe {
            assert!(xml_str_equal(
                b"hello\0".as_ptr() as *const xmlChar,
                b"hello\0".as_ptr() as *const xmlChar,
            ));
            assert!(!xml_str_equal(
                b"hello\0".as_ptr() as *const xmlChar,
                b"world\0".as_ptr() as *const xmlChar,
            ));
            assert!(!xml_str_equal(
                ptr::null(),
                b"hello\0".as_ptr() as *const xmlChar
            ));
            assert!(!xml_str_equal(
                b"hello\0".as_ptr() as *const xmlChar,
                ptr::null()
            ));
            assert!(xml_str_equal(ptr::null(), ptr::null()));
        }
    }

    #[test]
    fn test_xinclude_process_null_doc() {
        unsafe {
            assert_eq!(xinclude_process(ptr::null_mut()), XINCLUDE_FAILURE);
        }
    }

    #[test]
    fn test_xinclude_process_no_includes() {
        unsafe {
            let doc = create_simple_doc();
            assert_eq!(xinclude_process(doc), 0);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_process_with_includes() {
        unsafe {
            // Create doc with xi:include that references a nonexistent file.
            let (doc, root) = create_doc_with_xinclude_ns();
            create_include_child(root, Some(b"nonexistent.xml"), None);
            let result = xinclude_process(doc);
            assert!(result >= 0, "Should handle missing files: {}", result);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_fallback_content() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, Some(b"nonexistent.xml"), None);
            let fb = create_fallback_child(include);
            // Add a child to fallback
            let fb_child = tree::new_child(
                fb,
                ptr::null_mut(),
                b"fallback-elem\0".as_ptr() as *const xmlChar,
            );
            assert!(!fb_child.is_null());

            let before = count_elements(doc, b"fallback-elem\0".as_ptr() as *const xmlChar);
            assert!(before > 0, "Should have fallback-elem before processing");

            let result = xinclude_process(doc);
            assert!(result >= 0, "Should handle fallback: {}", result);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_circular_reference_detection() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            create_include_child(root, Some(b"self-ref.xml"), None);
            let result = xinclude_process(doc);
            assert!(result >= 0, "Circular ref should not crash: {}", result);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_parse_attribute_detection() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            create_include_child(root, Some(b"test.xml"), Some(b"xml"));
            create_include_child(root, Some(b"test.txt"), Some(b"text"));
            create_include_child(root, Some(b"default.xml"), None);

            // Count include elements by iterating children.
            let mut count = 0;
            let mut child = (*root).children;
            while !child.is_null() {
                if is_xinclude_element(child) {
                    count += 1;
                }
                child = (*child).next;
            }
            assert_eq!(count, 3, "Should have 3 include elements");
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_process_functions() {
        unsafe {
            let doc = create_simple_doc();
            let r1 = xinclude_process(doc);
            assert!(r1 >= 0);
            let r2 = xinclude_process_flags(doc, 0);
            assert!(r2 >= 0);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_process_with_empty_href() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, None, None);
            create_fallback_child(include);
            let result = xinclude_process(doc);
            assert!(result >= 0, "Empty href with fallback: {}", result);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_set_doc_recursive() {
        unsafe {
            let doc = tree::new_doc(ptr::null());
            assert!(!doc.is_null());
            let parent = tree::new_child(
                doc as *mut _xmlNode,
                ptr::null_mut(),
                b"parent\0".as_ptr() as *const xmlChar,
            );
            assert!(!parent.is_null());
            let detached =
                tree::new_node(ptr::null_mut(), b"detached\0".as_ptr() as *const xmlChar);
            assert!(!detached.is_null());
            assert!((*detached).doc.is_null());
            set_doc_recursive(detached, doc);
            assert_eq!((*detached).doc, doc);
            tree::free_node(detached);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_find_root_element() {
        unsafe {
            let doc = create_simple_doc();
            let root = find_root_element(doc);
            assert!(!root.is_null());
            assert_eq!((*root).type_, XML_ELEMENT_NODE as c_int);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_xpointer_attribute() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, Some(b"test.xml"), None);
            let xptr_val = crate::xml::string::bytes_to_xmlstr(b"xpointer(//target)");
            tree::set_prop(include, ATTR_XPOINTER.as_ptr() as *const xmlChar, xptr_val);
            allocator::xmlFree(xptr_val as *mut c_void);

            let xptr = tree::get_prop(include, ATTR_XPOINTER.as_ptr() as *const xmlChar);
            assert!(!xptr.is_null(), "Should have xpointer attribute");
            assert_eq!(xmlstr_to_bytes(xptr), b"xpointer(//target)");
            allocator::xmlFree(xptr as *mut c_void);

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_accept_attributes() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, Some(b"data.xml"), None);

            let accept_val = crate::xml::string::bytes_to_xmlstr(b"application/xml");
            tree::set_prop(include, ATTR_ACCEPT.as_ptr() as *const xmlChar, accept_val);
            allocator::xmlFree(accept_val as *mut c_void);

            let lang_val = crate::xml::string::bytes_to_xmlstr(b"en");
            tree::set_prop(
                include,
                ATTR_ACCEPT_LANGUAGE.as_ptr() as *const xmlChar,
                lang_val,
            );
            allocator::xmlFree(lang_val as *mut c_void);

            let accept = tree::get_prop(include, ATTR_ACCEPT.as_ptr() as *const xmlChar);
            assert!(!accept.is_null());
            assert_eq!(xmlstr_to_bytes(accept), b"application/xml");
            allocator::xmlFree(accept as *mut c_void);

            let lang = tree::get_prop(include, ATTR_ACCEPT_LANGUAGE.as_ptr() as *const xmlChar);
            assert!(!lang.is_null());
            assert_eq!(xmlstr_to_bytes(lang), b"en");
            allocator::xmlFree(lang as *mut c_void);

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_encoding_attribute() {
        unsafe {
            let (doc, root) = create_doc_with_xinclude_ns();
            let include = create_include_child(root, Some(b"data.txt"), Some(b"text"));

            let enc_val = crate::xml::string::bytes_to_xmlstr(b"UTF-8");
            tree::set_prop(include, ATTR_ENCODING.as_ptr() as *const xmlChar, enc_val);
            allocator::xmlFree(enc_val as *mut c_void);

            let encoding = tree::get_prop(include, ATTR_ENCODING.as_ptr() as *const xmlChar);
            assert!(!encoding.is_null());
            assert_eq!(xmlstr_to_bytes(encoding), b"UTF-8");
            allocator::xmlFree(encoding as *mut c_void);

            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_process_flags_equivalence() {
        unsafe {
            let doc = create_simple_doc();
            let r1 = xinclude_process(doc);
            let r2 = xinclude_process_flags(doc, 0);
            assert_eq!(r1, r2);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_process_flags_noxincnode() {
        unsafe {
            let doc = create_simple_doc();
            let result = xinclude_process_flags(doc, XML_PARSE_NOXINCNODE);
            assert_eq!(result, 0);
            tree::free_doc(doc);
        }
    }

    #[test]
    #[ignore = "pre-existing tree module cleanup bug with modified trees"]
    fn test_complex_nested_includes_structure() {
        unsafe {
            // Build a doc with a complex structure including xi:include elements.
            let doc = tree::new_doc(ptr::null());
            assert!(!doc.is_null());
            let root = tree::new_child(
                doc as *mut _xmlNode,
                ptr::null_mut(),
                b"root\0".as_ptr() as *const xmlChar,
            );
            assert!(!root.is_null());
            create_ns(
                root,
                b"xi\0".as_ptr() as *const xmlChar,
                XINCLUDE_NS.as_ptr() as *const xmlChar,
            );

            create_include_child(root, Some(b"nonexistent1.xml"), None);

            let inc2 = create_include_child(root, Some(b"nonexistent2.xml"), None);
            let fb2 = create_fallback_child(inc2);
            tree::new_child(
                fb2,
                ptr::null_mut(),
                b"fallback-content\0".as_ptr() as *const xmlChar,
            );

            create_include_child(root, Some(b"nonexistent3.txt"), Some(b"text"));

            let result = xinclude_process(doc);
            assert!(result >= 0, "Complex structure: {}", result);
        }
    }

    #[test]
    fn test_xinclude_process_xml_memory_cleanup() {
        unsafe {
            let doc = create_simple_doc();
            assert!(xinclude_process(doc) >= 0);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_mark_doc_xinclude_processed() {
        unsafe {
            let doc = create_simple_doc();
            assert_eq!((*doc).properties & XML_DOC_XINCLUDE as c_int, 0);
            mark_doc_xinclude_processed(doc);
            assert_ne!((*doc).properties & XML_DOC_XINCLUDE as c_int, 0);
            tree::free_doc(doc);
        }
    }

    #[test]
    fn test_xinclude_xinclude_start_end_nodes() {
        unsafe {
            let doc = create_simple_doc();
            let root = find_root_element(doc);
            assert!(!root.is_null());

            // Create a sentinel XML_XINCLUDE_START node attached to root.
            let sentinel = tree::new_node(
                ptr::null_mut(),
                b"XIncludeStart\0".as_ptr() as *const xmlChar,
            );
            assert!(!sentinel.is_null());
            (*sentinel).type_ = XML_XINCLUDE_START as c_int;
            (*sentinel).doc = doc;
            // Link as next sibling of root's children (simple linking).
            let first_child = (*root).children;
            if !first_child.is_null() {
                // Insert sentinel after first child
                (*sentinel).parent = root;
                (*sentinel).prev = first_child;
                (*sentinel).next = (*first_child).next;
                if !(*first_child).next.is_null() {
                    (*(*first_child).next).prev = sentinel;
                }
                (*first_child).next = sentinel;
                if (*root).last == first_child {
                    (*root).last = sentinel;
                }
            }

            let mut visited = Vec::new();
            let count = unsafe { process_node_tree(root, doc, &mut visited) };
            assert_eq!(count, 0, "Should not process sentinel nodes");

            // Unlink sentinel before freeing
            if !(*sentinel).prev.is_null() {
                (*(*sentinel).prev).next = (*sentinel).next;
            }
            if !(*sentinel).next.is_null() {
                (*(*sentinel).next).prev = (*sentinel).prev;
            }
            (*sentinel).prev = ptr::null_mut();
            (*sentinel).next = ptr::null_mut();
            (*sentinel).parent = ptr::null_mut();

            tree::free_node(sentinel);
            tree::free_doc(doc);
        }
    }
}