Skip to main content

einvoice_validator/
manifest.rs

1//! The manifest of a rule-set bundle (`bundle.toml`): what the rule set is, which XML
2//! schema and which stylesheets it runs, the resources the stylesheets read with
3//! `document()`, the SHA-256 of each file, and how the findings of the stylesheets are
4//! read: the severity of an unflagged failed assert, and the scenarios, which give rule
5//! ids severities and may select the stylesheets that run on a document.
6
7use std::fmt;
8
9use crate::{Error, Severity};
10
11/// The file name of the manifest in a bundle directory.
12pub const MANIFEST_FILE: &str = "bundle.toml";
13
14/// The newest manifest format this crate reads (the `format` key): format 2 adds to
15/// format 1, which is read too, the `[[resource]]` and `[[scenario]]` tables, the
16/// `unflagged-assert` key of `[[stylesheet]]` and the `unchecked-schema` key.
17pub const MANIFEST_FORMAT: u32 = 2;
18
19/// The XML schema a rule set validates documents against before running its
20/// stylesheets.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22#[non_exhaustive]
23pub enum SchemaId {
24    /// The OASIS UBL 2.1 schemas for Invoice and `CreditNote`, embedded in
25    /// [`einvoice_xsd`].
26    Ubl21,
27    /// The UN/CEFACT Cross Industry Invoice D16B schemas (uncoupled code lists),
28    /// embedded in [`einvoice_xsd`].
29    CiiD16b,
30}
31
32impl SchemaId {
33    /// The name used in manifests: `ubl-2.1` or `cii-d16b`.
34    #[must_use]
35    pub const fn as_str(self) -> &'static str {
36        match self {
37            Self::Ubl21 => "ubl-2.1",
38            Self::CiiD16b => "cii-d16b",
39        }
40    }
41
42    /// The schema named `name` in a manifest.
43    #[must_use]
44    pub fn from_name(name: &str) -> Option<Self> {
45        match name {
46            "ubl-2.1" => Some(Self::Ubl21),
47            "cii-d16b" => Some(Self::CiiD16b),
48            _ => None,
49        }
50    }
51}
52
53impl fmt::Display for SchemaId {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.write_str(self.as_str())
56    }
57}
58
59/// One stylesheet of a rule set, as its manifest describes it.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct StylesheetEntry {
62    name: String,
63    version: String,
64    path: String,
65    sha256: String,
66    unflagged_assert: Severity,
67}
68
69impl StylesheetEntry {
70    /// Its name, unique within the rule set (`EN16931-UBL`, ...).
71    #[must_use]
72    pub fn name(&self) -> &str {
73        &self.name
74    }
75
76    /// The version of the rule set it implements: the manifest's `version` of the
77    /// stylesheet, else the version of the bundle.
78    #[must_use]
79    pub fn version(&self) -> &str {
80        &self.version
81    }
82
83    /// Its path in the bundle: relative, `/`-separated.
84    #[must_use]
85    pub fn path(&self) -> &str {
86        &self.path
87    }
88
89    /// The SHA-256 of the file, lower-case hexadecimal.
90    #[must_use]
91    pub fn sha256(&self) -> &str {
92        &self.sha256
93    }
94
95    /// The severity of its failed asserts that have no flag (format 2,
96    /// `unflagged-assert`): [`Severity::Other`] unless the manifest says otherwise. The
97    /// rule sets whose reference validators reject a document for an unflagged failed
98    /// assert (Factur-X, XRechnung) say [`Severity::Fatal`].
99    #[must_use]
100    pub const fn unflagged_assert(&self) -> Severity {
101        self.unflagged_assert
102    }
103}
104
105/// A scenario of the rule set (format 2, `[[scenario]]`): which documents it matches, the
106/// severities it gives rule ids, whatever their flags, in them (the `customLevel`
107/// elements of a scenario of a KoSIT validator configuration), and, for a scenario with
108/// a `match` expression, the stylesheets that run on them.
109///
110/// A scenario matches documents in one of two ways, the same for every scenario of a
111/// manifest:
112///
113/// - With a `match` expression ([`Scenario::match_expression`]), the XPath expression of a
114///   KoSIT scenario, evaluated as the KoSIT validator evaluates it: its effective boolean
115///   value, the document node as the context item, the prefixes of
116///   [`Scenario::namespaces`] bound. The rule set then selects by scenario
117///   ([`RuleSet::selects_by_scenario`]): a document must match exactly one scenario, whose
118///   stylesheets run on it ([`Scenario::stylesheets`]); a document that matches none, or
119///   more than one, is invalid and no stylesheet runs on it, as the KoSIT validator
120///   rejects it with its fallback scenario.
121/// - With a root element and a specification identifier ([`Scenario::namespace`],
122///   [`Scenario::root`], [`Scenario::identifier`]): a document matches when its root
123///   element has the scenario's namespace and local name, and its specification
124///   identifier (BT-24) is the scenario's: the string value of a `cbc:CustomizationID`
125///   child of the root of a UBL document, or of
126///   `rsm:ExchangedDocumentContext/ram:GuidelineSpecifiedDocumentContextParameter/ram:ID`
127///   in a CII document, compared as it is written. The first scenario of the manifest
128///   that matches gives its severities; every stylesheet runs, whether one matches or
129///   not.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct Scenario {
132    name: String,
133    selector: Selector,
134    stylesheets: Option<Vec<String>>,
135    levels: Vec<(String, Severity)>,
136}
137
138/// How a scenario matches documents.
139#[derive(Debug, Clone, PartialEq, Eq)]
140enum Selector {
141    /// By the root element and the specification identifier.
142    Identifier {
143        namespace: String,
144        root: String,
145        identifier: String,
146    },
147    /// By an XPath expression, with its namespace bindings.
148    Match {
149        namespaces: Vec<(String, String)>,
150        expression: String,
151    },
152}
153
154impl Scenario {
155    /// Its name (`EN16931 XRechnung (UBL Invoice)`).
156    #[must_use]
157    pub fn name(&self) -> &str {
158        &self.name
159    }
160
161    /// The `match` expression, for a scenario that has one: XPath, evaluated on the
162    /// document node.
163    #[must_use]
164    pub fn match_expression(&self) -> Option<&str> {
165        match &self.selector {
166            Selector::Match { expression, .. } => Some(expression),
167            Selector::Identifier { .. } => None,
168        }
169    }
170
171    /// The namespace prefixes the `match` expression may use, with their URIs, in the
172    /// order of the manifest; empty for a scenario without a `match` expression.
173    #[must_use]
174    pub fn namespaces(&self) -> &[(String, String)] {
175        match &self.selector {
176            Selector::Match { namespaces, .. } => namespaces,
177            Selector::Identifier { .. } => &[],
178        }
179    }
180
181    /// The names of the stylesheets that run on the documents it matches, in the order
182    /// they run, for a scenario with a `match` expression that names them; `None` when
183    /// every stylesheet of the rule set runs, in its order.
184    #[must_use]
185    pub fn stylesheets(&self) -> Option<&[String]> {
186        self.stylesheets.as_deref()
187    }
188
189    /// The namespace of the root element of the documents it matches, for a scenario
190    /// without a `match` expression.
191    #[must_use]
192    pub fn namespace(&self) -> Option<&str> {
193        match &self.selector {
194            Selector::Identifier { namespace, .. } => Some(namespace),
195            Selector::Match { .. } => None,
196        }
197    }
198
199    /// The local name of the root element of the documents it matches (`Invoice`), for a
200    /// scenario without a `match` expression.
201    #[must_use]
202    pub fn root(&self) -> Option<&str> {
203        match &self.selector {
204            Selector::Identifier { root, .. } => Some(root),
205            Selector::Match { .. } => None,
206        }
207    }
208
209    /// The specification identifier (BT-24) of the documents it matches, for a scenario
210    /// without a `match` expression.
211    #[must_use]
212    pub fn identifier(&self) -> Option<&str> {
213        match &self.selector {
214            Selector::Identifier { identifier, .. } => Some(identifier),
215            Selector::Match { .. } => None,
216        }
217    }
218
219    /// The rule ids it gives a severity, with that severity, in the order of the
220    /// manifest (the ids of `fatal`, then `warning`, then `other`).
221    #[must_use]
222    pub fn levels(&self) -> &[(String, Severity)] {
223        &self.levels
224    }
225
226    /// The severity it gives the rule `id`, if any.
227    #[must_use]
228    pub fn level(&self, id: &str) -> Option<Severity> {
229        self.levels
230            .iter()
231            .find(|(rule, _)| rule == id)
232            .map(|(_, severity)| *severity)
233    }
234}
235
236/// The namespace of a UBL 2 invoice.
237pub(crate) const UBL_INVOICE: &str = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
238/// The namespace of a UBL 2 credit note.
239pub(crate) const UBL_CREDIT_NOTE: &str =
240    "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
241/// The namespace of a UN/CEFACT Cross Industry Invoice (D16B and the other releases of
242/// version 100).
243pub(crate) const CII: &str = "urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100";
244
245/// The root elements whose specification identifier (BT-24) is known, which a scenario
246/// may name: namespace, local name.
247const IDENTIFIED_ROOTS: [(&str, &str); 3] = [
248    (UBL_INVOICE, "Invoice"),
249    (UBL_CREDIT_NOTE, "CreditNote"),
250    (CII, "CrossIndustryInvoice"),
251];
252
253/// A file of the bundle that the stylesheets read with `document()` (a code list, ...),
254/// as the manifest describes it (format 2, `[[resource]]`).
255#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct ResourceEntry {
257    path: String,
258    sha256: String,
259}
260
261impl ResourceEntry {
262    /// Its path in the bundle: relative, `/`-separated. A stylesheet asks for it with
263    /// `document()` by its URI, relative to the stylesheet's own.
264    #[must_use]
265    pub fn path(&self) -> &str {
266        &self.path
267    }
268
269    /// The SHA-256 of the file, lower-case hexadecimal.
270    #[must_use]
271    pub fn sha256(&self) -> &str {
272        &self.sha256
273    }
274}
275
276/// A rule set, as described by the manifest of its bundle: its name and version, the
277/// XML schema to validate against first, the stylesheets to run, in order, and the
278/// resources they read, with their checksums.
279#[derive(Debug, Clone, PartialEq, Eq)]
280pub struct RuleSet {
281    name: String,
282    title: String,
283    version: String,
284    schema: Option<SchemaId>,
285    unchecked_schema: Option<String>,
286    stylesheets: Vec<StylesheetEntry>,
287    resources: Vec<ResourceEntry>,
288    scenarios: Vec<Scenario>,
289}
290
291impl RuleSet {
292    /// Parses a bundle manifest (see the crate documentation for the format).
293    ///
294    /// # Errors
295    ///
296    /// [`Error::Bundle`] naming the line: a syntax outside the accepted TOML subset, an
297    /// unknown or repeated key, a missing key, a value that is not valid for its key, an
298    /// unknown schema, a format other than 1 and [`MANIFEST_FORMAT`], a `[[resource]]`,
299    /// a `[[scenario]]`, an `unflagged-assert` or an `unchecked-schema` in format 1, a
300    /// path given twice, a scenario named twice, with a `match` expression that is not
301    /// XPath or uses a prefix it does not bind, naming a stylesheet the rule set does not
302    /// have (or one twice), with a `match` expression in some scenarios and not in others;
303    /// a scenario without one for a root element other than a UBL `Invoice` or
304    /// `CreditNote` or a CII `CrossIndustryInvoice`, or without a rule id; a scenario
305    /// giving a rule id two severities. [`Error::Unsupported`] for a `match` expression
306    /// outside the XPath subset of the engine.
307    pub fn parse(manifest: &str) -> Result<Self, Error> {
308        let tables = parse_tables(manifest)?;
309        let mut tables = tables.into_iter();
310        let Some(top) = tables.next() else {
311            return Err(Error::bundle(format!("{MANIFEST_FILE}: empty")));
312        };
313        let mut top = Table::new(top);
314        let format_line = top.line_of("format");
315        top.allow(&[
316            "format",
317            "name",
318            "title",
319            "version",
320            "schema",
321            "unchecked-schema",
322        ])?;
323        let format = match top.take("format") {
324            Some(Value::Integer(f)) if (1..=u64::from(MANIFEST_FORMAT)).contains(&f) => f,
325            Some(Value::Integer(f)) => {
326                return Err(Error::bundle(format!(
327                    "{MANIFEST_FILE}:{format_line}: format {f}: only formats 1 and {MANIFEST_FORMAT} are supported"
328                )));
329            }
330            Some(Value::String(_)) => {
331                return Err(Error::bundle(format!(
332                    "{MANIFEST_FILE}:{format_line}: `format` must be an integer"
333                )));
334            }
335            None => {
336                return Err(Error::bundle(format!(
337                    "{MANIFEST_FILE}: the `format` key is missing (format = {MANIFEST_FORMAT})"
338                )));
339            }
340        };
341        let name = top.required_string("name")?;
342        check_name(&name).map_err(|m| top.error("name", &m))?;
343        let title = top.required_string("title")?;
344        if title.trim().is_empty() || title.chars().any(char::is_control) {
345            return Err(top.error("title", "must be non-empty text on one line"));
346        }
347        let version = top.required_string("version")?;
348        check_version(&version).map_err(|m| top.error("version", &m))?;
349        let schema = match top.optional_string("schema")? {
350            None => None,
351            Some(s) => Some(SchemaId::from_name(&s).ok_or_else(|| {
352                top.error(
353                    "schema",
354                    &format!("unknown schema {s:?} (known: ubl-2.1, cii-d16b)"),
355                )
356            })?),
357        };
358        let unchecked_schema = match top.optional_string("unchecked-schema")? {
359            None => None,
360            Some(_) if format < 2 => {
361                return Err(top.error("unchecked-schema", "needs format = 2"));
362            }
363            Some(s) if s.trim().is_empty() || s.chars().any(char::is_control) => {
364                return Err(top.error("unchecked-schema", "must be non-empty text on one line"));
365            }
366            Some(s) => Some(s),
367        };
368        top.finish()?;
369
370        let mut stylesheets: Vec<StylesheetEntry> = Vec::new();
371        let mut resources: Vec<ResourceEntry> = Vec::new();
372        let mut scenarios: Vec<Scenario> = Vec::new();
373        // The line of each scenario's header.
374        let mut scenario_lines: Vec<u32> = Vec::new();
375        for raw in tables {
376            let kind = raw.kind;
377            let table = Table::new(raw);
378            if kind == TableKind::Resource {
379                let resource = resource(table, format, &stylesheets, &resources)?;
380                resources.push(resource);
381                continue;
382            }
383            if kind == TableKind::Scenario {
384                scenario_lines.push(table.header_line);
385                let scenario = scenario(table, format, &scenarios)?;
386                scenarios.push(scenario);
387                continue;
388            }
389            let entry = stylesheet(table, format, &version, &stylesheets, &resources)?;
390            stylesheets.push(entry);
391        }
392        if stylesheets.is_empty() {
393            return Err(Error::bundle(format!(
394                "{MANIFEST_FILE}: no [[stylesheet]]: a rule set runs at least one"
395            )));
396        }
397        check_scenarios(&scenarios, &scenario_lines, &stylesheets)?;
398        Ok(Self {
399            name,
400            title,
401            version,
402            schema,
403            unchecked_schema,
404            stylesheets,
405            resources,
406            scenarios,
407        })
408    }
409
410    /// The manifest of the built-in rule set `name` (see
411    /// [`BUILTIN_RULE_SETS`](crate::BUILTIN_RULE_SETS)), without loading it.
412    ///
413    /// # Errors
414    ///
415    /// [`Error::Bundle`] for an unknown name.
416    pub fn builtin(name: &str) -> Result<Self, Error> {
417        Self::parse(crate::builtin::get(name)?.0)
418    }
419
420    /// Its short name (`cen-ubl`): ASCII letters, digits, `-`, `.` and `_`.
421    #[must_use]
422    pub fn name(&self) -> &str {
423        &self.name
424    }
425
426    /// Its title (`CEN EN 16931 UBL`).
427    #[must_use]
428    pub fn title(&self) -> &str {
429        &self.title
430    }
431
432    /// The version of the official artefacts (`1.3.17`).
433    #[must_use]
434    pub fn version(&self) -> &str {
435        &self.version
436    }
437
438    /// The XML schema documents are validated against first, if any.
439    #[must_use]
440    pub const fn schema(&self) -> Option<SchemaId> {
441        self.schema
442    }
443
444    /// The XML schema that the reference validator of the rule set also validates
445    /// documents against and that this rule set does not (format 2, `unchecked-schema`),
446    /// as the manifest names it: a gap in its verdicts, which reports state.
447    #[must_use]
448    pub fn unchecked_schema(&self) -> Option<&str> {
449        self.unchecked_schema.as_deref()
450    }
451
452    /// The stylesheets, in the order of the manifest: the order they run in, unless the
453    /// scenario a document matches orders them ([`Scenario::stylesheets`]).
454    #[must_use]
455    pub fn stylesheets(&self) -> &[StylesheetEntry] {
456        &self.stylesheets
457    }
458
459    /// The resources the stylesheets read with `document()` (format 2), in the order of
460    /// the manifest.
461    #[must_use]
462    pub fn resources(&self) -> &[ResourceEntry] {
463        &self.resources
464    }
465
466    /// The scenarios (format 2), in the order of the manifest, which is the order they
467    /// are tried in.
468    #[must_use]
469    pub fn scenarios(&self) -> &[Scenario] {
470        &self.scenarios
471    }
472
473    /// Whether the rule set selects by scenario: its scenarios have `match` expressions,
474    /// so that a document must match exactly one of them, which gives the stylesheets
475    /// that run on it and the severities of its rule ids; a document that matches none,
476    /// or more than one, is invalid, and no stylesheet runs on it (see [`Scenario`]).
477    #[must_use]
478    pub fn selects_by_scenario(&self) -> bool {
479        self.scenarios
480            .first()
481            .is_some_and(|s| s.match_expression().is_some())
482    }
483}
484
485/// A `[[stylesheet]]` table, whose name no stylesheet has yet and whose path no file of
486/// the bundle has yet; `version` is the bundle's.
487fn stylesheet(
488    mut table: Table,
489    format: u64,
490    version: &str,
491    stylesheets: &[StylesheetEntry],
492    resources: &[ResourceEntry],
493) -> Result<StylesheetEntry, Error> {
494    table.allow(&["name", "version", "path", "sha256", "unflagged-assert"])?;
495    let name = table.required_string("name")?;
496    check_name(&name).map_err(|m| table.error("name", &m))?;
497    if stylesheets.iter().any(|s| s.name == name) {
498        return Err(table.error("name", &format!("stylesheet {name:?} twice")));
499    }
500    let version = match table.optional_string("version")? {
501        Some(v) => {
502            check_version(&v).map_err(|m| table.error("version", &m))?;
503            v
504        }
505        None => version.to_owned(),
506    };
507    let path = table.required_string("path")?;
508    check_path(&path).map_err(|m| table.error("path", &m))?;
509    if resources.iter().any(|r| r.path == path) {
510        return Err(table.error("path", &format!("{path:?} twice in the bundle")));
511    }
512    let sha256 = table.sha256()?;
513    let unflagged_assert = match table.optional_string("unflagged-assert")? {
514        None => Severity::Other,
515        Some(_) if format < 2 => {
516            return Err(table.error("unflagged-assert", "needs format = 2"));
517        }
518        Some(s) => severity(&s).map_err(|m| table.error("unflagged-assert", &m))?,
519    };
520    table.finish()?;
521    Ok(StylesheetEntry {
522        name,
523        version,
524        path,
525        sha256,
526        unflagged_assert,
527    })
528}
529
530/// A severity named in a manifest: `fatal`, `warning` or `other`.
531fn severity(name: &str) -> Result<Severity, String> {
532    match name {
533        "fatal" => Ok(Severity::Fatal),
534        "warning" => Ok(Severity::Warning),
535        "other" => Ok(Severity::Other),
536        _ => Err(format!("{name:?}: expected fatal, warning or other")),
537    }
538}
539
540/// A `[[scenario]]` table (format 2).
541fn scenario(mut table: Table, format: u64, scenarios: &[Scenario]) -> Result<Scenario, Error> {
542    if format < 2 {
543        return Err(Error::bundle(format!(
544            "{MANIFEST_FILE}:{}: [[scenario]] needs format = 2",
545            table.header_line
546        )));
547    }
548    table.allow(&[
549        "name",
550        "namespaces",
551        "match",
552        "stylesheets",
553        "namespace",
554        "root",
555        "identifier",
556        "fatal",
557        "warning",
558        "other",
559    ])?;
560    let name = table.required_string("name")?;
561    if name.trim().is_empty() || name.chars().any(char::is_control) {
562        return Err(table.error("name", "must be non-empty text on one line"));
563    }
564    if scenarios.iter().any(|s| s.name == name) {
565        return Err(table.error("name", &format!("scenario {name:?} twice")));
566    }
567    let selector = selector(&mut table)?;
568    let stylesheets = match table.optional_string("stylesheets")? {
569        None => None,
570        Some(names) => {
571            let names: Vec<String> = names
572                .split([' ', '\t'])
573                .filter(|n| !n.is_empty())
574                .map(str::to_owned)
575                .collect();
576            if names.is_empty() {
577                return Err(table.error(
578                    "stylesheets",
579                    "no stylesheet name (names separated by spaces)",
580                ));
581            }
582            Some(names)
583        }
584    };
585    let mut levels: Vec<(String, Severity)> = Vec::new();
586    for key in ["fatal", "warning", "other"] {
587        let Some(ids) = table.optional_string(key)? else {
588            continue;
589        };
590        let level = severity(key).map_err(|m| table.error(key, &m))?;
591        let before = levels.len();
592        for id in ids.split([' ', '\t']).filter(|id| !id.is_empty()) {
593            if levels.iter().any(|(rule, _)| rule == id) {
594                return Err(table.error(key, &format!("rule id {id:?} given twice")));
595            }
596            levels.push((id.to_owned(), level));
597        }
598        if levels.len() == before {
599            return Err(table.error(key, "no rule id (rule ids separated by spaces)"));
600        }
601    }
602    // Without a `match` expression, a scenario only gives severities: it must give some.
603    if levels.is_empty() && matches!(selector, Selector::Identifier { .. }) {
604        return Err(Error::bundle(format!(
605            "{}: no rule id (the keys fatal, warning and other)",
606            table.where_()
607        )));
608    }
609    table.finish()?;
610    Ok(Scenario {
611        name,
612        selector,
613        stylesheets,
614        levels,
615    })
616}
617
618/// How a `[[scenario]]` table says which documents the scenario matches: a `match`
619/// expression with its `namespaces`, or a root element and an identifier.
620fn selector(table: &mut Table) -> Result<Selector, Error> {
621    if let Some(expression) = table.optional_string("match")? {
622        for key in ["namespace", "root", "identifier"] {
623            if table.optional_string(key)?.is_some() {
624                return Err(table.error(key, "not with `match`, which says what matches"));
625            }
626        }
627        let namespaces = match table.optional_string("namespaces")? {
628            None => Vec::new(),
629            Some(text) => namespaces(&text).map_err(|m| table.error("namespaces", &m))?,
630        };
631        check_match(&expression, &namespaces).map_err(|(unsupported, m)| {
632            let error = table.error("match", &m);
633            if unsupported {
634                Error::unsupported(error.to_string())
635            } else {
636                error
637            }
638        })?;
639        return Ok(Selector::Match {
640            namespaces,
641            expression,
642        });
643    }
644    for key in ["namespaces", "stylesheets"] {
645        if table.optional_string(key)?.is_some() {
646            return Err(table.error(key, "only with `match`"));
647        }
648    }
649    let namespace = table.required_string("namespace")?;
650    let root = table.required_string("root")?;
651    if !IDENTIFIED_ROOTS.contains(&(namespace.as_str(), root.as_str())) {
652        return Err(table.error(
653            "root",
654            &format!(
655                "{{{namespace}}}{root}: a scenario matches a UBL Invoice or CreditNote, or a CII CrossIndustryInvoice"
656            ),
657        ));
658    }
659    let identifier = table.required_string("identifier")?;
660    if identifier.is_empty() || identifier.chars().any(char::is_control) {
661        return Err(table.error("identifier", "must be non-empty text on one line"));
662    }
663    Ok(Selector::Identifier {
664        namespace,
665        root,
666        identifier,
667    })
668}
669
670/// The `namespaces` of a scenario: `prefix=uri` pairs separated by spaces, each prefix
671/// an `NCName` given once.
672fn namespaces(text: &str) -> Result<Vec<(String, String)>, String> {
673    let mut out: Vec<(String, String)> = Vec::new();
674    for pair in text.split([' ', '\t']).filter(|p| !p.is_empty()) {
675        let Some((prefix, uri)) = pair.split_once('=') else {
676            return Err(format!("{pair:?}: expected prefix=uri"));
677        };
678        if !einvoice_xpath::is_ncname(prefix) || uri.is_empty() {
679            return Err(format!(
680                "{pair:?}: expected prefix=uri, the prefix an NCName"
681            ));
682        }
683        if out.iter().any(|(p, _)| p == prefix) {
684            return Err(format!("prefix {prefix:?} bound twice"));
685        }
686        out.push((prefix.to_owned(), uri.to_owned()));
687    }
688    if out.is_empty() {
689        return Err("no binding (prefix=uri pairs separated by spaces)".to_owned());
690    }
691    Ok(out)
692}
693
694/// The namespace bindings of a scenario's `match` expression.
695pub(crate) fn namespace_map(namespaces: &[(String, String)]) -> einvoice_xpath::NamespaceMap {
696    namespaces
697        .iter()
698        .fold(einvoice_xpath::NamespaceMap::new(), |map, (prefix, uri)| {
699            map.bind(prefix, uri)
700        })
701}
702
703/// Whether a `match` expression parses as XPath with its namespace bindings; when not,
704/// whether it is outside the subset of the engine rather than wrong, and why.
705fn check_match(expression: &str, namespaces: &[(String, String)]) -> Result<(), (bool, String)> {
706    if expression.trim().is_empty() {
707        return Err((false, "empty".to_owned()));
708    }
709    einvoice_xpath::parse_expr(expression, &namespace_map(namespaces))
710        .map(|_| ())
711        .map_err(|e| {
712            let unsupported = matches!(
713                e.kind,
714                einvoice_xpath::ErrorKind::Unsupported | einvoice_xpath::ErrorKind::TooDeep
715            );
716            (unsupported, e.to_string())
717        })
718}
719
720/// What holds across the scenarios of a manifest: they all have a `match` expression,
721/// or none has; the stylesheets each names are stylesheets of the rule set, each once.
722/// `lines` are the lines of their headers.
723fn check_scenarios(
724    scenarios: &[Scenario],
725    lines: &[u32],
726    stylesheets: &[StylesheetEntry],
727) -> Result<(), Error> {
728    let at = |index: usize| {
729        format!(
730            "{MANIFEST_FILE}: [[scenario]] of line {}",
731            lines.get(index).copied().unwrap_or(0)
732        )
733    };
734    let selecting = scenarios
735        .first()
736        .is_some_and(|s| s.match_expression().is_some());
737    for (index, scenario) in scenarios.iter().enumerate() {
738        if scenario.match_expression().is_some() != selecting {
739            return Err(Error::bundle(format!(
740                "{}: either every [[scenario]] has a `match` expression, or none has",
741                at(index)
742            )));
743        }
744        let names = scenario.stylesheets().unwrap_or_default();
745        for (i, name) in names.iter().enumerate() {
746            if !stylesheets.iter().any(|s| s.name() == name) {
747                return Err(Error::bundle(format!(
748                    "{}: `stylesheets`: no stylesheet {name:?} in the bundle",
749                    at(index)
750                )));
751            }
752            if names[..i].contains(name) {
753                return Err(Error::bundle(format!(
754                    "{}: `stylesheets`: {name:?} twice",
755                    at(index)
756                )));
757            }
758        }
759    }
760    Ok(())
761}
762
763/// A `[[resource]]` table (format 2), whose path no file of the bundle has yet.
764fn resource(
765    mut table: Table,
766    format: u64,
767    stylesheets: &[StylesheetEntry],
768    resources: &[ResourceEntry],
769) -> Result<ResourceEntry, Error> {
770    if format < 2 {
771        return Err(Error::bundle(format!(
772            "{MANIFEST_FILE}:{}: [[resource]] needs format = 2",
773            table.header_line
774        )));
775    }
776    table.allow(&["path", "sha256"])?;
777    let path = table.required_string("path")?;
778    check_path(&path).map_err(|m| table.error("path", &m))?;
779    let taken =
780        resources.iter().any(|r| r.path == path) || stylesheets.iter().any(|s| s.path == path);
781    if taken {
782        return Err(table.error("path", &format!("{path:?} twice in the bundle")));
783    }
784    let sha256 = table.sha256()?;
785    table.finish()?;
786    Ok(ResourceEntry { path, sha256 })
787}
788
789fn check_name(name: &str) -> Result<(), String> {
790    let mut bytes = name.bytes();
791    let first_ok = bytes.next().is_some_and(|b| b.is_ascii_alphanumeric());
792    if first_ok && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_')) {
793        Ok(())
794    } else {
795        Err(format!(
796            "{name:?}: ASCII letters, digits, `-`, `.` and `_` only, starting with a letter or digit"
797        ))
798    }
799}
800
801fn check_version(version: &str) -> Result<(), String> {
802    if !version.is_empty()
803        && version
804            .chars()
805            .all(|c| !c.is_whitespace() && !c.is_control())
806    {
807        Ok(())
808    } else {
809        Err(format!("{version:?}: must be non-empty, without spaces"))
810    }
811}
812
813/// A path inside the bundle: relative, `/`-separated, no empty, `.` or `..` segment, no
814/// backslash or colon, so that it can never designate a file outside the bundle.
815fn check_path(path: &str) -> Result<(), String> {
816    let bad = path.is_empty()
817        || path.contains(['\\', ':'])
818        || path.chars().any(char::is_control)
819        || path
820            .split('/')
821            .any(|segment| segment.is_empty() || segment == "." || segment == "..");
822    if bad {
823        Err(format!(
824            "{path:?}: must be a relative `/`-separated path inside the bundle (no empty, `.` or `..` segment, no `\\` or `:`)"
825        ))
826    } else {
827        Ok(())
828    }
829}
830
831/// A value of the accepted TOML subset.
832#[derive(Debug, Clone, PartialEq, Eq)]
833enum Value {
834    String(String),
835    Integer(u64),
836}
837
838/// The kind of a table: the top-level one, `[[stylesheet]]`, `[[resource]]` or
839/// `[[scenario]]`.
840#[derive(Debug, Clone, Copy, PartialEq, Eq)]
841enum TableKind {
842    Top,
843    Stylesheet,
844    Resource,
845    Scenario,
846}
847
848/// The keys of one table, in order, with their lines. The top-level table has header
849/// line 0.
850#[derive(Debug)]
851struct RawTable {
852    kind: TableKind,
853    header_line: u32,
854    entries: Vec<(String, Value, u32)>,
855}
856
857/// Reads the accepted TOML subset: comments, blank lines, `key = value` lines with a
858/// bare key and a basic string (escapes `\"` and `\\` only), a literal string or a
859/// non-negative integer, and `[[stylesheet]]`, `[[resource]]` and `[[scenario]]`
860/// headers.
861fn parse_tables(text: &str) -> Result<Vec<RawTable>, Error> {
862    let mut tables = vec![RawTable {
863        kind: TableKind::Top,
864        header_line: 0,
865        entries: Vec::new(),
866    }];
867    for (index, line) in text.split('\n').enumerate() {
868        let number = u32::try_from(index + 1).unwrap_or(u32::MAX);
869        let fail = |message: &str| Error::bundle(format!("{MANIFEST_FILE}:{number}: {message}"));
870        let line = line.strip_suffix('\r').unwrap_or(line);
871        let content = line.trim_matches([' ', '\t']);
872        if content.is_empty() || content.starts_with('#') {
873            continue;
874        }
875        if let Some(rest) = content.strip_prefix('[') {
876            let header = [
877                ("[stylesheet]]", TableKind::Stylesheet),
878                ("[resource]]", TableKind::Resource),
879                ("[scenario]]", TableKind::Scenario),
880            ]
881            .into_iter()
882            .find_map(|(h, kind)| rest.strip_prefix(h).map(|after| (after_value(after), kind)));
883            match header {
884                Some((Ok(()), kind)) => {
885                    tables.push(RawTable {
886                        kind,
887                        header_line: number,
888                        entries: Vec::new(),
889                    });
890                    continue;
891                }
892                Some((Err(m), _)) => return Err(fail(&m)),
893                None => {
894                    return Err(fail(
895                        "the only tables allowed are [[stylesheet]], [[resource]] and [[scenario]]",
896                    ));
897                }
898            }
899        }
900        let Some((key, value)) = content.split_once('=') else {
901            return Err(fail("expected `key = value`"));
902        };
903        let key = key.trim_matches([' ', '\t']);
904        if key.is_empty()
905            || !key
906                .bytes()
907                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
908        {
909            return Err(fail(&format!("{key:?}: expected a bare key")));
910        }
911        let value = parse_value(value.trim_start_matches([' ', '\t'])).map_err(|m| fail(&m))?;
912        let Some(table) = tables.last_mut() else {
913            return Err(Error::internal("manifest: no table"));
914        };
915        if table.entries.iter().any(|(k, _, _)| k == key) {
916            return Err(fail(&format!("key `{key}` repeated")));
917        }
918        table.entries.push((key.to_owned(), value, number));
919    }
920    Ok(tables)
921}
922
923fn parse_value(text: &str) -> Result<Value, String> {
924    if let Some(rest) = text.strip_prefix('"') {
925        let mut value = String::new();
926        let mut chars = rest.char_indices();
927        while let Some((i, c)) = chars.next() {
928            match c {
929                '"' => {
930                    after_value(&rest[i + 1..])?;
931                    return Ok(Value::String(value));
932                }
933                '\\' => match chars.next() {
934                    Some((_, '"')) => value.push('"'),
935                    Some((_, '\\')) => value.push('\\'),
936                    _ => return Err("only the escapes \\\" and \\\\ are accepted".to_owned()),
937                },
938                c if c.is_control() && c != '\t' => {
939                    return Err("control character in a string".to_owned());
940                }
941                c => value.push(c),
942            }
943        }
944        Err("unterminated string".to_owned())
945    } else if let Some(rest) = text.strip_prefix('\'') {
946        let end = rest
947            .find('\'')
948            .ok_or_else(|| "unterminated string".to_owned())?;
949        let value = &rest[..end];
950        if value.chars().any(|c| c.is_control() && c != '\t') {
951            return Err("control character in a string".to_owned());
952        }
953        after_value(&rest[end + 1..])?;
954        Ok(Value::String(value.to_owned()))
955    } else {
956        let end = text
957            .find(|c: char| !c.is_ascii_digit())
958            .unwrap_or(text.len());
959        let digits = &text[..end];
960        if digits.is_empty() || (digits.len() > 1 && digits.starts_with('0')) {
961            return Err("expected a string or a non-negative integer".to_owned());
962        }
963        let value = digits
964            .parse()
965            .map_err(|_| "integer out of range".to_owned())?;
966        after_value(&text[end..])?;
967        Ok(Value::Integer(value))
968    }
969}
970
971/// What may follow a value or a header on its line: blanks and a comment.
972fn after_value(rest: &str) -> Result<(), String> {
973    let rest = rest.trim_start_matches([' ', '\t']);
974    if rest.is_empty() || rest.starts_with('#') {
975        Ok(())
976    } else {
977        Err(format!("unexpected {rest:?} after the value"))
978    }
979}
980
981/// A table whose keys are taken one by one; [`Table::finish`] fails on any left.
982struct Table {
983    kind: TableKind,
984    header_line: u32,
985    /// Key, value (`None` once taken) and line.
986    entries: Vec<(String, Option<Value>, u32)>,
987}
988
989impl Table {
990    fn new(raw: RawTable) -> Self {
991        Self {
992            kind: raw.kind,
993            header_line: raw.header_line,
994            entries: raw
995                .entries
996                .into_iter()
997                .map(|(k, v, l)| (k, Some(v), l))
998                .collect(),
999        }
1000    }
1001
1002    fn where_(&self) -> String {
1003        match self.kind {
1004            TableKind::Top => MANIFEST_FILE.to_owned(),
1005            TableKind::Stylesheet => format!(
1006                "{MANIFEST_FILE}: [[stylesheet]] of line {}",
1007                self.header_line
1008            ),
1009            TableKind::Resource => {
1010                format!("{MANIFEST_FILE}: [[resource]] of line {}", self.header_line)
1011            }
1012            TableKind::Scenario => {
1013                format!("{MANIFEST_FILE}: [[scenario]] of line {}", self.header_line)
1014            }
1015        }
1016    }
1017
1018    /// The `sha256` key: 64 lower-case hexadecimal digits.
1019    fn sha256(&mut self) -> Result<String, Error> {
1020        let sha256 = self.required_string("sha256")?;
1021        if sha256.len() != 64
1022            || !sha256
1023                .bytes()
1024                .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
1025        {
1026            return Err(self.error("sha256", "must be 64 lower-case hexadecimal digits"));
1027        }
1028        Ok(sha256)
1029    }
1030
1031    /// The line of `key`, taken or not; the header's line when absent.
1032    fn line_of(&self, key: &str) -> u32 {
1033        self.entries
1034            .iter()
1035            .find(|(k, _, _)| k == key)
1036            .map_or(self.header_line, |(_, _, l)| *l)
1037    }
1038
1039    fn error(&self, key: &str, message: &str) -> Error {
1040        Error::bundle(format!(
1041            "{MANIFEST_FILE}:{}: `{key}`: {message}",
1042            self.line_of(key)
1043        ))
1044    }
1045
1046    /// Fails on a key outside `allowed`.
1047    fn allow(&self, allowed: &[&str]) -> Result<(), Error> {
1048        match self
1049            .entries
1050            .iter()
1051            .find(|(k, _, _)| !allowed.contains(&k.as_str()))
1052        {
1053            Some((key, _, line)) => Err(Error::bundle(format!(
1054                "{MANIFEST_FILE}:{line}: unknown key `{key}` (expected one of: {})",
1055                allowed.join(", ")
1056            ))),
1057            None => Ok(()),
1058        }
1059    }
1060
1061    fn take(&mut self, key: &str) -> Option<Value> {
1062        self.entries
1063            .iter_mut()
1064            .find(|(k, _, _)| k == key)
1065            .and_then(|(_, v, _)| v.take())
1066    }
1067
1068    fn optional_string(&mut self, key: &str) -> Result<Option<String>, Error> {
1069        match self.take(key) {
1070            None => Ok(None),
1071            Some(Value::String(s)) => Ok(Some(s)),
1072            Some(Value::Integer(_)) => Err(self.error(key, "must be a string")),
1073        }
1074    }
1075
1076    fn required_string(&mut self, key: &str) -> Result<String, Error> {
1077        let where_ = self.where_();
1078        self.optional_string(key)?
1079            .ok_or_else(|| Error::bundle(format!("{where_}: the `{key}` key is missing")))
1080    }
1081
1082    fn finish(self) -> Result<(), Error> {
1083        match self.entries.iter().find(|(_, v, _)| v.is_some()) {
1084            Some((key, _, line)) => Err(Error::bundle(format!(
1085                "{MANIFEST_FILE}:{line}: unexpected key `{key}`"
1086            ))),
1087            None => Ok(()),
1088        }
1089    }
1090}
1091
1092#[cfg(test)]
1093mod tests {
1094    use super::*;
1095
1096    const GOOD: &str = r#"# comment
1097format = 1
1098name = "cen-ubl"   # trailing comment
1099title = 'CEN EN 16931 UBL'
1100version = "1.3.17"
1101schema = "ubl-2.1"
1102
1103[[stylesheet]]
1104name = "EN16931-UBL"
1105path = "ubl/xslt/EN16931-UBL-validation.xslt"
1106sha256 = "fc4e6cfa8596bba0c2abd19038a98960c6ee9fc1f44566787c115efd4f4aca7c"
1107
1108[[stylesheet]]  # second
1109name = "other"
1110version = "3.0.22"
1111path = "x.xsl"
1112sha256 = "0000000000000000000000000000000000000000000000000000000000000000"
1113"#;
1114
1115    #[test]
1116    fn parses_a_manifest() {
1117        let rule_set = RuleSet::parse(GOOD).unwrap();
1118        assert_eq!(rule_set.name(), "cen-ubl");
1119        assert_eq!(rule_set.title(), "CEN EN 16931 UBL");
1120        assert_eq!(rule_set.version(), "1.3.17");
1121        assert_eq!(rule_set.schema(), Some(SchemaId::Ubl21));
1122        let s = rule_set.stylesheets();
1123        assert_eq!(s.len(), 2);
1124        assert_eq!(s[0].name(), "EN16931-UBL");
1125        assert_eq!(s[0].version(), "1.3.17");
1126        assert_eq!(s[0].path(), "ubl/xslt/EN16931-UBL-validation.xslt");
1127        assert_eq!(s[1].version(), "3.0.22");
1128    }
1129
1130    #[test]
1131    fn the_embedded_manifest_parses() {
1132        let rule_set = RuleSet::parse(include_str!("../bundles/cen-ubl/bundle.toml")).unwrap();
1133        assert_eq!(rule_set.name(), "cen-ubl");
1134    }
1135
1136    #[test]
1137    fn format_2_lists_resources() {
1138        let zeros = "0".repeat(64);
1139        let text = format!(
1140            "{}[[resource]]\npath = \"codes/a.xml\"\nsha256 = \"{zeros}\"\n\n[[resource]] # b\npath = \"b.xml\"\nsha256 = \"{}\"\n",
1141            GOOD.replace("format = 1", "format = 2"),
1142            "1".repeat(64)
1143        );
1144        let rule_set = RuleSet::parse(&text).unwrap();
1145        let resources: Vec<(&str, &str)> = rule_set
1146            .resources()
1147            .iter()
1148            .map(|r| (r.path(), r.sha256()))
1149            .collect();
1150        assert_eq!(
1151            resources,
1152            [
1153                ("codes/a.xml", zeros.as_str()),
1154                ("b.xml", "1".repeat(64).as_str())
1155            ]
1156        );
1157        assert_eq!(rule_set.stylesheets().len(), 2);
1158        assert_eq!(RuleSet::parse(GOOD).unwrap().resources(), []);
1159        for (bad, expected) in [
1160            (text.replace("codes/a.xml", "../a.xml"), "`path`"),
1161            (text.replace("codes/a.xml", "b.xml"), "twice in the bundle"),
1162            (text.replace("codes/a.xml", "x.xsl"), "twice in the bundle"),
1163            (
1164                text.replace(&format!("sha256 = \"{zeros}\""), "sha256 = \"x\""),
1165                "`sha256`",
1166            ),
1167            (
1168                text.replace("path = \"b.xml\"", "name = \"b\"\npath = \"b.xml\""),
1169                "unknown key `name`",
1170            ),
1171            (
1172                text.replace("path = \"b.xml\"\n", ""),
1173                "[[resource]] of line 22: the `path` key is missing",
1174            ),
1175        ] {
1176            let message = error(&bad);
1177            assert!(
1178                message.contains(expected),
1179                "{expected:?} not in {message:?}"
1180            );
1181        }
1182    }
1183
1184    /// [`GOOD`] in format 2, the second stylesheet failing closed on unflagged asserts,
1185    /// with two scenarios.
1186    fn with_severities() -> String {
1187        format!(
1188            "{}
1189[[scenario]]
1190name = \"S 1\"
1191namespace = \"{UBL_INVOICE}\"
1192root = \"Invoice\"
1193identifier = \"urn:x\"
1194fatal = \"R-1  R-2\"
1195other = \"R-3\"
1196
1197[[scenario]]  # CII
1198name = \"S 2\"
1199namespace = \"{CII}\"
1200root = \"CrossIndustryInvoice\"
1201identifier = \"urn:y#z\"
1202warning = \"R-1\"
1203",
1204            GOOD.replace("format = 1", "format = 2").replace(
1205                "path = \"x.xsl\"",
1206                "path = \"x.xsl\"\nunflagged-assert = \"fatal\""
1207            )
1208        )
1209    }
1210
1211    #[test]
1212    fn format_2_reads_severities() {
1213        let text = with_severities();
1214        let rule_set = RuleSet::parse(&text).unwrap();
1215        let unflagged: Vec<Severity> = rule_set
1216            .stylesheets()
1217            .iter()
1218            .map(StylesheetEntry::unflagged_assert)
1219            .collect();
1220        assert_eq!(unflagged, [Severity::Other, Severity::Fatal]);
1221        let [s1, s2] = rule_set.scenarios() else {
1222            panic!("{:?}", rule_set.scenarios());
1223        };
1224        assert_eq!(
1225            (s1.name(), s1.namespace(), s1.root(), s1.identifier()),
1226            ("S 1", Some(UBL_INVOICE), Some("Invoice"), Some("urn:x"))
1227        );
1228        assert_eq!(
1229            s1.levels(),
1230            [
1231                ("R-1".to_owned(), Severity::Fatal),
1232                ("R-2".to_owned(), Severity::Fatal),
1233                ("R-3".to_owned(), Severity::Other)
1234            ]
1235        );
1236        assert_eq!(s1.level("R-2"), Some(Severity::Fatal));
1237        assert_eq!(s1.level("R-4"), None);
1238        assert_eq!(
1239            (s2.root(), s2.identifier()),
1240            (Some("CrossIndustryInvoice"), Some("urn:y#z"))
1241        );
1242        assert_eq!(s2.level("R-1"), Some(Severity::Warning));
1243        // Format 1 and format 2 without them: as before.
1244        assert_eq!(RuleSet::parse(GOOD).unwrap().scenarios(), []);
1245        assert!(
1246            RuleSet::parse(GOOD)
1247                .unwrap()
1248                .stylesheets()
1249                .iter()
1250                .all(|s| s.unflagged_assert() == Severity::Other)
1251        );
1252    }
1253
1254    #[test]
1255    fn severities_are_refused_with_the_line() {
1256        let text = with_severities();
1257        let in_format_1 = text.replace("format = 2", "format = 1");
1258        assert!(
1259            error(&in_format_1).contains("bundle.toml:17: `unflagged-assert`: needs format = 2")
1260        );
1261        let scenario_in_format_1 = in_format_1.replace("unflagged-assert = \"fatal\"\n", "");
1262        assert!(
1263            error(&scenario_in_format_1).contains("bundle.toml:19: [[scenario]] needs format = 2"),
1264            "{}",
1265            error(&scenario_in_format_1)
1266        );
1267        for (bad, expected) in [
1268            (
1269                text.replace(
1270                    "unflagged-assert = \"fatal\"",
1271                    "unflagged-assert = \"error\"",
1272                ),
1273                "`unflagged-assert`: \"error\": expected fatal, warning or other",
1274            ),
1275            (
1276                text.replace("name = \"S 2\"", "name = \"S 1\""),
1277                "scenario \"S 1\" twice",
1278            ),
1279            (
1280                text.replace("root = \"Invoice\"", "root = \"CreditNote\""),
1281                "`root`: {urn:oasis:names:specification:ubl:schema:xsd:Invoice-2}CreditNote: a scenario matches",
1282            ),
1283            (
1284                text.replace("root = \"Invoice\"", "root = \"Order\""),
1285                "a scenario matches a UBL Invoice or CreditNote, or a CII CrossIndustryInvoice",
1286            ),
1287            (
1288                text.replace("other = \"R-3\"", "other = \"R-2\""),
1289                "rule id \"R-2\" given twice",
1290            ),
1291            (
1292                text.replace("warning = \"R-1\"", "warning = \" \""),
1293                "`warning`: no rule id",
1294            ),
1295            (
1296                text.replace("warning = \"R-1\"\n", ""),
1297                "[[scenario]] of line 28: no rule id (the keys fatal, warning and other)",
1298            ),
1299            (
1300                text.replace("identifier = \"urn:x\"", "identifier = \"\""),
1301                "`identifier`",
1302            ),
1303            (
1304                text.replace("name = \"S 1\"", "name = \" \""),
1305                "`name`: must be non-empty",
1306            ),
1307            (
1308                text.replace("identifier = \"urn:x\"\n", ""),
1309                "[[scenario]] of line 20: the `identifier` key is missing",
1310            ),
1311            (
1312                text.replace("other = \"R-3\"", "information = \"R-3\""),
1313                "unknown key `information`",
1314            ),
1315        ] {
1316            let message = error(&bad);
1317            assert!(
1318                message.contains(expected),
1319                "{expected:?} not in {message:?}"
1320            );
1321        }
1322    }
1323
1324    /// [`GOOD`] in format 2 with scenarios that select by `match` expressions, as the
1325    /// XRechnung bundles have them.
1326    fn with_matches() -> String {
1327        format!(
1328            "{}
1329[[scenario]]
1330name = \"Both\"
1331namespaces = \"cbc=urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2 invoice={UBL_INVOICE}\"
1332match = \"exists(/invoice:Invoice/cbc:CustomizationID[ . = 'urn:x#y']) \"
1333stylesheets = \"EN16931-UBL other\"
1334fatal = \"R-1\"
1335
1336[[scenario]]
1337name = \"First\"
1338namespaces = \"invoice={UBL_INVOICE}\"
1339match = \"exists(/invoice:Invoice)\"
1340stylesheets = \"EN16931-UBL\"
1341
1342[[scenario]]
1343name = \"Every one\"
1344match = \"true()\"
1345",
1346            GOOD.replace("format = 1", "format = 2").replace(
1347                "schema = \"ubl-2.1\"",
1348                "schema = \"ubl-2.1\"\nunchecked-schema = \"Another schema (x.xsd)\""
1349            )
1350        )
1351    }
1352
1353    #[test]
1354    fn format_2_selects_by_scenario() {
1355        let text = with_matches();
1356        let rule_set = RuleSet::parse(&text).unwrap();
1357        assert!(rule_set.selects_by_scenario());
1358        assert_eq!(rule_set.unchecked_schema(), Some("Another schema (x.xsd)"));
1359        let [both, first, every] = rule_set.scenarios() else {
1360            panic!("{:?}", rule_set.scenarios());
1361        };
1362        assert_eq!(
1363            both.match_expression(),
1364            Some("exists(/invoice:Invoice/cbc:CustomizationID[ . = 'urn:x#y']) ")
1365        );
1366        assert_eq!(
1367            both.namespaces(),
1368            [
1369                (
1370                    "cbc".to_owned(),
1371                    "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
1372                        .to_owned()
1373                ),
1374                ("invoice".to_owned(), UBL_INVOICE.to_owned())
1375            ]
1376        );
1377        assert_eq!(
1378            both.stylesheets(),
1379            Some(&["EN16931-UBL".to_owned(), "other".to_owned()][..])
1380        );
1381        assert_eq!(both.level("R-1"), Some(Severity::Fatal));
1382        assert_eq!(
1383            (both.namespace(), both.root(), both.identifier()),
1384            (None, None, None)
1385        );
1386        // Levels are optional with a `match` expression, and so are the stylesheets
1387        // (all of them) and the namespaces.
1388        assert_eq!(first.levels(), []);
1389        assert_eq!(first.stylesheets().map(<[String]>::len), Some(1));
1390        assert_eq!(every.stylesheets(), None);
1391        assert_eq!(every.namespaces(), []);
1392        // The scenarios of the other form do not select.
1393        let identified = RuleSet::parse(&with_severities()).unwrap();
1394        assert!(!identified.selects_by_scenario());
1395        assert_eq!(identified.scenarios()[0].match_expression(), None);
1396        assert_eq!(identified.scenarios()[0].stylesheets(), None);
1397        assert_eq!(identified.unchecked_schema(), None);
1398        assert!(!RuleSet::parse(GOOD).unwrap().selects_by_scenario());
1399    }
1400
1401    #[test]
1402    fn match_scenarios_are_refused_with_the_line() {
1403        let text = with_matches();
1404        let identified = "\n[[scenario]]\nname = \"I\"\nnamespace = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\"\nroot = \"Invoice\"\nidentifier = \"urn:x\"\nfatal = \"R-1\"\n";
1405        for (bad, expected) in [
1406            (
1407                text.replace("format = 2", "format = 1")
1408                    .replace("unchecked-schema = \"Another schema (x.xsd)\"\n", "")
1409                    .split("\n[[scenario]]")
1410                    .next()
1411                    .unwrap()
1412                    .replace(
1413                        "version = \"1.3.17\"",
1414                        "version = \"1.3.17\"\nunchecked-schema = \"x\"",
1415                    ),
1416                "bundle.toml:6: `unchecked-schema`: needs format = 2",
1417            ),
1418            (
1419                text.replace("\"Another schema (x.xsd)\"", "\" \""),
1420                "`unchecked-schema`: must be non-empty",
1421            ),
1422            (
1423                text.replace("match = \"true()\"", "match = \"true(\""),
1424                "bundle.toml:35: `match`: syntax error",
1425            ),
1426            (
1427                text.replace(
1428                    "match = \"exists(/invoice:Invoice)\"",
1429                    "match = \"exists(/x:Invoice)\"",
1430                ),
1431                "`match`: undeclared namespace prefix",
1432            ),
1433            (
1434                text.replace("match = \"true()\"", "match = \" \""),
1435                "`match`: empty",
1436            ),
1437            (
1438                text.replace(
1439                    "stylesheets = \"EN16931-UBL\"",
1440                    "stylesheets = \"EN16931-UBL x\"",
1441                ),
1442                "[[scenario]] of line 27: `stylesheets`: no stylesheet \"x\" in the bundle",
1443            ),
1444            (
1445                text.replace(
1446                    "stylesheets = \"EN16931-UBL\"",
1447                    "stylesheets = \"other other\"",
1448                ),
1449                "`stylesheets`: \"other\" twice",
1450            ),
1451            (
1452                text.replace("stylesheets = \"EN16931-UBL\"", "stylesheets = \" \""),
1453                "`stylesheets`: no stylesheet name",
1454            ),
1455            (
1456                text.replace(
1457                    "match = \"true()\"",
1458                    "match = \"true()\"\nroot = \"Invoice\"",
1459                ),
1460                "`root`: not with `match`",
1461            ),
1462            (
1463                text.replace("namespaces = \"invoice=", "namespaces = \"invoice "),
1464                "`namespaces`: \"invoice\": expected prefix=uri",
1465            ),
1466            (
1467                text.replace("namespaces = \"invoice=", "namespaces = \"1x="),
1468                "the prefix an NCName",
1469            ),
1470            (
1471                text.replace(
1472                    "namespaces = \"invoice=",
1473                    "namespaces = \"invoice=urn:a invoice=",
1474                ),
1475                "prefix \"invoice\" bound twice",
1476            ),
1477            (
1478                format!("{text}{identified}"),
1479                "[[scenario]] of line 37: either every [[scenario]] has a `match` expression, or none has",
1480            ),
1481            (
1482                format!("{}\nstylesheets = \"other\"\n", with_severities()),
1483                "`stylesheets`: only with `match`",
1484            ),
1485        ] {
1486            let message = error(&bad);
1487            assert!(
1488                message.contains(expected),
1489                "{expected:?} not in {message:?}"
1490            );
1491        }
1492        // An expression outside the subset of the engine: unsupported, not malformed.
1493        let unsupported = text.replace("match = \"true()\"", "match = \"let $x := 1 return $x\"");
1494        let e = RuleSet::parse(&unsupported).unwrap_err();
1495        assert_eq!(e.kind(), crate::ErrorKind::Unsupported, "{e}");
1496    }
1497
1498    #[test]
1499    fn schema_is_optional() {
1500        let text = GOOD.replace("schema = \"ubl-2.1\"\n", "");
1501        assert_eq!(RuleSet::parse(&text).unwrap().schema(), None);
1502    }
1503
1504    #[test]
1505    fn schema_names() {
1506        for id in [SchemaId::Ubl21, SchemaId::CiiD16b] {
1507            assert_eq!(SchemaId::from_name(id.as_str()), Some(id));
1508            let text = GOOD.replace("ubl-2.1", id.as_str());
1509            assert_eq!(RuleSet::parse(&text).unwrap().schema(), Some(id));
1510        }
1511        assert_eq!(SchemaId::CiiD16b.to_string(), "cii-d16b");
1512        assert_eq!(SchemaId::from_name("CII-D16B"), None);
1513    }
1514
1515    fn error(text: &str) -> String {
1516        RuleSet::parse(text).unwrap_err().to_string()
1517    }
1518
1519    #[test]
1520    fn refusals_name_the_line() {
1521        let cases = [
1522            (
1523                GOOD.replace("format = 1", "format = 3"),
1524                "bundle.toml:2: format 3",
1525            ),
1526            (
1527                format!(
1528                    "{GOOD}[[resource]]\npath = \"r.xml\"\nsha256 = \"{}\"\n",
1529                    "0".repeat(64)
1530                ),
1531                "bundle.toml:18: [[resource]] needs format = 2",
1532            ),
1533            (
1534                GOOD.replace("format = 1", "format = \"1\""),
1535                "bundle.toml:2:",
1536            ),
1537            (
1538                GOOD.replace("format = 1\n", ""),
1539                "the `format` key is missing",
1540            ),
1541            (
1542                GOOD.replace("ubl-2.1", "ubl-2.2"),
1543                "bundle.toml:6: `schema`: unknown schema",
1544            ),
1545            (
1546                GOOD.replace("title =", "titel ="),
1547                "bundle.toml:4: unknown key `titel`",
1548            ),
1549            (
1550                GOOD.replace("name = \"other\"", "name = \"EN16931-UBL\""),
1551                "twice",
1552            ),
1553            (GOOD.replace("x.xsl", "../x.xsl"), "`path`"),
1554            (GOOD.replace("x.xsl", "/x.xsl"), "`path`"),
1555            (GOOD.replace("x.xsl", "C:/x.xsl"), "`path`"),
1556            (GOOD.replace("x.xsl", "a//x.xsl"), "`path`"),
1557            (GOOD.replace("x.xsl", "a\\\\x.xsl"), "`path`"),
1558            (GOOD.replace("\"0000", "\"A000"), "`sha256`"),
1559            (
1560                GOOD.replace("version = \"1.3.17\"", "version = \"1 3\""),
1561                "`version`",
1562            ),
1563            (
1564                GOOD.replace("[[stylesheet]]  #", "[stylesheet] #"),
1565                "bundle.toml:13: the only tables allowed",
1566            ),
1567            (
1568                GOOD.replace("name = \"cen-ubl\"", "name = \"cen\\nubl\""),
1569                "bundle.toml:3: only the escapes",
1570            ),
1571            (
1572                GOOD.replace("name = \"cen-ubl\"", "name = \"cen-ubl"),
1573                "unterminated",
1574            ),
1575            (
1576                GOOD.replace("version = \"1.3.17\"", "version = \"1.3.17\" x"),
1577                "after the value",
1578            ),
1579            (
1580                GOOD.replace("format = 1", "format = 1\nformat = 1"),
1581                "repeated",
1582            ),
1583            (
1584                GOOD.replace("format = 1", "format = 01"),
1585                "bundle.toml:2: expected a string",
1586            ),
1587            (
1588                GOOD.replace("path = \"x.xsl\"\n", ""),
1589                "the `path` key is missing",
1590            ),
1591            (
1592                GOOD.split("[[stylesheet]]").next().unwrap().to_owned(),
1593                "no [[stylesheet]]",
1594            ),
1595            (String::new(), "the `format` key is missing"),
1596            (
1597                "format\n".to_owned(),
1598                "bundle.toml:1: expected `key = value`",
1599            ),
1600        ];
1601        for (text, expected) in cases {
1602            let message = error(&text);
1603            assert!(
1604                message.contains(expected),
1605                "{expected:?} not in {message:?}"
1606            );
1607        }
1608    }
1609}