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 that [`einvoice_xml::decode`] does not read, an `xs:ENTITY` value in a
62 /// document with a document type declaration, whose unparsed entities this crate
63 /// does not read, or a value constraint of a declaration taken as a value of a
64 /// type valid only in a context, such as `xs:QName`). Refused rather than answered
65 /// wrongly.
66 Unsupported {
67 /// 1-based line.
68 line: u32,
69 /// 1-based column.
70 column: u32,
71 /// What is not supported.
72 message: String,
73 },
74}
75
76impl fmt::Display for DocumentError {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 match self {
79 Self::Malformed {
80 line,
81 column,
82 message,
83 } => {
84 write!(f, "{line}:{column}: malformed document: {message}")
85 }
86 Self::Unsupported {
87 line,
88 column,
89 message,
90 } => {
91 write!(f, "{line}:{column}: unsupported: {message}")
92 }
93 }
94 }
95}
96
97impl std::error::Error for DocumentError {}
98
99/// The kind of a [`ValidationError`]. The set and the names of [`ErrorKind::as_str`]
100/// are stable.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
102pub enum ErrorKind {
103 /// The document element has no global element declaration (cvc-elt.1).
104 UnknownRoot,
105 /// A child element is not allowed here by the content model (cvc-complex-type.2.4).
106 UnexpectedElement,
107 /// The content model needs more child elements (cvc-complex-type.2.4).
108 MissingElement,
109 /// Non-whitespace text in element-only content (cvc-complex-type.2.3).
110 TextNotAllowed,
111 /// A child element where the type has simple content (cvc-complex-type.2.2,
112 /// cvc-type.3.1.2).
113 ElementInSimpleContent,
114 /// Text (even whitespace) or a child element where the content type is empty
115 /// (cvc-complex-type.2.1).
116 ContentNotEmpty,
117 /// An element matched by a strict wildcard has no global declaration
118 /// (cvc-wildcard, cvc-assess-elt).
119 UndeclaredElement,
120 /// An attribute matched by a strict attribute wildcard has no global
121 /// declaration (cvc-complex-type.3.2.2).
122 UndeclaredAttribute,
123 /// An attribute the type does not allow (cvc-complex-type.3.2).
124 AttributeNotAllowed,
125 /// A required attribute is absent (cvc-complex-type.4).
126 MissingAttribute,
127 /// The text of an element is not a valid value of its simple type (cvc-type.3.1.3,
128 /// cvc-complex-type.2.2).
129 InvalidValue,
130 /// An attribute value is not valid for its type (cvc-attribute.3).
131 InvalidAttributeValue,
132 /// An `xs:ID` value already used by an earlier attribute of the document (cvc-id.2).
133 DuplicateId,
134 /// An `xs:IDREF` value (or an item of an `xs:IDREFS`) that is not the value of an
135 /// `xs:ID` of the document (cvc-id.1).
136 UnresolvedIdref,
137 /// `xsi:type` is not a `QName`, does not resolve to a type, or names a type not
138 /// validly derived from the declared type (cvc-elt.4).
139 InvalidXsiType,
140 /// The type of the element is abstract (cvc-elt.2, cvc-type.2).
141 AbstractType,
142 /// `xsi:nil` on an element whose declaration is not nillable (cvc-elt.3.1).
143 NotNillable,
144 /// `xsi:nil` with a value that is not a boolean (cvc-elt.3).
145 InvalidXsiNil,
146}
147
148impl ErrorKind {
149 /// A stable identifier of the kind.
150 #[must_use]
151 pub fn as_str(self) -> &'static str {
152 match self {
153 Self::UnknownRoot => "unknown-root",
154 Self::UnexpectedElement => "unexpected-element",
155 Self::MissingElement => "missing-element",
156 Self::TextNotAllowed => "text-not-allowed",
157 Self::ElementInSimpleContent => "element-in-simple-content",
158 Self::ContentNotEmpty => "content-not-empty",
159 Self::UndeclaredElement => "undeclared-element",
160 Self::UndeclaredAttribute => "undeclared-attribute",
161 Self::AttributeNotAllowed => "attribute-not-allowed",
162 Self::MissingAttribute => "missing-attribute",
163 Self::InvalidValue => "invalid-value",
164 Self::InvalidAttributeValue => "invalid-attribute-value",
165 Self::DuplicateId => "duplicate-id",
166 Self::UnresolvedIdref => "unresolved-idref",
167 Self::InvalidXsiType => "invalid-xsi-type",
168 Self::AbstractType => "abstract-type",
169 Self::NotNillable => "not-nillable",
170 Self::InvalidXsiNil => "invalid-xsi-nil",
171 }
172 }
173}
174
175impl fmt::Display for ErrorKind {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 f.write_str(self.as_str())
178 }
179}
180
181/// One validity error of a document.
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct ValidationError {
184 /// What is wrong.
185 pub kind: ErrorKind,
186 /// 1-based line of the start tag of the element concerned.
187 pub line: u32,
188 /// 1-based column (in characters) of that start tag.
189 pub column: u32,
190 /// The element concerned, in Clark notation (`{namespace}local`).
191 pub element: String,
192 /// The attribute concerned, in Clark notation, for errors about one attribute
193 /// (including `xsi:type` and `xsi:nil`).
194 pub attribute: Option<String>,
195 /// A description, naming the attribute, value or expected elements involved.
196 pub message: String,
197}
198
199impl fmt::Display for ValidationError {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 write!(
202 f,
203 "{}:{}: {}: element {}",
204 self.line, self.column, self.kind, self.element
205 )?;
206 if let Some(attribute) = &self.attribute {
207 write!(f, ", attribute {attribute}")?;
208 }
209 write!(f, ": {}", self.message)
210 }
211}
212
213/// The result of validating a document: its validity errors, sorted by the position
214/// of the element they concern; errors of the same element in the order they were
215/// found (`xsi:nil`, `xsi:type`, attributes, content).
216#[derive(Debug, Clone, PartialEq, Eq, Default)]
217pub struct Report {
218 /// Every validity error; empty when the document is valid.
219 pub errors: Vec<ValidationError>,
220}
221
222impl Report {
223 /// Whether the document is schema-valid.
224 #[must_use]
225 pub fn is_valid(&self) -> bool {
226 self.errors.is_empty()
227 }
228}