Skip to main content

einvoice_validator/
validator.rs

1//! Loading a rule set once, then validating documents with it.
2
3use std::borrow::Cow;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6
7use einvoice_xpath_eval::{
8    Clock, CompiledExpr, Context, DEFAULT_MAX_DEPTH, Document, DynamicContext, ErrorCode, Item,
9    LimitExceeded, NoHost, SimpleStaticContext,
10};
11use einvoice_xslt::LoadErrorKind;
12use einvoice_xslt_exec::{
13    DEFAULT_MAX_STACK, Executable, TransformError, TransformOptions, max_nesting_for_depth,
14};
15use sha2::{Digest, Sha256};
16
17use crate::manifest::{
18    CII, MANIFEST_FILE, RuleSet, Scenario, SchemaDocumentEntry, SchemaId, StylesheetEntry,
19    UBL_CREDIT_NOTE, UBL_INVOICE, namespace_map,
20};
21use crate::report::{
22    NoScenario, Report, RuleSetVersion, SchemaError, Severities, StylesheetFailure,
23    StylesheetReport, SvrlReader,
24};
25use crate::resources::{BUNDLE_URI, Resources};
26use crate::{Error, builtin};
27
28/// Options of one validation.
29#[derive(Debug, Clone, Copy)]
30pub struct ValidateOptions<'a> {
31    document_uri: Option<&'a str>,
32    clock: Option<Clock>,
33    max_depth: u32,
34    max_stack: u32,
35    fail_closed: bool,
36}
37
38impl Default for ValidateOptions<'_> {
39    fn default() -> Self {
40        Self::new()
41    }
42}
43
44impl<'a> ValidateOptions<'a> {
45    /// The default options: the document has no URI, the clock is the system clock in
46    /// UTC, the maximum element depth is [`DEFAULT_MAX_DEPTH`] and the stack the
47    /// stylesheets may use is [`DEFAULT_MAX_STACK`].
48    #[must_use]
49    pub const fn new() -> Self {
50        Self {
51            document_uri: None,
52            clock: None,
53            max_depth: DEFAULT_MAX_DEPTH,
54            max_stack: DEFAULT_MAX_STACK,
55            fail_closed: false,
56        }
57    }
58
59    /// Fail closed: a finding that would otherwise be of severity
60    /// [`Severity::Other`](crate::Severity::Other) (a flag other than `fatal` and
61    /// `warning`, or none, unless the manifest of the rule set gives it a severity) is of
62    /// severity [`Severity::Fatal`](crate::Severity::Fatal): it makes the document
63    /// invalid. Off by default. For rule sets whose flags the caller does not know in
64    /// advance: every finding that is not a warning then rejects the document.
65    #[must_use]
66    pub const fn fail_closed(mut self, fail_closed: bool) -> Self {
67        self.fail_closed = fail_closed;
68        self
69    }
70
71    /// The maximum element depth of the document, and of any document a stylesheet
72    /// loads with `document()`: the document element is at depth 1, its children at
73    /// depth 2, and so on. A document with an element nested deeper is refused with
74    /// [`Error::Limit`] before its schema is checked. Default: [`DEFAULT_MAX_DEPTH`]
75    /// (256, libxml2's default).
76    ///
77    /// The stylesheets apply their template rules one element level inside another, so
78    /// their stack use grows with the depth: with the default, a validation runs on a
79    /// thread with the default 2 MiB stack, debug builds included. The nesting of
80    /// template and function invocations the stylesheets are allowed grows with the
81    /// maximum ([`max_nesting_for_depth`](crate::max_nesting_for_depth)), and so does the
82    /// stack they need: a larger maximum depth needs a larger
83    /// [`ValidateOptions::max_stack`], and a thread with that much stack.
84    ///
85    /// On WebAssembly, at most [`WASM_MAX_DEPTH`]: a validation asking for more fails with
86    /// [`Error::OptionOutOfRange`].
87    #[must_use]
88    pub const fn max_depth(mut self, max_depth: u32) -> Self {
89        self.max_depth = max_depth;
90        self
91    }
92
93    /// The most stack, in bytes, the stylesheets' template and function invocations may
94    /// use, measured from the start of each stylesheet: beyond it, the validation fails
95    /// with [`Error::Limit`] ([`LimitExceeded::Stack`]) instead of overflowing the
96    /// stack, which would abort the process. Default: [`DEFAULT_MAX_STACK`] (1.5 MiB), for
97    /// the default 2 MiB stack of a spawned thread. The thread that validates must have
98    /// this much stack and at least 512 KiB more, for its caller and the deepest
99    /// invocation.
100    ///
101    /// On WebAssembly, the default is 256 KiB, and so is the most allowed,
102    /// [`WASM_MAX_STACK`]: a validation asking for more fails with
103    /// [`Error::OptionOutOfRange`].
104    #[must_use]
105    pub const fn max_stack(mut self, bytes: u32) -> Self {
106        self.max_stack = bytes;
107        self
108    }
109
110    /// The clock of the stylesheets: the implicit timezone and the value of
111    /// `fn:current-dateTime()` (read once per validation, as the reference engine reads
112    /// it once per transformation). By default, the system clock in UTC; required on
113    /// targets without a system clock, such as `wasm32-unknown-unknown`, where
114    /// validating without it fails with [`Error::Unsupported`].
115    #[must_use]
116    pub const fn clock(mut self, clock: Clock) -> Self {
117        self.clock = Some(clock);
118        self
119    }
120
121    /// The URI of the document: what `document-uri(/)` returns in the stylesheets, and
122    /// what the SVRL report states in `svrl:active-pattern/@documents`. For a file,
123    /// [`file_uri`] gives the URI the reference engine uses.
124    #[must_use]
125    pub const fn document_uri(mut self, uri: &'a str) -> Self {
126        self.document_uri = Some(uri);
127        self
128    }
129}
130
131/// The largest [`ValidateOptions::max_depth`] on WebAssembly: 400.
132///
133/// A WebAssembly engine runs the module's functions on a native stack of its own, beside
134/// the module's stack in linear memory, which is the only one the library measures
135/// ([`ValidateOptions::max_stack`]). When the native stack runs out first, the engine
136/// throws (a `RangeError` in V8, an `InternalError` in Firefox) and leaves the module's
137/// memory inconsistent, so that every later call fails. What keeps the native stack from
138/// running out is [`WASM_MAX_STACK`]; this maximum bounds the depth, and the nesting of
139/// template and function invocations that comes with it
140/// ([`max_nesting_for_depth`](crate::max_nesting_for_depth): 864), to what that stack
141/// serves. Measured with the npm package (opt-level 3, `wasm-opt -O3`) and 256 KiB of
142/// stack, on documents nested inside a UBL or a CII invoice: the stylesheets of the
143/// built-in rule sets (and of Peppol BIS Billing 3.0.22) validate a document up to 487
144/// levels deep when no rule fires on the nested elements, and up to 243 levels deep when
145/// a rule fires and reports on every one of them; deeper, the validation fails with
146/// [`Error::Limit`] ([`LimitExceeded::Stack`]), the same in Chrome and Firefox (main
147/// thread and Web Worker) and in Node.js. 400 keeps a margin below 487.
148pub const WASM_MAX_DEPTH: u32 = 400;
149
150/// The largest [`ValidateOptions::max_stack`] on WebAssembly, and its default there
151/// ([`DEFAULT_MAX_STACK`]): 256 KiB.
152///
153/// The native stack of a JavaScript engine can run out before the module's stack in
154/// linear memory reaches [`ValidateOptions::max_stack`] (see [`WASM_MAX_DEPTH`]).
155/// Measured with the npm package, the largest `max_stack`, in KiB, with which a
156/// recursion still ends with [`Error::Limit`] ([`LimitExceeded::Stack`]) rather than with
157/// the engine's stack overflow, for the stylesheets of the built-in rule sets and of
158/// Peppol BIS Billing 3.0.22 on a document 8192 levels deep / a named template calling
159/// itself (not as a tail call) / a template rule applying itself / a function calling
160/// itself:
161///
162/// | Engine | Official | Named template | Template rule | Function |
163/// |---|---|---|---|---|
164/// | Chrome 154, Web Worker | 320 | 342 | 348 | 543 |
165/// | Chrome 154, main thread | 522 | 512 | 545 | 863 |
166/// | Firefox 153, Web Worker | 630 | 674 | 689 | 1021 |
167/// | Firefox 153, main thread | 1021 | 1021 | 1021 | 1021 |
168/// | Node.js 22 | 640 | 679 | 685 | 1021 |
169///
170/// (1021 KiB is the module's own stack, 1 MiB, running out.) 256 KiB keeps a margin of a
171/// fifth below the smallest, a Chrome Web Worker.
172pub const WASM_MAX_STACK: u32 = 256 << 10;
173
174/// What [`ValidateOptions`] may ask for on this target: the largest maximum depth and the
175/// largest stack, or `None` for no bound.
176#[cfg(target_family = "wasm")]
177const CAPS: Option<(u32, u32)> = Some((WASM_MAX_DEPTH, WASM_MAX_STACK));
178#[cfg(not(target_family = "wasm"))]
179const CAPS: Option<(u32, u32)> = None;
180
181// The defaults are within the caps.
182#[cfg(target_family = "wasm")]
183const _: () = assert!(DEFAULT_MAX_STACK <= WASM_MAX_STACK && DEFAULT_MAX_DEPTH <= WASM_MAX_DEPTH);
184
185impl ValidateOptions<'_> {
186    /// [`Error::OptionOutOfRange`] when the options ask for more than `caps` (the largest
187    /// maximum depth and the largest stack) allow.
188    const fn check(&self, caps: Option<(u32, u32)>) -> Result<(), Error> {
189        let Some((max_depth, max_stack)) = caps else {
190            return Ok(());
191        };
192        if self.max_depth > max_depth {
193            return Err(Error::OptionOutOfRange {
194                option: "max_depth",
195                value: self.max_depth,
196                max: max_depth,
197            });
198        }
199        if self.max_stack > max_stack {
200            return Err(Error::OptionOutOfRange {
201                option: "max_stack",
202                value: self.max_stack,
203                max: max_stack,
204            });
205        }
206        Ok(())
207    }
208}
209
210/// The `file:` URI that the reference engine (Saxon-HE) gives a document read from the
211/// file at `path` (absolute). `None` for a relative path or one that is not Unicode.
212#[must_use]
213pub fn file_uri(path: &Path) -> Option<String> {
214    einvoice_xpath_eval::file_uri(path)
215}
216
217/// A rule set ready to validate documents: its schema loaded and its stylesheets
218/// prepared, once. Validating a document only reads it, so one `Validator` serves any
219/// number of documents, from any number of threads at once (`Send + Sync`); nothing of
220/// the rule set is copied per document. A clone shares the loaded rule set (it is
221/// reference-counted): cloning is cheap, and the clones can be moved to other threads.
222#[derive(Debug, Clone)]
223pub struct Validator {
224    rule_set: RuleSet,
225    schema: Option<Arc<einvoice_xsd::Schema>>,
226    /// The prepared stylesheets, in the order of `rule_set.stylesheets()`.
227    stylesheets: Arc<[Executable]>,
228    /// The resources the stylesheets read with `document()`.
229    resources: Arc<Resources>,
230    /// In a rule set that selects by scenario, what each scenario selects, in the order
231    /// of `rule_set.scenarios()`; empty otherwise.
232    selections: Arc<[Selection]>,
233    /// The indices of every stylesheet, in order: what runs without a selection.
234    all: Arc<[usize]>,
235}
236
237/// A scenario of a rule set that selects by scenario, prepared: its `match` expression
238/// compiled, and the stylesheets it runs.
239#[derive(Debug)]
240struct Selection {
241    matches: CompiledExpr,
242    /// Indices in `rule_set.stylesheets()`, in the order they run.
243    stylesheets: Vec<usize>,
244}
245
246impl Validator {
247    /// The built-in rule set `name` (see [`BUILTIN_RULE_SETS`](crate::BUILTIN_RULE_SETS)).
248    ///
249    /// # Errors
250    ///
251    /// [`Error::Bundle`] for an unknown name; otherwise as [`Validator::from_bundle`],
252    /// which none of the built-in rule sets fails in practice (a test loads each).
253    pub fn builtin(name: &str) -> Result<Self, Error> {
254        let (manifest, files) = builtin::get(name)?;
255        Self::from_bundle(manifest, files)
256    }
257
258    /// The built-in rule set `cen-ubl`: the CEN EN 16931 validation artefacts for UBL,
259    /// release 1.3.17 (EUPL-1.2), embedded unmodified, with the UBL 2.1 schemas.
260    ///
261    /// # Errors
262    ///
263    /// None in practice (a test loads it); the error is returned rather than hidden.
264    #[cfg(feature = "cen-ubl")]
265    pub fn cen_ubl() -> Result<Self, Error> {
266        Self::builtin("cen-ubl")
267    }
268
269    /// The built-in rule set `cen-cii`: the CEN EN 16931 validation artefacts for UN/CEFACT
270    /// CII D16B, release 1.3.17 (EUPL-1.2), embedded unmodified, with the UN/CEFACT CII
271    /// D16B schemas embedded in [`einvoice_xsd`] ([`SchemaId::CiiD16b`]).
272    ///
273    /// # Errors
274    ///
275    /// None in practice (a test loads it); the error is returned rather than hidden.
276    #[cfg(feature = "cen-cii")]
277    pub fn cen_cii() -> Result<Self, Error> {
278        Self::builtin("cen-cii")
279    }
280
281    /// Loads a bundle from memory: its manifest and its files, by their paths in the
282    /// manifest. Files not named by the manifest are ignored.
283    ///
284    /// # Errors
285    ///
286    /// [`Error::Bundle`] for an invalid manifest, a missing file or a stylesheet that is
287    /// not well-formed; [`Error::Checksum`] for a file whose SHA-256 differs from the
288    /// manifest's; [`Error::Unsupported`] for a stylesheet or schema outside the
289    /// supported subset.
290    pub fn from_bundle(manifest: &str, files: &[(&str, &[u8])]) -> Result<Self, Error> {
291        let rule_set = RuleSet::parse(manifest)?;
292        let file = |path: &str| files.iter().find(|(p, _)| *p == path).map(|(_, b)| *b);
293        let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
294        for entry in rule_set.stylesheets() {
295            let Some(bytes) = file(entry.path()) else {
296                return Err(Error::bundle(format!(
297                    "stylesheet {}: file {} missing from the bundle",
298                    entry.name(),
299                    entry.path()
300                )));
301            };
302            // In memory, the files of the bundle have URIs of their own.
303            let base_uri = format!("{BUNDLE_URI}{}", entry.path());
304            stylesheets.push(prepare(entry, bytes, Some(base_uri))?);
305        }
306        let mut resources = Resources::default();
307        for entry in rule_set.resources() {
308            let Some(bytes) = file(entry.path()) else {
309                return Err(Error::bundle(format!(
310                    "resource {}: file missing from the bundle",
311                    entry.path()
312                )));
313            };
314            resources.add(entry, bytes, format!("{BUNDLE_URI}{}", entry.path()))?;
315        }
316        let mut schema_documents = Vec::with_capacity(rule_set.schema_documents().len());
317        for entry in rule_set.schema_documents() {
318            let Some(bytes) = file(entry.path()) else {
319                return Err(Error::bundle(format!(
320                    "schema document {}: file missing from the bundle",
321                    entry.path()
322                )));
323            };
324            schema_documents.push(schema_document(entry, bytes)?);
325        }
326        Self::with(rule_set, stylesheets, resources, &schema_documents)
327    }
328
329    /// Loads the bundle in the directory `dir`: its manifest [`MANIFEST_FILE`] and the
330    /// files it names, relative to `dir`.
331    ///
332    /// # Errors
333    ///
334    /// [`Error::Io`] when a file cannot be read, otherwise as
335    /// [`Validator::from_bundle`].
336    pub fn from_bundle_dir(dir: impl AsRef<Path>) -> Result<Self, Error> {
337        let dir = dir.as_ref();
338        let manifest_path = dir.join(MANIFEST_FILE);
339        let manifest = read(&manifest_path)?;
340        let manifest = std::str::from_utf8(&manifest)
341            .map_err(|e| Error::bundle(format!("{}: not UTF-8: {e}", manifest_path.display())))?;
342        let rule_set = RuleSet::parse(manifest)?;
343        let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
344        for entry in rule_set.stylesheets() {
345            let mut path = dir.to_path_buf();
346            path.extend(entry.path().split('/'));
347            let bytes = read(&path)?;
348            let base_uri = std::path::absolute(&path).ok().and_then(|p| file_uri(&p));
349            stylesheets.push(prepare(entry, &bytes, base_uri)?);
350        }
351        let mut resources = Resources::default();
352        for entry in rule_set.resources() {
353            let mut path = dir.to_path_buf();
354            path.extend(entry.path().split('/'));
355            let bytes = read(&path)?;
356            let uri = std::path::absolute(&path)
357                .ok()
358                .and_then(|p| file_uri(&p))
359                .ok_or_else(|| {
360                    Error::bundle(format!(
361                        "resource {}: no file URI for {}",
362                        entry.path(),
363                        path.display()
364                    ))
365                })?;
366            resources.add(entry, &bytes, uri)?;
367        }
368        let mut schema_documents = Vec::with_capacity(rule_set.schema_documents().len());
369        for entry in rule_set.schema_documents() {
370            let mut path = dir.to_path_buf();
371            path.extend(entry.path().split('/'));
372            schema_documents.push(schema_document(entry, &read(&path)?)?);
373        }
374        Self::with(rule_set, stylesheets, resources, &schema_documents)
375    }
376
377    /// The validator of `rule_set`, its stylesheets prepared, its resources and the
378    /// documents of its schema, if the bundle has one (path and text), read.
379    fn with(
380        rule_set: RuleSet,
381        stylesheets: Vec<Executable>,
382        resources: Resources,
383        schema_documents: &[(String, String)],
384    ) -> Result<Self, Error> {
385        let schema = match rule_set.schema() {
386            None => None,
387            Some(id) => Some(load_schema(id, schema_documents)?),
388        };
389        let selections = if rule_set.selects_by_scenario() {
390            rule_set
391                .scenarios()
392                .iter()
393                .map(|scenario| selection(&rule_set, scenario))
394                .collect::<Result<Vec<_>, Error>>()?
395        } else {
396            Vec::new()
397        };
398        Ok(Self {
399            rule_set,
400            schema: schema.map(Arc::new),
401            all: (0..stylesheets.len()).collect(),
402            stylesheets: stylesheets.into(),
403            resources: Arc::new(resources),
404            selections: selections.into(),
405        })
406    }
407
408    /// The rule set: name, version, schema, stylesheets and their checksums.
409    #[must_use]
410    pub const fn rule_set(&self) -> &RuleSet {
411        &self.rule_set
412    }
413
414    /// Validates a document with the default options (no document URI).
415    ///
416    /// # Errors
417    ///
418    /// As [`Validator::validate_with`].
419    pub fn validate(&self, document: &[u8]) -> Result<Report, Error> {
420        self.validate_with(document, &ValidateOptions::new())
421    }
422
423    /// Validates a document given as a buffer, with the default options (no document
424    /// URI).
425    ///
426    /// # Errors
427    ///
428    /// As [`Validator::validate_with`].
429    pub fn validate_owned(&self, document: Vec<u8>) -> Result<Report, Error> {
430        self.validate_owned_with(document, &ValidateOptions::new())
431    }
432
433    /// [`Validator::validate_with`] on a document given as a buffer, which the
434    /// validation keeps instead of copying: the buffer becomes the text without a copy,
435    /// and the tree of the last stylesheet refers to it, so that while that stylesheet
436    /// runs the document is in memory once rather than twice. Same report as
437    /// [`Validator::validate_with`]; for a caller that has no further use for the bytes
438    /// (a file just read).
439    ///
440    /// # Errors
441    ///
442    /// As [`Validator::validate_with`].
443    pub fn validate_owned_with(
444        &self,
445        document: Vec<u8>,
446        options: &ValidateOptions<'_>,
447    ) -> Result<Report, Error> {
448        options.check(CAPS)?;
449        self.validate_text(Cow::Owned(decode_owned(document)?), options)
450    }
451
452    /// Validates a document: checks that it is well-formed XML, validates it against
453    /// the rule set's schema, then runs every stylesheet of the rule set on it. The
454    /// stylesheets run even when the schema reports errors, so that the report is
455    /// complete.
456    ///
457    /// In a rule set that selects by scenario
458    /// ([`RuleSet::selects_by_scenario`](crate::RuleSet::selects_by_scenario)), the
459    /// `match` expression of each scenario is then evaluated on the document, as the
460    /// KoSIT validator evaluates it (an expression that raises a dynamic error is false):
461    /// when exactly one is true, the stylesheets of that scenario run, in its order;
462    /// otherwise the report has no stylesheet and no schema error, only
463    /// [`Report::no_scenario`], and the document is invalid.
464    ///
465    /// When a stylesheet raises a dynamic error on a document that has schema
466    /// errors (a non-numeric amount the rules compute with, ...), the report is returned
467    /// all the same, invalid, with the error in [`StylesheetReport::failure`]; without
468    /// schema errors, the error is returned.
469    ///
470    /// The document must be in an encoding the validator reads (UTF-8, UTF-16, US-ASCII, ISO-8859-1, ISO-8859-15 or windows-1252,
471    /// see [`einvoice_xml::decode`]) and have no document type declaration.
472    ///
473    /// # Errors
474    ///
475    /// [`Error::NotXml`] when the document is not well-formed XML (bytes that are not
476    /// characters of its encoding included); [`Error::Unsupported`] for an encoding the
477    /// validator does not read, a document type declaration, or a
478    /// construct the engine refuses; [`Error::Limit`] for a document beyond a limit;
479    /// [`Error::OptionOutOfRange`] for options beyond what the target allows (on
480    /// WebAssembly); [`Error::Transform`] when a stylesheet raises a dynamic error on
481    /// the document; [`Error::Bundle`] when a stylesheet's result is not an SVRL report;
482    /// [`Error::Internal`] for a bug.
483    pub fn validate_with(
484        &self,
485        document: &[u8],
486        options: &ValidateOptions<'_>,
487    ) -> Result<Report, Error> {
488        options.check(CAPS)?;
489        self.validate_text(decode(document)?, options)
490    }
491
492    /// The validation of a decoded document: borrowed by the schema and every stylesheet
493    /// but the last, which is given it when it is owned.
494    fn validate_text(
495        &self,
496        text: Cow<'_, str>,
497        options: &ValidateOptions<'_>,
498    ) -> Result<Report, Error> {
499        let selects = self.rule_set.selects_by_scenario();
500        let identify = !selects && !self.rule_set.scenarios().is_empty();
501        let checked = check(&text, options.max_depth, self.schema.as_deref(), identify)?;
502        let schema_errors = checked.schema_errors;
503        let (scenario, run) = if selects {
504            match self.select(&text, options)? {
505                Ok(index) => (
506                    self.rule_set.scenarios().get(index),
507                    self.selections
508                        .get(index)
509                        .map(|s| s.stylesheets.as_slice())
510                        .unwrap_or_default(),
511                ),
512                // As the KoSIT validator's fallback scenario: no schema, no stylesheet,
513                // rejected.
514                Err(no_scenario) => return Ok(self.without_scenario(no_scenario, options)),
515            }
516        } else {
517            (
518                checked.identification.scenario(self.rule_set.scenarios()),
519                self.all.as_ref(),
520            )
521        };
522        let transform_options = TransformOptions {
523            implicit_timezone: options.clock.map(|c| c.implicit_timezone()),
524            current_date_time: options.clock.map(|c| c.current_date_time()),
525            max_depth: options.max_depth,
526            max_nesting: max_nesting_for_depth(options.max_depth),
527            max_stack: options.max_stack,
528            resolver: Some(&*self.resources),
529            ..TransformOptions::default()
530        };
531        let mut stylesheets = Vec::with_capacity(run.len());
532        let count = run.len();
533        // The text, until the last stylesheet is given it.
534        let mut text = Some(text);
535        for (index, &stylesheet) in run.iter().enumerate() {
536            let (Some(entry), Some(executable)) = (
537                self.rule_set.stylesheets().get(stylesheet),
538                self.stylesheets.get(stylesheet),
539            ) else {
540                return Err(Error::internal(
541                    "a scenario names no stylesheet of the rule set",
542                ));
543            };
544            let source = if index + 1 == count {
545                text.take()
546            } else {
547                text.as_deref().map(Cow::Borrowed)
548            }
549            .ok_or_else(|| Error::internal("the document text was given away early"))?;
550            // The findings are read as the stylesheet writes its report.
551            let mut reader = SvrlReader::new(Severities {
552                fail_closed: options.fail_closed,
553                unflagged_assert: entry.unflagged_assert(),
554                scenario,
555            });
556            let result = executable.transform_compact(
557                source,
558                options.document_uri,
559                &transform_options,
560                &mut reader,
561            );
562            let report = match result {
563                Ok(result) => StylesheetReport::new(
564                    entry,
565                    result.output,
566                    reader,
567                    result.warnings,
568                    options.document_uri,
569                )?,
570                Err(e) => match transform_error(entry, &e) {
571                    // The schema errors already make the document invalid: the verdict
572                    // stands, the report says which stylesheet could not finish.
573                    Error::Transform {
574                        code,
575                        line,
576                        message,
577                        ..
578                    } if !schema_errors.is_empty() => StylesheetReport::failed(
579                        entry,
580                        StylesheetFailure {
581                            code,
582                            line,
583                            message,
584                        },
585                        options.document_uri,
586                    ),
587                    other => return Err(other),
588                },
589            };
590            stylesheets.push(report);
591        }
592        Ok(Report {
593            rule_set: self.version(),
594            document_uri: options.document_uri.map(str::to_owned),
595            scenario: scenario.map(|s| s.name().to_owned()),
596            no_scenario: None,
597            schema_errors,
598            stylesheets,
599        })
600    }
601
602    /// The report on a document that has no scenario, in a rule set that selects by
603    /// scenario.
604    fn without_scenario(&self, no_scenario: NoScenario, options: &ValidateOptions<'_>) -> Report {
605        Report {
606            rule_set: self.version(),
607            document_uri: options.document_uri.map(str::to_owned),
608            scenario: None,
609            no_scenario: Some(no_scenario),
610            schema_errors: Vec::new(),
611            stylesheets: Vec::new(),
612        }
613    }
614
615    /// The rule set, as a report names it.
616    fn version(&self) -> RuleSetVersion {
617        RuleSetVersion {
618            name: self.rule_set.name().to_owned(),
619            title: self.rule_set.title().to_owned(),
620            version: self.rule_set.version().to_owned(),
621            schema: self.rule_set.schema().cloned(),
622            unchecked_schema: self.rule_set.unchecked_schema().map(str::to_owned),
623        }
624    }
625
626    /// The scenario of a rule set that selects by scenario that a document (checked
627    /// well-formed, and not nested deeper than `options.max_depth`) matches: the index of
628    /// the one whose `match` expression is true on it, or why there is none. The
629    /// expressions are evaluated as the KoSIT validator evaluates them: with the document
630    /// node as the context item, the effective boolean value; one that raises a dynamic
631    /// error is false (the validator logs the error and goes on). A construct the engine
632    /// refuses, or a limit, is an error rather than a false.
633    fn select(
634        &self,
635        text: &str,
636        options: &ValidateOptions<'_>,
637    ) -> Result<Result<usize, NoScenario>, Error> {
638        let document =
639            Document::parse_with_max_depth(text, None, options.max_depth).map_err(|e| {
640                // The XML check accepted the text: two parsers disagree, a bug.
641                Error::internal(format!("the document for the scenarios: {}", e.message()))
642            })?;
643        let clock = match options.clock {
644            Some(clock) => clock,
645            None => system_clock()?,
646        };
647        let dc = DynamicContext::new(&NoHost, clock);
648        let context = Context::for_item(Item::Node(document.root()));
649        let mut matched = Vec::new();
650        for (index, (scenario, selection)) in self
651            .rule_set
652            .scenarios()
653            .iter()
654            .zip(self.selections.iter())
655            .enumerate()
656        {
657            match selection.matches.effective_boolean_value(&dc, &context) {
658                Ok(true) => matched.push(index),
659                Ok(false) => {}
660                Err(e) => {
661                    let what = format!("scenario {:?}: match: {}", scenario.name(), e.message());
662                    if let Some(limit) = e.limit() {
663                        return Err(Error::Limit {
664                            limit,
665                            message: what,
666                        });
667                    }
668                    match e.code() {
669                        ErrorCode::Unsupported => return Err(Error::unsupported(what)),
670                        ErrorCode::Internal => return Err(Error::internal(what)),
671                        // A dynamic error: the KoSIT validator takes the scenario not to
672                        // match.
673                        _ => {}
674                    }
675                }
676            }
677        }
678        Ok(match matched[..] {
679            [index] => Ok(index),
680            [] => Err(NoScenario::NoneMatches),
681            _ => Err(NoScenario::SeveralMatch(
682                matched
683                    .iter()
684                    .filter_map(|&i| self.rule_set.scenarios().get(i))
685                    .map(|s| s.name().to_owned())
686                    .collect(),
687            )),
688        })
689    }
690}
691
692/// The clock of the `match` expressions when the options give none: the system clock in
693/// UTC, as for the stylesheets.
694#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
695fn system_clock() -> Result<Clock, Error> {
696    Clock::system(0).map_err(|e| Error::internal(format!("the system clock: {}", e.message())))
697}
698
699/// No system clock on this target: the caller must give one.
700#[cfg(all(target_family = "wasm", target_os = "unknown"))]
701fn system_clock() -> Result<Clock, Error> {
702    Err(Error::unsupported(
703        "no system clock on this target: give ValidateOptions::clock",
704    ))
705}
706
707/// A scenario of a rule set that selects by scenario, prepared: its `match` expression
708/// parsed with its namespaces and compiled, as an XPath expression without the XSLT
709/// functions; its stylesheets by index, every one of the rule set when it names none.
710fn selection(rule_set: &RuleSet, scenario: &Scenario) -> Result<Selection, Error> {
711    let what = format!("scenario {:?}: match", scenario.name());
712    let Some(text) = scenario.match_expression() else {
713        return Err(Error::internal(format!("{what}: none")));
714    };
715    let expr = einvoice_xpath::parse_expr(text, &namespace_map(scenario.namespaces()))
716        .map_err(|e| Error::bundle(format!("{what}: {e}")))?;
717    // A function or construct the engine does not have: refused, not evaluated
718    // differently.
719    let matches = einvoice_xpath_eval::compile(&expr, &SimpleStaticContext::new())
720        .map_err(|e| Error::unsupported(format!("{what}: {}", e.message())))?;
721    let stylesheets = match scenario.stylesheets() {
722        None => (0..rule_set.stylesheets().len()).collect(),
723        Some(names) => names
724            .iter()
725            .map(|name| {
726                rule_set
727                    .stylesheets()
728                    .iter()
729                    .position(|s| s.name() == name)
730                    .ok_or_else(|| Error::internal(format!("{what}: no stylesheet {name}")))
731            })
732            .collect::<Result<_, Error>>()?,
733    };
734    Ok(Selection {
735        matches,
736        stylesheets,
737    })
738}
739
740fn read(path: &Path) -> Result<Vec<u8>, Error> {
741    std::fs::read(path).map_err(|source| Error::Io {
742        path: PathBuf::from(path),
743        source,
744    })
745}
746
747/// A document of the schema of a bundle: its SHA-256 checked against the manifest's, its
748/// text decoded as a document is (any supported encoding); its path in the bundle and its text.
749fn schema_document(entry: &SchemaDocumentEntry, bytes: &[u8]) -> Result<(String, String), Error> {
750    let actual = sha256_hex(bytes);
751    if actual != entry.sha256() {
752        return Err(Error::Checksum {
753            path: entry.path().to_owned(),
754            expected: entry.sha256().to_owned(),
755            actual,
756        });
757    }
758    let text = decode(bytes)
759        .map_err(|e| Error::bundle(format!("schema document {}: {e}", entry.path())))?;
760    Ok((entry.path().to_owned(), text.into_owned()))
761}
762
763/// Loads the schema `id`: an embedded one, or that of the bundle from its documents
764/// (path and text).
765fn load_schema(
766    id: &SchemaId,
767    documents: &[(String, String)],
768) -> Result<einvoice_xsd::Schema, Error> {
769    let loaded = match id {
770        SchemaId::Ubl21 => einvoice_xsd::Schema::ubl_2_1(),
771        SchemaId::CiiD16b => einvoice_xsd::Schema::cii_d16b(),
772        SchemaId::Bundle(entry_point) => {
773            let files: Vec<(&str, &str)> = documents
774                .iter()
775                .map(|(path, text)| (path.as_str(), text.as_str()))
776                .collect();
777            einvoice_xsd::Schema::load(&files, &[entry_point.as_str()])
778        }
779    };
780    loaded.map_err(|e| {
781        if e.kind == einvoice_xsd::LoadErrorKind::Unsupported {
782            Error::unsupported(format!("schema {id}: {e}"))
783        } else if matches!(id, SchemaId::Bundle(_)) {
784            Error::bundle(format!("schema {id}: {e}"))
785        } else {
786            Error::internal(format!("the embedded schema {id} does not load: {e}"))
787        }
788    })
789}
790
791/// Lower-case hexadecimal SHA-256.
792pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
793    const HEX: &[u8; 16] = b"0123456789abcdef";
794    let digest = Sha256::digest(bytes);
795    let mut hex = String::with_capacity(64);
796    for byte in digest {
797        hex.push(char::from(HEX[usize::from(byte >> 4)]));
798        hex.push(char::from(HEX[usize::from(byte & 0x0f)]));
799    }
800    hex
801}
802
803/// Checks the checksum of a stylesheet, loads and prepares it.
804fn prepare(
805    entry: &StylesheetEntry,
806    bytes: &[u8],
807    base_uri: Option<String>,
808) -> Result<Executable, Error> {
809    let actual = sha256_hex(bytes);
810    if actual != entry.sha256() {
811        return Err(Error::Checksum {
812            path: entry.path().to_owned(),
813            expected: entry.sha256().to_owned(),
814            actual,
815        });
816    }
817    let what = format!("stylesheet {} ({})", entry.name(), entry.path());
818    let text = decode(bytes).map_err(|e| Error::bundle(format!("{what}: {e}")))?;
819    let sheet = einvoice_xslt::load(&text).map_err(|errors| {
820        let unsupported = errors.0.iter().any(|e| {
821            matches!(
822                e.kind,
823                LoadErrorKind::UnsupportedElement { .. }
824                    | LoadErrorKind::UnsupportedAttribute { .. }
825                    | LoadErrorKind::UnsupportedValue { .. }
826                    | LoadErrorKind::XPath { .. }
827                    | LoadErrorKind::TooDeep { .. }
828            )
829        });
830        let message = format!("{what}: {}", first_lines(&errors.to_string()));
831        if unsupported {
832            Error::unsupported(message)
833        } else {
834            Error::bundle(message)
835        }
836    })?;
837    let executable = Executable::new(&sheet).map_err(|errors| {
838        Error::unsupported(format!("{what}: {}", first_lines(&errors.to_string())))
839    })?;
840    Ok(match base_uri {
841        Some(uri) => executable.with_base_uri(uri),
842        None => executable,
843    })
844}
845
846/// At most the first ten lines of a list of errors, with the number left out.
847fn first_lines(text: &str) -> String {
848    const MAX: usize = 10;
849    let lines: Vec<&str> = text.lines().collect();
850    if lines.len() <= MAX {
851        return lines.join("; ");
852    }
853    format!(
854        "{}; and {} more",
855        lines[..MAX].join("; "),
856        lines.len() - MAX
857    )
858}
859
860fn transform_error(entry: &StylesheetEntry, e: &TransformError) -> Error {
861    let at = e.line().map_or_else(String::new, |l| format!(", line {l}"));
862    if let Some(limit) = e.limit() {
863        return Error::Limit {
864            limit,
865            message: format!("stylesheet {}{at}: {}", entry.name(), e.message()),
866        };
867    }
868    match e.code() {
869        "UNSUPPORTED" => {
870            Error::unsupported(format!("stylesheet {}{at}: {}", entry.name(), e.message()))
871        }
872        // The document was checked before: a parse error here means two parsers
873        // disagree, which is a bug.
874        "INTERNAL" | "SXXP0003" => Error::internal(format!(
875            "stylesheet {}{at}: {}: {}",
876            entry.name(),
877            e.code(),
878            e.message()
879        )),
880        code => Error::Transform {
881            stylesheet: entry.name().to_owned(),
882            code: code.to_owned(),
883            line: e.line(),
884            message: e.message().to_owned(),
885        },
886    }
887}
888
889/// The text of a document given as bytes, decoded with [`einvoice_xml::decode`]: UTF-8
890/// (borrowed), UTF-16, US-ASCII, ISO-8859-1, ISO-8859-15 or windows-1252, as its byte
891/// order mark, first bytes and XML declaration say.
892pub(crate) fn decode(bytes: &[u8]) -> Result<Cow<'_, str>, Error> {
893    einvoice_xml::decode(bytes).map_err(decoding_error)
894}
895
896/// [`decode`] on a buffer, which becomes the text without being copied when it is UTF-8
897/// (the byte order mark, if any, is removed in place).
898fn decode_owned(bytes: Vec<u8>) -> Result<String, Error> {
899    einvoice_xml::decode_owned(bytes).map_err(decoding_error)
900}
901
902/// The error for a document that cannot be decoded: [`Error::Unsupported`] for an
903/// encoding that is not read, [`Error::NotXml`] otherwise (bytes that are not a character
904/// of the encoding, first bytes and an XML declaration that disagree, a second byte
905/// order mark).
906fn decoding_error(e: einvoice_xml::Error) -> Error {
907    match e {
908        einvoice_xml::Error::UnsupportedEncoding(name) => Error::unsupported(format!(
909            "the {name} encoding: the encodings read are UTF-8, UTF-16, US-ASCII, ISO-8859-1, ISO-8859-15 and windows-1252"
910        )),
911        e => Error::NotXml {
912            line: e.pos().row,
913            column: e.pos().col,
914            message: e.to_string(),
915        },
916    }
917}
918
919/// The namespace of the UBL basic components (`cbc:`).
920const UBL_CBC: &str = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
921/// The namespace of the CII aggregate components (`ram:`).
922const CII_RAM: &str =
923    "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100";
924
925/// The element that holds the specification identifier (BT-24) of a document with this
926/// root element: its path from the root, by namespace and local name.
927fn identifier_path(namespace: &str, local: &str) -> &'static [(&'static str, &'static str)] {
928    match (namespace, local) {
929        (UBL_INVOICE, "Invoice") | (UBL_CREDIT_NOTE, "CreditNote") => {
930            &[(UBL_CBC, "CustomizationID")]
931        }
932        (CII, "CrossIndustryInvoice") => &[
933            (CII, "ExchangedDocumentContext"),
934            (CII_RAM, "GuidelineSpecifiedDocumentContextParameter"),
935            (CII_RAM, "ID"),
936        ],
937        _ => &[],
938    }
939}
940
941/// The root element of a document and its specification identifiers (BT-24), read with
942/// the events of the XML check: what picks the scenario of the rule set that applies.
943#[derive(Debug, Default)]
944struct Identification {
945    /// The namespace and local name of the root element.
946    root: Option<(String, String)>,
947    /// The path of the identifier element from the root (see [`identifier_path`]).
948    path: &'static [(&'static str, &'static str)],
949    /// How many steps of the path the open elements below the root match.
950    matched: usize,
951    /// The text of the identifier element being read.
952    text: Option<String>,
953    /// The string value of every identifier element, in document order.
954    identifiers: Vec<String>,
955}
956
957impl Identification {
958    /// A start tag, the element at `depth` (the root at 1).
959    fn start(&mut self, name: &einvoice_xml::Name<'_, '_>, depth: u32) {
960        let Ok(depth) = usize::try_from(depth) else {
961            return;
962        };
963        let namespace = name.namespace.unwrap_or("");
964        if depth == 1 {
965            self.path = identifier_path(namespace, name.local);
966            self.root = Some((namespace.to_owned(), name.local.to_owned()));
967            return;
968        }
969        // The parent matches the path up to its own step: this element may be the next.
970        if self.matched + 2 == depth
971            && self
972                .path
973                .get(self.matched)
974                .is_some_and(|&(ns, local)| ns == namespace && local == name.local)
975        {
976            self.matched += 1;
977            if self.matched == self.path.len() {
978                self.text = Some(String::new());
979            }
980        }
981    }
982
983    /// The end of the element at `depth`.
984    fn end(&mut self, depth: u32) {
985        let Ok(depth) = usize::try_from(depth) else {
986            return;
987        };
988        if depth >= 2 && self.matched + 1 == depth {
989            if self.matched == self.path.len()
990                && let Some(text) = self.text.take()
991            {
992                self.identifiers.push(text);
993            }
994            self.matched -= 1;
995        }
996    }
997
998    /// Text, within the identifier element or not.
999    fn text(&mut self, text: &str) {
1000        if let Some(value) = &mut self.text {
1001            value.push_str(text);
1002        }
1003    }
1004
1005    /// The first of `scenarios` (without `match` expressions) the document matches.
1006    fn scenario<'s>(&self, scenarios: &'s [Scenario]) -> Option<&'s Scenario> {
1007        let (namespace, local) = self.root.as_ref()?;
1008        scenarios.iter().find(|s| {
1009            s.namespace() == Some(namespace.as_str())
1010                && s.root() == Some(local.as_str())
1011                && self
1012                    .identifiers
1013                    .iter()
1014                    .any(|i| Some(i.as_str()) == s.identifier())
1015        })
1016    }
1017}
1018
1019/// What the XML check found.
1020#[derive(Debug)]
1021struct Checked {
1022    /// The schema errors, sorted by position.
1023    schema_errors: Vec<SchemaError>,
1024    /// The root element and the specification identifiers, when asked for.
1025    identification: Identification,
1026}
1027
1028/// Reads the text once, with the streaming reader of `einvoice-xml`: checks that it is
1029/// namespace-well-formed XML without a document type declaration, as the stylesheets'
1030/// parser requires, and without an element nested deeper than `max_depth`, and
1031/// validates it against `schema`, if any, in the same pass; with `identify`, reads the
1032/// root element and the specification identifiers (BT-24) too. The schema errors,
1033/// sorted by position.
1034///
1035/// A well-formedness error comes first, wherever it is in the text; then an element
1036/// nested too deep, the first in document order (the schema is not checked from it
1037/// on); then a construct of the schema stage outside its subset.
1038fn check(
1039    text: &str,
1040    max_depth: u32,
1041    schema: Option<&einvoice_xsd::Schema>,
1042    identify: bool,
1043) -> Result<Checked, Error> {
1044    let mut reader = einvoice_xml::Reader::new(text);
1045    let mut validation = schema.map(|schema| schema.validation(text));
1046    let mut identification = Identification::default();
1047    let mut depth = 0u32;
1048    let mut too_deep = None;
1049    loop {
1050        let event = match reader.next_event() {
1051            Ok(Some(event)) => event,
1052            Ok(None) => break,
1053            Err(einvoice_xml::Error::DtdDetected) => {
1054                return Err(Error::unsupported(
1055                    "a document type declaration (DTD): its entities and default attributes could change the document, so it is refused",
1056                ));
1057            }
1058            Err(e) => {
1059                return Err(Error::NotXml {
1060                    line: e.pos().row,
1061                    column: e.pos().col,
1062                    message: e.to_string(),
1063                });
1064            }
1065        };
1066        match &event {
1067            einvoice_xml::Event::Start(start) => {
1068                depth = depth.saturating_add(1);
1069                if identify {
1070                    identification.start(&start.name(), depth);
1071                }
1072                if depth > max_depth && too_deep.is_none() {
1073                    let at = einvoice_xml::TextPos::at(text, start.range().start);
1074                    too_deep = Some(LimitExceeded::Depth {
1075                        max: max_depth,
1076                        line: at.row,
1077                        column: at.col,
1078                    });
1079                    // The rest is only checked for well-formedness.
1080                    validation = None;
1081                }
1082            }
1083            einvoice_xml::Event::End(_) => {
1084                if identify {
1085                    identification.end(depth);
1086                }
1087                depth = depth.saturating_sub(1);
1088            }
1089            einvoice_xml::Event::Text(t) if identify => identification.text(&t.value),
1090            _ => {}
1091        }
1092        if let Some(validation) = &mut validation {
1093            validation.event(event);
1094        }
1095    }
1096    if let Some(limit) = too_deep {
1097        return Err(Error::Limit {
1098            limit,
1099            message: format!("document, {limit}"),
1100        });
1101    }
1102    let schema_errors = match validation {
1103        None => Vec::new(),
1104        Some(validation) => schema_errors(validation)?,
1105    };
1106    Ok(Checked {
1107        schema_errors,
1108        identification,
1109    })
1110}
1111
1112/// The schema errors of a validation that read the whole document.
1113fn schema_errors(validation: einvoice_xsd::Validation<'_, '_>) -> Result<Vec<SchemaError>, Error> {
1114    match validation.finish() {
1115        Ok(report) => Ok(report.errors),
1116        Err(einvoice_xsd::DocumentError::Malformed {
1117            line,
1118            column,
1119            message,
1120        }) => Err(Error::NotXml {
1121            line,
1122            column,
1123            message,
1124        }),
1125        Err(einvoice_xsd::DocumentError::Unsupported {
1126            line,
1127            column,
1128            message,
1129        }) => Err(Error::unsupported(format!(
1130            "document, line {line}, column {column}: {message}"
1131        ))),
1132    }
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137    use super::*;
1138
1139    /// The schema errors of the XML check, without the identification.
1140    fn check(
1141        text: &str,
1142        max_depth: u32,
1143        schema: Option<&einvoice_xsd::Schema>,
1144    ) -> Result<Vec<SchemaError>, Error> {
1145        super::check(text, max_depth, schema, false).map(|c| c.schema_errors)
1146    }
1147
1148    /// The root element and the specification identifiers the XML check reads.
1149    fn identify(text: &str) -> (Option<(String, String)>, Vec<String>) {
1150        let checked = super::check(text, DEFAULT_MAX_DEPTH, None, true).unwrap();
1151        (
1152            checked.identification.root,
1153            checked.identification.identifiers,
1154        )
1155    }
1156
1157    #[test]
1158    fn specification_identifiers() {
1159        let root = |ns: &str, local: &str| Some((ns.to_owned(), local.to_owned()));
1160        let ubl = format!(
1161            "<Invoice xmlns='{UBL_INVOICE}' xmlns:cbc='{UBL_CBC}'><cbc:CustomizationID> urn:a</cbc:CustomizationID>\
1162             <x><cbc:CustomizationID>no</cbc:CustomizationID></x>\
1163             <cbc:CustomizationID>u<!-- c -->rn:<![CDATA[b]]><i>c</i></cbc:CustomizationID><CustomizationID>no</CustomizationID></Invoice>"
1164        );
1165        assert_eq!(
1166            identify(&ubl),
1167            (
1168                root(UBL_INVOICE, "Invoice"),
1169                vec![" urn:a".to_owned(), "urn:bc".to_owned()]
1170            )
1171        );
1172        let credit_note = format!(
1173            "<c:CreditNote xmlns:c='{UBL_CREDIT_NOTE}'><b:CustomizationID xmlns:b='{UBL_CBC}'>urn:x</b:CustomizationID></c:CreditNote>"
1174        );
1175        assert_eq!(
1176            identify(&credit_note),
1177            (
1178                root(UBL_CREDIT_NOTE, "CreditNote"),
1179                vec!["urn:x".to_owned()]
1180            )
1181        );
1182        let cii = format!(
1183            "<rsm:CrossIndustryInvoice xmlns:rsm='{CII}' xmlns:ram='{CII_RAM}'>\
1184             <rsm:ExchangedDocumentContext><ram:ID>no</ram:ID>\
1185             <ram:GuidelineSpecifiedDocumentContextParameter><ram:ID>urn:y</ram:ID><ram:Other>no</ram:Other></ram:GuidelineSpecifiedDocumentContextParameter>\
1186             <ram:GuidelineSpecifiedDocumentContextParameter><ram:ID>urn:z</ram:ID></ram:GuidelineSpecifiedDocumentContextParameter>\
1187             </rsm:ExchangedDocumentContext><ram:ID>no</ram:ID></rsm:CrossIndustryInvoice>"
1188        );
1189        assert_eq!(
1190            identify(&cii),
1191            (
1192                root(CII, "CrossIndustryInvoice"),
1193                vec!["urn:y".to_owned(), "urn:z".to_owned()]
1194            )
1195        );
1196        // Another root element: no identifier is read.
1197        assert_eq!(
1198            identify(&format!(
1199                "<Order xmlns='{UBL_INVOICE}'><CustomizationID xmlns='{UBL_CBC}'>x</CustomizationID></Order>"
1200            )),
1201            (root(UBL_INVOICE, "Order"), vec![])
1202        );
1203        assert_eq!(identify("<a/>"), (root("", "a"), vec![]));
1204    }
1205
1206    /// The caps of WebAssembly, checked on every target.
1207    #[test]
1208    fn options_within_the_caps_of_webassembly() {
1209        let caps = Some((WASM_MAX_DEPTH, WASM_MAX_STACK));
1210        let within = ValidateOptions::new()
1211            .max_depth(WASM_MAX_DEPTH)
1212            .max_stack(WASM_MAX_STACK);
1213        assert!(within.check(caps).is_ok());
1214        assert!(
1215            ValidateOptions::new()
1216                .max_stack(WASM_MAX_STACK)
1217                .check(caps)
1218                .is_ok()
1219        );
1220        let error = within
1221            .max_depth(WASM_MAX_DEPTH + 1)
1222            .check(caps)
1223            .unwrap_err();
1224        assert!(matches!(
1225            error,
1226            Error::OptionOutOfRange {
1227                option: "max_depth",
1228                value: 401,
1229                max: 400
1230            }
1231        ));
1232        assert_eq!(error.kind(), crate::ErrorKind::Unsupported);
1233        assert_eq!(
1234            error.to_string(),
1235            "option max_depth is 401, more than 400, the most this target allows"
1236        );
1237        let error = within
1238            .max_stack(WASM_MAX_STACK + 1)
1239            .check(caps)
1240            .unwrap_err();
1241        assert!(matches!(
1242            error,
1243            Error::OptionOutOfRange {
1244                option: "max_stack",
1245                value: 262_145,
1246                max: 262_144
1247            }
1248        ));
1249        // Without caps (the other targets), anything goes.
1250        let anything = ValidateOptions::new()
1251            .max_depth(u32::MAX)
1252            .max_stack(u32::MAX);
1253        assert!(anything.check(None).is_ok());
1254        assert_eq!(CAPS, None);
1255    }
1256
1257    #[test]
1258    fn decoding_a_buffer_gives_the_same_result() {
1259        for bytes in [
1260            &b"<a/>"[..],
1261            b"\xEF\xBB\xBF<a>\xC3\xA9</a>",
1262            b"<?xml version='1.0' encoding='UTF-8'?><a/>",
1263            b"\xFF\xFE<\0a\0/\0>\0",
1264            b"\xFE\xFF\0<\0a\0/\0>",
1265            b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>",
1266            b"<a>\n  \xC3\xA9\xFF</a>",
1267            b"\xEF\xBB\xBF<a>\n\xFF</a>",
1268            b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>",
1269            b"<?xml version='1.0' encoding='Shift_JIS'?><a/>",
1270            b"\xEF\xBB\xBF\xEF\xBB\xBF<a/>",
1271            b"\xEF\xBB\xBF",
1272            b"",
1273        ] {
1274            let borrowed = decode(bytes)
1275                .map(Cow::into_owned)
1276                .map_err(|e| e.to_string());
1277            let owned = decode_owned(bytes.to_vec()).map_err(|e| e.to_string());
1278            assert_eq!(owned, borrowed, "{bytes:?}");
1279        }
1280    }
1281
1282    #[test]
1283    fn decoding() {
1284        assert_eq!(decode(b"\xEF\xBB\xBF<a/>").unwrap(), "<a/>");
1285        assert_eq!(
1286            decode(b"<?xml version='1.0' encoding='UTF-8'?><a/>").unwrap(),
1287            "<?xml version='1.0' encoding='UTF-8'?><a/>"
1288        );
1289        assert!(matches!(decode(b"<a/>").unwrap(), Cow::Borrowed("<a/>")));
1290        assert_eq!(decode(b"\xFF\xFE<\0a\0/\0>\0").unwrap(), "<a/>");
1291        assert_eq!(
1292            decode(b"<?xml version='1.0' encoding='ISO-8859-1'?><a>\xE9</a>").unwrap(),
1293            "<?xml version='1.0' encoding='ISO-8859-1'?><a>\u{e9}</a>"
1294        );
1295        match decode(b"<?xml version='1.0' encoding='Shift_JIS'?><a/>") {
1296            Err(Error::Unsupported { message }) => assert_eq!(
1297                message,
1298                "the Shift_JIS encoding: the encodings read are UTF-8, UTF-16, US-ASCII, ISO-8859-1, ISO-8859-15 and windows-1252"
1299            ),
1300            other => panic!("{other:?}"),
1301        }
1302        match decode(b"<?xml version='1.0' encoding='UTF-16'?><a/>") {
1303            Err(Error::NotXml {
1304                line: 1,
1305                column: 1,
1306                message,
1307            }) => assert_eq!(
1308                message,
1309                "UTF-8 (no byte order mark), but the XML declaration names the encoding 'UTF-16'"
1310            ),
1311            other => panic!("{other:?}"),
1312        }
1313        match decode(b"<a>\n  \xC3\xA9\xFF</a>") {
1314            Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
1315            other => panic!("{other:?}"),
1316        }
1317        match decode(b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>") {
1318            Err(Error::NotXml {
1319                line,
1320                column,
1321                message,
1322            }) => {
1323                assert_eq!((line, column), (2, 4));
1324                assert_eq!(message, "bytes that are not US-ASCII at 2:4");
1325            }
1326            other => panic!("{other:?}"),
1327        }
1328        // Not an XML declaration: UTF-8.
1329        assert!(decode(b"<?xml-stylesheet encoding='x'?><a/>").is_ok());
1330    }
1331
1332    #[test]
1333    fn well_formedness() {
1334        assert!(check("<a/>", 1, None).is_ok());
1335        match check("<a>\n<b></a>", DEFAULT_MAX_DEPTH, None) {
1336            Err(Error::NotXml {
1337                line,
1338                column,
1339                message,
1340            }) => assert_eq!(
1341                (line, column, message.as_str()),
1342                (2, 4, "expected 'b' tag, not 'a' at 2:4")
1343            ),
1344            other => panic!("{other:?}"),
1345        }
1346        assert!(matches!(
1347            check(
1348                "<!DOCTYPE a [<!ENTITY e 'x'>]><a>&e;</a>",
1349                DEFAULT_MAX_DEPTH,
1350                None
1351            ),
1352            Err(Error::Unsupported { .. })
1353        ));
1354        assert!(matches!(
1355            check("<p:a/>", DEFAULT_MAX_DEPTH, None),
1356            Err(Error::NotXml { .. })
1357        ));
1358    }
1359
1360    #[test]
1361    fn one_pass_order_of_errors() {
1362        let schema = einvoice_xsd::Schema::ubl_2_1().unwrap();
1363        let invoice = "<Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' \
1364                       xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>";
1365        let depth = |text: &str, max| match check(text, max, Some(&schema)) {
1366            Err(Error::Limit {
1367                limit: LimitExceeded::Depth { line, column, .. },
1368                ..
1369            }) => Some((line, column)),
1370            _ => None,
1371        };
1372        // Schema errors, in one pass with the well-formedness check.
1373        let errors = check(&format!("{invoice}</Invoice>"), 3, Some(&schema)).unwrap();
1374        assert_eq!(errors.len(), 1);
1375        assert_eq!(errors[0].kind.as_str(), "missing-element");
1376        // An element too deep: a limit, from the first one; the schema is not checked.
1377        let deep = format!("{invoice}\n<a><b><c/></b></a><d><e><f/></e></d></Invoice>");
1378        assert_eq!(depth(&deep, 2), Some((2, 4)));
1379        assert_eq!(depth(&deep, 3), Some((2, 7)));
1380        assert_eq!(depth(&deep, 4), None);
1381        // A well-formedness error comes first, even after an element too deep.
1382        let malformed = format!("{deep}<");
1383        assert!(matches!(
1384            check(&malformed, 2, Some(&schema)),
1385            Err(Error::NotXml { .. })
1386        ));
1387        assert!(matches!(
1388            check(&malformed, 2, None),
1389            Err(Error::NotXml { .. })
1390        ));
1391        // A schema error comes after the depth limit, and after any well-formedness
1392        // error: an xsi:type naming a built-in type not derived from the declared one.
1393        let retyped = invoice.replace(
1394            "<Invoice ",
1395            "<Invoice xsi:type='xs:IDREF' xmlns:xs='http://www.w3.org/2001/XMLSchema' ",
1396        );
1397        let errors = check(&format!("{retyped}</Invoice>"), 3, Some(&schema)).unwrap();
1398        assert!(
1399            errors
1400                .iter()
1401                .any(|e| e.kind == einvoice_xsd::ErrorKind::InvalidXsiType),
1402            "{errors:?}"
1403        );
1404        assert!(matches!(
1405            check(&format!("{retyped}<b><c/></b></Invoice>"), 2, Some(&schema)),
1406            Err(Error::Limit { .. })
1407        ));
1408        assert!(matches!(
1409            check(&format!("{retyped}</Invoice><"), 3, Some(&schema)),
1410            Err(Error::NotXml { .. })
1411        ));
1412        // A document type declaration is refused, also with a schema.
1413        assert!(matches!(
1414            check("<!DOCTYPE Invoice><Invoice/>", 3, Some(&schema)),
1415            Err(Error::Unsupported { .. })
1416        ));
1417    }
1418
1419    #[test]
1420    fn checksums() {
1421        assert_eq!(
1422            sha256_hex(b"abc"),
1423            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1424        );
1425    }
1426
1427    #[test]
1428    fn errors_are_summarised() {
1429        let many: Vec<String> = (1..=12).map(|i| format!("line {i}: x")).collect();
1430        let text = first_lines(&many.join("\n"));
1431        assert!(text.ends_with("line 10: x; and 2 more"), "{text}");
1432    }
1433}