Skip to main content

einvoice_xpath_eval/
compile.rs

1//! Static analysis: an expression of the syntax tree becomes an evaluable tree in which
2//! functions and variables are resolved, numeric literals are values, and every path step
3//! knows how its result is to be ordered.
4//!
5//! The analysis also computes, for each subexpression, what is statically known of its
6//! value: whether it has at most one item, whether its items are nodes or atomic values,
7//! and for node sequences whether they come out in document order without duplicates
8//! (and whether no node is an ancestor of another). These properties choose the
9//! evaluation strategy, never the result: a path whose order is known is evaluated
10//! lazily, one whose order is not is sorted; a general comparison reads first the
11//! operand known to be a single item, as Saxon does.
12//!
13//! It also infers the static item type of every subexpression as Saxon-HE 12.10 does
14//! (`Expression.getItemType`, with the literals it folds), as far as it decides a
15//! result: the constructor `xs:decimal` strips the trailing zeros of an argument that is
16//! statically an `xs:integer` (see [`StaticType`]).
17
18use std::sync::Arc;
19
20use einvoice_xdm::{AtomicType, AtomicValue, Decimal, Integer, XPathRegex, ops, parse_double};
21use einvoice_xpath::{self as ast, AtomicKind, KindTest, NameOrWildcard, NameTest, QName};
22
23use crate::context::{
24    Cardinality, Clock, Context, DynamicContext, FunctionId, NoHost, StaticContext, VariableId,
25};
26use crate::error::{Error, ErrorCode, Result, err};
27use crate::functions::{self, Builtin, Returns};
28use crate::item::Item;
29use crate::tree::{Document, NodeAxis, NodeKind};
30
31/// A compiled expression.
32#[derive(Debug, Clone)]
33pub(crate) enum Expr {
34    Literal(AtomicValue),
35    ContextItem,
36    /// `/`: the document node of the context node's tree.
37    Root,
38    /// A range variable of `for`, `some`, `every`: its distance from the innermost one.
39    Local(usize),
40    External(VariableId),
41    Sequence(Vec<Expr>),
42    Filter {
43        base: Box<Expr>,
44        predicates: Vec<Predicate>,
45    },
46    Step(Box<Step>),
47    Path {
48        lhs: Box<Expr>,
49        rhs: Box<Expr>,
50        mode: PathMode,
51        /// Whether `rhs` reads the context size, so that `lhs` must be counted first.
52        rhs_uses_last: bool,
53    },
54    /// `lhs | rhs`; each flag says whether that operand is known to deliver document
55    /// order without duplicates (it is read lazily) or not (it is sorted first).
56    Union {
57        lhs: Box<Expr>,
58        rhs: Box<Expr>,
59        lhs_ordered: bool,
60        rhs_ordered: bool,
61    },
62    Negate(Box<Expr>),
63    Arithmetic {
64        op: ops::ArithmeticOp,
65        lhs: Box<Expr>,
66        rhs: Box<Expr>,
67    },
68    Range(Box<Expr>, Box<Expr>),
69    GeneralComparison {
70        op: ops::ComparisonOp,
71        lhs: Box<Expr>,
72        rhs: Box<Expr>,
73        strategy: CompareStrategy,
74    },
75    ValueComparison {
76        op: ops::ComparisonOp,
77        lhs: Box<Expr>,
78        rhs: Box<Expr>,
79    },
80    And(Box<Expr>, Box<Expr>),
81    Or(Box<Expr>, Box<Expr>),
82    If {
83        condition: Box<Expr>,
84        then: Box<Expr>,
85        otherwise: Box<Expr>,
86    },
87    For {
88        sequence: Box<Expr>,
89        body: Box<Expr>,
90    },
91    Quantified {
92        every: bool,
93        sequence: Box<Expr>,
94        satisfies: Box<Expr>,
95    },
96    InstanceOf {
97        operand: Box<Expr>,
98        item: ItemTest,
99        occurrence: ast::Occurrence,
100    },
101    Castable {
102        operand: Box<Expr>,
103        target: AtomicType,
104        allows_empty: bool,
105    },
106    Call {
107        function: Builtin,
108        args: Vec<Expr>,
109        data: CallData,
110    },
111    HostCall {
112        id: FunctionId,
113        args: Vec<Expr>,
114    },
115}
116
117/// What a call to a built-in function needs beyond its arguments.
118#[derive(Debug, Clone)]
119pub(crate) enum CallData {
120    None,
121    /// The regular expression of `matches`, `replace` or `tokenize` when pattern and
122    /// flags are literals, compiled once (an invalid one is reported when called).
123    Regex(Arc<std::result::Result<XPathRegex, Error>>),
124    /// The property named by the literal argument of `system-property`.
125    Property(QName),
126    /// `xs:decimal` of an argument whose static type is `xs:integer`: Saxon-HE 12.10
127    /// casts it with its up-casting converter, which strips the trailing zeros
128    /// (`AtomicValue::upcast`), where the cast of an operand typed at run time keeps
129    /// scale 0.
130    Upcast,
131}
132
133/// An axis step.
134#[derive(Debug, Clone)]
135pub(crate) struct Step {
136    pub(crate) axis: NodeAxis,
137    pub(crate) test: NodeTest,
138    pub(crate) predicates: Vec<Predicate>,
139}
140
141/// A predicate, with how its value is to be read.
142#[derive(Debug, Clone)]
143pub(crate) struct Predicate {
144    pub(crate) expr: Expr,
145    pub(crate) kind: PredicateKind,
146    /// Whether the predicate reads the context size (`last()`), so that the sequence it
147    /// filters must be counted first.
148    pub(crate) uses_last: bool,
149}
150
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub(crate) enum PredicateKind {
153    /// An integer literal: keeps the item at that position (`None`: at no position).
154    Position(Option<usize>),
155    /// A value that is never numeric: its effective boolean value decides.
156    Boolean,
157    /// Numeric (a position) or not (an effective boolean value), known at run time.
158    Dynamic,
159}
160
161/// How the result of `lhs/rhs` is assembled.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub(crate) enum PathMode {
164    /// Nodes, already in document order without duplicates: concatenated lazily.
165    Ordered,
166    /// Nodes in an unknown order: sorted, duplicates removed.
167    Sort,
168    /// Atomic values: concatenated lazily.
169    Atomic,
170    /// Unknown until run time: nodes are sorted, atomic values kept, a mix is an error.
171    Dynamic,
172}
173
174/// Which operand of a general comparison is read first (Saxon's comparison
175/// cardinalities).
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub(crate) enum CompareStrategy {
178    /// Both at most one item: the left one first; an empty one gives false.
179    OneToOne,
180    /// The right one is at most one item: it is evaluated first, then the left one read.
181    ManyToOne,
182    /// The left one is at most one item: it is evaluated first, then the right one read.
183    OneToMany,
184    /// Items read from each side in turn, each compared with those read from the other.
185    ManyToMany,
186}
187
188/// A node test.
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub(crate) enum NodeTest {
191    AnyNode,
192    Kind(NodeKind),
193    Named { kind: NodeKind, name: NameMatch },
194}
195
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub(crate) enum NameMatch {
198    Any,
199    Exact {
200        namespace: Option<String>,
201        local: String,
202    },
203    Namespace(String),
204    Local(String),
205}
206
207impl NodeTest {
208    pub(crate) fn matches(&self, doc: &Document, index: u32) -> bool {
209        let kind = doc.kind(index);
210        match self {
211            Self::AnyNode => true,
212            Self::Kind(k) => kind == *k,
213            Self::Named { kind: k, name } => {
214                if kind != *k {
215                    return false;
216                }
217                let Some(node_name) = doc.name(index) else {
218                    return false;
219                };
220                match name {
221                    NameMatch::Any => true,
222                    NameMatch::Exact { namespace, local } => {
223                        node_name.local == *local && node_name.namespace == *namespace
224                    }
225                    NameMatch::Namespace(namespace) => {
226                        node_name.namespace.as_deref() == Some(namespace.as_str())
227                    }
228                    NameMatch::Local(local) => node_name.local == *local,
229                }
230            }
231        }
232    }
233}
234
235/// The item type of `instance of`.
236#[derive(Debug, Clone)]
237pub(crate) enum ItemTest {
238    Atomic(AtomicType),
239    Node(NodeTest),
240}
241
242/// What is known of the items of a value.
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244enum Kinds {
245    Nodes,
246    Atomics,
247    Unknown,
248}
249
250/// What is known of a value, for the predicates it may appear in.
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252enum Class {
253    /// Never a single numeric value: its effective boolean value decides.
254    NotNumeric,
255    /// May be numeric.
256    Unknown,
257}
258
259/// The static item type of a value as Saxon-HE 12.10 infers it (`getItemType`), reduced
260/// to the distinctions that can change a result. It decides one thing: whether the
261/// argument of `xs:decimal` is an `xs:integer`, which Saxon then casts with its
262/// up-casting converter (trailing zeros stripped) rather than with the converter chosen
263/// at run time (scale 0 kept). The rules are Saxon's:
264///
265/// * literals have their type, and so have the expressions Saxon-HE folds into literals
266///   (its optimizer option `CONSTANT_FOLDING` is off, so only a few): unary minus of a
267///   literal and sequences of literals when parsed, arithmetic on two literals and casts
268///   of a literal when type-checked, and, when optimized, filters of a literal sequence
269///   that depend on the focus only (after which what contains them is type-checked
270///   again, see [`Typing`]); function calls and `if` are not folded;
271/// * `count`, `string-length`, `position`, `last`, `string-to-codepoints`, `to`,
272///   `xs:integer` give integers; `number` doubles; `xs:decimal` decimals;
273///   `distinct-values`, host functions and the external variables anything;
274/// * arithmetic follows Saxon's calculators: untyped operands count as doubles, any
275///   double operand gives a double, any decimal one a decimal, two integers an integer,
276///   except that `div` of two integers is a decimal and `idiv` always an integer; an
277///   operand of unknown type makes the result unknown;
278/// * `sum` gives the common type of its atomized argument (doubles for untyped values)
279///   and `xs:integer`, or the argument's type when it is exactly one item; `round`
280///   and `abs` the type of their argument; `reverse`, filters, unary minus, `for` and
281///   the range variables keep the type of their operand; `if` and sequences the
282///   common super type of their branches or items (`()` aside), integer and decimal
283///   giving decimal and any other mix giving anything;
284/// * a filter `E[. instance of T]` has type `T`, unless the items of `E` are known to be
285///   of type `T` (the test is then folded into `true()`);
286/// * elements, attributes, text and document nodes atomize to untyped values (Saxon-HE
287///   has no schema), comments and processing instructions to strings.
288///
289/// The context item at the top of an expression is of unknown type (the host knows
290/// it); inside a predicate or on the right of `/` it has the type of the items it
291/// ranges over.
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293pub(crate) enum StaticType {
294    /// No item: the empty sequence (Saxon's `ErrorType`), neutral in a common type.
295    Empty,
296    Integer,
297    Decimal,
298    Double,
299    UntypedAtomic,
300    /// A non-numeric atomic type: string, boolean, anyURI, date or dateTime.
301    OtherAtomic,
302    /// Elements, attributes, text or document nodes: their typed value is untyped.
303    UntypedNodes,
304    /// Comments or processing instructions: their typed value is a string.
305    StringNodes,
306    /// Nodes of kinds from both groups above, or of any kind.
307    Nodes,
308    /// Any item, any atomic value, any number.
309    Unknown,
310}
311
312impl StaticType {
313    /// The common super type (`Type.getCommonSuperType`).
314    const fn union(self, other: Self) -> Self {
315        match (self, other) {
316            (Self::Empty, t) | (t, Self::Empty) => t,
317            (Self::Integer, Self::Integer) => Self::Integer,
318            (Self::Integer | Self::Decimal, Self::Integer | Self::Decimal) => Self::Decimal,
319            (Self::Double, Self::Double) => Self::Double,
320            (Self::UntypedAtomic, Self::UntypedAtomic) => Self::UntypedAtomic,
321            (Self::OtherAtomic, Self::OtherAtomic) => Self::OtherAtomic,
322            (Self::UntypedNodes, Self::UntypedNodes) => Self::UntypedNodes,
323            (Self::StringNodes, Self::StringNodes) => Self::StringNodes,
324            (
325                Self::UntypedNodes | Self::StringNodes | Self::Nodes,
326                Self::UntypedNodes | Self::StringNodes | Self::Nodes,
327            ) => Self::Nodes,
328            _ => Self::Unknown,
329        }
330    }
331
332    /// The type of the atomized items (`Atomizer`, nodes untyped).
333    const fn atomized(self) -> Self {
334        match self {
335            Self::UntypedNodes => Self::UntypedAtomic,
336            Self::StringNodes => Self::OtherAtomic,
337            Self::Nodes => Self::Unknown,
338            t => t,
339        }
340    }
341
342    /// The type of an operand of arithmetic, `round`, `abs` or `sum`: atomized,
343    /// untyped values converted to doubles.
344    const fn numeric(self) -> Self {
345        match self.atomized() {
346            Self::UntypedAtomic => Self::Double,
347            t => t,
348        }
349    }
350
351    /// The type of `a op b`: the result type of Saxon's calculator for the operand
352    /// types (`Calculator.getResultType`), unknown when there is no specific one.
353    const fn arithmetic(op: ops::ArithmeticOp, a: Self, b: Self) -> Self {
354        let (a, b) = (a.numeric(), b.numeric());
355        let idiv = matches!(op, ops::ArithmeticOp::IntegerDivide);
356        match (a, b) {
357            (Self::Empty, _) | (_, Self::Empty) => Self::Empty,
358            (Self::Double, Self::Integer | Self::Decimal | Self::Double)
359            | (Self::Integer | Self::Decimal, Self::Double) => {
360                if idiv {
361                    Self::Integer
362                } else {
363                    Self::Double
364                }
365            }
366            (Self::Decimal, Self::Integer | Self::Decimal) | (Self::Integer, Self::Decimal) => {
367                if idiv {
368                    Self::Integer
369                } else {
370                    Self::Decimal
371                }
372            }
373            (Self::Integer, Self::Integer) => {
374                if matches!(op, ops::ArithmeticOp::Divide) {
375                    Self::Decimal
376                } else {
377                    Self::Integer
378                }
379            }
380            _ => Self::Unknown,
381        }
382    }
383
384    /// The type of the items of a value.
385    fn of_items(items: &[Item]) -> Self {
386        items.iter().fold(Self::Empty, |t, item| {
387            t.union(match item {
388                Item::Node(node) => match node.kind() {
389                    NodeKind::Comment | NodeKind::ProcessingInstruction => Self::StringNodes,
390                    _ => Self::UntypedNodes,
391                },
392                Item::Atomic(value) => Self::of_atomic(value.atomic_type()),
393            })
394        })
395    }
396
397    const fn of_atomic(t: AtomicType) -> Self {
398        match t {
399            AtomicType::Integer => Self::Integer,
400            AtomicType::Decimal => Self::Decimal,
401            AtomicType::Double => Self::Double,
402            AtomicType::UntypedAtomic => Self::UntypedAtomic,
403            _ => Self::OtherAtomic,
404        }
405    }
406
407    /// The type of the nodes a node test selects.
408    const fn of_test(test: &NodeTest) -> Self {
409        match test {
410            NodeTest::AnyNode => Self::Nodes,
411            NodeTest::Kind(NodeKind::Comment | NodeKind::ProcessingInstruction) => {
412                Self::StringNodes
413            }
414            NodeTest::Kind(_) | NodeTest::Named { .. } => Self::UntypedNodes,
415        }
416    }
417
418    /// Whether every item of this type is of type `t` (for `. instance of t`).
419    const fn subsumed_by(self, t: Self) -> bool {
420        matches!(
421            (self, t),
422            (Self::Integer, Self::Integer | Self::Decimal)
423                | (Self::Decimal, Self::Decimal)
424                | (Self::Double, Self::Double)
425                | (Self::OtherAtomic, Self::OtherAtomic)
426                | (Self::UntypedNodes, Self::UntypedNodes)
427                | (Self::StringNodes, Self::StringNodes)
428        )
429    }
430
431    /// The type of `-x` (`NegateExpression`: the primitive type of the operand).
432    const fn negated(self) -> Self {
433        match self.numeric() {
434            t @ (Self::Empty | Self::Integer | Self::Decimal | Self::Double) => t,
435            _ => Self::Unknown,
436        }
437    }
438}
439
440/// The static item type of a value at the two moments Saxon-HE 12.10 computes it.
441/// `checked` is the type after type checking, when a cast chooses its converter: an
442/// argument of `xs:decimal` of type `xs:integer` gets the up-casting converter, one of
443/// type `xs:decimal` is returned unchanged, one of unknown type gets no converter (it is
444/// chosen at run time). `optimized` is the type after optimization, which folds the
445/// filters of literal sequences: an expression that contains such a filter is
446/// type-checked again, so that a cast without a converter then gets the up-casting
447/// one if its argument has become a literal integer.
448#[derive(Debug, Clone, Copy, PartialEq, Eq)]
449struct Typing {
450    checked: StaticType,
451    optimized: StaticType,
452}
453
454impl Typing {
455    const fn of(t: StaticType) -> Self {
456        Self {
457            checked: t,
458            optimized: t,
459        }
460    }
461
462    const fn union(self, other: Self) -> Self {
463        Self {
464            checked: self.checked.union(other.checked),
465            optimized: self.optimized.union(other.optimized),
466        }
467    }
468
469    fn map(self, f: impl Fn(StaticType) -> StaticType) -> Self {
470        Self {
471            checked: f(self.checked),
472            optimized: f(self.optimized),
473        }
474    }
475
476    fn zip(self, other: Self, f: impl Fn(StaticType, StaticType) -> StaticType) -> Self {
477        Self {
478            checked: f(self.checked, other.checked),
479            optimized: f(self.optimized, other.optimized),
480        }
481    }
482
483    /// Whether Saxon casts a value of this type to `xs:decimal` with its up-casting
484    /// converter: an integer when type-checked, or of unknown type then and an integer
485    /// once optimized.
486    const fn upcasts_to_decimal(self) -> bool {
487        matches!(
488            (self.checked.atomized(), self.optimized.atomized()),
489            (StaticType::Integer, _) | (StaticType::Unknown, StaticType::Integer)
490        )
491    }
492}
493
494/// Statically known properties of a value.
495#[derive(Debug, Clone, Copy)]
496struct Props {
497    max_one: bool,
498    kinds: Kinds,
499    class: Class,
500    /// Nodes in document order without duplicates.
501    ordered: bool,
502    /// No node is an ancestor of another (only meaningful with `ordered`).
503    peer: bool,
504    /// The static item type.
505    ty: Typing,
506    /// Whether it is statically exactly one item.
507    count: Count,
508    /// Whether Saxon folds it into a literal.
509    folding: Folding,
510}
511
512/// Whether a value is statically exactly one item (for `sum`).
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514enum Count {
515    ExactlyOne,
516    Other,
517}
518
519impl Count {
520    const fn of(one: bool) -> Self {
521        if one { Self::ExactlyOne } else { Self::Other }
522    }
523}
524
525/// When Saxon-HE folds an expression into a literal.
526#[derive(Debug, Clone, Copy, PartialEq, Eq)]
527enum Folding {
528    Never,
529    /// When optimizing.
530    Optimized,
531    /// When type checking (and so when optimizing too).
532    Checked,
533}
534
535impl Props {
536    const fn atomic(max_one: bool, class: Class) -> Self {
537        Self {
538            max_one,
539            kinds: Kinds::Atomics,
540            class,
541            ordered: false,
542            peer: false,
543            ty: Typing::of(StaticType::Unknown),
544            count: Count::Other,
545            folding: Folding::Never,
546        }
547    }
548
549    const BOOLEAN: Self = Self::atomic(true, Class::NotNumeric).typed(StaticType::OtherAtomic);
550
551    const fn unknown(max_one: bool) -> Self {
552        Self {
553            max_one,
554            kinds: Kinds::Unknown,
555            class: Class::Unknown,
556            ordered: max_one,
557            peer: max_one,
558            ty: Typing::of(StaticType::Unknown),
559            count: Count::Other,
560            folding: Folding::Never,
561        }
562    }
563
564    const fn nodes(max_one: bool, ordered: bool, peer: bool) -> Self {
565        Self {
566            max_one,
567            kinds: Kinds::Nodes,
568            class: Class::NotNumeric,
569            ordered,
570            peer,
571            ty: Typing::of(StaticType::Nodes),
572            count: Count::Other,
573            folding: Folding::Never,
574        }
575    }
576
577    const fn typed(self, ty: StaticType) -> Self {
578        Self {
579            ty: Typing::of(ty),
580            ..self
581        }
582    }
583
584    const fn typing(self, ty: Typing) -> Self {
585        Self { ty, ..self }
586    }
587
588    const fn exactly_one(self, one: bool) -> Self {
589        Self {
590            count: Count::of(one),
591            ..self
592        }
593    }
594
595    const fn one(&self) -> bool {
596        matches!(self.count, Count::ExactlyOne)
597    }
598
599    /// Whether Saxon folds it into a literal when type-checking, and when optimizing.
600    const fn literal(self, checked: bool, optimized: bool) -> Self {
601        Self {
602            folding: if checked {
603                Folding::Checked
604            } else if optimized {
605                Folding::Optimized
606            } else {
607                Folding::Never
608            },
609            ..self
610        }
611    }
612
613    /// A literal once type-checked.
614    const fn is_literal(&self) -> bool {
615        matches!(self.folding, Folding::Checked)
616    }
617
618    /// A literal once optimized.
619    const fn folds(&self) -> bool {
620        matches!(self.folding, Folding::Checked | Folding::Optimized)
621    }
622
623    /// Either of two values (the branches of `if`).
624    const fn either(a: Self, b: Self) -> Self {
625        Self {
626            max_one: a.max_one && b.max_one,
627            kinds: if matches!(
628                (a.kinds, b.kinds),
629                (Kinds::Nodes, Kinds::Nodes)
630                    | (Kinds::Atomics, Kinds::Atomics)
631                    | (Kinds::Unknown, Kinds::Unknown)
632            ) {
633                a.kinds
634            } else {
635                Kinds::Unknown
636            },
637            class: if matches!((a.class, b.class), (Class::NotNumeric, Class::NotNumeric)) {
638                Class::NotNumeric
639            } else {
640                Class::Unknown
641            },
642            ordered: a.ordered && b.ordered,
643            peer: a.peer && b.peer,
644            ty: a.ty.union(b.ty),
645            count: Count::of(a.one() && b.one()),
646            folding: Folding::Never,
647        }
648    }
649}
650
651/// An expression ready to be evaluated: functions and variables resolved against a
652/// static context. It holds no node and can be shared between threads.
653#[derive(Debug, Clone)]
654pub struct CompiledExpr {
655    pub(crate) expr: Expr,
656    max_one: bool,
657}
658
659impl CompiledExpr {
660    /// Whether the value is statically known to have at most one item.
661    #[must_use]
662    pub const fn is_at_most_one(&self) -> bool {
663        self.max_one
664    }
665}
666
667/// Compiles an expression in a static context.
668///
669/// # Errors
670///
671/// `XPST0008` for a variable not in scope, `XPST0017` for an unknown function or arity,
672/// `XTDE1390` for an invalid `system-property` name, [`ErrorCode::Unsupported`] for a
673/// function of the specifications that is not implemented or a literal out of range.
674pub fn compile(expr: &ast::Expr, context: &dyn StaticContext) -> Result<CompiledExpr> {
675    let mut compiler = Compiler {
676        context,
677        locals: Vec::new(),
678        focus: Typing::of(StaticType::Unknown),
679    };
680    let (expr, props) = compiler.expr(expr)?;
681    Ok(CompiledExpr {
682        expr,
683        max_one: props.max_one,
684    })
685}
686
687struct Compiler<'a> {
688    context: &'a dyn StaticContext,
689    /// The range variables in scope, innermost last, with their static item type.
690    locals: Vec<(QName, Typing)>,
691    /// The static type of the context item.
692    focus: Typing,
693}
694
695/// The type of the value of an expression Saxon folds into a literal, evaluated as Saxon
696/// does at compile time, or `None` when the evaluation fails (Saxon then keeps the
697/// expression, and reports the error only if it is evaluated).
698fn folded_type(expr: &Expr) -> Option<StaticType> {
699    // Only the type of the value is used: `current-dateTime()` has the same at any time,
700    // so any clock does.
701    let dc = DynamicContext::new(&NoHost, Clock::from_unix_millis(0, 0).ok()?);
702    let compiled = CompiledExpr {
703        expr: expr.clone(),
704        max_one: false,
705    };
706    let items = compiled.evaluate(&dc, &Context::new()).ok()?;
707    Some(StaticType::of_items(&items))
708}
709
710/// Whether an expression refers to a variable or a host function anywhere
711/// (`ExpressionTool.refersToVariableOrFunction`).
712fn refers_to_variable_or_function(expr: &Expr) -> bool {
713    let any = |items: &[Expr]| items.iter().any(refers_to_variable_or_function);
714    let preds = |predicates: &[Predicate]| {
715        predicates
716            .iter()
717            .any(|p| refers_to_variable_or_function(&p.expr))
718    };
719    match expr {
720        Expr::Local(_) | Expr::External(_) | Expr::HostCall { .. } => true,
721        Expr::Literal(_) | Expr::ContextItem | Expr::Root => false,
722        Expr::Call { args, .. } | Expr::Sequence(args) => any(args),
723        Expr::Filter { base, predicates } => {
724            refers_to_variable_or_function(base) || preds(predicates)
725        }
726        Expr::Step(step) => preds(&step.predicates),
727        Expr::Path { lhs, rhs, .. }
728        | Expr::Union { lhs, rhs, .. }
729        | Expr::Arithmetic { lhs, rhs, .. }
730        | Expr::Range(lhs, rhs)
731        | Expr::GeneralComparison { lhs, rhs, .. }
732        | Expr::ValueComparison { lhs, rhs, .. }
733        | Expr::And(lhs, rhs)
734        | Expr::Or(lhs, rhs)
735        | Expr::For {
736            sequence: lhs,
737            body: rhs,
738        }
739        | Expr::Quantified {
740            sequence: lhs,
741            satisfies: rhs,
742            ..
743        } => refers_to_variable_or_function(lhs) || refers_to_variable_or_function(rhs),
744        Expr::Negate(e)
745        | Expr::InstanceOf { operand: e, .. }
746        | Expr::Castable { operand: e, .. } => refers_to_variable_or_function(e),
747        Expr::If {
748            condition,
749            then,
750            otherwise,
751        } => {
752            refers_to_variable_or_function(condition)
753                || refers_to_variable_or_function(then)
754                || refers_to_variable_or_function(otherwise)
755        }
756    }
757}
758
759fn boxed(e: Expr) -> Box<Expr> {
760    Box::new(e)
761}
762
763fn comparison_op(kind: ast::CompareKind) -> ops::ComparisonOp {
764    match kind {
765        ast::CompareKind::Eq => ops::ComparisonOp::Equal,
766        ast::CompareKind::Ne => ops::ComparisonOp::NotEqual,
767        ast::CompareKind::Lt => ops::ComparisonOp::Less,
768        ast::CompareKind::Le => ops::ComparisonOp::LessOrEqual,
769        ast::CompareKind::Gt => ops::ComparisonOp::Greater,
770        ast::CompareKind::Ge => ops::ComparisonOp::GreaterOrEqual,
771    }
772}
773
774fn arithmetic_op(op: ast::ArithmeticOp) -> ops::ArithmeticOp {
775    match op {
776        ast::ArithmeticOp::Add => ops::ArithmeticOp::Add,
777        ast::ArithmeticOp::Subtract => ops::ArithmeticOp::Subtract,
778        ast::ArithmeticOp::Multiply => ops::ArithmeticOp::Multiply,
779        ast::ArithmeticOp::Divide => ops::ArithmeticOp::Divide,
780        ast::ArithmeticOp::IntegerDivide => ops::ArithmeticOp::IntegerDivide,
781        ast::ArithmeticOp::Modulo => ops::ArithmeticOp::Modulo,
782    }
783}
784
785pub(crate) const fn atomic_type(kind: AtomicKind) -> AtomicType {
786    match kind {
787        AtomicKind::String => AtomicType::String,
788        AtomicKind::AnyUri => AtomicType::AnyUri,
789        AtomicKind::Boolean => AtomicType::Boolean,
790        AtomicKind::Integer => AtomicType::Integer,
791        AtomicKind::Decimal => AtomicType::Decimal,
792        AtomicKind::Date => AtomicType::Date,
793    }
794}
795
796fn node_axis(axis: ast::Axis) -> NodeAxis {
797    match axis {
798        ast::Axis::Child => NodeAxis::Child,
799        ast::Axis::Attribute => NodeAxis::Attribute,
800        ast::Axis::SelfAxis => NodeAxis::SelfAxis,
801        ast::Axis::DescendantOrSelf => NodeAxis::DescendantOrSelf,
802        ast::Axis::FollowingSibling => NodeAxis::FollowingSibling,
803        ast::Axis::Parent => NodeAxis::Parent,
804        ast::Axis::Ancestor => NodeAxis::Ancestor,
805        ast::Axis::AncestorOrSelf => NodeAxis::AncestorOrSelf,
806        ast::Axis::PrecedingSibling => NodeAxis::PrecedingSibling,
807        ast::Axis::Preceding => NodeAxis::Preceding,
808    }
809}
810
811fn name_match(name: Option<&NameOrWildcard>) -> NameMatch {
812    match name {
813        None | Some(NameOrWildcard::Wildcard) => NameMatch::Any,
814        Some(NameOrWildcard::Name(q)) => NameMatch::Exact {
815            namespace: q.namespace.clone(),
816            local: q.local.clone(),
817        },
818    }
819}
820
821/// The node test of a kind test.
822pub(crate) fn kind_test(test: &KindTest) -> NodeTest {
823    match test {
824        KindTest::AnyKind => NodeTest::AnyNode,
825        KindTest::Text => NodeTest::Kind(NodeKind::Text),
826        KindTest::Comment => NodeTest::Kind(NodeKind::Comment),
827        KindTest::ProcessingInstruction => NodeTest::Kind(NodeKind::ProcessingInstruction),
828        KindTest::Element(name) => NodeTest::Named {
829            kind: NodeKind::Element,
830            name: name_match(name.as_ref()),
831        },
832        KindTest::Attribute(name) => NodeTest::Named {
833            kind: NodeKind::Attribute,
834            name: name_match(name.as_ref()),
835        },
836    }
837}
838
839fn node_test(test: &ast::NodeTest, axis: NodeAxis) -> NodeTest {
840    let principal = if axis == NodeAxis::Attribute {
841        NodeKind::Attribute
842    } else {
843        NodeKind::Element
844    };
845    match test {
846        ast::NodeTest::Kind(kind) => kind_test(kind),
847        ast::NodeTest::Name(name) => NodeTest::Named {
848            kind: principal,
849            name: match name {
850                NameTest::Name(q) => NameMatch::Exact {
851                    namespace: q.namespace.clone(),
852                    local: q.local.clone(),
853                },
854                NameTest::Any => NameMatch::Any,
855                NameTest::AnyLocal { namespace, .. } => NameMatch::Namespace(namespace.clone()),
856                NameTest::AnyNamespace { local } => NameMatch::Local(local.clone()),
857            },
858        },
859    }
860}
861
862/// Whether an expression calls `last()` (or, with `position`, `position()`) anywhere.
863/// Conservative: a call inside a nested focus counts too.
864fn calls_focus(expr: &Expr, position: bool) -> bool {
865    let any = |items: &[Expr]| items.iter().any(|e| calls_focus(e, position));
866    let preds =
867        |predicates: &[Predicate]| predicates.iter().any(|p| calls_focus(&p.expr, position));
868    match expr {
869        Expr::Literal(_) | Expr::ContextItem | Expr::Root | Expr::Local(_) | Expr::External(_) => {
870            false
871        }
872        Expr::Call { function, args, .. } => {
873            *function == Builtin::Last || (position && *function == Builtin::Position) || any(args)
874        }
875        Expr::HostCall { args, .. } | Expr::Sequence(args) => any(args),
876        Expr::Filter { base, predicates } => calls_focus(base, position) || preds(predicates),
877        Expr::Step(step) => preds(&step.predicates),
878        Expr::Path { lhs, rhs, .. }
879        | Expr::Union { lhs, rhs, .. }
880        | Expr::Arithmetic { lhs, rhs, .. }
881        | Expr::Range(lhs, rhs)
882        | Expr::GeneralComparison { lhs, rhs, .. }
883        | Expr::ValueComparison { lhs, rhs, .. }
884        | Expr::And(lhs, rhs)
885        | Expr::Or(lhs, rhs)
886        | Expr::For {
887            sequence: lhs,
888            body: rhs,
889        }
890        | Expr::Quantified {
891            sequence: lhs,
892            satisfies: rhs,
893            ..
894        } => calls_focus(lhs, position) || calls_focus(rhs, position),
895        Expr::Negate(e)
896        | Expr::InstanceOf { operand: e, .. }
897        | Expr::Castable { operand: e, .. } => calls_focus(e, position),
898        Expr::If {
899            condition,
900            then,
901            otherwise,
902        } => {
903            calls_focus(condition, position)
904                || calls_focus(then, position)
905                || calls_focus(otherwise, position)
906        }
907    }
908}
909
910/// The axis of an expression used as a path step, if it is an axis step (`.` counts as
911/// `self::node()`).
912fn step_axis(expr: &Expr) -> Option<NodeAxis> {
913    match expr {
914        Expr::Step(step) => Some(step.axis),
915        Expr::ContextItem => Some(NodeAxis::SelfAxis),
916        _ => None,
917    }
918}
919
920/// Whether `lhs/rhs` yields nodes in document order without duplicates when `lhs` does.
921fn path_is_ordered(lhs: Props, axis: NodeAxis) -> bool {
922    if lhs.max_one {
923        // A step from one node: axis results are delivered in document order.
924        return true;
925    }
926    if !lhs.ordered {
927        return false;
928    }
929    match axis {
930        NodeAxis::Attribute | NodeAxis::SelfAxis => true,
931        NodeAxis::Child | NodeAxis::Descendant | NodeAxis::DescendantOrSelf => lhs.peer,
932        _ => false,
933    }
934}
935
936/// Properties of an axis step from a single node.
937fn step_props(axis: NodeAxis, test: &NodeTest, predicates: &[Predicate]) -> Props {
938    let positional = predicates
939        .iter()
940        .any(|p| matches!(p.kind, PredicateKind::Position(_)));
941    let one_attribute = axis == NodeAxis::Attribute
942        && matches!(
943            test,
944            NodeTest::Named {
945                name: NameMatch::Exact { .. },
946                ..
947            }
948        );
949    let max_one =
950        positional || one_attribute || matches!(axis, NodeAxis::SelfAxis | NodeAxis::Parent);
951    let peer = max_one
952        || matches!(
953            axis,
954            NodeAxis::Child
955                | NodeAxis::Attribute
956                | NodeAxis::FollowingSibling
957                | NodeAxis::PrecedingSibling
958        );
959    Props::nodes(max_one, true, peer)
960}
961
962/// A path step as the compiler sees it: a step of the syntax tree, or `//name` merged
963/// into one `descendant::name` step.
964enum PathStep<'a> {
965    Ast(&'a ast::Step),
966    Descendant(&'a ast::AxisStep),
967}
968
969impl Compiler<'_> {
970    #[expect(
971        clippy::too_many_lines,
972        reason = "one arm per expression form of the syntax tree"
973    )]
974    fn expr(&mut self, expr: &ast::Expr) -> Result<(Expr, Props)> {
975        match expr {
976            ast::Expr::Literal(literal) => literal_value(literal),
977            ast::Expr::VarRef(name) => self.variable(name),
978            ast::Expr::ContextItem => Ok((
979                Expr::ContextItem,
980                Props::unknown(true).typing(self.focus).exactly_one(true),
981            )),
982            ast::Expr::FunctionCall { name, args } => self.call(name, args),
983            ast::Expr::Sequence(items) => self.sequence(items),
984            ast::Expr::Filter {
985                base,
986                predicates: ast_predicates,
987            } => {
988                let (base, props) = self.expr(base)?;
989                let predicates = self.with_focus(props.ty, |c| c.predicates(ast_predicates))?;
990                let positional = predicates
991                    .iter()
992                    .any(|p| matches!(p.kind, PredicateKind::Position(_)));
993                // `E[. instance of T]` has type T, unless the test is always true.
994                let ty = ast_predicates.iter().fold(props.ty, |ty, p| match p {
995                    ast::Expr::InstanceOf { operand, target }
996                        if matches!(**operand, ast::Expr::ContextItem) =>
997                    {
998                        let tested = match &target.item {
999                            ast::ItemType::Atomic(atomic) => {
1000                                StaticType::of_atomic(atomic_type(atomic.kind))
1001                            }
1002                            ast::ItemType::Kind(kind) => StaticType::of_test(&kind_test(kind)),
1003                        };
1004                        ty.map(|t| if t.subsumed_by(tested) { t } else { tested })
1005                    }
1006                    _ => ty,
1007                });
1008                // The optimizer folds the filter of a literal sequence (not a range)
1009                // when every predicate is `[1]` (`FirstItemExpression`), or when none
1010                // is positional (numeric, or reading the position or the size) and
1011                // each depends on the focus only (`tryEarlyEvaluation`). Other
1012                // positional predicates are rewritten and not folded, and so is `[1]`
1013                // after another predicate.
1014                let first_items = predicates
1015                    .iter()
1016                    .all(|p| p.kind == PredicateKind::Position(Some(1)));
1017                let early = predicates.iter().all(|p| {
1018                    p.kind == PredicateKind::Boolean
1019                        && !calls_focus(&p.expr, true)
1020                        && !refers_to_variable_or_function(&p.expr)
1021                        && !depends_on_more_than_focus(&p.expr)
1022                });
1023                let folds =
1024                    props.folds() && !matches!(base, Expr::Range(..)) && (first_items || early);
1025                let compiled = Expr::Filter {
1026                    base: boxed(base),
1027                    predicates,
1028                };
1029                let ty = match folds.then(|| folded_type(&compiled)).flatten() {
1030                    Some(value) => Typing {
1031                        optimized: value,
1032                        ..ty
1033                    },
1034                    None => ty,
1035                };
1036                let props = Props {
1037                    max_one: props.max_one || positional,
1038                    count: Count::Other,
1039                    ..props
1040                }
1041                .typing(ty)
1042                .literal(false, folds);
1043                Ok((compiled, props))
1044            }
1045            ast::Expr::Path(path) => self.path(path),
1046            ast::Expr::Negate(operand) => {
1047                let (operand, p) = self.expr(operand)?;
1048                Ok((
1049                    Expr::Negate(boxed(operand)),
1050                    Props::atomic(true, Class::Unknown)
1051                        .typing(p.ty.map(StaticType::negated))
1052                        .exactly_one(p.one())
1053                        .literal(p.is_literal(), p.folds()),
1054                ))
1055            }
1056            ast::Expr::Castable { operand, target } => {
1057                let (operand, _) = self.expr(operand)?;
1058                Ok((
1059                    Expr::Castable {
1060                        operand: boxed(operand),
1061                        target: atomic_type(target.atomic.kind),
1062                        allows_empty: target.allows_empty,
1063                    },
1064                    Props::BOOLEAN.exactly_one(true),
1065                ))
1066            }
1067            ast::Expr::InstanceOf { operand, target } => {
1068                let (operand, _) = self.expr(operand)?;
1069                let item = match &target.item {
1070                    ast::ItemType::Atomic(atomic) => ItemTest::Atomic(atomic_type(atomic.kind)),
1071                    ast::ItemType::Kind(kind) => ItemTest::Node(kind_test(kind)),
1072                };
1073                Ok((
1074                    Expr::InstanceOf {
1075                        operand: boxed(operand),
1076                        item,
1077                        occurrence: target.occurrence,
1078                    },
1079                    Props::BOOLEAN.exactly_one(true),
1080                ))
1081            }
1082            ast::Expr::Union(lhs, rhs) => {
1083                let (lhs, lp) = self.expr(lhs)?;
1084                let (rhs, rp) = self.expr(rhs)?;
1085                Ok((
1086                    Expr::Union {
1087                        lhs: boxed(lhs),
1088                        rhs: boxed(rhs),
1089                        lhs_ordered: lp.ordered && lp.kinds == Kinds::Nodes,
1090                        rhs_ordered: rp.ordered && rp.kinds == Kinds::Nodes,
1091                    },
1092                    Props::nodes(false, true, false).typing(lp.ty.union(rp.ty)),
1093                ))
1094            }
1095            ast::Expr::Arithmetic { op, lhs, rhs } => {
1096                let op = arithmetic_op(*op);
1097                let (lhs, lp) = self.expr(lhs)?;
1098                let (rhs, rp) = self.expr(rhs)?;
1099                let compiled = Expr::Arithmetic {
1100                    op,
1101                    lhs: boxed(lhs),
1102                    rhs: boxed(rhs),
1103                };
1104                let mut ty = lp.ty.zip(rp.ty, |a, b| StaticType::arithmetic(op, a, b));
1105                // Arithmetic on two literals is folded when type-checked (and, after
1106                // optimization, on two operands folded by then), unless it fails.
1107                let (mut literal, mut folds) = (false, false);
1108                if lp.folds()
1109                    && rp.folds()
1110                    && let Some(value) = folded_type(&compiled)
1111                {
1112                    literal = lp.is_literal() && rp.is_literal();
1113                    folds = true;
1114                    ty.optimized = value;
1115                    if literal {
1116                        ty.checked = value;
1117                    }
1118                }
1119                Ok((
1120                    compiled,
1121                    Props::atomic(true, Class::Unknown)
1122                        .typing(ty)
1123                        .exactly_one(lp.one() && rp.one())
1124                        .literal(literal, folds),
1125                ))
1126            }
1127            ast::Expr::Range(lhs, rhs) => {
1128                let (lhs, _) = self.expr(lhs)?;
1129                let (rhs, _) = self.expr(rhs)?;
1130                Ok((
1131                    Expr::Range(boxed(lhs), boxed(rhs)),
1132                    Props::atomic(false, Class::Unknown).typed(StaticType::Integer),
1133                ))
1134            }
1135            ast::Expr::Comparison { op, lhs, rhs } => self.comparison(*op, lhs, rhs),
1136            ast::Expr::And(lhs, rhs) | ast::Expr::Or(lhs, rhs) => {
1137                let (l, _) = self.expr(lhs)?;
1138                let (r, _) = self.expr(rhs)?;
1139                let e = if matches!(expr, ast::Expr::And(..)) {
1140                    Expr::And(boxed(l), boxed(r))
1141                } else {
1142                    Expr::Or(boxed(l), boxed(r))
1143                };
1144                Ok((e, Props::BOOLEAN.exactly_one(true)))
1145            }
1146            ast::Expr::If {
1147                condition,
1148                then,
1149                otherwise,
1150            } => {
1151                // Not folded, even with a literal condition (the optimizer option
1152                // `CONSTANT_FOLDING` is off in Saxon-HE).
1153                let (condition, _) = self.expr(condition)?;
1154                let (then, a) = self.expr(then)?;
1155                let (otherwise, b) = self.expr(otherwise)?;
1156                Ok((
1157                    Expr::If {
1158                        condition: boxed(condition),
1159                        then: boxed(then),
1160                        otherwise: boxed(otherwise),
1161                    },
1162                    Props::either(a, b),
1163                ))
1164            }
1165            ast::Expr::For { bindings, body } => self
1166                .bindings(bindings, &mut |c| {
1167                    let (body, props) = c.expr(body)?;
1168                    Ok((body, (props.kinds, props.ty)))
1169                })
1170                .map(|(e, (kinds, ty))| {
1171                    (
1172                        e,
1173                        Props {
1174                            kinds,
1175                            ..Props::unknown(false)
1176                        }
1177                        .typing(ty),
1178                    )
1179                }),
1180            ast::Expr::Quantified {
1181                quantifier,
1182                bindings,
1183                satisfies,
1184            } => self.quantified(*quantifier == ast::Quantifier::Every, bindings, satisfies),
1185        }
1186    }
1187
1188    fn variable(&self, name: &QName) -> Result<(Expr, Props)> {
1189        if let Some((depth, (_, ty))) = self
1190            .locals
1191            .iter()
1192            .rev()
1193            .enumerate()
1194            .find(|(_, (local, _))| local.same_expanded_name(name))
1195        {
1196            return Ok((
1197                Expr::Local(depth),
1198                Props::unknown(true).typing(*ty).exactly_one(true),
1199            ));
1200        }
1201        match self.context.variable(name) {
1202            Some(info) => Ok((
1203                Expr::External(info.id),
1204                Props::unknown(info.cardinality == Cardinality::AtMostOne),
1205            )),
1206            None => err(
1207                ErrorCode::Xpst0008,
1208                format!("Variable ${name} has not been declared"),
1209            ),
1210        }
1211    }
1212
1213    fn sequence(&mut self, items: &[ast::Expr]) -> Result<(Expr, Props)> {
1214        let mut compiled = Vec::with_capacity(items.len());
1215        let mut props: Option<Props> = None;
1216        let mut all_literal = true;
1217        for item in items {
1218            let (e, p) = self.expr(item)?;
1219            all_literal &= p.is_literal() && p.kinds == Kinds::Atomics;
1220            compiled.push(e);
1221            props = Some(props.map_or(p, |q| Props::either(q, p)));
1222        }
1223        let props = match props {
1224            // `()` and a sequence of literals are literals once parsed.
1225            None => Props::atomic(true, Class::NotNumeric)
1226                .typed(StaticType::Empty)
1227                .literal(true, true),
1228            Some(p) => Props {
1229                max_one: false,
1230                ordered: false,
1231                peer: false,
1232                count: Count::Other,
1233                ..p
1234            }
1235            .literal(all_literal, all_literal),
1236        };
1237        Ok((Expr::Sequence(compiled), props))
1238    }
1239
1240    fn comparison(
1241        &mut self,
1242        op: ast::ComparisonOp,
1243        lhs: &ast::Expr,
1244        rhs: &ast::Expr,
1245    ) -> Result<(Expr, Props)> {
1246        let (l, lp) = self.expr(lhs)?;
1247        let (r, rp) = self.expr(rhs)?;
1248        let props = Props::BOOLEAN
1249            .exactly_one(matches!(op, ast::ComparisonOp::General(_)) || (lp.one() && rp.one()));
1250        let e = match op {
1251            ast::ComparisonOp::General(kind) => Expr::GeneralComparison {
1252                op: comparison_op(kind),
1253                lhs: boxed(l),
1254                rhs: boxed(r),
1255                strategy: match (lp.max_one, rp.max_one) {
1256                    (true, true) => CompareStrategy::OneToOne,
1257                    (_, true) => CompareStrategy::ManyToOne,
1258                    (true, false) => CompareStrategy::OneToMany,
1259                    (false, false) => CompareStrategy::ManyToMany,
1260                },
1261            },
1262            ast::ComparisonOp::Value(kind) => Expr::ValueComparison {
1263                op: comparison_op(kind),
1264                lhs: boxed(l),
1265                rhs: boxed(r),
1266            },
1267        };
1268        Ok((e, props))
1269    }
1270
1271    /// Compiles nested bindings (`for $a in A, $b in B return E` is
1272    /// `for $a in A return for $b in B return E`), with `inner` compiling the innermost
1273    /// body.
1274    fn bindings<T>(
1275        &mut self,
1276        bindings: &[ast::Binding],
1277        inner: &mut dyn FnMut(&mut Self) -> Result<(Expr, T)>,
1278    ) -> Result<(Expr, T)> {
1279        let Some((first, rest)) = bindings.split_first() else {
1280            return inner(self);
1281        };
1282        let (sequence, p) = self.expr(&first.sequence)?;
1283        self.locals.push((first.variable.clone(), p.ty));
1284        let body = self.bindings(rest, inner);
1285        self.locals.pop();
1286        let (body, extra) = body?;
1287        Ok((
1288            Expr::For {
1289                sequence: boxed(sequence),
1290                body: boxed(body),
1291            },
1292            extra,
1293        ))
1294    }
1295
1296    fn quantified(
1297        &mut self,
1298        every: bool,
1299        bindings: &[ast::Binding],
1300        satisfies: &ast::Expr,
1301    ) -> Result<(Expr, Props)> {
1302        let Some((first, rest)) = bindings.split_first() else {
1303            return err(ErrorCode::Internal, "quantified expression without binding");
1304        };
1305        let (sequence, p) = self.expr(&first.sequence)?;
1306        self.locals.push((first.variable.clone(), p.ty));
1307        let body = if rest.is_empty() {
1308            self.expr(satisfies).map(|(e, _)| e)
1309        } else {
1310            self.quantified(every, rest, satisfies).map(|(e, _)| e)
1311        };
1312        self.locals.pop();
1313        Ok((
1314            Expr::Quantified {
1315                every,
1316                sequence: boxed(sequence),
1317                satisfies: boxed(body?),
1318            },
1319            Props::BOOLEAN,
1320        ))
1321    }
1322
1323    fn predicates(&mut self, predicates: &[ast::Expr]) -> Result<Vec<Predicate>> {
1324        predicates
1325            .iter()
1326            .map(|p| {
1327                let (expr, props) = self.expr(p)?;
1328                let kind = match &expr {
1329                    Expr::Literal(AtomicValue::Integer(n)) => PredicateKind::Position(
1330                        n.to_i64()
1331                            .and_then(|n| usize::try_from(n).ok())
1332                            .filter(|&n| n > 0),
1333                    ),
1334                    _ if props.class == Class::NotNumeric => PredicateKind::Boolean,
1335                    _ => PredicateKind::Dynamic,
1336                };
1337                let uses_last = calls_focus(&expr, false);
1338                Ok(Predicate {
1339                    expr,
1340                    kind,
1341                    uses_last,
1342                })
1343            })
1344            .collect()
1345    }
1346
1347    /// Runs `compile` with the context item of that static type.
1348    fn with_focus<T>(
1349        &mut self,
1350        focus: Typing,
1351        compile: impl FnOnce(&mut Self) -> Result<T>,
1352    ) -> Result<T> {
1353        let outer = std::mem::replace(&mut self.focus, focus);
1354        let result = compile(self);
1355        self.focus = outer;
1356        result
1357    }
1358
1359    /// Whether the predicates of a `child::` step can be moved to a `descendant::` step
1360    /// (`//name[p]`): none of them may depend on the position.
1361    fn positional(predicates: &[Predicate]) -> bool {
1362        predicates
1363            .iter()
1364            .any(|p| p.kind != PredicateKind::Boolean || calls_focus(&p.expr, true))
1365    }
1366
1367    fn path(&mut self, path: &ast::PathExpr) -> Result<(Expr, Props)> {
1368        // `descendant-or-self::node()/child::name` without positional predicate is
1369        // `descendant::name`, which keeps document order from a single node.
1370        let mut steps = Vec::with_capacity(path.steps.len());
1371        let mut i = 0;
1372        while i < path.steps.len() {
1373            let step = &path.steps[i];
1374            if let (ast::Step::Axis(dos), Some(ast::Step::Axis(child))) =
1375                (step, path.steps.get(i + 1))
1376                && dos.axis == ast::Axis::DescendantOrSelf
1377                && dos.test == ast::NodeTest::Kind(KindTest::AnyKind)
1378                && dos.predicates.is_empty()
1379                && child.axis == ast::Axis::Child
1380            {
1381                let test = node_test(&child.test, NodeAxis::Child);
1382                let focus = Typing::of(StaticType::of_test(&test));
1383                let predicates = self.with_focus(focus, |c| c.predicates(&child.predicates))?;
1384                if !Self::positional(&predicates) {
1385                    steps.push(PathStep::Descendant(child));
1386                    i += 2;
1387                    continue;
1388                }
1389            }
1390            steps.push(PathStep::Ast(step));
1391            i += 1;
1392        }
1393        let mut acc = match path.start {
1394            ast::PathStart::Root => Some((
1395                Expr::Root,
1396                Props::nodes(true, true, true)
1397                    .typed(StaticType::UntypedNodes)
1398                    .exactly_one(true),
1399            )),
1400            ast::PathStart::Relative => None,
1401        };
1402        for step in steps {
1403            let (rhs, rhs_props) = match step {
1404                PathStep::Ast(ast::Step::Axis(axis_step)) => {
1405                    self.axis_step(node_axis(axis_step.axis), axis_step)?
1406                }
1407                PathStep::Descendant(axis_step) => {
1408                    self.axis_step(NodeAxis::Descendant, axis_step)?
1409                }
1410                PathStep::Ast(ast::Step::Expr(e)) => {
1411                    let focus = acc.as_ref().map_or(self.focus, |(_, p)| p.ty);
1412                    self.with_focus(focus, |c| c.expr(e))?
1413                }
1414            };
1415            acc = Some(match acc {
1416                None => (rhs, rhs_props),
1417                Some((lhs, lhs_props)) => Self::slash(lhs, lhs_props, rhs, rhs_props),
1418            });
1419        }
1420        acc.ok_or_else(|| Error::new(ErrorCode::Internal, "empty path"))
1421    }
1422
1423    fn axis_step(&mut self, axis: NodeAxis, step: &ast::AxisStep) -> Result<(Expr, Props)> {
1424        let test = node_test(&step.test, axis);
1425        let ty = StaticType::of_test(&test);
1426        let predicates = self.with_focus(Typing::of(ty), |c| c.predicates(&step.predicates))?;
1427        let props = step_props(axis, &test, &predicates).typed(ty);
1428        Ok((
1429            Expr::Step(Box::new(Step {
1430                axis,
1431                test,
1432                predicates,
1433            })),
1434            props,
1435        ))
1436    }
1437
1438    fn slash(lhs: Expr, lp: Props, rhs: Expr, rp: Props) -> (Expr, Props) {
1439        let axis = step_axis(&rhs);
1440        let rhs_kinds = if axis.is_some() {
1441            Kinds::Nodes
1442        } else {
1443            rp.kinds
1444        };
1445        let (mode, props) = match rhs_kinds {
1446            Kinds::Atomics => (
1447                PathMode::Atomic,
1448                Props::atomic(lp.max_one && rp.max_one, rp.class).typing(rp.ty),
1449            ),
1450            Kinds::Unknown => (
1451                PathMode::Dynamic,
1452                Props::unknown(lp.max_one && rp.max_one).typing(rp.ty),
1453            ),
1454            Kinds::Nodes => {
1455                let ordered = axis.is_some_and(|a| path_is_ordered(lp, a));
1456                let peer = if lp.max_one {
1457                    rp.peer
1458                } else {
1459                    lp.peer
1460                        && rp.peer
1461                        && matches!(
1462                            axis,
1463                            Some(NodeAxis::Child | NodeAxis::Attribute | NodeAxis::SelfAxis)
1464                        )
1465                };
1466                (
1467                    if ordered {
1468                        PathMode::Ordered
1469                    } else {
1470                        PathMode::Sort
1471                    },
1472                    Props::nodes(lp.max_one && rp.max_one, true, peer).typing(rp.ty),
1473                )
1474            }
1475        };
1476        let rhs_uses_last = calls_focus(&rhs, false);
1477        (
1478            Expr::Path {
1479                lhs: boxed(lhs),
1480                rhs: boxed(rhs),
1481                mode,
1482                rhs_uses_last,
1483            },
1484            props,
1485        )
1486    }
1487
1488    fn call(&mut self, name: &QName, args: &[ast::Expr]) -> Result<(Expr, Props)> {
1489        let builtin = functions::resolve(name, args.len(), self.context.xslt_functions())?;
1490        let Some(builtin) = builtin else {
1491            return match self.context.function(name, args.len()) {
1492                Some(id) => {
1493                    let args = args
1494                        .iter()
1495                        .map(|a| self.expr(a).map(|(e, _)| e))
1496                        .collect::<Result<_>>()?;
1497                    Ok((Expr::HostCall { id, args }, Props::unknown(false)))
1498                }
1499                None => err(
1500                    ErrorCode::Xpst0017,
1501                    format!(
1502                        "Cannot find a {}-argument function named {}{}",
1503                        args.len(),
1504                        name.namespace
1505                            .as_deref()
1506                            .map(|ns| format!("Q{{{ns}}}"))
1507                            .unwrap_or_default(),
1508                        name.local
1509                    ),
1510                ),
1511            };
1512        };
1513        let mut data = self.call_data(builtin, args)?;
1514        let mut compiled = Vec::with_capacity(args.len());
1515        let mut arg_props = Vec::with_capacity(args.len());
1516        for arg in args {
1517            let (e, p) = self.expr(arg)?;
1518            compiled.push(e);
1519            arg_props.push(p);
1520        }
1521        let many = builtin.returns_many();
1522        let props = match builtin.returns() {
1523            Returns::Boolean => Props::BOOLEAN,
1524            Returns::NonNumeric => {
1525                Props::atomic(!many, Class::NotNumeric).typed(StaticType::OtherAtomic)
1526            }
1527            Returns::Atomic => Props::atomic(!many, Class::Unknown),
1528            Returns::Nodes => Props::nodes(!many, !many, !many),
1529            Returns::Items => Props::unknown(!many),
1530        };
1531        let first = arg_props.first().copied();
1532        let ty = Typing {
1533            checked: call_type(builtin, first.map(|p| (p.ty.checked, p.one())))
1534                .unwrap_or(props.ty.checked),
1535            optimized: call_type(builtin, first.map(|p| (p.ty.optimized, p.one())))
1536                .unwrap_or(props.ty.optimized),
1537        };
1538        let constructor = matches!(
1539            builtin,
1540            Builtin::XsDecimal | Builtin::XsDate | Builtin::XsInteger | Builtin::XsString
1541        );
1542        let one = if constructor {
1543            first.is_some_and(|p| p.one())
1544        } else {
1545            builtin.exactly_one()
1546        };
1547        if builtin == Builtin::XsDecimal && first.is_some_and(|p| p.ty.upcasts_to_decimal()) {
1548            data = CallData::Upcast;
1549        }
1550        // A cast of a literal is folded (other calls are not: no `CONSTANT_FOLDING`).
1551        let props = props.typing(ty).exactly_one(one).literal(
1552            constructor && first.is_some_and(|p| p.is_literal()),
1553            constructor && first.is_some_and(|p| p.folds()),
1554        );
1555        Ok((
1556            Expr::Call {
1557                function: builtin,
1558                args: compiled,
1559                data,
1560            },
1561            props,
1562        ))
1563    }
1564
1565    fn call_data(&self, builtin: Builtin, args: &[ast::Expr]) -> Result<CallData> {
1566        let literal = |i: usize| match args.get(i) {
1567            Some(ast::Expr::Literal(ast::Literal::String(s))) => Some(s.as_str()),
1568            _ => None,
1569        };
1570        match builtin {
1571            Builtin::Matches | Builtin::Replace | Builtin::Tokenize => {
1572                let flags_at = if builtin == Builtin::Replace { 3 } else { 2 };
1573                let flags = if args.len() > flags_at {
1574                    literal(flags_at)
1575                } else {
1576                    Some("")
1577                };
1578                Ok(match (literal(1), flags) {
1579                    (Some(pattern), Some(flags)) => CallData::Regex(Arc::new(
1580                        XPathRegex::new(pattern, flags).map_err(Error::from),
1581                    )),
1582                    _ => CallData::None,
1583                })
1584            }
1585            Builtin::SystemProperty => {
1586                let Some(text) = literal(0) else {
1587                    return err(
1588                        ErrorCode::Unsupported,
1589                        "system-property() with an argument that is not a string literal",
1590                    );
1591                };
1592                self.property_name(text.trim()).map(CallData::Property)
1593            }
1594            _ => Ok(CallData::None),
1595        }
1596    }
1597
1598    fn property_name(&self, text: &str) -> Result<QName> {
1599        let invalid = || {
1600            Error::new(
1601                ErrorCode::Xtde1390,
1602                format!("Invalid QName {text:?} in system-property()"),
1603            )
1604        };
1605        match text.split_once(':') {
1606            None if einvoice_xpath::is_ncname(text) => Ok(QName::local(text)),
1607            Some((prefix, local))
1608                if einvoice_xpath::is_ncname(prefix) && einvoice_xpath::is_ncname(local) =>
1609            {
1610                let namespace = self.context.namespace_uri(prefix).ok_or_else(invalid)?;
1611                Ok(QName {
1612                    prefix: Some(prefix.to_owned()),
1613                    namespace: Some(namespace),
1614                    local: local.to_owned(),
1615                })
1616            }
1617            _ => Err(invalid()),
1618        }
1619    }
1620}
1621
1622fn literal_value(literal: &ast::Literal) -> Result<(Expr, Props)> {
1623    let (value, class) = match literal {
1624        ast::Literal::String(s) => (AtomicValue::String(s.clone()), Class::NotNumeric),
1625        ast::Literal::Integer(text) => {
1626            (AtomicValue::Integer(Integer::parse(text)?), Class::Unknown)
1627        }
1628        ast::Literal::Decimal(text) => {
1629            (AtomicValue::Decimal(Decimal::parse(text)?), Class::Unknown)
1630        }
1631        ast::Literal::Double(text) => (AtomicValue::Double(parse_double(text)?), Class::Unknown),
1632    };
1633    let ty = StaticType::of_atomic(value.atomic_type());
1634    Ok((
1635        Expr::Literal(value),
1636        Props::atomic(true, class)
1637            .typed(ty)
1638            .exactly_one(true)
1639            .literal(true, true),
1640    ))
1641}
1642
1643/// The static type of a call to a built-in function, when it does not follow from what
1644/// the function returns: `first` is the type of the first argument and whether it is
1645/// exactly one item.
1646fn call_type(builtin: Builtin, first: Option<(StaticType, bool)>) -> Option<StaticType> {
1647    let arg = first.map_or(StaticType::Unknown, |(t, _)| t);
1648    Some(match builtin {
1649        Builtin::Count
1650        | Builtin::StringLength
1651        | Builtin::Position
1652        | Builtin::Last
1653        | Builtin::StringToCodepoints
1654        | Builtin::XsInteger => StaticType::Integer,
1655        Builtin::Number => StaticType::Double,
1656        Builtin::XsDecimal => StaticType::Decimal,
1657        // `Sum.getResultItemType`.
1658        Builtin::Sum => {
1659            let base = arg.numeric();
1660            if first.is_some_and(|(_, one)| one) {
1661                base
1662            } else {
1663                base.union(StaticType::Integer)
1664            }
1665        }
1666        // AS_PRIM_ARG0: the atomized type of the argument, untyped as double.
1667        Builtin::Round | Builtin::Abs => arg.negated(),
1668        // AS_ARG0.
1669        Builtin::Reverse => arg,
1670        Builtin::DistinctValues | Builtin::Current => StaticType::Unknown,
1671        Builtin::Document => StaticType::UntypedNodes,
1672        _ => return None,
1673    })
1674}
1675
1676/// Whether a predicate depends on more than the focus (`current()`, the current date
1677/// and time, `document()`), so that Saxon does not fold the filter.
1678fn depends_on_more_than_focus(expr: &Expr) -> bool {
1679    let any = |items: &[Expr]| items.iter().any(depends_on_more_than_focus);
1680    let preds = |predicates: &[Predicate]| {
1681        predicates
1682            .iter()
1683            .any(|p| depends_on_more_than_focus(&p.expr))
1684    };
1685    match expr {
1686        Expr::Call { function, args, .. } => {
1687            matches!(
1688                function,
1689                Builtin::Current | Builtin::CurrentDateTime | Builtin::Document
1690            ) || any(args)
1691        }
1692        Expr::Literal(_) | Expr::ContextItem | Expr::Root | Expr::Local(_) | Expr::External(_) => {
1693            false
1694        }
1695        Expr::HostCall { args, .. } | Expr::Sequence(args) => any(args),
1696        Expr::Filter { base, predicates } => depends_on_more_than_focus(base) || preds(predicates),
1697        Expr::Step(step) => preds(&step.predicates),
1698        Expr::Path { lhs, rhs, .. }
1699        | Expr::Union { lhs, rhs, .. }
1700        | Expr::Arithmetic { lhs, rhs, .. }
1701        | Expr::Range(lhs, rhs)
1702        | Expr::GeneralComparison { lhs, rhs, .. }
1703        | Expr::ValueComparison { lhs, rhs, .. }
1704        | Expr::And(lhs, rhs)
1705        | Expr::Or(lhs, rhs)
1706        | Expr::For {
1707            sequence: lhs,
1708            body: rhs,
1709        }
1710        | Expr::Quantified {
1711            sequence: lhs,
1712            satisfies: rhs,
1713            ..
1714        } => depends_on_more_than_focus(lhs) || depends_on_more_than_focus(rhs),
1715        Expr::Negate(e)
1716        | Expr::InstanceOf { operand: e, .. }
1717        | Expr::Castable { operand: e, .. } => depends_on_more_than_focus(e),
1718        Expr::If {
1719            condition,
1720            then,
1721            otherwise,
1722        } => {
1723            depends_on_more_than_focus(condition)
1724                || depends_on_more_than_focus(then)
1725                || depends_on_more_than_focus(otherwise)
1726        }
1727    }
1728}
1729
1730#[cfg(test)]
1731mod tests {
1732    use super::*;
1733    use crate::context::SimpleStaticContext;
1734    use einvoice_xpath::{NamespaceMap, XS_NAMESPACE, parse_expr};
1735
1736    /// The static types of an expression, and whether it is an up-casting `xs:decimal`.
1737    fn typing(text: &str) -> (Typing, bool) {
1738        let ns = NamespaceMap::new().bind("xs", XS_NAMESPACE);
1739        let context = SimpleStaticContext::new();
1740        let mut compiler = Compiler {
1741            context: &context,
1742            locals: Vec::new(),
1743            focus: Typing::of(StaticType::Unknown),
1744        };
1745        let (expr, props) = compiler.expr(&parse_expr(text, &ns).unwrap()).unwrap();
1746        let upcast = matches!(
1747            expr,
1748            Expr::Call {
1749                function: Builtin::XsDecimal,
1750                data: CallData::Upcast,
1751                ..
1752            }
1753        );
1754        (props.ty, upcast)
1755    }
1756
1757    #[test]
1758    fn calculator_result_types() {
1759        use StaticType::{Decimal, Double, Integer, Unknown, UntypedAtomic};
1760        let t = StaticType::arithmetic;
1761        assert_eq!(t(ops::ArithmeticOp::Add, Integer, Integer), Integer);
1762        assert_eq!(t(ops::ArithmeticOp::Divide, Integer, Integer), Decimal);
1763        assert_eq!(
1764            t(ops::ArithmeticOp::IntegerDivide, Decimal, Integer),
1765            Integer
1766        );
1767        assert_eq!(
1768            t(ops::ArithmeticOp::IntegerDivide, UntypedAtomic, Integer),
1769            Integer
1770        );
1771        assert_eq!(
1772            t(ops::ArithmeticOp::Multiply, UntypedAtomic, Integer),
1773            Double
1774        );
1775        assert_eq!(t(ops::ArithmeticOp::Subtract, Decimal, Integer), Decimal);
1776        assert_eq!(t(ops::ArithmeticOp::Add, Unknown, Integer), Unknown);
1777        assert_eq!(Integer.union(Decimal), Decimal);
1778        assert_eq!(Integer.union(Double), Unknown);
1779        assert_eq!(StaticType::Empty.union(Integer), Integer);
1780    }
1781
1782    #[test]
1783    fn xs_decimal_upcasts_static_integers_only() {
1784        // Statically xs:integer: up-cast.
1785        assert!(typing("xs:decimal(300)").1);
1786        assert!(typing("xs:decimal(count(//a) * 100)").1);
1787        assert!(
1788            typing("xs:decimal(3000 div 10)").1,
1789            "literal arithmetic is folded"
1790        );
1791        assert!(
1792            typing("xs:decimal((300, 'a')[1])").1,
1793            "folded when optimized"
1794        );
1795        // Statically decimal, unknown or untyped: the converter of the run time.
1796        assert!(!typing("xs:decimal(count(//a) * 1000 div 10)").1);
1797        assert!(!typing("xs:decimal((300, 2.5)[1])").1);
1798        assert!(!typing("xs:decimal(if (true()) then 300 else 'a')").1);
1799        assert!(!typing("xs:decimal(sum((150, 150)) div 1)").1);
1800        assert!(!typing("xs:decimal(//a)").1);
1801        assert!(!typing("xs:decimal(('a', 300)[2])").1);
1802        assert_eq!(typing("(300, 'a')[1]").0.checked, StaticType::Unknown);
1803        assert_eq!(typing("(300, 'a')[1]").0.optimized, StaticType::Integer);
1804    }
1805}