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 UTF-8, or not namespace-well-formed).
40    NotXml {
41        /// 1-based line.
42        line: u32,
43        /// 1-based column.
44        column: u32,
45        /// The parser's message.
46        message: String,
47    },
48    /// The document or a rule-set artefact needs a construct that this engine does not
49    /// implement (an encoding other than UTF-8, a document type declaration, an XSLT or
50    /// XML Schema construct outside the supported subset). Refused rather than answered
51    /// differently from the reference engine.
52    Unsupported {
53        /// What is not supported, and where.
54        message: String,
55    },
56    /// The document exceeds a limit that keeps its validation within a bounded call
57    /// stack: an element nested deeper than [`ValidateOptions::max_depth`]
58    /// ([`LimitExceeded::Depth`]), in the document or in a document a stylesheet loads
59    /// with `document()`; or a stylesheet invoking templates and functions one inside
60    /// another beyond the nesting that maximum allows ([`LimitExceeded::Nesting`]).
61    /// Refused rather than risking a stack overflow, which would abort the process.
62    ///
63    /// [`ValidateOptions::max_depth`]: crate::ValidateOptions::max_depth
64    Limit {
65        /// The limit exceeded, with its value and, for a depth, the line and column of
66        /// the element.
67        limit: LimitExceeded,
68        /// Where: the document, or the stylesheet (by its name in the bundle) and the
69        /// line of its instruction.
70        message: String,
71    },
72    /// A stylesheet of the rule set raised a dynamic error on the document (the
73    /// reference engine fails on it as well).
74    Transform {
75        /// The stylesheet, by its name in the bundle.
76        stylesheet: String,
77        /// The XPath or XSLT error code (`FORG0001`, ...).
78        code: String,
79        /// The line of the stylesheet instruction, when known.
80        line: Option<u32>,
81        /// The explanation.
82        message: String,
83    },
84    /// A bug of this engine: a result it cannot read back.
85    Internal {
86        /// What went wrong.
87        message: String,
88    },
89}
90
91/// The kind of an [`Error`], for callers that only need to classify it (the exit code of
92/// a command-line tool, ...).
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94#[non_exhaustive]
95pub enum ErrorKind {
96    /// [`Error::Io`].
97    Io,
98    /// [`Error::Bundle`] and [`Error::Checksum`].
99    Bundle,
100    /// [`Error::NotXml`].
101    NotXml,
102    /// [`Error::Unsupported`] and [`Error::Limit`]: input refused rather than
103    /// processed differently from the reference engine, or with an unbounded stack.
104    Unsupported,
105    /// [`Error::Transform`].
106    Transform,
107    /// [`Error::Internal`].
108    Internal,
109}
110
111impl ErrorKind {
112    /// A stable identifier of the kind: `io`, `bundle`, `not-xml`, `unsupported`,
113    /// `transform` or `internal`.
114    #[must_use]
115    pub const fn as_str(self) -> &'static str {
116        match self {
117            Self::Io => "io",
118            Self::Bundle => "bundle",
119            Self::NotXml => "not-xml",
120            Self::Unsupported => "unsupported",
121            Self::Transform => "transform",
122            Self::Internal => "internal",
123        }
124    }
125}
126
127impl fmt::Display for ErrorKind {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.write_str(self.as_str())
130    }
131}
132
133impl Error {
134    /// The kind of the error.
135    #[must_use]
136    pub const fn kind(&self) -> ErrorKind {
137        match self {
138            Self::Io { .. } => ErrorKind::Io,
139            Self::Bundle { .. } | Self::Checksum { .. } => ErrorKind::Bundle,
140            Self::NotXml { .. } => ErrorKind::NotXml,
141            Self::Unsupported { .. } | Self::Limit { .. } => ErrorKind::Unsupported,
142            Self::Transform { .. } => ErrorKind::Transform,
143            Self::Internal { .. } => ErrorKind::Internal,
144        }
145    }
146
147    pub(crate) fn bundle(message: impl Into<String>) -> Self {
148        Self::Bundle {
149            message: message.into(),
150        }
151    }
152
153    pub(crate) fn unsupported(message: impl Into<String>) -> Self {
154        Self::Unsupported {
155            message: message.into(),
156        }
157    }
158
159    pub(crate) fn internal(message: impl Into<String>) -> Self {
160        Self::Internal {
161            message: message.into(),
162        }
163    }
164}
165
166impl fmt::Display for Error {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        match self {
169            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
170            Self::Bundle { message } => write!(f, "invalid rule-set bundle: {message}"),
171            Self::Checksum {
172                path,
173                expected,
174                actual,
175            } => write!(
176                f,
177                "invalid rule-set bundle: {path}: SHA-256 {actual}, the manifest records {expected}"
178            ),
179            Self::NotXml {
180                line,
181                column,
182                message,
183            } => write!(f, "{line}:{column}: not well-formed XML: {message}"),
184            Self::Unsupported { message } => write!(f, "unsupported: {message}"),
185            Self::Limit { message, .. } => write!(f, "limit exceeded: {message}"),
186            Self::Transform {
187                stylesheet,
188                code,
189                line,
190                message,
191            } => {
192                write!(f, "stylesheet {stylesheet}")?;
193                if let Some(line) = line {
194                    write!(f, ", line {line}")?;
195                }
196                write!(f, ": {code}: {message}")
197            }
198            Self::Internal { message } => write!(f, "internal error: {message}"),
199        }
200    }
201}
202
203impl std::error::Error for Error {
204    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
205        match self {
206            Self::Io { source, .. } => Some(source),
207            _ => None,
208        }
209    }
210}