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