einvoice_xslt_exec/lib.rs
1//! Executor of the XSLT 2.0 subset that the official e-invoicing validation stylesheets
2//! use (Schematron compiled to XSLT), with the behaviour of the reference engine,
3//! Saxon-HE 12.10: same template rules chosen, same result.
4//!
5//! A stylesheet loaded by [`einvoice_xslt::load`] is prepared once into an
6//! [`Executable`], which then runs on any number of documents with
7//! [`Executable::transform`]. Preparing compiles every XPath expression with
8//! [`einvoice_xpath_eval`], resolves variables, functions, named templates and modes, and
9//! indexes the template rules of each mode by the kind and name of the nodes they can
10//! match. A transformation parses the document, applies templates to its document node in
11//! the default mode and writes the result straight to XML as it is produced (the result
12//! tree is never held in memory): for a compiled Schematron, the SVRL report. Written by
13//! [`Executable::transform_compact`], the result is kept as a [`CompactOutput`], each
14//! distinct piece of its text once, and a [`ResultObserver`] reads it as it is written, as a
15//! parser of the text would: the report of a large document in a fraction of its size, and
16//! read without parsing it again.
17//!
18//! Supported, as XSLT 2.0 and Saxon define them:
19//!
20//! - template rules: match patterns (`/`, `root()`, path patterns with predicates, `//`,
21//! the XSLT 3.0 parenthesized patterns as Saxon-HE 12.10 reads them: `(A | B)` alone is
22//! `A | B`, a path ending with `(A | B)` is a union, `(A | B)[p]/c` and
23//! `(a | b)/(c | d)/e` match as written, see [`einvoice_xpath::parse_pattern`]),
24//! modes (named, `#default`, `#all`, `#current`),
25//! explicit and default priorities (each alternative of a pattern without explicit
26//! priority is a rule of its own, a pattern with one is a single rule), the rule
27//! chosen, and the next one for
28//! `xsl:next-match`, exactly as Saxon chooses them (its rule chains, ties going to
29//! the last declared rule with an XTDE0540 warning), the built-in rules for every node
30//! kind, and for atomic values, which Saxon, an XSLT 3.0 processor, lets
31//! `xsl:apply-templates` select and writes as text;
32//! - dynamic errors raised while matching a pattern (a template rule's, or the `count`
33//! pattern of `xsl:number`), in its predicates or in a global variable or function
34//! they use: as in Saxon, the node does not match and the error is a warning, except
35//! a circular global variable (`XTDE0640`), which ends the transformation; a global
36//! variable whose evaluation failed is evaluated again when next referred to;
37//! - `xsl:apply-templates`, `xsl:call-template`, `xsl:next-match` with `xsl:with-param`;
38//! template, function and global parameters and variables, with `as` conversion;
39//! `xsl:function`; when each value is computed, as Saxon-HE 12.10 computes it
40//! (lazily, inlined, or as its `LearningEvaluator` learns, see the `run` module), which
41//! decides which dynamic errors are raised;
42//! - `xsl:choose`, `xsl:if`, `xsl:for-each`, `xsl:sequence`, `xsl:value-of`
43//! (`separator`), `xsl:attribute`, `xsl:comment`, `xsl:text`, literal text,
44//! `xsl:number` (`level` single or multiple, `count`, format `1`), literal result
45//! elements with their namespaces;
46//! - temporary trees (variables whose value is a sequence constructor), simple content
47//! and complex content construction as XSLT 2.0 section 5.7 defines them, and
48//! sequences (an `xsl:function` body, a variable or parameter with `as`): an element,
49//! attribute, text node (even of zero length) or comment constructed there is a new
50//! parentless node, as the stylesheets compiled by SchXslt construct their reports;
51//! copied elements keep their namespaces;
52//! - `document()` through a [`DocumentResolver`] (the engine reads no file), relative
53//! URIs resolved against the base URI given by [`Executable::with_base_uri`], and the
54//! source document by its own URI, parsed again as Saxon does; a loaded document has
55//! that URI as document URI, the source document none (`document-uri(/)` is empty, as
56//! in Saxon-HE 12.10).
57//!
58//! Known differences: Saxon simplifies constant predicates before computing the
59//! default priority of a pattern (`x[true()]` gets the priority of `x`, 0, where XSLT
60//! gives 0.5); this crate uses the pattern as written. The official stylesheets have
61//! no constant predicate in a pattern. Error messages are worded differently from
62//! Saxon's (the codes are the same), and some of Saxon's quote the values involved
63//! where this crate's do not: the warnings for errors in patterns are then fewer
64//! distinct messages, for the same patterns and codes. Saxon keeps what its
65//! `LearningEvaluator` learns in the compiled stylesheet, over every document it
66//! transforms with it; this crate starts afresh with each transformation, as Saxon does
67//! with a stylesheet compiled for one document. The elements of a parsed document have
68//! no namespace nodes here: copied to the result, they get only the namespaces their
69//! names use.
70//!
71//! Limits ([`TransformOptions`]): the source document and the documents `document()`
72//! loads are refused when an element is nested deeper than `max_depth`
73//! ([`einvoice_xpath_eval::DEFAULT_MAX_DEPTH`], 256), and a transformation ends when its
74//! template rules, built-in rules, named templates and functions are invoked one inside
75//! another more than `max_nesting` deep ([`DEFAULT_MAX_NESTING`]) or use more than
76//! `max_stack` bytes of stack ([`DEFAULT_MAX_STACK`]), lazy values computed one inside
77//! another and the expressions being evaluated included: a `LIMIT` error
78//! ([`TransformError::limit`]) instead of a stack overflow, which would abort the process.
79//! The stylesheet itself is bounded when it is loaded: its instructions nest
80//! [`einvoice_xslt::MAX_NESTING`] deep at most, its expressions
81//! [`einvoice_xpath::MAX_DEPTH`] deep at most, so that loading and preparing it need a
82//! bounded stack too (a thread with the default 2 MiB stack, debug builds included).
83//! Walking a tree without template rules (copying a node, the path of a node in a
84//! warning) uses no recursion. With the defaults, the official stylesheets run on a
85//! document 256 deep on a thread with the default 2 MiB stack, debug builds included.
86//!
87//! Refused when the stylesheet is prepared, rather than run differently from the
88//! reference engine: a parenthesized pattern whose predicate may depend on the position.
89//! Everything outside the subset is already refused by [`einvoice_xslt::load`].
90//!
91//! ```
92//! let xslt = r#"<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
93//! <xsl:output omit-xml-declaration="yes"/>
94//! <xsl:template match="/"><total><xsl:value-of select="sum(//l/@a)"/></total></xsl:template>
95//! </xsl:stylesheet>"#;
96//! let executable = einvoice_xslt_exec::Executable::new(&einvoice_xslt::load(xslt)?)?;
97//! let result = executable.transform("<i><l a='1.5'/><l a='2'/></i>", None)?;
98//! assert_eq!(result.output, "<total>3.5</total>");
99//! # Ok::<(), Box<dyn std::error::Error>>(())
100//! ```
101
102mod error;
103mod output;
104mod pattern;
105mod prepare;
106mod run;
107mod sink;
108
109pub use error::{PrepareError, PrepareErrors, TransformError};
110pub use output::{CompactOutput, CompactTransformation, ResultObserver};
111pub use prepare::Executable;
112pub use run::{
113 DEFAULT_MAX_NESTING, DEFAULT_MAX_STACK, DEFAULT_MAX_TAIL_CALLS, DocumentResolver,
114 TransformOptions, Transformation, TreeTransformation, max_nesting_for_depth,
115};
116pub use sink::Serialization;
117
118/// Writes a tree as XML, as Saxon-HE 12.10 writes it with the XML output method and the
119/// parameters `settings` ([`Serialization`]): `root` is a document node (its children
120/// are written) or any other node.
121///
122/// # Errors
123///
124/// Text outside the document element (`UNSUPPORTED`).
125pub fn serialize(
126 root: &einvoice_xpath_eval::Node,
127 settings: Serialization,
128) -> Result<String, TransformError> {
129 sink::serialize(root, settings, false)
130}