einvoice_xsd/error.rs
1//! Errors of schema loading, document parsing and validation.
2
3use std::fmt;
4
5/// Why a schema set could not be loaded.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct LoadError {
8 /// What kind of failure.
9 pub kind: LoadErrorKind,
10 /// The schema document, as its path relative to the root of the schema set.
11 pub file: String,
12 /// 1-based line in that document (0 when the error concerns the whole file).
13 pub line: u32,
14 /// What went wrong.
15 pub message: String,
16}
17
18/// The kinds of [`LoadError`].
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum LoadErrorKind {
21 /// A schema document is missing from the schema set.
22 MissingFile,
23 /// A schema document is not well-formed XML.
24 Malformed,
25 /// A construct that is valid XML Schema 1.0 but outside the subset this crate
26 /// implements: refused rather than ignored or approximated.
27 Unsupported,
28 /// The schemas are not a correct XML Schema 1.0 schema set (unresolved
29 /// reference, duplicate definition, circular derivation, non-deterministic
30 /// content model, ...).
31 Invalid,
32}
33
34impl fmt::Display for LoadError {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 let kind = match self.kind {
37 LoadErrorKind::MissingFile => "missing schema document",
38 LoadErrorKind::Malformed => "malformed schema document",
39 LoadErrorKind::Unsupported => "unsupported schema construct",
40 LoadErrorKind::Invalid => "invalid schema",
41 };
42 write!(f, "{}:{}: {kind}: {}", self.file, self.line, self.message)
43 }
44}
45
46impl std::error::Error for LoadError {}
47
48/// Why a document could not be validated at all.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum DocumentError {
51 /// The document is not well-formed (namespace-well-formed) XML.
52 Malformed {
53 /// 1-based line.
54 line: u32,
55 /// 1-based column.
56 column: u32,
57 /// The parser's message.
58 message: String,
59 },
60 /// The document needs a feature outside the subset this crate implements (an
61 /// encoding other than UTF-8, or `xsi:type` naming a built-in type the UBL
62 /// schemas do not use). Refused rather than answered wrongly.
63 Unsupported {
64 /// 1-based line.
65 line: u32,
66 /// 1-based column.
67 column: u32,
68 /// What is not supported.
69 message: String,
70 },
71}
72
73impl fmt::Display for DocumentError {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 match self {
76 Self::Malformed {
77 line,
78 column,
79 message,
80 } => {
81 write!(f, "{line}:{column}: malformed document: {message}")
82 }
83 Self::Unsupported {
84 line,
85 column,
86 message,
87 } => {
88 write!(f, "{line}:{column}: unsupported: {message}")
89 }
90 }
91 }
92}
93
94impl std::error::Error for DocumentError {}
95
96/// The kind of a [`ValidationError`]. The set and the names of [`ErrorKind::as_str`]
97/// are stable.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
99pub enum ErrorKind {
100 /// The document element has no global element declaration (cvc-elt.1).
101 UnknownRoot,
102 /// A child element is not allowed here by the content model (cvc-complex-type.2.4).
103 UnexpectedElement,
104 /// The content model needs more child elements (cvc-complex-type.2.4).
105 MissingElement,
106 /// Non-whitespace text in element-only content (cvc-complex-type.2.3).
107 TextNotAllowed,
108 /// A child element where the type has simple content (cvc-complex-type.2.2,
109 /// cvc-type.3.1.2).
110 ElementInSimpleContent,
111 /// Text (even whitespace) or a child element where the content type is empty
112 /// (cvc-complex-type.2.1).
113 ContentNotEmpty,
114 /// An element matched by a strict wildcard has no global declaration
115 /// (cvc-wildcard, cvc-assess-elt).
116 UndeclaredElement,
117 /// An attribute matched by a strict attribute wildcard has no global
118 /// declaration (cvc-complex-type.3.2.2).
119 UndeclaredAttribute,
120 /// An attribute the type does not allow (cvc-complex-type.3.2).
121 AttributeNotAllowed,
122 /// A required attribute is absent (cvc-complex-type.4).
123 MissingAttribute,
124 /// The text of an element is not a valid value of its simple type (cvc-type.3.1.3,
125 /// cvc-complex-type.2.2).
126 InvalidValue,
127 /// An attribute value is not valid for its type (cvc-attribute.3).
128 InvalidAttributeValue,
129 /// An `xs:ID` value already used by an earlier attribute of the document (cvc-id.2).
130 DuplicateId,
131 /// `xsi:type` is not a `QName`, does not resolve to a type, or names a type not
132 /// validly derived from the declared type (cvc-elt.4).
133 InvalidXsiType,
134 /// The type of the element is abstract (cvc-elt.2, cvc-type.2).
135 AbstractType,
136 /// `xsi:nil` on an element whose declaration is not nillable (cvc-elt.3.1).
137 NotNillable,
138 /// `xsi:nil` with a value that is not a boolean (cvc-elt.3).
139 InvalidXsiNil,
140}
141
142impl ErrorKind {
143 /// A stable identifier of the kind.
144 #[must_use]
145 pub fn as_str(self) -> &'static str {
146 match self {
147 Self::UnknownRoot => "unknown-root",
148 Self::UnexpectedElement => "unexpected-element",
149 Self::MissingElement => "missing-element",
150 Self::TextNotAllowed => "text-not-allowed",
151 Self::ElementInSimpleContent => "element-in-simple-content",
152 Self::ContentNotEmpty => "content-not-empty",
153 Self::UndeclaredElement => "undeclared-element",
154 Self::UndeclaredAttribute => "undeclared-attribute",
155 Self::AttributeNotAllowed => "attribute-not-allowed",
156 Self::MissingAttribute => "missing-attribute",
157 Self::InvalidValue => "invalid-value",
158 Self::InvalidAttributeValue => "invalid-attribute-value",
159 Self::DuplicateId => "duplicate-id",
160 Self::InvalidXsiType => "invalid-xsi-type",
161 Self::AbstractType => "abstract-type",
162 Self::NotNillable => "not-nillable",
163 Self::InvalidXsiNil => "invalid-xsi-nil",
164 }
165 }
166}
167
168impl fmt::Display for ErrorKind {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 f.write_str(self.as_str())
171 }
172}
173
174/// One validity error of a document.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct ValidationError {
177 /// What is wrong.
178 pub kind: ErrorKind,
179 /// 1-based line of the start tag of the element concerned.
180 pub line: u32,
181 /// 1-based column (in characters) of that start tag.
182 pub column: u32,
183 /// The element concerned, in Clark notation (`{namespace}local`).
184 pub element: String,
185 /// The attribute concerned, in Clark notation, for errors about one attribute
186 /// (including `xsi:type` and `xsi:nil`).
187 pub attribute: Option<String>,
188 /// A description, naming the attribute, value or expected elements involved.
189 pub message: String,
190}
191
192impl fmt::Display for ValidationError {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 write!(
195 f,
196 "{}:{}: {}: element {}",
197 self.line, self.column, self.kind, self.element
198 )?;
199 if let Some(attribute) = &self.attribute {
200 write!(f, ", attribute {attribute}")?;
201 }
202 write!(f, ": {}", self.message)
203 }
204}
205
206/// The result of validating a document: its validity errors, sorted by the position
207/// of the element they concern; errors of the same element in the order they were
208/// found (`xsi:nil`, `xsi:type`, attributes, content).
209#[derive(Debug, Clone, PartialEq, Eq, Default)]
210pub struct Report {
211 /// Every validity error; empty when the document is valid.
212 pub errors: Vec<ValidationError>,
213}
214
215impl Report {
216 /// Whether the document is schema-valid.
217 #[must_use]
218 pub fn is_valid(&self) -> bool {
219 self.errors.is_empty()
220 }
221}