xsd-schema 0.1.0

XML Schema (XSD 1.0/1.1) validator with PSVI and a built-in XPath 2.0 engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//! High-level, ergonomic XPath evaluation API.
//!
//! This module provides a user-friendly interface for compiling and evaluating
//! XPath expressions with Rust-idiomatic patterns:
//!
//! - **Separation of compilation and execution**: Compile once, evaluate many times
//! - **Builder pattern**: Fluent API for setting variables and options
//! - **`From` traits**: Ergonomic value conversion (use `42` instead of `XPathValue::integer(42)`)
//! - **No lifetimes in compiled expressions**: Store `XPathExpr` anywhere
//!
//! # Example
//!
//! ```no_run
//! use xsd_schema::xpath::api::{XPathExpr, EvalValue};
//! use xsd_schema::xpath::{XPathContext, RoXmlNavigator};
//! use xsd_schema::namespace::table::NameTable;
//!
//! // Setup context
//! let names = NameTable::new();
//! let ctx = XPathContext::new(&names);
//!
//! // Compile once with external variables
//! let expr = XPathExpr::compile_with_vars("$x + $y", &ctx, &["x", "y"]).unwrap();
//!
//! // Evaluate with fluent builder
//! let result = expr.evaluator(&ctx)
//!     .with_variable("x", 10).unwrap()
//!     .with_variable("y", 32).unwrap()
//!     .run::<RoXmlNavigator<'static>>().unwrap();
//!
//! // Convenience methods for common return types
//! let sum = expr.evaluator(&ctx)
//!     .with_variable("x", 20).unwrap()
//!     .with_variable("y", 22).unwrap()
//!     .run_number::<RoXmlNavigator<'static>>().unwrap();
//! assert_eq!(sum, 42.0);
//! ```

use num_bigint::BigInt;

use crate::namespace::qname::QualifiedName;

use super::arena::{AstArena, AstNodeId, SourceSpan};
use super::bind::bind_node;
use super::context::{DynamicContext, NameBinder, VarSlotId, XPathContext};
use super::error::XPathError;
use super::eval::eval_node;
use super::functions::{effective_boolean_value, XPathValue};
use super::iterator::XmlItem;
use super::parser::{parse, parse_with_mode};
use super::DomNavigator;

// ============================================================================
// ExternalVar - Information about a declared external variable
// ============================================================================

/// Information about an external variable declared at compile time.
///
/// External variables are those declared by the user (via `compile_with_vars`)
/// as opposed to variables introduced by the expression itself (like `for $x in ...`).
#[derive(Debug, Clone)]
pub struct ExternalVar {
    /// The qualified name of the variable
    pub name: QualifiedName,
    /// The slot ID for storing the variable's value
    pub slot: VarSlotId,
}

// ============================================================================
// XPathExpr - Compiled XPath expression (owns its AST)
// ============================================================================

/// A compiled XPath expression that can be evaluated multiple times.
///
/// `XPathExpr` owns its AST and contains no lifetimes, so it can be stored
/// in structs, sent across threads (if using appropriate synchronization),
/// or cached for repeated evaluation.
///
/// # Compilation vs Evaluation
///
/// Compilation (`compile()` or `compile_with_vars()`) parses and binds the expression,
/// resolving function names, variable slots, and namespace prefixes. This is the
/// expensive step.
///
/// Evaluation (`evaluator().run()`) executes the compiled AST, which is much faster.
/// You can evaluate the same compiled expression many times with different variable
/// values or context nodes.
///
/// # External Variables
///
/// Use `compile_with_vars()` to declare variables that will be provided at evaluation time:
///
/// ```no_run
/// # use xsd_schema::xpath::api::XPathExpr;
/// # use xsd_schema::xpath::XPathContext;
/// # use xsd_schema::namespace::table::NameTable;
/// let names = NameTable::new();
/// let ctx = XPathContext::new(&names);
///
/// // Declare $x and $y as external variables
/// let expr = XPathExpr::compile_with_vars("$x + $y", &ctx, &["x", "y"]).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct XPathExpr {
    /// Original source expression
    source: String,
    /// The AST arena containing all nodes
    arena: AstArena,
    /// Root node ID of the expression
    root: AstNodeId,
    /// Source span of the entire expression
    span: SourceSpan,
    /// Total number of variable slots needed
    var_slots: usize,
    /// External variables declared at compile time
    external_vars: Vec<ExternalVar>,
}

impl XPathExpr {
    /// Compile an XPath expression without external variables.
    ///
    /// Use this when your expression doesn't reference any variables, or when
    /// all variables are provided by the expression itself (e.g., `for $x in 1 to 10`).
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The expression has syntax errors
    /// - A function is not found
    /// - A variable is referenced but not defined
    /// - A namespace prefix is not bound
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use xsd_schema::xpath::api::XPathExpr;
    /// # use xsd_schema::xpath::XPathContext;
    /// # use xsd_schema::namespace::table::NameTable;
    /// let names = NameTable::new();
    /// let ctx = XPathContext::new(&names);
    /// let expr = XPathExpr::compile("1 + 2 * 3", &ctx).unwrap();
    /// ```
    pub fn compile(expr: &str, ctx: &XPathContext<'_>) -> Result<Self, XPathError> {
        Self::compile_with_vars(expr, ctx, &[])
    }

    /// Compile an XPath expression with declared external variables.
    ///
    /// External variables must be provided at evaluation time via `with_variable()`.
    /// Variable names should be provided without the `$` prefix.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The expression has syntax errors
    /// - A function is not found
    /// - A variable is referenced that wasn't declared
    /// - A namespace prefix is not bound
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use xsd_schema::xpath::api::XPathExpr;
    /// # use xsd_schema::xpath::XPathContext;
    /// # use xsd_schema::namespace::table::NameTable;
    /// let names = NameTable::new();
    /// let ctx = XPathContext::new(&names);
    ///
    /// // Compile expression that uses $x and $y
    /// let expr = XPathExpr::compile_with_vars("$x + $y", &ctx, &["x", "y"]).unwrap();
    /// ```
    pub fn compile_with_vars(
        expr: &str,
        ctx: &XPathContext<'_>,
        vars: &[&str],
    ) -> Result<Self, XPathError> {
        // Parse the expression using the mode from context (ParseError → XPathError via From)
        let parsed = if ctx.mode() == super::XPathMode::XPath20 {
            parse(expr)?
        } else {
            parse_with_mode(expr, ctx.mode())?
        };

        let mut arena = parsed.arena;
        let root = parsed.root;
        let span = parsed.span;

        // Create name binder and push external variables
        let mut binder = NameBinder::new();
        let mut external_vars = Vec::with_capacity(vars.len());

        for var_name in vars {
            // Parse variable name - support both "local" and "prefix:local" formats
            let qname = parse_variable_name(var_name, ctx)?;

            // Check for duplicate variable declarations
            if external_vars.iter().any(|v: &ExternalVar| v.name == qname) {
                return Err(XPathError::XPST0003 {
                    message: format!("Duplicate external variable declaration: ${}", var_name),
                });
            }

            let var_ref = binder.push_var(qname.clone());
            external_vars.push(ExternalVar {
                name: qname,
                slot: var_ref.slot,
            });
        }

        // Mark boundary between external vars and expression-internal vars
        binder.mark_external_boundary();

        // Bind the expression (resolves functions, variables, namespaces)
        bind_node(&mut arena, root, ctx, &mut binder)?;

        let var_slots = binder.len();

        Ok(Self {
            source: expr.to_string(),
            arena,
            root,
            span,
            var_slots,
            external_vars,
        })
    }

    /// Get the original source expression.
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Get the source span of the expression.
    pub fn span(&self) -> SourceSpan {
        self.span
    }

    /// Get the external variables declared for this expression.
    pub fn external_vars(&self) -> &[ExternalVar] {
        &self.external_vars
    }

    /// Borrow the bound AST arena of this expression.
    ///
    /// Useful for callers that want to inspect the compiled tree
    /// (e.g. CTA schema-time validation walking type expressions).
    pub fn arena(&self) -> &AstArena {
        &self.arena
    }

    /// Create an evaluator for this expression.
    ///
    /// The evaluator uses a builder pattern to set variables and other options
    /// before running the expression.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use xsd_schema::xpath::api::XPathExpr;
    /// # use xsd_schema::xpath::{XPathContext, RoXmlNavigator};
    /// # use xsd_schema::namespace::table::NameTable;
    /// let names = NameTable::new();
    /// let ctx = XPathContext::new(&names);
    /// let expr = XPathExpr::compile_with_vars("$x * 2", &ctx, &["x"]).unwrap();
    ///
    /// let result = expr.evaluator(&ctx)
    ///     .with_variable("x", 21).unwrap()
    ///     .run_number::<RoXmlNavigator<'static>>().unwrap();
    /// assert_eq!(result, 42.0);
    /// ```
    pub fn evaluator<'a, 'ctx>(
        &'a self,
        ctx: &'ctx XPathContext<'ctx>,
    ) -> XPathEvaluator<'a, 'ctx> {
        XPathEvaluator::new(self, ctx)
    }
}

// ============================================================================
// EvalValue - Ergonomic value type for variable binding
// ============================================================================

/// A value that can be bound to an XPath variable at evaluation time.
///
/// This enum provides ergonomic conversion from Rust types to XPath values
/// via the `From` trait implementations. You can use Rust literals directly:
///
/// ```no_run
/// # use xsd_schema::xpath::api::{XPathExpr, EvalValue};
/// # use xsd_schema::xpath::XPathContext;
/// # use xsd_schema::namespace::table::NameTable;
/// # let names = NameTable::new();
/// # let ctx = XPathContext::new(&names);
/// # let expr = XPathExpr::compile_with_vars("$x", &ctx, &["x"]).unwrap();
/// // All of these work:
/// expr.evaluator(&ctx).with_variable("x", 42);          // i32 -> Integer
/// expr.evaluator(&ctx).with_variable("x", 3.14);        // f64 -> Double
/// expr.evaluator(&ctx).with_variable("x", true);        // bool -> Bool
/// expr.evaluator(&ctx).with_variable("x", "hello");     // &str -> String
/// ```
#[derive(Debug, Clone)]
pub enum EvalValue {
    /// Boolean value
    Bool(bool),
    /// Small integer (converted to BigInt internally)
    Integer(i64),
    /// Big integer
    BigInteger(BigInt),
    /// Double-precision floating point
    Double(f64),
    /// String value
    String(String),
}

impl From<bool> for EvalValue {
    fn from(b: bool) -> Self {
        EvalValue::Bool(b)
    }
}

impl From<i32> for EvalValue {
    fn from(i: i32) -> Self {
        EvalValue::Integer(i as i64)
    }
}

impl From<i64> for EvalValue {
    fn from(i: i64) -> Self {
        EvalValue::Integer(i)
    }
}

impl From<f32> for EvalValue {
    fn from(f: f32) -> Self {
        EvalValue::Double(f as f64)
    }
}

impl From<f64> for EvalValue {
    fn from(f: f64) -> Self {
        EvalValue::Double(f)
    }
}

impl From<String> for EvalValue {
    fn from(s: String) -> Self {
        EvalValue::String(s)
    }
}

impl From<&str> for EvalValue {
    fn from(s: &str) -> Self {
        EvalValue::String(s.to_string())
    }
}

impl From<BigInt> for EvalValue {
    fn from(i: BigInt) -> Self {
        EvalValue::BigInteger(i)
    }
}

// ============================================================================
// PendingValue - Internal type for deferred XPathValue construction
// ============================================================================

/// Internal representation of a value waiting to be converted to XPathValue<N>.
///
/// Since XPathValue is generic over the navigator type N, and we don't know N
/// until `run()` is called, we store values in this intermediate form.
#[derive(Debug, Clone)]
enum PendingValue {
    Bool(bool),
    Integer(i64),
    BigInteger(BigInt),
    Double(f64),
    String(String),
}

impl PendingValue {
    /// Convert this pending value to an XPathValue for the given navigator type.
    fn into_xpath_value<N: DomNavigator>(self) -> XPathValue<N> {
        match self {
            PendingValue::Bool(b) => XPathValue::boolean(b),
            PendingValue::Integer(i) => XPathValue::integer(BigInt::from(i)),
            PendingValue::BigInteger(i) => XPathValue::integer(i),
            PendingValue::Double(d) => XPathValue::double(d),
            PendingValue::String(s) => XPathValue::string(s),
        }
    }
}

impl From<EvalValue> for PendingValue {
    fn from(v: EvalValue) -> Self {
        match v {
            EvalValue::Bool(b) => PendingValue::Bool(b),
            EvalValue::Integer(i) => PendingValue::Integer(i),
            EvalValue::BigInteger(i) => PendingValue::BigInteger(i),
            EvalValue::Double(d) => PendingValue::Double(d),
            EvalValue::String(s) => PendingValue::String(s),
        }
    }
}

// ============================================================================
// XPathEvaluator - Builder for expression evaluation
// ============================================================================

/// Builder for evaluating a compiled XPath expression.
///
/// Use this to set variables, context nodes, and other evaluation options
/// before running the expression. The builder pattern allows fluent API usage:
///
/// ```no_run
/// # use xsd_schema::xpath::api::XPathExpr;
/// # use xsd_schema::xpath::{XPathContext, RoXmlNavigator};
/// # use xsd_schema::namespace::table::NameTable;
/// # let names = NameTable::new();
/// # let ctx = XPathContext::new(&names);
/// # let expr = XPathExpr::compile_with_vars("$x + $y", &ctx, &["x", "y"]).unwrap();
/// let result = expr.evaluator(&ctx)
///     .with_variable("x", 10).unwrap()
///     .with_variable("y", 32).unwrap()
///     .run::<RoXmlNavigator<'static>>().unwrap();
/// ```
pub struct XPathEvaluator<'expr, 'ctx> {
    /// The compiled expression to evaluate
    expr: &'expr XPathExpr,
    /// The static context
    static_ctx: &'ctx XPathContext<'ctx>,
    /// Variables to set before evaluation (slot -> value)
    pending_vars: Vec<(VarSlotId, PendingValue)>,
}

impl<'expr, 'ctx> XPathEvaluator<'expr, 'ctx> {
    /// Create a new evaluator for the given expression and context.
    fn new(expr: &'expr XPathExpr, static_ctx: &'ctx XPathContext<'ctx>) -> Self {
        Self {
            expr,
            static_ctx,
            pending_vars: Vec::new(),
        }
    }

    /// Set an external variable's value.
    ///
    /// The variable must have been declared when compiling the expression
    /// (via `compile_with_vars()`). Variable names should not include the `$` prefix.
    ///
    /// # Errors
    ///
    /// Returns `XPST0008` if the variable was not declared at compile time.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use xsd_schema::xpath::api::XPathExpr;
    /// # use xsd_schema::xpath::XPathContext;
    /// # use xsd_schema::namespace::table::NameTable;
    /// # let names = NameTable::new();
    /// # let ctx = XPathContext::new(&names);
    /// let expr = XPathExpr::compile_with_vars("$price * $qty", &ctx, &["price", "qty"]).unwrap();
    ///
    /// let eval = expr.evaluator(&ctx)
    ///     .with_variable("price", 19.99).unwrap()
    ///     .with_variable("qty", 3).unwrap();
    /// ```
    pub fn with_variable(
        mut self,
        name: &str,
        value: impl Into<EvalValue>,
    ) -> Result<Self, XPathError> {
        let slot = find_external_var(name, &self.expr.external_vars, self.static_ctx)?;
        self.pending_vars.push((slot, value.into().into()));
        Ok(self)
    }

    /// Evaluate the expression and return the full result.
    ///
    /// This is the most flexible method, returning the raw `XPathValue` which
    /// can be empty, a single item, or a sequence.
    ///
    /// # Type Parameter
    ///
    /// - `N`: The navigator type (e.g., `RoXmlNavigator<'doc>`)
    ///
    /// # Errors
    ///
    /// Returns an error if evaluation fails (e.g., type errors, undefined context).
    pub fn run<N: DomNavigator>(self) -> Result<XPathValue<N>, XPathError> {
        self.run_internal(None)
    }

    /// Evaluate the expression with a context node.
    ///
    /// Sets the context item to the given node before evaluation. This is
    /// necessary for expressions that use `.` or axis steps like `child::*`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use xsd_schema::xpath::api::XPathExpr;
    /// # use xsd_schema::xpath::{XPathContext, RoXmlNavigator, DomNavigator};
    /// # use xsd_schema::namespace::table::NameTable;
    /// # let names = NameTable::new();
    /// # let ctx = XPathContext::new(&names);
    /// let expr = XPathExpr::compile("child::item", &ctx).unwrap();
    ///
    /// // Parse some XML and get a navigator
    /// let doc = roxmltree::Document::parse("<root><item/></root>").unwrap();
    /// let mut nav = RoXmlNavigator::new(&doc);
    /// nav.move_to_first_child(); // move to <root>
    ///
    /// let result = expr.evaluator(&ctx)
    ///     .run_with_node(nav).unwrap();
    /// ```
    pub fn run_with_node<N: DomNavigator>(self, node: N) -> Result<XPathValue<N>, XPathError> {
        self.run_internal(Some(node))
    }

    /// Internal evaluation implementation.
    fn run_internal<N: DomNavigator>(
        self,
        context_node: Option<N>,
    ) -> Result<XPathValue<N>, XPathError> {
        // Create dynamic context
        let mut dyn_ctx = DynamicContext::new(self.static_ctx, self.expr.var_slots);

        // Set context node if provided
        if let Some(node) = context_node {
            dyn_ctx = dyn_ctx.with_context_node(node);
        }

        // Set pending variables
        for (slot, pending) in self.pending_vars {
            let value: XPathValue<N> = pending.into_xpath_value();
            dyn_ctx.set_variable(slot, value);
        }

        // Evaluate the expression
        eval_node(&self.expr.arena, self.expr.root, &mut dyn_ctx)
    }

    /// Evaluate and return the result as a boolean.
    ///
    /// Uses the XPath effective boolean value rules:
    /// - Empty sequence → `false`
    /// - Boolean → its value
    /// - String → `false` if empty, `true` otherwise
    /// - Number → `false` if 0 or NaN, `true` otherwise
    /// - Node sequence → `true` if non-empty
    ///
    /// # Errors
    ///
    /// Returns an error if evaluation fails or if effective boolean value
    /// cannot be computed (e.g., sequence of multiple atomic values).
    pub fn run_bool<N: DomNavigator>(self) -> Result<bool, XPathError> {
        let value = self.run::<N>()?;
        effective_boolean_value(&value)
    }

    /// Evaluate and return the result as a string.
    ///
    /// Atomizes the result and converts to string. For sequences, returns
    /// the string value of the first item (or empty string for empty sequence).
    ///
    /// # Errors
    ///
    /// Returns an error if evaluation fails.
    pub fn run_string<N: DomNavigator>(self) -> Result<String, XPathError> {
        let value = self.run::<N>()?;
        Ok(xpath_value_to_string(&value))
    }

    /// Evaluate and return the result as a number (f64).
    ///
    /// Atomizes the result and converts to double. Returns `NaN` for
    /// values that cannot be converted to numbers.
    ///
    /// # Errors
    ///
    /// Returns an error if evaluation fails.
    pub fn run_number<N: DomNavigator>(self) -> Result<f64, XPathError> {
        let value = self.run::<N>()?;
        Ok(xpath_value_to_number(&value))
    }

    /// Evaluate and return the result as a vector of nodes.
    ///
    /// Filters the result to include only nodes, discarding atomic values.
    /// Useful for path expressions that return node sequences.
    ///
    /// # Errors
    ///
    /// Returns an error if evaluation fails.
    pub fn run_nodes<N: DomNavigator>(self) -> Result<Vec<N>, XPathError> {
        let value = self.run::<N>()?;
        let items = value.into_vec();
        let nodes = items
            .into_iter()
            .filter_map(|item| match item {
                XmlItem::Node(n) => Some(n),
                XmlItem::Atomic(_) => None,
            })
            .collect();
        Ok(nodes)
    }

    /// Evaluate with a setup callback for advanced variable binding.
    ///
    /// This method allows binding variables that cannot be represented as `EvalValue`,
    /// such as:
    /// - Node values
    /// - Sequences of items
    /// - Empty sequences
    ///
    /// The setup callback receives a mutable reference to the `DynamicContext`
    /// and can use `set_variable_by_name()` or `context.set_variable()` directly.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use xsd_schema::xpath::api::XPathExpr;
    /// # use xsd_schema::xpath::{XPathContext, RoXmlNavigator, XPathValue};
    /// # use xsd_schema::namespace::table::NameTable;
    /// # let names = NameTable::new();
    /// # let ctx = XPathContext::new(&names);
    /// let expr = XPathExpr::compile_with_vars("count($items)", &ctx, &["items"]).unwrap();
    ///
    /// // Bind a sequence of integers
    /// let result = expr.evaluator(&ctx)
    ///     .run_with::<RoXmlNavigator<'static>, _>(|eval| {
    ///         // Create a sequence value
    ///         let seq = XPathValue::from_sequence(vec![
    ///             xsd_schema::xpath::XmlItem::Atomic(xsd_schema::types::XmlValue::integer(1.into())),
    ///             xsd_schema::xpath::XmlItem::Atomic(xsd_schema::types::XmlValue::integer(2.into())),
    ///             xsd_schema::xpath::XmlItem::Atomic(xsd_schema::types::XmlValue::integer(3.into())),
    ///         ]);
    ///         eval.set_variable_by_name("items", seq).unwrap();
    ///     })
    ///     .unwrap();
    /// ```
    pub fn run_with<N, F>(self, setup: F) -> Result<XPathValue<N>, XPathError>
    where
        N: DomNavigator,
        F: for<'a> FnOnce(&mut TypedEvaluator<'_, '_, 'a, N>),
    {
        self.run_with_node_and_setup(None, setup)
    }

    /// Evaluate with a context node and setup callback for advanced variable binding.
    ///
    /// Combines `run_with_node` and `run_with` functionality.
    pub fn run_with_node_and_setup<N, F>(
        self,
        context_node: Option<N>,
        setup: F,
    ) -> Result<XPathValue<N>, XPathError>
    where
        N: DomNavigator,
        F: for<'a> FnOnce(&mut TypedEvaluator<'_, '_, 'a, N>),
    {
        // Create dynamic context
        let mut dyn_ctx = DynamicContext::new(self.static_ctx, self.expr.var_slots);

        // Set context node if provided
        if let Some(node) = context_node {
            dyn_ctx = dyn_ctx.with_context_node(node);
        }

        // Set pending variables (from with_variable calls)
        for (slot, pending) in self.pending_vars {
            let value: XPathValue<N> = pending.into_xpath_value();
            dyn_ctx.set_variable(slot, value);
        }

        // Create typed evaluator and run setup callback
        {
            let mut typed_eval = TypedEvaluator {
                expr: self.expr,
                static_ctx: self.static_ctx,
                dyn_ctx: &mut dyn_ctx,
            };
            setup(&mut typed_eval);
        } // typed_eval dropped here, releasing the borrow

        // Evaluate the expression
        eval_node(&self.expr.arena, self.expr.root, &mut dyn_ctx)
    }
}

// ============================================================================
// TypedEvaluator - For advanced variable binding with known navigator type
// ============================================================================

/// A typed evaluator that allows binding arbitrary `XPathValue<N>` values.
///
/// This is used within `run_with` callbacks to set variables that cannot be
/// represented as simple `EvalValue` (like nodes or sequences).
pub struct TypedEvaluator<'expr, 'ctx, 'dyn_ctx, N: DomNavigator> {
    expr: &'expr XPathExpr,
    static_ctx: &'ctx XPathContext<'ctx>,
    dyn_ctx: &'dyn_ctx mut DynamicContext<'ctx, N>,
}

impl<'expr, 'ctx, 'dyn_ctx, N: DomNavigator> TypedEvaluator<'expr, 'ctx, 'dyn_ctx, N> {
    /// Set a variable by name to an arbitrary XPath value.
    ///
    /// This allows binding nodes, sequences, empty sequences, or any other
    /// `XPathValue<N>` to an external variable.
    ///
    /// # Errors
    ///
    /// Returns `XPST0008` if the variable was not declared at compile time.
    pub fn set_variable_by_name(
        &mut self,
        name: &str,
        value: XPathValue<N>,
    ) -> Result<(), XPathError> {
        let slot = find_external_var(name, &self.expr.external_vars, self.static_ctx)?;
        self.dyn_ctx.set_variable(slot, value);
        Ok(())
    }

    /// Set a variable by slot ID directly.
    ///
    /// Use this when you already know the slot ID (e.g., from `ExternalVar::slot`).
    pub fn set_variable(&mut self, slot: VarSlotId, value: XPathValue<N>) {
        self.dyn_ctx.set_variable(slot, value);
    }

    /// Get a reference to the dynamic context for advanced manipulation.
    pub fn context(&mut self) -> &mut DynamicContext<'ctx, N> {
        &mut *self.dyn_ctx
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Parse a variable name string into a QualifiedName.
///
/// Supports both simple names ("x") and prefixed names ("prefix:local").
/// The prefix must be bound in the static context.
fn parse_variable_name(name: &str, ctx: &XPathContext<'_>) -> Result<QualifiedName, XPathError> {
    if let Some(colon_pos) = name.find(':') {
        // Prefixed name: "prefix:local"
        let prefix = &name[..colon_pos];
        let local = &name[colon_pos + 1..];

        if prefix.is_empty() || local.is_empty() {
            return Err(XPathError::XPST0003 {
                message: format!("Invalid variable name: '{}'", name),
            });
        }

        let prefix_id = ctx.names.add(prefix);
        let local_id = ctx.names.add(local);

        // Resolve prefix to namespace
        let ns_id = ctx
            .resolve_prefix_id(prefix_id)
            .ok_or_else(|| XPathError::undefined_prefix(prefix))?;

        Ok(QualifiedName::new(Some(ns_id), local_id, Some(prefix_id)))
    } else {
        // Simple name: "x"
        let local_id = ctx.names.add(name);
        Ok(QualifiedName::local(local_id))
    }
}

/// Find an external variable by name, searching from the end to match binder resolution.
///
/// Returns the slot ID if found, or an error if not declared.
fn find_external_var(
    name: &str,
    external_vars: &[ExternalVar],
    ctx: &XPathContext<'_>,
) -> Result<VarSlotId, XPathError> {
    let qname = parse_variable_name(name, ctx)?;

    // Search from the end to match the binder's last-in-first-out resolution
    external_vars
        .iter()
        .rev()
        .find(|v| v.name == qname)
        .map(|v| v.slot)
        .ok_or_else(|| XPathError::XPST0008 {
            qname: format!("${}", name),
        })
}

/// Convert an XPathValue to a string.
fn xpath_value_to_string<N: DomNavigator>(value: &XPathValue<N>) -> String {
    match value {
        XPathValue::Empty => String::new(),
        XPathValue::Item(item) => item_to_string(item),
        XPathValue::Sequence(items) => {
            if let Some(first) = items.first() {
                item_to_string(first)
            } else {
                String::new()
            }
        }
    }
}

/// Convert an XmlItem to a string.
fn item_to_string<N: DomNavigator>(item: &XmlItem<N>) -> String {
    match item {
        XmlItem::Node(nav) => nav.value(),
        XmlItem::Atomic(val) => val.to_string_value(),
    }
}

/// Convert an XPathValue to a number.
fn xpath_value_to_number<N: DomNavigator>(value: &XPathValue<N>) -> f64 {
    match value {
        XPathValue::Empty => f64::NAN,
        XPathValue::Item(item) => item_to_number(item),
        XPathValue::Sequence(items) => {
            if let Some(first) = items.first() {
                item_to_number(first)
            } else {
                f64::NAN
            }
        }
    }
}

/// Convert an XmlItem to a number.
fn item_to_number<N: DomNavigator>(item: &XmlItem<N>) -> f64 {
    match item {
        XmlItem::Node(nav) => nav.value().trim().parse().unwrap_or(f64::NAN),
        XmlItem::Atomic(val) => {
            if let Some(d) = val.as_double() {
                d
            } else if let Some(i) = val.as_integer() {
                // Convert BigInt to f64 (may lose precision for very large numbers)
                i.to_string().parse().unwrap_or(f64::NAN)
            } else {
                // Try string conversion
                val.to_string_value().trim().parse().unwrap_or(f64::NAN)
            }
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::namespace::table::NameTable;
    use crate::xpath::RoXmlNavigator;

    #[test]
    fn test_compile_simple_expression() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile("1 + 2", &ctx);
        assert!(expr.is_ok());

        let expr = expr.unwrap();
        assert_eq!(expr.source(), "1 + 2");
        assert!(expr.external_vars().is_empty());
    }

    #[test]
    fn test_compile_with_variables() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile_with_vars("$x + $y", &ctx, &["x", "y"]);
        assert!(expr.is_ok());

        let expr = expr.unwrap();
        assert_eq!(expr.external_vars().len(), 2);
    }

    #[test]
    fn test_eval_simple_arithmetic() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile("1 + 2", &ctx).unwrap();
        let result = expr
            .evaluator(&ctx)
            .run_number::<RoXmlNavigator<'static>>()
            .unwrap();

        assert_eq!(result, 3.0);
    }

    #[test]
    fn test_eval_with_variable() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile_with_vars("$x + 1", &ctx, &["x"]).unwrap();
        let result = expr
            .evaluator(&ctx)
            .with_variable("x", 41)
            .unwrap()
            .run_number::<RoXmlNavigator<'static>>()
            .unwrap();

        assert_eq!(result, 42.0);
    }

    #[test]
    fn test_eval_with_string_variable() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile_with_vars(
            "concat($greeting, ' ', $name)",
            &ctx,
            &["greeting", "name"],
        )
        .unwrap();
        let result = expr
            .evaluator(&ctx)
            .with_variable("greeting", "Hello")
            .unwrap()
            .with_variable("name", "World")
            .unwrap()
            .run_string::<RoXmlNavigator<'static>>()
            .unwrap();

        assert_eq!(result, "Hello World");
    }

    #[test]
    fn test_eval_run_bool() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile("1 < 2", &ctx).unwrap();
        let result = expr
            .evaluator(&ctx)
            .run_bool::<RoXmlNavigator<'static>>()
            .unwrap();
        assert!(result);

        let expr = XPathExpr::compile("2 < 1", &ctx).unwrap();
        let result = expr
            .evaluator(&ctx)
            .run_bool::<RoXmlNavigator<'static>>()
            .unwrap();
        assert!(!result);
    }

    #[test]
    fn test_eval_run_number() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile("2.5", &ctx).unwrap();
        let result = expr
            .evaluator(&ctx)
            .run_number::<RoXmlNavigator<'static>>()
            .unwrap();
        assert!((result - 2.5).abs() < 0.001);
    }

    #[test]
    fn test_undefined_variable_error() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        // Try to compile expression with undefined variable
        let result = XPathExpr::compile("$x", &ctx);
        assert!(result.is_err());

        if let Err(XPathError::XPST0008 { qname }) = result {
            assert!(qname.contains("x"));
        } else {
            panic!("Expected XPST0008 error");
        }
    }

    #[test]
    fn test_setting_undeclared_variable_error() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        // Compile with only $x declared
        let expr = XPathExpr::compile_with_vars("$x", &ctx, &["x"]).unwrap();

        // Try to set undeclared variable $y
        let result = expr
            .evaluator(&ctx)
            .with_variable("x", 1)
            .unwrap()
            .with_variable("y", 2); // $y was not declared

        assert!(result.is_err());
        if let Err(XPathError::XPST0008 { qname }) = result {
            assert!(qname.contains("y"));
        } else {
            panic!("Expected XPST0008 error");
        }
    }

    #[test]
    fn test_eval_with_context_node() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile("child::item", &ctx).unwrap();

        let doc = roxmltree::Document::parse("<root><item>value</item></root>").unwrap();
        let mut nav = RoXmlNavigator::new(&doc);
        nav.move_to_first_child(); // move to <root>

        let result = expr.evaluator(&ctx).run_with_node(nav).unwrap();
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_expr_is_clone() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr1 = XPathExpr::compile("1 + 2", &ctx).unwrap();
        let expr2 = expr1.clone();

        // Both should evaluate to the same result
        let result1 = expr1
            .evaluator(&ctx)
            .run_number::<RoXmlNavigator<'static>>()
            .unwrap();
        let result2 = expr2
            .evaluator(&ctx)
            .run_number::<RoXmlNavigator<'static>>()
            .unwrap();

        assert_eq!(result1, result2);
    }

    #[test]
    fn test_eval_value_conversions() {
        // Test that all From implementations work
        let _: EvalValue = true.into();
        let _: EvalValue = 42i32.into();
        let _: EvalValue = 42i64.into();
        let _: EvalValue = 2.5f32.into();
        let _: EvalValue = 2.5f64.into();
        let _: EvalValue = "hello".into();
        let _: EvalValue = String::from("hello").into();
        let _: EvalValue = BigInt::from(1000000000000i64).into();
    }

    #[test]
    fn test_multiple_evaluations_same_expr() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile_with_vars("$x * 2", &ctx, &["x"]).unwrap();

        // Evaluate multiple times with different values
        let result1 = expr
            .evaluator(&ctx)
            .with_variable("x", 5)
            .unwrap()
            .run_number::<RoXmlNavigator<'static>>()
            .unwrap();

        let result2 = expr
            .evaluator(&ctx)
            .with_variable("x", 10)
            .unwrap()
            .run_number::<RoXmlNavigator<'static>>()
            .unwrap();

        let result3 = expr
            .evaluator(&ctx)
            .with_variable("x", 21)
            .unwrap()
            .run_number::<RoXmlNavigator<'static>>()
            .unwrap();

        assert_eq!(result1, 10.0);
        assert_eq!(result2, 20.0);
        assert_eq!(result3, 42.0);
    }

    #[test]
    fn test_duplicate_variable_error() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        // Duplicate variable names should cause an error
        let result = XPathExpr::compile_with_vars("$x + $x", &ctx, &["x", "x"]);
        assert!(result.is_err());

        if let Err(XPathError::XPST0003 { message }) = result {
            assert!(message.contains("Duplicate"));
        } else {
            panic!("Expected XPST0003 error for duplicate variable");
        }
    }

    #[test]
    fn test_prefixed_variable() {
        let names = NameTable::new();

        // Create a context with a namespace binding
        let my_ns = names.add("http://example.com/my");
        let my_prefix = names.add("my");

        let mut namespaces = crate::namespace::context::NamespaceContextSnapshot::default();
        namespaces.bindings.push((my_prefix, my_ns));

        let ctx = XPathContext::new(&names).with_namespaces(namespaces);

        // Compile with a prefixed variable
        let expr = XPathExpr::compile_with_vars("$my:value + 1", &ctx, &["my:value"]).unwrap();

        // Set the prefixed variable
        let result = expr
            .evaluator(&ctx)
            .with_variable("my:value", 41)
            .unwrap()
            .run_number::<RoXmlNavigator<'static>>()
            .unwrap();

        assert_eq!(result, 42.0);
    }

    #[test]
    fn test_run_with_sequence() {
        use crate::types::XmlValue;

        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile_with_vars("count($items)", &ctx, &["items"]).unwrap();

        // Use run_with to bind a sequence
        let result = expr
            .evaluator(&ctx)
            .run_with::<RoXmlNavigator<'static>, _>(|eval| {
                let seq = XPathValue::from_sequence(vec![
                    XmlItem::Atomic(XmlValue::integer(1.into())),
                    XmlItem::Atomic(XmlValue::integer(2.into())),
                    XmlItem::Atomic(XmlValue::integer(3.into())),
                ]);
                eval.set_variable_by_name("items", seq).unwrap();
            })
            .unwrap();

        // count() should return 3
        assert_eq!(
            result.as_integer().map(|i| i.to_string()),
            Some("3".to_string())
        );
    }

    #[test]
    fn test_run_with_empty_sequence() {
        let names = NameTable::new();
        let ctx = XPathContext::new(&names);

        let expr = XPathExpr::compile_with_vars("empty($items)", &ctx, &["items"]).unwrap();

        // Use run_with to bind an empty sequence
        let result = expr
            .evaluator(&ctx)
            .run_with::<RoXmlNavigator<'static>, _>(|eval| {
                eval.set_variable_by_name("items", XPathValue::empty())
                    .unwrap();
            })
            .unwrap();

        // empty() should return true for empty sequence
        assert_eq!(result.as_bool(), Some(true));
    }
}