Skip to main content

einvoice_validator/
error.rs

1//! The errors of loading a rule set and of validating a document.
2
3use std::fmt;
4use std::path::PathBuf;
5
6use einvoice_xpath_eval::LimitExceeded;
7
8/// Why a rule set could not be loaded, or a document could not be validated.
9///
10/// Validity problems of a document (schema errors, failed asserts) are not errors: they
11/// are in the [`Report`](crate::Report). An error means that no complete verdict could
12/// be given.
13#[derive(Debug)]
14#[non_exhaustive]
15pub enum Error {
16    /// A file could not be read.
17    Io {
18        /// The file.
19        path: PathBuf,
20        /// The cause.
21        source: std::io::Error,
22    },
23    /// The bundle is not usable: a manifest that does not follow the format, a missing
24    /// file, an unknown schema name, a stylesheet that is not well-formed XSLT, or one
25    /// whose result is not an SVRL report.
26    Bundle {
27        /// What is wrong, naming the file and line when known.
28        message: String,
29    },
30    /// A file of the bundle does not have the SHA-256 its manifest records.
31    Checksum {
32        /// The file, relative to the bundle.
33        path: String,
34        /// The SHA-256 the manifest records (lower-case hexadecimal).
35        expected: String,
36        /// The SHA-256 of the file.
37        actual: String,
38    },
39    /// The document is not well-formed XML (or not namespace-well-formed, or with bytes
40    /// that are not characters of its encoding, or first bytes and an XML declaration
41    /// that name different encodings).
42    NotXml {
43        /// 1-based line.
44        line: u32,
45        /// 1-based column.
46        column: u32,
47        /// The parser's message.
48        message: String,
49    },
50    /// The document or a rule-set artefact needs a construct that this engine does not
51    /// implement (an encoding the validator does not read, a document type declaration,
52    /// an XSLT or
53    /// XML Schema construct outside the supported subset). Refused rather than answered
54    /// differently from the reference engine.
55    Unsupported {
56        /// What is not supported, and where.
57        message: String,
58    },
59    /// The document exceeds a limit that keeps its validation within a bounded call
60    /// stack: an element nested deeper than [`ValidateOptions::max_depth`]
61    /// ([`LimitExceeded::Depth`]), in the document or in a document a stylesheet loads
62    /// with `document()`; or a stylesheet invoking templates and functions one inside
63    /// another beyond the nesting that maximum allows ([`LimitExceeded::Nesting`]).
64    /// Refused rather than risking a stack overflow, which would abort the process.
65    ///
66    /// [`ValidateOptions::max_depth`]: crate::ValidateOptions::max_depth
67    Limit {
68        /// The limit exceeded, with its value and, for a depth, the line and column of
69        /// the element.
70        limit: LimitExceeded,
71        /// Where: the document, or the stylesheet (by its name in the bundle) and the
72        /// line of its instruction.
73        message: String,
74    },
75    /// An option of the validation beyond what this target allows: on WebAssembly, a
76    /// [`ValidateOptions::max_depth`] above [`WASM_MAX_DEPTH`] or a
77    /// [`ValidateOptions::max_stack`] above [`WASM_MAX_STACK`], for which the native stack
78    /// of the JavaScript engines has no room. Never on other targets.
79    ///
80    /// [`ValidateOptions::max_depth`]: crate::ValidateOptions::max_depth
81    /// [`ValidateOptions::max_stack`]: crate::ValidateOptions::max_stack
82    /// [`WASM_MAX_DEPTH`]: crate::WASM_MAX_DEPTH
83    /// [`WASM_MAX_STACK`]: crate::WASM_MAX_STACK
84    OptionOutOfRange {
85        /// The option: `max_depth` or `max_stack`.
86        option: &'static str,
87        /// The value asked for.
88        value: u32,
89        /// The largest value allowed.
90        max: u32,
91    },
92    /// A stylesheet of the rule set raised a dynamic error on the document (the
93    /// reference engine fails on it as well).
94    Transform {
95        /// The stylesheet, by its name in the bundle.
96        stylesheet: String,
97        /// The XPath or XSLT error code (`FORG0001`, ...).
98        code: String,
99        /// The line of the stylesheet instruction, when known.
100        line: Option<u32>,
101        /// The explanation.
102        message: String,
103    },
104    /// A bug of this engine: a result it cannot read back.
105    Internal {
106        /// What went wrong.
107        message: String,
108    },
109    /// A fetched rule set ([`fetched_rule_sets`](crate::fetched_rule_sets)) that is not
110    /// in the cache: it must be fetched first (`RuleSetCache::fetch`, feature `fetch`;
111    /// `einvoice-validate rules fetch NAME`). Nothing is downloaded without being asked.
112    NotCached {
113        /// The rule set.
114        name: String,
115        /// The cache directory.
116        dir: PathBuf,
117    },
118    /// A rule set could not be fetched: a download failed or did not have its pinned
119    /// digest, an archive is not as published, or its bundle could not be built (no
120    /// Java for the Schematron compiler of Peppol BIS Billing, ...).
121    Fetch {
122        /// What went wrong, naming the URL or file concerned.
123        message: String,
124    },
125    /// No invoice XML could be extracted from a PDF file ([`crate::pdf::extract`]): its
126    /// kind is [`ErrorKind::Unsupported`] for an encrypted file, a PDF feature outside the
127    /// subset read or a limit exceeded, and [`ErrorKind::Io`] otherwise (not a PDF, a
128    /// malformed file, no embedded file with an invoice name or several, XMP metadata
129    /// that is not well-formed): the file cannot be read as an e-invoice.
130    #[cfg(feature = "pdf")]
131    Pdf(einvoice_pdf::Error),
132}
133
134/// The kind of an [`Error`], for callers that only need to classify it (the exit code of
135/// a command-line tool, ...).
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
137#[non_exhaustive]
138pub enum ErrorKind {
139    /// [`Error::Io`] and [`Error::Fetch`], and an `Error::Pdf` (feature `pdf`) for a PDF
140    /// file no invoice can be read from.
141    Io,
142    /// [`Error::Bundle`], [`Error::Checksum`] and [`Error::NotCached`].
143    Bundle,
144    /// [`Error::NotXml`].
145    NotXml,
146    /// [`Error::Unsupported`], [`Error::Limit`] and [`Error::OptionOutOfRange`]: input
147    /// refused rather than processed differently from the reference engine, or with an
148    /// unbounded stack, and options beyond what the target allows; and
149    /// an `Error::Pdf` (feature `pdf`) for an encrypted PDF file, a PDF feature outside
150    /// the subset read, or a limit of the PDF reader.
151    Unsupported,
152    /// [`Error::Transform`].
153    Transform,
154    /// [`Error::Internal`].
155    Internal,
156}
157
158impl ErrorKind {
159    /// A stable identifier of the kind: `io`, `bundle`, `not-xml`, `unsupported`,
160    /// `transform` or `internal`.
161    #[must_use]
162    pub const fn as_str(self) -> &'static str {
163        match self {
164            Self::Io => "io",
165            Self::Bundle => "bundle",
166            Self::NotXml => "not-xml",
167            Self::Unsupported => "unsupported",
168            Self::Transform => "transform",
169            Self::Internal => "internal",
170        }
171    }
172}
173
174impl fmt::Display for ErrorKind {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        f.write_str(self.as_str())
177    }
178}
179
180impl Error {
181    /// The kind of the error.
182    #[must_use]
183    pub const fn kind(&self) -> ErrorKind {
184        match self {
185            Self::Io { .. } | Self::Fetch { .. } => ErrorKind::Io,
186            Self::Bundle { .. } | Self::Checksum { .. } | Self::NotCached { .. } => {
187                ErrorKind::Bundle
188            }
189            Self::NotXml { .. } => ErrorKind::NotXml,
190            Self::Unsupported { .. } | Self::Limit { .. } | Self::OptionOutOfRange { .. } => {
191                ErrorKind::Unsupported
192            }
193            Self::Transform { .. } => ErrorKind::Transform,
194            Self::Internal { .. } => ErrorKind::Internal,
195            #[cfg(feature = "pdf")]
196            Self::Pdf(
197                einvoice_pdf::Error::Encrypted
198                | einvoice_pdf::Error::Unsupported { .. }
199                | einvoice_pdf::Error::LimitExceeded { .. },
200            ) => ErrorKind::Unsupported,
201            #[cfg(feature = "pdf")]
202            Self::Pdf(_) => ErrorKind::Io,
203        }
204    }
205
206    pub(crate) fn bundle(message: impl Into<String>) -> Self {
207        Self::Bundle {
208            message: message.into(),
209        }
210    }
211
212    pub(crate) fn unsupported(message: impl Into<String>) -> Self {
213        Self::Unsupported {
214            message: message.into(),
215        }
216    }
217
218    pub(crate) fn internal(message: impl Into<String>) -> Self {
219        Self::Internal {
220            message: message.into(),
221        }
222    }
223}
224
225impl fmt::Display for Error {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        match self {
228            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
229            Self::Bundle { message } => write!(f, "invalid rule-set bundle: {message}"),
230            Self::Checksum {
231                path,
232                expected,
233                actual,
234            } => write!(
235                f,
236                "invalid rule-set bundle: {path}: SHA-256 {actual}, the manifest records {expected}"
237            ),
238            Self::NotXml {
239                line,
240                column,
241                message,
242            } => write!(f, "{line}:{column}: not well-formed XML: {message}"),
243            Self::Unsupported { message } => write!(f, "unsupported: {message}"),
244            Self::Limit { message, .. } => write!(f, "limit exceeded: {message}"),
245            Self::OptionOutOfRange { option, value, max } => write!(
246                f,
247                "option {option} is {value}, more than {max}, the most this target allows"
248            ),
249            Self::Transform {
250                stylesheet,
251                code,
252                line,
253                message,
254            } => {
255                write!(f, "stylesheet {stylesheet}")?;
256                if let Some(line) = line {
257                    write!(f, ", line {line}")?;
258                }
259                write!(f, ": {code}: {message}")
260            }
261            Self::Internal { message } => write!(f, "internal error: {message}"),
262            Self::NotCached { name, dir } => write!(
263                f,
264                "rule set {name} is not in the cache ({}): it must be fetched first",
265                dir.display()
266            ),
267            Self::Fetch { message } => write!(f, "cannot fetch the rule set: {message}"),
268            #[cfg(feature = "pdf")]
269            Self::Pdf(error) => error.fmt(f),
270        }
271    }
272}
273
274impl std::error::Error for Error {
275    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
276        match self {
277            Self::Io { source, .. } => Some(source),
278            #[cfg(feature = "pdf")]
279            Self::Pdf(error) => Some(error),
280            _ => None,
281        }
282    }
283}