Skip to main content

einvoice_xslt_exec/
prepare.rs

1//! Preparation: a loaded [`Stylesheet`] becomes an [`Executable`], once, to be run on any
2//! number of documents. Every XPath expression is compiled against its static context
3//! (global variables, the local variables in scope, the stylesheet functions), every
4//! variable gets a slot in the frame of its template, function or global variable,
5//! named templates and modes are resolved, and the template rules of each mode are
6//! ranked and indexed by the kind and name of the nodes they can match.
7
8use std::cell::RefCell;
9use std::collections::{BTreeSet, HashMap};
10use std::sync::Arc;
11
12use einvoice_xpath::{
13    self as ast, Avt, AvtPart, Expr, NamespaceMap, Occurrence, QName, SequenceType, parse_expr,
14};
15use einvoice_xpath_eval::{
16    BindingValue, Cardinality, CompiledExpr, DocumentCache, FunctionId, RegexCache, StaticContext,
17    ValueType, VariableId, VariableInfo, compile,
18};
19use einvoice_xslt::{
20    ApplyMode, ApplyTemplates, Attribute, CallTemplate, Choose, Comment, Copy, CopyOf, Element,
21    ForEach, GlobalKind, If, Instruction, LiteralElement, Message, Mode, NamespaceBinding,
22    NamespaceNode, NextMatch, Number, NumberLevel, Priority, ProcessingInstruction, Sequence,
23    Standalone, Stylesheet, Template, TemplateModes, ValueOf, Variable, VariableValue,
24};
25
26use crate::error::{PrepareError, PrepareErrors};
27use crate::pattern::{self, Alternative, Key};
28use crate::sink::Serialization;
29
30/// A stylesheet ready to run: prepared once, run on any number of documents with
31/// [`Executable::transform`](crate::Executable::transform).
32#[derive(Debug)]
33pub struct Executable {
34    pub(crate) globals: Vec<Global>,
35    pub(crate) templates: Vec<CompiledTemplate>,
36    pub(crate) functions: Vec<CompiledFunction>,
37    pub(crate) modes: Vec<CompiledMode>,
38    pub(crate) default_mode: usize,
39    pub(crate) serialization: Serialization,
40    /// The static base URI, against which `document()` resolves relative URIs given as
41    /// strings.
42    pub(crate) base_uri: Option<String>,
43    /// Whether some expression calls `document()`, which may load the source document
44    /// again from its text: a transformation given its source as an owned `String` then
45    /// keeps the text (see [`Executable::transform`](crate::Executable::transform)).
46    pub(crate) calls_document: bool,
47    /// How many bindings are evaluated as [`Eval::Learning`].
48    pub(crate) learners: usize,
49    /// The documents `document()` loaded through the resolver, parsed once for every
50    /// transformation that loads the same text again.
51    pub(crate) loaded: DocumentCache,
52    /// The regular expressions compiled at evaluation, for every transformation.
53    pub(crate) regexes: RegexCache,
54    /// The names of elements and attributes that have rules of their own in some mode,
55    /// numbered ([`CompiledMode::named_by_number`]).
56    pub(crate) rule_names: RuleNames,
57}
58
59/// Numbers of names, by local name and namespace.
60pub(crate) type RuleNames = HashMap<String, Vec<(Option<String>, u32)>>;
61
62/// The number of an expanded name in `names`, if it has one.
63pub(crate) fn rule_name_number(names: &RuleNames, name: &QName) -> Option<u32> {
64    names.get(name.local.as_str()).and_then(|by_ns| {
65        by_ns
66            .iter()
67            .find(|(ns, _)| ns.as_deref() == name.namespace.as_deref())
68            .map(|(_, number)| *number)
69    })
70}
71
72/// The template rules of each mode, and the numbers of the names they have rules for.
73fn compile_modes(
74    sheet: &Stylesheet,
75    templates: &[CompiledTemplate],
76    modes: &[Mode],
77) -> (Vec<CompiledMode>, RuleNames) {
78    let mut compiled: Vec<CompiledMode> = modes
79        .iter()
80        .map(|mode| rank_rules(sheet, templates, mode))
81        .collect();
82    let names = number_rule_names(&mut compiled);
83    (compiled, names)
84}
85
86/// Numbers the names of elements and attributes that have rules of their own in the
87/// modes, and gives each mode its chains of those names by number.
88fn number_rule_names(modes: &mut [CompiledMode]) -> RuleNames {
89    let mut names = RuleNames::new();
90    let mut count = 0_u32;
91    for mode in modes.iter_mut() {
92        for attribute in [false, true] {
93            let map = if attribute {
94                &mode.attributes
95            } else {
96                &mode.elements
97            };
98            let mut numbered: Vec<(u32, Vec<u32>)> = Vec::new();
99            for (local, by_ns) in map {
100                for (namespace, ranks) in by_ns {
101                    let entry = names.entry(local.clone()).or_default();
102                    let number =
103                        if let Some((_, number)) = entry.iter().find(|(ns, _)| ns == namespace) {
104                            *number
105                        } else {
106                            entry.push((namespace.clone(), count));
107                            count += 1;
108                            count - 1
109                        };
110                    numbered.push((number, ranks.clone()));
111                }
112            }
113            numbered.sort_by_key(|(number, _)| *number);
114            if attribute {
115                mode.attributes_by_number = numbered;
116            } else {
117                mode.elements_by_number = numbered;
118            }
119        }
120    }
121    names
122}
123
124/// A global variable or parameter.
125#[derive(Debug)]
126pub(crate) struct Global {
127    pub(crate) name: QName,
128    pub(crate) is_param: bool,
129    pub(crate) line: u32,
130    pub(crate) value: Value,
131    pub(crate) as_type: Option<SequenceType>,
132    /// Slots of the variables local to its sequence constructor.
133    pub(crate) slots: usize,
134}
135
136/// How the value of a binding is computed.
137#[derive(Debug)]
138pub(crate) enum Value {
139    Select(Box<CompiledExpr>),
140    Content(Vec<Inst>),
141    Absent,
142}
143
144/// A local variable, a template or function parameter: a slot of the frame.
145#[derive(Debug)]
146pub(crate) struct Binding {
147    pub(crate) line: u32,
148    pub(crate) name: QName,
149    pub(crate) slot: usize,
150    pub(crate) as_type: Option<SequenceType>,
151    pub(crate) value: Value,
152    /// When its value is computed.
153    pub(crate) eval: Eval,
154    /// Whether some expression in its scope refers to it (an unused variable is never
155    /// evaluated, as Saxon removes it).
156    pub(crate) used: bool,
157}
158
159/// When the value of a binding is computed, as Saxon-HE 12.10 computes it.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub(crate) enum Eval {
162    /// Where it is bound.
163    Eager,
164    /// When first referenced: a local variable referred to once, not in a loop, which
165    /// Saxon inlines into the reference.
166    Lazy,
167    /// Saxon's `LearningEvaluator`: when first referenced, until the binding has been
168    /// evaluated 20 times, its value each time computed (or, in a function body, 20
169    /// times at all); from then on where it is bound. Only the first 40 evaluations
170    /// count. `learner` indexes its counters, kept per transformation.
171    Learning {
172        learner: usize,
173        /// In an `xsl:function` body, where every evaluation counts, read or not.
174        every_counts: bool,
175    },
176}
177
178/// `xsl:with-param`.
179#[derive(Debug)]
180pub(crate) struct WithParam {
181    pub(crate) name: QName,
182    pub(crate) as_type: Option<SequenceType>,
183    pub(crate) value: Value,
184    pub(crate) eval: Eval,
185}
186
187#[derive(Debug)]
188pub(crate) struct CompiledTemplate {
189    pub(crate) line: u32,
190    pub(crate) params: Vec<Binding>,
191    pub(crate) body: Vec<Inst>,
192    pub(crate) slots: usize,
193    /// The compiled alternatives of the match pattern (empty without one).
194    pub(crate) pattern: Vec<Alternative>,
195    /// The match pattern as written, and each of its alternatives, for warnings.
196    pub(crate) pattern_text: String,
197    pub(crate) alternative_texts: Vec<String>,
198    /// Whether the body can end with an `xsl:call-template` in tail position (its last
199    /// instruction, or the last of a branch of an `xsl:choose` or `xsl:if` that is): run
200    /// as a tail call ([`has_tail_call`]).
201    pub(crate) tail_calls: bool,
202}
203
204/// Whether a sequence constructor can end with an `xsl:call-template` in tail position:
205/// its last instruction is one, or is an `xsl:choose` (or `xsl:if`) with a branch that
206/// can.
207fn has_tail_call(body: &[Inst]) -> bool {
208    match body.last() {
209        Some(Inst::CallTemplate(_)) => true,
210        Some(Inst::Choose(CompiledChoose { whens, otherwise })) => {
211            whens.iter().any(|w| has_tail_call(&w.body)) || has_tail_call(otherwise)
212        }
213        _ => false,
214    }
215}
216
217#[derive(Debug)]
218pub(crate) struct CompiledFunction {
219    pub(crate) line: u32,
220    pub(crate) name: QName,
221    pub(crate) params: Vec<Binding>,
222    pub(crate) as_type: Option<SequenceType>,
223    pub(crate) body: Vec<Inst>,
224    pub(crate) slots: usize,
225}
226
227/// The mode of `xsl:apply-templates`.
228#[derive(Debug, Clone, Copy)]
229pub(crate) enum ModeRef {
230    Mode(usize),
231    Current,
232}
233
234/// An attribute value template.
235#[derive(Debug)]
236pub(crate) struct CompiledAvt(pub(crate) Vec<AvtItem>);
237
238#[derive(Debug)]
239pub(crate) enum AvtItem {
240    Text(Box<str>),
241    Expr(Box<CompiledExpr>),
242}
243
244/// An instruction of a sequence constructor.
245#[derive(Debug)]
246pub(crate) enum Inst {
247    // The instructions on the path of a recursion through the templates hold their parts
248    // in a struct of their own, which `Runtime::instruction` passes whole to the function
249    // that runs it: a debug build keeps every binding of every arm of a match on the
250    // stack, and that function is part of every level of the recursion.
251    ApplyTemplates(CompiledApplyTemplates),
252    NextMatch(CompiledNextMatch),
253    CallTemplate(CompiledCallTemplate),
254    /// `xsl:choose`, and `xsl:if` as a choose with one branch.
255    Choose(CompiledChoose),
256    ForEach(CompiledForEach),
257    Variable(Box<Binding>),
258    Sequence {
259        line: u32,
260        select: Box<CompiledExpr>,
261    },
262    ValueOf {
263        line: u32,
264        select: Option<Box<CompiledExpr>>,
265        separator: Option<CompiledAvt>,
266        body: Vec<Inst>,
267    },
268    Attribute {
269        line: u32,
270        name: CompiledAvt,
271        namespace: Option<CompiledAvt>,
272        namespaces: Arc<[NamespaceBinding]>,
273        select: Option<Box<CompiledExpr>>,
274        body: Vec<Inst>,
275    },
276    Comment {
277        line: u32,
278        body: Vec<Inst>,
279    },
280    Text(Box<str>),
281    Number {
282        line: u32,
283        level: NumberLevel,
284        /// `None`: nodes of the context node's kind and name.
285        count: Option<CountPattern>,
286    },
287    /// A literal result element.
288    Element(CompiledElement),
289    /// `xsl:copy`.
290    Copy {
291        line: u32,
292        body: Vec<Inst>,
293    },
294    /// `xsl:copy-of`.
295    CopyOf {
296        line: u32,
297        select: Box<CompiledExpr>,
298    },
299    /// `xsl:element`.
300    ComputedElement {
301        line: u32,
302        name: CompiledAvt,
303        namespace: Option<CompiledAvt>,
304        namespaces: Arc<[NamespaceBinding]>,
305        body: Vec<Inst>,
306    },
307    /// `xsl:namespace`.
308    Namespace {
309        line: u32,
310        name: CompiledAvt,
311        select: Option<Box<CompiledExpr>>,
312        body: Vec<Inst>,
313    },
314    /// `xsl:processing-instruction`.
315    ProcessingInstruction {
316        line: u32,
317        name: CompiledAvt,
318        select: Option<Box<CompiledExpr>>,
319        body: Vec<Inst>,
320    },
321    /// `xsl:message`.
322    Message {
323        line: u32,
324        terminate: Option<CompiledAvt>,
325        body: Vec<Inst>,
326    },
327}
328
329/// `xsl:apply-templates`.
330#[derive(Debug)]
331pub(crate) struct CompiledApplyTemplates {
332    pub(crate) line: u32,
333    pub(crate) select: Box<CompiledExpr>,
334    pub(crate) mode: ModeRef,
335    pub(crate) params: Vec<WithParam>,
336}
337
338/// `xsl:next-match`.
339#[derive(Debug)]
340pub(crate) struct CompiledNextMatch {
341    pub(crate) line: u32,
342    pub(crate) params: Vec<WithParam>,
343}
344
345/// `xsl:call-template`.
346#[derive(Debug)]
347pub(crate) struct CompiledCallTemplate {
348    pub(crate) line: u32,
349    pub(crate) template: usize,
350    pub(crate) params: Vec<WithParam>,
351}
352
353/// `xsl:choose`, and `xsl:if` as a choose with one branch.
354#[derive(Debug)]
355pub(crate) struct CompiledChoose {
356    pub(crate) whens: Vec<When>,
357    pub(crate) otherwise: Vec<Inst>,
358}
359
360/// `xsl:for-each`.
361#[derive(Debug)]
362pub(crate) struct CompiledForEach {
363    pub(crate) line: u32,
364    pub(crate) select: Box<CompiledExpr>,
365    pub(crate) body: Vec<Inst>,
366}
367
368/// A literal result element.
369#[derive(Debug)]
370pub(crate) struct CompiledElement {
371    pub(crate) line: u32,
372    pub(crate) name: Arc<QName>,
373    pub(crate) namespaces: Arc<[NamespaceBinding]>,
374    pub(crate) attributes: Vec<(Arc<QName>, CompiledAvt)>,
375    pub(crate) body: Vec<Inst>,
376}
377
378/// A branch of `xsl:choose` (`xsl:when`), or `xsl:if`: an error in its test is
379/// attributed to its own line, as Saxon attributes it.
380#[derive(Debug)]
381pub(crate) struct When {
382    pub(crate) line: u32,
383    pub(crate) test: Box<CompiledExpr>,
384    pub(crate) body: Vec<Inst>,
385}
386
387/// The `count` pattern of `xsl:number`, and its text for warnings.
388#[derive(Debug)]
389pub(crate) struct CountPattern {
390    pub(crate) alternatives: Vec<Alternative>,
391    pub(crate) text: String,
392}
393
394/// A template rule as Saxon-HE 12.10 registers it: one per alternative of a match
395/// pattern without explicit priority (`A | B` is split into rules, XSLT 2.0 section
396/// 6.4), one for the whole pattern with an explicit priority.
397#[derive(Debug)]
398pub(crate) struct Rule {
399    pub(crate) template: usize,
400    /// The alternative of the template's pattern; `None` for the whole pattern.
401    pub(crate) alternative: Option<usize>,
402    /// The import precedence of the template's module, compared before the priority.
403    pub(crate) precedence: u32,
404    /// The priority, compared as Saxon compares it: as a double.
405    pub(crate) priority: f64,
406    /// Declaration order: the template's position.
407    pub(crate) sequence: usize,
408    /// The position of the alternative among the rules split from the same template
409    /// without explicit priority; 0 for a pattern with an explicit priority (Saxon's
410    /// `part`, which keeps `xsl:next-match` from running the same template twice).
411    pub(crate) part: usize,
412    /// The node kinds ([`kind_index`], one bit each) whose every node the rule is tried
413    /// on matches its pattern, which is then matched without evaluating anything: the
414    /// first alternative tried that can match the kind, as its test tells, is `text()`,
415    /// `node()`, `*` or `@*` alone without predicates, or `cac:X` in the chain of that
416    /// name ([`certain_kinds`]).
417    pub(crate) certain: u8,
418}
419
420impl Rule {
421    /// The rank of the rule against another, as Saxon ranks rules: import precedence,
422    /// then priority (declaration order and part tell the rules apart beyond it).
423    pub(crate) fn compare_rank(&self, other: &Self) -> std::cmp::Ordering {
424        self.precedence
425            .cmp(&other.precedence)
426            .then(self.priority.total_cmp(&other.priority))
427    }
428}
429
430/// The [`Rule::certain`] kinds of a rule whose pattern's alternatives are tried in the
431/// order of `alternatives` and that is held by the chains of `keys`.
432fn certain_kinds(alternatives: &[pattern::Alternative], keys: &[pattern::Key]) -> u8 {
433    use einvoice_xpath_eval::NodeKind as K;
434    let mut kinds = 0;
435    for kind in [
436        K::Document,
437        K::Element,
438        K::Attribute,
439        K::Text,
440        K::Comment,
441        K::ProcessingInstruction,
442    ] {
443        // A rule held only by the chains of one name (a lone name test) is tried on nodes
444        // of that name only.
445        let by_name = !keys.is_empty()
446            && keys.iter().all(|key| match key {
447                pattern::Key::Element(ns, local) => {
448                    kind == K::Element
449                        && alternatives
450                            .first()
451                            .is_some_and(|a| a.is_lone_name_test(K::Element, ns.as_deref(), local))
452                }
453                pattern::Key::Attribute(ns, local) => {
454                    kind == K::Attribute
455                        && alternatives.first().is_some_and(|a| {
456                            a.is_lone_name_test(K::Attribute, ns.as_deref(), local)
457                        })
458                }
459                _ => false,
460            });
461        let first = alternatives.iter().find(|a| !a.excludes(kind));
462        if by_name || first.is_some_and(|a| a.matches_every_node_of(kind)) {
463            kinds |= 1 << kind_index(kind);
464        }
465    }
466    kinds
467}
468
469/// Rule ranks of elements or attributes by local name, then namespace.
470type ByName = HashMap<String, Vec<(Option<String>, Vec<u32>)>>;
471
472/// The rules of a mode and Saxon's rule chains: the ranks of the rules that can match
473/// nodes of one name (elements, attributes), of one kind, or of any kind, each chain in
474/// rank order.
475#[derive(Debug, Default)]
476pub(crate) struct CompiledMode {
477    pub(crate) name: String,
478    /// In rank order: import precedence descending, priority descending, then
479    /// declaration order descending, then part descending (Saxon puts a rule added later
480    /// before the earlier ones of the same priority).
481    pub(crate) rules: Vec<Rule>,
482    elements: ByName,
483    attributes: ByName,
484    any_element: Vec<u32>,
485    any_attribute: Vec<u32>,
486    text: Vec<u32>,
487    comment: Vec<u32>,
488    processing_instruction: Vec<u32>,
489    document: Vec<u32>,
490    generic: Vec<u32>,
491    /// What the rule search gives for a node of each kind ([`kind_index`]) whose name has
492    /// no rule of its own, when it is known without matching any pattern.
493    plans: [Plan; 6],
494    /// The chains of `elements` and `attributes` by the number of their name in
495    /// [`Executable::rule_names`], in number order.
496    elements_by_number: Vec<(u32, Vec<u32>)>,
497    attributes_by_number: Vec<(u32, Vec<u32>)>,
498}
499
500/// The outcome of the rule search ([`Runtime::find_rule`](crate::run)) for a node of a
501/// kind, when the chain of its name is empty and no rule is current
502/// (`xsl:apply-templates`, not `xsl:next-match`).
503#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
504pub(crate) enum Plan {
505    /// Unknown without matching patterns: search the chains.
506    #[default]
507    Search,
508    /// No rule can match: the built-in rule.
509    Builtin,
510    /// This rule matches every node of the kind, without evaluating anything, and every
511    /// other rule that could match has a lower priority.
512    Rule(u32),
513}
514
515/// The index of a node kind in [`CompiledMode`]'s plans.
516pub(crate) const fn kind_index(kind: einvoice_xpath_eval::NodeKind) -> usize {
517    use einvoice_xpath_eval::NodeKind as K;
518    match kind {
519        K::Document => 0,
520        K::Element => 1,
521        K::Attribute => 2,
522        K::Text => 3,
523        K::Comment => 4,
524        K::ProcessingInstruction => 5,
525    }
526}
527
528const EMPTY: &[u32] = &[];
529
530impl CompiledMode {
531    /// The chain of rules for elements (or attributes, `attribute`) of a name.
532    pub(crate) fn named_chain(&self, attribute: bool, name: Option<&QName>) -> &[u32] {
533        Self::named(
534            if attribute {
535                &self.attributes
536            } else {
537                &self.elements
538            },
539            name,
540        )
541    }
542
543    /// The chain of rules for elements (or attributes, `attribute`) whose name has the
544    /// number `number` in [`Executable::rule_names`].
545    pub(crate) fn named_by_number(&self, attribute: bool, number: u32) -> &[u32] {
546        let numbered = if attribute {
547            &self.attributes_by_number
548        } else {
549            &self.elements_by_number
550        };
551        numbered
552            .binary_search_by_key(&number, |(n, _)| *n)
553            .map_or(EMPTY, |i| numbered[i].1.as_slice())
554    }
555
556    /// The rule search's outcome for a node of `kind` without rules for its name.
557    pub(crate) const fn plan(&self, kind: einvoice_xpath_eval::NodeKind) -> Plan {
558        self.plans[kind_index(kind)]
559    }
560
561    /// The chains Saxon searches for a node of that kind, `named` being the chain of its
562    /// name ([`CompiledMode::named_chain`], empty for other kinds), in its order: the
563    /// chain of the name, the chain of the kind, the generic chain.
564    pub(crate) fn chains_with<'a>(
565        &'a self,
566        kind: einvoice_xpath_eval::NodeKind,
567        named: &'a [u32],
568    ) -> [&'a [u32]; 3] {
569        [named, self.kind_chain(kind), &self.generic]
570    }
571
572    fn kind_chain(&self, kind: einvoice_xpath_eval::NodeKind) -> &[u32] {
573        use einvoice_xpath_eval::NodeKind as K;
574        match kind {
575            K::Element => &self.any_element,
576            K::Attribute => &self.any_attribute,
577            K::Text => &self.text,
578            K::Comment => &self.comment,
579            K::ProcessingInstruction => &self.processing_instruction,
580            K::Document => &self.document,
581        }
582    }
583
584    /// The plans of the node kinds ([`Plan`]), once the rules are indexed: the search
585    /// [`Runtime::find_rule`](crate::run) does, over the chain of the kind and the
586    /// generic chain, when its outcome needs no pattern to be matched.
587    fn plan_kinds(&mut self) {
588        use einvoice_xpath_eval::NodeKind as K;
589        for kind in [
590            K::Document,
591            K::Element,
592            K::Attribute,
593            K::Text,
594            K::Comment,
595            K::ProcessingInstruction,
596        ] {
597            let mut ranks = self.kind_chain(kind).iter().chain(&self.generic).copied();
598            let plan = match ranks.next() {
599                None => Plan::Builtin,
600                Some(first) => {
601                    let rule = &self.rules[first as usize];
602                    let unconditional = rule.certain & (1 << kind_index(kind)) != 0;
603                    if unconditional
604                        && ranks.all(|r| {
605                            self.rules[r as usize].compare_rank(rule) == std::cmp::Ordering::Less
606                        })
607                    {
608                        Plan::Rule(first)
609                    } else {
610                        Plan::Search
611                    }
612                }
613            };
614            self.plans[kind_index(kind)] = plan;
615        }
616    }
617
618    fn named<'a>(map: &'a ByName, name: Option<&QName>) -> &'a [u32] {
619        let Some(name) = name else {
620            return EMPTY;
621        };
622        map.get(name.local.as_str())
623            .and_then(|by_ns| {
624                by_ns
625                    .iter()
626                    .find(|(ns, _)| ns.as_deref() == name.namespace.as_deref())
627            })
628            .map_or(EMPTY, |(_, ranks)| ranks.as_slice())
629    }
630
631    fn index(&mut self, rank: u32, key: &Key) {
632        let push_named = |map: &mut ByName, ns: &Option<String>, local: &str| {
633            let by_ns = map.entry(local.to_owned()).or_default();
634            match by_ns.iter_mut().find(|(n, _)| n == ns) {
635                Some((_, ranks)) => ranks.push(rank),
636                None => by_ns.push((ns.clone(), vec![rank])),
637            }
638        };
639        match key {
640            Key::Document => self.document.push(rank),
641            Key::Element(ns, local) => push_named(&mut self.elements, ns, local),
642            Key::Attribute(ns, local) => push_named(&mut self.attributes, ns, local),
643            Key::AnyElement => self.any_element.push(rank),
644            Key::AnyAttribute => self.any_attribute.push(rank),
645            Key::AnyChild => {
646                self.any_element.push(rank);
647                self.text.push(rank);
648                self.comment.push(rank);
649                self.processing_instruction.push(rank);
650            }
651            Key::Text => self.text.push(rank),
652            Key::Comment => self.comment.push(rank),
653            Key::ProcessingInstruction => self.processing_instruction.push(rank),
654            Key::Generic => self.generic.push(rank),
655        }
656    }
657}
658
659/// The local variables of one frame (a template, a function or a global variable)
660/// during compilation.
661#[derive(Debug, Default)]
662struct Frame {
663    slots: usize,
664    /// In scope, innermost last.
665    locals: Vec<(QName, VariableInfo)>,
666    /// References seen, per slot.
667    uses: RefCell<Vec<u32>>,
668    /// Per slot, whether a reference is in a loop: an operand of an XPath expression
669    /// evaluated repeatedly, or an `xsl:for-each` body the variable is declared outside.
670    looping: RefCell<Vec<bool>>,
671    /// Per slot, the number of `xsl:for-each` bodies around its declaration.
672    depths: Vec<u32>,
673    /// The number of `xsl:for-each` bodies around the instruction being compiled.
674    depth: u32,
675    /// The local variables whose value is being compiled, innermost last.
676    enclosing: Vec<usize>,
677    /// Every reference to a local variable: its slot, and the variables whose value holds
678    /// it (`enclosing` then).
679    references: RefCell<Vec<(usize, Vec<usize>)>>,
680    /// Per slot, whether Saxon removes the variable: unused, or inlined into its one
681    /// reference (the references in its value are then gone too).
682    gone: Vec<bool>,
683    /// Per slot, the variables whose value holds its declaration (`enclosing` then).
684    declared_in: Vec<Vec<usize>>,
685}
686
687impl Frame {
688    /// A new slot, not in scope yet ([`Frame::bind`]).
689    fn reserve(&mut self) -> usize {
690        let slot = self.slots;
691        self.slots += 1;
692        self.uses.borrow_mut().push(0);
693        self.looping.borrow_mut().push(false);
694        self.depths.push(self.depth);
695        self.gone.push(false);
696        self.declared_in.push(self.enclosing.clone());
697        slot
698    }
699
700    /// Whether a reference to `target` held in the values of the variables `enclosing` is
701    /// in the value of one for which `removed` holds, among those declared after `target`
702    /// (a variable whose value holds the declaration of `target` holds it whole).
703    fn removed_with(
704        &self,
705        target: usize,
706        enclosing: &[usize],
707        removed: &dyn Fn(usize) -> bool,
708    ) -> bool {
709        let declared_in = self.declared_in.get(target);
710        enclosing
711            .iter()
712            .any(|e| !declared_in.is_some_and(|d| d.contains(e)) && removed(*e))
713    }
714
715    fn declare(
716        &mut self,
717        name: QName,
718        cardinality: Cardinality,
719        value_type: ValueType,
720        globals: usize,
721    ) -> usize {
722        let slot = self.reserve();
723        self.bind(slot, name, cardinality, value_type, globals);
724        slot
725    }
726
727    /// Puts a reserved slot in scope under `name`.
728    fn bind(
729        &mut self,
730        slot: usize,
731        name: QName,
732        cardinality: Cardinality,
733        value_type: ValueType,
734        globals: usize,
735    ) {
736        let id = VariableId(u32::try_from(globals + slot).unwrap_or(u32::MAX));
737        self.locals.push((
738            name,
739            VariableInfo {
740                id,
741                cardinality,
742                value_type,
743            },
744        ));
745    }
746}
747
748/// The static context of an expression.
749struct Scope<'a> {
750    globals: &'a [(QName, VariableInfo)],
751    /// How many globals Saxon has typed before the declaration being compiled (those
752    /// declared before it): a reference to a later one is of unknown type for the type
753    /// inference of the variables declared here.
754    typed_globals: usize,
755    functions: &'a [(QName, usize)],
756    /// The declared result types of the functions.
757    function_types: &'a [ValueType],
758    frame: Option<&'a Frame>,
759    /// The URI of the module of the declaration: the static base URI of `document()`.
760    static_base: Option<&'a str>,
761}
762
763impl Scope<'_> {
764    /// The local variable of that name in scope, innermost first, and its slot.
765    fn local(&self, name: &QName) -> Option<(usize, VariableInfo)> {
766        let frame = self.frame?;
767        let (_, info) = frame
768            .locals
769            .iter()
770            .rev()
771            .find(|(n, _)| n.same_expanded_name(name))?;
772        let slot = (info.id.0 as usize).saturating_sub(self.globals.len());
773        Some((slot, info.clone()))
774    }
775}
776
777impl StaticContext for Scope<'_> {
778    fn variable(&self, name: &QName) -> Option<VariableInfo> {
779        if let Some((_, info)) = self.local(name) {
780            return Some(info);
781        }
782        let (index, (_, info)) = self
783            .globals
784            .iter()
785            .enumerate()
786            .find(|(_, (n, _))| n.same_expanded_name(name))?;
787        Some(if index < self.typed_globals {
788            info.clone()
789        } else {
790            VariableInfo {
791                value_type: info.value_type.declared_later(),
792                ..info.clone()
793            }
794        })
795    }
796
797    fn variable_reference(&self, name: &QName, in_loop: bool) -> Option<VariableInfo> {
798        if let (Some(frame), Some((slot, _))) = (self.frame, self.local(name)) {
799            if let Some(count) = frame.uses.borrow_mut().get_mut(slot) {
800                *count += 1;
801            }
802            let outside = frame.depths.get(slot).is_some_and(|&d| frame.depth > d);
803            if let Some(looping) = frame.looping.borrow_mut().get_mut(slot) {
804                *looping |= in_loop || outside;
805            }
806            frame
807                .references
808                .borrow_mut()
809                .push((slot, frame.enclosing.clone()));
810        }
811        self.variable(name)
812    }
813
814    fn function(&self, name: &QName, arity: usize) -> Option<FunctionId> {
815        self.functions
816            .iter()
817            .position(|(n, a)| *a == arity && n.same_expanded_name(name))
818            .map(|i| FunctionId(u32::try_from(i).unwrap_or(u32::MAX)))
819    }
820
821    fn function_type(&self, id: FunctionId) -> ValueType {
822        self.function_types
823            .get(id.0 as usize)
824            .cloned()
825            .unwrap_or_default()
826    }
827
828    fn xslt_functions(&self) -> bool {
829        true
830    }
831
832    /// The parser has resolved the prefixed names of `system-property()`,
833    /// `element-available()` and `function-available()` already (as `Q{uri}local`): a
834    /// prefix the compiler asks for is not bound.
835    fn namespace_uri(&self, _prefix: &str) -> Option<String> {
836        None
837    }
838
839    fn element_available(&self, name: &QName) -> Option<bool> {
840        einvoice_xslt::element_available(name.namespace.as_deref(), &name.local)
841    }
842
843    fn static_base_uri(&self) -> Option<String> {
844        self.static_base.map(str::to_owned)
845    }
846}
847
848/// Calls `f` on each sequence constructor an instruction holds (its bodies, the value of
849/// a variable or of a parameter it passes).
850fn for_each_body(inst: &Inst, f: &mut dyn FnMut(&[Inst])) {
851    let params = |params: &[WithParam], f: &mut dyn FnMut(&[Inst])| {
852        for p in params {
853            if let Value::Content(body) = &p.value {
854                f(body);
855            }
856        }
857    };
858    match inst {
859        Inst::ApplyTemplates(CompiledApplyTemplates { params: p, .. })
860        | Inst::NextMatch(CompiledNextMatch { params: p, .. })
861        | Inst::CallTemplate(CompiledCallTemplate { params: p, .. }) => params(p, f),
862        Inst::Choose(CompiledChoose { whens, otherwise }) => {
863            for w in whens {
864                f(&w.body);
865            }
866            f(otherwise);
867        }
868        Inst::Variable(b) => {
869            if let Value::Content(body) = &b.value {
870                f(body);
871            }
872        }
873        Inst::ForEach(CompiledForEach { body, .. })
874        | Inst::ValueOf { body, .. }
875        | Inst::Attribute { body, .. }
876        | Inst::Comment { body, .. }
877        | Inst::Element(CompiledElement { body, .. })
878        | Inst::Copy { body, .. }
879        | Inst::ComputedElement { body, .. }
880        | Inst::Namespace { body, .. }
881        | Inst::ProcessingInstruction { body, .. }
882        | Inst::Message { body, .. } => f(body),
883        Inst::Sequence { .. } | Inst::Text(_) | Inst::Number { .. } | Inst::CopyOf { .. } => {}
884    }
885}
886
887/// [`for_each_body`], mutably.
888fn for_each_body_mut<'i>(inst: &'i mut Inst, f: &mut dyn FnMut(&'i mut Vec<Inst>)) {
889    let params = |params: &'i mut Vec<WithParam>, f: &mut dyn FnMut(&'i mut Vec<Inst>)| {
890        for p in params {
891            if let Value::Content(body) = &mut p.value {
892                f(body);
893            }
894        }
895    };
896    match inst {
897        Inst::ApplyTemplates(CompiledApplyTemplates { params: p, .. })
898        | Inst::NextMatch(CompiledNextMatch { params: p, .. })
899        | Inst::CallTemplate(CompiledCallTemplate { params: p, .. }) => params(p, f),
900        Inst::Choose(CompiledChoose { whens, otherwise }) => {
901            for w in whens {
902                f(&mut w.body);
903            }
904            f(otherwise);
905        }
906        Inst::Variable(b) => {
907            if let Value::Content(body) = &mut b.value {
908                f(body);
909            }
910        }
911        Inst::ForEach(CompiledForEach { body, .. })
912        | Inst::ValueOf { body, .. }
913        | Inst::Attribute { body, .. }
914        | Inst::Comment { body, .. }
915        | Inst::Element(CompiledElement { body, .. })
916        | Inst::Copy { body, .. }
917        | Inst::ComputedElement { body, .. }
918        | Inst::Namespace { body, .. }
919        | Inst::ProcessingInstruction { body, .. }
920        | Inst::Message { body, .. } => f(body),
921        Inst::Sequence { .. } | Inst::Text(_) | Inst::Number { .. } | Inst::CopyOf { .. } => {}
922    }
923}
924
925/// Whether the value of a binding depends on the position, the size or the current item
926/// of the focus it is bound in (`fn:position()`, `fn:last()`, `fn:current()`, and the
927/// instructions that pass the focus on, `xsl:call-template` and `xsl:next-match`), as
928/// Saxon's dependencies tell it: such a value is never evaluated lazily.
929fn depends_on_focus_position(value: &VariableValue) -> bool {
930    match value {
931        VariableValue::Select(expr) => expr_depends_on_focus_position(expr, true),
932        VariableValue::Content(body) => instructions_depend_on_focus_position(body),
933        VariableValue::Absent => false,
934    }
935}
936
937fn instructions_depend_on_focus_position(instructions: &[Instruction]) -> bool {
938    let expr = |e: &Expr| expr_depends_on_focus_position(e, true);
939    let avt = |a: &Avt| {
940        a.parts
941            .iter()
942            .any(|p| matches!(p, AvtPart::Expr(e) if expr(e)))
943    };
944    let params = |params: &[Variable]| params.iter().any(|p| depends_on_focus_position(&p.value));
945    instructions.iter().any(|instruction| match instruction {
946        Instruction::CallTemplate(_) | Instruction::NextMatch(_) => true,
947        Instruction::ApplyTemplates(a) => a.select.as_ref().is_some_and(expr) || params(&a.params),
948        Instruction::Choose(c) => {
949            c.whens
950                .iter()
951                .any(|w| expr(&w.test) || instructions_depend_on_focus_position(&w.body))
952                || c.otherwise
953                    .as_ref()
954                    .is_some_and(|o| instructions_depend_on_focus_position(o))
955        }
956        Instruction::If(i) => expr(&i.test) || instructions_depend_on_focus_position(&i.body),
957        // The body has the focus of the items selected.
958        Instruction::ForEach(f) => expr(&f.select),
959        Instruction::Variable(v) => depends_on_focus_position(&v.value),
960        Instruction::Sequence(q) => expr(&q.select),
961        Instruction::ValueOf(v) => {
962            v.select.as_ref().is_some_and(expr)
963                || v.separator.as_ref().is_some_and(avt)
964                || instructions_depend_on_focus_position(&v.body)
965        }
966        Instruction::Attribute(a) => {
967            avt(&a.name)
968                || a.namespace.as_ref().is_some_and(avt)
969                || a.select.as_ref().is_some_and(expr)
970                || instructions_depend_on_focus_position(&a.body)
971        }
972        Instruction::Comment(c) => instructions_depend_on_focus_position(&c.body),
973        Instruction::LiteralElement(e) => {
974            e.attributes.iter().any(|a| avt(&a.value))
975                || instructions_depend_on_focus_position(&e.body)
976        }
977        Instruction::Copy(c) => instructions_depend_on_focus_position(&c.body),
978        Instruction::CopyOf(c) => expr(&c.select),
979        Instruction::Element(e) => {
980            avt(&e.name)
981                || e.namespace.as_ref().is_some_and(avt)
982                || instructions_depend_on_focus_position(&e.body)
983        }
984        Instruction::Namespace(n) => {
985            avt(&n.name)
986                || n.select.as_ref().is_some_and(expr)
987                || instructions_depend_on_focus_position(&n.body)
988        }
989        Instruction::ProcessingInstruction(p) => {
990            avt(&p.name)
991                || p.select.as_ref().is_some_and(expr)
992                || instructions_depend_on_focus_position(&p.body)
993        }
994        Instruction::Message(m) => {
995            m.terminate.as_ref().is_some_and(avt) || instructions_depend_on_focus_position(&m.body)
996        }
997        Instruction::Text(_) | Instruction::Number(_) => false,
998    })
999}
1000
1001/// Whether `expr` calls `current()` anywhere, or `position()` or `last()` where the
1002/// focus is still the outer one (`outer`): not in a predicate, nor in a path step after
1003/// the first.
1004fn expr_depends_on_focus_position(expr: &Expr, outer: bool) -> bool {
1005    let at = |e: &Expr, outer: bool| expr_depends_on_focus_position(e, outer);
1006    let bindings = |bindings: &[ast::Binding]| bindings.iter().any(|b| at(&b.sequence, outer));
1007    match expr {
1008        Expr::FunctionCall { name, args } => {
1009            let fn_name = |local: &str| {
1010                name.namespace.as_deref() == Some(ast::FN_NAMESPACE) && name.local == local
1011            };
1012            fn_name("current")
1013                || (outer && (fn_name("position") || fn_name("last")))
1014                || args.iter().any(|a| at(a, outer))
1015        }
1016        Expr::Literal(_) | Expr::VarRef(_) | Expr::ContextItem => false,
1017        Expr::Sequence(items) => items.iter().any(|e| at(e, outer)),
1018        Expr::Filter { base, predicates } => {
1019            at(base, outer) || predicates.iter().any(|p| at(p, false))
1020        }
1021        Expr::Path(path) => path.steps.iter().enumerate().any(|(i, step)| {
1022            let step_outer = outer && i == 0 && path.start == ast::PathStart::Relative;
1023            match step {
1024                ast::Step::Axis(axis_step) => axis_step.predicates.iter().any(|p| at(p, false)),
1025                ast::Step::Expr(e) => at(e, step_outer),
1026            }
1027        }),
1028        Expr::Negate(e)
1029        | Expr::Castable { operand: e, .. }
1030        | Expr::Cast { operand: e, .. }
1031        | Expr::InstanceOf { operand: e, .. } => at(e, outer),
1032        Expr::Union(lhs, rhs)
1033        | Expr::Range(lhs, rhs)
1034        | Expr::And(lhs, rhs)
1035        | Expr::Or(lhs, rhs)
1036        | Expr::Arithmetic { lhs, rhs, .. }
1037        | Expr::Comparison { lhs, rhs, .. } => at(lhs, outer) || at(rhs, outer),
1038        Expr::If {
1039            condition,
1040            then,
1041            otherwise,
1042        } => at(condition, outer) || at(then, outer) || at(otherwise, outer),
1043        Expr::For { bindings: b, body } => bindings(b) || at(body, outer),
1044        Expr::Quantified {
1045            bindings: b,
1046            satisfies,
1047            ..
1048        } => bindings(b) || at(satisfies, outer),
1049    }
1050}
1051
1052/// Whether an expression calls `fn:document` anywhere.
1053fn calls_document(expr: &Expr) -> bool {
1054    let any = |exprs: &[Expr]| exprs.iter().any(calls_document);
1055    let bindings = |bindings: &[ast::Binding]| bindings.iter().any(|b| calls_document(&b.sequence));
1056    match expr {
1057        Expr::FunctionCall { name, args } => {
1058            (name.namespace.as_deref() == Some(ast::FN_NAMESPACE) && name.local == "document")
1059                || any(args)
1060        }
1061        Expr::Literal(_) | Expr::VarRef(_) | Expr::ContextItem => false,
1062        Expr::Sequence(items) => any(items),
1063        Expr::Filter { base, predicates } => calls_document(base) || any(predicates),
1064        Expr::Path(path) => path.steps.iter().any(|step| match step {
1065            ast::Step::Axis(axis_step) => any(&axis_step.predicates),
1066            ast::Step::Expr(e) => calls_document(e),
1067        }),
1068        Expr::Negate(e)
1069        | Expr::Castable { operand: e, .. }
1070        | Expr::Cast { operand: e, .. }
1071        | Expr::InstanceOf { operand: e, .. } => calls_document(e),
1072        Expr::Union(lhs, rhs)
1073        | Expr::Range(lhs, rhs)
1074        | Expr::And(lhs, rhs)
1075        | Expr::Or(lhs, rhs)
1076        | Expr::Arithmetic { lhs, rhs, .. }
1077        | Expr::Comparison { lhs, rhs, .. } => calls_document(lhs) || calls_document(rhs),
1078        Expr::If {
1079            condition,
1080            then,
1081            otherwise,
1082        } => calls_document(condition) || calls_document(then) || calls_document(otherwise),
1083        Expr::For { bindings: b, body } => bindings(b) || calls_document(body),
1084        Expr::Quantified {
1085            bindings: b,
1086            satisfies,
1087            ..
1088        } => bindings(b) || calls_document(satisfies),
1089    }
1090}
1091
1092/// Whether the predicates of a pattern alternative call `fn:document` anywhere.
1093fn pattern_calls_document(alternative: &ast::PatternAlternative) -> bool {
1094    let any = |exprs: &[Expr]| exprs.iter().any(calls_document);
1095    match alternative {
1096        ast::PatternAlternative::DocumentRoot | ast::PatternAlternative::RootFunction => false,
1097        ast::PatternAlternative::Path(path) => std::iter::once(&path.first)
1098            .chain(path.rest.iter().map(|(_, step)| step))
1099            .any(|step| match step {
1100                ast::PathStep::Axis(step) => any(&step.predicates),
1101                ast::PathStep::Parenthesized { inner, predicates } => {
1102                    inner.alternatives.iter().any(pattern_calls_document) || any(predicates)
1103                }
1104            }),
1105    }
1106}
1107
1108fn cardinality_of(occurrence: Occurrence) -> Cardinality {
1109    match occurrence {
1110        Occurrence::One | Occurrence::ZeroOrOne => Cardinality::AtMostOne,
1111        Occurrence::ZeroOrMore | Occurrence::OneOrMore => Cardinality::Any,
1112    }
1113}
1114
1115/// What a binding's value is, for the inference of its static type.
1116fn binding_value(value: &Value) -> BindingValue<'_> {
1117    match value {
1118        Value::Select(expr) => BindingValue::Select(expr),
1119        Value::Content(_) => BindingValue::Content,
1120        Value::Absent => BindingValue::Absent,
1121    }
1122}
1123
1124/// What is statically known of the number of items of a binding's value.
1125fn binding_cardinality(as_type: Option<&SequenceType>, value: &Value) -> Cardinality {
1126    if let Some(t) = as_type {
1127        return cardinality_of(t.occurrence);
1128    }
1129    match value {
1130        Value::Select(expr) if !expr.is_at_most_one() => Cardinality::Any,
1131        Value::Select(_) | Value::Content(_) | Value::Absent => Cardinality::AtMostOne,
1132    }
1133}
1134
1135struct Compiler<'s> {
1136    sheet: &'s Stylesheet,
1137    /// Names of literal result elements and their attributes, shared.
1138    names: Vec<Arc<QName>>,
1139    errors: Vec<PrepareError>,
1140    globals: Vec<(QName, VariableInfo)>,
1141    /// How many globals are declared before the declaration being compiled.
1142    typed_globals: usize,
1143    functions: Vec<(QName, usize)>,
1144    /// The declared result types of the functions, by identity.
1145    function_types: Vec<ValueType>,
1146    modes: Vec<Mode>,
1147    /// Whether some expression compiled so far calls `document()`.
1148    calls_document: bool,
1149    /// How many [`Eval::Learning`] bindings so far.
1150    learners: usize,
1151    /// Whether the bindings being compiled are in an `xsl:function` body.
1152    in_function: bool,
1153    /// The URI of the module of the declaration being compiled.
1154    module_uri: Option<String>,
1155}
1156
1157/// Collects the modes named by templates and by `xsl:apply-templates`.
1158fn collect_modes(instructions: &[Instruction], modes: &mut BTreeSet<Mode>) {
1159    for instruction in instructions {
1160        match instruction {
1161            Instruction::ApplyTemplates(apply) => {
1162                if let ApplyMode::Mode(mode) = &apply.mode {
1163                    modes.insert(mode.clone());
1164                }
1165                collect_params(&apply.params, modes);
1166            }
1167            Instruction::NextMatch(n) => collect_params(&n.params, modes),
1168            Instruction::CallTemplate(c) => collect_params(&c.params, modes),
1169            Instruction::Choose(choose) => {
1170                for when in &choose.whens {
1171                    collect_modes(&when.body, modes);
1172                }
1173                if let Some(otherwise) = &choose.otherwise {
1174                    collect_modes(otherwise, modes);
1175                }
1176            }
1177            Instruction::If(i) => collect_modes(&i.body, modes),
1178            Instruction::ForEach(f) => collect_modes(&f.body, modes),
1179            Instruction::Variable(v) => collect_value(&v.value, modes),
1180            Instruction::ValueOf(v) => collect_modes(&v.body, modes),
1181            Instruction::Attribute(a) => collect_modes(&a.body, modes),
1182            Instruction::Comment(c) => collect_modes(&c.body, modes),
1183            Instruction::LiteralElement(e) => collect_modes(&e.body, modes),
1184            Instruction::Copy(c) => collect_modes(&c.body, modes),
1185            Instruction::Element(e) => collect_modes(&e.body, modes),
1186            Instruction::Namespace(n) => collect_modes(&n.body, modes),
1187            Instruction::ProcessingInstruction(p) => collect_modes(&p.body, modes),
1188            Instruction::Message(m) => collect_modes(&m.body, modes),
1189            Instruction::Sequence(_)
1190            | Instruction::Text(_)
1191            | Instruction::Number(_)
1192            | Instruction::CopyOf(_) => {}
1193        }
1194    }
1195}
1196
1197fn collect_params(params: &[Variable], modes: &mut BTreeSet<Mode>) {
1198    for p in params {
1199        collect_value(&p.value, modes);
1200    }
1201}
1202
1203fn collect_value(value: &VariableValue, modes: &mut BTreeSet<Mode>) {
1204    if let VariableValue::Content(body) = value {
1205        collect_modes(body, modes);
1206    }
1207}
1208
1209impl Compiler<'_> {
1210    fn error(&mut self, line: u32, message: impl Into<String>) {
1211        self.errors.push(PrepareError {
1212            line,
1213            message: message.into(),
1214        });
1215    }
1216
1217    fn scope<'a>(&'a self, frame: Option<&'a Frame>) -> Scope<'a> {
1218        Scope {
1219            globals: &self.globals,
1220            typed_globals: self.typed_globals,
1221            functions: &self.functions,
1222            function_types: &self.function_types,
1223            frame,
1224            static_base: self.module_uri.as_deref(),
1225        }
1226    }
1227
1228    fn expr(&mut self, line: u32, expr: &Expr, frame: Option<&Frame>) -> Option<Box<CompiledExpr>> {
1229        self.calls_document |= calls_document(expr);
1230        let scope = self.scope(frame);
1231        match compile(expr, &scope) {
1232            Ok(compiled) => Some(Box::new(compiled)),
1233            Err(e) => {
1234                self.error(line, format!("{expr}: {e}"));
1235                None
1236            }
1237        }
1238    }
1239
1240    fn avt(&mut self, line: u32, avt: &Avt, frame: Option<&Frame>) -> Option<CompiledAvt> {
1241        let mut items = Vec::with_capacity(avt.parts.len());
1242        let mut ok = true;
1243        for part in &avt.parts {
1244            match part {
1245                AvtPart::Text(text) => items.push(AvtItem::Text(text.as_str().into())),
1246                AvtPart::Expr(e) => match self.expr(line, e, frame) {
1247                    Some(c) => items.push(AvtItem::Expr(c)),
1248                    None => ok = false,
1249                },
1250            }
1251        }
1252        ok.then_some(CompiledAvt(items))
1253    }
1254
1255    /// A shared copy of `name` (the prefix counts: it is serialized).
1256    fn intern(&mut self, name: &QName) -> Arc<QName> {
1257        if let Some(shared) = self.names.iter().find(|n| ***n == *name) {
1258            return Arc::clone(shared);
1259        }
1260        let shared = Arc::new(name.clone());
1261        self.names.push(Arc::clone(&shared));
1262        shared
1263    }
1264
1265    fn mode_index(&self, mode: &Mode) -> usize {
1266        self.modes.iter().position(|m| m == mode).unwrap_or(0)
1267    }
1268
1269    /// The value of a binding (its content is a temporary tree without `as`, a sequence
1270    /// with it, which the executor tells apart).
1271    fn value(&mut self, line: u32, value: &VariableValue, frame: &mut Frame) -> Value {
1272        match value {
1273            VariableValue::Select(expr) => self
1274                .expr(line, expr, Some(frame))
1275                .map_or(Value::Absent, Value::Select),
1276            VariableValue::Content(body) => Value::Content(self.sequence_constructor(body, frame)),
1277            VariableValue::Absent => Value::Absent,
1278        }
1279    }
1280
1281    /// The `xsl:with-param` of an instruction: evaluated eagerly by `xsl:apply-templates`
1282    /// and `xsl:next-match` (`lazy` false), as Saxon evaluates them, lazily with Saxon's
1283    /// learning by `xsl:call-template`.
1284    fn with_params(
1285        &mut self,
1286        params: &[Variable],
1287        frame: &mut Frame,
1288        lazy: bool,
1289    ) -> Vec<WithParam> {
1290        let mut compiled = Vec::with_capacity(params.len());
1291        for p in params {
1292            let value = self.value(p.line, &p.value, frame);
1293            let eval = if lazy {
1294                self.learning(&p.value)
1295            } else {
1296                Eval::Eager
1297            };
1298            compiled.push(WithParam {
1299                name: p.name.clone(),
1300                as_type: p.as_type.clone(),
1301                value,
1302                eval,
1303            });
1304        }
1305        compiled
1306    }
1307
1308    /// [`Eval::Learning`] with new counters, or [`Eval::Eager`] for a value that depends
1309    /// on the position, the size or the current item of its focus, which Saxon never
1310    /// evaluates lazily (`Expression.supportsLazyEvaluation`).
1311    fn learning(&mut self, value: &VariableValue) -> Eval {
1312        if depends_on_focus_position(value) {
1313            return Eval::Eager;
1314        }
1315        let learner = self.learners;
1316        self.learners += 1;
1317        Eval::Learning {
1318            learner,
1319            every_counts: self.in_function,
1320        }
1321    }
1322
1323    /// Compiles a sequence constructor. Local variables are in scope for their
1324    /// following siblings and their descendants.
1325    fn sequence_constructor(
1326        &mut self,
1327        instructions: &[Instruction],
1328        frame: &mut Frame,
1329    ) -> Vec<Inst> {
1330        let scope_depth = frame.locals.len();
1331        let mut out = Vec::with_capacity(instructions.len());
1332        for instruction in instructions {
1333            if let Some(inst) = self.instruction(instruction, frame) {
1334                out.push(inst);
1335            }
1336        }
1337        frame.locals.truncate(scope_depth);
1338        out
1339    }
1340
1341    /// When the local variables of a template, function or global variable are
1342    /// evaluated, once its whole body is compiled (`body`, and the default values of its
1343    /// parameters, `params`), as Saxon-HE 12.10 decides it (`LetExpression.optimize` and
1344    /// `setEvaluator`):
1345    ///
1346    /// - unused (no reference left once the unused variables are removed): never;
1347    /// - referred to once, not in a loop: inlined into the reference, evaluated when it
1348    ///   is ([`Eval::Lazy`]);
1349    /// - otherwise as Saxon counts its references, which it does not always count again
1350    ///   after inlining others: a variable keeps the references it had, less those in
1351    ///   the values of the variables removed since, unless it is optimized again: when the
1352    ///   variable right after it is removed (its action changes), or a variable before
1353    ///   it in scope has the variable right after it removed (which optimizes all that
1354    ///   follows again, `verifyReferences`). With two references or more (or one in a
1355    ///   loop), Saxon's learning ([`Eval::Learning`]); with one or none, a value of at
1356    ///   most one item is computed where it is bound (`LazyPullEvaluator` on an item), any
1357    ///   other when first read.
1358    fn decide_frame(&mut self, frame: &mut Frame, body: &mut [Inst], params: &mut [Binding]) {
1359        // The references left, per slot: none in the value of an unused variable. A
1360        // reference is always from a variable declared later, with a higher slot.
1361        let mut live = vec![0_u32; frame.slots];
1362        let is_variable = Self::variable_slots(body, params, frame.slots);
1363        for slot in (0..frame.slots).rev() {
1364            let count = frame
1365                .references
1366                .borrow()
1367                .iter()
1368                .filter(|(target, enclosing)| {
1369                    *target == slot
1370                        && !frame.removed_with(slot, enclosing, &|e| {
1371                            is_variable.get(e).copied().unwrap_or(false)
1372                                && live.get(e).copied().unwrap_or(0) == 0
1373                        })
1374                })
1375                .count();
1376            live[slot] = u32::try_from(count).unwrap_or(u32::MAX);
1377            let looping = frame.looping.borrow().get(slot).copied().unwrap_or(true);
1378            if let Some(gone) = frame.gone.get_mut(slot) {
1379                *gone = is_variable.get(slot).copied().unwrap_or(false)
1380                    && (live[slot] == 0 || (live[slot] == 1 && !looping));
1381            }
1382        }
1383        for param in params.iter_mut() {
1384            if let Value::Content(content) = &mut param.value {
1385                self.decide_sequence(frame, &live, content, false);
1386            }
1387        }
1388        self.decide_sequence(frame, &live, body, false);
1389    }
1390
1391    /// Which slots are local variables (not parameters).
1392    fn variable_slots(body: &[Inst], params: &[Binding], slots: usize) -> Vec<bool> {
1393        fn walk(insts: &[Inst], out: &mut Vec<bool>) {
1394            for inst in insts {
1395                if let Inst::Variable(b) = inst
1396                    && let Some(v) = out.get_mut(b.slot)
1397                {
1398                    *v = true;
1399                }
1400                for_each_body(inst, &mut |body| walk(body, out));
1401            }
1402        }
1403        let mut out = vec![false; slots];
1404        for param in params {
1405            if let Value::Content(content) = &param.value {
1406                walk(content, &mut out);
1407            }
1408        }
1409        walk(body, &mut out);
1410        out
1411    }
1412
1413    /// [`Compiler::decide_frame`] on one sequence constructor; `again`: a variable before
1414    /// it in scope is optimized again.
1415    fn decide_sequence(&mut self, frame: &Frame, live: &[u32], insts: &mut [Inst], again: bool) {
1416        let is_gone = |slot: usize| frame.gone.get(slot).copied().unwrap_or(false);
1417        let next_is_gone: Vec<bool> = (0..insts.len())
1418            .map(|i| matches!(insts.get(i + 1), Some(Inst::Variable(next)) if is_gone(next.slot)))
1419            .collect();
1420        let mut again = again;
1421        for (inst, next_is_gone) in insts.iter_mut().zip(next_is_gone) {
1422            if let Inst::Variable(binding) = inst {
1423                let slot = binding.slot;
1424                binding.used = live.get(slot).copied().unwrap_or(0) > 0;
1425                if !is_gone(slot) && binding.eval != Eval::Eager {
1426                    let looping = frame.looping.borrow().get(slot).copied().unwrap_or(true);
1427                    let registered = if again || next_is_gone {
1428                        live.get(slot).copied().unwrap_or(0)
1429                    } else {
1430                        let kept = frame
1431                            .references
1432                            .borrow()
1433                            .iter()
1434                            .filter(|(target, enclosing)| {
1435                                *target == slot && !frame.removed_with(slot, enclosing, &is_gone)
1436                            })
1437                            .count();
1438                        u32::try_from(kept).unwrap_or(u32::MAX)
1439                    };
1440                    binding.eval = if looping || registered >= 2 {
1441                        let learner = self.learners;
1442                        self.learners += 1;
1443                        Eval::Learning {
1444                            learner,
1445                            every_counts: self.in_function,
1446                        }
1447                    } else if matches!(&binding.value, Value::Select(e) if e.is_at_most_one()) {
1448                        Eval::Eager
1449                    } else {
1450                        Eval::Lazy
1451                    };
1452                }
1453            }
1454            let mut bodies: Vec<&mut Vec<Inst>> = Vec::new();
1455            for_each_body_mut(inst, &mut |body| bodies.push(body));
1456            for body in bodies {
1457                self.decide_sequence(frame, live, body, again);
1458            }
1459            if let Inst::Variable(binding) = inst
1460                && !is_gone(binding.slot)
1461                && next_is_gone
1462            {
1463                // Its action changes: what follows is optimized again.
1464                again = true;
1465            }
1466        }
1467    }
1468
1469    /// Compiles one instruction. Each kind is compiled by a function of its own, so that
1470    /// the recursion over nested instructions holds, at each level, only what that
1471    /// level's instruction needs (the call stack of a debug build keeps every local of a
1472    /// function).
1473    fn instruction(&mut self, instruction: &Instruction, frame: &mut Frame) -> Option<Inst> {
1474        match instruction {
1475            Instruction::ApplyTemplates(apply) => self.apply_templates(apply, frame),
1476            Instruction::NextMatch(next) => Some(self.next_match(next, frame)),
1477            Instruction::CallTemplate(call) => self.call_template(call, frame),
1478            Instruction::Choose(choose) => self.choose(choose, frame),
1479            Instruction::If(i) => self.if_instruction(i, frame),
1480            Instruction::ForEach(f) => self.for_each(f, frame),
1481            Instruction::Variable(v) => Some(self.local_variable(v, frame)),
1482            Instruction::Sequence(s) => self.sequence(s, frame),
1483            Instruction::ValueOf(v) => self.value_of(v, frame),
1484            Instruction::Attribute(a) => self.attribute(a, frame),
1485            Instruction::Comment(c) => Some(self.comment(c, frame)),
1486            Instruction::Text(t) => Some(Inst::Text(t.value.as_str().into())),
1487            Instruction::Number(n) => self.number(n),
1488            Instruction::LiteralElement(e) => self.literal_element(e, frame),
1489            Instruction::Copy(c) => Some(self.copy(c, frame)),
1490            Instruction::CopyOf(c) => self.copy_of(c, frame),
1491            Instruction::Element(e) => self.computed_element(e, frame),
1492            Instruction::Namespace(n) => self.namespace(n, frame),
1493            Instruction::ProcessingInstruction(p) => self.processing_instruction(p, frame),
1494            Instruction::Message(m) => self.message(m, frame),
1495        }
1496    }
1497
1498    /// `xsl:apply-templates`.
1499    fn apply_templates(&mut self, apply: &ApplyTemplates, frame: &mut Frame) -> Option<Inst> {
1500        let select = if let Some(e) = &apply.select {
1501            self.expr(apply.line, e, Some(frame))
1502        } else {
1503            let children = parse_expr("child::node()", &NamespaceMap::new()).ok()?;
1504            self.expr(apply.line, &children, Some(frame))
1505        };
1506        let mode = match &apply.mode {
1507            ApplyMode::Current => ModeRef::Current,
1508            ApplyMode::Mode(m) => ModeRef::Mode(self.mode_index(m)),
1509        };
1510        let params = self.with_params(&apply.params, frame, false);
1511        Some(Inst::ApplyTemplates(CompiledApplyTemplates {
1512            line: apply.line,
1513            select: select?,
1514            mode,
1515            params,
1516        }))
1517    }
1518
1519    /// `xsl:next-match`.
1520    fn next_match(&mut self, next: &NextMatch, frame: &mut Frame) -> Inst {
1521        Inst::NextMatch(CompiledNextMatch {
1522            line: next.line,
1523            params: self.with_params(&next.params, frame, false),
1524        })
1525    }
1526
1527    /// `xsl:call-template`.
1528    fn call_template(&mut self, call: &CallTemplate, frame: &mut Frame) -> Option<Inst> {
1529        let Some(template) = self.sheet.named_template_index(&call.name) else {
1530            self.error(
1531                call.line,
1532                format!("no template named {} (XTSE0650)", call.name),
1533            );
1534            return None;
1535        };
1536        let declared = &self.sheet.templates[template].params;
1537        if let Some(p) = call
1538            .params
1539            .iter()
1540            .find(|p| !declared.iter().any(|d| d.name.same_expanded_name(&p.name)))
1541        {
1542            let message = format!(
1543                "parameter {} is not declared by template {} (XTSE0680)",
1544                p.name, call.name
1545            );
1546            self.error(call.line, message);
1547            return None;
1548        }
1549        Some(Inst::CallTemplate(CompiledCallTemplate {
1550            line: call.line,
1551            template,
1552            params: self.with_params(&call.params, frame, true),
1553        }))
1554    }
1555
1556    /// `xsl:choose`.
1557    fn choose(&mut self, choose: &Choose, frame: &mut Frame) -> Option<Inst> {
1558        let mut whens = Vec::with_capacity(choose.whens.len());
1559        for when in &choose.whens {
1560            whens.push(self.when(when.line, &when.test, &when.body, frame)?);
1561        }
1562        let otherwise = match &choose.otherwise {
1563            Some(body) => self.sequence_constructor(body, frame),
1564            None => Vec::new(),
1565        };
1566        Some(Inst::Choose(CompiledChoose { whens, otherwise }))
1567    }
1568
1569    /// `xsl:when`, and `xsl:if` as a `xsl:choose` of one `xsl:when`.
1570    fn when(
1571        &mut self,
1572        line: u32,
1573        test: &Expr,
1574        body: &[Instruction],
1575        frame: &mut Frame,
1576    ) -> Option<When> {
1577        let test = self.expr(line, test, Some(frame));
1578        let body = self.sequence_constructor(body, frame);
1579        Some(When {
1580            line,
1581            test: test?,
1582            body,
1583        })
1584    }
1585
1586    /// `xsl:if`.
1587    fn if_instruction(&mut self, i: &If, frame: &mut Frame) -> Option<Inst> {
1588        let when = self.when(i.line, &i.test, &i.body, frame)?;
1589        Some(Inst::Choose(CompiledChoose {
1590            whens: vec![when],
1591            otherwise: Vec::new(),
1592        }))
1593    }
1594
1595    /// `xsl:for-each`.
1596    fn for_each(&mut self, f: &ForEach, frame: &mut Frame) -> Option<Inst> {
1597        let select = self.expr(f.line, &f.select, Some(frame));
1598        frame.depth += 1;
1599        let body = self.sequence_constructor(&f.body, frame);
1600        frame.depth -= 1;
1601        Some(Inst::ForEach(CompiledForEach {
1602            line: f.line,
1603            select: select?,
1604            body,
1605        }))
1606    }
1607
1608    /// A local `xsl:variable`.
1609    fn local_variable(&mut self, v: &Variable, frame: &mut Frame) -> Inst {
1610        let slot = frame.reserve();
1611        frame.enclosing.push(slot);
1612        let value = self.value(v.line, &v.value, frame);
1613        frame.enclosing.pop();
1614        let cardinality = binding_cardinality(v.as_type.as_ref(), &value);
1615        let value_type = ValueType::local_variable(binding_value(&value), v.as_type.as_ref());
1616        frame.bind(
1617            slot,
1618            v.name.clone(),
1619            cardinality,
1620            value_type,
1621            self.globals.len(),
1622        );
1623        // Decided once the references in its scope are known (`sequence_constructor`).
1624        let eval = if depends_on_focus_position(&v.value) {
1625            Eval::Eager
1626        } else {
1627            Eval::Lazy
1628        };
1629        Inst::Variable(Box::new(Binding {
1630            line: v.line,
1631            name: v.name.clone(),
1632            slot,
1633            as_type: v.as_type.clone(),
1634            value,
1635            eval,
1636            used: false,
1637        }))
1638    }
1639
1640    /// `xsl:sequence`.
1641    fn sequence(&mut self, s: &Sequence, frame: &mut Frame) -> Option<Inst> {
1642        Some(Inst::Sequence {
1643            line: s.line,
1644            select: self.expr(s.line, &s.select, Some(frame))?,
1645        })
1646    }
1647
1648    /// `xsl:value-of`.
1649    fn value_of(&mut self, v: &ValueOf, frame: &mut Frame) -> Option<Inst> {
1650        let select = v.select.as_ref().map(|e| self.expr(v.line, e, Some(frame)));
1651        let separator = v
1652            .separator
1653            .as_ref()
1654            .map(|s| self.avt(v.line, s, Some(frame)));
1655        let body = self.sequence_constructor(&v.body, frame);
1656        Some(Inst::ValueOf {
1657            line: v.line,
1658            select: select.map_or(Some(None), |s| s.map(Some))?,
1659            separator: separator.map_or(Some(None), |s| s.map(Some))?,
1660            body,
1661        })
1662    }
1663
1664    /// `xsl:attribute`.
1665    fn attribute(&mut self, a: &Attribute, frame: &mut Frame) -> Option<Inst> {
1666        let name = self.avt(a.line, &a.name, Some(frame));
1667        let namespace = a
1668            .namespace
1669            .as_ref()
1670            .map(|n| self.avt(a.line, n, Some(frame)));
1671        let select = a.select.as_ref().map(|e| self.expr(a.line, e, Some(frame)));
1672        let body = self.sequence_constructor(&a.body, frame);
1673        Some(Inst::Attribute {
1674            line: a.line,
1675            name: name?,
1676            namespace: namespace.map_or(Some(None), |n| n.map(Some))?,
1677            namespaces: Arc::clone(&a.namespaces),
1678            select: select.map_or(Some(None), |s| s.map(Some))?,
1679            body,
1680        })
1681    }
1682
1683    /// `xsl:comment`.
1684    fn comment(&mut self, c: &Comment, frame: &mut Frame) -> Inst {
1685        Inst::Comment {
1686            line: c.line,
1687            body: self.sequence_constructor(&c.body, frame),
1688        }
1689    }
1690
1691    /// `xsl:copy`.
1692    fn copy(&mut self, c: &Copy, frame: &mut Frame) -> Inst {
1693        Inst::Copy {
1694            line: c.line,
1695            body: self.sequence_constructor(&c.body, frame),
1696        }
1697    }
1698
1699    /// `xsl:copy-of`.
1700    fn copy_of(&mut self, c: &CopyOf, frame: &mut Frame) -> Option<Inst> {
1701        Some(Inst::CopyOf {
1702            line: c.line,
1703            select: self.expr(c.line, &c.select, Some(frame))?,
1704        })
1705    }
1706
1707    /// `xsl:element`.
1708    fn computed_element(&mut self, e: &Element, frame: &mut Frame) -> Option<Inst> {
1709        let name = self.avt(e.line, &e.name, Some(frame));
1710        let namespace = e
1711            .namespace
1712            .as_ref()
1713            .map(|n| self.avt(e.line, n, Some(frame)));
1714        let body = self.sequence_constructor(&e.body, frame);
1715        Some(Inst::ComputedElement {
1716            line: e.line,
1717            name: name?,
1718            namespace: namespace.map_or(Some(None), |n| n.map(Some))?,
1719            namespaces: Arc::clone(&e.namespaces),
1720            body,
1721        })
1722    }
1723
1724    /// `xsl:namespace`.
1725    fn namespace(&mut self, n: &NamespaceNode, frame: &mut Frame) -> Option<Inst> {
1726        let name = self.avt(n.line, &n.name, Some(frame));
1727        let select = n.select.as_ref().map(|e| self.expr(n.line, e, Some(frame)));
1728        let body = self.sequence_constructor(&n.body, frame);
1729        Some(Inst::Namespace {
1730            line: n.line,
1731            name: name?,
1732            select: select.map_or(Some(None), |s| s.map(Some))?,
1733            body,
1734        })
1735    }
1736
1737    /// `xsl:processing-instruction`.
1738    fn processing_instruction(
1739        &mut self,
1740        p: &ProcessingInstruction,
1741        frame: &mut Frame,
1742    ) -> Option<Inst> {
1743        let name = self.avt(p.line, &p.name, Some(frame));
1744        let select = p.select.as_ref().map(|e| self.expr(p.line, e, Some(frame)));
1745        let body = self.sequence_constructor(&p.body, frame);
1746        Some(Inst::ProcessingInstruction {
1747            line: p.line,
1748            name: name?,
1749            select: select.map_or(Some(None), |s| s.map(Some))?,
1750            body,
1751        })
1752    }
1753
1754    /// `xsl:message`.
1755    fn message(&mut self, m: &Message, frame: &mut Frame) -> Option<Inst> {
1756        let terminate = m
1757            .terminate
1758            .as_ref()
1759            .map(|t| self.avt(m.line, t, Some(frame)));
1760        let body = self.sequence_constructor(&m.body, frame);
1761        Some(Inst::Message {
1762            line: m.line,
1763            terminate: terminate.map_or(Some(None), |t| t.map(Some))?,
1764            body,
1765        })
1766    }
1767
1768    /// `xsl:number`.
1769    fn number(&mut self, n: &Number) -> Option<Inst> {
1770        let count = match &n.count {
1771            None => None,
1772            Some(p) => Some(CountPattern {
1773                alternatives: self.pattern(n.line, p)?,
1774                text: p.to_string(),
1775            }),
1776        };
1777        Some(Inst::Number {
1778            line: n.line,
1779            level: n.level,
1780            count,
1781        })
1782    }
1783
1784    /// A literal result element.
1785    fn literal_element(&mut self, e: &LiteralElement, frame: &mut Frame) -> Option<Inst> {
1786        let mut attributes = Vec::with_capacity(e.attributes.len());
1787        let mut ok = true;
1788        for attribute in &e.attributes {
1789            match self.avt(e.line, &attribute.value, Some(frame)) {
1790                Some(value) => attributes.push((self.intern(&attribute.name), value)),
1791                None => ok = false,
1792            }
1793        }
1794        let body = self.sequence_constructor(&e.body, frame);
1795        if !ok {
1796            return None;
1797        }
1798        Some(Inst::Element(CompiledElement {
1799            line: e.line,
1800            name: self.intern(&e.name),
1801            namespaces: Arc::clone(&e.namespaces),
1802            attributes,
1803            body,
1804        }))
1805    }
1806
1807    /// A pattern (template `match`, `xsl:number/@count`): global variables only.
1808    fn pattern(&mut self, line: u32, pattern: &ast::Pattern) -> Option<Vec<Alternative>> {
1809        let mut out = Vec::with_capacity(pattern.alternatives.len());
1810        for alternative in &pattern.alternatives {
1811            self.calls_document |= pattern_calls_document(alternative);
1812            let scope = self.scope(None);
1813            match pattern::compile_alternative(alternative, &scope) {
1814                Ok(a) => out.push(a),
1815                Err(message) => {
1816                    self.error(line, format!("pattern {alternative}: {message}"));
1817                    return None;
1818                }
1819            }
1820        }
1821        Some(out)
1822    }
1823
1824    /// Template and function parameters, declared in order in `frame`.
1825    fn params(&mut self, params: &[Variable], frame: &mut Frame) -> Vec<Binding> {
1826        let mut out = Vec::with_capacity(params.len());
1827        for p in params {
1828            let value = self.value(p.line, &p.value, frame);
1829            let cardinality = p
1830                .as_type
1831                .as_ref()
1832                .map_or(Cardinality::Any, |t| cardinality_of(t.occurrence));
1833            let eval = self.learning(&p.value);
1834            let slot = frame.declare(
1835                p.name.clone(),
1836                cardinality,
1837                ValueType::declared(p.as_type.as_ref()),
1838                self.globals.len(),
1839            );
1840            out.push(Binding {
1841                line: p.line,
1842                name: p.name.clone(),
1843                slot,
1844                as_type: p.as_type.clone(),
1845                value,
1846                eval,
1847                used: true,
1848            });
1849        }
1850        out
1851    }
1852
1853    fn template(&mut self, template: &Template) -> CompiledTemplate {
1854        self.typed_globals = self.globals_before(template.module, template.line);
1855        self.module_uri = self.module_uri_of(template.module);
1856        let mut frame = Frame::default();
1857        let mut params = self.params(&template.params, &mut frame);
1858        let mut body = self.sequence_constructor(&template.body, &mut frame);
1859        self.decide_frame(&mut frame, &mut body, &mut params);
1860        let (pattern, pattern_text, alternative_texts) = match &template.pattern {
1861            Some(p) => (
1862                self.pattern(template.line, p).unwrap_or_default(),
1863                p.to_string(),
1864                p.alternatives.iter().map(ToString::to_string).collect(),
1865            ),
1866            None => (Vec::new(), String::new(), Vec::new()),
1867        };
1868        CompiledTemplate {
1869            line: template.line,
1870            params,
1871            tail_calls: has_tail_call(&body),
1872            body,
1873            slots: frame.slots,
1874            pattern,
1875            pattern_text,
1876            alternative_texts,
1877        }
1878    }
1879}
1880
1881impl Executable {
1882    /// Prepares a loaded stylesheet.
1883    ///
1884    /// # Errors
1885    ///
1886    /// Every problem found: XPath expressions that do not compile in their static
1887    /// context (unknown variables or functions), calls of undeclared templates, and the
1888    /// constructs refused because their result would differ from the reference engine's
1889    /// (instructions that construct nodes inside an `xsl:function` or a variable with
1890    /// `as`, a positional predicate in a parenthesized pattern, `system-property()` with
1891    /// a prefixed name).
1892    pub fn new(sheet: &Stylesheet) -> Result<Self, PrepareErrors> {
1893        let mut modes = BTreeSet::new();
1894        modes.insert(Mode::Default);
1895        for template in &sheet.templates {
1896            if template.pattern.is_some()
1897                && let TemplateModes::Listed(listed) = &template.modes
1898            {
1899                modes.extend(listed.iter().cloned());
1900            }
1901            collect_modes(&template.body, &mut modes);
1902            collect_params(&template.params, &mut modes);
1903        }
1904        for function in &sheet.functions {
1905            collect_modes(&function.body, &mut modes);
1906        }
1907        for global in &sheet.globals {
1908            collect_value(&global.variable.value, &mut modes);
1909        }
1910        let mut compiler = Compiler {
1911            sheet,
1912            names: Vec::new(),
1913            errors: Vec::new(),
1914            globals: Vec::new(),
1915            typed_globals: 0,
1916            functions: sheet
1917                .functions
1918                .iter()
1919                .map(|f| (f.name.clone(), f.params.len()))
1920                .collect(),
1921            function_types: sheet
1922                .functions
1923                .iter()
1924                .map(|f| ValueType::declared(f.as_type.as_ref()))
1925                .collect(),
1926            modes: modes.into_iter().collect(),
1927            calls_document: false,
1928            learners: 0,
1929            in_function: false,
1930            module_uri: None,
1931        };
1932        let globals = compiler.globals(sheet);
1933        let templates: Vec<CompiledTemplate> = sheet
1934            .templates
1935            .iter()
1936            .map(|t| compiler.template(t))
1937            .collect();
1938        let functions = sheet
1939            .functions
1940            .iter()
1941            .map(|f| {
1942                compiler.typed_globals = compiler.globals_before(f.module, f.line);
1943                compiler.module_uri = compiler.module_uri_of(f.module);
1944                let mut frame = Frame::default();
1945                let mut params = compiler.params(&f.params, &mut frame);
1946                compiler.in_function = true;
1947                let mut body = compiler.sequence_constructor(&f.body, &mut frame);
1948                compiler.decide_frame(&mut frame, &mut body, &mut params);
1949                compiler.in_function = false;
1950                CompiledFunction {
1951                    line: f.line,
1952                    name: f.name.clone(),
1953                    params,
1954                    as_type: f.as_type.clone(),
1955                    body,
1956                    slots: frame.slots,
1957                }
1958            })
1959            .collect();
1960        let (compiled_modes, rule_names) = compile_modes(sheet, &templates, &compiler.modes);
1961        if !compiler.errors.is_empty() {
1962            compiler.errors.sort_by_key(|e| e.line);
1963            return Err(PrepareErrors(compiler.errors));
1964        }
1965        let default_mode = compiler.mode_index(&Mode::Default);
1966        let serialization = sheet
1967            .output
1968            .map_or_else(Serialization::default, |o| Serialization {
1969                indent: o.indent == Some(true),
1970                omit_xml_declaration: o.omit_xml_declaration == Some(true),
1971                standalone: match o.standalone {
1972                    Some(Standalone::Yes) => Some(true),
1973                    Some(Standalone::No) => Some(false),
1974                    Some(Standalone::Omit) | None => None,
1975                },
1976            });
1977        Ok(Self {
1978            globals,
1979            templates,
1980            functions,
1981            modes: compiled_modes,
1982            default_mode,
1983            serialization,
1984            base_uri: None,
1985            calls_document: compiler.calls_document,
1986            learners: compiler.learners,
1987            loaded: DocumentCache::new(),
1988            regexes: RegexCache::new(),
1989            rule_names,
1990        })
1991    }
1992
1993    /// Sets the static base URI of the stylesheet (its location), against which
1994    /// `document()` resolves relative URIs given as strings.
1995    #[must_use]
1996    pub fn with_base_uri(mut self, uri: impl Into<String>) -> Self {
1997        self.base_uri = Some(uri.into());
1998        self
1999    }
2000}
2001
2002impl Compiler<'_> {
2003    /// How many global variables and parameters are declared before `line` of module
2004    /// `module`: Saxon types the declarations in document order, the modules of a lower
2005    /// import precedence first.
2006    fn globals_before(&self, module: usize, line: u32) -> usize {
2007        let precedence = self.sheet.precedence(module);
2008        self.sheet
2009            .globals
2010            .iter()
2011            .take_while(|g| {
2012                let p = self.sheet.precedence(g.module);
2013                p < precedence || (p == precedence && g.variable.line < line)
2014            })
2015            .count()
2016    }
2017
2018    /// The URI of module `module`, the static base URI of its expressions.
2019    fn module_uri_of(&self, module: usize) -> Option<String> {
2020        self.sheet.modules.get(module).and_then(|m| m.uri.clone())
2021    }
2022
2023    /// The global variables. Their static cardinality comes from their compiled value,
2024    /// which may refer to other globals: compiled again until it is stable. Their static
2025    /// type is inferred in declaration order from the types of the globals declared
2026    /// before them, and used from the second compilation on.
2027    fn globals(&mut self, sheet: &Stylesheet) -> Vec<Global> {
2028        self.globals = sheet
2029            .globals
2030            .iter()
2031            .enumerate()
2032            .map(|(i, g)| {
2033                (
2034                    g.variable.name.clone(),
2035                    VariableInfo {
2036                        id: VariableId(u32::try_from(i).unwrap_or(u32::MAX)),
2037                        cardinality: g
2038                            .variable
2039                            .as_type
2040                            .as_ref()
2041                            .map_or(Cardinality::Any, |t| cardinality_of(t.occurrence)),
2042                        value_type: ValueType::unknown(),
2043                    },
2044                )
2045            })
2046            .collect();
2047        let errors_before = self.errors.len();
2048        let mut compiled: Vec<Global> = Vec::new();
2049        for pass in 0..=sheet.globals.len() + 1 {
2050            self.errors.truncate(errors_before);
2051            compiled = Vec::with_capacity(sheet.globals.len());
2052            for (index, g) in sheet.globals.iter().enumerate() {
2053                let v = &g.variable;
2054                self.typed_globals = index;
2055                self.module_uri = self.module_uri_of(g.module);
2056                let mut frame = Frame::default();
2057                let mut value = self.value(v.line, &v.value, &mut frame);
2058                if let Value::Content(body) = &mut value {
2059                    self.decide_frame(&mut frame, body, &mut []);
2060                }
2061                let value_type = if g.kind == GlobalKind::Param {
2062                    ValueType::declared(v.as_type.as_ref())
2063                } else {
2064                    ValueType::global_variable(binding_value(&value), v.as_type.as_ref())
2065                };
2066                if let Some((_, info)) = self.globals.get_mut(index) {
2067                    info.value_type = value_type;
2068                }
2069                compiled.push(Global {
2070                    name: v.name.clone(),
2071                    is_param: g.kind == GlobalKind::Param,
2072                    line: v.line,
2073                    value,
2074                    as_type: v.as_type.clone(),
2075                    slots: frame.slots,
2076                });
2077            }
2078            // The types are final after the first compilation (each depends on the
2079            // globals declared before it only), which saw the later ones untyped.
2080            let mut changed = pass == 0;
2081            for (info, global) in self.globals.iter_mut().zip(&compiled) {
2082                let cardinality = binding_cardinality(global.as_type.as_ref(), &global.value);
2083                if info.1.cardinality != cardinality {
2084                    info.1.cardinality = cardinality;
2085                    changed = true;
2086                }
2087            }
2088            if !changed {
2089                break;
2090            }
2091        }
2092        compiled
2093    }
2094}
2095
2096/// The priority as Saxon compares priorities: a double.
2097fn as_double(priority: Priority) -> f64 {
2098    priority.to_string().parse().unwrap_or(f64::NAN)
2099}
2100
2101/// The rules of `mode`, ranked and indexed.
2102fn rank_rules(sheet: &Stylesheet, templates: &[CompiledTemplate], mode: &Mode) -> CompiledMode {
2103    let mut rules = Vec::new();
2104    for (index, template) in sheet.templates.iter().enumerate() {
2105        if template.pattern.is_none() {
2106            continue;
2107        }
2108        let in_mode = match &template.modes {
2109            TemplateModes::All => true,
2110            TemplateModes::Listed(modes) => modes.contains(mode),
2111        };
2112        if !in_mode {
2113            continue;
2114        }
2115        // Saxon-HE 12.10 keeps a union pattern with an explicit priority as one rule
2116        // (Saxon-HE 9.9 split it like a pattern without one).
2117        let whole = template.rules.len() > 1 && template.rules.iter().all(|r| !r.is_default);
2118        for rule in &template.rules {
2119            rules.push(Rule {
2120                template: index,
2121                alternative: (!whole).then_some(rule.alternative),
2122                precedence: sheet.precedence(template.module),
2123                priority: as_double(rule.priority),
2124                sequence: index,
2125                part: if rule.is_default { rule.alternative } else { 0 },
2126                certain: 0,
2127            });
2128            if whole {
2129                break;
2130            }
2131        }
2132    }
2133    rules.sort_by(|a, b| {
2134        b.compare_rank(a)
2135            .then(b.sequence.cmp(&a.sequence))
2136            .then(b.part.cmp(&a.part))
2137    });
2138    let mut compiled = CompiledMode {
2139        name: match mode {
2140            Mode::Default => "#default".to_owned(),
2141            Mode::Named(q) => q.to_string(),
2142        },
2143        ..CompiledMode::default()
2144    };
2145    for (rank, rule) in rules.iter_mut().enumerate() {
2146        let rank = u32::try_from(rank).unwrap_or(u32::MAX);
2147        let pattern = &templates[rule.template].pattern;
2148        let (keys, tried) = match rule.alternative {
2149            Some(alternative) => (
2150                pattern
2151                    .get(alternative)
2152                    .map(pattern::Alternative::chain_keys)
2153                    .unwrap_or_default(),
2154                pattern.get(alternative..=alternative).unwrap_or_default(),
2155            ),
2156            None => (
2157                pattern::union_chain_key(pattern).into_iter().collect(),
2158                pattern.as_slice(),
2159            ),
2160        };
2161        rule.certain = certain_kinds(tried, &keys);
2162        for key in &keys {
2163            compiled.index(rank, key);
2164        }
2165    }
2166    compiled.rules = rules;
2167    compiled.plan_kinds();
2168    compiled
2169}