libxml-rs 0.1.0-alpha.44

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure; three-DSO ELF packaging (libxml2.so.16 core + libxslt.so.1/libexslt.so.0 facades, upstream NEEDED chain); fail-closed oracle-isolated ABI-FUNCTION-SIGNATURE plane (SOURCE_PROTOTYPE + MACHINE_ABI fingerprints, zero silent omissions); Phase-12 real downstream substitution (binary/static/docker substitution, export-surface disposition, ELF version graphs); Phase-13 hostile audit courts (ABI/ownership/allocator/callbacks/failure/threads/oracle-contamination) byte-identical vs the system oracle incl. the upstream thread-local globals model; Phase-14 downstream custodian validation courts (lxml/Nokogiri/PHP/Debian). Test counts live in atlas/TEST_COUNTS.json, residuals in atlas/RESIDUAL_LEDGER.json (generated evidence).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
//! XPointer implementation (§26, §85 Phase 5).
//!
//! XML Pointer Language (XPointer) v1.0 support based on the
//! [XPointer Framework](https://www.w3.org/TR/xptr-framework/) and
//! [element() Scheme](https://www.w3.org/TR/xptr-element/) W3C Recommendations.
//!
//! This module provides:
//!
//! - **Shorthand pointers** — bare names treated as element IDs
//! - **`element()` scheme** — `element(id)` or `element(id/N/M/…)` for
//!   child-axis traversal
//! - **`xmlXPtrEval` C ABI** — for interop with libxml2 consumers
//!
//! The caller is responsible for stripping the `#` from the URI fragment;
//! this module receives only the fragment content.
//!
//! # Upstream contract
//!
//! Mirrors upstream `xpointer.c` / `xpointer.h`
//! (`SRC-LIBXML2-2.15.0-XPOINTER-C`, parity target libxml2 2.15.3 oracle)
//! implementing the W3C-XPTR-1.0 framework: shorthand pointers, the
//! `element()` scheme (with child-axis positions `id/N/M`), and the
//! `xmlXPtrEval` / `xmlXPtrEvalNodeSet` C ABI entry points that XInclude
//! uses for `xpointer` attributes.
//!
//! # Conceptual behavior
//!
//! Evaluates an XPointer fragment against a document: a scheme-based
//! pointer (`scheme(data)`) is parsed and dispatched, and a bare name
//! falls back to shorthand semantics (element with that ID). The
//! `element(id/N/M)` form walks the child axis 1-indexed, per the XPointer
//! element() scheme. The XPath/XPointer context adapter converts between
//! this module and the xpath engine.
//!
//! # Ownership & safety invariants
//!
//! `doc` is borrowed for the evaluation; results are borrowed node
//! pointers into that document (never freed here). The caller owns the
//! document and the fragment string. The context adapter allocates
//! XPath objects that are freed before returning.
//!
//! # Historical quirks & epochs
//!
//! XPointer had a burst of CVE-2016-* fixes in the 2016 epoch
//! (SEC-0009: commits 9ab01a27, c1d1f712, 2016-06-28) that hardened the
//! element()/child-axis path this module mirrors; behavior targets the
//! 2.15.3 oracle.
//!
//! # Deliberate oddities
//!
//! The `#`-stripping contract is deliberate: upstream callers pass the
//! raw fragment after `#`, and xmlXPtrEval operates on the fragment
//! content — the candidate keeps the split explicit at the boundary.
//!
//! # Proving courts
//!
//! The XPOINTER court family (incl. XInclude xpointer cases) compares
//! resolution byte-identical against the oracle; XINCLUDE differential
//! probes exercise xmlXPtrEvalNodeSet end-to-end.
//!
//! # Tempting simplifications that would break parity
//!
//! Do not restrict xptr_eval to shorthand IDs only: the element() scheme
//! with child positions is part of the XPointer framework and XInclude
//! depends on it. Do not strip the `#` inside the module — callers that
//! pass a full fragment would silently break.

use crate::abi::structs::{_xmlAttr, _xmlDoc, _xmlNode};
use crate::abi::types::xmlAttributeType::XML_ATTRIBUTE_ID;
use crate::abi::types::xmlElementType::{XML_ELEMENT_NODE, XML_TEXT_NODE};
use crate::xml::xpath::context::XPathContext;
use crate::xml::xpath::types::NodeSet;
use std::ffi::CStr;

#[cfg(test)]
use std::ffi::CString;
use std::os::raw::c_char;
use std::ptr;

// ═══════════════════════════════════════════════════════════════════════════════
// Public API
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluate an XPointer expression and return the pointed-to node.
///
/// Supports:
/// - **Shorthand pointers** — bare name treated as an element ID.
/// - **`element()` scheme** — `element(id)` selects the element with that ID;
///   `element(id/N)` selects the N-th child (1-indexed) of that element, etc.
///
/// Returns `None` if the pointer does not resolve to a node.
///
/// # Parameters
///
/// * `expr` — the XPointer expression (without the leading `#`).
/// * `doc` — pointer to the XML document to search in.
///
/// # Safety
///
/// `doc` must be a valid, non-null pointer to a fully parsed `_xmlDoc`.
pub unsafe fn xptr_eval(expr: &str, doc: *mut _xmlDoc) -> Option<*mut _xmlNode> {
    if doc.is_null() {
        return None;
    }

    let expr = expr.trim();

    if expr.is_empty() {
        return None;
    }

    // Try to parse as a scheme-based pointer: scheme(data)
    if let Some(result) = try_eval_scheme(expr, doc) {
        return result;
    }

    // Fall back to shorthand pointer (bare name as ID).
    shorthand_lookup(expr, doc)
}

/// Evaluate an XPointer using the full XPath/XPointer context.
///
/// This is a convenience wrapper that creates a temporary XPath context
/// and delegates to [`xptr_eval`].
///
/// # Safety
///
/// `doc` must be a valid, non-null pointer to a fully parsed `_xmlDoc`.
pub unsafe fn xptr_eval_with_context(
    expr: &str,
    doc: *mut _xmlDoc,
    _context: Option<&mut XPathContext>,
) -> Option<*mut _xmlNode> {
    xptr_eval(expr, doc)
}

// ═══════════════════════════════════════════════════════════════════════════════
// C ABI
// ═══════════════════════════════════════════════════════════════════════════════

/// C ABI entry point for XPointer evaluation.
///
/// Corresponds to `xmlXPtrEval` in libxml2.
///
/// # Safety
///
/// * `expr` must be a valid null-terminated C string.
/// * `doc` must be a valid pointer to `_xmlDoc` or NULL.
///
/// Returns a pointer to the selected `_xmlNode`, or NULL if the pointer
/// does not resolve.
pub unsafe extern "C" fn xmlXPtrEval(expr: *const c_char, doc: *mut _xmlDoc) -> *mut _xmlNode {
    if expr.is_null() || doc.is_null() {
        return ptr::null_mut();
    }

    let expr_str = match unsafe { CStr::from_ptr(expr) }.to_str() {
        Ok(s) => s,
        Err(_) => return ptr::null_mut(),
    };

    match unsafe { xptr_eval(expr_str, doc) } {
        Some(node) => node,
        None => ptr::null_mut(),
    }
}

/// Evaluate an XPointer expression and return a node-set.
///
/// Corresponds to `xmlXPtrEval` returning a node-set in some libxml2 APIs.
///
/// # Safety
///
/// * `expr` must be a valid null-terminated C string.
/// * `doc` must be a valid pointer to `_xmlDoc` or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlXPtrEvalNodeSet(
    expr: *const c_char,
    doc: *mut _xmlDoc,
) -> *mut crate::abi::structs::_xmlNodeSet {
    if expr.is_null() || doc.is_null() {
        return ptr::null_mut();
    }

    let expr_str = match unsafe { CStr::from_ptr(expr) }.to_str() {
        Ok(s) => s,
        Err(_) => return ptr::null_mut(),
    };

    let node = unsafe { xptr_eval(expr_str, doc) };

    let mut ns = NodeSet::new();
    if let Some(n) = node {
        ns.push(n);
    }

    unsafe { ns.to_raw() }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Scheme-based pointer evaluation
// ═══════════════════════════════════════════════════════════════════════════════

/// Try to evaluate `expr` as a scheme-based pointer (`scheme(data)`).
///
/// Returns `None` if the expression does not match a known scheme pattern.
///
/// # Safety
///
/// - `doc` must be NULL or a valid pointer to a live `_xmlDoc` whose node tree
///   stays alive for the duration of the call; it is forwarded to
///   `eval_element_scheme`, which walks the tree through raw node pointers.
unsafe fn try_eval_scheme(expr: &str, doc: *mut _xmlDoc) -> Option<Option<*mut _xmlNode>> {
    let expr = expr.trim();

    // Try to match `element(...)` scheme
    if let Some(inner) = strip_scheme(expr, "element") {
        return Some(unsafe { eval_element_scheme(inner, doc) });
    }

    // `xpointer(...)` scheme: the inner text is an XPath expression
    // evaluated against the document (bug43364 uses
    // `xpointer="xpointer(/root/a)"` includes).
    if let Some(inner) = strip_scheme(expr, "xpointer") {
        return Some(unsafe { eval_xpointer_scheme(inner, doc) });
    }

    // No known scheme matched; return None to let the caller fall back to
    // shorthand pointer.
    None
}

/// Evaluate an `xpointer(...)` scheme: run the inner XPath expression against
/// the document and return the first selected node.
///
/// # Safety
///
/// - `doc` must be NULL or a valid `_xmlDoc`; the returned node is owned by
///   the document (borrowed).
unsafe fn eval_xpointer_scheme(inner: &str, doc: *mut _xmlDoc) -> Option<*mut _xmlNode> {
    let mut ctx = crate::xml::xpath::context::XPathContext::new(doc);
    ctx.set_context_node(doc as *mut crate::abi::structs::_xmlNode);
    match crate::xml::xpath::evaluate_str(inner, &mut ctx) {
        Some(crate::xml::xpath::types::XPathValue::NodeSet(ns)) => ns.first(),
        _ => None,
    }
}

/// Strip a scheme name and parentheses from the front of `expr`.
///
/// If `expr` starts with `scheme(` and ends with `)`, returns the inner
/// content. Otherwise returns `None`.
fn strip_scheme<'a>(expr: &'a str, scheme: &str) -> Option<&'a str> {
    let expr = expr.trim();

    let expected_prefix = format!("{}(", scheme);
    if !expr.starts_with(&expected_prefix) {
        return None;
    }

    let inner_start = expected_prefix.len();
    if !expr.ends_with(')') {
        return None;
    }

    let inner_end = expr.len() - 1;
    if inner_end <= inner_start {
        return Some("");
    }

    Some(&expr[inner_start..inner_end])
}

// ═══════════════════════════════════════════════════════════════════════════════
// element() scheme
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluate an `element()` scheme pointer.
///
/// Syntax: `element(id)` or `element(id/N1/N2/...)`
///
/// * `element(id)` — select the element with the given ID.
/// * `element(id/N)` — select the N-th child (1-indexed) of the element
///   with the given ID.
/// * `element(id/N1/N2/...)` — traverse deeper child levels.
///
/// # Safety
///
/// - `doc` must be NULL or a valid pointer to a live `_xmlDoc`; the lookup
///   walks `(*doc).children` and the node `children`/`next` links via
///   `find_element_by_id` and `nth_child_element`, so every visited node must
///   belong to the live document. The returned node pointer is borrowed from
///   `doc` and must not outlive it.
unsafe fn eval_element_scheme(inner: &str, doc: *mut _xmlDoc) -> Option<*mut _xmlNode> {
    let inner = inner.trim();
    if inner.is_empty() {
        return None;
    }

    // Split on '/'
    let parts: Vec<&str> = inner.split('/').collect();
    if parts.is_empty() {
        return None;
    }

    let id = parts[0].trim();
    if id.is_empty() {
        return None;
    }

    // Find the element with this ID
    let base = unsafe { find_element_by_id(id, doc) }?;

    // If only ID was given, return the element directly
    if parts.len() == 1 {
        return Some(base);
    }

    // Otherwise traverse child indices: element(id/N1/N2/...)
    let mut current = base;
    for &part in &parts[1..] {
        let index_str = part.trim();
        let index: usize = match index_str.parse() {
            Ok(n) if n >= 1 => n,
            _ => return None,
        };

        // Get the N-th child element (1-indexed)
        current = unsafe { nth_child_element(current, index) }?;
    }

    Some(current)
}

/// Get the N-th child element node (1-indexed) of `node`.
///
/// Only counts element nodes (XML_ELEMENT_NODE).
///
/// # Safety
///
/// - `node` must be NULL or a pointer to a valid, live `_xmlNode`; the
///   function follows the `children` and `next` links inside the live tree and
///   reads each visited node's `type_` field.
unsafe fn nth_child_element(node: *mut _xmlNode, n: usize) -> Option<*mut _xmlNode> {
    if node.is_null() {
        return None;
    }

    let mut count = 0usize;
    let mut child = unsafe { (*node).children };

    while !child.is_null() {
        let ty = unsafe { (*child).type_ };
        if ty == XML_ELEMENT_NODE as std::os::raw::c_int {
            count += 1;
            if count == n {
                return Some(child);
            }
        }
        child = unsafe { (*child).next };
    }

    None
}

// ═══════════════════════════════════════════════════════════════════════════════
// Shorthand pointer (bare name as ID)
// ═══════════════════════════════════════════════════════════════════════════════

/// Look up a bare name as an element ID (shorthand pointer).
///
/// Per the XPointer Framework, a shorthand pointer is treated as if it were
/// `element(id)`.
///
/// # Safety
///
/// - `doc` must be NULL or a valid pointer to a live `_xmlDoc`; the lookup
///   delegates to `find_element_by_id`, which walks the document tree through
///   raw node pointers, so the document must stay alive for the call.
unsafe fn shorthand_lookup(name: &str, doc: *mut _xmlDoc) -> Option<*mut _xmlNode> {
    unsafe { find_element_by_id(name, doc) }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Element-by-ID lookup
// ═══════════════════════════════════════════════════════════════════════════════

/// Find an element by its ID attribute.
///
/// This function searches the document tree for an element whose `id`
/// attribute (case-insensitive name match) has the given value.
///
/// It also checks the DTD-declared ID type (`_xmlAttr.atype ==
/// XML_ATTRIBUTE_ID`) as a secondary identification mechanism.
///
/// # Parameters
///
/// * `id` — the ID value to search for.
/// * `doc` — the document to search.
///
/// # Returns
///
/// The first matching element node, or `None`.
///
/// # Safety
///
/// - `doc` must be NULL or a valid pointer to a live `_xmlDoc`; the search
///   dereferences `(*doc).children` and recurses through the node tree via
///   `walk_for_id`, so every node visited must belong to the live document.
unsafe fn find_element_by_id(id: &str, doc: *mut _xmlDoc) -> Option<*mut _xmlNode> {
    if doc.is_null() || id.is_empty() {
        return None;
    }

    // Walk the document tree searching for an element with a matching ID
    // attribute.
    let root = unsafe { (*doc).children };
    if root.is_null() {
        return None;
    }

    unsafe { walk_for_id(root, id) }
}

/// Recursively walk the tree looking for an element with the given ID.
///
/// # Safety
///
/// - `node` must be NULL or a pointer to a valid, live `_xmlNode` whose
///   `children` and `next` links form the subtree to search; `id` is a
///   borrowed `&str` that must stay valid for the whole walk.
unsafe fn walk_for_id(node: *mut _xmlNode, id: &str) -> Option<*mut _xmlNode> {
    if node.is_null() {
        return None;
    }

    // Check if this node is an element with a matching ID attribute
    let ty = unsafe { (*node).type_ };
    if ty == XML_ELEMENT_NODE as std::os::raw::c_int && unsafe { element_has_id(node, id) } {
        return Some(node);
    }

    // Recurse into children
    let mut child = unsafe { (*node).children };
    while !child.is_null() {
        if let Some(found) = unsafe { walk_for_id(child, id) } {
            return Some(found);
        }
        child = unsafe { (*child).next };
    }

    None
}

/// Check if an element node has an attribute whose ID value matches.
///
/// Checks:
/// 1. If the attribute's `atype` is `XML_ATTRIBUTE_ID`, compare its value.
/// 2. If the attribute's name is "id" (case-insensitive), compare its value.
///
/// # Safety
///
/// - `node` must be NULL or a pointer to a valid, live `_xmlNode`; the
///   function walks `(*node).properties` through the `next` links and reads
///   each attribute's `atype`, `name`, and value, so every visited attribute
///   must belong to the live node.
unsafe fn element_has_id(node: *mut _xmlNode, id: &str) -> bool {
    if node.is_null() {
        return false;
    }

    let mut prop = unsafe { (*node).properties };
    while !prop.is_null() {
        let attr = unsafe { &*prop };

        // Check 1: DTD-declared ID type
        if attr.atype == XML_ATTRIBUTE_ID as std::os::raw::c_int {
            if let Some(val) = unsafe { get_attr_value(prop) } {
                if val == id {
                    return true;
                }
            }
        }

        // Check 2: attribute named "id" (case-insensitive)
        if !attr.name.is_null() {
            let name_str = unsafe { c_xmlchar_to_str(attr.name) };
            if name_str.as_deref() == Some("id") || name_str.as_deref() == Some("ID") {
                if let Some(val) = unsafe { get_attr_value(prop) } {
                    if val == id {
                        return true;
                    }
                }
            }
        }

        prop = unsafe { (*prop).next };
    }

    false
}

/// Extract the string value of an attribute.
unsafe fn get_attr_value(attr: *mut _xmlAttr) -> Option<String> {
    if attr.is_null() {
        return None;
    }

    let children = unsafe { (*attr).children };
    if children.is_null() {
        return None;
    }

    let text = unsafe { &*children };
    if text.type_ == XML_TEXT_NODE as std::os::raw::c_int && !text.content.is_null() {
        let val = unsafe { c_xmlchar_to_str(text.content) };
        return val;
    }

    None
}

/// Convert a `*const xmlChar` (C string) to a Rust `String`.
///
/// SAFETY: `ptr` must point to a null-terminated sequence of bytes.
unsafe fn c_xmlchar_to_str(ptr: *const crate::abi::types::xmlChar) -> Option<String> {
    if ptr.is_null() {
        return None;
    }

    // xmlChar is `c_uchar`; we reinterpret as `*const c_char` for CStr.
    let c_str = unsafe { CStr::from_ptr(ptr as *const c_char) };
    match c_str.to_str() {
        Ok(s) => Some(s.to_string()),
        Err(_) => None,
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abi::allocator::xmlMallocZero;
    use crate::abi::types::xmlElementType::*;
    use std::mem;
    use std::os::raw::c_int;
    use std::ptr;

    // ── Helper: create a minimal document tree for testing ────────────────

    /// Create a minimal document with one element: `<root id="main">`.
    ///
    /// # Safety
    ///
    /// - The function dereferences the `xmlMallocZero` allocations it makes
    ///   for `doc`, `root`, and the attribute and text nodes only after
    ///   asserting they are non-NULL; the returned `doc` owns the whole tree,
    ///   which the tests deliberately leak (never freed), so no use-after-free
    ///   is possible.
    unsafe fn create_simple_doc() -> *mut _xmlDoc {
        let doc = xmlMallocZero(mem::size_of::<_xmlDoc>()) as *mut _xmlDoc;
        assert!(!doc.is_null());

        let root = xmlMallocZero(mem::size_of::<_xmlNode>()) as *mut _xmlNode;
        assert!(!root.is_null());

        unsafe {
            (*doc).type_ = XML_DOCUMENT_NODE as c_int;
            (*doc).doc = doc;
            (*doc).children = root;

            (*root).type_ = XML_ELEMENT_NODE as c_int;
            (*root).name = string_to_xmlchar("root");
            (*root).parent = doc as *mut _xmlNode;
            (*root).doc = doc;
            (*root).properties = ptr::null_mut();
        }

        // Add id="main" attribute
        let attr = unsafe { add_id_attr(root, "id", "main") };
        unsafe {
            (*root).properties = attr;
        }

        doc
    }

    /// Create a more complex document tree:
    /// ```
    /// <root id="main">
    ///   <child1 id="a"/>
    ///   <child2 id="b">
    ///     <grandchild id="c"/>
    ///   </child2>
    ///   <child3/>
    /// </root>
    /// ```
    ///
    /// # Safety
    ///
    /// - All nodes and attributes are `xmlMallocZero` allocations asserted
    ///   non-NULL before being dereferenced and linked; the returned `doc`
    ///   owns the whole tree, which the tests deliberately leak (never
    ///   freed), so no use-after-free is possible.
    unsafe fn create_complex_doc() -> *mut _xmlDoc {
        let doc = xmlMallocZero(mem::size_of::<_xmlDoc>()) as *mut _xmlDoc;
        assert!(!doc.is_null());

        // root element
        let root = xmlMallocZero(mem::size_of::<_xmlNode>()) as *mut _xmlNode;
        assert!(!root.is_null());

        unsafe {
            (*doc).type_ = XML_DOCUMENT_NODE as c_int;
            (*doc).doc = doc;
            (*doc).children = root;

            (*root).type_ = XML_ELEMENT_NODE as c_int;
            (*root).name = string_to_xmlchar("root");
            (*root).parent = doc as *mut _xmlNode;
            (*root).doc = doc;
        }

        let attr_root = unsafe { add_id_attr(root, "id", "main") };
        unsafe { (*root).properties = attr_root };

        // child1
        let child1 = unsafe { append_child_element(root, "child1") };
        let attr_c1 = unsafe { add_id_attr(child1, "id", "a") };
        unsafe { (*child1).properties = attr_c1 };

        // child2
        let child2 = unsafe { append_child_element(root, "child2") };
        let attr_c2 = unsafe { add_id_attr(child2, "id", "b") };
        unsafe { (*child2).properties = attr_c2 };

        // grandchild (child of child2)
        let grandchild = unsafe { append_child_element(child2, "grandchild") };
        let attr_gc = unsafe { add_id_attr(grandchild, "id", "c") };
        unsafe { (*grandchild).properties = attr_gc };

        // child3 (no ID)
        let _child3 = unsafe { append_child_element(root, "child3") };

        doc
    }

    unsafe fn string_to_xmlchar(s: &str) -> *const crate::abi::types::xmlChar {
        let c_str = CString::new(s).unwrap();
        c_str.into_raw() as *const crate::abi::types::xmlChar
    }

    /// Append a new element node as the last child of `parent`.
    ///
    /// # Safety
    ///
    /// - `parent` must be a non-NULL pointer to a valid, live `_xmlNode` whose
    ///   `doc` field is readable; its `children` and `last` links are updated
    ///   in place, and `name` must stay valid until it is copied by
    ///   `string_to_xmlchar`.
    unsafe fn append_child_element(parent: *mut _xmlNode, name: &str) -> *mut _xmlNode {
        let node = xmlMallocZero(mem::size_of::<_xmlNode>()) as *mut _xmlNode;
        assert!(!node.is_null());

        unsafe {
            (*node).type_ = XML_ELEMENT_NODE as c_int;
            (*node).name = string_to_xmlchar(name);
            (*node).parent = parent;
            (*node).doc = (*parent).doc;
            (*node).next = ptr::null_mut();
            (*node).prev = (*parent).last;
            (*node).properties = ptr::null_mut();

            // Link into parent's child list
            if (*parent).children.is_null() {
                (*parent).children = node;
                (*parent).last = node;
            } else {
                let last = (*parent).last;
                if !last.is_null() {
                    (*last).next = node;
                }
                (*parent).last = node;
            }
        }

        node
    }

    /// Add an attribute node with a text-value child to an element.
    ///
    /// # Safety
    ///
    /// - `node` must be a non-NULL pointer to a valid, live `_xmlNode` whose
    ///   `doc` field is readable; the attribute and its text child are fresh
    ///   `xmlMallocZero` allocations asserted non-NULL, and `name` and `value`
    ///   must stay valid until copied by `string_to_xmlchar`.
    unsafe fn add_id_attr(node: *mut _xmlNode, name: &str, value: &str) -> *mut _xmlAttr {
        let attr = xmlMallocZero(mem::size_of::<_xmlAttr>()) as *mut _xmlAttr;
        assert!(!attr.is_null());

        // Create text child for the attribute value
        let text = xmlMallocZero(mem::size_of::<_xmlNode>()) as *mut _xmlNode;
        assert!(!text.is_null());

        unsafe {
            (*attr).type_ = 2; // XML_ATTRIBUTE_NODE
            (*attr).name = string_to_xmlchar(name);
            (*attr).parent = node;
            (*attr).doc = (*node).doc;
            (*attr).children = text;
            (*attr).last = text;
            (*attr).atype = crate::abi::types::xmlAttributeType::XML_ATTRIBUTE_CDATA as c_int;
            (*attr).next = ptr::null_mut();
            (*attr).prev = ptr::null_mut();

            (*text).type_ = XML_TEXT_NODE as c_int;
            (*text).name = string_to_xmlchar("text");
            (*text).content = string_to_xmlchar(value) as *mut crate::abi::types::xmlChar;
            (*text).parent = attr as *mut _xmlNode;
            (*text).doc = (*node).doc;
            (*text).next = ptr::null_mut();
            (*text).prev = ptr::null_mut();
        }

        attr
    }

    // ── Tests ────────────────────────────────────────────────────────────

    macro_rules! c_name_eq {
        ($node:expr, $expected:expr) => {
            assert_eq!(
                CStr::from_ptr((*$node).name as *const c_char)
                    .to_str()
                    .unwrap(),
                $expected
            );
        };
    }

    #[test]
    /// Tests that a bare name resolves as a shorthand ID pointer.
    ///
    /// # Safety
    ///
    /// - `doc` is built by `create_simple_doc`, which allocates and links the
    ///   nodes; the resolved node is dereferenced by `c_name_eq` while `doc`
    ///   is still live (the tree is leaked, never freed).
    fn test_shorthand_pointer() {
        unsafe {
            let doc = create_simple_doc();
            let result = xptr_eval("main", doc);
            assert!(result.is_some());
            c_name_eq!(result.unwrap(), "root");
        }
    }

    #[test]
    /// Tests that an unknown shorthand pointer resolves to nothing.
    ///
    /// # Safety
    ///
    /// - `doc` is built by `create_simple_doc`; `xptr_eval` walks the live
    ///   tree and returns `None` without any dangling dereferences.
    fn test_shorthand_pointer_not_found() {
        unsafe {
            let doc = create_simple_doc();
            let result = xptr_eval("nonexistent", doc);
            assert!(result.is_none());
        }
    }

    #[test]
    /// Tests basic `element(id)` scheme resolution.
    ///
    /// # Safety
    ///
    /// - `doc` is built by `create_complex_doc`; every node dereferenced by
    ///   the lookup and by `c_name_eq` is part of that live, leaked tree.
    fn test_element_scheme_basic() {
        unsafe {
            let doc = create_complex_doc();

            let result = xptr_eval("element(main)", doc);
            assert!(result.is_some());
            c_name_eq!(result.unwrap(), "root");

            let result = xptr_eval("element(a)", doc);
            assert!(result.is_some());
            c_name_eq!(result.unwrap(), "child1");

            let result = xptr_eval("element(c)", doc);
            assert!(result.is_some());
            c_name_eq!(result.unwrap(), "grandchild");
        }
    }

    #[test]
    /// Tests `element(id/N)` child-sequence traversal.
    ///
    /// # Safety
    ///
    /// - `doc` is built by `create_complex_doc`; every node dereferenced by
    ///   the child-axis walk and by `c_name_eq` belongs to that live, leaked
    ///   tree.
    fn test_element_scheme_with_child_sequence() {
        unsafe {
            let doc = create_complex_doc();

            let result = xptr_eval("element(main/1)", doc);
            assert!(result.is_some());
            c_name_eq!(result.unwrap(), "child1");

            let result = xptr_eval("element(main/2)", doc);
            assert!(result.is_some());
            c_name_eq!(result.unwrap(), "child2");

            let result = xptr_eval("element(main/2/1)", doc);
            assert!(result.is_some());
            c_name_eq!(result.unwrap(), "grandchild");
        }
    }

    #[test]
    /// Tests that an out-of-range child index resolves to nothing.
    ///
    /// # Safety
    ///
    /// - `doc` is built by `create_complex_doc`; `xptr_eval` walks the live
    ///   tree and returns `None` for the out-of-range index without dangling
    ///   dereferences.
    fn test_element_scheme_child_out_of_range() {
        unsafe {
            let doc = create_complex_doc();
            let result = xptr_eval("element(main/99)", doc);
            assert!(result.is_none());
        }
    }

    #[test]
    /// Tests that a zero child index is rejected by the `element` scheme.
    ///
    /// # Safety
    ///
    /// - `doc` is built by `create_complex_doc`; `xptr_eval` walks the live
    ///   tree and returns `None` because zero is not a valid 1-indexed child
    ///   position.
    fn test_element_scheme_zero_index() {
        unsafe {
            let doc = create_complex_doc();
            let result = xptr_eval("element(main/0)", doc);
            assert!(result.is_none());
        }
    }

    #[test]
    /// Tests that an empty expression resolves to nothing.
    ///
    /// # Safety
    ///
    /// - `doc` is built by `create_simple_doc`; `xptr_eval` returns early for
    ///   the empty expression, and the tree stays live for the whole test.
    fn test_empty_expr() {
        unsafe {
            let doc = create_simple_doc();
            let result = xptr_eval("", doc);
            assert!(result.is_none());
        }
    }

    #[test]
    /// Tests that a NULL document resolves to nothing.
    ///
    /// # Safety
    ///
    /// - `xptr_eval` checks `doc` for NULL and returns early without
    ///   dereferencing it.
    fn test_null_doc() {
        unsafe {
            let result = xptr_eval("main", ptr::null_mut());
            assert!(result.is_none());
        }
    }

    #[test]
    /// Tests the `xmlXPtrEval` C ABI entry point.
    ///
    /// # Safety
    ///
    /// - `c_expr` is a `CString` that stays alive for the call; `doc` is
    ///   built by `create_simple_doc` and stays live while the returned node
    ///   is dereferenced by `c_name_eq`.
    fn test_xml_xptr_eval_c_abi() {
        unsafe {
            let doc = create_simple_doc();
            let c_expr = CString::new("main").unwrap();
            let node = xmlXPtrEval(c_expr.as_ptr(), doc);
            assert!(!node.is_null());
            c_name_eq!(node, "root");
        }
    }

    #[test]
    /// Tests that `xmlXPtrEval` returns NULL for a NULL expression.
    ///
    /// # Safety
    ///
    /// - `xmlXPtrEval` checks `expr` for NULL and returns early without
    ///   dereferencing it; `doc` stays live for the whole test.
    fn test_xml_xptr_eval_null_expr() {
        unsafe {
            let doc = create_simple_doc();
            let node = xmlXPtrEval(ptr::null(), doc);
            assert!(node.is_null());
        }
    }

    #[test]
    /// Tests that `xmlXPtrEval` returns NULL for a NULL document.
    ///
    /// # Safety
    ///
    /// - `c_expr` is a `CString` that stays alive for the call; `xmlXPtrEval`
    ///   checks `doc` for NULL and returns early without dereferencing it.
    fn test_xml_xptr_eval_null_doc() {
        unsafe {
            let c_expr = CString::new("main").unwrap();
            let node = xmlXPtrEval(c_expr.as_ptr(), ptr::null_mut());
            assert!(node.is_null());
        }
    }

    #[test]
    /// Tests the `xmlXPtrEvalNodeSet` C ABI entry point.
    ///
    /// # Safety
    ///
    /// - `c_expr` is a `CString` alive for the call; `doc` is built by
    ///   `create_simple_doc` and stays live; the returned node set is asserted
    ///   non-NULL before `(*ns).nodeNr` and `(*ns).nodeTab` are read, and the
    ///   node taken from `(*ns).nodeTab` is dereferenced by `c_name_eq` while
    ///   `doc` is live.
    fn test_xml_xptr_eval_node_set() {
        unsafe {
            let doc = create_simple_doc();
            let c_expr = CString::new("main").unwrap();
            let ns = xmlXPtrEvalNodeSet(c_expr.as_ptr(), doc);
            assert!(!ns.is_null());
            assert_eq!((*ns).nodeNr, 1);
            assert!(!(*ns).nodeTab.is_null());
            let node = *(*ns).nodeTab;
            c_name_eq!(node, "root");
        }
    }

    #[test]
    /// Tests that an unknown ID in the `element` scheme resolves to nothing.
    ///
    /// # Safety
    ///
    /// - `doc` is built by `create_complex_doc`; the lookup walks the live
    ///   tree and returns `None` without dangling dereferences.
    fn test_element_scheme_not_found() {
        unsafe {
            let doc = create_complex_doc();
            let result = xptr_eval("element(nonexistent)", doc);
            assert!(result.is_none());
        }
    }

    #[test]
    /// Tests that whitespace inside the `element` scheme is tolerated.
    ///
    /// # Safety
    ///
    /// - `doc` is built by `create_complex_doc`; the resolved node is
    ///   dereferenced by `c_name_eq` while the tree is live.
    fn test_element_scheme_extra_spaces() {
        unsafe {
            let doc = create_complex_doc();
            let result = xptr_eval("element( main )", doc);
            assert!(result.is_some());
            c_name_eq!(result.unwrap(), "root");
        }
    }

    #[test]
    /// Tests that an element without an ID is not found by shorthand lookup.
    ///
    /// # Safety
    ///
    /// - `doc` is built by `create_complex_doc`; `xptr_eval` walks the live
    ///   tree and returns `None` for the ID-less element.
    fn test_child3_no_id() {
        unsafe {
            let doc = create_complex_doc();
            let result = xptr_eval("child3", doc);
            assert!(result.is_none());
        }
    }
}