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 (see [`StaticType`]): the constructor `xs:decimal` strips the trailing zeros of
16//! an argument that is statically an `xs:integer` and returns unchanged one that is
17//! statically an `xs:decimal` (an `xs:integer` value stays one); `div` of operands
18//! statically `xs:decimal` or `xs:integer`, not both `xs:integer`, is a decimal division
19//! even of two integer values ([`Calculator`]). The types of the host's variables and
20//! functions come from the static context ([`ValueType`]).
21
22use std::sync::Arc;
23
24use einvoice_xdm::{AtomicType, AtomicValue, Decimal, Integer, XPathRegex, ops, parse_double};
25use einvoice_xpath::{self as ast, AtomicKind, KindTest, NameOrWildcard, NameTest, QName};
26
27use crate::context::{
28    Cardinality, Clock, Context, DynamicContext, FunctionId, NoHost, StaticContext, VariableId,
29    VariableInfo,
30};
31use crate::error::{Error, ErrorCode, Result, err};
32use crate::functions::{self, Builtin, Returns};
33use crate::item::Item;
34use crate::tree::{Document, NodeAxis, NodeKind};
35
36/// A compiled expression.
37#[derive(Debug, Clone)]
38pub(crate) enum Expr {
39    Literal(AtomicValue),
40    ContextItem,
41    /// `/`: the document node of the context node's tree.
42    Root,
43    /// A range variable of `for`, `some`, `every`: its distance from the innermost one.
44    Local(usize),
45    External(VariableId),
46    Sequence(Vec<Expr>),
47    Filter {
48        base: Box<Expr>,
49        predicates: Vec<Predicate>,
50    },
51    Step(Box<Step>),
52    Path {
53        lhs: Box<Expr>,
54        rhs: Box<Expr>,
55        mode: PathMode,
56        /// Whether `rhs` reads the context size, so that `lhs` must be counted first.
57        rhs_uses_last: bool,
58    },
59    /// `lhs | rhs`; each flag says whether that operand is known to deliver document
60    /// order without duplicates (it is read lazily) or not (it is sorted first).
61    Union {
62        lhs: Box<Expr>,
63        rhs: Box<Expr>,
64        lhs_ordered: bool,
65        rhs_ordered: bool,
66    },
67    Negate(Box<Expr>),
68    Arithmetic {
69        op: ops::ArithmeticOp,
70        lhs: Box<Expr>,
71        rhs: Box<Expr>,
72        calculator: Calculator,
73    },
74    Range(Box<Expr>, Box<Expr>),
75    GeneralComparison {
76        op: ops::ComparisonOp,
77        lhs: Box<Expr>,
78        rhs: Box<Expr>,
79        strategy: CompareStrategy,
80    },
81    ValueComparison {
82        op: ops::ComparisonOp,
83        lhs: Box<Expr>,
84        rhs: Box<Expr>,
85    },
86    And(Box<Expr>, Box<Expr>),
87    Or(Box<Expr>, Box<Expr>),
88    If {
89        condition: Box<Expr>,
90        then: Box<Expr>,
91        otherwise: Box<Expr>,
92    },
93    For {
94        sequence: Box<Expr>,
95        body: Box<Expr>,
96    },
97    Quantified {
98        every: bool,
99        sequence: Box<Expr>,
100        satisfies: Box<Expr>,
101    },
102    InstanceOf {
103        operand: Box<Expr>,
104        item: ItemTest,
105        occurrence: ast::Occurrence,
106    },
107    Castable {
108        operand: Box<Expr>,
109        target: AtomicType,
110        allows_empty: bool,
111    },
112    /// `operand cast as target` (`?` when `allows_empty`). `upcast` as for
113    /// [`CallData::Upcast`]: an `xs:decimal` target and an operand statically typed
114    /// `xs:integer`.
115    Cast {
116        operand: Box<Expr>,
117        target: AtomicType,
118        allows_empty: bool,
119        upcast: bool,
120    },
121    Call {
122        function: Builtin,
123        args: Vec<Expr>,
124        data: CallData,
125    },
126    HostCall {
127        id: FunctionId,
128        args: Vec<Expr>,
129    },
130}
131
132/// What a call to a built-in function needs beyond its arguments.
133#[derive(Debug, Clone)]
134pub(crate) enum CallData {
135    None,
136    /// The regular expression of `matches`, `replace` or `tokenize` when pattern and
137    /// flags are literals, compiled once (an invalid one is reported when called).
138    Regex(Arc<std::result::Result<XPathRegex, Error>>),
139    /// The property named by the literal argument of `system-property`.
140    Property(QName),
141    /// `xs:decimal` of an argument whose static type is `xs:integer`: Saxon-HE 12.10
142    /// casts it with its up-casting converter, which strips the trailing zeros
143    /// (`AtomicValue::upcast`), where the cast of an operand typed at run time keeps
144    /// scale 0.
145    Upcast,
146    /// `xs:decimal` of an argument whose static type is `xs:decimal`: Saxon-HE 12.10
147    /// removes the cast (`CastExpression.typeCheck`, the operand and the target are the
148    /// same type), so the value is returned unchanged, an `xs:integer` included.
149    Unchanged,
150}
151
152/// How an arithmetic operation computes, chosen from the static types of its operands
153/// as Saxon-HE 12.10 chooses its `Calculator`. Only the choices that can give another
154/// result than the routine chosen from the operands' values are kept apart.
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub(crate) enum Calculator {
157    /// From the types of the operands' values ([`ops::arithmetic`]), as Saxon's
158    /// `AnyDivAny` and the calculators that compute the same.
159    Dynamic,
160    /// `div` of operands statically `xs:decimal` or `xs:integer`, not both
161    /// `xs:integer` (`DecimalDivDecimal`): a decimal division even of two integer
162    /// values, each taken at scale 0, so never an `xs:integer` and never the scale of
163    /// an integer division (which strips a 64-bit operand Saxon does not hold as an
164    /// `int`, a negative one for instance).
165    DecimalDivide,
166}
167
168/// An axis step.
169#[derive(Debug, Clone)]
170pub(crate) struct Step {
171    pub(crate) axis: NodeAxis,
172    pub(crate) test: NodeTest,
173    pub(crate) predicates: Vec<Predicate>,
174}
175
176/// A predicate, with how its value is to be read.
177#[derive(Debug, Clone)]
178pub(crate) struct Predicate {
179    pub(crate) expr: Expr,
180    pub(crate) kind: PredicateKind,
181    /// Whether the predicate reads the context size (`last()`), so that the sequence it
182    /// filters must be counted first.
183    pub(crate) uses_last: bool,
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub(crate) enum PredicateKind {
188    /// An integer literal: keeps the item at that position (`None`: at no position).
189    Position(Option<usize>),
190    /// A value that is never numeric: its effective boolean value decides.
191    Boolean,
192    /// Numeric (a position) or not (an effective boolean value), known at run time.
193    Dynamic,
194}
195
196/// How the result of `lhs/rhs` is assembled.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub(crate) enum PathMode {
199    /// Nodes, already in document order without duplicates: concatenated lazily.
200    Ordered,
201    /// Nodes in an unknown order: sorted, duplicates removed.
202    Sort,
203    /// Atomic values: concatenated lazily.
204    Atomic,
205    /// Unknown until run time: nodes are sorted, atomic values kept, a mix is an error.
206    Dynamic,
207}
208
209/// Which operand of a general comparison is read first (Saxon's comparison
210/// cardinalities).
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub(crate) enum CompareStrategy {
213    /// Both at most one item: the left one first; an empty one gives false.
214    OneToOne,
215    /// The right one is at most one item: it is evaluated first, then the left one read.
216    ManyToOne,
217    /// The left one is at most one item: it is evaluated first, then the right one read.
218    OneToMany,
219    /// Items read from each side in turn, each compared with those read from the other.
220    ManyToMany,
221}
222
223/// A node test.
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub(crate) enum NodeTest {
226    AnyNode,
227    Kind(NodeKind),
228    Named { kind: NodeKind, name: NameMatch },
229}
230
231#[derive(Debug, Clone, PartialEq, Eq)]
232pub(crate) enum NameMatch {
233    Any,
234    Exact {
235        namespace: Option<String>,
236        local: String,
237    },
238    Namespace(String),
239    Local(String),
240}
241
242impl NodeTest {
243    pub(crate) fn matches(&self, doc: &Document, index: u32) -> bool {
244        let kind = doc.kind(index);
245        match self {
246            Self::AnyNode => true,
247            Self::Kind(k) => kind == *k,
248            Self::Named { kind: k, name } => {
249                if kind != *k {
250                    return false;
251                }
252                let Some(node_name) = doc.name(index) else {
253                    return false;
254                };
255                match name {
256                    NameMatch::Any => true,
257                    NameMatch::Exact { namespace, local } => {
258                        node_name.local == *local && node_name.namespace == *namespace
259                    }
260                    NameMatch::Namespace(namespace) => {
261                        node_name.namespace.as_deref() == Some(namespace.as_str())
262                    }
263                    NameMatch::Local(local) => node_name.local == *local,
264                }
265            }
266        }
267    }
268}
269
270/// The item type of `instance of`.
271#[derive(Debug, Clone)]
272pub(crate) enum ItemTest {
273    Atomic(AtomicType),
274    Node(NodeTest),
275}
276
277/// What is known of the items of a value.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279enum Kinds {
280    Nodes,
281    Atomics,
282    Unknown,
283}
284
285/// What is known of a value, for the predicates it may appear in.
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
287enum Class {
288    /// Never a single numeric value: its effective boolean value decides.
289    NotNumeric,
290    /// May be numeric.
291    Unknown,
292}
293
294/// The static item type of a value as Saxon-HE 12.10 infers it (`getItemType`), reduced
295/// to the distinctions that can change a result. It decides two things: how
296/// `xs:decimal` casts its argument, with the up-casting converter (trailing zeros
297/// stripped) for an `xs:integer`, not at all for an `xs:decimal` (Saxon removes the cast),
298/// with the converter chosen at run time otherwise (scale 0 kept for an integer); and the
299/// calculator of arithmetic ([`Calculator`]). The rules are Saxon's:
300///
301/// * literals have their type, and so have the expressions Saxon-HE folds into literals
302///   (its optimizer option `CONSTANT_FOLDING` is off, so only a few): unary minus of a
303///   literal and sequences of literals when parsed, arithmetic on two literals and casts
304///   of a literal when type-checked, and, when optimized, filters of a literal sequence
305///   that depend on the focus only (after which what contains them is type-checked
306///   again, see [`Typing`]); function calls and `if` are not folded;
307/// * `count`, `string-length`, `position`, `last`, `string-to-codepoints`, `to`,
308///   `xs:integer` give integers; `number` doubles; `xs:decimal` decimals, unless the cast
309///   is removed (it then has the type of its argument); `distinct-values` anything; host
310///   functions and variables the type the host gives ([`ValueType`]);
311/// * arithmetic follows Saxon's calculators: untyped operands count as doubles, any
312///   double operand gives a double, any decimal one a decimal, two integers an integer,
313///   except that `div` of two integers is a decimal and `idiv` always an integer; an
314///   operand of unknown type makes the result unknown;
315/// * `sum` gives the common type of its atomized argument (doubles for untyped values)
316///   and `xs:integer`, or the argument's type when it is exactly one item; `round`
317///   and `abs` the type of their argument; `reverse`, filters, unary minus, `for` and
318///   the range variables keep the type of their operand; `if` and sequences the
319///   common super type of their branches or items (`()` aside), integer and decimal
320///   giving decimal and any other mix giving anything;
321/// * a filter `E[. instance of T]` has type `T`, unless the items of `E` are known to be
322///   of type `T` (the test is then folded into `true()`);
323/// * elements, attributes, text and document nodes atomize to untyped values (Saxon-HE
324///   has no schema), comments and processing instructions to strings.
325///
326/// The context item at the top of an expression is of unknown type (the host knows
327/// it); inside a predicate or on the right of `/` it has the type of the items it
328/// ranges over. Saxon computes these types at several moments of the compilation of a
329/// stylesheet, which [`Typing`] keeps apart.
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
331pub(crate) enum StaticType {
332    /// No item: the empty sequence (Saxon's `ErrorType`), neutral in a common type.
333    Empty,
334    Integer,
335    Decimal,
336    Double,
337    UntypedAtomic,
338    /// A non-numeric atomic type: string, boolean, anyURI, date or dateTime.
339    OtherAtomic,
340    /// Elements, attributes, text or document nodes: their typed value is untyped.
341    UntypedNodes,
342    /// Comments or processing instructions: their typed value is a string.
343    StringNodes,
344    /// Nodes of kinds from both groups above, or of any kind.
345    Nodes,
346    /// Any item, any atomic value, any number.
347    Unknown,
348}
349
350impl StaticType {
351    /// The common super type (`Type.getCommonSuperType`).
352    const fn union(self, other: Self) -> Self {
353        match (self, other) {
354            (Self::Empty, t) | (t, Self::Empty) => t,
355            (Self::Integer, Self::Integer) => Self::Integer,
356            (Self::Integer | Self::Decimal, Self::Integer | Self::Decimal) => Self::Decimal,
357            (Self::Double, Self::Double) => Self::Double,
358            (Self::UntypedAtomic, Self::UntypedAtomic) => Self::UntypedAtomic,
359            (Self::OtherAtomic, Self::OtherAtomic) => Self::OtherAtomic,
360            (Self::UntypedNodes, Self::UntypedNodes) => Self::UntypedNodes,
361            (Self::StringNodes, Self::StringNodes) => Self::StringNodes,
362            (
363                Self::UntypedNodes | Self::StringNodes | Self::Nodes,
364                Self::UntypedNodes | Self::StringNodes | Self::Nodes,
365            ) => Self::Nodes,
366            _ => Self::Unknown,
367        }
368    }
369
370    /// The type of the atomized items (`Atomizer`, nodes untyped).
371    const fn atomized(self) -> Self {
372        match self {
373            Self::UntypedNodes => Self::UntypedAtomic,
374            Self::StringNodes => Self::OtherAtomic,
375            Self::Nodes => Self::Unknown,
376            t => t,
377        }
378    }
379
380    /// The type of an operand of arithmetic, `round`, `abs` or `sum`: atomized,
381    /// untyped values converted to doubles.
382    const fn numeric(self) -> Self {
383        match self.atomized() {
384            Self::UntypedAtomic => Self::Double,
385            t => t,
386        }
387    }
388
389    /// The type of `a op b`: the result type of Saxon's calculator for the operand
390    /// types (`Calculator.getResultType`), unknown when there is no specific one.
391    const fn arithmetic(op: ops::ArithmeticOp, a: Self, b: Self) -> Self {
392        let (a, b) = (a.numeric(), b.numeric());
393        let idiv = matches!(op, ops::ArithmeticOp::IntegerDivide);
394        match (a, b) {
395            (Self::Empty, _) | (_, Self::Empty) => Self::Empty,
396            (Self::Double, Self::Integer | Self::Decimal | Self::Double)
397            | (Self::Integer | Self::Decimal, Self::Double) => {
398                if idiv {
399                    Self::Integer
400                } else {
401                    Self::Double
402                }
403            }
404            (Self::Decimal, Self::Integer | Self::Decimal) | (Self::Integer, Self::Decimal) => {
405                if idiv {
406                    Self::Integer
407                } else {
408                    Self::Decimal
409                }
410            }
411            (Self::Integer, Self::Integer) => {
412                if matches!(op, ops::ArithmeticOp::Divide) {
413                    Self::Decimal
414                } else {
415                    Self::Integer
416                }
417            }
418            _ => Self::Unknown,
419        }
420    }
421
422    /// The type of the items of a value.
423    fn of_items(items: &[Item]) -> Self {
424        items.iter().fold(Self::Empty, |t, item| {
425            t.union(match item {
426                Item::Node(node) => match node.kind() {
427                    NodeKind::Comment | NodeKind::ProcessingInstruction => Self::StringNodes,
428                    _ => Self::UntypedNodes,
429                },
430                Item::Atomic(value) => Self::of_atomic(value.atomic_type()),
431            })
432        })
433    }
434
435    const fn of_atomic(t: AtomicType) -> Self {
436        match t {
437            AtomicType::Integer => Self::Integer,
438            AtomicType::Decimal => Self::Decimal,
439            AtomicType::Double => Self::Double,
440            AtomicType::UntypedAtomic => Self::UntypedAtomic,
441            _ => Self::OtherAtomic,
442        }
443    }
444
445    /// The type of the nodes a node test selects.
446    const fn of_test(test: &NodeTest) -> Self {
447        match test {
448            NodeTest::AnyNode => Self::Nodes,
449            NodeTest::Kind(NodeKind::Comment | NodeKind::ProcessingInstruction) => {
450                Self::StringNodes
451            }
452            NodeTest::Kind(_) | NodeTest::Named { .. } => Self::UntypedNodes,
453        }
454    }
455
456    /// Whether every item of this type is of type `t` (for `. instance of t`).
457    const fn subsumed_by(self, t: Self) -> bool {
458        matches!(
459            (self, t),
460            (Self::Integer, Self::Integer | Self::Decimal)
461                | (Self::Decimal, Self::Decimal)
462                | (Self::Double, Self::Double)
463                | (Self::OtherAtomic, Self::OtherAtomic)
464                | (Self::UntypedNodes, Self::UntypedNodes)
465                | (Self::StringNodes, Self::StringNodes)
466        )
467    }
468
469    /// Whether every value of this type is of type `other` (`TypeHierarchy.isSubType`):
470    /// the empty sequence is of every type, every value of the unknown type.
471    const fn is_subtype(self, other: Self) -> bool {
472        matches!(
473            (self, other),
474            (Self::Empty, _)
475                | (_, Self::Unknown)
476                | (Self::Integer, Self::Integer | Self::Decimal)
477                | (Self::Decimal, Self::Decimal)
478                | (Self::Double, Self::Double)
479                | (Self::UntypedAtomic, Self::UntypedAtomic)
480                | (Self::OtherAtomic, Self::OtherAtomic)
481                | (Self::UntypedNodes, Self::UntypedNodes | Self::Nodes)
482                | (Self::StringNodes, Self::StringNodes | Self::Nodes)
483                | (Self::Nodes, Self::Nodes)
484        )
485    }
486
487    /// The type of `-x` (`NegateExpression`: the primitive type of the operand).
488    const fn negated(self) -> Self {
489        match self.numeric() {
490            t @ (Self::Empty | Self::Integer | Self::Decimal | Self::Double) => t,
491            _ => Self::Unknown,
492        }
493    }
494}
495
496/// The static item type of a value at the moments Saxon-HE 12.10 computes it, in an XSLT
497/// stylesheet (in a plain expression, only the references to variables and host
498/// functions tell them apart).
499///
500/// * `parsed`: before type checking (`getItemType` of the parsed expression), the type
501///   from which Saxon infers the type of a variable (`SourceBinding.getInferredType`).
502///   Arithmetic has no calculator yet and is of unknown type, a reference to a range
503///   variable, to a host function or to a global variable declared later too, and the
504///   context item is of unknown type.
505/// * `first`: when an instruction's expression is type-checked on its own
506///   (`StyleElement.typeCheck`), variables being of their inferred type. A cast to
507///   `xs:decimal` of a value then statically `xs:decimal` is removed for good.
508/// * `checked`: when the body of the template or function is type-checked
509///   (`XSLTemplate.optimize`), local variables being of the type of their type-checked
510///   value (`LetExpression.typeCheck`). A cast chooses its converter here: an argument of
511///   `xs:decimal` of type `xs:integer` gets the up-casting converter, one of type
512///   `xs:decimal` is returned unchanged, one of unknown type gets no converter (it is
513///   chosen at run time); and arithmetic its calculator.
514/// * `optimized`: after optimization, which folds the filters of literal sequences and
515///   inlines the variables whose value has become a literal: an expression that contains
516///   such a literal is type-checked again, so that a cast without a converter then gets
517///   the up-casting one if its argument has become a literal integer, and arithmetic
518///   chooses its calculator again.
519#[derive(Debug, Clone, Copy, PartialEq, Eq)]
520pub(crate) struct Typing {
521    parsed: StaticType,
522    first: StaticType,
523    checked: StaticType,
524    optimized: StaticType,
525}
526
527impl Default for Typing {
528    fn default() -> Self {
529        Self::of(StaticType::Unknown)
530    }
531}
532
533impl Typing {
534    const fn of(t: StaticType) -> Self {
535        Self {
536            parsed: t,
537            first: t,
538            checked: t,
539            optimized: t,
540        }
541    }
542
543    const fn union(self, other: Self) -> Self {
544        Self {
545            parsed: self.parsed.union(other.parsed),
546            first: self.first.union(other.first),
547            checked: self.checked.union(other.checked),
548            optimized: self.optimized.union(other.optimized),
549        }
550    }
551
552    fn map(self, f: impl Fn(StaticType) -> StaticType) -> Self {
553        Self {
554            parsed: f(self.parsed),
555            first: f(self.first),
556            checked: f(self.checked),
557            optimized: f(self.optimized),
558        }
559    }
560
561    fn zip(self, other: Self, f: impl Fn(StaticType, StaticType) -> StaticType) -> Self {
562        Self {
563            parsed: f(self.parsed, other.parsed),
564            first: f(self.first, other.first),
565            checked: f(self.checked, other.checked),
566            optimized: f(self.optimized, other.optimized),
567        }
568    }
569
570    /// The same, of unknown type before type checking.
571    const fn unparsed(self) -> Self {
572        Self {
573            parsed: StaticType::Unknown,
574            ..self
575        }
576    }
577
578    /// Whether Saxon casts a value of this type to `xs:decimal` with its up-casting
579    /// converter: an integer when type-checked, or of unknown type then and an integer
580    /// once optimized.
581    const fn upcasts_to_decimal(self) -> bool {
582        matches!(
583            (self.checked.atomized(), self.optimized.atomized()),
584            (StaticType::Integer, _) | (StaticType::Unknown, StaticType::Integer)
585        )
586    }
587
588    /// Whether Saxon removes the cast of a value of this type to `xs:decimal`
589    /// (`CastExpression.typeCheck`: same type): a decimal when an instruction's
590    /// expression is type-checked or when the body is (the cast is then gone, whatever
591    /// is found later), or of unknown type then and a decimal once optimized. This comes
592    /// before the up-casting converter: a cast removed when the value was typed
593    /// `xs:decimal` stays removed if it is typed `xs:integer` later.
594    const fn is_decimal(self) -> bool {
595        self.removes_cast_when_checked()
596            || matches!(
597                (self.checked.atomized(), self.optimized.atomized()),
598                (StaticType::Unknown, StaticType::Decimal)
599            )
600    }
601
602    /// Whether the cast to `xs:decimal` is removed by the time the body is type-checked.
603    const fn removes_cast_when_checked(self) -> bool {
604        matches!(self.first.atomized(), StaticType::Decimal)
605            || matches!(self.checked.atomized(), StaticType::Decimal)
606    }
607
608    /// The calculator Saxon chooses for `a op b` (`ArithmeticExpression.typeCheck`,
609    /// `Calculator.getCalculator`) from the primitive types of the operands, untyped
610    /// values counting as doubles. The types are those once optimized: an expression in
611    /// which the optimizer folded something is type-checked again, which chooses the
612    /// calculator again (and they are the types when type-checked otherwise).
613    fn calculator(op: ops::ArithmeticOp, a: Self, b: Self) -> Calculator {
614        use StaticType::{Decimal, Integer};
615        let (a, b) = (a.optimized.numeric(), b.optimized.numeric());
616        match (op, a, b) {
617            (ops::ArithmeticOp::Divide, Integer | Decimal, Decimal)
618            | (ops::ArithmeticOp::Divide, Decimal, Integer) => Calculator::DecimalDivide,
619            _ => Calculator::Dynamic,
620        }
621    }
622}
623
624/// Statically known properties of a value.
625#[derive(Debug, Clone, Copy)]
626struct Props {
627    max_one: bool,
628    kinds: Kinds,
629    class: Class,
630    /// Nodes in document order without duplicates.
631    ordered: bool,
632    /// No node is an ancestor of another (only meaningful with `ordered`).
633    peer: bool,
634    /// The static item type.
635    ty: Typing,
636    /// Whether it is statically exactly one item.
637    count: Count,
638    /// Whether Saxon folds it into a literal.
639    folding: Folding,
640}
641
642/// Whether a value is statically exactly one item (for `sum`).
643#[derive(Debug, Clone, Copy, PartialEq, Eq)]
644enum Count {
645    ExactlyOne,
646    Other,
647}
648
649impl Count {
650    const fn of(one: bool) -> Self {
651        if one { Self::ExactlyOne } else { Self::Other }
652    }
653}
654
655/// When Saxon-HE folds an expression into a literal.
656#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
657pub(crate) enum Folding {
658    #[default]
659    Never,
660    /// When optimizing.
661    Optimized,
662    /// When type checking (and so when optimizing too).
663    Checked,
664    /// When parsing: literals, unary minus of a literal, sequences of those (and so when
665    /// type checking and optimizing too).
666    Parsed,
667}
668
669impl Props {
670    const fn atomic(max_one: bool, class: Class) -> Self {
671        Self {
672            max_one,
673            kinds: Kinds::Atomics,
674            class,
675            ordered: false,
676            peer: false,
677            ty: Typing::of(StaticType::Unknown),
678            count: Count::Other,
679            folding: Folding::Never,
680        }
681    }
682
683    const BOOLEAN: Self = Self::atomic(true, Class::NotNumeric).typed(StaticType::OtherAtomic);
684
685    const fn unknown(max_one: bool) -> Self {
686        Self {
687            max_one,
688            kinds: Kinds::Unknown,
689            class: Class::Unknown,
690            ordered: max_one,
691            peer: max_one,
692            ty: Typing::of(StaticType::Unknown),
693            count: Count::Other,
694            folding: Folding::Never,
695        }
696    }
697
698    const fn nodes(max_one: bool, ordered: bool, peer: bool) -> Self {
699        Self {
700            max_one,
701            kinds: Kinds::Nodes,
702            class: Class::NotNumeric,
703            ordered,
704            peer,
705            ty: Typing::of(StaticType::Nodes),
706            count: Count::Other,
707            folding: Folding::Never,
708        }
709    }
710
711    const fn typed(self, ty: StaticType) -> Self {
712        Self {
713            ty: Typing::of(ty),
714            ..self
715        }
716    }
717
718    const fn typing(self, ty: Typing) -> Self {
719        Self { ty, ..self }
720    }
721
722    const fn exactly_one(self, one: bool) -> Self {
723        Self {
724            count: Count::of(one),
725            ..self
726        }
727    }
728
729    const fn one(&self) -> bool {
730        matches!(self.count, Count::ExactlyOne)
731    }
732
733    /// Whether Saxon folds it into a literal when type-checking, and when optimizing.
734    const fn literal(self, checked: bool, optimized: bool) -> Self {
735        Self {
736            folding: if checked {
737                Folding::Checked
738            } else if optimized {
739                Folding::Optimized
740            } else {
741                Folding::Never
742            },
743            ..self
744        }
745    }
746
747    const fn folded(self, folding: Folding) -> Self {
748        Self { folding, ..self }
749    }
750
751    /// A literal once type-checked.
752    const fn is_literal(&self) -> bool {
753        matches!(self.folding, Folding::Checked | Folding::Parsed)
754    }
755
756    /// A literal once optimized.
757    const fn folds(&self) -> bool {
758        !matches!(self.folding, Folding::Never)
759    }
760
761    /// Either of two values (the branches of `if`).
762    const fn either(a: Self, b: Self) -> Self {
763        Self {
764            max_one: a.max_one && b.max_one,
765            kinds: if matches!(
766                (a.kinds, b.kinds),
767                (Kinds::Nodes, Kinds::Nodes)
768                    | (Kinds::Atomics, Kinds::Atomics)
769                    | (Kinds::Unknown, Kinds::Unknown)
770            ) {
771                a.kinds
772            } else {
773                Kinds::Unknown
774            },
775            class: if matches!((a.class, b.class), (Class::NotNumeric, Class::NotNumeric)) {
776                Class::NotNumeric
777            } else {
778                Class::Unknown
779            },
780            ordered: a.ordered && b.ordered,
781            peer: a.peer && b.peer,
782            ty: a.ty.union(b.ty),
783            count: Count::of(a.one() && b.one()),
784            folding: Folding::Never,
785        }
786    }
787}
788
789/// An expression ready to be evaluated: functions and variables resolved against a
790/// static context. It holds no node and can be shared between threads.
791#[derive(Debug, Clone)]
792pub struct CompiledExpr {
793    pub(crate) expr: Expr,
794    max_one: bool,
795    /// Its static item type, as Saxon infers it.
796    ty: Typing,
797    /// When Saxon folds it into a literal ([`Folding::Never`] when the folding fails).
798    folding: Folding,
799    /// Its value when Saxon folds it.
800    constant: Option<Arc<[AtomicValue]>>,
801}
802
803impl CompiledExpr {
804    /// Whether the value is statically known to have at most one item.
805    #[must_use]
806    pub const fn is_at_most_one(&self) -> bool {
807        self.max_one
808    }
809
810    /// Whether it is `()`, which Saxon reads as no value for the type of a variable.
811    fn is_empty_sequence(&self) -> bool {
812        matches!(&self.expr, Expr::Sequence(items) if items.is_empty())
813    }
814}
815
816/// What is statically known of the value of a variable, or of the result of a host
817/// function, as Saxon-HE 12.10 infers it in a stylesheet: its item type at each moment of
818/// the compilation and, when Saxon replaces the references to the variable by a literal,
819/// its value. A reference compiled with it has that type, and is that literal (the same
820/// value as the variable's, which is then context-free).
821#[derive(Debug, Clone, Default)]
822pub struct ValueType {
823    pub(crate) ty: Typing,
824    folding: Folding,
825    constant: Option<Arc<[AtomicValue]>>,
826}
827
828/// What a variable is bound to, for [`ValueType::global_variable`] and
829/// [`ValueType::local_variable`].
830#[derive(Debug, Clone, Copy)]
831pub enum BindingValue<'a> {
832    /// The `select` expression, compiled.
833    Select(&'a CompiledExpr),
834    /// A sequence constructor: a temporary tree without `as`.
835    Content,
836    /// Neither: the empty string without `as`.
837    Absent,
838}
839
840/// The item type of a declared sequence type.
841fn declared_item_type(declared: &ast::SequenceType) -> StaticType {
842    match &declared.item {
843        ast::ItemType::Atomic(atomic) => StaticType::of_atomic(atomic_type(atomic.kind)),
844        ast::ItemType::Kind(kind) => StaticType::of_test(&kind_test(kind)),
845    }
846}
847
848/// The type of a value of type `actual` declared of type `declared`: the actual type
849/// when it is a subtype of the declared one, else the declared one
850/// (`SourceBinding.getInferredType`, and the type checking of a variable's value).
851fn narrowed(actual: StaticType, declared: Option<StaticType>) -> StaticType {
852    match declared {
853        Some(d) if !actual.is_subtype(d) => d,
854        _ => actual,
855    }
856}
857
858impl ValueType {
859    /// Nothing known: any value.
860    #[must_use]
861    pub fn unknown() -> Self {
862        Self::default()
863    }
864
865    /// The type of a parameter (of the stylesheet, of a template, of a function), or of the
866    /// result of a function: its declared type (`as`), whatever its default value, any
867    /// value without one.
868    #[must_use]
869    pub fn declared(as_type: Option<&ast::SequenceType>) -> Self {
870        Self {
871            ty: Typing::of(as_type.map_or(StaticType::Unknown, declared_item_type)),
872            ..Self::default()
873        }
874    }
875
876    /// The type of a global `xsl:variable` (not a parameter). Saxon infers it before type
877    /// checking anything (`SourceBinding.getInferredType`): the type of the parsed
878    /// `select` expression (arithmetic, a host function call and a reference to a global
879    /// declared later are then of unknown type), narrowed to the declared one, or the
880    /// declared type when the value is not a subtype of it. A literal `select` that is of
881    /// the declared type is a constant: the references are that literal.
882    #[must_use]
883    pub fn global_variable(value: BindingValue<'_>, as_type: Option<&ast::SequenceType>) -> Self {
884        let declared = as_type.map(declared_item_type);
885        let select = match value {
886            BindingValue::Select(select) => select,
887            // A temporary tree (a document node) without `as`.
888            BindingValue::Content => {
889                return Self {
890                    ty: Typing::of(declared.unwrap_or(StaticType::UntypedNodes)),
891                    ..Self::default()
892                };
893            }
894            // The empty string without `as`.
895            BindingValue::Absent => {
896                return Self {
897                    ty: Typing::of(declared.unwrap_or(StaticType::OtherAtomic)),
898                    ..Self::default()
899                };
900            }
901        };
902        let inferred = Self::inferred(select, declared);
903        if Self::constant_when_parsed(select, inferred) {
904            return Self::constant(select, inferred);
905        }
906        Self {
907            ty: Typing::of(inferred),
908            ..Self::default()
909        }
910    }
911
912    /// The type of a local `xsl:variable`. Saxon gives its references the type inferred
913    /// as for a global variable while the instructions are type-checked one by one,
914    /// then, when the body is, the type of the type-checked value (narrowed to the
915    /// declared type), if it is a subtype of the inferred one (`LetExpression.typeCheck`,
916    /// `VariableReference.refineVariableType`). The references are a literal when the
917    /// `select` is one when parsed, or once type-checked, or once optimized (the
918    /// optimizer then inlines it), if of the declared type.
919    #[must_use]
920    pub fn local_variable(value: BindingValue<'_>, as_type: Option<&ast::SequenceType>) -> Self {
921        let BindingValue::Select(select) = value else {
922            return Self::global_variable(value, as_type);
923        };
924        let declared = as_type.map(declared_item_type);
925        let inferred = Self::inferred(select, declared);
926        if Self::constant_when_parsed(select, inferred) {
927            return Self::constant(select, inferred);
928        }
929        let of_declared = |t: StaticType| declared.is_none_or(|d| t.is_subtype(d));
930        let folding = match select.folding {
931            Folding::Parsed | Folding::Checked if of_declared(select.ty.checked) => {
932                Folding::Checked
933            }
934            Folding::Optimized if of_declared(select.ty.optimized) => Folding::Optimized,
935            _ => Folding::Never,
936        };
937        let checked = narrowed(select.ty.checked, declared);
938        let refined = if checked.is_subtype(inferred) {
939            checked
940        } else {
941            inferred
942        };
943        let ty = Typing {
944            parsed: inferred,
945            first: inferred,
946            checked: refined,
947            optimized: refined,
948        };
949        match (folding, &select.constant) {
950            (Folding::Checked, Some(constant)) => Self {
951                ty: Typing {
952                    checked: select.ty.checked,
953                    optimized: select.ty.optimized,
954                    ..ty
955                },
956                folding,
957                constant: Some(Arc::clone(constant)),
958            },
959            (Folding::Optimized, Some(constant)) => Self {
960                ty: Typing {
961                    optimized: select.ty.optimized,
962                    ..ty
963                },
964                folding,
965                constant: Some(Arc::clone(constant)),
966            },
967            _ => Self {
968                ty,
969                ..Self::default()
970            },
971        }
972    }
973
974    /// The same value, referred to from a declaration that Saxon processes before this
975    /// global variable's (one earlier in the stylesheet): the reference is then of
976    /// unknown type for the inference of the type of a variable declared there.
977    #[must_use]
978    pub fn declared_later(&self) -> Self {
979        Self {
980            ty: self.ty.unparsed(),
981            ..self.clone()
982        }
983    }
984
985    /// The type Saxon infers for a variable before type checking.
986    fn inferred(select: &CompiledExpr, declared: Option<StaticType>) -> StaticType {
987        if select.is_empty_sequence() {
988            // `()`: the declared type, or any.
989            return declared.unwrap_or(StaticType::Unknown);
990        }
991        narrowed(select.ty.parsed, declared)
992    }
993
994    /// Whether the references are a literal from the start
995    /// (`SourceBinding.getConstantValue`): a literal of the inferred type.
996    fn constant_when_parsed(select: &CompiledExpr, inferred: StaticType) -> bool {
997        select.folding == Folding::Parsed
998            && select.constant.is_some()
999            && (select.is_empty_sequence() || select.ty.parsed.is_subtype(inferred))
1000    }
1001
1002    /// References that are the literal value of `select` from the start: of the inferred
1003    /// type before type checking, of the literal's type after.
1004    fn constant(select: &CompiledExpr, inferred: StaticType) -> Self {
1005        Self {
1006            ty: Typing {
1007                parsed: inferred,
1008                ..Typing::of(select.ty.checked)
1009            },
1010            folding: Folding::Parsed,
1011            constant: select.constant.clone(),
1012        }
1013    }
1014}
1015
1016/// Compiles an expression in a static context.
1017///
1018/// # Errors
1019///
1020/// `XPST0008` for a variable not in scope, `XPST0017` for an unknown function or arity,
1021/// `XTDE1390` for an invalid `system-property` name, [`ErrorCode::Unsupported`] for a
1022/// function of the specifications that is not implemented or a literal out of range.
1023pub fn compile(expr: &ast::Expr, context: &dyn StaticContext) -> Result<CompiledExpr> {
1024    let mut compiler = Compiler {
1025        context,
1026        locals: Vec::new(),
1027        focus: Typing::of(StaticType::Unknown),
1028    };
1029    let (expr, props) = compiler.expr(expr)?;
1030    let constant = if props.folds() {
1031        folded_values(&expr).map(Arc::from)
1032    } else {
1033        None
1034    };
1035    Ok(CompiledExpr {
1036        expr,
1037        max_one: props.max_one,
1038        ty: props.ty,
1039        folding: if constant.is_some() {
1040            props.folding
1041        } else {
1042            Folding::Never
1043        },
1044        constant,
1045    })
1046}
1047
1048struct Compiler<'a> {
1049    context: &'a dyn StaticContext,
1050    /// The range variables in scope, innermost last, with their static item type.
1051    locals: Vec<(QName, Typing)>,
1052    /// The static type of the context item.
1053    focus: Typing,
1054}
1055
1056/// The type of the value of an expression Saxon folds into a literal, evaluated as Saxon
1057/// does at compile time, or `None` when the evaluation fails (Saxon then keeps the
1058/// expression, and reports the error only if it is evaluated).
1059fn folded_type(expr: &Expr) -> Option<StaticType> {
1060    folded_items(expr).map(|items| StaticType::of_items(&items))
1061}
1062
1063/// The value of an expression Saxon folds into a literal, evaluated as Saxon does at
1064/// compile time; context-free, so the value it has at run time too.
1065fn folded_items(expr: &Expr) -> Option<Vec<Item>> {
1066    // Only literals, arithmetic and casts of literals, and filters of literal sequences
1067    // whose predicates depend on the focus only are folded: no clock is read, any does.
1068    let dc = DynamicContext::new(&NoHost, Clock::from_unix_millis(0, 0).ok()?);
1069    let compiled = CompiledExpr {
1070        expr: expr.clone(),
1071        max_one: false,
1072        ty: Typing::default(),
1073        folding: Folding::Never,
1074        constant: None,
1075    };
1076    compiled.evaluate(&dc, &Context::new()).ok()
1077}
1078
1079/// The atomic values of an expression Saxon folds into a literal (`None` when the
1080/// evaluation fails, or for a node, which no folded expression gives).
1081fn folded_values(expr: &Expr) -> Option<Vec<AtomicValue>> {
1082    folded_items(expr)?
1083        .into_iter()
1084        .map(|item| match item {
1085            Item::Atomic(value) => Some(value),
1086            Item::Node(_) => None,
1087        })
1088        .collect()
1089}
1090
1091/// Whether an expression refers to a variable or a host function anywhere
1092/// (`ExpressionTool.refersToVariableOrFunction`).
1093fn refers_to_variable_or_function(expr: &Expr) -> bool {
1094    let any = |items: &[Expr]| items.iter().any(refers_to_variable_or_function);
1095    let preds = |predicates: &[Predicate]| {
1096        predicates
1097            .iter()
1098            .any(|p| refers_to_variable_or_function(&p.expr))
1099    };
1100    match expr {
1101        Expr::Local(_) | Expr::External(_) | Expr::HostCall { .. } => true,
1102        Expr::Literal(_) | Expr::ContextItem | Expr::Root => false,
1103        Expr::Call { args, .. } | Expr::Sequence(args) => any(args),
1104        Expr::Filter { base, predicates } => {
1105            refers_to_variable_or_function(base) || preds(predicates)
1106        }
1107        Expr::Step(step) => preds(&step.predicates),
1108        Expr::Path { lhs, rhs, .. }
1109        | Expr::Union { lhs, rhs, .. }
1110        | Expr::Arithmetic { lhs, rhs, .. }
1111        | Expr::Range(lhs, rhs)
1112        | Expr::GeneralComparison { lhs, rhs, .. }
1113        | Expr::ValueComparison { lhs, rhs, .. }
1114        | Expr::And(lhs, rhs)
1115        | Expr::Or(lhs, rhs)
1116        | Expr::For {
1117            sequence: lhs,
1118            body: rhs,
1119        }
1120        | Expr::Quantified {
1121            sequence: lhs,
1122            satisfies: rhs,
1123            ..
1124        } => refers_to_variable_or_function(lhs) || refers_to_variable_or_function(rhs),
1125        Expr::Negate(e)
1126        | Expr::InstanceOf { operand: e, .. }
1127        | Expr::Castable { operand: e, .. }
1128        | Expr::Cast { operand: e, .. } => refers_to_variable_or_function(e),
1129        Expr::If {
1130            condition,
1131            then,
1132            otherwise,
1133        } => {
1134            refers_to_variable_or_function(condition)
1135                || refers_to_variable_or_function(then)
1136                || refers_to_variable_or_function(otherwise)
1137        }
1138    }
1139}
1140
1141fn boxed(e: Expr) -> Box<Expr> {
1142    Box::new(e)
1143}
1144
1145fn comparison_op(kind: ast::CompareKind) -> ops::ComparisonOp {
1146    match kind {
1147        ast::CompareKind::Eq => ops::ComparisonOp::Equal,
1148        ast::CompareKind::Ne => ops::ComparisonOp::NotEqual,
1149        ast::CompareKind::Lt => ops::ComparisonOp::Less,
1150        ast::CompareKind::Le => ops::ComparisonOp::LessOrEqual,
1151        ast::CompareKind::Gt => ops::ComparisonOp::Greater,
1152        ast::CompareKind::Ge => ops::ComparisonOp::GreaterOrEqual,
1153    }
1154}
1155
1156fn arithmetic_op(op: ast::ArithmeticOp) -> ops::ArithmeticOp {
1157    match op {
1158        ast::ArithmeticOp::Add => ops::ArithmeticOp::Add,
1159        ast::ArithmeticOp::Subtract => ops::ArithmeticOp::Subtract,
1160        ast::ArithmeticOp::Multiply => ops::ArithmeticOp::Multiply,
1161        ast::ArithmeticOp::Divide => ops::ArithmeticOp::Divide,
1162        ast::ArithmeticOp::IntegerDivide => ops::ArithmeticOp::IntegerDivide,
1163        ast::ArithmeticOp::Modulo => ops::ArithmeticOp::Modulo,
1164    }
1165}
1166
1167pub(crate) const fn atomic_type(kind: AtomicKind) -> AtomicType {
1168    match kind {
1169        AtomicKind::String => AtomicType::String,
1170        AtomicKind::AnyUri => AtomicType::AnyUri,
1171        AtomicKind::Boolean => AtomicType::Boolean,
1172        AtomicKind::Integer => AtomicType::Integer,
1173        AtomicKind::Decimal => AtomicType::Decimal,
1174        AtomicKind::Date => AtomicType::Date,
1175    }
1176}
1177
1178fn node_axis(axis: ast::Axis) -> NodeAxis {
1179    match axis {
1180        ast::Axis::Child => NodeAxis::Child,
1181        ast::Axis::Attribute => NodeAxis::Attribute,
1182        ast::Axis::SelfAxis => NodeAxis::SelfAxis,
1183        ast::Axis::DescendantOrSelf => NodeAxis::DescendantOrSelf,
1184        ast::Axis::FollowingSibling => NodeAxis::FollowingSibling,
1185        ast::Axis::Parent => NodeAxis::Parent,
1186        ast::Axis::Ancestor => NodeAxis::Ancestor,
1187        ast::Axis::AncestorOrSelf => NodeAxis::AncestorOrSelf,
1188        ast::Axis::PrecedingSibling => NodeAxis::PrecedingSibling,
1189        ast::Axis::Preceding => NodeAxis::Preceding,
1190    }
1191}
1192
1193fn name_match(name: Option<&NameOrWildcard>) -> NameMatch {
1194    match name {
1195        None | Some(NameOrWildcard::Wildcard) => NameMatch::Any,
1196        Some(NameOrWildcard::Name(q)) => NameMatch::Exact {
1197            namespace: q.namespace.clone(),
1198            local: q.local.clone(),
1199        },
1200    }
1201}
1202
1203/// The node test of a kind test.
1204pub(crate) fn kind_test(test: &KindTest) -> NodeTest {
1205    match test {
1206        KindTest::AnyKind => NodeTest::AnyNode,
1207        KindTest::Text => NodeTest::Kind(NodeKind::Text),
1208        KindTest::Comment => NodeTest::Kind(NodeKind::Comment),
1209        KindTest::ProcessingInstruction => NodeTest::Kind(NodeKind::ProcessingInstruction),
1210        KindTest::Element(name) => NodeTest::Named {
1211            kind: NodeKind::Element,
1212            name: name_match(name.as_ref()),
1213        },
1214        KindTest::Attribute(name) => NodeTest::Named {
1215            kind: NodeKind::Attribute,
1216            name: name_match(name.as_ref()),
1217        },
1218    }
1219}
1220
1221fn node_test(test: &ast::NodeTest, axis: NodeAxis) -> NodeTest {
1222    let principal = if axis == NodeAxis::Attribute {
1223        NodeKind::Attribute
1224    } else {
1225        NodeKind::Element
1226    };
1227    match test {
1228        ast::NodeTest::Kind(kind) => kind_test(kind),
1229        ast::NodeTest::Name(name) => NodeTest::Named {
1230            kind: principal,
1231            name: match name {
1232                NameTest::Name(q) => NameMatch::Exact {
1233                    namespace: q.namespace.clone(),
1234                    local: q.local.clone(),
1235                },
1236                NameTest::Any => NameMatch::Any,
1237                NameTest::AnyLocal { namespace, .. } => NameMatch::Namespace(namespace.clone()),
1238                NameTest::AnyNamespace { local } => NameMatch::Local(local.clone()),
1239            },
1240        },
1241    }
1242}
1243
1244/// Whether an expression calls `last()` (or, with `position`, `position()`) anywhere.
1245/// Conservative: a call inside a nested focus counts too.
1246fn calls_focus(expr: &Expr, position: bool) -> bool {
1247    let any = |items: &[Expr]| items.iter().any(|e| calls_focus(e, position));
1248    let preds =
1249        |predicates: &[Predicate]| predicates.iter().any(|p| calls_focus(&p.expr, position));
1250    match expr {
1251        Expr::Literal(_) | Expr::ContextItem | Expr::Root | Expr::Local(_) | Expr::External(_) => {
1252            false
1253        }
1254        Expr::Call { function, args, .. } => {
1255            *function == Builtin::Last || (position && *function == Builtin::Position) || any(args)
1256        }
1257        Expr::HostCall { args, .. } | Expr::Sequence(args) => any(args),
1258        Expr::Filter { base, predicates } => calls_focus(base, position) || preds(predicates),
1259        Expr::Step(step) => preds(&step.predicates),
1260        Expr::Path { lhs, rhs, .. }
1261        | Expr::Union { lhs, rhs, .. }
1262        | Expr::Arithmetic { lhs, rhs, .. }
1263        | Expr::Range(lhs, rhs)
1264        | Expr::GeneralComparison { lhs, rhs, .. }
1265        | Expr::ValueComparison { lhs, rhs, .. }
1266        | Expr::And(lhs, rhs)
1267        | Expr::Or(lhs, rhs)
1268        | Expr::For {
1269            sequence: lhs,
1270            body: rhs,
1271        }
1272        | Expr::Quantified {
1273            sequence: lhs,
1274            satisfies: rhs,
1275            ..
1276        } => calls_focus(lhs, position) || calls_focus(rhs, position),
1277        Expr::Negate(e)
1278        | Expr::InstanceOf { operand: e, .. }
1279        | Expr::Castable { operand: e, .. }
1280        | Expr::Cast { operand: e, .. } => calls_focus(e, position),
1281        Expr::If {
1282            condition,
1283            then,
1284            otherwise,
1285        } => {
1286            calls_focus(condition, position)
1287                || calls_focus(then, position)
1288                || calls_focus(otherwise, position)
1289        }
1290    }
1291}
1292
1293/// The axis of an expression used as a path step, if it is an axis step (`.` counts as
1294/// `self::node()`).
1295fn step_axis(expr: &Expr) -> Option<NodeAxis> {
1296    match expr {
1297        Expr::Step(step) => Some(step.axis),
1298        Expr::ContextItem => Some(NodeAxis::SelfAxis),
1299        _ => None,
1300    }
1301}
1302
1303/// Whether `lhs/rhs` yields nodes in document order without duplicates when `lhs` does.
1304fn path_is_ordered(lhs: Props, axis: NodeAxis) -> bool {
1305    if lhs.max_one {
1306        // A step from one node: axis results are delivered in document order.
1307        return true;
1308    }
1309    if !lhs.ordered {
1310        return false;
1311    }
1312    match axis {
1313        NodeAxis::Attribute | NodeAxis::SelfAxis => true,
1314        NodeAxis::Child | NodeAxis::Descendant | NodeAxis::DescendantOrSelf => lhs.peer,
1315        _ => false,
1316    }
1317}
1318
1319/// Properties of an axis step from a single node.
1320fn step_props(axis: NodeAxis, test: &NodeTest, predicates: &[Predicate]) -> Props {
1321    let positional = predicates
1322        .iter()
1323        .any(|p| matches!(p.kind, PredicateKind::Position(_)));
1324    let one_attribute = axis == NodeAxis::Attribute
1325        && matches!(
1326            test,
1327            NodeTest::Named {
1328                name: NameMatch::Exact { .. },
1329                ..
1330            }
1331        );
1332    let max_one =
1333        positional || one_attribute || matches!(axis, NodeAxis::SelfAxis | NodeAxis::Parent);
1334    let peer = max_one
1335        || matches!(
1336            axis,
1337            NodeAxis::Child
1338                | NodeAxis::Attribute
1339                | NodeAxis::FollowingSibling
1340                | NodeAxis::PrecedingSibling
1341        );
1342    Props::nodes(max_one, true, peer)
1343}
1344
1345/// A path step as the compiler sees it: a step of the syntax tree, or `//name` merged
1346/// into one `descendant::name` step.
1347enum PathStep<'a> {
1348    Ast(&'a ast::Step),
1349    Descendant(&'a ast::AxisStep),
1350}
1351
1352impl Compiler<'_> {
1353    #[expect(
1354        clippy::too_many_lines,
1355        reason = "one arm per expression form of the syntax tree"
1356    )]
1357    fn expr(&mut self, expr: &ast::Expr) -> Result<(Expr, Props)> {
1358        match expr {
1359            ast::Expr::Literal(literal) => literal_value(literal),
1360            ast::Expr::VarRef(name) => self.variable(name),
1361            ast::Expr::ContextItem => Ok((
1362                Expr::ContextItem,
1363                Props::unknown(true)
1364                    .typing(self.focus.unparsed())
1365                    .exactly_one(true),
1366            )),
1367            ast::Expr::FunctionCall { name, args } => self.call(name, args),
1368            ast::Expr::Sequence(items) => self.sequence(items),
1369            ast::Expr::Filter {
1370                base,
1371                predicates: ast_predicates,
1372            } => {
1373                let (base, props) = self.expr(base)?;
1374                let predicates = self.with_focus(props.ty, |c| c.predicates(ast_predicates))?;
1375                let positional = predicates
1376                    .iter()
1377                    .any(|p| matches!(p.kind, PredicateKind::Position(_)));
1378                // `E[. instance of T]` has type T, unless the test is always true.
1379                let ty = ast_predicates.iter().fold(props.ty, |ty, p| match p {
1380                    ast::Expr::InstanceOf { operand, target }
1381                        if matches!(**operand, ast::Expr::ContextItem) =>
1382                    {
1383                        let tested = match &target.item {
1384                            ast::ItemType::Atomic(atomic) => {
1385                                StaticType::of_atomic(atomic_type(atomic.kind))
1386                            }
1387                            ast::ItemType::Kind(kind) => StaticType::of_test(&kind_test(kind)),
1388                        };
1389                        // Before type checking, `FilterExpression.getItemType` gives T.
1390                        Typing {
1391                            parsed: tested,
1392                            ..ty.map(|t| if t.subsumed_by(tested) { t } else { tested })
1393                        }
1394                    }
1395                    _ => ty,
1396                });
1397                // The optimizer folds the filter of a literal sequence (not a range)
1398                // when every predicate is `[1]` (`FirstItemExpression`), or when none
1399                // is positional (numeric, or reading the position or the size) and
1400                // each depends on the focus only (`tryEarlyEvaluation`). Other
1401                // positional predicates are rewritten and not folded, and so is `[1]`
1402                // after another predicate.
1403                let first_items = predicates
1404                    .iter()
1405                    .all(|p| p.kind == PredicateKind::Position(Some(1)));
1406                let early = predicates.iter().all(|p| {
1407                    p.kind == PredicateKind::Boolean
1408                        && !calls_focus(&p.expr, true)
1409                        && !refers_to_variable_or_function(&p.expr)
1410                        && !depends_on_more_than_focus(&p.expr)
1411                });
1412                let folds =
1413                    props.folds() && !matches!(base, Expr::Range(..)) && (first_items || early);
1414                let compiled = Expr::Filter {
1415                    base: boxed(base),
1416                    predicates,
1417                };
1418                let ty = match folds.then(|| folded_type(&compiled)).flatten() {
1419                    Some(value) => Typing {
1420                        optimized: value,
1421                        ..ty
1422                    },
1423                    None => ty,
1424                };
1425                let props = Props {
1426                    max_one: props.max_one || positional,
1427                    count: Count::Other,
1428                    ..props
1429                }
1430                .typing(ty)
1431                .literal(false, folds);
1432                Ok((compiled, props))
1433            }
1434            ast::Expr::Path(path) => self.path(path),
1435            ast::Expr::Negate(operand) => {
1436                let (operand, p) = self.expr(operand)?;
1437                // The parser folds the negation of a literal; of anything else, it makes
1438                // arithmetic (`0 - x`), of unknown type until type-checked.
1439                let ty = p.ty.map(StaticType::negated);
1440                let ty = if p.folding == Folding::Parsed {
1441                    ty
1442                } else {
1443                    ty.unparsed()
1444                };
1445                Ok((
1446                    Expr::Negate(boxed(operand)),
1447                    Props::atomic(true, Class::Unknown)
1448                        .typing(ty)
1449                        .exactly_one(p.one())
1450                        .folded(p.folding),
1451                ))
1452            }
1453            ast::Expr::Castable { operand, target } => {
1454                let (operand, _) = self.expr(operand)?;
1455                Ok((
1456                    Expr::Castable {
1457                        operand: boxed(operand),
1458                        target: atomic_type(target.atomic.kind),
1459                        allows_empty: target.allows_empty,
1460                    },
1461                    Props::BOOLEAN.exactly_one(true),
1462                ))
1463            }
1464            // As the constructor functions, which Saxon-HE 12.10 compiles to the same
1465            // `CastExpression` with the empty sequence allowed.
1466            ast::Expr::Cast { operand, target } => {
1467                let (operand, p) = self.expr(operand)?;
1468                let atomic = atomic_type(target.atomic.kind);
1469                let class = if matches!(atomic, AtomicType::Integer | AtomicType::Decimal) {
1470                    Class::Unknown
1471                } else {
1472                    Class::NotNumeric
1473                };
1474                Ok((
1475                    Expr::Cast {
1476                        operand: boxed(operand),
1477                        target: atomic,
1478                        allows_empty: target.allows_empty,
1479                        upcast: atomic == AtomicType::Decimal && p.ty.upcasts_to_decimal(),
1480                    },
1481                    Props::atomic(true, class)
1482                        .typed(StaticType::of_atomic(atomic))
1483                        .exactly_one(!target.allows_empty || p.one())
1484                        .literal(p.is_literal(), p.folds()),
1485                ))
1486            }
1487            ast::Expr::InstanceOf { operand, target } => {
1488                let (operand, _) = self.expr(operand)?;
1489                let item = match &target.item {
1490                    ast::ItemType::Atomic(atomic) => ItemTest::Atomic(atomic_type(atomic.kind)),
1491                    ast::ItemType::Kind(kind) => ItemTest::Node(kind_test(kind)),
1492                };
1493                Ok((
1494                    Expr::InstanceOf {
1495                        operand: boxed(operand),
1496                        item,
1497                        occurrence: target.occurrence,
1498                    },
1499                    Props::BOOLEAN.exactly_one(true),
1500                ))
1501            }
1502            ast::Expr::Union(lhs, rhs) => {
1503                let (lhs, lp) = self.expr(lhs)?;
1504                let (rhs, rp) = self.expr(rhs)?;
1505                Ok((
1506                    Expr::Union {
1507                        lhs: boxed(lhs),
1508                        rhs: boxed(rhs),
1509                        lhs_ordered: lp.ordered && lp.kinds == Kinds::Nodes,
1510                        rhs_ordered: rp.ordered && rp.kinds == Kinds::Nodes,
1511                    },
1512                    Props::nodes(false, true, false).typing(lp.ty.union(rp.ty)),
1513                ))
1514            }
1515            ast::Expr::Arithmetic { op, lhs, rhs } => {
1516                let op = arithmetic_op(*op);
1517                let (lhs, lp) = self.expr(lhs)?;
1518                let (rhs, rp) = self.expr(rhs)?;
1519                let compiled = Expr::Arithmetic {
1520                    op,
1521                    lhs: boxed(lhs),
1522                    rhs: boxed(rhs),
1523                    calculator: Typing::calculator(op, lp.ty, rp.ty),
1524                };
1525                // Before type checking, arithmetic has no calculator: of unknown type.
1526                let mut ty = lp
1527                    .ty
1528                    .zip(rp.ty, |a, b| StaticType::arithmetic(op, a, b))
1529                    .unparsed();
1530                // Arithmetic on two literals is folded when type-checked (and, after
1531                // optimization, on two operands folded by then), unless it fails.
1532                let (mut literal, mut folds) = (false, false);
1533                if lp.folds()
1534                    && rp.folds()
1535                    && let Some(value) = folded_type(&compiled)
1536                {
1537                    literal = lp.is_literal() && rp.is_literal();
1538                    folds = true;
1539                    ty.optimized = value;
1540                    if literal {
1541                        ty.first = value;
1542                        ty.checked = value;
1543                    }
1544                }
1545                Ok((
1546                    compiled,
1547                    Props::atomic(true, Class::Unknown)
1548                        .typing(ty)
1549                        .exactly_one(lp.one() && rp.one())
1550                        .literal(literal, folds),
1551                ))
1552            }
1553            ast::Expr::Range(lhs, rhs) => {
1554                let (lhs, _) = self.expr(lhs)?;
1555                let (rhs, _) = self.expr(rhs)?;
1556                Ok((
1557                    Expr::Range(boxed(lhs), boxed(rhs)),
1558                    Props::atomic(false, Class::Unknown).typed(StaticType::Integer),
1559                ))
1560            }
1561            ast::Expr::Comparison { op, lhs, rhs } => self.comparison(*op, lhs, rhs),
1562            ast::Expr::And(lhs, rhs) | ast::Expr::Or(lhs, rhs) => {
1563                let (l, _) = self.expr(lhs)?;
1564                let (r, _) = self.expr(rhs)?;
1565                let e = if matches!(expr, ast::Expr::And(..)) {
1566                    Expr::And(boxed(l), boxed(r))
1567                } else {
1568                    Expr::Or(boxed(l), boxed(r))
1569                };
1570                Ok((e, Props::BOOLEAN.exactly_one(true)))
1571            }
1572            ast::Expr::If {
1573                condition,
1574                then,
1575                otherwise,
1576            } => {
1577                // Not folded, even with a literal condition (the optimizer option
1578                // `CONSTANT_FOLDING` is off in Saxon-HE).
1579                let (condition, _) = self.expr(condition)?;
1580                let (then, a) = self.expr(then)?;
1581                let (otherwise, b) = self.expr(otherwise)?;
1582                Ok((
1583                    Expr::If {
1584                        condition: boxed(condition),
1585                        then: boxed(then),
1586                        otherwise: boxed(otherwise),
1587                    },
1588                    Props::either(a, b),
1589                ))
1590            }
1591            ast::Expr::For { bindings, body } => self
1592                .bindings(bindings, &mut |c| {
1593                    let (body, props) = c.expr(body)?;
1594                    Ok((body, (props.kinds, props.ty)))
1595                })
1596                .map(|(e, (kinds, ty))| {
1597                    (
1598                        e,
1599                        Props {
1600                            kinds,
1601                            ..Props::unknown(false)
1602                        }
1603                        .typing(ty),
1604                    )
1605                }),
1606            ast::Expr::Quantified {
1607                quantifier,
1608                bindings,
1609                satisfies,
1610            } => self.quantified(*quantifier == ast::Quantifier::Every, bindings, satisfies),
1611        }
1612    }
1613
1614    fn variable(&self, name: &QName) -> Result<(Expr, Props)> {
1615        if let Some((depth, (_, ty))) = self
1616            .locals
1617            .iter()
1618            .rev()
1619            .enumerate()
1620            .find(|(_, (local, _))| local.same_expanded_name(name))
1621        {
1622            return Ok((
1623                Expr::Local(depth),
1624                Props::unknown(true).typing(*ty).exactly_one(true),
1625            ));
1626        }
1627        match self.context.variable(name) {
1628            Some(info) => Ok(reference(&info)),
1629            None => err(
1630                ErrorCode::Xpst0008,
1631                format!("Variable ${name} has not been declared"),
1632            ),
1633        }
1634    }
1635
1636    fn sequence(&mut self, items: &[ast::Expr]) -> Result<(Expr, Props)> {
1637        let mut compiled = Vec::with_capacity(items.len());
1638        let mut props: Option<Props> = None;
1639        let (mut all_parsed, mut all_fold) = (true, true);
1640        for item in items {
1641            let (e, p) = self.expr(item)?;
1642            let atomic = p.kinds == Kinds::Atomics;
1643            all_parsed &= atomic && p.folding == Folding::Parsed;
1644            all_fold &= atomic && p.folds();
1645            compiled.push(e);
1646            props = Some(props.map_or(p, |q| Props::either(q, p)));
1647        }
1648        let props = match props {
1649            // `()` and a sequence of literals are literals once parsed (`Block.simplify`);
1650            // a sequence of values that are all literals later is merged into one when
1651            // optimized (`Block.optimize`).
1652            None => Props::atomic(true, Class::NotNumeric)
1653                .typed(StaticType::Empty)
1654                .folded(Folding::Parsed),
1655            Some(p) => Props {
1656                max_one: false,
1657                ordered: false,
1658                peer: false,
1659                count: Count::Other,
1660                ..p
1661            }
1662            .folded(if all_parsed {
1663                Folding::Parsed
1664            } else if all_fold {
1665                Folding::Optimized
1666            } else {
1667                Folding::Never
1668            }),
1669        };
1670        Ok((Expr::Sequence(compiled), props))
1671    }
1672
1673    fn comparison(
1674        &mut self,
1675        op: ast::ComparisonOp,
1676        lhs: &ast::Expr,
1677        rhs: &ast::Expr,
1678    ) -> Result<(Expr, Props)> {
1679        let (l, lp) = self.expr(lhs)?;
1680        let (r, rp) = self.expr(rhs)?;
1681        let props = Props::BOOLEAN
1682            .exactly_one(matches!(op, ast::ComparisonOp::General(_)) || (lp.one() && rp.one()));
1683        let e = match op {
1684            ast::ComparisonOp::General(kind) => Expr::GeneralComparison {
1685                op: comparison_op(kind),
1686                lhs: boxed(l),
1687                rhs: boxed(r),
1688                strategy: match (lp.max_one, rp.max_one) {
1689                    (true, true) => CompareStrategy::OneToOne,
1690                    (_, true) => CompareStrategy::ManyToOne,
1691                    (true, false) => CompareStrategy::OneToMany,
1692                    (false, false) => CompareStrategy::ManyToMany,
1693                },
1694            },
1695            ast::ComparisonOp::Value(kind) => Expr::ValueComparison {
1696                op: comparison_op(kind),
1697                lhs: boxed(l),
1698                rhs: boxed(r),
1699            },
1700        };
1701        Ok((e, props))
1702    }
1703
1704    /// Compiles nested bindings (`for $a in A, $b in B return E` is
1705    /// `for $a in A return for $b in B return E`), with `inner` compiling the innermost
1706    /// body.
1707    fn bindings<T>(
1708        &mut self,
1709        bindings: &[ast::Binding],
1710        inner: &mut dyn FnMut(&mut Self) -> Result<(Expr, T)>,
1711    ) -> Result<(Expr, T)> {
1712        let Some((first, rest)) = bindings.split_first() else {
1713            return inner(self);
1714        };
1715        let (sequence, p) = self.expr(&first.sequence)?;
1716        self.locals.push((first.variable.clone(), p.ty.unparsed()));
1717        let body = self.bindings(rest, inner);
1718        self.locals.pop();
1719        let (body, extra) = body?;
1720        Ok((
1721            Expr::For {
1722                sequence: boxed(sequence),
1723                body: boxed(body),
1724            },
1725            extra,
1726        ))
1727    }
1728
1729    fn quantified(
1730        &mut self,
1731        every: bool,
1732        bindings: &[ast::Binding],
1733        satisfies: &ast::Expr,
1734    ) -> Result<(Expr, Props)> {
1735        let Some((first, rest)) = bindings.split_first() else {
1736            return err(ErrorCode::Internal, "quantified expression without binding");
1737        };
1738        let (sequence, p) = self.expr(&first.sequence)?;
1739        self.locals.push((first.variable.clone(), p.ty.unparsed()));
1740        let body = if rest.is_empty() {
1741            self.expr(satisfies).map(|(e, _)| e)
1742        } else {
1743            self.quantified(every, rest, satisfies).map(|(e, _)| e)
1744        };
1745        self.locals.pop();
1746        Ok((
1747            Expr::Quantified {
1748                every,
1749                sequence: boxed(sequence),
1750                satisfies: boxed(body?),
1751            },
1752            Props::BOOLEAN,
1753        ))
1754    }
1755
1756    fn predicates(&mut self, predicates: &[ast::Expr]) -> Result<Vec<Predicate>> {
1757        predicates
1758            .iter()
1759            .map(|p| {
1760                let (expr, props) = self.expr(p)?;
1761                let kind = match &expr {
1762                    Expr::Literal(AtomicValue::Integer(n)) => PredicateKind::Position(
1763                        n.to_i64()
1764                            .and_then(|n| usize::try_from(n).ok())
1765                            .filter(|&n| n > 0),
1766                    ),
1767                    _ if props.class == Class::NotNumeric => PredicateKind::Boolean,
1768                    _ => PredicateKind::Dynamic,
1769                };
1770                let uses_last = calls_focus(&expr, false);
1771                Ok(Predicate {
1772                    expr,
1773                    kind,
1774                    uses_last,
1775                })
1776            })
1777            .collect()
1778    }
1779
1780    /// Runs `compile` with the context item of that static type.
1781    fn with_focus<T>(
1782        &mut self,
1783        focus: Typing,
1784        compile: impl FnOnce(&mut Self) -> Result<T>,
1785    ) -> Result<T> {
1786        let outer = std::mem::replace(&mut self.focus, focus);
1787        let result = compile(self);
1788        self.focus = outer;
1789        result
1790    }
1791
1792    /// Whether the predicates of a `child::` step can be moved to a `descendant::` step
1793    /// (`//name[p]`): none of them may depend on the position.
1794    fn positional(predicates: &[Predicate]) -> bool {
1795        predicates
1796            .iter()
1797            .any(|p| p.kind != PredicateKind::Boolean || calls_focus(&p.expr, true))
1798    }
1799
1800    fn path(&mut self, path: &ast::PathExpr) -> Result<(Expr, Props)> {
1801        // `descendant-or-self::node()/child::name` without positional predicate is
1802        // `descendant::name`, which keeps document order from a single node.
1803        let mut steps = Vec::with_capacity(path.steps.len());
1804        let mut i = 0;
1805        while i < path.steps.len() {
1806            let step = &path.steps[i];
1807            if let (ast::Step::Axis(dos), Some(ast::Step::Axis(child))) =
1808                (step, path.steps.get(i + 1))
1809                && dos.axis == ast::Axis::DescendantOrSelf
1810                && dos.test == ast::NodeTest::Kind(KindTest::AnyKind)
1811                && dos.predicates.is_empty()
1812                && child.axis == ast::Axis::Child
1813            {
1814                let test = node_test(&child.test, NodeAxis::Child);
1815                let focus = Typing::of(StaticType::of_test(&test));
1816                let predicates = self.with_focus(focus, |c| c.predicates(&child.predicates))?;
1817                if !Self::positional(&predicates) {
1818                    steps.push(PathStep::Descendant(child));
1819                    i += 2;
1820                    continue;
1821                }
1822            }
1823            steps.push(PathStep::Ast(step));
1824            i += 1;
1825        }
1826        let mut acc = match path.start {
1827            ast::PathStart::Root => Some((
1828                Expr::Root,
1829                Props::nodes(true, true, true)
1830                    .typed(StaticType::UntypedNodes)
1831                    .exactly_one(true),
1832            )),
1833            ast::PathStart::Relative => None,
1834        };
1835        for step in steps {
1836            let (rhs, rhs_props) = match step {
1837                PathStep::Ast(ast::Step::Axis(axis_step)) => {
1838                    self.axis_step(node_axis(axis_step.axis), axis_step)?
1839                }
1840                PathStep::Descendant(axis_step) => {
1841                    self.axis_step(NodeAxis::Descendant, axis_step)?
1842                }
1843                PathStep::Ast(ast::Step::Expr(e)) => {
1844                    let focus = acc.as_ref().map_or(self.focus, |(_, p)| p.ty);
1845                    self.with_focus(focus, |c| c.expr(e))?
1846                }
1847            };
1848            acc = Some(match acc {
1849                None => (rhs, rhs_props),
1850                Some((lhs, lhs_props)) => Self::slash(lhs, lhs_props, rhs, rhs_props),
1851            });
1852        }
1853        acc.ok_or_else(|| Error::new(ErrorCode::Internal, "empty path"))
1854    }
1855
1856    fn axis_step(&mut self, axis: NodeAxis, step: &ast::AxisStep) -> Result<(Expr, Props)> {
1857        let test = node_test(&step.test, axis);
1858        let ty = StaticType::of_test(&test);
1859        let predicates = self.with_focus(Typing::of(ty), |c| c.predicates(&step.predicates))?;
1860        let props = step_props(axis, &test, &predicates).typed(ty);
1861        Ok((
1862            Expr::Step(Box::new(Step {
1863                axis,
1864                test,
1865                predicates,
1866            })),
1867            props,
1868        ))
1869    }
1870
1871    fn slash(lhs: Expr, lp: Props, rhs: Expr, rp: Props) -> (Expr, Props) {
1872        let axis = step_axis(&rhs);
1873        let rhs_kinds = if axis.is_some() {
1874            Kinds::Nodes
1875        } else {
1876            rp.kinds
1877        };
1878        let (mode, props) = match rhs_kinds {
1879            Kinds::Atomics => (
1880                PathMode::Atomic,
1881                Props::atomic(lp.max_one && rp.max_one, rp.class).typing(rp.ty),
1882            ),
1883            Kinds::Unknown => (
1884                PathMode::Dynamic,
1885                Props::unknown(lp.max_one && rp.max_one).typing(rp.ty),
1886            ),
1887            Kinds::Nodes => {
1888                let ordered = axis.is_some_and(|a| path_is_ordered(lp, a));
1889                let peer = if lp.max_one {
1890                    rp.peer
1891                } else {
1892                    lp.peer
1893                        && rp.peer
1894                        && matches!(
1895                            axis,
1896                            Some(NodeAxis::Child | NodeAxis::Attribute | NodeAxis::SelfAxis)
1897                        )
1898                };
1899                (
1900                    if ordered {
1901                        PathMode::Ordered
1902                    } else {
1903                        PathMode::Sort
1904                    },
1905                    Props::nodes(lp.max_one && rp.max_one, true, peer).typing(rp.ty),
1906                )
1907            }
1908        };
1909        let rhs_uses_last = calls_focus(&rhs, false);
1910        (
1911            Expr::Path {
1912                lhs: boxed(lhs),
1913                rhs: boxed(rhs),
1914                mode,
1915                rhs_uses_last,
1916            },
1917            props,
1918        )
1919    }
1920
1921    fn call(&mut self, name: &QName, args: &[ast::Expr]) -> Result<(Expr, Props)> {
1922        let builtin = functions::resolve(name, args.len(), self.context.xslt_functions())?;
1923        let Some(builtin) = builtin else {
1924            return match self.context.function(name, args.len()) {
1925                Some(id) => {
1926                    let args = args
1927                        .iter()
1928                        .map(|a| self.expr(a).map(|(e, _)| e))
1929                        .collect::<Result<_>>()?;
1930                    // Of its declared type once type-checked (`UserFunctionCall`), of
1931                    // unknown type before.
1932                    let ty = self.context.function_type(id).ty.unparsed();
1933                    Ok((
1934                        Expr::HostCall { id, args },
1935                        Props::unknown(false).typing(ty),
1936                    ))
1937                }
1938                None => err(
1939                    ErrorCode::Xpst0017,
1940                    format!(
1941                        "Cannot find a {}-argument function named {}{}",
1942                        args.len(),
1943                        name.namespace
1944                            .as_deref()
1945                            .map(|ns| format!("Q{{{ns}}}"))
1946                            .unwrap_or_default(),
1947                        name.local
1948                    ),
1949                ),
1950            };
1951        };
1952        let mut data = self.call_data(builtin, args)?;
1953        let mut compiled = Vec::with_capacity(args.len());
1954        let mut arg_props = Vec::with_capacity(args.len());
1955        for arg in args {
1956            let (e, p) = self.expr(arg)?;
1957            compiled.push(e);
1958            arg_props.push(p);
1959        }
1960        let many = builtin.returns_many();
1961        let props = match builtin.returns() {
1962            Returns::Boolean => Props::BOOLEAN,
1963            Returns::NonNumeric => {
1964                Props::atomic(!many, Class::NotNumeric).typed(StaticType::OtherAtomic)
1965            }
1966            Returns::Atomic => Props::atomic(!many, Class::Unknown),
1967            Returns::Nodes => Props::nodes(!many, !many, !many),
1968            Returns::Items => Props::unknown(!many),
1969        };
1970        let first = arg_props.first().copied();
1971        let at = |moment: fn(Typing) -> StaticType| {
1972            call_type(builtin, first.map(|p| (moment(p.ty), p.one())))
1973                .unwrap_or_else(|| moment(props.ty))
1974        };
1975        let mut ty = Typing {
1976            parsed: at(|t| t.parsed),
1977            first: at(|t| t.first),
1978            checked: at(|t| t.checked),
1979            optimized: at(|t| t.optimized),
1980        };
1981        let constructor = matches!(
1982            builtin,
1983            Builtin::XsDecimal | Builtin::XsDate | Builtin::XsInteger | Builtin::XsString
1984        );
1985        let one = if constructor {
1986            first.is_some_and(|p| p.one())
1987        } else {
1988            builtin.exactly_one()
1989        };
1990        if builtin == Builtin::XsDecimal
1991            && let Some(arg) = first
1992        {
1993            if arg.ty.is_decimal() {
1994                // The cast is gone: from then on, what contains it sees its argument.
1995                data = CallData::Unchanged;
1996                if arg.ty.removes_cast_when_checked() {
1997                    ty.checked = arg.ty.checked;
1998                }
1999                ty.optimized = arg.ty.optimized;
2000            } else if arg.ty.upcasts_to_decimal() {
2001                data = CallData::Upcast;
2002            }
2003        }
2004        // A cast of a literal is folded (other calls are not: no `CONSTANT_FOLDING`).
2005        let props = props.typing(ty).exactly_one(one).literal(
2006            constructor && first.is_some_and(|p| p.is_literal()),
2007            constructor && first.is_some_and(|p| p.folds()),
2008        );
2009        Ok((
2010            Expr::Call {
2011                function: builtin,
2012                args: compiled,
2013                data,
2014            },
2015            props,
2016        ))
2017    }
2018
2019    fn call_data(&self, builtin: Builtin, args: &[ast::Expr]) -> Result<CallData> {
2020        let literal = |i: usize| match args.get(i) {
2021            Some(ast::Expr::Literal(ast::Literal::String(s))) => Some(s.as_str()),
2022            _ => None,
2023        };
2024        match builtin {
2025            Builtin::Matches | Builtin::Replace | Builtin::Tokenize => {
2026                let flags_at = if builtin == Builtin::Replace { 3 } else { 2 };
2027                let flags = if args.len() > flags_at {
2028                    literal(flags_at)
2029                } else {
2030                    Some("")
2031                };
2032                Ok(match (literal(1), flags) {
2033                    (Some(pattern), Some(flags)) => CallData::Regex(Arc::new(
2034                        XPathRegex::new(pattern, flags).map_err(Error::from),
2035                    )),
2036                    _ => CallData::None,
2037                })
2038            }
2039            Builtin::SystemProperty => {
2040                let Some(text) = literal(0) else {
2041                    return err(
2042                        ErrorCode::Unsupported,
2043                        "system-property() with an argument that is not a string literal",
2044                    );
2045                };
2046                self.property_name(text.trim()).map(CallData::Property)
2047            }
2048            _ => Ok(CallData::None),
2049        }
2050    }
2051
2052    fn property_name(&self, text: &str) -> Result<QName> {
2053        let invalid = || {
2054            Error::new(
2055                ErrorCode::Xtde1390,
2056                format!("Invalid QName {text:?} in system-property()"),
2057            )
2058        };
2059        match text.split_once(':') {
2060            None if einvoice_xpath::is_ncname(text) => Ok(QName::local(text)),
2061            Some((prefix, local))
2062                if einvoice_xpath::is_ncname(prefix) && einvoice_xpath::is_ncname(local) =>
2063            {
2064                let namespace = self.context.namespace_uri(prefix).ok_or_else(invalid)?;
2065                Ok(QName {
2066                    prefix: Some(prefix.to_owned()),
2067                    namespace: Some(namespace),
2068                    local: local.to_owned(),
2069                })
2070            }
2071            _ => Err(invalid()),
2072        }
2073    }
2074}
2075
2076/// A reference to a variable of the host: of the type the host gives, and the literal it
2077/// gives when Saxon replaces the reference by one.
2078fn reference(info: &VariableInfo) -> (Expr, Props) {
2079    let value_type = &info.value_type;
2080    if let Some(values) = &value_type.constant {
2081        let expr = match &**values {
2082            [one] => Expr::Literal(one.clone()),
2083            many => Expr::Sequence(many.iter().cloned().map(Expr::Literal).collect()),
2084        };
2085        let props = Props::atomic(values.len() <= 1, Class::Unknown)
2086            .typing(value_type.ty)
2087            .exactly_one(values.len() == 1)
2088            .folded(value_type.folding);
2089        return (expr, props);
2090    }
2091    (
2092        Expr::External(info.id),
2093        Props::unknown(info.cardinality == Cardinality::AtMostOne).typing(value_type.ty),
2094    )
2095}
2096
2097fn literal_value(literal: &ast::Literal) -> Result<(Expr, Props)> {
2098    let (value, class) = match literal {
2099        ast::Literal::String(s) => (AtomicValue::String(s.clone()), Class::NotNumeric),
2100        ast::Literal::Integer(text) => {
2101            (AtomicValue::Integer(Integer::parse(text)?), Class::Unknown)
2102        }
2103        ast::Literal::Decimal(text) => {
2104            (AtomicValue::Decimal(Decimal::parse(text)?), Class::Unknown)
2105        }
2106        ast::Literal::Double(text) => (AtomicValue::Double(parse_double(text)?), Class::Unknown),
2107    };
2108    let ty = StaticType::of_atomic(value.atomic_type());
2109    Ok((
2110        Expr::Literal(value),
2111        Props::atomic(true, class)
2112            .typed(ty)
2113            .exactly_one(true)
2114            .folded(Folding::Parsed),
2115    ))
2116}
2117
2118/// The static type of a call to a built-in function, when it does not follow from what
2119/// the function returns: `first` is the type of the first argument and whether it is
2120/// exactly one item.
2121fn call_type(builtin: Builtin, first: Option<(StaticType, bool)>) -> Option<StaticType> {
2122    let arg = first.map_or(StaticType::Unknown, |(t, _)| t);
2123    Some(match builtin {
2124        Builtin::Count
2125        | Builtin::StringLength
2126        | Builtin::Position
2127        | Builtin::Last
2128        | Builtin::StringToCodepoints
2129        | Builtin::XsInteger => StaticType::Integer,
2130        Builtin::Number => StaticType::Double,
2131        Builtin::XsDecimal => StaticType::Decimal,
2132        // `Sum.getResultItemType`.
2133        Builtin::Sum => {
2134            let base = arg.numeric();
2135            if first.is_some_and(|(_, one)| one) {
2136                base
2137            } else {
2138                base.union(StaticType::Integer)
2139            }
2140        }
2141        // AS_PRIM_ARG0: the atomized type of the argument, untyped as double.
2142        Builtin::Round | Builtin::Abs => arg.negated(),
2143        // AS_ARG0.
2144        Builtin::Reverse => arg,
2145        Builtin::DistinctValues | Builtin::Current => StaticType::Unknown,
2146        Builtin::Document => StaticType::UntypedNodes,
2147        _ => return None,
2148    })
2149}
2150
2151/// Whether a predicate depends on more than the focus (`current()`, the current date
2152/// and time, `document()`), so that Saxon does not fold the filter.
2153fn depends_on_more_than_focus(expr: &Expr) -> bool {
2154    let any = |items: &[Expr]| items.iter().any(depends_on_more_than_focus);
2155    let preds = |predicates: &[Predicate]| {
2156        predicates
2157            .iter()
2158            .any(|p| depends_on_more_than_focus(&p.expr))
2159    };
2160    match expr {
2161        Expr::Call { function, args, .. } => {
2162            matches!(
2163                function,
2164                Builtin::Current | Builtin::CurrentDateTime | Builtin::Document
2165            ) || any(args)
2166        }
2167        Expr::Literal(_) | Expr::ContextItem | Expr::Root | Expr::Local(_) | Expr::External(_) => {
2168            false
2169        }
2170        Expr::HostCall { args, .. } | Expr::Sequence(args) => any(args),
2171        Expr::Filter { base, predicates } => depends_on_more_than_focus(base) || preds(predicates),
2172        Expr::Step(step) => preds(&step.predicates),
2173        Expr::Path { lhs, rhs, .. }
2174        | Expr::Union { lhs, rhs, .. }
2175        | Expr::Arithmetic { lhs, rhs, .. }
2176        | Expr::Range(lhs, rhs)
2177        | Expr::GeneralComparison { lhs, rhs, .. }
2178        | Expr::ValueComparison { lhs, rhs, .. }
2179        | Expr::And(lhs, rhs)
2180        | Expr::Or(lhs, rhs)
2181        | Expr::For {
2182            sequence: lhs,
2183            body: rhs,
2184        }
2185        | Expr::Quantified {
2186            sequence: lhs,
2187            satisfies: rhs,
2188            ..
2189        } => depends_on_more_than_focus(lhs) || depends_on_more_than_focus(rhs),
2190        Expr::Negate(e)
2191        | Expr::InstanceOf { operand: e, .. }
2192        | Expr::Castable { operand: e, .. }
2193        | Expr::Cast { operand: e, .. } => depends_on_more_than_focus(e),
2194        Expr::If {
2195            condition,
2196            then,
2197            otherwise,
2198        } => {
2199            depends_on_more_than_focus(condition)
2200                || depends_on_more_than_focus(then)
2201                || depends_on_more_than_focus(otherwise)
2202        }
2203    }
2204}
2205
2206#[cfg(test)]
2207mod tests {
2208    use super::*;
2209    use crate::context::SimpleStaticContext;
2210    use einvoice_xpath::{NamespaceMap, XS_NAMESPACE, parse_expr};
2211
2212    /// The static types of an expression, and whether it is an up-casting `xs:decimal`.
2213    fn typing(text: &str) -> (Typing, bool) {
2214        let ns = NamespaceMap::new().bind("xs", XS_NAMESPACE);
2215        let context = SimpleStaticContext::new();
2216        let mut compiler = Compiler {
2217            context: &context,
2218            locals: Vec::new(),
2219            focus: Typing::of(StaticType::Unknown),
2220        };
2221        let (expr, props) = compiler.expr(&parse_expr(text, &ns).unwrap()).unwrap();
2222        let upcast = matches!(
2223            expr,
2224            Expr::Call {
2225                function: Builtin::XsDecimal,
2226                data: CallData::Upcast,
2227                ..
2228            }
2229        );
2230        (props.ty, upcast)
2231    }
2232
2233    #[test]
2234    fn calculator_result_types() {
2235        use StaticType::{Decimal, Double, Integer, Unknown, UntypedAtomic};
2236        let t = StaticType::arithmetic;
2237        assert_eq!(t(ops::ArithmeticOp::Add, Integer, Integer), Integer);
2238        assert_eq!(t(ops::ArithmeticOp::Divide, Integer, Integer), Decimal);
2239        assert_eq!(
2240            t(ops::ArithmeticOp::IntegerDivide, Decimal, Integer),
2241            Integer
2242        );
2243        assert_eq!(
2244            t(ops::ArithmeticOp::IntegerDivide, UntypedAtomic, Integer),
2245            Integer
2246        );
2247        assert_eq!(
2248            t(ops::ArithmeticOp::Multiply, UntypedAtomic, Integer),
2249            Double
2250        );
2251        assert_eq!(t(ops::ArithmeticOp::Subtract, Decimal, Integer), Decimal);
2252        assert_eq!(t(ops::ArithmeticOp::Add, Unknown, Integer), Unknown);
2253        assert_eq!(Integer.union(Decimal), Decimal);
2254        assert_eq!(Integer.union(Double), Unknown);
2255        assert_eq!(StaticType::Empty.union(Integer), Integer);
2256    }
2257
2258    #[test]
2259    fn xs_decimal_upcasts_static_integers_only() {
2260        // Statically xs:integer: up-cast.
2261        assert!(typing("xs:decimal(300)").1);
2262        assert!(typing("xs:decimal(count(//a) * 100)").1);
2263        assert!(
2264            typing("xs:decimal(3000 div 10)").1,
2265            "literal arithmetic is folded"
2266        );
2267        assert!(
2268            typing("xs:decimal((300, 'a')[1])").1,
2269            "folded when optimized"
2270        );
2271        // Statically decimal, unknown or untyped: the converter of the run time.
2272        assert!(!typing("xs:decimal(count(//a) * 1000 div 10)").1);
2273        assert!(!typing("xs:decimal((300, 2.5)[1])").1);
2274        assert!(!typing("xs:decimal(if (true()) then 300 else 'a')").1);
2275        assert!(!typing("xs:decimal(sum((150, 150)) div 1)").1);
2276        assert!(!typing("xs:decimal(//a)").1);
2277        assert!(!typing("xs:decimal(('a', 300)[2])").1);
2278        assert_eq!(typing("(300, 'a')[1]").0.checked, StaticType::Unknown);
2279        assert_eq!(typing("(300, 'a')[1]").0.optimized, StaticType::Integer);
2280    }
2281
2282    #[test]
2283    fn types_before_type_checking() {
2284        use StaticType::{Decimal, Integer, Unknown};
2285        let parsed = |text: &str| typing(text).0.parsed;
2286        // Arithmetic has no calculator before type checking; unary minus of a literal is
2287        // folded by the parser.
2288        assert_eq!(parsed("count(//a) * 100"), Unknown);
2289        assert_eq!(typing("count(//a) * 100").0.checked, Integer);
2290        assert_eq!(parsed("-count(//a)"), Unknown);
2291        assert_eq!(parsed("-1"), Integer);
2292        assert_eq!(parsed("count(//a)"), Integer);
2293        assert_eq!(parsed("if (true()) then 300 else 1.5"), Decimal);
2294        assert_eq!(parsed("for $i in (1, 2) return $i"), Unknown);
2295        // `E[. instance of T]` is of type T before type checking, whatever E.
2296        let filter = "(count(//a) * 100)[. instance of xs:decimal]";
2297        assert_eq!(parsed(filter), Decimal);
2298        assert_eq!(typing(filter).0.checked, Integer);
2299    }
2300
2301    #[test]
2302    fn decimal_casts_and_divisions() {
2303        let ns = NamespaceMap::new().bind("xs", XS_NAMESPACE);
2304        let context = SimpleStaticContext::new();
2305        let compiled = |text: &str| {
2306            let mut compiler = Compiler {
2307                context: &context,
2308                locals: Vec::new(),
2309                focus: Typing::of(StaticType::Unknown),
2310            };
2311            compiler.expr(&parse_expr(text, &ns).unwrap()).unwrap()
2312        };
2313        let removed = |text: &str| {
2314            matches!(
2315                compiled(text).0,
2316                Expr::Call {
2317                    data: CallData::Unchanged,
2318                    ..
2319                }
2320            )
2321        };
2322        assert!(removed("xs:decimal(count(//a) div 1)"));
2323        assert!(removed("xs:decimal((300, 2.5)[1])"));
2324        assert!(!removed("xs:decimal(count(//a))"));
2325        assert!(!removed("xs:decimal(//a)"));
2326        // A removed cast has the type of its argument once it is gone.
2327        let (_, props) = compiled("xs:decimal((300, 2.5)[1])");
2328        assert_eq!(props.ty.checked, StaticType::Decimal);
2329        assert_eq!(props.ty.optimized, StaticType::Integer);
2330        let calculator = |text: &str| match compiled(text).0 {
2331            Expr::Arithmetic { calculator, .. } => calculator,
2332            other => panic!("not arithmetic: {other:?}"),
2333        };
2334        assert_eq!(
2335            calculator("count(//a) div 1 div 3"),
2336            Calculator::DecimalDivide
2337        );
2338        assert_eq!(
2339            calculator("3 div (count(//a) div 1)"),
2340            Calculator::DecimalDivide
2341        );
2342        assert_eq!(calculator("count(//a) div 3"), Calculator::Dynamic);
2343        assert_eq!(calculator("count(//a) div 1 * 3"), Calculator::Dynamic);
2344        assert_eq!(calculator("(-1, 1.5)[1] div 300"), Calculator::Dynamic);
2345        assert_eq!(calculator("//a div 1.5"), Calculator::Dynamic);
2346    }
2347}