Skip to main content

einvoice_xsd/
model.rs

1//! The compiled schema components.
2
3use std::collections::HashMap;
4use std::sync::Arc;
5
6use crate::automaton::Automaton;
7use crate::datatypes::Builtin;
8
9/// The XML Schema namespace.
10pub(crate) const XS: &str = "http://www.w3.org/2001/XMLSchema";
11/// The XML Schema instance namespace.
12pub(crate) const XSI: &str = "http://www.w3.org/2001/XMLSchema-instance";
13
14pub(crate) type TypeId = usize;
15pub(crate) type ElementId = usize;
16
17/// The type `xs:anyType` is always the first type.
18pub(crate) const ANY_TYPE: TypeId = 0;
19
20/// An expanded name: namespace (absent for no namespace) and local name.
21#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub(crate) struct QName {
23    pub(crate) namespace: Option<String>,
24    pub(crate) local: String,
25}
26
27impl QName {
28    pub(crate) fn new(namespace: Option<&str>, local: &str) -> Self {
29        Self {
30            namespace: namespace.map(str::to_owned),
31            local: local.to_owned(),
32        }
33    }
34
35    pub(crate) fn matches(&self, namespace: Option<&str>, local: &str) -> bool {
36        self.local == local && self.namespace.as_deref() == namespace
37    }
38}
39
40/// A namespace name as the XML parser reports it, with the empty name (from
41/// `xmlns=""`, which undeclares the default namespace) mapped to no namespace.
42pub(crate) fn namespace_name(namespace: Option<&str>) -> Option<&str> {
43    namespace.filter(|ns| !ns.is_empty())
44}
45
46/// Clark notation: `{namespace}local`, or `local` without a namespace.
47pub(crate) fn clark(namespace: Option<&str>, local: &str) -> String {
48    match namespace {
49        Some(ns) => format!("{{{ns}}}{local}"),
50        None => local.to_owned(),
51    }
52}
53
54impl std::fmt::Display for QName {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.write_str(&clark(self.namespace.as_deref(), &self.local))
57    }
58}
59
60/// An element declaration (global or local). Declarations are never nillable and
61/// never abstract: the loader refuses those attributes.
62#[derive(Debug, Clone)]
63pub(crate) struct ElementDecl {
64    pub(crate) name: QName,
65    pub(crate) type_id: TypeId,
66}
67
68/// `processContents` of a wildcard.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub(crate) enum ProcessContents {
71    Strict,
72    Lax,
73    Skip,
74}
75
76/// The namespace constraint of a wildcard.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub(crate) enum NamespaceConstraint {
79    /// `##any`.
80    Any,
81    /// `##other`: any namespace except the given target namespace, and not absent.
82    Other(Option<String>),
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub(crate) struct Wildcard {
87    pub(crate) namespaces: NamespaceConstraint,
88    pub(crate) process: ProcessContents,
89}
90
91impl Wildcard {
92    pub(crate) fn allows(&self, namespace: Option<&str>) -> bool {
93        match &self.namespaces {
94            NamespaceConstraint::Any => true,
95            NamespaceConstraint::Other(target) => {
96                namespace.is_some() && namespace != target.as_deref()
97            }
98        }
99    }
100}
101
102/// An attribute use of a complex type.
103#[derive(Debug, Clone)]
104pub(crate) struct AttributeUse {
105    pub(crate) name: QName,
106    /// A simple type.
107    pub(crate) type_id: TypeId,
108    pub(crate) required: bool,
109    /// The `fixed` value constraint: a present attribute must have that value
110    /// (cvc-attribute.4). A `default` has no effect on validity (it only supplies
111    /// the value of an absent attribute in the post-schema-validation infoset,
112    /// which this crate does not build), so it is checked when the schema is loaded
113    /// and not kept.
114    pub(crate) fixed: Option<FixedValue>,
115}
116
117/// A fixed attribute value, as written in the schema, kept in
118/// [`Schema::fixed_values`]: an index rather than the text, so that an attribute use
119/// is no larger than without it.
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub(crate) struct FixedValue(std::num::NonZeroU32);
122
123impl FixedValue {
124    /// The handle of the value at `index` in [`Schema::fixed_values`]; `None` past
125    /// `u32::MAX - 1` values.
126    pub(crate) fn new(index: usize) -> Option<Self> {
127        u32::try_from(index)
128            .ok()
129            .and_then(|i| i.checked_add(1))
130            .and_then(std::num::NonZeroU32::new)
131            .map(Self)
132    }
133
134    fn index(self) -> usize {
135        // u32 to usize does not lose bits on the supported targets (32 and 64
136        // bits); the fallback only avoids a panic path.
137        usize::try_from(self.0.get() - 1).unwrap_or(usize::MAX)
138    }
139}
140
141/// Whether the value constraint of an element declaration is a default or a fixed
142/// value.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub(crate) enum ConstraintKind {
145    Default,
146    Fixed,
147}
148
149impl ConstraintKind {
150    pub(crate) fn as_str(self) -> &'static str {
151        match self {
152            Self::Default => "default",
153            Self::Fixed => "fixed",
154        }
155    }
156}
157
158/// The value constraint (`default` or `fixed`) of an element declaration, whose
159/// type has simple content.
160#[derive(Debug, Clone)]
161pub(crate) struct ValueConstraint {
162    pub(crate) kind: ConstraintKind,
163    /// The value as written in the schema.
164    pub(crate) value: Box<str>,
165}
166
167/// The content type of a complex type.
168#[derive(Debug, Clone)]
169pub(crate) enum Content {
170    /// No children at all, not even whitespace.
171    Empty,
172    /// Text only, valid for the given simple type.
173    Simple(TypeId),
174    /// Child elements, whitespace between them.
175    ElementOnly(Box<Automaton>),
176    /// Child elements and text.
177    Mixed(Box<Automaton>),
178}
179
180#[derive(Debug, Clone)]
181pub(crate) struct ComplexType {
182    pub(crate) name: Option<QName>,
183    /// The base type (`anyType` is its own base). Whether by extension or
184    /// restriction does not matter here: no derivation is blocked in the subset.
185    pub(crate) base: TypeId,
186    pub(crate) is_abstract: bool,
187    pub(crate) content: Content,
188    /// Shared with the base type when the derivation adds or changes none.
189    pub(crate) attributes: Arc<[AttributeUse]>,
190    pub(crate) attribute_wildcard: Option<Wildcard>,
191}
192
193#[derive(Debug, Clone)]
194pub(crate) struct SimpleType {
195    pub(crate) name: Option<QName>,
196    /// The base type: a simple type, or `anyType` for `anySimpleType`.
197    pub(crate) base: TypeId,
198    /// The built-in type at the root of the derivation chain below
199    /// `anySimpleType` that decides whitespace and lexical space (for built-ins,
200    /// the type itself).
201    pub(crate) builtin: Builtin,
202    /// The `enumeration` facet of this restriction step, if any.
203    pub(crate) enumeration: Option<Vec<String>>,
204    /// The `minLength` facet of this restriction step, if any (types derived from
205    /// `xs:string` only: a length in characters).
206    pub(crate) min_length: Option<usize>,
207    /// The `maxLength` facet of this restriction step, if any.
208    pub(crate) max_length: Option<usize>,
209}
210
211impl SimpleType {
212    /// Whether this restriction step has a facet to check besides the lexical
213    /// space of its built-in type.
214    pub(crate) fn has_facets(&self) -> bool {
215        self.enumeration.is_some() || self.min_length.is_some() || self.max_length.is_some()
216    }
217}
218
219#[derive(Debug, Clone)]
220pub(crate) enum TypeDef {
221    Simple(SimpleType),
222    Complex(ComplexType),
223}
224
225impl TypeDef {
226    pub(crate) fn name(&self) -> Option<&QName> {
227        match self {
228            Self::Simple(s) => s.name.as_ref(),
229            Self::Complex(c) => c.name.as_ref(),
230        }
231    }
232
233    pub(crate) fn base(&self) -> TypeId {
234        match self {
235            Self::Simple(s) => s.base,
236            Self::Complex(c) => c.base,
237        }
238    }
239}
240
241/// Whether a simple type or one of the simple types it is derived from has a facet
242/// ([`SimpleType::has_facets`]).
243pub(crate) fn has_facets(types: &[TypeDef], type_id: TypeId) -> bool {
244    let mut current = type_id;
245    while let TypeDef::Simple(step) = &types[current] {
246        if step.has_facets() {
247            return true;
248        }
249        current = step.base;
250    }
251    false
252}
253
254/// A facet that a value does not satisfy.
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub(crate) enum FacetProblem<'s> {
257    /// Not one of these values.
258    Enumeration(&'s [String]),
259    /// Shorter than `min` characters.
260    MinLength { length: usize, min: usize },
261    /// Longer than `max` characters.
262    MaxLength { length: usize, max: usize },
263}
264
265impl FacetProblem<'_> {
266    /// A description, completing "`value` is ..." or "the value is ...";
267    /// `type_name` names the type whose facet it is.
268    pub(crate) fn describe(self, type_name: &str) -> String {
269        match self {
270            Self::Enumeration(values) => format!(
271                "not one of the values allowed by {type_name}: {}",
272                values
273                    .iter()
274                    .map(|v| quote(v))
275                    .collect::<Vec<_>>()
276                    .join(", ")
277            ),
278            Self::MinLength { length, min } => format!(
279                "{length} characters long, less than the minimum length {min} of {type_name}"
280            ),
281            Self::MaxLength { length, max } => format!(
282                "{length} characters long, more than the maximum length {max} of {type_name}"
283            ),
284        }
285    }
286}
287
288/// The first facet of the derivation chain of a simple type (from the type itself
289/// towards its built-in type) that a value, already whitespace-processed and in the
290/// lexical space of the built-in type, does not satisfy. `None` when it satisfies
291/// every facet.
292pub(crate) fn facet_problem<'s>(
293    types: &'s [TypeDef],
294    type_id: TypeId,
295    value: &str,
296) -> Option<FacetProblem<'s>> {
297    let mut length = None;
298    let mut current = type_id;
299    while let TypeDef::Simple(step) = &types[current] {
300        if let Some(values) = &step.enumeration
301            && !values.iter().any(|v| v == value)
302        {
303            return Some(FacetProblem::Enumeration(values));
304        }
305        if step.min_length.is_some() || step.max_length.is_some() {
306            let length = *length.get_or_insert_with(|| value.chars().count());
307            if let Some(min) = step.min_length
308                && length < min
309            {
310                return Some(FacetProblem::MinLength { length, min });
311            }
312            if let Some(max) = step.max_length
313                && length > max
314            {
315                return Some(FacetProblem::MaxLength { length, max });
316            }
317        }
318        current = step.base;
319    }
320    None
321}
322
323/// Values quoted in messages are cut to this many characters.
324const MAX_QUOTED: usize = 80;
325
326/// A value quoted for a message, cut to [`MAX_QUOTED`] characters.
327pub(crate) fn quote(value: &str) -> String {
328    let mut out: String = value.chars().take(MAX_QUOTED).collect();
329    if value.chars().nth(MAX_QUOTED).is_some() {
330        out.push_str("...");
331    }
332    format!("{out:?}")
333}
334
335/// A loaded schema set: every component reachable from the entry points.
336#[derive(Debug, Clone)]
337pub struct Schema {
338    pub(crate) types: Vec<TypeDef>,
339    pub(crate) elements: Vec<ElementDecl>,
340    /// Global element declarations by namespace ([`namespace_key`]), then local
341    /// name.
342    pub(crate) global_elements: HashMap<String, HashMap<String, ElementId>>,
343    /// Global type definitions by namespace ([`namespace_key`]), then local name
344    /// (built-ins included).
345    pub(crate) global_types: HashMap<String, HashMap<String, TypeId>>,
346    /// The schema documents that were loaded, in load order.
347    pub(crate) documents: Vec<String>,
348    /// The imports that were not loaded, in the order they were found.
349    pub(crate) omitted_imports: Vec<OmittedImport>,
350    /// The value constraints of element declarations, sorted by element: few
351    /// declarations have one, so they are kept out of [`ElementDecl`].
352    pub(crate) element_constraints: Vec<(ElementId, ValueConstraint)>,
353    /// The fixed values of attribute uses ([`FixedValue`]).
354    pub(crate) fixed_values: Vec<Box<str>>,
355}
356
357/// An `xs:import` that was not loaded: it imports one of the namespaces of
358/// [`XADES_NAMESPACES`](crate::XADES_NAMESPACES) and the schema document it names
359/// is not in the schema set. Elements of that namespace then have no declaration;
360/// where a lax wildcard allows them (the UBL extension content, `ds:Object`) they
361/// are validated laxly, as `xs:anyType`.
362#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct OmittedImport {
364    /// The importing schema document, as its path relative to the root of the
365    /// schema set.
366    pub file: String,
367    /// 1-based line of the `xs:import` element in that document.
368    pub line: u32,
369    /// The imported namespace.
370    pub namespace: String,
371    /// The schema document the import names, resolved against the importing
372    /// document: a path that is not in the schema set.
373    pub location: String,
374}
375
376/// The key of a namespace in the global component maps of [`Schema`]: the
377/// namespace name, or the empty string for no namespace (a target namespace is never
378/// empty: the loader refuses `targetNamespace=""`), so that a lookup borrows the name
379/// instead of copying it. `None` for `Some("")`, which names no namespace of the set.
380pub(crate) fn namespace_key(namespace: Option<&str>) -> Option<&str> {
381    match namespace {
382        None => Some(""),
383        Some("") => None,
384        Some(ns) => Some(ns),
385    }
386}
387
388impl Schema {
389    pub(crate) fn global_element(&self, namespace: Option<&str>, local: &str) -> Option<ElementId> {
390        let by_name = self.global_elements.get(namespace_key(namespace)?)?;
391        by_name.get(local).copied()
392    }
393
394    pub(crate) fn global_type(&self, namespace: Option<&str>, local: &str) -> Option<TypeId> {
395        let by_name = self.global_types.get(namespace_key(namespace)?)?;
396        by_name.get(local).copied()
397    }
398
399    /// Releases the spare capacity that loading leaves in the tables: the schema
400    /// is kept for many validations.
401    pub(crate) fn shrink_to_fit(&mut self) {
402        self.types.shrink_to_fit();
403        for type_def in &mut self.types {
404            if let TypeDef::Simple(SimpleType {
405                enumeration: Some(values),
406                ..
407            }) = type_def
408            {
409                values.shrink_to_fit();
410            }
411        }
412        self.elements.shrink_to_fit();
413        for by_name in self.global_elements.values_mut() {
414            by_name.shrink_to_fit();
415        }
416        self.global_elements.shrink_to_fit();
417        for by_name in self.global_types.values_mut() {
418            by_name.shrink_to_fit();
419        }
420        self.global_types.shrink_to_fit();
421        self.element_constraints.shrink_to_fit();
422        self.fixed_values.shrink_to_fit();
423    }
424
425    /// Whether a simple type or one of the simple types it is derived from has a
426    /// facet ([`SimpleType::has_facets`]).
427    pub(crate) fn has_facets(&self, type_id: TypeId) -> bool {
428        has_facets(&self.types, type_id)
429    }
430
431    /// The text of a fixed attribute value.
432    pub(crate) fn fixed_value(&self, fixed: FixedValue) -> &str {
433        self.fixed_values.get(fixed.index()).map_or("", |v| v)
434    }
435
436    /// The value constraint of an element declaration, if it has one.
437    pub(crate) fn element_constraint(&self, element: ElementId) -> Option<&ValueConstraint> {
438        if self.element_constraints.is_empty() {
439            return None;
440        }
441        self.element_constraints
442            .binary_search_by_key(&element, |(id, _)| *id)
443            .ok()
444            .map(|index| &self.element_constraints[index].1)
445    }
446
447    /// Whether `derived` is `base` or derived from it through any number of
448    /// derivation steps (no derivation is blocked in the supported subset).
449    pub(crate) fn is_derived_from(&self, derived: TypeId, base: TypeId) -> bool {
450        let mut current = derived;
451        loop {
452            if current == base {
453                return true;
454            }
455            if current == ANY_TYPE {
456                return false;
457            }
458            current = self.types[current].base();
459        }
460    }
461
462    /// The paths of the schema documents the set was loaded from.
463    #[must_use]
464    pub fn documents(&self) -> &[String] {
465        &self.documents
466    }
467
468    /// The imports that were not loaded because their namespace is one of
469    /// [`XADES_NAMESPACES`](crate::XADES_NAMESPACES) and the schema document they
470    /// name is not in the set, in the order they were found. Empty when every
471    /// import was loaded.
472    #[must_use]
473    pub fn omitted_imports(&self) -> &[OmittedImport] {
474        &self.omitted_imports
475    }
476
477    /// The number of global element declarations.
478    #[must_use]
479    pub fn global_element_count(&self) -> usize {
480        self.global_elements.values().map(HashMap::len).sum()
481    }
482
483    /// The number of type definitions, built-in and anonymous included.
484    #[must_use]
485    pub fn type_count(&self) -> usize {
486        self.types.len()
487    }
488}