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