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
//! XPath 1.0 Evaluation Context (§25).
//!
//! The evaluation context holds the state required to evaluate an XPath
//! expression: the current document, context node, context position/size,
//! variable bindings, namespace declarations, registered extension functions,
//! and recursion-depth tracking.
//!
//! # UPSTREAM-PARITY
//!
//! Mirrors `xmlXPathContext` from libxml2 with additional Rust-side state
//! for variable/function resolution and safe recursion guards.
//!
//! # Courts
//!
//! XPATH-CONTEXT-*

use crate::abi::structs::{_xmlDoc, _xmlNode, _xmlXPathObject};
use crate::abi::types::xmlChar;
use crate::xml::xpath::types::XPathValue;
use std::collections::HashMap;
use std::os::raw::c_void;

// ═══════════════════════════════════════════════════════════════════════════════
// Type Aliases
// ═══════════════════════════════════════════════════════════════════════════════

/// XPath extension function signature.
///
/// Registered extension functions receive a mutable reference to the current
/// evaluation context and a slice of already-evaluated argument values.
/// They return an `XPathValue` on success or an error string on failure.
pub type XPathFunction = fn(&mut XPathContext, &[XPathValue]) -> Result<XPathValue, String>;

/// C callback for variable lookup.
///
/// SAFETY: This is called from C ABI boundaries (e.g. when libxml2's XPath
/// evaluator invokes the variable lookup hook). The implementation must not
/// panic and must handle null pointers gracefully.
///
/// * `data` — user-supplied data pointer (the `var_lookup_data` field).
/// * `ns`   — namespace URI of the variable (may be null for no namespace).
/// * `name` — local part of the variable name.
///
/// Returns a pointer to an `_xmlXPathObject` that the caller takes ownership
/// of, or null if the variable is not found.
pub type VarLookupFunc =
    unsafe extern "C" fn(*mut c_void, *const xmlChar, *const xmlChar) -> *mut _xmlXPathObject;

/// C callback for function lookup.
///
/// SAFETY: Called from C ABI boundaries. The implementation must not panic
/// and must handle null pointers gracefully.
///
/// * `data` — user-supplied data pointer (the `func_lookup_data` field).
/// * `ns`   — namespace URI of the function (may be null for no namespace).
/// * `name` — local part of the function name.
///
/// Returns an opaque pointer to a function implementation, or null if the
/// function is not found. The interpretation of the returned pointer is
/// defined by the caller that registered the callback.
pub type FuncLookupFunc =
    unsafe extern "C" fn(*mut c_void, *const xmlChar, *const xmlChar) -> *mut c_void;

// ═══════════════════════════════════════════════════════════════════════════════
// XPathContext
// ═══════════════════════════════════════════════════════════════════════════════

/// XPath 1.0 evaluation context.
///
/// Carries all state required to evaluate an XPath expression:
///
/// * **Document and node** — the current XML document and context node.
/// * **Context position/size** — for `position()` and `last()`.
/// * **Variable bindings** — in-scope XPath variables.
/// * **Namespace bindings** — prefix-to-URI mappings.
/// * **Extension functions** — registered extension functions.
/// * **Recursion guard** — depth counter to prevent infinite recursion.
/// * **C callbacks** — hooks for variable and function lookup from the C ABI.
///
/// # Lifetime / Safety
///
/// The context borrows raw pointers to the document and nodes. It is the
/// caller's responsibility to ensure those pointers remain valid for the
/// duration of evaluation. The context does **not** own the document tree.
#[derive(Debug, Clone)]
pub struct XPathContext {
    /// The current XML document.
    pub document: *mut _xmlDoc,

    /// The current context node.
    pub context_node: *mut _xmlNode,

    /// Position of the context node within the context list (1-based).
    pub context_position: i32,

    /// Size of the context list.
    pub context_size: i32,

    /// Bound variables (name → value).
    pub variables: HashMap<String, XPathValue>,

    /// Namespace bindings (prefix → URI).
    pub namespaces: HashMap<String, String>,

    /// Registered extension functions (name → function).
    pub functions: HashMap<String, XPathFunction>,

    /// Last error message, if any.
    pub error: Option<String>,

    /// Current proximity position (for `last()` / `position()`).
    pub proximity_position: i32,

    /// The context list for `position()` / `last()`.
    pub context_list: Vec<*mut _xmlNode>,

    /// Recursion depth counter (to prevent infinite recursion).
    pub recursion_depth: u32,

    /// C callback for variable lookup.
    pub var_lookup_func: Option<VarLookupFunc>,

    /// Opaque data pointer passed to `var_lookup_func`.
    pub var_lookup_data: *mut c_void,

    /// C callback for function lookup.
    pub func_lookup_func: Option<FuncLookupFunc>,

    /// Opaque data pointer passed to `func_lookup_func`.
    pub func_lookup_data: *mut c_void,
}

impl XPathContext {
    /// Create a new XPath evaluation context for the given document.
    ///
    /// The context is initialised with:
    /// * The document pointer set to `doc`.
    /// * No context node (`null`).
    /// * Context position = 1, context size = 1 (defaults per XPath 1.0).
    /// * Empty variable, namespace, and function tables.
    /// * No error.
    /// * Proximity position = 1.
    /// * Empty context list.
    /// * Recursion depth = 0.
    /// * No C callbacks registered.
    /// * Callback data pointers set to null.
    pub fn new(doc: *mut _xmlDoc) -> Self {
        Self {
            document: doc,
            context_node: std::ptr::null_mut(),
            context_position: 1,
            context_size: 1,
            variables: HashMap::new(),
            namespaces: HashMap::new(),
            functions: HashMap::new(),
            error: None,
            proximity_position: 1,
            context_list: Vec::new(),
            recursion_depth: 0,
            var_lookup_func: None,
            var_lookup_data: std::ptr::null_mut(),
            func_lookup_func: None,
            func_lookup_data: std::ptr::null_mut(),
        }
    }

    /// Set the context node and update context position / size.
    ///
    /// If `node` is non-null, the context list is set to a single-element
    /// list containing only that node, and both `context_position` and
    /// `context_size` are set to 1.
    ///
    /// If `node` is null, the context list is cleared and both
    /// `context_position` and `context_size` are set to 1.
    pub fn set_context_node(&mut self, node: *mut _xmlNode) {
        self.context_node = node;
        if node.is_null() {
            self.context_list.clear();
            self.context_position = 1;
            self.context_size = 1;
            self.proximity_position = 1;
        } else {
            self.context_list = vec![node];
            self.context_position = 1;
            self.context_size = 1;
            self.proximity_position = 1;
        }
    }

    /// Set the context list for `position()` / `last()`.
    ///
    /// Updates `context_list`, `context_size`, and resets
    /// `context_position` and `proximity_position` to 1.
    ///
    /// The context node is not changed by this call; use
    /// [`set_context_node`](Self::set_context_node) to update it.
    pub fn set_context_list(&mut self, nodes: Vec<*mut _xmlNode>) {
        self.context_size = nodes.len() as i32;
        self.context_list = nodes;
        self.context_position = 1;
        self.proximity_position = 1;
    }

    /// Look up a variable by name.
    ///
    /// Checks the local `variables` map first. If the variable is not found
    /// there, and a `var_lookup_func` callback is registered, the callback
    /// is invoked with the variable name and its namespace (currently passed
    /// as null since our Rust-side variables have no namespace component).
    ///
    /// Returns `None` if the variable is not bound.
    ///
    /// # Note
    ///
    /// When the C callback path is used, the returned `_xmlXPathObject` is
    /// converted into an `XPathValue`. Currently this path is a placeholder;
    /// a full implementation would call into `xmlXPathObject` conversion
    /// routines.
    pub fn resolve_variable(&self, name: &str) -> Option<XPathValue> {
        // Check local Rust-side variables first.
        if let Some(value) = self.variables.get(name) {
            return Some(value.clone());
        }

        // Fall back to the C callback if registered.
        if let Some(lookup) = self.var_lookup_func {
            // Convert the name to a C string (xmlChar*).
            let c_name: Vec<xmlChar> = name.bytes().collect();
            // SAFETY: We call the C callback with the user-provided data pointer.
            // The callback must not panic and must handle null inputs gracefully.
            let result = unsafe { lookup(self.var_lookup_data, std::ptr::null(), c_name.as_ptr()) };
            if !result.is_null() {
                // TODO: Convert _xmlXPathObject to XPathValue.
                // For now, free the object and return a placeholder.
                // In a full implementation this would inspect result.type_
                // and extract the appropriate value.
                unsafe {
                    // We cannot easily convert without more ABI support.
                    // Return None for now — the C callback path is for
                    // interop scenarios where the caller handles conversion.
                    let _ = result; // would free with xmlXPathFreeObject
                }
            }
        }

        None
    }

    /// Look up a namespace URI by prefix.
    ///
    /// Checks the local `namespaces` map first. If the prefix is not found
    /// there, it falls back to scanning the namespace definitions on the
    /// context node (`nsDef` chain) and its ancestors.
    ///
    /// Returns `None` if the prefix is not bound.
    pub fn resolve_namespace(&self, prefix: &str) -> Option<String> {
        // Check local bindings first.
        if let Some(uri) = self.namespaces.get(prefix) {
            return Some(uri.clone());
        }

        // Fall back to scanning the node's namespace definitions.
        // Walk up the ancestor chain looking for nsDef declarations.
        let mut current = self.context_node;
        while !current.is_null() {
            // SAFETY: We dereference raw pointers up the parent chain.
            // The caller guarantees these pointers remain valid.
            unsafe {
                let mut ns = (*current).nsDef;
                while !ns.is_null() {
                    let ns_prefix = (*ns).prefix;
                    let ns_href = (*ns).href;

                    // Compare prefix.
                    let prefix_matches = if ns_prefix.is_null() {
                        // Default namespace (no prefix) — only matches
                        // if the caller is asking for the default namespace.
                        prefix.is_empty()
                    } else {
                        // Read the prefix as a C string and compare.
                        let mut len = 0;
                        while *ns_prefix.add(len) != 0 {
                            len += 1;
                        }
                        let slice = std::slice::from_raw_parts(ns_prefix, len);
                        slice == prefix.as_bytes()
                    };

                    if prefix_matches {
                        // Read the href as a Rust String.
                        let mut len = 0;
                        while *ns_href.add(len) != 0 {
                            len += 1;
                        }
                        let slice = std::slice::from_raw_parts(ns_href, len);
                        return Some(String::from_utf8_lossy(slice).into_owned());
                    }

                    ns = (*ns).next;
                }
            }

            // Move to parent.
            // SAFETY: The node tree is valid for the lifetime of the context.
            unsafe {
                current = (*current).parent;
            }
        }

        None
    }

    /// Look up a registered extension function by name.
    ///
    /// Checks the local `functions` map first. If not found, and a
    /// `func_lookup_func` callback is registered, the callback is invoked.
    ///
    /// Returns `None` if no such function is registered.
    pub fn lookup_function(&self, name: &str) -> Option<XPathFunction> {
        // Check local Rust-side functions first.
        if let Some(func) = self.functions.get(name) {
            return Some(*func);
        }

        // Fall back to the C callback if registered.
        if let Some(lookup) = self.func_lookup_func {
            let c_name: Vec<xmlChar> = name.bytes().collect();
            // SAFETY: The callback must return a valid function pointer or null.
            let _result =
                unsafe { lookup(self.func_lookup_data, std::ptr::null(), c_name.as_ptr()) };
            // TODO: Convert the opaque pointer back to an XPathFunction.
            // This requires storing function pointers in a registry that can
            // be looked up by the opaque handle returned by the callback.
        }

        None
    }

    /// Register an extension function.
    ///
    /// The function is stored in the local `functions` map under `name`.
    /// It will be found by [`lookup_function`](Self::lookup_function) before
    /// any C callback is consulted.
    pub fn register_function(&mut self, name: &str, func: XPathFunction) {
        self.functions.insert(name.to_string(), func);
    }

    /// Register a variable binding.
    ///
    /// The variable is stored in the local `variables` map under `name`.
    /// It will be found by [`resolve_variable`](Self::resolve_variable) before
    /// any C callback is consulted.
    pub fn register_variable(&mut self, name: &str, value: XPathValue) {
        self.variables.insert(name.to_string(), value);
    }

    /// Register a namespace binding.
    ///
    /// Maps `prefix` to `uri` in the local `namespaces` map.
    /// An empty prefix registers the default namespace.
    pub fn register_namespace(&mut self, prefix: &str, uri: &str) {
        self.namespaces.insert(prefix.to_string(), uri.to_string());
    }

    /// Record an error message.
    ///
    /// Overwrites any previously recorded error. Use `clear_error` to reset.
    pub fn set_error(&mut self, msg: &str) {
        self.error = Some(msg.to_string());
    }

    /// Clear any recorded error.
    pub fn clear_error(&mut self) {
        self.error = None;
    }

    /// Push onto the recursion stack.
    ///
    /// Increments `recursion_depth`. If the depth exceeds a reasonable limit
    /// (currently 1000), returns `Err` with an overflow message.
    ///
    /// Callers should invoke this before recursing into expression evaluation
    /// and call [`pop_recursion`](Self::pop_recursion) after returning.
    pub fn push_recursion(&mut self) -> Result<(), String> {
        const MAX_RECURSION_DEPTH: u32 = 1000;
        if self.recursion_depth >= MAX_RECURSION_DEPTH {
            return Err(
                "XPath evaluation recursion depth exceeded (infinite recursion?)".to_string(),
            );
        }
        self.recursion_depth += 1;
        Ok(())
    }

    /// Pop from the recursion stack.
    ///
    /// Decrements `recursion_depth`. Must be called after a corresponding
    /// [`push_recursion`](Self::push_recursion).
    ///
    /// # Panics
    ///
    /// Panics if `recursion_depth` is already 0 (indicating unbalanced
    /// push/pop calls).
    pub fn pop_recursion(&mut self) {
        assert!(
            self.recursion_depth > 0,
            "unbalanced pop_recursion: recursion_depth is already 0"
        );
        self.recursion_depth -= 1;
    }

    /// Returns `true` if a context node is set (non-null).
    pub fn has_context_node(&self) -> bool {
        !self.context_node.is_null()
    }

    /// Reset the context to its initial state, keeping the document pointer.
    ///
    /// Clears the context node, context list, error, and recursion depth.
    /// Variable, namespace, and function bindings are preserved.
    pub fn reset(&mut self) {
        self.context_node = std::ptr::null_mut();
        self.context_position = 1;
        self.context_size = 1;
        self.error = None;
        self.proximity_position = 1;
        self.context_list.clear();
        self.recursion_depth = 0;
    }

    /// Returns the current proximity position (1-based).
    ///
    /// Equivalent to the XPath `position()` function.
    pub fn position(&self) -> i32 {
        self.proximity_position
    }

    /// Returns the context size.
    ///
    /// Equivalent to the XPath `last()` function.
    pub fn last(&self) -> i32 {
        self.context_size
    }

    /// Advance the proximity position by one.
    ///
    /// Called when iterating over the context list during predicate
    /// evaluation.
    pub fn advance_position(&mut self) {
        self.proximity_position += 1;
        self.context_position = self.proximity_position;
    }

    /// Rewind the proximity position to 1.
    pub fn reset_position(&mut self) {
        self.proximity_position = 1;
        self.context_position = 1;
    }
}

impl Default for XPathContext {
    /// Create a default context with a null document pointer.
    ///
    /// This is useful when you need a context for testing or when the
    /// document will be set later via [`set_context_node`](Self::set_context_node).
    fn default() -> Self {
        Self::new(std::ptr::null_mut())
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::xml::xpath::ast::Expr;
    use crate::xml::xpath::types::NodeSet;

    // ── Helpers ──────────────────────────────────────────────────────────

    /// Create a minimal _xmlDoc for testing.
    ///
    /// SAFETY: The caller is responsible for freeing the allocated doc.
    unsafe fn create_test_doc() -> *mut _xmlDoc {
        // Allocate zeroed memory for a minimal document.
        let layout = std::alloc::Layout::new::<_xmlDoc>();
        let ptr = std::alloc::alloc_zeroed(layout) as *mut _xmlDoc;
        assert!(!ptr.is_null(), "failed to allocate test document");
        ptr
    }

    /// Create a minimal _xmlNode for testing.
    ///
    /// SAFETY: The caller is responsible for freeing the allocated node.
    unsafe fn create_test_node() -> *mut _xmlNode {
        let layout = std::alloc::Layout::new::<_xmlNode>();
        let ptr = std::alloc::alloc_zeroed(layout) as *mut _xmlNode;
        assert!(!ptr.is_null(), "failed to allocate test node");
        ptr
    }

    /// SAFETY: Frees a test document allocated with `create_test_doc`.
    unsafe fn free_test_doc(doc: *mut _xmlDoc) {
        if !doc.is_null() {
            let layout = std::alloc::Layout::new::<_xmlDoc>();
            std::alloc::dealloc(doc as *mut u8, layout);
        }
    }

    /// SAFETY: Frees a test node allocated with `create_test_node`.
    unsafe fn free_test_node(node: *mut _xmlNode) {
        if !node.is_null() {
            let layout = std::alloc::Layout::new::<_xmlNode>();
            std::alloc::dealloc(node as *mut u8, layout);
        }
    }

    // ── Construction ─────────────────────────────────────────────────────

    #[test]
    fn test_new_context() {
        let ctx = XPathContext::new(std::ptr::null_mut());
        assert!(ctx.document.is_null());
        assert!(ctx.context_node.is_null());
        assert_eq!(ctx.context_position, 1);
        assert_eq!(ctx.context_size, 1);
        assert!(ctx.variables.is_empty());
        assert!(ctx.namespaces.is_empty());
        assert!(ctx.functions.is_empty());
        assert!(ctx.error.is_none());
        assert_eq!(ctx.proximity_position, 1);
        assert!(ctx.context_list.is_empty());
        assert_eq!(ctx.recursion_depth, 0);
        assert!(ctx.var_lookup_func.is_none());
        assert!(ctx.var_lookup_data.is_null());
        assert!(ctx.func_lookup_func.is_none());
        assert!(ctx.func_lookup_data.is_null());
    }

    #[test]
    fn test_default_context() {
        let ctx = XPathContext::default();
        assert!(ctx.document.is_null());
        assert_eq!(ctx.context_position, 1);
    }

    #[test]
    fn test_new_with_doc() {
        unsafe {
            let doc = create_test_doc();
            let ctx = XPathContext::new(doc);
            assert_eq!(ctx.document, doc);
            free_test_doc(doc);
        }
    }

    // ── set_context_node ─────────────────────────────────────────────────

    #[test]
    fn test_set_context_node_non_null() {
        unsafe {
            let node = create_test_node();
            let mut ctx = XPathContext::new(std::ptr::null_mut());
            ctx.set_context_node(node);

            assert_eq!(ctx.context_node, node);
            assert_eq!(ctx.context_position, 1);
            assert_eq!(ctx.context_size, 1);
            assert_eq!(ctx.proximity_position, 1);
            assert_eq!(ctx.context_list.len(), 1);
            assert_eq!(ctx.context_list[0], node);

            free_test_node(node);
        }
    }

    #[test]
    fn test_set_context_node_null() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        // Set a non-null node first.
        // SAFETY: We use a dangling pointer as a sentinel — it won't be dereferenced.
        let sentinel = 1 as *mut _xmlNode;
        ctx.context_list = vec![sentinel];
        ctx.context_position = 5;
        ctx.context_size = 5;
        ctx.proximity_position = 5;

        // Now set to null — should reset everything.
        ctx.set_context_node(std::ptr::null_mut());
        assert!(ctx.context_node.is_null());
        assert!(ctx.context_list.is_empty());
        assert_eq!(ctx.context_position, 1);
        assert_eq!(ctx.context_size, 1);
        assert_eq!(ctx.proximity_position, 1);
    }

    // ── set_context_list ─────────────────────────────────────────────────

    #[test]
    fn test_set_context_list() {
        unsafe {
            let node1 = create_test_node();
            let node2 = create_test_node();
            let nodes = vec![node1, node2];

            let mut ctx = XPathContext::new(std::ptr::null_mut());
            ctx.set_context_list(nodes.clone());

            assert_eq!(ctx.context_list.len(), 2);
            assert_eq!(ctx.context_size, 2);
            assert_eq!(ctx.context_position, 1);
            assert_eq!(ctx.proximity_position, 1);

            free_test_node(node1);
            free_test_node(node2);
        }
    }

    #[test]
    fn test_set_context_list_empty() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.set_context_list(vec![]);

        assert!(ctx.context_list.is_empty());
        assert_eq!(ctx.context_size, 0);
        assert_eq!(ctx.context_position, 1);
    }

    // ── Variables ────────────────────────────────────────────────────────

    #[test]
    fn test_register_and_resolve_variable() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_variable("foo", XPathValue::String("bar".to_string()));

        let result = ctx.resolve_variable("foo");
        assert!(result.is_some());
        assert_eq!(result.unwrap().as_string(), "bar");
    }

    #[test]
    fn test_resolve_unknown_variable() {
        let ctx = XPathContext::new(std::ptr::null_mut());
        assert!(ctx.resolve_variable("nonexistent").is_none());
    }

    #[test]
    fn test_register_variable_number() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_variable("pi", XPathValue::Number(3.14159));

        let result = ctx.resolve_variable("pi");
        assert!(result.is_some());
        let val = result.unwrap();
        assert!((val.as_number() - 3.14159).abs() < 1e-10);
    }

    #[test]
    fn test_register_variable_boolean() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_variable("flag", XPathValue::Boolean(true));

        let result = ctx.resolve_variable("flag");
        assert!(result.is_some());
        assert!(result.unwrap().as_boolean());
    }

    #[test]
    fn test_register_variable_nodeset() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        let ns = NodeSet::new();
        ctx.register_variable("nodes", XPathValue::NodeSet(ns));

        let result = ctx.resolve_variable("nodes");
        assert!(result.is_some());
        assert!(matches!(result.unwrap(), XPathValue::NodeSet(_)));
    }

    #[test]
    fn test_variable_overwrite() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_variable("x", XPathValue::Number(1.0));
        ctx.register_variable("x", XPathValue::Number(2.0));

        let result = ctx.resolve_variable("x");
        assert!(result.is_some());
        assert!((result.unwrap().as_number() - 2.0).abs() < 1e-10);
    }

    // ── Namespaces ───────────────────────────────────────────────────────

    #[test]
    fn test_register_and_resolve_namespace() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_namespace("xslt", "http://www.w3.org/1999/XSL/Transform");

        let result = ctx.resolve_namespace("xslt");
        assert!(result.is_some());
        assert_eq!(result.unwrap(), "http://www.w3.org/1999/XSL/Transform");
    }

    #[test]
    fn test_resolve_unknown_namespace() {
        let ctx = XPathContext::new(std::ptr::null_mut());
        // With no context node and no bindings, this should return None.
        assert!(ctx.resolve_namespace("unknown").is_none());
    }

    #[test]
    fn test_register_default_namespace() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_namespace("", "http://example.com/default");

        let result = ctx.resolve_namespace("");
        assert!(result.is_some());
        assert_eq!(result.unwrap(), "http://example.com/default");
    }

    #[test]
    fn test_namespace_overwrite() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_namespace("a", "http://example.com/1");
        ctx.register_namespace("a", "http://example.com/2");

        let result = ctx.resolve_namespace("a");
        assert_eq!(result.unwrap(), "http://example.com/2");
    }

    // ── Functions ────────────────────────────────────────────────────────

    #[test]
    fn test_register_and_lookup_function() {
        fn test_func(_ctx: &mut XPathContext, _args: &[XPathValue]) -> Result<XPathValue, String> {
            Ok(XPathValue::String("test".to_string()))
        }

        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_function("test:func", test_func);

        let result = ctx.lookup_function("test:func");
        assert!(result.is_some());
    }

    #[test]
    fn test_lookup_unknown_function() {
        let ctx = XPathContext::new(std::ptr::null_mut());
        assert!(ctx.lookup_function("nonexistent").is_none());
    }

    #[test]
    fn test_function_overwrite() {
        fn func_a(_ctx: &mut XPathContext, _args: &[XPathValue]) -> Result<XPathValue, String> {
            Ok(XPathValue::String("a".to_string()))
        }
        fn func_b(_ctx: &mut XPathContext, _args: &[XPathValue]) -> Result<XPathValue, String> {
            Ok(XPathValue::String("b".to_string()))
        }

        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_function("f", func_a);
        ctx.register_function("f", func_b);

        let result = ctx.lookup_function("f");
        assert!(result.is_some());

        // The overwritten function should be func_b.
        if let Some(f) = result {
            let mut tmp_ctx = XPathContext::new(std::ptr::null_mut());
            let value = f(&mut tmp_ctx, &[]).unwrap();
            assert_eq!(value.as_string(), "b");
        }
    }

    // ── Error handling ───────────────────────────────────────────────────

    #[test]
    fn test_set_and_get_error() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        assert!(ctx.error.is_none());

        ctx.set_error("something went wrong");
        assert_eq!(ctx.error.as_deref(), Some("something went wrong"));
    }

    #[test]
    fn test_clear_error() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.set_error("an error");
        assert!(ctx.error.is_some());

        ctx.clear_error();
        assert!(ctx.error.is_none());
    }

    #[test]
    fn test_error_overwrite() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.set_error("first error");
        ctx.set_error("second error");
        assert_eq!(ctx.error.as_deref(), Some("second error"));
    }

    // ── Recursion depth ──────────────────────────────────────────────────

    #[test]
    fn test_push_pop_recursion() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        assert_eq!(ctx.recursion_depth, 0);

        assert!(ctx.push_recursion().is_ok());
        assert_eq!(ctx.recursion_depth, 1);

        ctx.pop_recursion();
        assert_eq!(ctx.recursion_depth, 0);
    }

    #[test]
    fn test_recursion_depth_limit() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());

        // Push to the limit (1000).
        for _ in 0..1000 {
            assert!(ctx.push_recursion().is_ok());
        }
        assert_eq!(ctx.recursion_depth, 1000);

        // The next push should fail.
        let result = ctx.push_recursion();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("recursion depth exceeded"));

        // Pop back down.
        for _ in 0..1000 {
            ctx.pop_recursion();
        }
        assert_eq!(ctx.recursion_depth, 0);
    }

    #[test]
    #[should_panic(expected = "unbalanced pop_recursion")]
    fn test_pop_recursion_underflow() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.pop_recursion(); // depth is 0 — should panic
    }

    #[test]
    fn test_recursion_nesting() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());

        // Simulate nested evaluation.
        assert!(ctx.push_recursion().is_ok());
        assert!(ctx.push_recursion().is_ok());
        assert!(ctx.push_recursion().is_ok());
        assert_eq!(ctx.recursion_depth, 3);

        ctx.pop_recursion();
        assert_eq!(ctx.recursion_depth, 2);

        ctx.pop_recursion();
        assert_eq!(ctx.recursion_depth, 1);

        ctx.pop_recursion();
        assert_eq!(ctx.recursion_depth, 0);
    }

    // ── Position / Size ──────────────────────────────────────────────────

    #[test]
    fn test_position_and_last() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        assert_eq!(ctx.position(), 1);
        assert_eq!(ctx.last(), 1);
    }

    #[test]
    fn test_advance_position() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.advance_position();
        assert_eq!(ctx.position(), 2);
        assert_eq!(ctx.proximity_position, 2);
        assert_eq!(ctx.context_position, 2);
    }

    #[test]
    fn test_reset_position() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.advance_position();
        ctx.advance_position();
        ctx.advance_position();
        assert_eq!(ctx.position(), 4);

        ctx.reset_position();
        assert_eq!(ctx.position(), 1);
        assert_eq!(ctx.context_position, 1);
    }

    #[test]
    fn test_position_with_context_list() {
        unsafe {
            let node1 = create_test_node();
            let node2 = create_test_node();
            let node3 = create_test_node();
            let nodes = vec![node1, node2, node3];

            let mut ctx = XPathContext::new(std::ptr::null_mut());
            ctx.set_context_list(nodes);

            assert_eq!(ctx.last(), 3);
            assert_eq!(ctx.position(), 1);

            ctx.advance_position();
            assert_eq!(ctx.position(), 2);

            ctx.advance_position();
            assert_eq!(ctx.position(), 3);

            free_test_node(node1);
            free_test_node(node2);
            free_test_node(node3);
        }
    }

    // ── has_context_node ─────────────────────────────────────────────────

    #[test]
    fn test_has_context_node() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        assert!(!ctx.has_context_node());

        unsafe {
            let node = create_test_node();
            ctx.set_context_node(node);
            assert!(ctx.has_context_node());
            free_test_node(node);
        }
    }

    // ── reset ────────────────────────────────────────────────────────────

    #[test]
    fn test_reset() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());

        // Set up some state.
        ctx.set_error("test error");
        ctx.proximity_position = 5;
        ctx.context_position = 5;
        ctx.context_size = 10;
        ctx.recursion_depth = 3;
        unsafe {
            let sentinel = 1 as *mut _xmlNode;
            ctx.context_list = vec![sentinel];
        }

        // Register some bindings — these should survive reset.
        ctx.register_variable("x", XPathValue::Number(42.0));
        ctx.register_namespace("p", "http://example.com/ns");
        fn dummy(_: &mut XPathContext, _: &[XPathValue]) -> Result<XPathValue, String> {
            Ok(XPathValue::Boolean(true))
        }
        ctx.register_function("f", dummy);

        ctx.reset();

        // Context node and position should be reset.
        assert!(ctx.context_node.is_null());
        assert_eq!(ctx.context_position, 1);
        assert_eq!(ctx.context_size, 1);
        assert_eq!(ctx.proximity_position, 1);
        assert!(ctx.error.is_none());
        assert!(ctx.context_list.is_empty());
        assert_eq!(ctx.recursion_depth, 0);

        // Bindings should be preserved.
        assert!(ctx.resolve_variable("x").is_some());
        assert!(ctx.resolve_namespace("p").is_some());
        assert!(ctx.lookup_function("f").is_some());
    }

    // ── C callback fields ────────────────────────────────────────────────

    #[test]
    fn test_callback_fields_default_to_none() {
        let ctx = XPathContext::new(std::ptr::null_mut());
        assert!(ctx.var_lookup_func.is_none());
        assert!(ctx.var_lookup_data.is_null());
        assert!(ctx.func_lookup_func.is_none());
        assert!(ctx.func_lookup_data.is_null());
    }

    #[test]
    fn test_set_callback_fields() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());

        unsafe extern "C" fn dummy_var_lookup(
            _data: *mut c_void,
            _ns: *const xmlChar,
            _name: *const xmlChar,
        ) -> *mut _xmlXPathObject {
            std::ptr::null_mut()
        }

        unsafe extern "C" fn dummy_func_lookup(
            _data: *mut c_void,
            _ns: *const xmlChar,
            _name: *const xmlChar,
        ) -> *mut c_void {
            std::ptr::null_mut()
        }

        let data_ptr = &mut 42u32 as *mut u32 as *mut c_void;

        ctx.var_lookup_func = Some(dummy_var_lookup);
        ctx.var_lookup_data = data_ptr;
        ctx.func_lookup_func = Some(dummy_func_lookup);
        ctx.func_lookup_data = data_ptr;

        assert!(ctx.var_lookup_func.is_some());
        assert!(!ctx.var_lookup_data.is_null());
        assert!(ctx.func_lookup_func.is_some());
        assert!(!ctx.func_lookup_data.is_null());
    }

    // ── Clone ────────────────────────────────────────────────────────────

    #[test]
    fn test_context_clone() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_variable("x", XPathValue::Number(10.0));
        ctx.register_namespace("ns", "http://example.com/ns");
        ctx.set_error("clone test");

        let cloned = ctx.clone();
        assert_eq!(cloned.document, ctx.document);
        assert_eq!(cloned.context_node, ctx.context_node);
        assert_eq!(cloned.context_position, ctx.context_position);
        assert_eq!(cloned.context_size, ctx.context_size);
        assert_eq!(cloned.error, ctx.error);

        // Verify the clone has independent state.
        let var = cloned.resolve_variable("x");
        assert!(var.is_some());
        assert!((var.unwrap().as_number() - 10.0).abs() < 1e-10);

        let ns = cloned.resolve_namespace("ns");
        assert!(ns.is_some());
        assert_eq!(ns.unwrap(), "http://example.com/ns");
    }

    // ── Debug ────────────────────────────────────────────────────────────

    #[test]
    fn test_context_debug_format() {
        let ctx = XPathContext::new(std::ptr::null_mut());
        let debug_str = format!("{:?}", ctx);
        assert!(debug_str.contains("context_position"));
        assert!(debug_str.contains("context_size"));
        assert!(debug_str.contains("recursion_depth"));
    }

    // ── Edge cases ───────────────────────────────────────────────────────

    #[test]
    fn test_context_size_zero() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.set_context_list(vec![]);
        assert_eq!(ctx.last(), 0);
        assert_eq!(ctx.position(), 1);
    }

    #[test]
    fn test_multiple_advancements() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        for i in 1..=10 {
            assert_eq!(ctx.position(), i);
            ctx.advance_position();
        }
        assert_eq!(ctx.position(), 11);
    }

    #[test]
    fn test_register_multiple_variables() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_variable("a", XPathValue::Number(1.0));
        ctx.register_variable("b", XPathValue::String("two".to_string()));
        ctx.register_variable("c", XPathValue::Boolean(true));

        assert_eq!(ctx.variables.len(), 3);
        assert_eq!(ctx.resolve_variable("a").unwrap().as_number(), 1.0);
        assert_eq!(ctx.resolve_variable("b").unwrap().as_string(), "two");
        assert!(ctx.resolve_variable("c").unwrap().as_boolean());
    }

    #[test]
    fn test_register_multiple_namespaces() {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_namespace("a", "http://example.com/a");
        ctx.register_namespace("b", "http://example.com/b");
        ctx.register_namespace("c", "http://example.com/c");

        assert_eq!(ctx.namespaces.len(), 3);
        assert_eq!(ctx.resolve_namespace("a").unwrap(), "http://example.com/a");
        assert_eq!(ctx.resolve_namespace("b").unwrap(), "http://example.com/b");
        assert_eq!(ctx.resolve_namespace("c").unwrap(), "http://example.com/c");
    }

    #[test]
    fn test_register_multiple_functions() {
        fn f1(_: &mut XPathContext, _: &[XPathValue]) -> Result<XPathValue, String> {
            Ok(XPathValue::Number(1.0))
        }
        fn f2(_: &mut XPathContext, _: &[XPathValue]) -> Result<XPathValue, String> {
            Ok(XPathValue::Number(2.0))
        }
        fn f3(_: &mut XPathContext, _: &[XPathValue]) -> Result<XPathValue, String> {
            Ok(XPathValue::Number(3.0))
        }

        let mut ctx = XPathContext::new(std::ptr::null_mut());
        ctx.register_function("f1", f1);
        ctx.register_function("f2", f2);
        ctx.register_function("f3", f3);

        assert_eq!(ctx.functions.len(), 3);
    }
}