Skip to main content

einvoice_xslt_exec/
run.rs

1//! Running an [`Executable`] on a document.
2//!
3//! Template rules are chosen as Saxon-HE chooses them: highest priority first, the last
4//! declared on a tie (an ambiguity is reported as a warning, as Saxon does), then the
5//! built-in rules of XSLT 2.0 section 6.6. A dynamic error while matching a pattern is
6//! recovered as Saxon recovers it: a warning, and the rule does not match. Variables live in frames, one per template,
7//! function or global variable invocation; the XPath evaluator reads them through the
8//! [`Host`] interface, and calls stylesheet functions through it too.
9//!
10//! Evaluation order follows Saxon where it is observable (which dynamic errors are
11//! raised): global variables are evaluated when first referenced; a local variable or
12//! parameter that nothing refers to is never evaluated; one whose `select` may return
13//! several items is evaluated when first referenced; any other is evaluated where it is
14//! declared.
15
16use std::borrow::Cow;
17use std::cell::{Cell, OnceCell, RefCell};
18use std::collections::HashSet;
19use std::rc::{Rc, Weak};
20use std::sync::Arc;
21
22use einvoice_xdm::{AtomicType, AtomicValue, DateTime};
23use einvoice_xpath::{AtomicKind, ItemType, Occurrence, QName, SequenceType};
24use einvoice_xpath_eval::{
25    Clock, CompiledExpr, Context, DEFAULT_MAX_DEPTH, Document, DocumentError, DynamicContext,
26    ErrorCode, FunctionId, Host, Item, LimitExceeded, Node, NodeAxis, NodeKind, VariableId,
27};
28use einvoice_xslt::{NamespaceBinding, NumberLevel};
29
30use crate::error::{LIMIT, Result, TransformError, err};
31use crate::pattern::{self, Matcher};
32use crate::prepare::{
33    AvtItem, Binding, CompiledAvt, CompiledTemplate, CountPattern, Executable, Inst, ModeRef,
34    Value, When, WithParam,
35};
36use crate::sink::{SequenceSink, Sink, TextSink, TreeSink, XmlWriter, attribute_name};
37
38/// Fetches the documents that `document()` asks for, by absolute URI. The engine never
39/// reads files or the network itself.
40pub trait DocumentResolver {
41    /// The text of the document at `uri`, or `None` when it cannot be retrieved.
42    fn resolve(&self, uri: &str) -> Option<String>;
43}
44
45/// The maximum nesting of invocations in a transformation, unless the caller sets another
46/// one ([`TransformOptions::max_nesting`]): template rules, built-in template rules, named
47/// templates and stylesheet functions invoked one inside another. It is
48/// [`max_nesting_for_depth`] of [`DEFAULT_MAX_DEPTH`]: 576.
49pub const DEFAULT_MAX_NESTING: u32 = max_nesting_for_depth(DEFAULT_MAX_DEPTH);
50
51/// The nesting of invocations that the official stylesheets need on a document
52/// `max_depth` deep, with room to spare: twice the depth, plus 64.
53///
54/// A compiled Schematron applies the template rules of each pattern to every element, one
55/// element level inside another, so the nesting reaches the depth of the document; where
56/// a rule fires, the ISO Schematron skeleton writes the location of the node with a
57/// template that recurses over its ancestors (mode `schematron-get-full-path`), which
58/// nests as deep again. The 64 levels above are for the few invocations around them
59/// (the root template, the next rule in a chain) and for stylesheets that recurse
60/// otherwise. On a document [`DEFAULT_MAX_DEPTH`] deep, this nesting fits in the 2 MiB
61/// stack a thread is given by default, in a debug build too.
62#[must_use]
63pub const fn max_nesting_for_depth(max_depth: u32) -> u32 {
64    max_depth.saturating_mul(2).saturating_add(64)
65}
66
67/// Options of a transformation.
68pub struct TransformOptions<'r> {
69    /// The implicit timezone in minutes east of UTC (Saxon takes the JVM's). Default: UTC.
70    pub implicit_timezone: Option<i16>,
71    /// The value of `fn:current-dateTime()`, with a timezone. Default: the system clock,
72    /// read once per transformation; required on targets without one
73    /// (`wasm32-unknown-unknown`).
74    pub current_date_time: Option<DateTime>,
75    /// Values of the global parameters (`xsl:param`), by name.
76    pub parameters: Vec<(QName, Vec<Item>)>,
77    /// Where `document()` gets documents other than the source document.
78    pub resolver: Option<&'r dyn DocumentResolver>,
79    /// The maximum element depth of the source document and of the documents `document()`
80    /// loads (the document element is at depth 1): a document with an element nested
81    /// deeper is refused with a `LIMIT` error ([`TransformError::limit`]). Default:
82    /// [`DEFAULT_MAX_DEPTH`].
83    pub max_depth: u32,
84    /// The maximum nesting of template rules, built-in template rules, named templates
85    /// and stylesheet functions invoked one inside another: beyond it, the transformation
86    /// ends with a `LIMIT` error ([`TransformError::limit`]) instead of overflowing the
87    /// stack. Default: [`DEFAULT_MAX_NESTING`]. A larger value needs a larger stack.
88    pub max_nesting: u32,
89    /// The most stack, in bytes, the invocations in progress may use, measured from the
90    /// start of the transformation: beyond it, the transformation ends with a `LIMIT`
91    /// error ([`LimitExceeded::Stack`]) instead of overflowing the stack. It bounds what
92    /// the nesting alone cannot, the stack of each level, which depends on the
93    /// stylesheet: a function calling itself from a nested expression needs much more
94    /// than a template rule applied to a child. The thread must have this much stack and
95    /// some more, for its caller and for the deepest level. Default:
96    /// [`DEFAULT_MAX_STACK`].
97    pub max_stack: u32,
98}
99
100/// The default of [`TransformOptions::max_stack`]: 1.5 MiB, for a thread with the
101/// default 2 MiB stack of a spawned thread; 640 KiB on WebAssembly, whose stack is 1 MiB.
102/// With it, the official stylesheets run on a document [`DEFAULT_MAX_DEPTH`] deep, in a
103/// debug build too, and the 512 KiB left (384 KiB on WebAssembly) are more than the
104/// caller and one level of invocation need.
105#[cfg(not(target_family = "wasm"))]
106pub const DEFAULT_MAX_STACK: u32 = 3 << 19;
107
108/// The default of [`TransformOptions::max_stack`] (see the other targets).
109#[cfg(target_family = "wasm")]
110pub const DEFAULT_MAX_STACK: u32 = 640 << 10;
111
112impl Default for TransformOptions<'_> {
113    fn default() -> Self {
114        Self {
115            implicit_timezone: None,
116            current_date_time: None,
117            parameters: Vec::new(),
118            resolver: None,
119            max_depth: DEFAULT_MAX_DEPTH,
120            max_nesting: DEFAULT_MAX_NESTING,
121            max_stack: DEFAULT_MAX_STACK,
122        }
123    }
124}
125
126impl std::fmt::Debug for TransformOptions<'_> {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        f.debug_struct("TransformOptions")
129            .field("implicit_timezone", &self.implicit_timezone)
130            .field("current_date_time", &self.current_date_time)
131            .field("parameters", &self.parameters)
132            .field("resolver", &self.resolver.map(|_| "..."))
133            .field("max_depth", &self.max_depth)
134            .field("max_nesting", &self.max_nesting)
135            .field("max_stack", &self.max_stack)
136            .finish()
137    }
138}
139
140/// The result of a transformation.
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct Transformation {
143    /// The result document, serialized as `xsl:output` asks.
144    pub output: String,
145    /// Recoverable conditions reported as warnings, as Saxon reports them, each
146    /// distinct message once in the order first reported, as Saxon's standard error
147    /// reporter prints them: ambiguous template rule matches (`XTDE0540: ...`), and
148    /// dynamic errors raised while matching a pattern, after which the node is taken
149    /// not to match (`line <L>: <CODE>: An error occurred matching pattern {...}:
150    /// <message>`, `L` the line of the `xsl:template` or `xsl:number`).
151    pub warnings: Vec<String>,
152}
153
154impl Executable {
155    /// Runs the stylesheet on a document: `xsl:apply-templates` on its document node in
156    /// the default mode, the result serialized. `base_uri` is the URI of the document:
157    /// the base URI of its nodes, and the URI under which `document()` loads it again. As
158    /// in Saxon-HE 12.10, it is not its document URI: `document-uri(/)` is empty.
159    ///
160    /// The source text can be borrowed (`&str`, `&String`) or given (`String`), as for
161    /// [`Document::parse`]: borrowed, the texts of its nodes are copied into the tree;
162    /// given, the tree keeps the text and refers to it, so that the document is in memory
163    /// once. A given text is kept as a copy only for a stylesheet that calls
164    /// `document()` and a document with a `base_uri`, where `document()` may load the
165    /// document again from its text.
166    ///
167    /// # Errors
168    ///
169    /// The document is not well-formed (or has a document type declaration), or the
170    /// transformation raised a dynamic error.
171    pub fn transform<'s>(
172        &self,
173        source: impl Into<Cow<'s, str>>,
174        base_uri: Option<&str>,
175    ) -> std::result::Result<Transformation, TransformError> {
176        self.transform_with(source, base_uri, &TransformOptions::default())
177    }
178
179    /// [`Executable::transform`] with options.
180    ///
181    /// # Errors
182    ///
183    /// As [`Executable::transform`], and an invalid timezone or current date and time
184    /// (or none given on a target without a system clock).
185    pub fn transform_with<'s>(
186        &self,
187        source: impl Into<Cow<'s, str>>,
188        base_uri: Option<&str>,
189        options: &TransformOptions<'_>,
190    ) -> std::result::Result<Transformation, TransformError> {
191        let source = source.into();
192        // The text `document()` parses again when asked for the source document.
193        let source_text = match &source {
194            Cow::Borrowed(text) => Some(Cow::Borrowed(*text)),
195            Cow::Owned(text) if self.calls_document && base_uri.is_some() => {
196                Some(Cow::Owned(text.clone()))
197            }
198            Cow::Owned(_) => None,
199        };
200        let document = Document::parse_with_max_depth(source, base_uri, options.max_depth)
201            .map_err(|e| match e.limit() {
202                Some(limit) => TransformError::limit_exceeded(limit),
203                None => TransformError::new("SXXP0003", e.message()),
204            })?;
205        let root = document.root();
206        let runtime = Runtime {
207            exe: self,
208            source_root: root.clone(),
209            source_text: RefCell::new(source_text),
210            source_uri: base_uri,
211            options,
212            dc: Cell::new(None),
213            globals: (0..self.globals.len())
214                .map(|_| RefCell::new(GlobalState::Pending))
215                .collect(),
216            frames: RefCell::new(Vec::new()),
217            documents: RefCell::new(Vec::new()),
218            warnings: RefCell::new(Vec::new()),
219            warned: RefCell::new(HashSet::new()),
220            stashed: RefCell::new(None),
221            nesting: Cell::new(0),
222            stack_base: stack_position(),
223        };
224        let timezone = options.implicit_timezone.unwrap_or(0);
225        let clock = match options.current_date_time {
226            Some(now) => Clock::new(timezone, now)?,
227            None => system_clock(timezone)?,
228        };
229        let dc = DynamicContext::new(&runtime, clock);
230        runtime.dc.set(Some(&dc));
231        let mut writer = XmlWriter::new(self.serialization);
232        runtime.apply_rule(&root, 1, 1, self.default_mode, None, &[], &mut writer)?;
233        let output = writer.finish()?;
234        let warnings = runtime.warnings.take();
235        Ok(Transformation { output, warnings })
236    }
237}
238
239/// The system clock, in the implicit timezone.
240#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
241fn system_clock(timezone: i16) -> Result<Clock> {
242    Ok(Clock::system(timezone)?)
243}
244
245/// No system clock on this target: the caller must give the current date and time.
246#[cfg(all(target_family = "wasm", target_os = "unknown"))]
247fn system_clock(_timezone: i16) -> Result<Clock> {
248    Err(einvoice_xpath_eval::Error::new(
249        ErrorCode::Unsupported,
250        "no system clock on this target: give TransformOptions::current_date_time",
251    )
252    .into())
253}
254
255#[derive(Debug)]
256enum GlobalState {
257    Pending,
258    Evaluating,
259    Done(Rc<[Item]>),
260}
261
262/// A value computed when first read.
263struct Thunk<'e> {
264    expr: &'e CompiledExpr,
265    as_type: Option<&'e SequenceType>,
266    code: &'static str,
267    context: Context,
268    /// The frame the expression's variables are read from.
269    frame: Option<Weak<Frame<'e>>>,
270    memo: OnceCell<Rc<[Item]>>,
271}
272
273#[derive(Clone)]
274enum Slot<'e> {
275    Unset,
276    Value(Rc<[Item]>),
277    Lazy(Rc<Thunk<'e>>),
278}
279
280/// The variables of one invocation.
281struct Frame<'e> {
282    slots: RefCell<Vec<Slot<'e>>>,
283}
284
285impl Frame<'_> {
286    fn new(slots: usize) -> Rc<Self> {
287        Rc::new(Self {
288            slots: RefCell::new(vec![Slot::Unset; slots]),
289        })
290    }
291}
292
293/// The XSLT part of the dynamic context of an instruction.
294struct State<'c> {
295    context: &'c Context,
296    mode: usize,
297    /// The rank of the current template rule in `mode`, if any.
298    rule: Option<u32>,
299}
300
301type Params<'e> = Vec<(&'e QName, Slot<'e>)>;
302
303struct Runtime<'e, 'a> {
304    exe: &'e Executable,
305    source_root: Node,
306    /// The text of the source document, until `document()` loads it again (absent when
307    /// the stylesheet never calls `document()` and the text was given to the tree).
308    source_text: RefCell<Option<Cow<'a, str>>>,
309    source_uri: Option<&'a str>,
310    options: &'a TransformOptions<'a>,
311    dc: Cell<Option<&'a DynamicContext<'a>>>,
312    globals: Vec<RefCell<GlobalState>>,
313    frames: RefCell<Vec<Rc<Frame<'e>>>>,
314    /// Documents loaded by `document()`, by absolute URI.
315    documents: RefCell<Vec<(String, Node)>>,
316    /// The warnings, each distinct one once, in the order first reported.
317    warnings: RefCell<Vec<String>>,
318    warned: RefCell<HashSet<String>>,
319    /// The error a host callback raised, given back when the evaluator returns it.
320    stashed: RefCell<Option<TransformError>>,
321    /// The invocations in progress: template rules, built-in template rules, named
322    /// templates and stylesheet functions (at most `options.max_nesting`).
323    nesting: Cell<u32>,
324    /// The position of the stack when the transformation started (see
325    /// [`stack_position`]).
326    stack_base: usize,
327}
328
329/// The position of the call stack: the address of a local of this function. Two of them
330/// measure the stack used between two calls (stacks grow downwards on every supported
331/// target, the WebAssembly shadow stack included; the distance is taken either way).
332#[inline(never)]
333fn stack_position() -> usize {
334    let marker = 0_u8;
335    std::hint::black_box(std::ptr::addr_of!(marker)).addr()
336}
337
338/// An invocation counted in [`Runtime::nesting`], until it is dropped.
339struct Nested<'n>(&'n Cell<u32>);
340
341impl Drop for Nested<'_> {
342    fn drop(&mut self) {
343        self.0.set(self.0.get().saturating_sub(1));
344    }
345}
346
347/// Sets the line of an error.
348trait At<T> {
349    fn at(self, line: u32) -> Result<T>;
350}
351
352impl<T> At<T> for Result<T> {
353    fn at(self, line: u32) -> Result<T> {
354        self.map_err(|e| e.at(line))
355    }
356}
357
358/// XPath type names, for messages.
359fn type_name(t: &SequenceType) -> String {
360    let item = match &t.item {
361        ItemType::Atomic(a) => a.name.to_string(),
362        ItemType::Kind(k) => format!("{k:?}"),
363    };
364    let occurrence = match t.occurrence {
365        Occurrence::One => "",
366        Occurrence::ZeroOrOne => "?",
367        Occurrence::ZeroOrMore => "*",
368        Occurrence::OneOrMore => "+",
369    };
370    format!("{item}{occurrence}")
371}
372
373const fn atomic_type(kind: AtomicKind) -> AtomicType {
374    match kind {
375        AtomicKind::String => AtomicType::String,
376        AtomicKind::AnyUri => AtomicType::AnyUri,
377        AtomicKind::Boolean => AtomicType::Boolean,
378        AtomicKind::Integer => AtomicType::Integer,
379        AtomicKind::Decimal => AtomicType::Decimal,
380        AtomicKind::Date => AtomicType::Date,
381    }
382}
383
384/// Converts a value to a sequence type with the function conversion rules (XPath 2.0
385/// section 3.1.5): atomization, `xs:untypedAtomic` cast to the expected type, URI
386/// promotion to `xs:string`, then the item type and cardinality checks.
387fn convert(items: Vec<Item>, t: &SequenceType, code: &str) -> Result<Vec<Item>> {
388    let count = items.len();
389    let cardinality_ok = match t.occurrence {
390        Occurrence::One => count == 1,
391        Occurrence::ZeroOrOne => count <= 1,
392        Occurrence::ZeroOrMore => true,
393        Occurrence::OneOrMore => count >= 1,
394    };
395    if !cardinality_ok {
396        return err(
397            code,
398            format!(
399                "Required cardinality of value is {}; supplied value has {count} items",
400                type_name(t)
401            ),
402        );
403    }
404    match &t.item {
405        ItemType::Atomic(a) => {
406            let target = atomic_type(a.kind);
407            items
408                .into_iter()
409                .map(|item| {
410                    let value = item.atomize();
411                    let value = match value {
412                        AtomicValue::UntypedAtomic(_) => value.cast(target)?,
413                        AtomicValue::AnyUri(s) if target == AtomicType::String => {
414                            AtomicValue::String(s)
415                        }
416                        v if v.is_instance_of(target) => v,
417                        v => {
418                            return err(
419                                code,
420                                format!(
421                                    "Required item type of value is {}; supplied value has item type {}",
422                                    a.name,
423                                    v.atomic_type()
424                                ),
425                            );
426                        }
427                    };
428                    Ok(Item::Atomic(value))
429                })
430                .collect()
431        }
432        ItemType::Kind(kind) => {
433            let test = pattern::step_test(
434                match kind {
435                    einvoice_xpath::KindTest::Attribute(_) => {
436                        einvoice_xpath::PatternAxis::Attribute
437                    }
438                    _ => einvoice_xpath::PatternAxis::Child,
439                },
440                &einvoice_xpath::NodeTest::Kind(kind.clone()),
441            );
442            for item in &items {
443                let ok = match item {
444                    Item::Node(n) => {
445                        matches!(kind, einvoice_xpath::KindTest::AnyKind) || test.matches(n)
446                    }
447                    Item::Atomic(_) => false,
448                };
449                if !ok {
450                    return err(
451                        code,
452                        format!("Required item type of value is {}", type_name(t)),
453                    );
454                }
455            }
456            Ok(items)
457        }
458    }
459}
460
461/// Inserts a space where a comment's text would contain `--` or end with `-` (XSLT 2.0
462/// section 11.6).
463fn comment_text(text: &str) -> String {
464    let mut out = String::with_capacity(text.len());
465    let mut previous_dash = false;
466    for c in text.chars() {
467        if c == '-' && previous_dash {
468            out.push(' ');
469        }
470        previous_dash = c == '-';
471        out.push(c);
472    }
473    if previous_dash {
474        out.push(' ');
475    }
476    out
477}
478
479/// Resolves a URI reference against a base URI (RFC 3986 section 5.2, without the
480/// query and fragment cases the rule sets never produce).
481fn resolve_uri(reference: &str, base: Option<&str>) -> String {
482    let has_scheme = reference.split_once(':').is_some_and(|(scheme, _)| {
483        let mut chars = scheme.chars();
484        chars.next().is_some_and(|c| c.is_ascii_alphabetic())
485            && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
486    });
487    let Some(base) = base.filter(|_| !has_scheme) else {
488        return reference.to_owned();
489    };
490    if reference.is_empty() {
491        return base.to_owned();
492    }
493    let joined = if reference.starts_with('/') {
494        match base.split_once(':') {
495            Some((scheme, _)) => format!("{scheme}:{reference}"),
496            None => reference.to_owned(),
497        }
498    } else {
499        let directory = base.rfind('/').map_or("", |i| &base[..=i]);
500        format!("{directory}{reference}")
501    };
502    // Remove `.` and `..` segments.
503    let (prefix, path) = joined.split_once(':').unwrap_or(("", &joined));
504    let mut segments: Vec<&str> = Vec::new();
505    for segment in path.split('/') {
506        match segment {
507            "." => {}
508            ".." => {
509                if segments.len() > 1 {
510                    segments.pop();
511                }
512            }
513            s => segments.push(s),
514        }
515    }
516    let path = segments.join("/");
517    if prefix.is_empty() {
518        path
519    } else {
520        format!("{prefix}:{path}")
521    }
522}
523
524impl<'e, 'a> Runtime<'e, 'a> {
525    fn dc(&self) -> Result<&'a DynamicContext<'a>> {
526        self.dc
527            .get()
528            .ok_or_else(|| TransformError::new("INTERNAL", "no dynamic context"))
529    }
530
531    /// Converts an evaluator error, giving back the error a host callback raised.
532    fn xerr(&self, e: einvoice_xpath_eval::Error) -> TransformError {
533        if e.code() == ErrorCode::Host
534            && let Some(stashed) = self.stashed.borrow_mut().take()
535        {
536            return stashed;
537        }
538        e.into()
539    }
540
541    /// Counts one more invocation in progress, until the guard returned is dropped: a
542    /// `LIMIT` error beyond `options.max_nesting`, or when the invocations in progress
543    /// use more than `options.max_stack` bytes of stack. Every recursion of a
544    /// transformation goes through an invocation (a template rule applied to a child, a
545    /// named template or a function calling itself), so this bounds the depth of the
546    /// call stack.
547    fn nested(&self) -> Result<Nested<'_>> {
548        let depth = self.nesting.get();
549        if depth >= self.options.max_nesting {
550            return Err(TransformError::limit_exceeded(LimitExceeded::Nesting {
551                max: self.options.max_nesting,
552            }));
553        }
554        let used = self.stack_base.abs_diff(stack_position());
555        if u32::try_from(used).map_or(true, |used| used > self.options.max_stack) {
556            return Err(TransformError::limit_exceeded(LimitExceeded::Stack {
557                max: self.options.max_stack,
558            }));
559        }
560        self.nesting.set(depth + 1);
561        Ok(Nested(&self.nesting))
562    }
563
564    /// Keeps an error for [`Runtime::xerr`] and gives the evaluator a placeholder.
565    fn stash(&self, e: TransformError) -> einvoice_xpath_eval::Error {
566        let message = e.to_string();
567        *self.stashed.borrow_mut() = Some(e);
568        einvoice_xpath_eval::Error::new(ErrorCode::Host, message)
569    }
570
571    fn evaluate(&self, expr: &CompiledExpr, context: &Context) -> Result<Vec<Item>> {
572        expr.evaluate(self.dc()?, context).map_err(|e| self.xerr(e))
573    }
574
575    fn test(&self, expr: &CompiledExpr, context: &Context) -> Result<bool> {
576        expr.effective_boolean_value(self.dc()?, context)
577            .map_err(|e| self.xerr(e))
578    }
579
580    /// Runs `f` with `frame` as the frame variables are read from.
581    fn in_frame<T>(
582        &self,
583        frame: Option<Rc<Frame<'e>>>,
584        f: impl FnOnce() -> Result<T>,
585    ) -> Result<T> {
586        let Some(frame) = frame else {
587            return f();
588        };
589        self.frames.borrow_mut().push(frame);
590        let result = f();
591        self.frames.borrow_mut().pop();
592        result
593    }
594
595    fn top_frame(&self) -> Option<Rc<Frame<'e>>> {
596        self.frames.borrow().last().cloned()
597    }
598
599    fn set_slot(&self, slot: usize, value: Slot<'e>) -> Result<()> {
600        let frames = self.frames.borrow();
601        let Some(frame) = frames.last() else {
602            return err("INTERNAL", "no frame for a local variable");
603        };
604        let mut slots = frame.slots.borrow_mut();
605        let Some(s) = slots.get_mut(slot) else {
606            return err("INTERNAL", "variable slot out of range");
607        };
608        *s = value;
609        Ok(())
610    }
611
612    fn force(&self, thunk: &Thunk<'e>) -> Result<Rc<[Item]>> {
613        if let Some(value) = thunk.memo.get() {
614            return Ok(Rc::clone(value));
615        }
616        let frame = match &thunk.frame {
617            None => None,
618            Some(weak) => Some(
619                weak.upgrade()
620                    .ok_or_else(|| TransformError::new("INTERNAL", "variable frame is gone"))?,
621            ),
622        };
623        let items = self.in_frame(frame, || self.evaluate(thunk.expr, &thunk.context))?;
624        let items = match thunk.as_type {
625            Some(t) => convert(items, t, thunk.code)?,
626            None => items,
627        };
628        let value: Rc<[Item]> = items.into();
629        let _ = thunk.memo.set(Rc::clone(&value));
630        Ok(value)
631    }
632
633    fn slot_value(&self, slot: &Slot<'e>) -> Result<Rc<[Item]>> {
634        match slot {
635            Slot::Value(v) => Ok(Rc::clone(v)),
636            Slot::Lazy(thunk) => self.force(thunk),
637            Slot::Unset => err("INTERNAL", "variable read before it is bound"),
638        }
639    }
640
641    fn variable(&self, id: VariableId) -> Result<Rc<[Item]>> {
642        let index = id.0 as usize;
643        let globals = self.exe.globals.len();
644        if index < globals {
645            return self.global(index);
646        }
647        let slot = {
648            let frames = self.frames.borrow();
649            let Some(frame) = frames.last() else {
650                return err("INTERNAL", "no frame for a local variable");
651            };
652            let slots = frame.slots.borrow();
653            slots
654                .get(index - globals)
655                .cloned()
656                .ok_or_else(|| TransformError::new("INTERNAL", "variable slot out of range"))?
657        };
658        self.slot_value(&slot)
659    }
660
661    fn global(&self, index: usize) -> Result<Rc<[Item]>> {
662        let g = &self.exe.globals[index];
663        {
664            let mut state = self.globals[index].borrow_mut();
665            match &*state {
666                GlobalState::Done(v) => return Ok(Rc::clone(v)),
667                GlobalState::Evaluating => {
668                    return err(
669                        "XTDE0640",
670                        format!("Circular definition of global variable ${}", g.name),
671                    )
672                    .at(g.line);
673                }
674                GlobalState::Pending => *state = GlobalState::Evaluating,
675            }
676        }
677        let supplied = if g.is_param {
678            self.options
679                .parameters
680                .iter()
681                .find(|(n, _)| n.same_expanded_name(&g.name))
682        } else {
683            None
684        };
685        let value = if let Some((_, items)) = supplied {
686            match &g.as_type {
687                Some(t) => convert(items.clone(), t, "XTTE0590"),
688                None => Ok(items.clone()),
689            }
690            .map(Rc::from)
691        } else {
692            let context = Context::for_item(Item::Node(self.source_root.clone()));
693            let state = State {
694                context: &context,
695                mode: self.exe.default_mode,
696                rule: None,
697            };
698            let frame = (g.slots > 0).then(|| Frame::new(g.slots));
699            let code = if g.is_param { "XTTE0590" } else { "XTTE0570" };
700            self.in_frame(frame, || {
701                self.value(&g.value, g.as_type.as_ref(), &state, code)
702            })
703        };
704        let value = match value {
705            Ok(v) => v,
706            Err(e) => {
707                *self.globals[index].borrow_mut() = GlobalState::Pending;
708                return Err(e.at(g.line));
709            }
710        };
711        *self.globals[index].borrow_mut() = GlobalState::Done(Rc::clone(&value));
712        Ok(value)
713    }
714
715    /// The value of a binding, computed now.
716    fn value(
717        &self,
718        value: &'e Value,
719        as_type: Option<&'e SequenceType>,
720        state: &State<'_>,
721        code: &str,
722    ) -> Result<Rc<[Item]>> {
723        let items = match value {
724            Value::Select(expr) => self.evaluate(expr, state.context)?,
725            Value::Content(body) => {
726                if as_type.is_some() {
727                    let mut sink = SequenceSink::default();
728                    self.exec(body, state, &mut sink)?;
729                    sink.items
730                } else {
731                    let mut sink = TreeSink::new();
732                    self.exec(body, state, &mut sink)?;
733                    vec![Item::Node(sink.finish()?.root())]
734                }
735            }
736            Value::Absent => {
737                if as_type.is_some() {
738                    Vec::new()
739                } else {
740                    vec![Item::Atomic(AtomicValue::String(String::new()))]
741                }
742            }
743        };
744        let items = match as_type {
745            Some(t) => convert(items, t, code)?,
746            None => items,
747        };
748        Ok(items.into())
749    }
750
751    /// A binding's slot: computed now, or later when it may be a sequence.
752    fn bind(
753        &self,
754        value: &'e Value,
755        as_type: Option<&'e SequenceType>,
756        lazy: bool,
757        state: &State<'_>,
758        code: &'static str,
759    ) -> Result<Slot<'e>> {
760        if lazy && let Value::Select(expr) = value {
761            return Ok(Slot::Lazy(Rc::new(Thunk {
762                expr,
763                as_type,
764                code,
765                context: state.context.clone(),
766                frame: self.top_frame().map(|f| Rc::downgrade(&f)),
767                memo: OnceCell::new(),
768            })));
769        }
770        Ok(Slot::Value(self.value(value, as_type, state, code)?))
771    }
772
773    fn with_params(&self, params: &'e [WithParam], state: &State<'_>) -> Result<Params<'e>> {
774        params
775            .iter()
776            .map(|p| {
777                Ok((
778                    &p.name,
779                    self.bind(&p.value, p.as_type.as_ref(), p.lazy, state, "XTTE0590")?,
780                ))
781            })
782            .collect()
783    }
784
785    fn exec(&self, body: &'e [Inst], state: &State<'_>, sink: &mut dyn Sink) -> Result<()> {
786        for inst in body {
787            self.instruction(inst, state, sink)?;
788        }
789        Ok(())
790    }
791
792    /// Runs one instruction. Each instruction has a function of its own: this one is on
793    /// the path of every recursion through the templates (`xsl:apply-templates` in a
794    /// template rule, ...), whose stack use per level of the document must stay small,
795    /// so that it holds none of their locals, and dispatches only the instructions that
796    /// hold others or invoke templates; [`Runtime::other_instruction`] the rest.
797    fn instruction(&self, inst: &'e Inst, state: &State<'_>, sink: &mut dyn Sink) -> Result<()> {
798        match inst {
799            Inst::ApplyTemplates {
800                line,
801                select,
802                mode,
803                params,
804            } => self.apply_templates(*line, select, mode, params, state, sink),
805            Inst::NextMatch { line, params } => self.next_match(*line, params, state, sink),
806            Inst::CallTemplate {
807                line,
808                template,
809                params,
810            } => self.call_template(*line, *template, params, state, sink),
811            Inst::Choose { whens, otherwise } => self.choose(whens, otherwise, state, sink),
812            Inst::ForEach { line, select, body } => self.for_each(*line, select, body, state, sink),
813            Inst::Element {
814                line,
815                name,
816                namespaces,
817                attributes,
818                body,
819            } => self.element(*line, name, namespaces, attributes, body, state, sink),
820            _ => self.other_instruction(inst, state, sink),
821        }
822    }
823
824    /// The instructions [`Runtime::instruction`] does not dispatch itself.
825    #[inline(never)]
826    fn other_instruction(
827        &self,
828        inst: &'e Inst,
829        state: &State<'_>,
830        sink: &mut dyn Sink,
831    ) -> Result<()> {
832        match inst {
833            Inst::Variable(binding) => self.variable_instruction(binding, state),
834            Inst::Sequence { line, select } => self.sequence(*line, select, state, sink),
835            Inst::ValueOf {
836                line,
837                select,
838                separator,
839                body,
840            } => self.value_of(
841                *line,
842                select.as_deref(),
843                separator.as_ref(),
844                body,
845                state,
846                sink,
847            ),
848            Inst::Attribute {
849                line,
850                name,
851                namespaces,
852                select,
853                body,
854            } => self.attribute(
855                *line,
856                name,
857                namespaces,
858                select.as_deref(),
859                body,
860                state,
861                sink,
862            ),
863            Inst::Comment { line, body } => self.comment(*line, body, state, sink),
864            Inst::Text(text) => sink.text(text),
865            Inst::Number { line, level, count } => {
866                self.number_instruction(*line, *level, count.as_ref(), state, sink)
867            }
868            Inst::ApplyTemplates { .. }
869            | Inst::NextMatch { .. }
870            | Inst::CallTemplate { .. }
871            | Inst::Choose { .. }
872            | Inst::ForEach { .. }
873            | Inst::Element { .. } => self.instruction(inst, state, sink),
874        }
875    }
876
877    fn apply_templates(
878        &self,
879        line: u32,
880        select: &'e CompiledExpr,
881        mode: &ModeRef,
882        params: &'e [WithParam],
883        state: &State<'_>,
884        sink: &mut dyn Sink,
885    ) -> Result<()> {
886        let items = self.evaluate(select, state.context).at(line)?;
887        let mode = match mode {
888            ModeRef::Mode(m) => *m,
889            ModeRef::Current => state.mode,
890        };
891        let params = self.with_params(params, state).at(line)?;
892        let size = items.len();
893        for (i, item) in items.iter().enumerate() {
894            match item {
895                Item::Node(node) => self
896                    .apply_rule(node, i + 1, size, mode, None, &params, sink)
897                    .at(line)?,
898                // As Saxon, an XSLT 3.0 processor: no pattern of the subset matches an
899                // atomic value, whose built-in rule writes it as text.
900                Item::Atomic(_) => sink.text(&item.string_value()).at(line)?,
901            }
902        }
903        Ok(())
904    }
905
906    fn next_match(
907        &self,
908        line: u32,
909        params: &'e [WithParam],
910        state: &State<'_>,
911        sink: &mut dyn Sink,
912    ) -> Result<()> {
913        let Some(rank) = state.rule else {
914            return err("XTDE0560", "xsl:next-match without a current template rule").at(line);
915        };
916        let Some(focus) = &state.context.focus else {
917            return err("XTDE0560", "xsl:next-match without a context item").at(line);
918        };
919        let Item::Node(node) = &focus.item else {
920            return err("XTDE0560", "xsl:next-match on an atomic value").at(line);
921        };
922        let params = self.with_params(params, state).at(line)?;
923        self.apply_rule(
924            node,
925            focus.position,
926            focus.size,
927            state.mode,
928            Some(rank),
929            &params,
930            sink,
931        )
932        .at(line)
933    }
934
935    fn call_template(
936        &self,
937        line: u32,
938        template: usize,
939        params: &'e [WithParam],
940        state: &State<'_>,
941        sink: &mut dyn Sink,
942    ) -> Result<()> {
943        let params = self.with_params(params, state).at(line)?;
944        self.invoke(
945            template,
946            state.context,
947            state.mode,
948            state.rule,
949            &params,
950            sink,
951        )
952        .at(line)
953    }
954
955    fn choose(
956        &self,
957        whens: &'e [When],
958        otherwise: &'e [Inst],
959        state: &State<'_>,
960        sink: &mut dyn Sink,
961    ) -> Result<()> {
962        for when in whens {
963            if self.test(&when.test, state.context).at(when.line)? {
964                return self.exec(&when.body, state, sink);
965            }
966        }
967        self.exec(otherwise, state, sink)
968    }
969
970    fn for_each(
971        &self,
972        line: u32,
973        select: &'e CompiledExpr,
974        body: &'e [Inst],
975        state: &State<'_>,
976        sink: &mut dyn Sink,
977    ) -> Result<()> {
978        let items = self.evaluate(select, state.context).at(line)?;
979        let size = items.len();
980        for (i, item) in items.into_iter().enumerate() {
981            let context = Context::at(item, i + 1, size);
982            let inner = State {
983                context: &context,
984                mode: state.mode,
985                rule: None,
986            };
987            self.exec(body, &inner, sink)?;
988        }
989        Ok(())
990    }
991
992    #[inline(never)]
993    fn sequence(
994        &self,
995        line: u32,
996        select: &'e CompiledExpr,
997        state: &State<'_>,
998        sink: &mut dyn Sink,
999    ) -> Result<()> {
1000        for item in self.evaluate(select, state.context).at(line)? {
1001            sink.item(&item).at(line)?;
1002        }
1003        Ok(())
1004    }
1005
1006    #[inline(never)]
1007    fn value_of(
1008        &self,
1009        line: u32,
1010        select: Option<&'e CompiledExpr>,
1011        separator: Option<&'e CompiledAvt>,
1012        body: &'e [Inst],
1013        state: &State<'_>,
1014        sink: &mut dyn Sink,
1015    ) -> Result<()> {
1016        let separator = match separator {
1017            Some(avt) => Some(self.avt(avt, state).at(line)?),
1018            None => None,
1019        };
1020        let mut parts = TextSink::new();
1021        let text = if let Some(expr) = select {
1022            for item in self.evaluate(expr, state.context).at(line)? {
1023                parts.item(&item)?;
1024            }
1025            parts.finish(separator.as_deref().unwrap_or(" "))
1026        } else {
1027            self.exec(body, state, &mut parts)?;
1028            parts.finish(separator.as_deref().unwrap_or(""))
1029        };
1030        sink.text(&text).at(line)
1031    }
1032
1033    #[inline(never)]
1034    #[expect(
1035        clippy::too_many_arguments,
1036        reason = "the parts of the instruction, its dynamic context and its sink"
1037    )]
1038    fn attribute(
1039        &self,
1040        line: u32,
1041        name: &'e CompiledAvt,
1042        namespaces: &[NamespaceBinding],
1043        select: Option<&'e CompiledExpr>,
1044        body: &'e [Inst],
1045        state: &State<'_>,
1046        sink: &mut dyn Sink,
1047    ) -> Result<()> {
1048        let name = self.avt(name, state).at(line)?;
1049        let name = attribute_name(&name, namespaces).at(line)?;
1050        let value = self.simple_content(select, body, state).at(line)?;
1051        sink.attribute(&name, &value).at(line)
1052    }
1053
1054    #[inline(never)]
1055    fn comment(
1056        &self,
1057        line: u32,
1058        body: &'e [Inst],
1059        state: &State<'_>,
1060        sink: &mut dyn Sink,
1061    ) -> Result<()> {
1062        let mut parts = TextSink::new();
1063        self.exec(body, state, &mut parts)?;
1064        sink.comment(&comment_text(&parts.finish(""))).at(line)
1065    }
1066
1067    #[inline(never)]
1068    fn number_instruction(
1069        &self,
1070        line: u32,
1071        level: NumberLevel,
1072        count: Option<&'e CountPattern>,
1073        state: &State<'_>,
1074        sink: &mut dyn Sink,
1075    ) -> Result<()> {
1076        let text = self.number(line, level, count, state).at(line)?;
1077        sink.text(&text).at(line)
1078    }
1079
1080    #[expect(
1081        clippy::too_many_arguments,
1082        reason = "the parts of the instruction, its dynamic context and its sink"
1083    )]
1084    fn element(
1085        &self,
1086        line: u32,
1087        name: &QName,
1088        namespaces: &[NamespaceBinding],
1089        attributes: &'e [(Arc<QName>, CompiledAvt)],
1090        body: &'e [Inst],
1091        state: &State<'_>,
1092        sink: &mut dyn Sink,
1093    ) -> Result<()> {
1094        sink.start_element(name, namespaces).at(line)?;
1095        for (attribute, value) in attributes {
1096            self.attribute_value(line, attribute, value, state, sink)?;
1097        }
1098        self.exec(body, state, sink)?;
1099        sink.end_element().at(line)
1100    }
1101
1102    /// An attribute of a literal result element.
1103    #[inline(never)]
1104    fn attribute_value(
1105        &self,
1106        line: u32,
1107        name: &QName,
1108        value: &'e CompiledAvt,
1109        state: &State<'_>,
1110        sink: &mut dyn Sink,
1111    ) -> Result<()> {
1112        let value = self.avt(value, state).at(line)?;
1113        sink.attribute(name, &value).at(line)
1114    }
1115
1116    fn variable_instruction(&self, binding: &'e Binding, state: &State<'_>) -> Result<()> {
1117        if !binding.used {
1118            return Ok(());
1119        }
1120        let slot = self
1121            .bind(
1122                &binding.value,
1123                binding.as_type.as_ref(),
1124                binding.lazy,
1125                state,
1126                "XTTE0570",
1127            )
1128            .at(binding.line)?;
1129        self.set_slot(binding.slot, slot).at(binding.line)
1130    }
1131
1132    /// The value of `xsl:attribute`: `select` joined with spaces, or the content.
1133    fn simple_content(
1134        &self,
1135        select: Option<&'e CompiledExpr>,
1136        body: &'e [Inst],
1137        state: &State<'_>,
1138    ) -> Result<String> {
1139        let mut parts = TextSink::new();
1140        if let Some(expr) = select {
1141            for item in self.evaluate(expr, state.context)? {
1142                parts.item(&item)?;
1143            }
1144            Ok(parts.finish(" "))
1145        } else {
1146            self.exec(body, state, &mut parts)?;
1147            Ok(parts.finish(""))
1148        }
1149    }
1150
1151    fn avt(&self, avt: &'e CompiledAvt, state: &State<'_>) -> Result<String> {
1152        if let [AvtItem::Text(text)] = avt.0.as_slice() {
1153            return Ok(text.to_string());
1154        }
1155        let mut out = String::new();
1156        for item in &avt.0 {
1157            match item {
1158                AvtItem::Text(text) => out.push_str(text),
1159                AvtItem::Expr(expr) => {
1160                    for (i, value) in self.evaluate(expr, state.context)?.iter().enumerate() {
1161                        if i > 0 {
1162                            out.push(' ');
1163                        }
1164                        out.push_str(&value.atomize().to_string());
1165                    }
1166                }
1167            }
1168        }
1169        Ok(out)
1170    }
1171
1172    /// Finds the best rule for `node` in `mode` (ranked after `after`, for
1173    /// `xsl:next-match`) and runs it, or the built-in rule.
1174    #[expect(
1175        clippy::too_many_arguments,
1176        reason = "the focus, the mode, the rule and the parameters of the invocation"
1177    )]
1178    fn apply_rule(
1179        &self,
1180        node: &Node,
1181        position: usize,
1182        size: usize,
1183        mode: usize,
1184        after: Option<u32>,
1185        params: &[(&'e QName, Slot<'e>)],
1186        sink: &mut dyn Sink,
1187    ) -> Result<()> {
1188        match self.find_rule(mode, node, after)? {
1189            Some(rank) => {
1190                let template = self.exe.modes[mode].rules[rank as usize].template;
1191                let context = Context::at(Item::Node(node.clone()), position, size);
1192                self.invoke(template, &context, mode, Some(rank), params, sink)
1193            }
1194            None => self.builtin(node, mode, params, sink),
1195        }
1196    }
1197
1198    /// Whether `node` matches the pattern of a rule. A dynamic error while matching is
1199    /// recovered as Saxon recovers it (see [`Runtime::pattern_error`]).
1200    fn rule_matches(&self, rank: u32, mode: usize, node: &Node) -> Result<bool> {
1201        let rule = &self.exe.modes[mode].rules[rank as usize];
1202        let template = &self.exe.templates[rule.template];
1203        let matcher = Matcher { dc: self.dc()? };
1204        // A union pattern with an explicit priority is one rule: its alternatives in
1205        // order, the first error ending the match.
1206        let (alternatives, text) = match rule.alternative {
1207            Some(index) => (
1208                template.pattern.get(index..=index).unwrap_or_default(),
1209                template
1210                    .alternative_texts
1211                    .get(index)
1212                    .map_or("", String::as_str),
1213            ),
1214            None => (template.pattern.as_slice(), template.pattern_text.as_str()),
1215        };
1216        let outcome = alternatives
1217            .iter()
1218            .try_fold(false, |found, a| Ok(found || matcher.matches(a, node)?));
1219        outcome.or_else(|e| self.pattern_error(e, template.line, text))
1220    }
1221
1222    /// A dynamic error raised while matching a pattern (of a template rule, or the
1223    /// `count` pattern of `xsl:number`), as Saxon-HE 12.10 handles it
1224    /// (`Pattern.matchesItem`): the node does not match, and the error is reported as
1225    /// a warning, whatever its code, except a circularity (`XTDE0640`), which ends the
1226    /// transformation. A global variable whose evaluation failed is not kept in error:
1227    /// the next reference evaluates it again (`GlobalVariable.actuallyEvaluate`), in a
1228    /// pattern or elsewhere. The refusals, limits and bugs of this crate (`UNSUPPORTED`,
1229    /// `LIMIT`, `INTERNAL`) are never recovered: Saxon would not have raised them.
1230    fn pattern_error(
1231        &self,
1232        e: einvoice_xpath_eval::Error,
1233        line: u32,
1234        pattern: &str,
1235    ) -> Result<bool> {
1236        let e = self.xerr(e);
1237        if matches!(
1238            e.code(),
1239            "XTDE0640" | "UNSUPPORTED" | LIMIT | "INTERNAL" | "HOST"
1240        ) {
1241            return Err(e.at(line));
1242        }
1243        self.warn(format!(
1244            "line {line}: {}: An error occurred matching pattern {{{pattern}}}: {}",
1245            e.code(),
1246            e.message()
1247        ));
1248        Ok(false)
1249    }
1250
1251    /// Reports a warning, once: Saxon's standard error reporter prints each distinct
1252    /// warning once.
1253    fn warn(&self, message: String) {
1254        if self.warned.borrow_mut().insert(message.clone()) {
1255            self.warnings.borrow_mut().push(message);
1256        }
1257    }
1258
1259    /// The rule for `node` in `mode`, chosen exactly as Saxon-HE 12.10 chooses it
1260    /// (`SimpleMode.getRule` and `searchRuleChain`): the chains of the node's name, of
1261    /// its kind, then the generic chain, each in rank order; a rule of higher priority
1262    /// replaces the best so far; on a tie the later declared rule wins and the ambiguity
1263    /// is reported as an XTDE0540 warning. For `xsl:next-match` (`after` is the current
1264    /// rule) only the rules ranked below the current one are candidates (lower
1265    /// priority, or same priority and declared before it, or an earlier part of the
1266    /// same template), and a tie between two parts of one template goes to the part
1267    /// found last.
1268    fn find_rule(&self, mode: usize, node: &Node, after: Option<u32>) -> Result<Option<u32>> {
1269        let compiled = &self.exe.modes[mode];
1270        let rules = &compiled.rules;
1271        let below_current = |rank: u32| -> bool {
1272            let Some(current) = after else {
1273                return true;
1274            };
1275            let (r, c) = (&rules[rank as usize], &rules[current as usize]);
1276            match r.priority.total_cmp(&c.priority) {
1277                std::cmp::Ordering::Less => true,
1278                std::cmp::Ordering::Greater => false,
1279                std::cmp::Ordering::Equal => {
1280                    r.sequence < c.sequence || (r.sequence == c.sequence && r.part < c.part)
1281                }
1282            }
1283        };
1284        let mut best: Option<u32> = None;
1285        for chain in compiled.chains(node.kind(), node.name()) {
1286            for &rank in chain {
1287                if !below_current(rank) {
1288                    continue;
1289                }
1290                let Some(chosen) = best else {
1291                    if self.rule_matches(rank, mode, node)? {
1292                        best = Some(rank);
1293                    }
1294                    continue;
1295                };
1296                let (head, b) = (&rules[rank as usize], &rules[chosen as usize]);
1297                match head.priority.total_cmp(&b.priority) {
1298                    std::cmp::Ordering::Less => break,
1299                    std::cmp::Ordering::Greater => {
1300                        if self.rule_matches(rank, mode, node)? {
1301                            best = Some(rank);
1302                        }
1303                    }
1304                    std::cmp::Ordering::Equal => {
1305                        if !self.rule_matches(rank, mode, node)? {
1306                            continue;
1307                        }
1308                        if head.template != b.template {
1309                            self.ambiguity(node, compiled, b, head);
1310                        }
1311                        // The later declared rule; between two parts of one template,
1312                        // the higher part, or for xsl:next-match the one found last.
1313                        let keep = b.sequence > head.sequence
1314                            || (b.sequence == head.sequence
1315                                && after.is_none()
1316                                && b.part > head.part);
1317                        best = Some(if keep { chosen } else { rank });
1318                        break;
1319                    }
1320                }
1321            }
1322        }
1323        Ok(best)
1324    }
1325
1326    /// Reports a tie between `a`, the best rule so far, and `b`, as Saxon's
1327    /// `reportAmbiguity` does, naming them in that order.
1328    fn ambiguity(
1329        &self,
1330        node: &Node,
1331        mode: &crate::prepare::CompiledMode,
1332        a: &crate::prepare::Rule,
1333        b: &crate::prepare::Rule,
1334    ) {
1335        let (ta, tb) = (
1336            &self.exe.templates[a.template],
1337            &self.exe.templates[b.template],
1338        );
1339        let later = if a.sequence > b.sequence { ta } else { tb };
1340        self.warn(format!(
1341            "XTDE0540: Ambiguous rule match for {} in mode {}: matches the template rules on line {} and line {}; the one on line {} is used",
1342            describe(node),
1343            mode.name,
1344            ta.line,
1345            tb.line,
1346            later.line
1347        ));
1348    }
1349
1350    /// The built-in template rule for `node`. For a document node or an element, it
1351    /// applies the template rules to the children, one level of recursion counted as an
1352    /// invocation ([`Runtime::nested`]).
1353    fn builtin(
1354        &self,
1355        node: &Node,
1356        mode: usize,
1357        params: &[(&'e QName, Slot<'e>)],
1358        sink: &mut dyn Sink,
1359    ) -> Result<()> {
1360        match node.kind() {
1361            NodeKind::Document | NodeKind::Element => {
1362                let _nested = self.nested()?;
1363                let children: Vec<Node> = node.children().collect();
1364                let size = children.len();
1365                for (i, child) in children.iter().enumerate() {
1366                    self.apply_rule(child, i + 1, size, mode, None, params, sink)?;
1367                }
1368                Ok(())
1369            }
1370            NodeKind::Text | NodeKind::Attribute => sink.text(&node.string_value()),
1371            NodeKind::Comment | NodeKind::ProcessingInstruction => Ok(()),
1372        }
1373    }
1374
1375    /// Runs a template: its parameters bound from `params` or their default values,
1376    /// then its body. Counted as an invocation ([`Runtime::nested`]).
1377    fn invoke(
1378        &self,
1379        index: usize,
1380        context: &Context,
1381        mode: usize,
1382        rule: Option<u32>,
1383        params: &[(&'e QName, Slot<'e>)],
1384        sink: &mut dyn Sink,
1385    ) -> Result<()> {
1386        let template = &self.exe.templates[index];
1387        let _nested = self.nested().at(template.line)?;
1388        let frame = (template.slots > 0).then(|| Frame::new(template.slots));
1389        let state = State {
1390            context,
1391            mode,
1392            rule,
1393        };
1394        self.in_frame(frame, || {
1395            self.bind_params(template, params, &state)?;
1396            self.exec(&template.body, &state, sink)
1397        })
1398        .at(template.line)
1399    }
1400
1401    /// Binds the parameters of a template being invoked, in its frame: from `params`, or
1402    /// their default values. Out of [`Runtime::invoke`], whose stack use is part of every
1403    /// level of recursion through the templates.
1404    #[inline(never)]
1405    fn bind_params(
1406        &self,
1407        template: &'e CompiledTemplate,
1408        params: &[(&'e QName, Slot<'e>)],
1409        state: &State<'_>,
1410    ) -> Result<()> {
1411        for param in &template.params {
1412            let passed = params
1413                .iter()
1414                .find(|(name, _)| name.same_expanded_name(&param.name));
1415            let slot = match (passed, &param.as_type) {
1416                (Some((_, slot)), None) => slot.clone(),
1417                (Some((_, slot)), Some(t)) => {
1418                    let items = self.slot_value(slot)?.to_vec();
1419                    Slot::Value(convert(items, t, "XTTE0590").at(param.line)?.into())
1420                }
1421                (None, as_type) => self
1422                    .bind(
1423                        &param.value,
1424                        as_type.as_ref(),
1425                        param.lazy,
1426                        state,
1427                        "XTTE0590",
1428                    )
1429                    .at(param.line)?,
1430            };
1431            self.set_slot(param.slot, slot)?;
1432        }
1433        Ok(())
1434    }
1435
1436    /// Calls a stylesheet function. Counted as an invocation ([`Runtime::nested`]).
1437    fn call(&self, id: FunctionId, args: Vec<Vec<Item>>) -> Result<Vec<Item>> {
1438        let function = &self.exe.functions[id.0 as usize];
1439        let _nested = self.nested().at(function.line)?;
1440        let frame = Frame::new(function.slots);
1441        for (param, arg) in function.params.iter().zip(args) {
1442            let value = match &param.as_type {
1443                Some(t) => convert(arg, t, "XPTY0004").map_err(|e| {
1444                    TransformError::new(
1445                        e.code(),
1446                        format!(
1447                            "{} (argument ${} of {}())",
1448                            e.message(),
1449                            param.name,
1450                            function.name
1451                        ),
1452                    )
1453                })?,
1454                None => arg,
1455            };
1456            frame.slots.borrow_mut()[param.slot] = Slot::Value(value.into());
1457        }
1458        // A stylesheet function has no focus and no current template rule.
1459        let context = Context::new();
1460        let state = State {
1461            context: &context,
1462            mode: self.exe.default_mode,
1463            rule: None,
1464        };
1465        let mut sink = SequenceSink::default();
1466        self.in_frame(Some(frame), || self.exec(&function.body, &state, &mut sink))
1467            .at(function.line)?;
1468        match &function.as_type {
1469            Some(t) => convert(sink.items, t, "XTTE0780").at(function.line),
1470            None => Ok(sink.items),
1471        }
1472    }
1473
1474    fn number(
1475        &self,
1476        line: u32,
1477        level: NumberLevel,
1478        count: Option<&'e CountPattern>,
1479        state: &State<'_>,
1480    ) -> Result<String> {
1481        let Some(Item::Node(node)) = state.context.focus.as_ref().map(|f| &f.item) else {
1482            return err("XTTE0990", "xsl:number needs a node as context item");
1483        };
1484        let matcher = Matcher { dc: self.dc()? };
1485        let counted = |n: &Node| -> Result<bool> {
1486            match count {
1487                // As a template rule's pattern, an error is recovered (Saxon's
1488                // `Navigator` matches the count pattern with `matchesItem`).
1489                Some(pattern) => pattern
1490                    .alternatives
1491                    .iter()
1492                    .try_fold(false, |found, a| Ok(found || matcher.matches(a, n)?))
1493                    .or_else(|e| self.pattern_error(e, line, &pattern.text)),
1494                None => Ok(n.kind() == node.kind()
1495                    && match (n.name(), node.name()) {
1496                        (Some(a), Some(b)) => a.same_expanded_name(b),
1497                        (None, None) => true,
1498                        _ => false,
1499                    }),
1500            }
1501        };
1502        let position = |n: &Node| -> Result<usize> {
1503            let mut p = 1;
1504            for sibling in n.axis(NodeAxis::PrecedingSibling) {
1505                if counted(&sibling)? {
1506                    p += 1;
1507                }
1508            }
1509            Ok(p)
1510        };
1511        let mut numbers = Vec::new();
1512        for ancestor in node.axis(NodeAxis::AncestorOrSelf) {
1513            if counted(&ancestor)? {
1514                numbers.push(position(&ancestor)?);
1515                if level == NumberLevel::Single {
1516                    break;
1517                }
1518            }
1519        }
1520        numbers.reverse();
1521        Ok(numbers
1522            .iter()
1523            .map(usize::to_string)
1524            .collect::<Vec<_>>()
1525            .join("."))
1526    }
1527
1528    fn load_document(&self, uri: &str, base: Option<&str>) -> Result<Node> {
1529        let absolute = resolve_uri(uri, base.or(self.exe.base_uri.as_deref()));
1530        if let Some((_, node)) = self.documents.borrow().iter().find(|(u, _)| *u == absolute) {
1531            return Ok(node.clone());
1532        }
1533        // As Saxon: the source document, asked for by its base URI, is parsed again and
1534        // is a different tree. Loaded once: the tree is kept under its URI above.
1535        let text: Cow<'_, str> = if self.source_uri == Some(absolute.as_str()) {
1536            self.source_text.take().ok_or_else(|| {
1537                TransformError::new(
1538                    "INTERNAL",
1539                    "document() loads the source document, whose text was not kept",
1540                )
1541            })?
1542        } else {
1543            // The resolver's text is given to the tree, not copied.
1544            Cow::Owned(
1545                self.options
1546                    .resolver
1547                    .and_then(|r| r.resolve(&absolute))
1548                    .ok_or_else(|| {
1549                        TransformError::new(
1550                            "FODC0002",
1551                            format!("cannot retrieve the document at {absolute}"),
1552                        )
1553                    })?,
1554            )
1555        };
1556        // A loaded document has a document URI, as one in Saxon's document pool.
1557        let node = Document::parse_loaded_with_max_depth(text, &absolute, self.options.max_depth)
1558            .map_err(|e| loaded_document_error(&absolute, &e))?
1559            .root();
1560        self.documents.borrow_mut().push((absolute, node.clone()));
1561        Ok(node)
1562    }
1563}
1564
1565/// A node, for messages: its path from the root, written as Saxon-HE 12.10 writes it
1566/// (`Navigator.getPath`): `/r/x[2]/@a`, `/r/text()[1]`, the outermost element without
1567/// position. Saxon's error reporter prints each distinct warning once, so the path tells
1568/// apart exactly the nodes Saxon's tells apart.
1569fn describe(node: &Node) -> String {
1570    let name = |n: &Node| n.name().map(ToString::to_string).unwrap_or_default();
1571    // The position among the preceding siblings of the same kind and, for a node with a
1572    // name, the same name (`Navigator.getNumberSimple`).
1573    let number = |n: &Node| {
1574        1 + n
1575            .axis(NodeAxis::PrecedingSibling)
1576            .filter(|s| {
1577                s.kind() == n.kind()
1578                    && match (s.name(), n.name()) {
1579                        (Some(a), Some(b)) => a.same_expanded_name(b),
1580                        (None, None) => true,
1581                        _ => false,
1582                    }
1583            })
1584            .count()
1585    };
1586    // The path of each node from the root down, from its parent's: a loop rather than a
1587    // recursion over the ancestors, whose number only the document bounds.
1588    let lineage: Vec<Node> = node.axis(NodeAxis::AncestorOrSelf).collect();
1589    let mut path = String::new();
1590    let mut parent_kind: Option<NodeKind> = None;
1591    for n in lineage.iter().rev() {
1592        let parent_path = std::mem::take(&mut path);
1593        // A step under the parent, which is "/" for the document node.
1594        let under_parent = |step: String| {
1595            format!(
1596                "{}/{step}",
1597                if parent_path == "/" {
1598                    ""
1599                } else {
1600                    parent_path.as_str()
1601                }
1602            )
1603        };
1604        path = match n.kind() {
1605            NodeKind::Document => "/".to_owned(),
1606            NodeKind::Element => match parent_kind {
1607                None => name(n),
1608                Some(NodeKind::Document) => format!("/{}", name(n)),
1609                Some(_) => format!("{parent_path}/{}[{}]", name(n), number(n)),
1610            },
1611            NodeKind::Attribute => format!("{parent_path}/@{}", name(n)),
1612            NodeKind::Text => under_parent(format!("text()[{}]", number(n))),
1613            NodeKind::Comment => under_parent(format!("comment()[{}]", number(n))),
1614            NodeKind::ProcessingInstruction => {
1615                under_parent(format!("processing-instruction()[{}]", number(n)))
1616            }
1617        };
1618        parent_kind = Some(n.kind());
1619    }
1620    path
1621}
1622
1623/// The error for a document that `document()` could not parse: `LIMIT` for one beyond
1624/// the maximum depth, else `FODC0002`, as Saxon reports a document it cannot parse.
1625fn loaded_document_error(uri: &str, e: &DocumentError) -> TransformError {
1626    match e.limit() {
1627        Some(limit) => TransformError::limit_exceeded(limit).in_document(uri),
1628        None => TransformError::new("FODC0002", format!("{uri}: {}", e.message())),
1629    }
1630}
1631
1632impl Host for Runtime<'_, '_> {
1633    fn variable(&self, id: VariableId) -> einvoice_xpath_eval::Result<Rc<[Item]>> {
1634        Runtime::variable(self, id).map_err(|e| self.stash(e))
1635    }
1636
1637    fn call_function(
1638        &self,
1639        id: FunctionId,
1640        args: Vec<Vec<Item>>,
1641    ) -> einvoice_xpath_eval::Result<Vec<Item>> {
1642        self.call(id, args).map_err(|e| self.stash(e))
1643    }
1644
1645    fn document(&self, uri: &str, base: Option<&str>) -> einvoice_xpath_eval::Result<Node> {
1646        self.load_document(uri, base).map_err(|e| self.stash(e))
1647    }
1648
1649    fn system_property(&self, name: &QName) -> String {
1650        // Saxon-HE 12.10's values.
1651        if name.namespace.as_deref() != Some(einvoice_xslt::XSLT_NAMESPACE) {
1652            return String::new();
1653        }
1654        match name.local.as_str() {
1655            "version" => "3.0",
1656            "vendor" => "Saxonica",
1657            "vendor-url" => "http://www.saxonica.com/",
1658            "product-name" => "SAXON",
1659            "product-version" => "HE 12.10",
1660            _ => "",
1661        }
1662        .to_owned()
1663    }
1664}
1665
1666#[cfg(test)]
1667mod tests {
1668    use super::{comment_text, resolve_uri};
1669
1670    #[test]
1671    fn comments_never_hold_double_dashes() {
1672        assert_eq!(comment_text("a--b-"), "a- -b- ");
1673        assert_eq!(comment_text("-x"), "-x");
1674        assert_eq!(comment_text("---"), "- - - ");
1675    }
1676
1677    #[test]
1678    fn uris_resolve_against_the_base() {
1679        assert_eq!(resolve_uri("b.xml", Some("file:/d/a.xml")), "file:/d/b.xml");
1680        assert_eq!(
1681            resolve_uri("../c/b.xml", Some("file:/d/e/a.xml")),
1682            "file:/d/c/b.xml"
1683        );
1684        assert_eq!(
1685            resolve_uri("file:/x.xml", Some("file:/d/a.xml")),
1686            "file:/x.xml"
1687        );
1688        assert_eq!(resolve_uri("/x.xml", Some("file:/d/a.xml")), "file:/x.xml");
1689        assert_eq!(resolve_uri("x.xml", None), "x.xml");
1690        assert_eq!(resolve_uri("", Some("file:/d/a.xml")), "file:/d/a.xml");
1691    }
1692}