libxml-rs 0.1.0-alpha.46

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure; three-DSO ELF packaging (libxml2.so.16 core + libxslt.so.1/libexslt.so.0 facades, upstream NEEDED chain); fail-closed oracle-isolated ABI-FUNCTION-SIGNATURE plane (SOURCE_PROTOTYPE + MACHINE_ABI fingerprints, zero silent omissions); Phase-12 real downstream substitution (binary/static/docker substitution, export-surface disposition, ELF version graphs); Phase-13 hostile audit courts (ABI/ownership/allocator/callbacks/failure/threads/oracle-contamination) byte-identical vs the system oracle incl. the upstream thread-local globals model; Phase-14 downstream custodian validation courts (lxml/Nokogiri/PHP/Debian). Test counts live in atlas/TEST_COUNTS.json, residuals in atlas/RESIDUAL_LEDGER.json (generated evidence).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
//! XPath 1.0 Evaluation Engine (§25).
//!
//! Evaluates compiled XPath expressions against XML trees using the
//! internal Rust representation.
//!
//! # UPSTREAM-PARITY
//!
//! Full XPath 1.0 evaluation semantics: location paths, axes, node tests,
//! predicates, functions, operators, type conversions, comparison semantics.
//!
//! # Courts
//!
//! XPATH-EVAL-*
//!
//! # Upstream contract
//!
//! Mirrors the evaluation core of upstream `xpath.c`
//! (`SRC-LIBXML2-2.15.0-XPATH-C`, parity target libxml2 2.15.3 oracle):
//! xmlXPathEvalExpr semantics for location paths, predicates, operators,
//! type conversions and comparison rules.
//!
//! # Conceptual behavior
//!
//! Walks the AST with an explicit recursion guard (`push_recursion` /
//! `pop_recursion`). Absolute paths start at the document node (the
//! `_xmlDoc` cast to `_xmlNode`, type 9), NOT at the root element — the
//! R-000102 fix that aligns `/` with XPath 1.0. Predicates are evaluated
//! per-step with live context position/size; node-sets are deduplicated
//! in document order.
//!
//! # Ownership & safety invariants
//!
//! Evaluation borrows the tree and the context: node-sets hold borrowed
//! `_xmlNode` pointers that stay valid while the document lives; the
//! engine never frees tree nodes. Values returned to the C ABI are
//! converted in exports.rs and owned by the `_xmlXPathObject`. Context
//! mutation is confined to the evaluation call (no global state).
//!
//! # Historical quirks & epochs
//!
//! R-000102: absolute paths originally evaluated from the root element
//! (candidate bug) and were fixed to the document node. R-000159:
//! `//book[position() <= 2]` matched one extra node until the predicate
//! context-size semantics were aligned with the oracle. Both were sealed
//! during the 11.1 XPath closure against the 2.15.3 oracle.
//!
//! # Deliberate oddities
//!
//! The engine evaluates predicates eagerly per step (upstream
//! xmlXPathCompOpEval style) rather than collecting then filtering —
//! position()/last() depend on that order, so it is deliberate.
//!
//! # Proving courts
//!
//! XPATH-EVAL-* and the XPATH differential probes compare evaluation
//! results byte-identical against the oracle; the XSLT courts
//! (CLI-XSLTPROC-*) run compiled templates through this engine.
//!
//! # Tempting simplifications that would break parity
//!
//! Do not defer predicate evaluation to a post-filter pass: position() /
//! last() are order-sensitive (R-000159). Do not drop the recursion
//! guard, and do not evaluate absolute paths from the root element
//! (R-000102) — both are observable through xmlXPathEval results.

use crate::abi::structs::_xmlNode;
use crate::xml::xpath::ast::{Axis, BinaryOp, Expr, NameTest, NodeTest, Step};
use crate::xml::xpath::axes;
use crate::xml::xpath::context::XPathContext;
use crate::xml::xpath::parser_context::{
    free_parser_context, new_parser_context, value_pop, value_push,
};
use crate::xml::xpath::types::{node_string_value, string_to_number, NodeSet, XPathValue};
use core::ffi::c_void;
use std::os::raw::c_int;

// ═══════════════════════════════════════════════════════════════════════════════
// Evaluation
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluate an XPath expression in the given context.
pub fn eval(ctx: &mut XPathContext, expr: &Expr) -> Result<XPathValue, String> {
    ctx.push_recursion()?;

    let result = match expr {
        Expr::Step(step) => eval_step(ctx, step),
        Expr::AbsolutePath(expr) => eval_absolute_path(ctx, expr),
        Expr::RelativePath(left, right) => eval_relative_path(ctx, left, right),
        Expr::Filter(expr, predicates) => eval_filter(ctx, expr, predicates),
        Expr::Variable(name) => eval_variable(ctx, name),
        Expr::StringLiteral(s) => Ok(XPathValue::String(s.clone())),
        Expr::NumberLiteral(n) => Ok(XPathValue::Number(*n)),
        Expr::BooleanLiteral(b) => Ok(XPathValue::Boolean(*b)),
        Expr::FunctionCall { name, args } => eval_function_call(ctx, name, args),
        Expr::BinaryOp { op, left, right } => eval_binary_op(ctx, op, left, right),
        Expr::UnaryMinus(expr) => {
            let val = eval(ctx, expr)?;
            Ok(XPathValue::Number(-val.as_number()))
        }
        Expr::Union(left, right) => eval_union(ctx, left, right),
    };

    ctx.pop_recursion();
    result
}

// ═══════════════════════════════════════════════════════════════════════════════
// Location Path Evaluation
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluate an absolute location path: `/foo/bar`.
fn eval_absolute_path(ctx: &mut XPathContext, expr: &Expr) -> Result<XPathValue, String> {
    // Start from the document root
    let doc = ctx.document;
    if doc.is_null() {
        return Ok(XPathValue::NodeSet(NodeSet::new()));
    }

    {
        // The document node is the _xmlDoc cast to _xmlNode (type 9).
        // Absolute paths like `/root/item` select relative to the
        // document node itself, NOT the root element. This matches
        // XPath 1.0: `/` selects the document root node.
        let doc_node = doc as *mut _xmlNode;

        // Set context to document node and evaluate the path
        let saved_node = ctx.context_node;
        let saved_list = ctx.context_list.clone();
        ctx.context_node = doc_node;
        ctx.set_context_list(vec![doc_node]);

        let result = eval(ctx, expr);

        ctx.context_node = saved_node;
        ctx.context_list = saved_list;

        result
    }
}

/// Evaluate a relative location path: `foo/bar`.
fn eval_relative_path(
    ctx: &mut XPathContext,
    left: &Expr,
    right: &Expr,
) -> Result<XPathValue, String> {
    // Evaluate left side to get a node-set. UPSTREAM-PARITY (xpath.c
    // xmlXPathCompOpEval, FilterExpr '/' RelativeLocationPath): a non-node-set
    // left operand (e.g. `1/b`) is XPATH_INVALID_TYPE — "XPath error : Invalid
    // type" — NOT a panic (Phase 16 ASan fuzz finding: `1/b` aborted the
    // process).
    let left_val = eval(ctx, left)?;
    let left_ns = match left_val {
        XPathValue::NodeSet(ns) => ns,
        _ => return Err("Invalid type".to_string()),
    };
    let left_ns = left_ns.clone();

    let mut result = NodeSet::new();

    for node in left_ns.iter() {
        // For each node in the left result, evaluate the right step
        let saved_node = ctx.context_node;
        let saved_list = ctx.context_list.clone();
        ctx.context_node = node;
        ctx.set_context_list(left_ns.iter().collect());

        match eval(ctx, right) {
            Ok(val) => {
                if let XPathValue::NodeSet(ns) = val {
                    for n in ns.iter() {
                        result.push(n);
                    }
                }
            }
            Err(e) => {
                ctx.context_node = saved_node;
                ctx.context_list = saved_list;
                return Err(e);
            }
        }

        ctx.context_node = saved_node;
        ctx.context_list = saved_list;
    }

    // The per-context-node concatenation is append-only and may overlap across
    // context nodes; restore document order + uniqueness once (NodeSet::push
    // no longer sorts/dedups per insert).
    result.sort();
    Ok(XPathValue::NodeSet(result))
}

/// Evaluate a single step.
/// Evaluate one axis step, applying predicates to the traversed node-set.
///
/// # Safety
///
/// - `ctx.context_node` must be NULL or a valid `_xmlNode` that stays
///   alive for the call; `traverse_axis` reads the node's subtree, so the
///   whole reachable tree must be valid and stable while it runs; the
///   predicate evaluation temporarily mutates the context fields, which
///   must not be observed by other threads during the call.
fn eval_step(ctx: &mut XPathContext, step: &Step) -> Result<XPathValue, String> {
    let context_node = ctx.context_node;
    if context_node.is_null() {
        return Ok(XPathValue::NodeSet(NodeSet::new()));
    }

    // UPSTREAM-PARITY (xpath.c xmlXPathCompQName): a QName / prefix:* node
    // test resolves its prefix through the context's REGISTERED namespaces
    // (ctxt->nsHash) — never the document's in-scope declarations. An
    // unregistered prefix raises XPATH_UNDEF_PREFIX_ERROR
    // ("Undefined namespace prefix: prefix").
    let node_test = resolve_step_prefix(&step.node_test, &ctx.namespaces)?;

    // Traverse the axis. Attribute nodes are included for every axis step;
    // namespace nodes only when the step is explicitly the namespace axis
    // (upstream collects namespace nodes only on AXIS_NAMESPACE).
    let include_namespaces = step.axis == Axis::Namespace;
    let mut result = unsafe {
        axes::traverse_axis(
            context_node,
            step.axis,
            &node_test,
            true, // include attributes
            include_namespaces,
        )
    };

    // Apply predicates
    for predicate in &step.predicates {
        let mut filtered = NodeSet::new();

        for (i, node) in result.iter().enumerate() {
            // Set context position and size for this node
            let saved_node = ctx.context_node;
            let saved_pos = ctx.context_position;
            let saved_prox = ctx.proximity_position;
            let saved_size = ctx.context_size;
            let saved_list = ctx.context_list.clone();

            ctx.context_node = node;
            ctx.context_position = (i + 1) as i32;
            // UPSTREAM-PARITY: position() reads proximityPosition — both
            // must track the predicate position (R-000159).
            ctx.proximity_position = (i + 1) as i32;
            ctx.context_size = result.len() as i32;

            // Evaluate predicate
            let pred_val = eval(ctx, predicate)?;

            // Predicate is true if:
            // - It's a number and equals the context position
            // - It's a boolean and is true
            // - It converts to true
            let matches = match pred_val {
                XPathValue::Number(n) => {
                    // Number predicate: match if n == context_position
                    (n - (i as f64 + 1.0)).abs() < f64::EPSILON
                        || (n.round() as i32) == (i + 1) as i32
                }
                _ => pred_val.as_boolean(),
            };

            if matches {
                filtered.push(node);
            }

            ctx.context_node = saved_node;
            ctx.context_position = saved_pos;
            ctx.proximity_position = saved_prox;
            ctx.context_size = saved_size;
            ctx.context_list = saved_list;
        }

        result = filtered;
    }

    Ok(XPathValue::NodeSet(result))
}

/// Resolve a step's node-test prefix through the registered namespaces,
/// replacing prefix-based tests with URI-based ones (upstream
/// `xmlXPathCompQName`/`xmlXPathCompNodeTest` do this at compile time; the
/// candidate's AST is built without the context, so the resolution happens
/// here at the start of each step evaluation).
///
/// An unregistered prefix is an error (XPATH_UNDEF_PREFIX_ERROR).
fn resolve_step_prefix(
    node_test: &NodeTest,
    namespaces: &std::collections::HashMap<String, String>,
) -> Result<NodeTest, String> {
    match node_test {
        NodeTest::NameTest(NameTest::QName { prefix, local }) if !prefix.is_empty() => {
            let uri = namespaces
                .get(prefix)
                .ok_or_else(|| format!("Undefined namespace prefix: {}", prefix))?;
            Ok(NodeTest::NameTest(NameTest::QNameUri {
                uri: uri.clone(),
                local: local.clone(),
            }))
        }
        NodeTest::NsWildcard(prefix) if !prefix.is_empty() => {
            let uri = namespaces
                .get(prefix)
                .ok_or_else(|| format!("Undefined namespace prefix: {}", prefix))?;
            Ok(NodeTest::NsWildcardUri(uri.clone()))
        }
        _ => Ok(node_test.clone()),
    }
}

/// Evaluate a filter expression: `primary[pred1][pred2]`.
fn eval_filter(
    ctx: &mut XPathContext,
    expr: &Expr,
    predicates: &[Expr],
) -> Result<XPathValue, String> {
    // Evaluate the primary expression
    let mut result = eval(ctx, expr)?;

    // Apply predicates
    let ns = match &mut result {
        XPathValue::NodeSet(ns) => ns,
        _ => return Ok(result), // Non-node-set can't have predicates
    };

    for predicate in predicates {
        let mut filtered = NodeSet::new();
        let nodes: Vec<_> = ns.iter().collect();

        for (i, node) in nodes.iter().enumerate() {
            let saved_node = ctx.context_node;
            let saved_pos = ctx.context_position;
            let saved_prox = ctx.proximity_position;
            let saved_size = ctx.context_size;
            let saved_list = ctx.context_list.clone();

            ctx.context_node = *node;
            ctx.context_position = (i + 1) as i32;
            // UPSTREAM-PARITY: position() reads proximityPosition (R-000159).
            ctx.proximity_position = (i + 1) as i32;
            ctx.context_size = nodes.len() as i32;

            let pred_val = eval(ctx, predicate)?;

            let matches = match pred_val {
                XPathValue::Number(n) => {
                    (n - (i as f64 + 1.0)).abs() < f64::EPSILON
                        || (n.round() as i32) == (i + 1) as i32
                }
                _ => pred_val.as_boolean(),
            };

            if matches {
                filtered.push(*node);
            }

            ctx.context_node = saved_node;
            ctx.context_position = saved_pos;
            ctx.proximity_position = saved_prox;
            ctx.context_size = saved_size;
            ctx.context_list = saved_list;
        }

        *ns = filtered;
    }

    Ok(result)
}

// ═══════════════════════════════════════════════════════════════════════════════
// Variable / Function Call Evaluation
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluate a variable reference.
fn eval_variable(ctx: &mut XPathContext, name: &str) -> Result<XPathValue, String> {
    ctx.resolve_variable(name)
        .ok_or_else(|| format!("Undefined variable: ${}", name))
}

/// Resolve a function-call name to the qualified `{URI}local` key used by
/// `xmlXPathRegisterFuncNS`. Unprefixed names stay as-is; a `prefix:local`
/// name is expanded using the context's registered namespace map. Returns
/// `None` when the prefix is undeclared or the name is unprefixed.
fn resolve_function_qualified_name(ctx: &XPathContext, name: &str) -> Option<String> {
    let (prefix, local) = name.split_once(':')?;
    let uri = ctx.namespaces.get(prefix)?;
    Some(format!("{{{}}}{}", uri, local))
}

/// Evaluate a function call.
fn eval_function_call(
    ctx: &mut XPathContext,
    name: &str,
    args: &[Expr],
) -> Result<XPathValue, String> {
    // Evaluate arguments first
    let mut evaluated_args = Vec::new();
    for arg in args {
        evaluated_args.push(eval(ctx, arg)?);
    }

    // Look up the function. Namespaced function calls (nokogiri's
    // `nokogiri-builtin:css-class` registered via xmlXPathRegisterFuncNS with
    // URI `https://www.nokogiri.org/default_ns/ruby/builtins`) are stored under
    // the `{URI}local` qualified key. The raw name (e.g. `exsl:node-set`) is
    // tried first so the XSLT function_lookup closure (which splits on ':') and
    // prefix-string-registered functions resolve; the qualified key falls back.
    //
    // UPSTREAM-PARITY (functions.c xsltXPathFunctionLookup): for a PREFIXED
    // call whose prefix is declared, the per-context extension registry is
    // consulted BEFORE the builtin/native tables — xslt gives "priority to
    // context-level functions" (xmlHashLookup2 on the funcHash, which
    // xsltRegisterExtFunction fills) over the module registry and the XSLT
    // builtins. PHP exploits this to OVERRIDE EXSLT builtins
    // (registerPHPFunctionNS on the EXSLT namespace); native Rust registrations
    // (e.g. the candidate's EXSLT library) must therefore yield to a
    // per-context C registration for the same prefix:local name.
    let namespaced_c_first: Option<crate::xml::xpath::context::BoxedXPathFunction> = {
        let prefixed = name
            .split_once(':')
            .is_some_and(|(p, _)| !p.is_empty() && ctx.namespaces.contains_key(p));
        if prefixed {
            ctx.function_lookup.as_ref().and_then(|lk| lk(ctx, name))
        } else {
            None
        }
    };
    if let Some(f) = namespaced_c_first {
        return f(ctx, &evaluated_args);
    }
    let mut func_ptr: Option<*const crate::xml::xpath::context::BoxedXPathFunction> = None;
    if let Some(f) = ctx.lookup_function(name) {
        func_ptr = Some(f as *const _);
    } else if let Some(qname) = resolve_function_qualified_name(ctx, name) {
        if let Some(f) = ctx.lookup_function(&qname) {
            func_ptr = Some(f as *const _);
        }
    }
    match func_ptr {
        Some(p) => {
            // SAFETY: `p` points into `ctx.functions`, which is alive for the
            // duration of this call and is not mutated during evaluation.
            let f: &crate::xml::xpath::context::BoxedXPathFunction = unsafe { &*p };
            f(ctx, &evaluated_args)
        }
        None => {
            // C-registered extension function (xmlXPathRegisterFuncLookup):
            // consumers like nokogiri register a lookup callback that returns
            // an xmlXPathFunction; the candidate must invoke it with the
            // upstream parser-context protocol (name on ctxt->function, args
            // on the value stack, result popped off the stack).
            if ctx.func_lookup_func.is_some() {
                if let Some(result) = invoke_c_extension_function(ctx, name, &evaluated_args) {
                    return Ok(result);
                }
            }
            // UPSTREAM-PARITY (xpath.c xmlXPathCompFunction): an unknown
            // function reports "Unregistered function: name"; when the name
            // carries a prefix whose namespace was never declared, the error
            // is "Undefined namespace prefix: prefix" instead (both are
            // XPATH_UNKNOWN_FUNC / XPATH_UNDEF_PREFIX_ERROR, delivered as
            // "XPath error : ...").
            let msg = match name.split_once(':') {
                Some((prefix, _)) if !ctx.namespaces.contains_key(prefix) => {
                    format!("Undefined namespace prefix: {}", prefix)
                }
                _ => format!("Unregistered function: {}", name),
            };
            Err(msg)
        }
    }
}

/// Invoke a C-registered XPath extension function through the upstream
/// parser-context protocol.
///
/// UPSTREAM-PARITY (xpath.c `xmlXPathFunctionCall` / `xmlXPathCompFunction`):
/// the function-lookup callback (`xmlXPathFuncLookupFunc`) is called with a
/// NUL-terminated name; when it returns a function pointer, the candidate
/// builds a fresh `xmlXPathParserContext`, sets `ctxt->function` to the
/// function name (the invoker reads it), pushes the evaluated arguments in
/// REVERSE order (so the first argument is on top — the function pops them in
/// order), calls `func(pc, argc)`, and pops the result. Returns `None` when
/// the callback is absent, returns NULL, or the C context is unavailable.
///
/// # Safety
///
/// - `ctx.func_lookup_func` / `ctx.func_lookup_data` come from
///   `xmlXPathRegisterFuncLookup`; `ctx.c_context` must be the owning
///   `_xmlXPathContext`.
fn invoke_c_extension_function(
    ctx: &mut XPathContext,
    name: &str,
    args: &[XPathValue],
) -> Option<XPathValue> {
    let lookup = ctx.func_lookup_func?;
    let c_ctxt = ctx.c_context;
    if c_ctxt.is_null() {
        return None;
    }

    // UPSTREAM-PARITY (xpath.c xmlXPathCompFunction): the lookup callback
    // receives the LOCAL name and the prefix's RESOLVED namespace URI, not
    // the raw `prefix:local` token — xslt's xsltXPathFunctionLookup and
    // php's php:function registration (module table keyed by
    // {http://php.net/xsl}function) match on that. When the prefix is not
    // declared the raw name + NULL URI are passed (consumers that key on
    // the raw token, e.g. nokogiri's per-context lookup, keep working).
    let (lookup_name, lookup_uri): (Vec<u8>, Option<Vec<u8>>) = match name.split_once(':') {
        Some((prefix, local)) => match ctx.namespaces.get(prefix) {
            Some(uri) => (local.as_bytes().to_vec(), Some(uri.as_bytes().to_vec())),
            None => (name.as_bytes().to_vec(), None),
        },
        None => (name.as_bytes().to_vec(), None),
    };
    let mut lookup_name_nul: Vec<crate::abi::types::xmlChar> = lookup_name.clone();
    lookup_name_nul.push(0);
    let lookup_uri_nul: Option<Vec<crate::abi::types::xmlChar>> = lookup_uri.as_ref().map(|u| {
        let mut v = u.clone();
        v.push(0);
        v
    });
    // SAFETY: the callback contract returns an xmlXPathFunction (fn pointer)
    // stored as void*, or NULL when the handler does not provide the name.
    let fp = unsafe {
        lookup(
            ctx.func_lookup_data,
            lookup_name_nul.as_ptr() as *const crate::abi::types::xmlChar,
            lookup_uri_nul.as_ref().map_or(std::ptr::null(), |v| {
                v.as_ptr() as *const crate::abi::types::xmlChar
            }),
        )
    };
    if fp.is_null() {
        return None;
    }
    let func: unsafe extern "C" fn(*mut c_void, c_int) = unsafe { std::mem::transmute(fp) };

    unsafe {
        let saved_function = (*c_ctxt).function;
        (*c_ctxt).function = lookup_name_nul.as_ptr() as *const crate::abi::types::xmlChar;
        let pc = new_parser_context(std::ptr::null(), c_ctxt);
        if pc.is_null() {
            (*c_ctxt).function = saved_function;
            return None;
        }

        // Push the evaluated arguments in reverse order (upstream
        // xmlXPathFunctionCall evaluates and pushes args from the last to the
        // first, so the first argument sits on top of the stack).
        let mut ok = true;
        for val in args.iter().rev() {
            let obj = crate::abi::exports_xml2::xpath_to_object_pub(val.clone());
            if obj.is_null() {
                ok = false;
                break;
            }
            value_push(pc, obj);
        }

        let result = if ok {
            func(pc as *mut c_void, args.len() as c_int);
            let res = value_pop(pc);
            if res.is_null() {
                None
            } else {
                let val = crate::abi::exports_xml2::object_to_xpathvalue_pub(res);
                crate::abi::exports_xml2::xmlXPathFreeObject(res);
                Some(val)
            }
        } else {
            None
        };

        // free_parser_context frees any remaining stack values and the
        // context itself; the popped result was already freed above.
        free_parser_context(pc);
        (*c_ctxt).function = saved_function;
        result
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Operators
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluate a binary operation.
fn eval_binary_op(
    ctx: &mut XPathContext,
    op: &BinaryOp,
    left: &Expr,
    right: &Expr,
) -> Result<XPathValue, String> {
    match op {
        BinaryOp::Or => {
            // Short-circuit: evaluate left, if true return true
            let left_val = eval(ctx, left)?;
            if left_val.as_boolean() {
                return Ok(XPathValue::Boolean(true));
            }
            let right_val = eval(ctx, right)?;
            Ok(XPathValue::Boolean(right_val.as_boolean()))
        }
        BinaryOp::And => {
            // Short-circuit: evaluate left, if false return false
            let left_val = eval(ctx, left)?;
            if !left_val.as_boolean() {
                return Ok(XPathValue::Boolean(false));
            }
            let right_val = eval(ctx, right)?;
            Ok(XPathValue::Boolean(right_val.as_boolean()))
        }
        BinaryOp::Eq | BinaryOp::Ne => {
            let left_val = eval(ctx, left)?;
            let right_val = eval(ctx, right)?;
            let eq = compare_equal(ctx, &left_val, &right_val);
            Ok(match op {
                BinaryOp::Eq => XPathValue::Boolean(eq),
                BinaryOp::Ne => XPathValue::Boolean(!eq),
                _ => unreachable!(),
            })
        }
        BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge => {
            let left_val = eval(ctx, left)?;
            let right_val = eval(ctx, right)?;
            let cmp = compare_ordered(ctx, &left_val, &right_val);
            let result = match op {
                BinaryOp::Lt => cmp == std::cmp::Ordering::Less,
                BinaryOp::Gt => cmp == std::cmp::Ordering::Greater,
                BinaryOp::Le => cmp != std::cmp::Ordering::Greater,
                BinaryOp::Ge => cmp != std::cmp::Ordering::Less,
                _ => unreachable!(),
            };
            Ok(XPathValue::Boolean(result))
        }
        BinaryOp::Add => {
            let left_val = eval(ctx, left)?;
            let right_val = eval(ctx, right)?;
            Ok(XPathValue::Number(
                left_val.as_number() + right_val.as_number(),
            ))
        }
        BinaryOp::Sub => {
            let left_val = eval(ctx, left)?;
            let right_val = eval(ctx, right)?;
            Ok(XPathValue::Number(
                left_val.as_number() - right_val.as_number(),
            ))
        }
        BinaryOp::Mul => {
            let left_val = eval(ctx, left)?;
            let right_val = eval(ctx, right)?;
            Ok(XPathValue::Number(
                left_val.as_number() * right_val.as_number(),
            ))
        }
        BinaryOp::Div => {
            let left_val = eval(ctx, left)?;
            let right_val = eval(ctx, right)?;
            Ok(XPathValue::Number(
                left_val.as_number() / right_val.as_number(),
            ))
        }
        BinaryOp::Mod => {
            let left_val = eval(ctx, left)?;
            let right_val = eval(ctx, right)?;
            Ok(XPathValue::Number(
                left_val.as_number() % right_val.as_number(),
            ))
        }
        BinaryOp::Union => {
            // Union is handled at the Expr level, not BinaryOp level
            unreachable!("Union operator should be handled by Expr::Union")
        }
    }
}

/// Evaluate a union expression: `left | right`.
fn eval_union(ctx: &mut XPathContext, left: &Expr, right: &Expr) -> Result<XPathValue, String> {
    // UPSTREAM-PARITY (xpath.c xmlXPathUnionExpr): a union of non-node-sets
    // (e.g. `1 | 2`) is XPATH_INVALID_TYPE — "XPath error : Invalid type" —
    // not a panic (Phase 16 ASan fuzz finding).
    let left_val = eval(ctx, left)?;
    let right_val = eval(ctx, right)?;
    let mut result = match left_val {
        XPathValue::NodeSet(ns) => ns,
        _ => return Err("Invalid type".to_string()),
    };
    match right_val {
        XPathValue::NodeSet(ns) => {
            result.extend(&ns);
        }
        _ => return Err("Invalid type".to_string()),
    }
    result.sort();

    Ok(XPathValue::NodeSet(result))
}

// ═══════════════════════════════════════════════════════════════════════════════
// Comparison Semantics
// ═══════════════════════════════════════════════════════════════════════════════

/// Compare two XPath values for equality (XPath 1.0 §3.4).
fn compare_equal(_ctx: &mut XPathContext, a: &XPathValue, b: &XPathValue) -> bool {
    match (a, b) {
        // If both are node-sets, compare by set intersection
        (XPathValue::NodeSet(ns_a), XPathValue::NodeSet(ns_b)) => {
            for node_a in ns_a.iter() {
                let val_a = node_string_value(node_a);
                for node_b in ns_b.iter() {
                    let val_b = node_string_value(node_b);
                    if val_a == val_b {
                        return true;
                    }
                }
            }
            false
        }
        // If one is a node-set and the other is not
        (XPathValue::NodeSet(ns), other) | (other, XPathValue::NodeSet(ns)) => {
            for node in ns.iter() {
                let node_str = node_string_value(node);
                match other {
                    XPathValue::Boolean(_) => {
                        // Compare boolean(node-set) == other
                        return (!ns.is_empty()) == other.as_boolean();
                    }
                    XPathValue::Number(_) => {
                        let node_num = string_to_number(&node_str);
                        if (node_num - other.as_number()).abs() < f64::EPSILON {
                            return true;
                        }
                        continue;
                    }
                    XPathValue::String(_) => {
                        if node_str == other.as_string() {
                            return true;
                        }
                        continue;
                    }
                    _ => continue,
                };
            }
            false
        }
        // Neither is a node-set
        _ => match (a, b) {
            (XPathValue::Boolean(_), _) | (_, XPathValue::Boolean(_)) => {
                a.as_boolean() == b.as_boolean()
            }
            (XPathValue::Number(_), _) | (_, XPathValue::Number(_)) => {
                let na = a.as_number();
                let nb = b.as_number();
                if na.is_nan() || nb.is_nan() {
                    false
                } else {
                    (na - nb).abs() < f64::EPSILON || na == nb
                }
            }
            _ => a.as_string() == b.as_string(),
        },
    }
}

/// Compare two XPath values for ordering (XPath 1.0 §3.4).
fn compare_ordered(_ctx: &mut XPathContext, a: &XPathValue, b: &XPathValue) -> std::cmp::Ordering {
    match (a, b) {
        // If both are node-sets, compare pairwise
        (XPathValue::NodeSet(ns_a), XPathValue::NodeSet(ns_b)) => {
            for node_a in ns_a.iter() {
                let num_a = string_to_number(&node_string_value(node_a));
                for node_b in ns_b.iter() {
                    let num_b = string_to_number(&node_string_value(node_b));
                    if num_a < num_b {
                        return std::cmp::Ordering::Less;
                    }
                    if num_a > num_b {
                        return std::cmp::Ordering::Greater;
                    }
                }
            }
            std::cmp::Ordering::Equal
        }
        // If one is a node-set
        (XPathValue::NodeSet(ns), other) | (other, XPathValue::NodeSet(ns)) => {
            let other_num = other.as_number();
            for node in ns.iter() {
                let node_num = string_to_number(&node_string_value(node));
                if node_num < other_num {
                    return std::cmp::Ordering::Less;
                }
                if node_num > other_num {
                    return std::cmp::Ordering::Greater;
                }
            }
            std::cmp::Ordering::Equal
        }
        // Neither is a node-set: compare as numbers
        _ => {
            let na = a.as_number();
            let nb = b.as_number();
            if na.is_nan() || nb.is_nan() {
                std::cmp::Ordering::Equal // NaN comparisons return false, so equal for ordering
            } else if na < nb {
                std::cmp::Ordering::Less
            } else if na > nb {
                std::cmp::Ordering::Greater
            } else {
                std::cmp::Ordering::Equal
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Top-level evaluation API
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluate an XPath expression string against a document.
///
/// This is the main entry point for XPath evaluation.
pub fn eval_xpath(ctx: &mut XPathContext, expression: &str) -> Result<XPathValue, String> {
    let expr = crate::xml::xpath::parser::parse_xpath(expression).map_err(|e| e.message)?;
    eval(ctx, &expr)
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::xml::xpath::context::XPathContext;
    use crate::xml::xpath::functions;

    fn setup_context() -> XPathContext {
        let mut ctx = XPathContext::new(std::ptr::null_mut());
        // Register core functions
        let funcs = functions::core_functions();
        for (name, func) in funcs {
            ctx.register_function(&name, func);
        }
        ctx
    }

    #[test]
    fn test_eval_string_literal() {
        let mut ctx = setup_context();
        let result = eval_xpath(&mut ctx, "'hello'").unwrap();
        assert_eq!(result.as_string(), "hello");
    }

    #[test]
    fn test_eval_number_literal() {
        let mut ctx = setup_context();
        let result = eval_xpath(&mut ctx, "42").unwrap();
        assert_eq!(result.as_number(), 42.0);
    }

    #[test]
    fn test_eval_addition() {
        let mut ctx = setup_context();
        let result = eval_xpath(&mut ctx, "1 + 2").unwrap();
        assert_eq!(result.as_number(), 3.0);
    }

    #[test]
    fn test_eval_subtraction() {
        let mut ctx = setup_context();
        let result = eval_xpath(&mut ctx, "5 - 3").unwrap();
        assert_eq!(result.as_number(), 2.0);
    }

    #[test]
    fn test_eval_multiplication() {
        let mut ctx = setup_context();
        let result = eval_xpath(&mut ctx, "3 * 4").unwrap();
        assert_eq!(result.as_number(), 12.0);
    }

    #[test]
    fn test_eval_division() {
        let mut ctx = setup_context();
        let result = eval_xpath(&mut ctx, "10 div 3").unwrap();
        assert!((result.as_number() - 3.3333333333333335).abs() < 1e-10);
    }

    #[test]
    fn test_eval_modulo() {
        let mut ctx = setup_context();
        let result = eval_xpath(&mut ctx, "10 mod 3").unwrap();
        assert_eq!(result.as_number(), 1.0);
    }

    #[test]
    fn test_eval_equality() {
        let mut ctx = setup_context();
        assert!(eval_xpath(&mut ctx, "1 = 1").unwrap().as_boolean());
        assert!(!eval_xpath(&mut ctx, "1 = 2").unwrap().as_boolean());
        assert!(eval_xpath(&mut ctx, "1 != 2").unwrap().as_boolean());
    }

    #[test]
    fn test_eval_comparison() {
        let mut ctx = setup_context();
        assert!(eval_xpath(&mut ctx, "1 < 2").unwrap().as_boolean());
        assert!(eval_xpath(&mut ctx, "2 > 1").unwrap().as_boolean());
        assert!(eval_xpath(&mut ctx, "1 <= 1").unwrap().as_boolean());
        assert!(eval_xpath(&mut ctx, "2 >= 2").unwrap().as_boolean());
    }

    #[test]
    fn test_eval_and_or() {
        let mut ctx = setup_context();
        assert!(eval_xpath(&mut ctx, "true() and true()")
            .unwrap()
            .as_boolean());
        assert!(!eval_xpath(&mut ctx, "true() and false()")
            .unwrap()
            .as_boolean());
        assert!(eval_xpath(&mut ctx, "true() or false()")
            .unwrap()
            .as_boolean());
        assert!(!eval_xpath(&mut ctx, "false() or false()")
            .unwrap()
            .as_boolean());
    }

    #[test]
    fn test_eval_not() {
        let mut ctx = setup_context();
        assert!(!eval_xpath(&mut ctx, "not(true())").unwrap().as_boolean());
        assert!(eval_xpath(&mut ctx, "not(false())").unwrap().as_boolean());
    }

    #[test]
    fn test_eval_boolean() {
        let mut ctx = setup_context();
        assert!(eval_xpath(&mut ctx, "boolean('hello')")
            .unwrap()
            .as_boolean());
        assert!(!eval_xpath(&mut ctx, "boolean('')").unwrap().as_boolean());
        assert!(!eval_xpath(&mut ctx, "boolean(0)").unwrap().as_boolean());
        assert!(eval_xpath(&mut ctx, "boolean(1)").unwrap().as_boolean());
    }

    #[test]
    fn test_eval_number() {
        let mut ctx = setup_context();
        assert_eq!(
            eval_xpath(&mut ctx, "number('42')").unwrap().as_number(),
            42.0
        );
    }

    #[test]
    fn test_eval_string() {
        let mut ctx = setup_context();
        assert_eq!(
            eval_xpath(&mut ctx, "string(42)").unwrap().as_string(),
            "42"
        );
    }

    #[test]
    fn test_eval_concat() {
        let mut ctx = setup_context();
        assert_eq!(
            eval_xpath(&mut ctx, "concat('a', 'b', 'c')")
                .unwrap()
                .as_string(),
            "abc"
        );
    }

    #[test]
    fn test_eval_starts_with() {
        let mut ctx = setup_context();
        assert!(eval_xpath(&mut ctx, "starts-with('hello', 'he')")
            .unwrap()
            .as_boolean());
    }

    #[test]
    fn test_eval_contains() {
        let mut ctx = setup_context();
        assert!(eval_xpath(&mut ctx, "contains('hello', 'ell')")
            .unwrap()
            .as_boolean());
    }

    #[test]
    fn test_eval_substring() {
        let mut ctx = setup_context();
        assert_eq!(
            eval_xpath(&mut ctx, "substring('12345', 1, 3)")
                .unwrap()
                .as_string(),
            "123"
        );
        assert_eq!(
            eval_xpath(&mut ctx, "substring('12345', 2)")
                .unwrap()
                .as_string(),
            "2345"
        );
    }

    #[test]
    fn test_eval_string_length() {
        let mut ctx = setup_context();
        assert_eq!(
            eval_xpath(&mut ctx, "string-length('hello')")
                .unwrap()
                .as_number(),
            5.0
        );
    }

    #[test]
    fn test_eval_normalize_space() {
        let mut ctx = setup_context();
        assert_eq!(
            eval_xpath(&mut ctx, "normalize-space('  hello   world  ')")
                .unwrap()
                .as_string(),
            "hello world"
        );
    }

    #[test]
    fn test_eval_floor_ceiling_round() {
        let mut ctx = setup_context();
        assert_eq!(eval_xpath(&mut ctx, "floor(3.7)").unwrap().as_number(), 3.0);
        assert_eq!(
            eval_xpath(&mut ctx, "ceiling(3.2)").unwrap().as_number(),
            4.0
        );
        assert_eq!(eval_xpath(&mut ctx, "round(3.5)").unwrap().as_number(), 4.0);
    }

    #[test]
    fn test_eval_sum() {
        // sum() on an empty node-set should return 0
        let mut ctx = setup_context();
        ctx.document = std::ptr::null_mut();
        // Can't test sum directly without a node-set, but we can test it
        // with literal values when we add node-set construction
    }

    #[test]
    fn test_eval_variable_not_found() {
        let mut ctx = setup_context();
        let result = eval_xpath(&mut ctx, "$undefined_var");
        assert!(result.is_err());
    }

    #[test]
    fn test_eval_variable_found() {
        let mut ctx = setup_context();
        ctx.register_variable("x", XPathValue::Number(42.0));
        let result = eval_xpath(&mut ctx, "$x").unwrap();
        assert_eq!(result.as_number(), 42.0);
    }

    #[test]
    fn test_eval_union() {
        // Union requires node-sets, which need a document.
        // Test basic union of numbers (should error since numbers aren't node-sets).
        // Actually, union on non-node-sets would panic at as_node_set().
        // For now, this is a placeholder for when we have document support.
    }

    #[test]
    fn test_eval_operator_precedence() {
        let mut ctx = setup_context();
        // 1 + 2 * 3 should be 7 (multiplication before addition)
        let result = eval_xpath(&mut ctx, "1 + 2 * 3").unwrap();
        assert_eq!(result.as_number(), 7.0);

        // (1 + 2) * 3 should be 9
        let result = eval_xpath(&mut ctx, "(1 + 2) * 3").unwrap();
        assert_eq!(result.as_number(), 9.0);
    }

    #[test]
    fn test_eval_unary_minus() {
        let mut ctx = setup_context();
        let result = eval_xpath(&mut ctx, "-5").unwrap();
        assert_eq!(result.as_number(), -5.0);

        let result = eval_xpath(&mut ctx, "--5").unwrap();
        assert_eq!(result.as_number(), 5.0);
    }

    #[test]
    fn test_eval_true_false() {
        let mut ctx = setup_context();
        assert!(eval_xpath(&mut ctx, "true()").unwrap().as_boolean());
        assert!(!eval_xpath(&mut ctx, "false()").unwrap().as_boolean());
    }

    #[test]
    fn test_eval_translate() {
        let mut ctx = setup_context();
        assert_eq!(
            eval_xpath(
                &mut ctx,
                "translate('hello', 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')"
            )
            .unwrap()
            .as_string(),
            "HELLO"
        );
    }

    #[test]
    fn test_eval_empty_expression() {
        let mut ctx = setup_context();
        let result = eval_xpath(&mut ctx, "");
        assert!(result.is_err());
    }
}