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-HE 12.10 where it is observable (which dynamic errors
11//! are raised): global variables are evaluated when first referenced; a local variable
12//! that nothing refers to is never evaluated; one referred to once, not in a loop, is
13//! evaluated when the reference is (Saxon inlines it); a value that depends on the
14//! position, size or current item of its focus is evaluated where it is bound, and so are
15//! the parameters `xsl:apply-templates` and `xsl:next-match` pass; any other local
16//! variable, template parameter default or parameter `xsl:call-template` passes is
17//! evaluated as Saxon's `LearningEvaluator` evaluates it: when first referenced, until
18//! it has been evaluated 20 times with its value computed each time (in a function body,
19//! 20 times at all), then where it is bound (see [`Eval`]). Saxon keeps these counts in
20//! the compiled stylesheet, over every document it transforms with it; they are kept
21//! here for one transformation, as Saxon on a stylesheet compiled for one document.
22//! Arguments of stylesheet functions are evaluated before the call (Saxon evaluates them
23//! lazily too).
24
25use std::borrow::Cow;
26use std::cell::{Cell, OnceCell, RefCell};
27use std::collections::{HashMap, HashSet};
28use std::rc::{Rc, Weak};
29use std::sync::Arc;
30
31use einvoice_xdm::{AtomicType, AtomicValue, DateTime};
32use einvoice_xpath::{AtomicKind, ItemType, Occurrence, QName, SequenceType};
33use einvoice_xpath_eval::{
34    Argument, Clock, CompiledExpr, Context, DEFAULT_MAX_DEPTH, Document, DocumentError,
35    DynamicContext, ErrorCode, FunctionId, Host, Item, LimitExceeded, Node, NodeAxis, NodeKind,
36    NodeSelection, SelectionStorage, StackLimit, VariableId,
37};
38use einvoice_xslt::{NamespaceBinding, NumberLevel};
39
40use crate::error::{LIMIT, Result, TransformError, err};
41use crate::output::{CompactBuilder, CompactTransformation, ResultObserver};
42use crate::pattern::{self, Matcher};
43use crate::prepare::{
44    AvtItem, Binding, CompiledApplyTemplates, CompiledAvt, CompiledCallTemplate, CompiledChoose,
45    CompiledElement, CompiledForEach, CompiledFunction, CompiledNextMatch, CompiledTemplate,
46    CountPattern, Eval, Executable, Inst, ModeRef, Plan, Value, WithParam, kind_index,
47    rule_name_number,
48};
49use crate::sink::{
50    Compact, SequenceSink, Serialization, Sink, Target, TextSink, TreeSink, WholeText, XmlWriter,
51    attribute_name, copy_node, element_name, serialize,
52};
53
54/// Fetches the documents that `document()` asks for, by absolute URI. The engine never
55/// reads files or the network itself.
56pub trait DocumentResolver {
57    /// The text of the document at `uri`, or `None` when it cannot be retrieved.
58    fn resolve(&self, uri: &str) -> Option<String>;
59}
60
61/// The maximum nesting of invocations in a transformation, unless the caller sets another
62/// one ([`TransformOptions::max_nesting`]): template rules, built-in template rules, named
63/// templates and stylesheet functions invoked one inside another. It is
64/// [`max_nesting_for_depth`] of [`DEFAULT_MAX_DEPTH`]: 576.
65pub const DEFAULT_MAX_NESTING: u32 = max_nesting_for_depth(DEFAULT_MAX_DEPTH);
66
67/// The most tail calls in a row in a transformation, unless the caller sets another
68/// maximum ([`TransformOptions::max_tail_calls`]): 65 536. A template that ends with an
69/// `xsl:call-template` runs the template it calls in its place, as Saxon does, without
70/// stack in proportion to the recursion; the ISO Schematron skeleton recurses so over
71/// each character of every XPath expression of a schema (8519 for the longest of the CEN
72/// rules).
73pub const DEFAULT_MAX_TAIL_CALLS: u32 = 1 << 16;
74
75/// The nesting of invocations that the official stylesheets need on a document
76/// `max_depth` deep, with room to spare: twice the depth, plus 64.
77///
78/// A compiled Schematron applies the template rules of each pattern to every element, one
79/// element level inside another, so the nesting reaches the depth of the document; where
80/// a rule fires, the ISO Schematron skeleton writes the location of the node with a
81/// template that recurses over its ancestors (mode `schematron-get-full-path`), which
82/// nests as deep again. The 64 levels above are for the few invocations around them
83/// (the root template, the next rule in a chain) and for stylesheets that recurse
84/// otherwise. On a document [`DEFAULT_MAX_DEPTH`] deep, this nesting fits in the 2 MiB
85/// stack a thread is given by default, in a debug build too.
86#[must_use]
87pub const fn max_nesting_for_depth(max_depth: u32) -> u32 {
88    max_depth.saturating_mul(2).saturating_add(64)
89}
90
91/// Options of a transformation.
92pub struct TransformOptions<'r> {
93    /// The implicit timezone in minutes east of UTC (Saxon takes the JVM's). Default: UTC.
94    pub implicit_timezone: Option<i16>,
95    /// The value of `fn:current-dateTime()`, with a timezone. Default: the system clock,
96    /// read once per transformation; required on targets without one
97    /// (`wasm32-unknown-unknown`).
98    pub current_date_time: Option<DateTime>,
99    /// Values of the global parameters (`xsl:param`), by name.
100    pub parameters: Vec<(QName, Vec<Item>)>,
101    /// Where `document()` gets documents other than the source document.
102    pub resolver: Option<&'r dyn DocumentResolver>,
103    /// The maximum element depth of the source document and of the documents `document()`
104    /// loads (the document element is at depth 1): a document with an element nested
105    /// deeper is refused with a `LIMIT` error ([`TransformError::limit`]). Default:
106    /// [`DEFAULT_MAX_DEPTH`].
107    pub max_depth: u32,
108    /// The maximum nesting of template rules, built-in template rules, named templates
109    /// and stylesheet functions invoked one inside another: beyond it, the transformation
110    /// ends with a `LIMIT` error ([`TransformError::limit`]) instead of overflowing the
111    /// stack. Default: [`DEFAULT_MAX_NESTING`]. A larger value needs a larger stack.
112    pub max_nesting: u32,
113    /// The most stack, in bytes, the invocations in progress and the expressions they
114    /// evaluate may use, measured from the start of the transformation: beyond it, the
115    /// transformation ends with a `LIMIT` error ([`LimitExceeded::Stack`]) instead of
116    /// overflowing the stack. It bounds what the nesting alone cannot, the stack of each
117    /// level, which depends on the stylesheet: a function calling itself from a nested
118    /// expression needs much more than a template rule applied to a child. The thread
119    /// must have this much stack and some more, for its caller and for the deepest level.
120    /// Default: [`DEFAULT_MAX_STACK`].
121    pub max_stack: u32,
122    /// The most tail calls in a row (`xsl:call-template` at the end of a template, run in
123    /// its place): beyond it, the transformation ends with a `LIMIT` error
124    /// ([`LimitExceeded::TailCalls`]) rather than run for ever. Default:
125    /// [`DEFAULT_MAX_TAIL_CALLS`].
126    pub max_tail_calls: u32,
127}
128
129/// The default of [`TransformOptions::max_stack`]: 1.5 MiB, for a thread with the
130/// default 2 MiB stack of a spawned thread; 256 KiB on WebAssembly. With it, the official
131/// stylesheets run on a document [`DEFAULT_MAX_DEPTH`] deep, in a debug build too, and
132/// the 512 KiB left are more than the caller and one level of invocation need.
133///
134/// A level of recursion through the templates (a named template, a template rule
135/// applied to a child, a built-in rule) needs less than 3 KiB of stack, in a debug build
136/// too, on Linux, macOS and Windows (`tests/limits.rs` checks it): the default holds the
137/// 512 levels the Peppol stylesheets nest on a document [`DEFAULT_MAX_DEPTH`] deep (two
138/// per element level), and more than 550 levels of named templates. Measured on x86-64
139/// Linux, a debug build needs 1.2 KiB per named template, 2.1 KiB per template rule; a
140/// release build 0.6 and 1.3 KiB. A level of stylesheet function, evaluated through the
141/// XPath evaluator, needs several times more: a recursion through functions may end at
142/// the stack limit before the nesting limit.
143///
144/// On WebAssembly, the stack measured is the program's stack in linear memory (1 MiB),
145/// but what runs out first is the stack of the engine running the code, which the
146/// program cannot measure: 512 KiB by default in wasmtime. A recursion stopped at 256 KiB
147/// of the former uses at most 380 KB of the latter (measured on the `wasm-validate`
148/// example of `einvoice-validator`, a function calling itself without end), and the
149/// official stylesheets need less than half of it on a document [`DEFAULT_MAX_DEPTH`]
150/// deep.
151#[cfg(not(target_family = "wasm"))]
152pub const DEFAULT_MAX_STACK: u32 = 3 << 19;
153
154/// The default of [`TransformOptions::max_stack`] (see the other targets).
155#[cfg(target_family = "wasm")]
156pub const DEFAULT_MAX_STACK: u32 = 256 << 10;
157
158impl Default for TransformOptions<'_> {
159    fn default() -> Self {
160        Self {
161            implicit_timezone: None,
162            current_date_time: None,
163            parameters: Vec::new(),
164            resolver: None,
165            max_depth: DEFAULT_MAX_DEPTH,
166            max_nesting: DEFAULT_MAX_NESTING,
167            max_stack: DEFAULT_MAX_STACK,
168            max_tail_calls: DEFAULT_MAX_TAIL_CALLS,
169        }
170    }
171}
172
173impl std::fmt::Debug for TransformOptions<'_> {
174    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175        f.debug_struct("TransformOptions")
176            .field("implicit_timezone", &self.implicit_timezone)
177            .field("current_date_time", &self.current_date_time)
178            .field("parameters", &self.parameters)
179            .field("resolver", &self.resolver.map(|_| "..."))
180            .field("max_depth", &self.max_depth)
181            .field("max_nesting", &self.max_nesting)
182            .field("max_stack", &self.max_stack)
183            .field("max_tail_calls", &self.max_tail_calls)
184            .finish()
185    }
186}
187
188/// The result of a transformation.
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub struct Transformation {
191    /// The result document, serialized as `xsl:output` asks.
192    pub output: String,
193    /// Recoverable conditions reported as warnings, as Saxon reports them, each
194    /// distinct message once in the order first reported, as Saxon's standard error
195    /// reporter prints them: ambiguous template rule matches (`XTDE0540: ...`), and
196    /// dynamic errors raised while matching a pattern, after which the node is taken
197    /// not to match (`line <L>: <CODE>: An error occurred matching pattern {...}:
198    /// <message>`, `L` the line of the `xsl:template` or `xsl:number`).
199    pub warnings: Vec<String>,
200    /// The messages of `xsl:message`, in the order they were made, each its content
201    /// written as Saxon-HE 12.10's message handler writes it: as XML without
202    /// declaration nor indentation (text escaped, elements as tags). A message without
203    /// content is not kept, as Saxon prints nothing for it. The message of an
204    /// `xsl:message` that terminates is the error's ([`TransformError::message`], code
205    /// `XTMM9000`).
206    pub messages: Vec<String>,
207}
208
209/// The result of [`Executable::transform_tree`]: the result tree.
210#[derive(Debug, Clone)]
211pub struct TreeTransformation {
212    /// The result document (its nodes without base URI).
213    pub document: Rc<Document>,
214    /// The warnings, as [`Transformation::warnings`].
215    pub warnings: Vec<String>,
216    /// The messages, as [`Transformation::messages`].
217    pub messages: Vec<String>,
218}
219
220impl Executable {
221    /// Runs the stylesheet on a document: `xsl:apply-templates` on its document node in
222    /// the default mode, the result serialized. `base_uri` is the URI of the document:
223    /// the base URI of its nodes, and the URI under which `document()` loads it again. As
224    /// in Saxon-HE 12.10, it is not its document URI: `document-uri(/)` is empty.
225    ///
226    /// The source text can be borrowed (`&str`, `&String`) or given (`String`), as for
227    /// [`Document::parse`]: borrowed, the texts of its nodes are copied into the tree;
228    /// given, the tree keeps the text and refers to it, so that the document is in memory
229    /// once. A given text is kept as a copy only for a stylesheet that calls
230    /// `document()` and a document with a `base_uri`, where `document()` may load the
231    /// document again from its text.
232    ///
233    /// # Errors
234    ///
235    /// The document is not well-formed (or has a document type declaration), or the
236    /// transformation raised a dynamic error.
237    pub fn transform<'s>(
238        &self,
239        source: impl Into<Cow<'s, str>>,
240        base_uri: Option<&str>,
241    ) -> std::result::Result<Transformation, TransformError> {
242        self.transform_with(source, base_uri, &TransformOptions::default())
243    }
244
245    /// [`Executable::transform`] with options.
246    ///
247    /// # Errors
248    ///
249    /// As [`Executable::transform`], and an invalid timezone or current date and time
250    /// (or none given on a target without a system clock).
251    pub fn transform_with<'s>(
252        &self,
253        source: impl Into<Cow<'s, str>>,
254        base_uri: Option<&str>,
255        options: &TransformOptions<'_>,
256    ) -> std::result::Result<Transformation, TransformError> {
257        let ((output, WholeText), warnings, messages) =
258            self.run(source, base_uri, options, WholeText)?;
259        Ok(Transformation {
260            output,
261            warnings,
262            messages,
263        })
264    }
265
266    /// Runs the stylesheet on a tree (`source`, a document node) and gives the result
267    /// tree instead of its serialization, for a transformation whose result is read by
268    /// another one. `document()` loads every document through the resolver of the
269    /// options, the source's own URI included.
270    ///
271    /// # Errors
272    ///
273    /// The source is not a document node, or the transformation raised a dynamic error;
274    /// as [`Executable::transform_with`] otherwise.
275    pub fn transform_tree(
276        &self,
277        source: &Node,
278        options: &TransformOptions<'_>,
279    ) -> std::result::Result<TreeTransformation, TransformError> {
280        if source.kind() != NodeKind::Document {
281            return err(
282                "XTDE0040",
283                "the source of a tree transformation is a document node",
284            );
285        }
286        let mut sink = TreeSink::new();
287        let (warnings, messages) = self.execute(source, None, None, options, &mut sink)?;
288        Ok(TreeTransformation {
289            document: sink.finish()?,
290            warnings,
291            messages,
292        })
293    }
294
295    /// The serialization parameters of the stylesheet's `xsl:output`.
296    #[must_use]
297    pub const fn serialization(&self) -> Serialization {
298        self.serialization
299    }
300
301    /// [`Executable::transform_with`], the result kept as a
302    /// [`CompactOutput`](crate::CompactOutput) instead of a string, and read as it is
303    /// written by `observer`: a large result in less memory, read without parsing its
304    /// text.
305    ///
306    /// # Errors
307    ///
308    /// As [`Executable::transform_with`].
309    pub fn transform_compact<'s>(
310        &self,
311        source: impl Into<Cow<'s, str>>,
312        base_uri: Option<&str>,
313        options: &TransformOptions<'_>,
314        observer: &mut dyn ResultObserver,
315    ) -> std::result::Result<CompactTransformation, TransformError> {
316        let target = Compact {
317            builder: CompactBuilder::default(),
318            observer,
319        };
320        // The pieces are all taken: nothing is left in the writer's buffer.
321        let ((_, target), warnings, messages) = self.run(source, base_uri, options, target)?;
322        let mut output = target.builder.finish();
323        // The source tree is dropped: the room left in the buffers is released.
324        output.shrink_to_fit();
325        Ok(CompactTransformation {
326            output,
327            warnings,
328            messages,
329        })
330    }
331
332    /// Runs the stylesheet, its result written to `target`: what
333    /// [`XmlWriter::finish`] returns, the warnings and the messages.
334    #[expect(
335        clippy::type_complexity,
336        reason = "the writer's result, the warnings and the messages"
337    )]
338    fn run<'s, T: Target>(
339        &self,
340        source: impl Into<Cow<'s, str>>,
341        base_uri: Option<&str>,
342        options: &TransformOptions<'_>,
343        target: T,
344    ) -> std::result::Result<((String, T), Vec<String>, Vec<String>), TransformError> {
345        let source = source.into();
346        // The text `document()` parses again when asked for the source document.
347        let source_text = match &source {
348            Cow::Borrowed(text) => Some(Cow::Borrowed(*text)),
349            Cow::Owned(text) if self.calls_document && base_uri.is_some() => {
350                Some(Cow::Owned(text.clone()))
351            }
352            Cow::Owned(_) => None,
353        };
354        let document = Document::parse_with_max_depth(source, base_uri, options.max_depth)
355            .map_err(|e| match e.limit() {
356                Some(limit) => TransformError::limit_exceeded(limit),
357                None => TransformError::new("SXXP0003", e.message()),
358            })?;
359        let mut writer = XmlWriter::new(self.serialization, target);
360        let (warnings, messages) = self.execute(
361            &document.root(),
362            source_text,
363            base_uri,
364            options,
365            &mut writer,
366        )?;
367        let finished = writer.finish()?;
368        Ok((finished, warnings, messages))
369    }
370
371    /// Runs the stylesheet on the tree of `root`, its result written to `sink`: the
372    /// warnings and the messages. `source_text` and `source_uri` are the text of the
373    /// source and its URI, for `document()` asked for the source document by its URI.
374    fn execute<'a>(
375        &self,
376        root: &Node,
377        source_text: Option<Cow<'a, str>>,
378        source_uri: Option<&'a str>,
379        options: &'a TransformOptions<'a>,
380        sink: &mut dyn Sink,
381    ) -> std::result::Result<(Vec<String>, Vec<String>), TransformError> {
382        let runtime = Runtime {
383            exe: self,
384            source_root: root.clone(),
385            source_text: RefCell::new(source_text),
386            source_uri,
387            options,
388            dc: Cell::new(None),
389            globals: (0..self.globals.len())
390                .map(|_| RefCell::new(GlobalState::Pending))
391                .collect(),
392            frames: RefCell::new(Vec::new()),
393            documents: RefCell::new(Vec::new()),
394            warnings: RefCell::new(Vec::new()),
395            warned: RefCell::new(HashSet::new()),
396            messages: RefCell::new(Vec::new()),
397            stashed: RefCell::new(None),
398            nesting: Cell::new(0),
399            stack: StackLimit::from_here(options.max_stack),
400            learners: (0..self.learners).map(|_| Rc::default()).collect(),
401            argument_learners: RefCell::new(HashMap::new()),
402            rule_name_numbers: RefCell::new(Vec::new()),
403            selections: RefCell::new(Vec::new()),
404        };
405        let timezone = options.implicit_timezone.unwrap_or(0);
406        let clock = match options.current_date_time {
407            Some(now) => Clock::new(timezone, now)?,
408            None => system_clock(timezone)?,
409        };
410        let dc = DynamicContext::new(&runtime, clock)
411            .with_stack_limit(runtime.stack)
412            .with_regex_cache(&self.regexes);
413        runtime.dc.set(Some(&dc));
414        runtime.apply_rule(root, 1, &Size::Known(1), self.default_mode, None, &[], sink)?;
415        let warnings = runtime.warnings.take();
416        let messages = runtime.messages.take();
417        Ok((warnings, messages))
418    }
419}
420
421/// The system clock, in the implicit timezone.
422#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
423fn system_clock(timezone: i16) -> Result<Clock> {
424    Ok(Clock::system(timezone)?)
425}
426
427/// No system clock on this target: the caller must give the current date and time.
428#[cfg(all(target_family = "wasm", target_os = "unknown"))]
429fn system_clock(_timezone: i16) -> Result<Clock> {
430    Err(einvoice_xpath_eval::Error::new(
431        ErrorCode::Unsupported,
432        "no system clock on this target: give TransformOptions::current_date_time",
433    )
434    .into())
435}
436
437#[derive(Debug)]
438enum GlobalState {
439    Pending,
440    Evaluating,
441    Done(Rc<[Item]>),
442}
443
444/// A value computed when first read.
445struct Thunk<'e> {
446    value: &'e Value,
447    as_type: Option<&'e SequenceType>,
448    code: &'static str,
449    context: Context,
450    /// The mode and the current template rule, for a sequence constructor.
451    mode: usize,
452    rule: Option<u32>,
453    /// The frame the expression's variables are read from.
454    frame: Option<Weak<Frame<'e>>>,
455    memo: OnceCell<Rc<[Item]>>,
456    /// The learner to tell when the value is computed ([`Eval::Learning`]).
457    report: Option<Rc<Learner>>,
458    /// The frame, kept alive until the value is computed: for a parameter of a tail call
459    /// (see [`Runtime::invoke`]), whose frame ends before the template it calls.
460    hold: RefCell<Option<Rc<Frame<'e>>>>,
461}
462
463/// Dropping a value kept by the parameters of tail calls drops the frames they keep, and
464/// the values not computed in those frames, and so on: a chain as long as the tail calls
465/// (a parameter passed down a recursion and never read). It is dropped here in a loop,
466/// not by a recursion of drops as deep as the chain.
467impl Drop for Thunk<'_> {
468    fn drop(&mut self) {
469        let mut frames: Vec<Rc<Frame<'_>>> = self.hold.get_mut().take().into_iter().collect();
470        while let Some(frame) = frames.pop() {
471            // A frame still read elsewhere is not dropped here.
472            let Ok(frame) = Rc::try_unwrap(frame) else {
473                continue;
474            };
475            for slot in frame.slots.into_inner() {
476                if let Slot::Lazy(thunk) = slot
477                    && let Ok(mut thunk) = Rc::try_unwrap(thunk)
478                {
479                    frames.extend(thunk.hold.get_mut().take());
480                }
481            }
482        }
483    }
484}
485
486/// The argument of a stylesheet function call, computed when first read, in the frame
487/// of the caller.
488struct ArgumentThunk<'e> {
489    argument: Argument,
490    param: &'e Binding,
491    function: &'e CompiledFunction,
492    frame: Option<Weak<Frame<'e>>>,
493    memo: OnceCell<Rc<[Item]>>,
494    report: Option<Rc<Learner>>,
495}
496
497/// The counters of Saxon's `LearningEvaluator` for one binding ([`Eval::Learning`]).
498#[derive(Debug, Default)]
499struct Learner {
500    /// Evaluations so far.
501    count: Cell<u32>,
502    /// Evaluations whose value was computed.
503    completed: Cell<u32>,
504    /// Whether the binding is now evaluated where it is bound.
505    eager: Cell<bool>,
506}
507
508/// Saxon's `LearningEvaluator`: the evaluations whose completion counts, and how many
509/// completed ones make the binding eager.
510const LEARNING_LIMIT: u32 = 40;
511const EAGER_AFTER: u32 = 20;
512
513impl Learner {
514    /// One more evaluation: `None` when the binding is now evaluated where it is bound,
515    /// else whether the completion of this evaluation is to be reported
516    /// ([`Learner::completed`]). With `every_counts` (a function body), each evaluation
517    /// counts as completed.
518    fn evaluation(&self, every_counts: bool) -> Option<bool> {
519        if self.eager.get() {
520            return None;
521        }
522        let count = self.count.get().saturating_add(1);
523        self.count.set(count);
524        if every_counts {
525            if count >= EAGER_AFTER {
526                self.eager.set(true);
527            }
528            return Some(false);
529        }
530        Some(count <= LEARNING_LIMIT)
531    }
532
533    /// The value of an evaluation was computed (`LearningEvaluator.reportCompletion`):
534    /// eager from now on once 20 evaluations have, and all so far.
535    fn completed(&self) {
536        let completed = self.completed.get().saturating_add(1);
537        self.completed.set(completed);
538        if completed >= EAGER_AFTER && completed == self.count.get() {
539            self.eager.set(true);
540        }
541    }
542}
543
544#[derive(Clone)]
545enum Slot<'e> {
546    Unset,
547    Value(Rc<[Item]>),
548    Lazy(Rc<Thunk<'e>>),
549    Argument(Rc<ArgumentThunk<'e>>),
550}
551
552/// The variables of one invocation.
553struct Frame<'e> {
554    slots: RefCell<Vec<Slot<'e>>>,
555}
556
557impl Frame<'_> {
558    fn new(slots: usize) -> Rc<Self> {
559        Rc::new(Self {
560            slots: RefCell::new(vec![Slot::Unset; slots]),
561        })
562    }
563}
564
565/// The XSLT part of the dynamic context of an instruction.
566struct State<'c> {
567    context: &'c Context,
568    mode: usize,
569    /// The rank of the current template rule in `mode`, if any.
570    rule: Option<u32>,
571}
572
573type Params<'e> = Vec<(&'e QName, Slot<'e>)>;
574
575/// An `xsl:call-template` in tail position, its parameters bound: the template to run in
576/// place of the one whose body it ends.
577struct TailCall<'e> {
578    template: usize,
579    params: Params<'e>,
580}
581
582struct Runtime<'e, 'a> {
583    exe: &'e Executable,
584    source_root: Node,
585    /// The text of the source document, until `document()` loads it again (absent when
586    /// the stylesheet never calls `document()` and the text was given to the tree).
587    source_text: RefCell<Option<Cow<'a, str>>>,
588    source_uri: Option<&'a str>,
589    options: &'a TransformOptions<'a>,
590    dc: Cell<Option<&'a DynamicContext<'a>>>,
591    globals: Vec<RefCell<GlobalState>>,
592    frames: RefCell<Vec<Rc<Frame<'e>>>>,
593    /// Documents loaded by `document()`, by absolute URI.
594    documents: RefCell<Vec<(String, Node)>>,
595    /// The warnings, each distinct one once, in the order first reported.
596    warnings: RefCell<Vec<String>>,
597    warned: RefCell<HashSet<String>>,
598    /// The messages of `xsl:message`.
599    messages: RefCell<Vec<String>>,
600    /// The error a host callback raised, given back when the evaluator returns it.
601    stashed: RefCell<Option<TransformError>>,
602    /// The invocations in progress: template rules, built-in template rules, named
603    /// templates and stylesheet functions (at most `options.max_nesting`).
604    nesting: Cell<u32>,
605    /// The stack the transformation may use, from its start (`options.max_stack`): the
606    /// invocations and the evaluations of the expressions check it.
607    stack: StackLimit,
608    /// The counters of the bindings evaluated as Saxon learns ([`Eval::Learning`]).
609    learners: Vec<Rc<Learner>>,
610    /// The same for the arguments of stylesheet function calls, by call site
611    /// ([`Argument::site`]).
612    argument_learners: RefCell<HashMap<usize, Rc<Learner>>>,
613    /// The number in [`Executable::rule_names`] of each name of the source document, by
614    /// [`Node::name_id`], as looked up.
615    rule_name_numbers: RefCell<Vec<NameNumber>>,
616    /// The storage of the selections of `xsl:apply-templates` done, for the next ones.
617    selections: RefCell<Vec<SelectionStorage>>,
618}
619
620/// The size of the sequence of nodes a template rule is applied to, the context size of
621/// the rule: known, or that of the children of a node, counted when first needed (the
622/// built-in rule applies the rules to the children, and most children of a document
623/// walked by a compiled Schematron get a rule with an empty body or the built-in rule).
624enum Size<'n> {
625    Known(usize),
626    ChildrenOf(&'n Node, Cell<Option<usize>>),
627}
628
629impl Size<'_> {
630    fn get(&self) -> usize {
631        match self {
632            Self::Known(size) => *size,
633            Self::ChildrenOf(parent, counted) => {
634                if let Some(size) = counted.get() {
635                    return size;
636                }
637                let size = parent.children().count();
638                counted.set(Some(size));
639                size
640            }
641        }
642    }
643}
644
645/// The number of a name of the source document in [`Executable::rule_names`].
646#[derive(Debug, Clone, Copy)]
647enum NameNumber {
648    /// Not looked up yet.
649    Unknown,
650    /// No mode has rules for the name.
651    NoRules,
652    Known(u32),
653}
654
655/// An invocation counted in [`Runtime::nesting`], until it is dropped.
656struct Nested<'n>(&'n Cell<u32>);
657
658impl Drop for Nested<'_> {
659    fn drop(&mut self) {
660        self.0.set(self.0.get().saturating_sub(1));
661    }
662}
663
664/// Sets the line of an error.
665trait At<T> {
666    fn at(self, line: u32) -> Result<T>;
667}
668
669impl<T> At<T> for Result<T> {
670    fn at(self, line: u32) -> Result<T> {
671        self.map_err(|e| e.at(line))
672    }
673}
674
675/// The context of a template rule applied to `node`, at `position` in a sequence of
676/// `size` nodes. Out of [`Runtime::apply_rule`], whose stack use is part of every level
677/// of recursion through the template rules.
678#[inline(never)]
679fn node_context(node: &Node, position: usize, size: usize) -> Context {
680    Context::at(Item::Node(node.clone()), position, size)
681}
682
683/// XPath type names, for messages.
684fn type_name(t: &SequenceType) -> String {
685    let item = match &t.item {
686        ItemType::Atomic(a) => a.name.to_string(),
687        ItemType::Kind(k) => format!("{k:?}"),
688    };
689    let occurrence = match t.occurrence {
690        Occurrence::One => "",
691        Occurrence::ZeroOrOne => "?",
692        Occurrence::ZeroOrMore => "*",
693        Occurrence::OneOrMore => "+",
694    };
695    format!("{item}{occurrence}")
696}
697
698const fn atomic_type(kind: AtomicKind) -> AtomicType {
699    match kind {
700        AtomicKind::String => AtomicType::String,
701        AtomicKind::AnyUri => AtomicType::AnyUri,
702        AtomicKind::Boolean => AtomicType::Boolean,
703        AtomicKind::Integer => AtomicType::Integer,
704        AtomicKind::Decimal => AtomicType::Decimal,
705        AtomicKind::Date => AtomicType::Date,
706    }
707}
708
709/// Converts a value to a sequence type with the function conversion rules (XPath 2.0
710/// section 3.1.5): atomization, `xs:untypedAtomic` cast to the expected type, URI
711/// promotion to `xs:string`, then the item type and cardinality checks.
712fn convert(items: Vec<Item>, t: &SequenceType, code: &str) -> Result<Vec<Item>> {
713    let count = items.len();
714    let cardinality_ok = match t.occurrence {
715        Occurrence::One => count == 1,
716        Occurrence::ZeroOrOne => count <= 1,
717        Occurrence::ZeroOrMore => true,
718        Occurrence::OneOrMore => count >= 1,
719    };
720    if !cardinality_ok {
721        return err(
722            code,
723            format!(
724                "Required cardinality of value is {}; supplied value has {count} items",
725                type_name(t)
726            ),
727        );
728    }
729    match &t.item {
730        ItemType::Atomic(a) => {
731            let target = atomic_type(a.kind);
732            items
733                .into_iter()
734                .map(|item| {
735                    let value = item.atomize();
736                    let value = match value {
737                        AtomicValue::UntypedAtomic(_) => value.cast(target)?,
738                        AtomicValue::AnyUri(s) if target == AtomicType::String => {
739                            AtomicValue::String(s)
740                        }
741                        v if v.is_instance_of(target) => v,
742                        v => {
743                            return err(
744                                code,
745                                format!(
746                                    "Required item type of value is {}; supplied value has item type {}",
747                                    a.name,
748                                    v.atomic_type()
749                                ),
750                            );
751                        }
752                    };
753                    Ok(Item::Atomic(value))
754                })
755                .collect()
756        }
757        ItemType::Kind(kind) => {
758            let test = pattern::step_test(
759                match kind {
760                    einvoice_xpath::KindTest::Attribute(_) => {
761                        einvoice_xpath::PatternAxis::Attribute
762                    }
763                    _ => einvoice_xpath::PatternAxis::Child,
764                },
765                &einvoice_xpath::NodeTest::Kind(kind.clone()),
766            );
767            for item in &items {
768                let ok = match item {
769                    Item::Node(n) => {
770                        matches!(kind, einvoice_xpath::KindTest::AnyKind) || test.matches(n)
771                    }
772                    Item::Atomic(_) => false,
773                };
774                if !ok {
775                    return err(
776                        code,
777                        format!("Required item type of value is {}", type_name(t)),
778                    );
779                }
780            }
781            Ok(items)
782        }
783    }
784}
785
786/// Inserts a space where a comment's text would contain `--` or end with `-` (XSLT 2.0
787/// section 11.6).
788fn comment_text(text: &str) -> String {
789    let mut out = String::with_capacity(text.len());
790    let mut previous_dash = false;
791    for c in text.chars() {
792        if c == '-' && previous_dash {
793            out.push(' ');
794        }
795        previous_dash = c == '-';
796        out.push(c);
797    }
798    if previous_dash {
799        out.push(' ');
800    }
801    out
802}
803
804/// Resolves a URI reference against a base URI (RFC 3986 section 5.2, without the
805/// query and fragment cases the rule sets never produce).
806fn resolve_uri(reference: &str, base: Option<&str>) -> String {
807    let has_scheme = reference.split_once(':').is_some_and(|(scheme, _)| {
808        let mut chars = scheme.chars();
809        chars.next().is_some_and(|c| c.is_ascii_alphabetic())
810            && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
811    });
812    let Some(base) = base.filter(|_| !has_scheme) else {
813        return reference.to_owned();
814    };
815    if reference.is_empty() {
816        return base.to_owned();
817    }
818    let joined = if reference.starts_with('/') {
819        match base.split_once(':') {
820            Some((scheme, _)) => format!("{scheme}:{reference}"),
821            None => reference.to_owned(),
822        }
823    } else {
824        let directory = base.rfind('/').map_or("", |i| &base[..=i]);
825        format!("{directory}{reference}")
826    };
827    // Remove `.` and `..` segments.
828    let (prefix, path) = joined.split_once(':').unwrap_or(("", &joined));
829    let mut segments: Vec<&str> = Vec::new();
830    for segment in path.split('/') {
831        match segment {
832            "." => {}
833            ".." => {
834                if segments.len() > 1 {
835                    segments.pop();
836                }
837            }
838            s => segments.push(s),
839        }
840    }
841    let path = segments.join("/");
842    if prefix.is_empty() {
843        path
844    } else {
845        format!("{prefix}:{path}")
846    }
847}
848
849impl<'e, 'a> Runtime<'e, 'a> {
850    fn dc(&self) -> Result<&'a DynamicContext<'a>> {
851        self.dc
852            .get()
853            .ok_or_else(|| TransformError::new("INTERNAL", "no dynamic context"))
854    }
855
856    /// Converts an evaluator error, giving back the error a host callback raised.
857    fn xerr(&self, e: einvoice_xpath_eval::Error) -> TransformError {
858        if e.code() == ErrorCode::Host
859            && let Some(stashed) = self.stashed.borrow_mut().take()
860        {
861            return stashed;
862        }
863        e.into()
864    }
865
866    /// Counts one more invocation in progress, until the guard returned is dropped: a
867    /// `LIMIT` error beyond `options.max_nesting`, or when the invocations in progress
868    /// use more than `options.max_stack` bytes of stack. Every recursion of a
869    /// transformation goes through an invocation (a template rule applied to a child, a
870    /// named template or a function calling itself), so this bounds the depth of the
871    /// call stack.
872    fn nested(&self) -> Result<Nested<'_>> {
873        let depth = self.nesting.get();
874        if depth >= self.options.max_nesting {
875            return Err(TransformError::limit_exceeded(LimitExceeded::Nesting {
876                max: self.options.max_nesting,
877            }));
878        }
879        self.check_stack()?;
880        self.nesting.set(depth + 1);
881        Ok(Nested(&self.nesting))
882    }
883
884    /// A `LIMIT` error when the invocations in progress use more than `options.max_stack`
885    /// bytes of stack. Computing a lazy value checks it: a value may refer to another lazy
886    /// one, and so on (a parameter passed down a recursion and read at its end), each
887    /// computed inside the one that refers to it. The evaluator checks the same bound
888    /// ([`DynamicContext::with_stack_limit`]) at each level of an expression, which may be
889    /// evaluated at the deepest invocation.
890    fn check_stack(&self) -> Result<()> {
891        self.stack.check().map_err(TransformError::limit_exceeded)
892    }
893
894    /// Keeps an error for [`Runtime::xerr`] and gives the evaluator a placeholder.
895    fn stash(&self, e: TransformError) -> einvoice_xpath_eval::Error {
896        let message = e.to_string();
897        *self.stashed.borrow_mut() = Some(e);
898        einvoice_xpath_eval::Error::new(ErrorCode::Host, message)
899    }
900
901    fn evaluate(&self, expr: &CompiledExpr, context: &Context) -> Result<Vec<Item>> {
902        expr.evaluate(self.dc()?, context).map_err(|e| self.xerr(e))
903    }
904
905    fn test(&self, expr: &CompiledExpr, context: &Context) -> Result<bool> {
906        expr.effective_boolean_value(self.dc()?, context)
907            .map_err(|e| self.xerr(e))
908    }
909
910    /// Runs `f` with `frame` as the frame variables are read from.
911    fn in_frame<T>(
912        &self,
913        frame: Option<Rc<Frame<'e>>>,
914        f: impl FnOnce() -> Result<T>,
915    ) -> Result<T> {
916        let Some(frame) = frame else {
917            return f();
918        };
919        self.frames.borrow_mut().push(frame);
920        let result = f();
921        self.frames.borrow_mut().pop();
922        result
923    }
924
925    fn top_frame(&self) -> Option<Rc<Frame<'e>>> {
926        self.frames.borrow().last().cloned()
927    }
928
929    fn set_slot(&self, slot: usize, value: Slot<'e>) -> Result<()> {
930        let frames = self.frames.borrow();
931        let Some(frame) = frames.last() else {
932            return err("INTERNAL", "no frame for a local variable");
933        };
934        let mut slots = frame.slots.borrow_mut();
935        let Some(s) = slots.get_mut(slot) else {
936            return err("INTERNAL", "variable slot out of range");
937        };
938        *s = value;
939        Ok(())
940    }
941
942    #[inline(never)]
943    fn force(&self, thunk: &Thunk<'e>) -> Result<Rc<[Item]>> {
944        if let Some(value) = thunk.memo.get() {
945            return Ok(Rc::clone(value));
946        }
947        self.check_stack()?;
948        let frame = match &thunk.frame {
949            None => None,
950            Some(weak) => Some(
951                weak.upgrade()
952                    .ok_or_else(|| TransformError::new("INTERNAL", "variable frame is gone"))?,
953            ),
954        };
955        let state = State {
956            context: &thunk.context,
957            mode: thunk.mode,
958            rule: thunk.rule,
959        };
960        let value = self.in_frame(frame, || {
961            self.value(thunk.value, thunk.as_type, &state, thunk.code)
962        })?;
963        let _ = thunk.memo.set(Rc::clone(&value));
964        thunk.hold.borrow_mut().take();
965        if let Some(learner) = &thunk.report {
966            learner.completed();
967        }
968        Ok(value)
969    }
970
971    #[inline(never)]
972    fn force_argument(&self, thunk: &ArgumentThunk<'e>) -> Result<Rc<[Item]>> {
973        if let Some(value) = thunk.memo.get() {
974            return Ok(Rc::clone(value));
975        }
976        self.check_stack()?;
977        let frame = match &thunk.frame {
978            None => None,
979            Some(weak) => Some(
980                weak.upgrade()
981                    .ok_or_else(|| TransformError::new("INTERNAL", "caller frame is gone"))?,
982            ),
983        };
984        let items = self.in_frame(frame, || {
985            thunk
986                .argument
987                .evaluate(self.dc()?)
988                .map_err(|e| self.xerr(e))
989        })?;
990        let value: Rc<[Item]> = Self::argument_value(thunk.function, thunk.param, items)?.into();
991        let _ = thunk.memo.set(Rc::clone(&value));
992        if let Some(learner) = &thunk.report {
993            learner.completed();
994        }
995        Ok(value)
996    }
997
998    /// An argument converted to the type of its parameter.
999    fn argument_value(
1000        function: &CompiledFunction,
1001        param: &Binding,
1002        items: Vec<Item>,
1003    ) -> Result<Vec<Item>> {
1004        match &param.as_type {
1005            Some(t) => convert(items, t, "XPTY0004").map_err(|e| {
1006                TransformError::new(
1007                    e.code(),
1008                    format!(
1009                        "{} (argument ${} of {}())",
1010                        e.message(),
1011                        param.name,
1012                        function.name
1013                    ),
1014                )
1015            }),
1016            None => Ok(items),
1017        }
1018    }
1019
1020    fn slot_value(&self, slot: &Slot<'e>) -> Result<Rc<[Item]>> {
1021        match slot {
1022            Slot::Value(v) => Ok(Rc::clone(v)),
1023            Slot::Lazy(thunk) => self.force(thunk),
1024            Slot::Argument(thunk) => self.force_argument(thunk),
1025            Slot::Unset => err("INTERNAL", "variable read before it is bound"),
1026        }
1027    }
1028
1029    fn variable(&self, id: VariableId) -> Result<Rc<[Item]>> {
1030        let index = id.0 as usize;
1031        let globals = self.exe.globals.len();
1032        if index < globals {
1033            return self.global(index);
1034        }
1035        let slot = {
1036            let frames = self.frames.borrow();
1037            let Some(frame) = frames.last() else {
1038                return err("INTERNAL", "no frame for a local variable");
1039            };
1040            let slots = frame.slots.borrow();
1041            slots
1042                .get(index - globals)
1043                .cloned()
1044                .ok_or_else(|| TransformError::new("INTERNAL", "variable slot out of range"))?
1045        };
1046        self.slot_value(&slot)
1047    }
1048
1049    fn global(&self, index: usize) -> Result<Rc<[Item]>> {
1050        let g = &self.exe.globals[index];
1051        {
1052            let mut state = self.globals[index].borrow_mut();
1053            match &*state {
1054                GlobalState::Done(v) => return Ok(Rc::clone(v)),
1055                GlobalState::Evaluating => {
1056                    return err(
1057                        "XTDE0640",
1058                        format!("Circular definition of global variable ${}", g.name),
1059                    )
1060                    .at(g.line);
1061                }
1062                GlobalState::Pending => *state = GlobalState::Evaluating,
1063            }
1064        }
1065        let supplied = if g.is_param {
1066            self.options
1067                .parameters
1068                .iter()
1069                .find(|(n, _)| n.same_expanded_name(&g.name))
1070        } else {
1071            None
1072        };
1073        let value = if let Some((_, items)) = supplied {
1074            match &g.as_type {
1075                Some(t) => convert(items.clone(), t, "XTTE0590"),
1076                None => Ok(items.clone()),
1077            }
1078            .map(Rc::from)
1079        } else {
1080            let context = Context::for_item(Item::Node(self.source_root.clone()));
1081            let state = State {
1082                context: &context,
1083                mode: self.exe.default_mode,
1084                rule: None,
1085            };
1086            let frame = (g.slots > 0).then(|| Frame::new(g.slots));
1087            let code = if g.is_param { "XTTE0590" } else { "XTTE0570" };
1088            self.in_frame(frame, || {
1089                self.value(&g.value, g.as_type.as_ref(), &state, code)
1090            })
1091        };
1092        let value = match value {
1093            Ok(v) => v,
1094            Err(e) => {
1095                *self.globals[index].borrow_mut() = GlobalState::Pending;
1096                return Err(e.at(g.line));
1097            }
1098        };
1099        *self.globals[index].borrow_mut() = GlobalState::Done(Rc::clone(&value));
1100        Ok(value)
1101    }
1102
1103    /// The value of a binding, computed now.
1104    fn value(
1105        &self,
1106        value: &'e Value,
1107        as_type: Option<&'e SequenceType>,
1108        state: &State<'_>,
1109        code: &str,
1110    ) -> Result<Rc<[Item]>> {
1111        let items = match value {
1112            Value::Select(expr) => self.evaluate(expr, state.context)?,
1113            Value::Content(body) => {
1114                if as_type.is_some() {
1115                    let mut sink = SequenceSink::default();
1116                    self.exec(body, state, &mut sink)?;
1117                    sink.items
1118                } else {
1119                    let mut sink = TreeSink::new();
1120                    self.exec(body, state, &mut sink)?;
1121                    vec![Item::Node(sink.finish()?.root())]
1122                }
1123            }
1124            Value::Absent => {
1125                if as_type.is_some() {
1126                    Vec::new()
1127                } else {
1128                    vec![Item::Atomic(AtomicValue::String(String::new()))]
1129                }
1130            }
1131        };
1132        let items = match as_type {
1133            Some(t) => convert(items, t, code)?,
1134            None => items,
1135        };
1136        Ok(items.into())
1137    }
1138
1139    /// A binding's slot: computed now, or later (see [`Eval`]).
1140    fn bind(
1141        &self,
1142        value: &'e Value,
1143        as_type: Option<&'e SequenceType>,
1144        eval: Eval,
1145        state: &State<'_>,
1146        code: &'static str,
1147    ) -> Result<Slot<'e>> {
1148        let report = match eval {
1149            Eval::Eager => None,
1150            Eval::Lazy => Some(None),
1151            Eval::Learning {
1152                learner,
1153                every_counts,
1154            } => self
1155                .learners
1156                .get(learner)
1157                .and_then(|l| l.evaluation(every_counts).map(|r| r.then(|| Rc::clone(l)))),
1158        };
1159        let Some(report) = report else {
1160            return Ok(Slot::Value(self.value(value, as_type, state, code)?));
1161        };
1162        Ok(Slot::Lazy(Rc::new(Thunk {
1163            value,
1164            as_type,
1165            code,
1166            context: state.context.clone(),
1167            mode: state.mode,
1168            rule: state.rule,
1169            frame: self.top_frame().map(|f| Rc::downgrade(&f)),
1170            memo: OnceCell::new(),
1171            report,
1172            hold: RefCell::new(None),
1173        })))
1174    }
1175
1176    fn with_params(&self, params: &'e [WithParam], state: &State<'_>) -> Result<Params<'e>> {
1177        if params.is_empty() {
1178            return Ok(Vec::new());
1179        }
1180        params
1181            .iter()
1182            .map(|p| {
1183                Ok((
1184                    &p.name,
1185                    self.bind(&p.value, p.as_type.as_ref(), p.eval, state, "XTTE0590")?,
1186                ))
1187            })
1188            .collect()
1189    }
1190
1191    /// Runs a sequence constructor. An `xsl:choose` (or `xsl:if`) that is its last
1192    /// instruction runs its branch in place, in the same loop: a template whose body is
1193    /// a choice (most templates that recurse) needs no stack frame for it.
1194    fn exec(&self, body: &'e [Inst], state: &State<'_>, sink: &mut dyn Sink) -> Result<()> {
1195        let mut body = body;
1196        while let Some((inst, rest)) = body.split_first() {
1197            if rest.is_empty()
1198                && let Inst::Choose(choose) = inst
1199            {
1200                body = self.branch(choose, state)?;
1201            } else {
1202                self.instruction(inst, state, sink)?;
1203                body = rest;
1204            }
1205        }
1206        Ok(())
1207    }
1208
1209    /// Runs one instruction. Each instruction has a function of its own: this one is on
1210    /// the path of every recursion through the templates (`xsl:apply-templates` in a
1211    /// template rule, ...), whose stack use per level of the document must stay small,
1212    /// so that it holds none of their locals, and dispatches only the instructions that
1213    /// hold others or invoke templates, each passed whole (its parts in a struct of their
1214    /// own, one binding per arm); [`Runtime::other_instruction`] the rest.
1215    fn instruction(&self, inst: &'e Inst, state: &State<'_>, sink: &mut dyn Sink) -> Result<()> {
1216        match inst {
1217            Inst::ApplyTemplates(apply) => self.apply_templates(apply, state, sink),
1218            Inst::NextMatch(next) => self.next_match(next, state, sink),
1219            Inst::CallTemplate(call) => self.call_template(call, state, sink),
1220            Inst::Choose(choose) => self.choose(choose, state, sink),
1221            Inst::ForEach(for_each) => self.for_each(for_each, state, sink),
1222            Inst::Element(element) => self.element(element, state, sink),
1223            _ => self.other_instruction(inst, state, sink),
1224        }
1225    }
1226
1227    /// The instructions [`Runtime::instruction`] does not dispatch itself.
1228    #[inline(never)]
1229    fn other_instruction(
1230        &self,
1231        inst: &'e Inst,
1232        state: &State<'_>,
1233        sink: &mut dyn Sink,
1234    ) -> Result<()> {
1235        match inst {
1236            Inst::Variable(binding) => self.variable_instruction(binding, state),
1237            Inst::Sequence { line, select } => self.sequence(*line, select, state, sink),
1238            Inst::ValueOf {
1239                line,
1240                select,
1241                separator,
1242                body,
1243            } => self.value_of(
1244                *line,
1245                select.as_deref(),
1246                separator.as_ref(),
1247                body,
1248                state,
1249                sink,
1250            ),
1251            Inst::Attribute {
1252                line,
1253                name,
1254                namespace,
1255                namespaces,
1256                select,
1257                body,
1258            } => self.attribute(
1259                *line,
1260                (name, namespace.as_ref()),
1261                namespaces,
1262                select.as_deref(),
1263                body,
1264                state,
1265                sink,
1266            ),
1267            Inst::CopyOf { line, select } => self.copy_of(*line, select, state, sink),
1268            Inst::Copy { line, body } => self.copy(*line, body, state, sink),
1269            Inst::ComputedElement {
1270                line,
1271                name,
1272                namespace,
1273                namespaces,
1274                body,
1275            } => self.computed_element(
1276                *line,
1277                name,
1278                namespace.as_ref(),
1279                namespaces,
1280                body,
1281                state,
1282                sink,
1283            ),
1284            Inst::Namespace {
1285                line,
1286                name,
1287                select,
1288                body,
1289            } => self.namespace(*line, name, select.as_deref(), body, state, sink),
1290            Inst::ProcessingInstruction {
1291                line,
1292                name,
1293                select,
1294                body,
1295            } => self.processing_instruction(*line, name, select.as_deref(), body, state, sink),
1296            Inst::Message {
1297                line,
1298                terminate,
1299                body,
1300            } => self.message(*line, terminate.as_ref(), body, state),
1301            Inst::Comment { line, body } => self.comment(*line, body, state, sink),
1302            Inst::Text(text) => sink.text(text),
1303            Inst::Number { line, level, count } => {
1304                self.number_instruction(*line, *level, count.as_ref(), state, sink)
1305            }
1306            Inst::ApplyTemplates(_)
1307            | Inst::NextMatch(_)
1308            | Inst::CallTemplate(_)
1309            | Inst::Choose(_)
1310            | Inst::ForEach(_)
1311            | Inst::Element(_) => self.instruction(inst, state, sink),
1312        }
1313    }
1314
1315    fn apply_templates(
1316        &self,
1317        apply: &'e CompiledApplyTemplates,
1318        state: &State<'_>,
1319        sink: &mut dyn Sink,
1320    ) -> Result<()> {
1321        let CompiledApplyTemplates {
1322            line,
1323            ref select,
1324            mode,
1325            ref params,
1326        } = *apply;
1327        let mode = match mode {
1328            ModeRef::Mode(m) => m,
1329            ModeRef::Current => state.mode,
1330        };
1331        // A selection of nodes read from the tree (`@*|*`), or any value. Each step in a
1332        // function of its own: the stack of a level of a recursion holds as little as
1333        // it can (a debug build keeps every local of a function on its stack).
1334        let Some(nodes) = self.select_in_place(line, select, state)? else {
1335            return self.apply_to_value(line, select, mode, params, state, sink);
1336        };
1337        let params = self.with_params(params, state).at(line)?;
1338        let size = Size::Known(nodes.len());
1339        let mut position = 0;
1340        while let Some(node) = nodes.get(position) {
1341            position += 1;
1342            self.apply_rule(&node, position, &size, mode, None, &params, sink)
1343                .at(line)?;
1344        }
1345        self.selections.borrow_mut().push(nodes.into_storage());
1346        Ok(())
1347    }
1348
1349    /// The nodes `select` selects, read in place from the tree, if it can be.
1350    fn select_in_place(
1351        &self,
1352        line: u32,
1353        select: &CompiledExpr,
1354        state: &State<'_>,
1355    ) -> Result<Option<NodeSelection>> {
1356        let storage = self.selections.borrow_mut().pop().unwrap_or_default();
1357        select
1358            .select_in_place(self.dc()?, state.context, storage)
1359            .map_err(|e| self.xerr(e))
1360            .at(line)
1361    }
1362
1363    /// `xsl:apply-templates` to the value of `select`.
1364    fn apply_to_value(
1365        &self,
1366        line: u32,
1367        select: &'e CompiledExpr,
1368        mode: usize,
1369        params: &'e [WithParam],
1370        state: &State<'_>,
1371        sink: &mut dyn Sink,
1372    ) -> Result<()> {
1373        let items = self.evaluate(select, state.context).at(line)?;
1374        let params = self.with_params(params, state).at(line)?;
1375        let size = items.len();
1376        for (i, item) in items.iter().enumerate() {
1377            match item {
1378                Item::Node(node) => self
1379                    .apply_rule(node, i + 1, &Size::Known(size), mode, None, &params, sink)
1380                    .at(line)?,
1381                // As Saxon, an XSLT 3.0 processor: no pattern of the subset matches an
1382                // atomic value, whose built-in rule writes it as text.
1383                Item::Atomic(_) => sink.text(&item.string_value()).at(line)?,
1384            }
1385        }
1386        Ok(())
1387    }
1388
1389    fn next_match(
1390        &self,
1391        next: &'e CompiledNextMatch,
1392        state: &State<'_>,
1393        sink: &mut dyn Sink,
1394    ) -> Result<()> {
1395        let CompiledNextMatch { line, ref params } = *next;
1396        let Some(rank) = state.rule else {
1397            return err("XTDE0560", "xsl:next-match without a current template rule").at(line);
1398        };
1399        let Some(focus) = &state.context.focus else {
1400            return err("XTDE0560", "xsl:next-match without a context item").at(line);
1401        };
1402        let Item::Node(node) = &focus.item else {
1403            return err("XTDE0560", "xsl:next-match on an atomic value").at(line);
1404        };
1405        let params = self.with_params(params, state).at(line)?;
1406        self.apply_rule(
1407            node,
1408            focus.position,
1409            &Size::Known(focus.size),
1410            state.mode,
1411            Some(rank),
1412            &params,
1413            sink,
1414        )
1415        .at(line)
1416    }
1417
1418    fn call_template(
1419        &self,
1420        call: &'e CompiledCallTemplate,
1421        state: &State<'_>,
1422        sink: &mut dyn Sink,
1423    ) -> Result<()> {
1424        let params = self.with_params(&call.params, state).at(call.line)?;
1425        self.invoke(
1426            call.template,
1427            state.context,
1428            state.mode,
1429            state.rule,
1430            &params,
1431            sink,
1432        )
1433        .at(call.line)
1434    }
1435
1436    fn choose(
1437        &self,
1438        choose: &'e CompiledChoose,
1439        state: &State<'_>,
1440        sink: &mut dyn Sink,
1441    ) -> Result<()> {
1442        let branch = self.branch(choose, state)?;
1443        self.exec(branch, state, sink)
1444    }
1445
1446    /// The branch of an `xsl:choose` to run: that of the first `xsl:when` whose test is
1447    /// true, or the `xsl:otherwise`. Out of [`Runtime::exec`] and [`Runtime::choose`],
1448    /// whose stack use is part of every level of recursion through the templates.
1449    #[inline(never)]
1450    fn branch(&self, choose: &'e CompiledChoose, state: &State<'_>) -> Result<&'e [Inst]> {
1451        for when in &choose.whens {
1452            if self.test(&when.test, state.context).at(when.line)? {
1453                return Ok(&when.body);
1454            }
1455        }
1456        Ok(&choose.otherwise)
1457    }
1458
1459    fn for_each(
1460        &self,
1461        for_each: &'e CompiledForEach,
1462        state: &State<'_>,
1463        sink: &mut dyn Sink,
1464    ) -> Result<()> {
1465        let CompiledForEach {
1466            line,
1467            ref select,
1468            ref body,
1469        } = *for_each;
1470        let items = self.evaluate(select, state.context).at(line)?;
1471        let size = items.len();
1472        for (i, item) in items.into_iter().enumerate() {
1473            let context = Context::at(item, i + 1, size);
1474            let inner = State {
1475                context: &context,
1476                mode: state.mode,
1477                rule: None,
1478            };
1479            self.exec(body, &inner, sink)?;
1480        }
1481        Ok(())
1482    }
1483
1484    #[inline(never)]
1485    fn sequence(
1486        &self,
1487        line: u32,
1488        select: &'e CompiledExpr,
1489        state: &State<'_>,
1490        sink: &mut dyn Sink,
1491    ) -> Result<()> {
1492        for item in self.evaluate(select, state.context).at(line)? {
1493            sink.item(&item).at(line)?;
1494        }
1495        Ok(())
1496    }
1497
1498    #[inline(never)]
1499    fn value_of(
1500        &self,
1501        line: u32,
1502        select: Option<&'e CompiledExpr>,
1503        separator: Option<&'e CompiledAvt>,
1504        body: &'e [Inst],
1505        state: &State<'_>,
1506        sink: &mut dyn Sink,
1507    ) -> Result<()> {
1508        let separator = match separator {
1509            Some(avt) => Some(self.avt(avt, state).at(line)?),
1510            None => None,
1511        };
1512        let mut parts = TextSink::new();
1513        let text = if let Some(expr) = select {
1514            for item in self.evaluate(expr, state.context).at(line)? {
1515                parts.item(&item)?;
1516            }
1517            parts.finish(separator.as_deref().unwrap_or(" "))
1518        } else {
1519            self.exec(body, state, &mut parts)?;
1520            parts.finish(separator.as_deref().unwrap_or(""))
1521        };
1522        sink.text(&text).at(line)
1523    }
1524
1525    #[inline(never)]
1526    #[expect(
1527        clippy::too_many_arguments,
1528        reason = "the parts of the instruction, its dynamic context and its sink"
1529    )]
1530    fn attribute(
1531        &self,
1532        line: u32,
1533        (name, namespace): (&'e CompiledAvt, Option<&'e CompiledAvt>),
1534        namespaces: &[NamespaceBinding],
1535        select: Option<&'e CompiledExpr>,
1536        body: &'e [Inst],
1537        state: &State<'_>,
1538        sink: &mut dyn Sink,
1539    ) -> Result<()> {
1540        let name = self.avt(name, state).at(line)?;
1541        let namespace = match namespace {
1542            Some(avt) => Some(self.avt(avt, state).at(line)?),
1543            None => None,
1544        };
1545        let name = attribute_name(&name, namespace.as_deref(), namespaces).at(line)?;
1546        let value = self.simple_content(select, body, state).at(line)?;
1547        sink.attribute(&name, &value).at(line)
1548    }
1549
1550    #[inline(never)]
1551    fn comment(
1552        &self,
1553        line: u32,
1554        body: &'e [Inst],
1555        state: &State<'_>,
1556        sink: &mut dyn Sink,
1557    ) -> Result<()> {
1558        let mut parts = TextSink::new();
1559        self.exec(body, state, &mut parts)?;
1560        sink.comment(&comment_text(&parts.finish(""))).at(line)
1561    }
1562
1563    #[inline(never)]
1564    fn number_instruction(
1565        &self,
1566        line: u32,
1567        level: NumberLevel,
1568        count: Option<&'e CountPattern>,
1569        state: &State<'_>,
1570        sink: &mut dyn Sink,
1571    ) -> Result<()> {
1572        let text = self.number(line, level, count, state).at(line)?;
1573        sink.text(&text).at(line)
1574    }
1575
1576    fn element(
1577        &self,
1578        element: &'e CompiledElement,
1579        state: &State<'_>,
1580        sink: &mut dyn Sink,
1581    ) -> Result<()> {
1582        self.start_element(element, state, sink)?;
1583        self.exec(&element.body, state, sink)?;
1584        sink.end_element().at(element.line)
1585    }
1586
1587    /// The start tag of a literal result element: its name, namespaces and attributes.
1588    /// Out of [`Runtime::element`], whose stack use is part of every level of recursion
1589    /// through the templates.
1590    #[inline(never)]
1591    fn start_element(
1592        &self,
1593        element: &'e CompiledElement,
1594        state: &State<'_>,
1595        sink: &mut dyn Sink,
1596    ) -> Result<()> {
1597        sink.start_element(&element.name, &element.namespaces)
1598            .at(element.line)?;
1599        for (attribute, value) in &element.attributes {
1600            self.attribute_value(element.line, attribute, value, state, sink)?;
1601        }
1602        Ok(())
1603    }
1604
1605    /// An attribute of a literal result element.
1606    #[inline(never)]
1607    fn attribute_value(
1608        &self,
1609        line: u32,
1610        name: &QName,
1611        value: &'e CompiledAvt,
1612        state: &State<'_>,
1613        sink: &mut dyn Sink,
1614    ) -> Result<()> {
1615        let value = self.avt(value, state).at(line)?;
1616        sink.attribute(name, &value).at(line)
1617    }
1618
1619    /// `xsl:copy`: a copy of the context item, the body evaluated for a document node or
1620    /// an element only, which keeps its namespace nodes.
1621    #[inline(never)]
1622    fn copy(
1623        &self,
1624        line: u32,
1625        body: &'e [Inst],
1626        state: &State<'_>,
1627        sink: &mut dyn Sink,
1628    ) -> Result<()> {
1629        let Some(focus) = &state.context.focus else {
1630            return err("XTTE0945", "xsl:copy without a context item").at(line);
1631        };
1632        let Item::Node(node) = &focus.item else {
1633            return sink.item(&focus.item).at(line);
1634        };
1635        match node.kind() {
1636            NodeKind::Document => {
1637                sink.start_document().at(line)?;
1638                self.exec(body, state, sink)?;
1639                sink.end_document().at(line)
1640            }
1641            NodeKind::Element => {
1642                let Some(name) = node.name() else {
1643                    return err("INTERNAL", "element without name");
1644                };
1645                let namespaces: Arc<[NamespaceBinding]> = node.namespaces_in_scope().into();
1646                sink.start_copied_element(name, &namespaces).at(line)?;
1647                self.exec(body, state, sink)?;
1648                sink.end_element().at(line)
1649            }
1650            // Of the other kinds, a copy of the node alone: the body is not evaluated.
1651            _ => copy_node(sink, node).at(line),
1652        }
1653    }
1654
1655    /// `xsl:copy-of`: deep copies of the nodes selected, the atomic values as they are.
1656    #[inline(never)]
1657    fn copy_of(
1658        &self,
1659        line: u32,
1660        select: &'e CompiledExpr,
1661        state: &State<'_>,
1662        sink: &mut dyn Sink,
1663    ) -> Result<()> {
1664        for item in self.evaluate(select, state.context).at(line)? {
1665            match &item {
1666                Item::Node(node) => copy_node(sink, node).at(line)?,
1667                Item::Atomic(_) => sink.item(&item).at(line)?,
1668            }
1669        }
1670        Ok(())
1671    }
1672
1673    /// `xsl:element`: an element named by the computed name, in the namespace it names,
1674    /// without namespace nodes of its own: the binding its name needs is added when its
1675    /// start tag is complete (namespace fixup, after those of `xsl:namespace`).
1676    #[expect(
1677        clippy::too_many_arguments,
1678        reason = "the parts of the instruction, its dynamic context and its sink"
1679    )]
1680    #[inline(never)]
1681    fn computed_element(
1682        &self,
1683        line: u32,
1684        name: &'e CompiledAvt,
1685        namespace: Option<&'e CompiledAvt>,
1686        namespaces: &[NamespaceBinding],
1687        body: &'e [Inst],
1688        state: &State<'_>,
1689        sink: &mut dyn Sink,
1690    ) -> Result<()> {
1691        let name = self.element_name(line, name, namespace, namespaces, state)?;
1692        sink.start_element(&name, &Arc::from(Vec::new())).at(line)?;
1693        self.exec(body, state, sink)?;
1694        sink.end_element().at(line)
1695    }
1696
1697    /// The name of `xsl:element`.
1698    #[inline(never)]
1699    fn element_name(
1700        &self,
1701        line: u32,
1702        name: &'e CompiledAvt,
1703        namespace: Option<&'e CompiledAvt>,
1704        namespaces: &[NamespaceBinding],
1705        state: &State<'_>,
1706    ) -> Result<QName> {
1707        let text = self.avt(name, state).at(line)?;
1708        let namespace = match namespace {
1709            Some(avt) => Some(self.avt(avt, state).at(line)?),
1710            None => None,
1711        };
1712        element_name(&text, namespace.as_deref(), namespaces).at(line)
1713    }
1714
1715    /// `xsl:namespace`: a namespace node on the element being constructed (XSLT 2.0
1716    /// section 11.7).
1717    #[inline(never)]
1718    fn namespace(
1719        &self,
1720        line: u32,
1721        name: &'e CompiledAvt,
1722        select: Option<&'e CompiledExpr>,
1723        body: &'e [Inst],
1724        state: &State<'_>,
1725        sink: &mut dyn Sink,
1726    ) -> Result<()> {
1727        let prefix = self.avt(name, state).at(line)?;
1728        let prefix = prefix.trim_matches(einvoice_xpath::is_xml_whitespace);
1729        let uri = self.simple_content(select, body, state).at(line)?;
1730        if !(prefix.is_empty() || einvoice_xpath::is_ncname(prefix)) || prefix == "xmlns" {
1731            return err(
1732                "XTDE0920",
1733                format!("invalid namespace prefix {prefix:?} in xsl:namespace"),
1734            )
1735            .at(line);
1736        }
1737        let xml = einvoice_xpath::XML_NAMESPACE;
1738        if (prefix == "xml") != (uri == xml) {
1739            return err(
1740                "XTDE0925",
1741                "the xml prefix and the XML namespace are bound to each other only",
1742            )
1743            .at(line);
1744        }
1745        if uri.is_empty() {
1746            return err("XTDE0930", "xsl:namespace with an empty namespace URI").at(line);
1747        }
1748        if prefix == "xml" {
1749            return Ok(());
1750        }
1751        sink.namespace((!prefix.is_empty()).then_some(prefix), &uri)
1752            .at(line)
1753    }
1754
1755    /// `xsl:processing-instruction` (XSLT 2.0 section 11.6): the target, an `NCName` other
1756    /// than `xml` in any case; the value without leading whitespace, `?>` written `? >`.
1757    #[inline(never)]
1758    fn processing_instruction(
1759        &self,
1760        line: u32,
1761        name: &'e CompiledAvt,
1762        select: Option<&'e CompiledExpr>,
1763        body: &'e [Inst],
1764        state: &State<'_>,
1765        sink: &mut dyn Sink,
1766    ) -> Result<()> {
1767        let target = self.avt(name, state).at(line)?;
1768        let target = target.trim_matches(einvoice_xpath::is_xml_whitespace);
1769        if !einvoice_xpath::is_ncname(target) || target.eq_ignore_ascii_case("xml") {
1770            return err(
1771                "XTDE0890",
1772                format!("invalid processing instruction name {target:?}"),
1773            )
1774            .at(line);
1775        }
1776        let value = self.simple_content(select, body, state).at(line)?;
1777        let value = value
1778            .trim_start_matches(einvoice_xpath::is_xml_whitespace)
1779            .replace("?>", "? >");
1780        sink.processing_instruction(target, &value).at(line)
1781    }
1782
1783    /// `xsl:message`: its content, a document node, written as Saxon writes messages
1784    /// (see [`Transformation::messages`]); with `terminate` `yes`, the transformation ends
1785    /// with the error `XTMM9000`.
1786    #[inline(never)]
1787    fn message(
1788        &self,
1789        line: u32,
1790        terminate: Option<&'e CompiledAvt>,
1791        body: &'e [Inst],
1792        state: &State<'_>,
1793    ) -> Result<()> {
1794        let terminate = match terminate {
1795            None => false,
1796            Some(avt) => {
1797                let value = self.avt(avt, state).at(line)?;
1798                match value.trim_matches(einvoice_xpath::is_xml_whitespace) {
1799                    "yes" | "true" | "1" => true,
1800                    "no" | "false" | "0" => false,
1801                    other => {
1802                        return err(
1803                            "XTDE0030",
1804                            format!("invalid value {other:?} of xsl:message/@terminate"),
1805                        )
1806                        .at(line);
1807                    }
1808                }
1809            }
1810        };
1811        let mut content = TreeSink::new();
1812        self.exec(body, state, &mut content)?;
1813        let document = content.finish()?;
1814        let root = document.root();
1815        let text = if root.children().next().is_some() {
1816            let settings = Serialization {
1817                indent: false,
1818                omit_xml_declaration: true,
1819                standalone: None,
1820            };
1821            let text = serialize(&root, settings, true).at(line)?;
1822            self.messages.borrow_mut().push(text.clone());
1823            text
1824        } else {
1825            String::new()
1826        };
1827        if terminate {
1828            return err("XTMM9000", text).at(line);
1829        }
1830        Ok(())
1831    }
1832
1833    fn variable_instruction(&self, binding: &'e Binding, state: &State<'_>) -> Result<()> {
1834        if !binding.used {
1835            return Ok(());
1836        }
1837        let slot = self
1838            .bind(
1839                &binding.value,
1840                binding.as_type.as_ref(),
1841                binding.eval,
1842                state,
1843                "XTTE0570",
1844            )
1845            .at(binding.line)?;
1846        self.set_slot(binding.slot, slot).at(binding.line)
1847    }
1848
1849    /// The value of `xsl:attribute`: `select` joined with spaces, or the content.
1850    fn simple_content(
1851        &self,
1852        select: Option<&'e CompiledExpr>,
1853        body: &'e [Inst],
1854        state: &State<'_>,
1855    ) -> Result<String> {
1856        let mut parts = TextSink::new();
1857        if let Some(expr) = select {
1858            for item in self.evaluate(expr, state.context)? {
1859                parts.item(&item)?;
1860            }
1861            Ok(parts.finish(" "))
1862        } else {
1863            self.exec(body, state, &mut parts)?;
1864            Ok(parts.finish(""))
1865        }
1866    }
1867
1868    fn avt(&self, avt: &'e CompiledAvt, state: &State<'_>) -> Result<String> {
1869        if let [AvtItem::Text(text)] = avt.0.as_slice() {
1870            return Ok(text.to_string());
1871        }
1872        let mut out = String::new();
1873        for item in &avt.0 {
1874            match item {
1875                AvtItem::Text(text) => out.push_str(text),
1876                AvtItem::Expr(expr) => {
1877                    for (i, value) in self.evaluate(expr, state.context)?.iter().enumerate() {
1878                        if i > 0 {
1879                            out.push(' ');
1880                        }
1881                        out.push_str(&value.atomize().to_string());
1882                    }
1883                }
1884            }
1885        }
1886        Ok(out)
1887    }
1888
1889    /// Finds the best rule for `node` in `mode` (ranked after `after`, for
1890    /// `xsl:next-match`) and runs it, or the built-in rule.
1891    #[expect(
1892        clippy::too_many_arguments,
1893        reason = "the focus, the mode, the rule and the parameters of the invocation"
1894    )]
1895    fn apply_rule(
1896        &self,
1897        node: &Node,
1898        position: usize,
1899        size: &Size<'_>,
1900        mode: usize,
1901        after: Option<u32>,
1902        params: &[(&'e QName, Slot<'e>)],
1903        sink: &mut dyn Sink,
1904    ) -> Result<()> {
1905        let Some(rank) = self.find_rule(mode, node, after)? else {
1906            return self.builtin(node, mode, params, sink);
1907        };
1908        let Some(index) = self.rule_template(mode, rank)? else {
1909            return Ok(());
1910        };
1911        let context = node_context(node, position, size.get());
1912        self.invoke(index, &context, mode, Some(rank), params, sink)
1913    }
1914
1915    /// The template of the rule of rank `rank` in `mode`, to invoke; `None` when it has
1916    /// nothing to bind or run, its invocation counted only, as [`Runtime::invoke`] counts
1917    /// it. Out of [`Runtime::apply_rule`], whose stack use is part of every level of
1918    /// recursion through the template rules.
1919    #[inline(never)]
1920    fn rule_template(&self, mode: usize, rank: u32) -> Result<Option<usize>> {
1921        let index = self.exe.modes[mode].rules[rank as usize].template;
1922        let template = &self.exe.templates[index];
1923        if template.body.is_empty() && template.params.is_empty() {
1924            let _nested = self.nested().at(template.line)?;
1925            return Ok(None);
1926        }
1927        Ok(Some(index))
1928    }
1929
1930    /// The chain of rules of `mode` for the name of `node`, an element or (`attribute`)
1931    /// an attribute. The names of the source document are looked up once per
1932    /// transformation ([`Executable::rule_names`]), then by number in each mode.
1933    fn named_chain(&self, mode: usize, node: &Node, attribute: bool) -> &'e [u32] {
1934        let exe: &'e Executable = self.exe;
1935        let compiled = &exe.modes[mode];
1936        let id = node
1937            .name_id()
1938            .filter(|_| Rc::ptr_eq(node.document(), self.source_root.document()));
1939        let Some(id) = id else {
1940            return compiled.named_chain(attribute, node.name());
1941        };
1942        let number = {
1943            let mut numbers = self.rule_name_numbers.borrow_mut();
1944            if numbers.is_empty() {
1945                numbers.resize(
1946                    self.source_root.document().name_count(),
1947                    NameNumber::Unknown,
1948                );
1949            }
1950            match numbers.get_mut(id as usize) {
1951                Some(NameNumber::Known(number)) => *number,
1952                Some(NameNumber::NoRules) => return &[],
1953                Some(entry) => {
1954                    let found = node
1955                        .name()
1956                        .and_then(|name| rule_name_number(&exe.rule_names, name));
1957                    *entry = found.map_or(NameNumber::NoRules, NameNumber::Known);
1958                    match found {
1959                        Some(number) => number,
1960                        None => return &[],
1961                    }
1962                }
1963                None => return compiled.named_chain(attribute, node.name()),
1964            }
1965        };
1966        compiled.named_by_number(attribute, number)
1967    }
1968
1969    /// Whether `node` matches the pattern of a rule. A dynamic error while matching is
1970    /// recovered as Saxon recovers it (see [`Runtime::pattern_error`]).
1971    fn rule_matches(&self, rank: u32, mode: usize, node: &Node) -> Result<bool> {
1972        let rule = &self.exe.modes[mode].rules[rank as usize];
1973        if rule.certain & (1 << kind_index(node.kind())) != 0 {
1974            // Every node of its kind the rule is tried on matches it.
1975            return Ok(true);
1976        }
1977        let template = &self.exe.templates[rule.template];
1978        let matcher = Matcher { dc: self.dc()? };
1979        // A union pattern with an explicit priority is one rule: its alternatives in
1980        // order, the first error ending the match.
1981        let (alternatives, text) = match rule.alternative {
1982            Some(index) => (
1983                template.pattern.get(index..=index).unwrap_or_default(),
1984                template
1985                    .alternative_texts
1986                    .get(index)
1987                    .map_or("", String::as_str),
1988            ),
1989            None => (template.pattern.as_slice(), template.pattern_text.as_str()),
1990        };
1991        let outcome = alternatives
1992            .iter()
1993            .try_fold(false, |found, a| Ok(found || matcher.matches(a, node)?));
1994        outcome.or_else(|e| self.pattern_error(e, template.line, text))
1995    }
1996
1997    /// A dynamic error raised while matching a pattern (of a template rule, or the
1998    /// `count` pattern of `xsl:number`), as Saxon-HE 12.10 handles it
1999    /// (`Pattern.matchesItem`): the node does not match, and the error is reported as
2000    /// a warning, whatever its code, except a circularity (`XTDE0640`), which ends the
2001    /// transformation. A global variable whose evaluation failed is not kept in error:
2002    /// the next reference evaluates it again (`GlobalVariable.actuallyEvaluate`), in a
2003    /// pattern or elsewhere. The refusals, limits and bugs of this crate (`UNSUPPORTED`,
2004    /// `LIMIT`, `INTERNAL`) are never recovered: Saxon would not have raised them.
2005    fn pattern_error(
2006        &self,
2007        e: einvoice_xpath_eval::Error,
2008        line: u32,
2009        pattern: &str,
2010    ) -> Result<bool> {
2011        let e = self.xerr(e);
2012        if matches!(
2013            e.code(),
2014            "XTDE0640" | "UNSUPPORTED" | LIMIT | "INTERNAL" | "HOST"
2015        ) {
2016            return Err(e.at(line));
2017        }
2018        self.warn(format!(
2019            "line {line}: {}: An error occurred matching pattern {{{pattern}}}: {}",
2020            e.code(),
2021            e.message()
2022        ));
2023        Ok(false)
2024    }
2025
2026    /// Reports a warning, once: Saxon's standard error reporter prints each distinct
2027    /// warning once.
2028    fn warn(&self, message: String) {
2029        if self.warned.borrow_mut().insert(message.clone()) {
2030            self.warnings.borrow_mut().push(message);
2031        }
2032    }
2033
2034    /// The rule for `node` in `mode`, chosen exactly as Saxon-HE 12.10 chooses it
2035    /// (`SimpleMode.getRule` and `searchRuleChain`): the chains of the node's name, of
2036    /// its kind, then the generic chain, each in rank order; a rule of higher priority
2037    /// replaces the best so far; on a tie the later declared rule wins and the ambiguity
2038    /// is reported as an XTDE0540 warning. For `xsl:next-match` (`after` is the current
2039    /// rule) only the rules ranked below the current one are candidates (lower
2040    /// priority, or same priority and declared before it, or an earlier part of the
2041    /// same template), and a tie between two parts of one template goes to the part
2042    /// found last.
2043    fn find_rule(&self, mode: usize, node: &Node, after: Option<u32>) -> Result<Option<u32>> {
2044        let compiled = &self.exe.modes[mode];
2045        let rules = &compiled.rules;
2046        let kind = node.kind();
2047        let named = match kind {
2048            NodeKind::Element => self.named_chain(mode, node, false),
2049            NodeKind::Attribute => self.named_chain(mode, node, true),
2050            _ => &[],
2051        };
2052        if after.is_none() && named.is_empty() {
2053            match compiled.plan(kind) {
2054                Plan::Builtin => return Ok(None),
2055                Plan::Rule(rank) => return Ok(Some(rank)),
2056                Plan::Search => {}
2057            }
2058        }
2059        let below_current = |rank: u32| -> bool {
2060            let Some(current) = after else {
2061                return true;
2062            };
2063            let (r, c) = (&rules[rank as usize], &rules[current as usize]);
2064            match r.compare_rank(c) {
2065                std::cmp::Ordering::Less => true,
2066                std::cmp::Ordering::Greater => false,
2067                std::cmp::Ordering::Equal => {
2068                    r.sequence < c.sequence || (r.sequence == c.sequence && r.part < c.part)
2069                }
2070            }
2071        };
2072        let mut best: Option<u32> = None;
2073        for chain in compiled.chains_with(kind, named) {
2074            for &rank in chain {
2075                if !below_current(rank) {
2076                    continue;
2077                }
2078                let Some(chosen) = best else {
2079                    if self.rule_matches(rank, mode, node)? {
2080                        best = Some(rank);
2081                    }
2082                    continue;
2083                };
2084                let (head, b) = (&rules[rank as usize], &rules[chosen as usize]);
2085                match head.compare_rank(b) {
2086                    std::cmp::Ordering::Less => break,
2087                    std::cmp::Ordering::Greater => {
2088                        if self.rule_matches(rank, mode, node)? {
2089                            best = Some(rank);
2090                        }
2091                    }
2092                    std::cmp::Ordering::Equal => {
2093                        if !self.rule_matches(rank, mode, node)? {
2094                            continue;
2095                        }
2096                        if head.template != b.template {
2097                            self.ambiguity(node, compiled, b, head);
2098                        }
2099                        // The later declared rule; between two parts of one template,
2100                        // the higher part, or for xsl:next-match the one found last.
2101                        let keep = b.sequence > head.sequence
2102                            || (b.sequence == head.sequence
2103                                && after.is_none()
2104                                && b.part > head.part);
2105                        best = Some(if keep { chosen } else { rank });
2106                        break;
2107                    }
2108                }
2109            }
2110        }
2111        Ok(best)
2112    }
2113
2114    /// Reports a tie between `a`, the best rule so far, and `b`, as Saxon's
2115    /// `reportAmbiguity` does, naming them in that order.
2116    fn ambiguity(
2117        &self,
2118        node: &Node,
2119        mode: &crate::prepare::CompiledMode,
2120        a: &crate::prepare::Rule,
2121        b: &crate::prepare::Rule,
2122    ) {
2123        let (ta, tb) = (
2124            &self.exe.templates[a.template],
2125            &self.exe.templates[b.template],
2126        );
2127        let later = if a.sequence > b.sequence { ta } else { tb };
2128        self.warn(format!(
2129            "XTDE0540: Ambiguous rule match for {} in mode {}: matches the template rules on line {} and line {}; the one on line {} is used",
2130            describe(node),
2131            mode.name,
2132            ta.line,
2133            tb.line,
2134            later.line
2135        ));
2136    }
2137
2138    /// The built-in template rule for `node`. For a document node or an element, it
2139    /// applies the template rules to the children, one level of recursion counted as an
2140    /// invocation ([`Runtime::nested`]).
2141    fn builtin(
2142        &self,
2143        node: &Node,
2144        mode: usize,
2145        params: &[(&'e QName, Slot<'e>)],
2146        sink: &mut dyn Sink,
2147    ) -> Result<()> {
2148        match node.kind() {
2149            NodeKind::Document | NodeKind::Element => {
2150                let _nested = self.nested()?;
2151                // The children are counted only if a template rule applied to one runs.
2152                let size = Size::ChildrenOf(node, Cell::new(None));
2153                for (i, child) in node.children().enumerate() {
2154                    self.apply_rule(&child, i + 1, &size, mode, None, params, sink)?;
2155                }
2156                Ok(())
2157            }
2158            NodeKind::Text | NodeKind::Attribute => sink.text(&node.string_value()),
2159            NodeKind::Comment | NodeKind::ProcessingInstruction => Ok(()),
2160        }
2161    }
2162
2163    /// Runs a template: its parameters bound from `params` or their default values,
2164    /// then its body. Counted as an invocation ([`Runtime::nested`]).
2165    ///
2166    /// An `xsl:call-template` in tail position of the body (its last instruction, or the
2167    /// last of the branch of an `xsl:choose` or `xsl:if` that is) runs as Saxon runs it,
2168    /// in the same invocation rather than one more inside it (Saxon's tail calls): a
2169    /// template that recurses so, over each character of a string for instance, needs no
2170    /// stack in proportion to its recursion. The frame of an invocation replaced is kept
2171    /// by the parameters it passes that are not computed yet, until they are
2172    /// ([`Runtime::exec_tail`]). At most `max_tail_calls` in a row.
2173    fn invoke(
2174        &self,
2175        index: usize,
2176        context: &Context,
2177        mode: usize,
2178        rule: Option<u32>,
2179        params: &[(&'e QName, Slot<'e>)],
2180        sink: &mut dyn Sink,
2181    ) -> Result<()> {
2182        let template = &self.exe.templates[index];
2183        if template.tail_calls {
2184            return self.invoke_with_tail_calls(index, context, mode, rule, params, sink);
2185        }
2186        let _nested = self.nested().at(template.line)?;
2187        // The frame pushed and popped here, not by `in_frame`: a closure and a generic
2188        // function would be two more stack frames in each level of the recursion.
2189        let framed = self.push_frame(template.slots);
2190        let state = State {
2191            context,
2192            mode,
2193            rule,
2194        };
2195        let mut result = self.bind_params(template, params, &state);
2196        if result.is_ok() {
2197            result = self.exec(&template.body, &state, sink);
2198        }
2199        if framed {
2200            self.pop_frame();
2201        }
2202        result.at(template.line)
2203    }
2204
2205    /// Pushes a new frame of `slots` slots, if `slots` is not 0: whether it did. Out of
2206    /// [`Runtime::invoke`], whose stack use is part of every level of recursion through
2207    /// the templates.
2208    #[inline(never)]
2209    fn push_frame(&self, slots: usize) -> bool {
2210        if slots == 0 {
2211            return false;
2212        }
2213        self.frames.borrow_mut().push(Frame::new(slots));
2214        true
2215    }
2216
2217    /// Pops the frame [`Runtime::push_frame`] pushed.
2218    #[inline(never)]
2219    fn pop_frame(&self) {
2220        self.frames.borrow_mut().pop();
2221    }
2222
2223    /// [`Runtime::invoke`] of a template with an `xsl:call-template` in tail position
2224    /// (see [`CompiledTemplate::tail_calls`](crate::prepare::CompiledTemplate)): the
2225    /// templates it calls so run in a loop, in place of the one that calls them. Out of
2226    /// [`Runtime::invoke`], whose stack use is part of every level of recursion through
2227    /// the templates.
2228    #[inline(never)]
2229    fn invoke_with_tail_calls(
2230        &self,
2231        index: usize,
2232        context: &Context,
2233        mode: usize,
2234        rule: Option<u32>,
2235        params: &[(&'e QName, Slot<'e>)],
2236        sink: &mut dyn Sink,
2237    ) -> Result<()> {
2238        let _nested = self.nested().at(self.exe.templates[index].line)?;
2239        let state = State {
2240            context,
2241            mode,
2242            rule,
2243        };
2244        let mut current = index;
2245        let mut passed: Option<Params<'e>> = None;
2246        let mut tail_calls = 0_u32;
2247        loop {
2248            let template = &self.exe.templates[current];
2249            let frame = (template.slots > 0).then(|| Frame::new(template.slots));
2250            let params = passed.as_deref().unwrap_or(params);
2251            let tail = self
2252                .in_frame(frame, || {
2253                    self.bind_params(template, params, &state)?;
2254                    self.exec_tail(&template.body, &state, sink)
2255                })
2256                .at(template.line)?;
2257            let Some(tail) = tail else {
2258                return Ok(());
2259            };
2260            tail_calls += 1;
2261            if tail_calls > self.options.max_tail_calls {
2262                return Err(TransformError::limit_exceeded(LimitExceeded::TailCalls {
2263                    max: self.options.max_tail_calls,
2264                })
2265                .at(template.line));
2266            }
2267            current = tail.template;
2268            passed = Some(tail.params);
2269        }
2270    }
2271
2272    /// Runs a sequence constructor in tail position of a template body: its
2273    /// `xsl:call-template` in tail position, if any, is not run but returned, its
2274    /// parameters bound, for [`Runtime::invoke`] to run in place of the template.
2275    fn exec_tail(
2276        &self,
2277        body: &'e [Inst],
2278        state: &State<'_>,
2279        sink: &mut dyn Sink,
2280    ) -> Result<Option<Box<TailCall<'e>>>> {
2281        let Some((last, rest)) = body.split_last() else {
2282            return Ok(None);
2283        };
2284        self.exec(rest, state, sink)?;
2285        match last {
2286            Inst::CallTemplate(CompiledCallTemplate {
2287                line,
2288                template,
2289                params,
2290            }) => {
2291                let params = self.with_params(params, state).at(*line)?;
2292                // The values not computed yet read this frame, which ends now.
2293                let frame = self.top_frame();
2294                for (_, slot) in &params {
2295                    if let Slot::Lazy(thunk) = slot {
2296                        thunk.hold.borrow_mut().clone_from(&frame);
2297                    }
2298                }
2299                Ok(Some(Box::new(TailCall {
2300                    template: *template,
2301                    params,
2302                })))
2303            }
2304            Inst::Choose(choose) => {
2305                let branch = self.branch(choose, state)?;
2306                self.exec_tail(branch, state, sink)
2307            }
2308            other => {
2309                self.instruction(other, state, sink)?;
2310                Ok(None)
2311            }
2312        }
2313    }
2314
2315    /// Binds the parameters of a template being invoked, in its frame: from `params`, or
2316    /// their default values. Out of [`Runtime::invoke`], whose stack use is part of every
2317    /// level of recursion through the templates.
2318    #[inline(never)]
2319    fn bind_params(
2320        &self,
2321        template: &'e CompiledTemplate,
2322        params: &[(&'e QName, Slot<'e>)],
2323        state: &State<'_>,
2324    ) -> Result<()> {
2325        for param in &template.params {
2326            let passed = params
2327                .iter()
2328                .find(|(name, _)| name.same_expanded_name(&param.name));
2329            let slot = match (passed, &param.as_type) {
2330                (Some((_, slot)), None) => slot.clone(),
2331                (Some((_, slot)), Some(t)) => {
2332                    let items = self.slot_value(slot)?.to_vec();
2333                    Slot::Value(convert(items, t, "XTTE0590").at(param.line)?.into())
2334                }
2335                (None, as_type) => self
2336                    .bind(
2337                        &param.value,
2338                        as_type.as_ref(),
2339                        param.eval,
2340                        state,
2341                        "XTTE0590",
2342                    )
2343                    .at(param.line)?,
2344            };
2345            self.set_slot(param.slot, slot)?;
2346        }
2347        Ok(())
2348    }
2349
2350    /// Calls a stylesheet function. Counted as an invocation ([`Runtime::nested`]). Its
2351    /// arguments are bound as Saxon binds them: those evaluated before the call as they
2352    /// are, the others lazily, with Saxon's learning per call site.
2353    fn call(&self, id: FunctionId, args: Vec<Argument>) -> Result<Vec<Item>> {
2354        let function = &self.exe.functions[id.0 as usize];
2355        let _nested = self.nested().at(function.line)?;
2356        let frame = self.bind_arguments(function, args)?;
2357        self.function_body(function, frame)
2358    }
2359
2360    /// The frame of a function call, its parameters bound to the arguments. Out of
2361    /// [`Runtime::call`], whose stack use is part of every level of a recursion through
2362    /// functions.
2363    #[inline(never)]
2364    fn bind_arguments(
2365        &self,
2366        function: &'e CompiledFunction,
2367        args: Vec<Argument>,
2368    ) -> Result<Rc<Frame<'e>>> {
2369        let caller = self.top_frame().map(|f| Rc::downgrade(&f));
2370        let frame = Frame::new(function.slots);
2371        for (param, argument) in function.params.iter().zip(args) {
2372            let learner = argument.site().map(|site| {
2373                Rc::clone(self.argument_learners.borrow_mut().entry(site).or_default())
2374            });
2375            let report = match &learner {
2376                None => None,
2377                Some(l) => l.evaluation(false),
2378            };
2379            let slot = match report {
2380                None => {
2381                    let items = argument.evaluate(self.dc()?).map_err(|e| self.xerr(e))?;
2382                    Slot::Value(Self::argument_value(function, param, items)?.into())
2383                }
2384                Some(report) => Slot::Argument(Rc::new(ArgumentThunk {
2385                    argument,
2386                    param,
2387                    function,
2388                    frame: caller.clone(),
2389                    memo: OnceCell::new(),
2390                    report: if report { learner } else { None },
2391                })),
2392            };
2393            frame.slots.borrow_mut()[param.slot] = slot;
2394        }
2395        Ok(frame)
2396    }
2397
2398    /// Runs the body of a function in its frame.
2399    #[inline(never)]
2400    fn function_body(
2401        &self,
2402        function: &'e CompiledFunction,
2403        frame: Rc<Frame<'e>>,
2404    ) -> Result<Vec<Item>> {
2405        // A stylesheet function has no focus and no current template rule.
2406        let context = Context::new();
2407        let state = State {
2408            context: &context,
2409            mode: self.exe.default_mode,
2410            rule: None,
2411        };
2412        let mut sink = SequenceSink::default();
2413        self.in_frame(Some(frame), || self.exec(&function.body, &state, &mut sink))
2414            .at(function.line)?;
2415        match &function.as_type {
2416            Some(t) => convert(sink.items, t, "XTTE0780").at(function.line),
2417            None => Ok(sink.items),
2418        }
2419    }
2420
2421    fn number(
2422        &self,
2423        line: u32,
2424        level: NumberLevel,
2425        count: Option<&'e CountPattern>,
2426        state: &State<'_>,
2427    ) -> Result<String> {
2428        let Some(Item::Node(node)) = state.context.focus.as_ref().map(|f| &f.item) else {
2429            return err("XTTE0990", "xsl:number needs a node as context item");
2430        };
2431        let matcher = Matcher { dc: self.dc()? };
2432        let counted = |n: &Node| -> Result<bool> {
2433            match count {
2434                // As a template rule's pattern, an error is recovered (Saxon's
2435                // `Navigator` matches the count pattern with `matchesItem`).
2436                Some(pattern) => pattern
2437                    .alternatives
2438                    .iter()
2439                    .try_fold(false, |found, a| Ok(found || matcher.matches(a, n)?))
2440                    .or_else(|e| self.pattern_error(e, line, &pattern.text)),
2441                None => Ok(n.kind() == node.kind()
2442                    && match (n.name(), node.name()) {
2443                        (Some(a), Some(b)) => a.same_expanded_name(b),
2444                        (None, None) => true,
2445                        _ => false,
2446                    }),
2447            }
2448        };
2449        let position = |n: &Node| -> Result<usize> {
2450            let mut p = 1;
2451            for sibling in n.axis(NodeAxis::PrecedingSibling) {
2452                if counted(&sibling)? {
2453                    p += 1;
2454                }
2455            }
2456            Ok(p)
2457        };
2458        let mut numbers = Vec::new();
2459        for ancestor in node.axis(NodeAxis::AncestorOrSelf) {
2460            if counted(&ancestor)? {
2461                numbers.push(position(&ancestor)?);
2462                if level == NumberLevel::Single {
2463                    break;
2464                }
2465            }
2466        }
2467        numbers.reverse();
2468        Ok(numbers
2469            .iter()
2470            .map(usize::to_string)
2471            .collect::<Vec<_>>()
2472            .join("."))
2473    }
2474
2475    fn load_document(&self, uri: &str, base: Option<&str>) -> Result<Node> {
2476        let absolute = resolve_uri(uri, base.or(self.exe.base_uri.as_deref()));
2477        if let Some((_, node)) = self.documents.borrow().iter().find(|(u, _)| *u == absolute) {
2478            return Ok(node.clone());
2479        }
2480        // As Saxon: the source document, asked for by its base URI, is parsed again and
2481        // is a different tree. Loaded once: the tree is kept under its URI above.
2482        let is_source = self.source_uri == Some(absolute.as_str());
2483        let text: Cow<'_, str> = if is_source {
2484            self.source_text.take().ok_or_else(|| {
2485                TransformError::new(
2486                    "INTERNAL",
2487                    "document() loads the source document, whose text was not kept",
2488                )
2489            })?
2490        } else {
2491            // The resolver's text is given to the tree, not copied.
2492            Cow::Owned(
2493                self.options
2494                    .resolver
2495                    .and_then(|r| r.resolve(&absolute))
2496                    .ok_or_else(|| {
2497                        TransformError::new(
2498                            "FODC0002",
2499                            format!("cannot retrieve the document at {absolute}"),
2500                        )
2501                    })?,
2502            )
2503        };
2504        // A loaded document has a document URI, as one in Saxon's document pool. A text
2505        // from the resolver is parsed once for every transformation of the stylesheet.
2506        let parsed = match text {
2507            Cow::Owned(text) if !is_source => {
2508                self.exe
2509                    .loaded
2510                    .parse_loaded(text, &absolute, self.options.max_depth)
2511            }
2512            text => Document::parse_loaded_with_max_depth(text, &absolute, self.options.max_depth),
2513        };
2514        let node = parsed
2515            .map_err(|e| loaded_document_error(&absolute, &e))?
2516            .root();
2517        self.documents.borrow_mut().push((absolute, node.clone()));
2518        Ok(node)
2519    }
2520}
2521
2522/// A node, for messages: its path from the root, written as Saxon-HE 12.10 writes it
2523/// (`Navigator.getPath`): `/r/x[2]/@a`, `/r/text()[1]`, the outermost element without
2524/// position. Saxon's error reporter prints each distinct warning once, so the path tells
2525/// apart exactly the nodes Saxon's tells apart.
2526fn describe(node: &Node) -> String {
2527    let name = |n: &Node| n.name().map(ToString::to_string).unwrap_or_default();
2528    // The position among the preceding siblings of the same kind and, for a node with a
2529    // name, the same name (`Navigator.getNumberSimple`).
2530    let number = |n: &Node| {
2531        1 + n
2532            .axis(NodeAxis::PrecedingSibling)
2533            .filter(|s| {
2534                s.kind() == n.kind()
2535                    && match (s.name(), n.name()) {
2536                        (Some(a), Some(b)) => a.same_expanded_name(b),
2537                        (None, None) => true,
2538                        _ => false,
2539                    }
2540            })
2541            .count()
2542    };
2543    // The path of each node from the root down, from its parent's: a loop rather than a
2544    // recursion over the ancestors, whose number only the document bounds.
2545    let lineage: Vec<Node> = node.axis(NodeAxis::AncestorOrSelf).collect();
2546    let mut path = String::new();
2547    let mut parent_kind: Option<NodeKind> = None;
2548    for n in lineage.iter().rev() {
2549        let parent_path = std::mem::take(&mut path);
2550        // A step under the parent, which is "/" for the document node.
2551        let under_parent = |step: String| {
2552            format!(
2553                "{}/{step}",
2554                if parent_path == "/" {
2555                    ""
2556                } else {
2557                    parent_path.as_str()
2558                }
2559            )
2560        };
2561        path = match n.kind() {
2562            NodeKind::Document => "/".to_owned(),
2563            NodeKind::Element => match parent_kind {
2564                None => name(n),
2565                Some(NodeKind::Document) => format!("/{}", name(n)),
2566                Some(_) => format!("{parent_path}/{}[{}]", name(n), number(n)),
2567            },
2568            NodeKind::Attribute => format!("{parent_path}/@{}", name(n)),
2569            NodeKind::Text => under_parent(format!("text()[{}]", number(n))),
2570            NodeKind::Comment => under_parent(format!("comment()[{}]", number(n))),
2571            NodeKind::ProcessingInstruction => {
2572                under_parent(format!("processing-instruction()[{}]", number(n)))
2573            }
2574        };
2575        parent_kind = Some(n.kind());
2576    }
2577    path
2578}
2579
2580/// The error for a document that `document()` could not parse: `LIMIT` for one beyond
2581/// the maximum depth, else `FODC0002`, as Saxon reports a document it cannot parse.
2582fn loaded_document_error(uri: &str, e: &DocumentError) -> TransformError {
2583    match e.limit() {
2584        Some(limit) => TransformError::limit_exceeded(limit).in_document(uri),
2585        None => TransformError::new("FODC0002", format!("{uri}: {}", e.message())),
2586    }
2587}
2588
2589impl Host for Runtime<'_, '_> {
2590    fn variable(&self, id: VariableId) -> einvoice_xpath_eval::Result<Rc<[Item]>> {
2591        Runtime::variable(self, id).map_err(|e| self.stash(e))
2592    }
2593
2594    fn call_function(
2595        &self,
2596        id: FunctionId,
2597        args: Vec<Argument>,
2598        _dc: &DynamicContext<'_>,
2599    ) -> einvoice_xpath_eval::Result<Vec<Item>> {
2600        self.call(id, args).map_err(|e| self.stash(e))
2601    }
2602
2603    fn document(&self, uri: &str, base: Option<&str>) -> einvoice_xpath_eval::Result<Node> {
2604        self.load_document(uri, base).map_err(|e| self.stash(e))
2605    }
2606
2607    fn system_property(&self, name: &QName) -> String {
2608        // Saxon-HE 12.10's values.
2609        einvoice_xslt::system_property(name.namespace.as_deref(), &name.local).to_owned()
2610    }
2611}
2612
2613#[cfg(test)]
2614mod tests {
2615    use super::{comment_text, resolve_uri};
2616
2617    #[test]
2618    fn comments_never_hold_double_dashes() {
2619        assert_eq!(comment_text("a--b-"), "a- -b- ");
2620        assert_eq!(comment_text("-x"), "-x");
2621        assert_eq!(comment_text("---"), "- - - ");
2622    }
2623
2624    #[test]
2625    fn uris_resolve_against_the_base() {
2626        assert_eq!(resolve_uri("b.xml", Some("file:/d/a.xml")), "file:/d/b.xml");
2627        assert_eq!(
2628            resolve_uri("../c/b.xml", Some("file:/d/e/a.xml")),
2629            "file:/d/c/b.xml"
2630        );
2631        assert_eq!(
2632            resolve_uri("file:/x.xml", Some("file:/d/a.xml")),
2633            "file:/x.xml"
2634        );
2635        assert_eq!(resolve_uri("/x.xml", Some("file:/d/a.xml")), "file:/x.xml");
2636        assert_eq!(resolve_uri("x.xml", None), "x.xml");
2637        assert_eq!(resolve_uri("", Some("file:/d/a.xml")), "file:/d/a.xml");
2638    }
2639}