Skip to main content

einvoice_xml/
error.rs

1//! Well-formedness errors and their positions.
2
3use std::fmt;
4
5/// A position in the text: 1-based row (lines are counted by line feeds) and 1-based
6/// column (counted in characters from the last line feed).
7#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
8pub struct TextPos {
9    /// The line, from 1.
10    pub row: u32,
11    /// The character in the line, from 1.
12    pub col: u32,
13}
14
15impl TextPos {
16    /// A position from its row and column.
17    #[must_use]
18    pub const fn new(row: u32, col: u32) -> Self {
19        Self { row, col }
20    }
21
22    /// The position of the byte `offset` of `text` (an offset past the end is taken as
23    /// the end). Linear in `offset`: meant for errors, not for every event.
24    #[must_use]
25    pub fn at(text: &str, offset: usize) -> Self {
26        let before = text.as_bytes().get(..offset).unwrap_or(text.as_bytes());
27        let line_start = memchr::memrchr(b'\n', before).map_or(0, |i| i + 1);
28        let rows = memchr::memchr_iter(b'\n', before).count();
29        let cols = before[line_start..]
30            .iter()
31            .filter(|&&b| b & 0xC0 != 0x80)
32            .count();
33        Self {
34            row: saturating_u32(rows.saturating_add(1)),
35            col: saturating_u32(cols.saturating_add(1)),
36        }
37    }
38}
39
40fn saturating_u32(n: usize) -> u32 {
41    u32::try_from(n).unwrap_or(u32::MAX)
42}
43
44impl fmt::Display for TextPos {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(f, "{}:{}", self.row, self.col)
47    }
48}
49
50/// Why a text is not a document the reader accepts.
51///
52/// The variants before [`Error::InvalidCharacterReference`] are reported for the same
53/// documents, at the same positions and with the same messages as the `roxmltree` crate
54/// (version 0.21, with document type declarations refused) reports them. The variants
55/// from [`Error::InvalidCharacterReference`] on are for documents that `roxmltree`
56/// accepts although they are not well-formed (XML 1.0) or not namespace-well-formed
57/// (Namespaces in XML 1.0), and for the limits that it does not have; the crate
58/// documentation lists them.
59#[derive(Clone, PartialEq, Eq, Hash, Debug)]
60#[non_exhaustive]
61pub enum Error {
62    /// `xmlns:xml` declares a namespace other than
63    /// `http://www.w3.org/XML/1998/namespace`.
64    InvalidXmlPrefixUri(TextPos),
65    /// The `http://www.w3.org/XML/1998/namespace` namespace is declared for a prefix
66    /// other than `xml`, or as the default namespace.
67    UnexpectedXmlUri(TextPos),
68    /// The `http://www.w3.org/2000/xmlns/` namespace is declared.
69    UnexpectedXmlnsUri(TextPos),
70    /// An element name with the `xmlns` prefix.
71    InvalidElementNamePrefix(TextPos),
72    /// The same prefix is declared twice on an element.
73    DuplicatedNamespace(String, TextPos),
74    /// An element or attribute name whose prefix is not declared (the prefix).
75    UnknownNamespace(String, TextPos),
76    /// An end tag that does not match the open element.
77    UnexpectedCloseTag {
78        /// The name of the open element, as written.
79        expected: String,
80        /// The name in the end tag.
81        actual: String,
82        /// Where the end tag starts.
83        pos: TextPos,
84    },
85    /// A reference to an entity other than the five predefined ones (its name).
86    UnknownEntityReference(String, TextPos),
87    /// An `&` that does not start a well-formed reference to an XML character.
88    MalformedEntityReference(TextPos),
89    /// Two attributes of an element with the same expanded name (the local name).
90    DuplicatedAttribute(String, TextPos),
91    /// No element.
92    NoRootNode,
93    /// The text ends before the document element is closed.
94    UnclosedRootNode,
95    /// An XML declaration elsewhere than at the start of the text.
96    UnexpectedDeclaration(TextPos),
97    /// A document type declaration: refused, because its entities and attribute
98    /// defaults could change the document.
99    DtdDetected,
100    /// More nodes than [`crate::Limits::nodes`].
101    NodesLimitReached,
102    /// More attributes than [`crate::Limits::attributes`].
103    AttributesLimitReached,
104    /// More distinct namespace declarations than [`crate::Limits::namespaces`].
105    NamespacesLimitReached,
106    /// A name that is not a name.
107    InvalidName(TextPos),
108    /// A character that XML does not allow.
109    NonXmlChar(char, TextPos),
110    /// A byte other than the one expected.
111    InvalidChar {
112        /// The byte expected.
113        expected: u8,
114        /// The byte found.
115        actual: u8,
116        /// Where.
117        pos: TextPos,
118    },
119    /// A byte other than one of a class expected (described in words).
120    ExpectedChar {
121        /// What was expected.
122        expected: &'static str,
123        /// The byte found.
124        actual: u8,
125        /// Where.
126        pos: TextPos,
127    },
128    /// The string expected is missing.
129    InvalidString(&'static str, TextPos),
130    /// A comment that contains `--` or ends with `-` (the position of the comment).
131    InvalidComment(TextPos),
132    /// `]]>` in character data (the position of the end of the text).
133    InvalidCharacterData(TextPos),
134    /// Something that is not markup where markup is expected.
135    UnknownToken(TextPos),
136    /// The text ends in the middle of markup.
137    UnexpectedEndOfStream,
138    /// A character reference to a code point that is not a Unicode scalar value (a
139    /// surrogate or a number above `0x10FFFF`).
140    InvalidCharacterReference(TextPos),
141    /// A processing instruction target that is `xml` in any case or contains `:`.
142    InvalidPiTarget(TextPos),
143    /// A processing instruction without whitespace between its target and its data.
144    PiWithoutWhitespace(TextPos),
145    /// An XML declaration with a pseudo-attribute that is not `version`, `encoding` or
146    /// `standalone` as written, or with an invalid value (the reason).
147    InvalidXmlDeclaration(&'static str, TextPos),
148    /// A name that starts with `:`, which is not a qualified name.
149    InvalidQName(TextPos),
150    /// A prefix declared with an empty namespace name (the prefix).
151    EmptyPrefixedNamespace(String, TextPos),
152    /// A declaration of the `xmlns` prefix.
153    XmlnsPrefixDeclared(TextPos),
154    /// The default namespace (`xmlns`) or the `xml` prefix (`xmlns:xml`) declared twice
155    /// on an element (the attribute name).
156    DuplicatedNamespaceDeclaration(String, TextPos),
157    /// An attribute whose local name is `xmlns` and which has a prefix (its name).
158    PrefixedXmlnsAttribute(String, TextPos),
159    /// Elements nested deeper than [`crate::Limits::depth`].
160    DepthLimitReached,
161}
162
163impl Error {
164    /// The position of the error; `1:1` for the errors that have none.
165    #[must_use]
166    pub fn pos(&self) -> TextPos {
167        match self {
168            Self::InvalidXmlPrefixUri(pos)
169            | Self::UnexpectedXmlUri(pos)
170            | Self::UnexpectedXmlnsUri(pos)
171            | Self::InvalidElementNamePrefix(pos)
172            | Self::DuplicatedNamespace(_, pos)
173            | Self::UnknownNamespace(_, pos)
174            | Self::UnexpectedCloseTag { pos, .. }
175            | Self::UnknownEntityReference(_, pos)
176            | Self::MalformedEntityReference(pos)
177            | Self::DuplicatedAttribute(_, pos)
178            | Self::UnexpectedDeclaration(pos)
179            | Self::InvalidName(pos)
180            | Self::NonXmlChar(_, pos)
181            | Self::InvalidChar { pos, .. }
182            | Self::ExpectedChar { pos, .. }
183            | Self::InvalidString(_, pos)
184            | Self::InvalidComment(pos)
185            | Self::InvalidCharacterData(pos)
186            | Self::UnknownToken(pos)
187            | Self::InvalidCharacterReference(pos)
188            | Self::InvalidPiTarget(pos)
189            | Self::PiWithoutWhitespace(pos)
190            | Self::InvalidXmlDeclaration(_, pos)
191            | Self::InvalidQName(pos)
192            | Self::EmptyPrefixedNamespace(_, pos)
193            | Self::XmlnsPrefixDeclared(pos)
194            | Self::DuplicatedNamespaceDeclaration(_, pos)
195            | Self::PrefixedXmlnsAttribute(_, pos) => *pos,
196            Self::NoRootNode
197            | Self::UnclosedRootNode
198            | Self::DtdDetected
199            | Self::NodesLimitReached
200            | Self::AttributesLimitReached
201            | Self::NamespacesLimitReached
202            | Self::UnexpectedEndOfStream
203            | Self::DepthLimitReached => TextPos::new(1, 1),
204        }
205    }
206}
207
208impl fmt::Display for Error {
209    #[expect(clippy::too_many_lines, reason = "one message per error, in one place")]
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        match self {
212            Self::InvalidXmlPrefixUri(pos) => {
213                write!(f, "'xml' namespace prefix mapped to wrong URI at {pos}")
214            }
215            Self::UnexpectedXmlUri(pos) => write!(
216                f,
217                "the 'xml' namespace URI is used for not 'xml' prefix at {pos}"
218            ),
219            Self::UnexpectedXmlnsUri(pos) => write!(
220                f,
221                "the 'xmlns' URI is used at {pos}, but it must not be declared"
222            ),
223            Self::InvalidElementNamePrefix(pos) => {
224                write!(f, "the 'xmlns' prefix is used at {pos}, but it must not be")
225            }
226            Self::DuplicatedNamespace(name, pos) => {
227                write!(f, "namespace '{name}' at {pos} is already defined")
228            }
229            Self::UnknownNamespace(name, pos) => {
230                write!(f, "an unknown namespace prefix '{name}' at {pos}")
231            }
232            Self::UnexpectedCloseTag {
233                expected,
234                actual,
235                pos,
236            } => write!(f, "expected '{expected}' tag, not '{actual}' at {pos}"),
237            Self::UnknownEntityReference(name, pos) => {
238                write!(f, "unknown entity reference '{name}' at {pos}")
239            }
240            Self::MalformedEntityReference(pos) => {
241                write!(f, "malformed entity reference at {pos}")
242            }
243            Self::DuplicatedAttribute(name, pos) => {
244                write!(f, "attribute '{name}' at {pos} is already defined")
245            }
246            Self::NoRootNode => f.write_str("the document does not have a root node"),
247            Self::UnclosedRootNode => f.write_str("the root node was opened but never closed"),
248            Self::UnexpectedDeclaration(pos) => write!(f, "unexpected XML declaration at {pos}"),
249            Self::DtdDetected => f.write_str("XML with DTD detected"),
250            Self::NodesLimitReached => f.write_str("nodes limit reached"),
251            Self::AttributesLimitReached => f.write_str("more than 2^32 attributes were parsed"),
252            Self::NamespacesLimitReached => {
253                f.write_str("more than 2^16 unique namespaces were parsed")
254            }
255            Self::InvalidName(pos) => write!(f, "invalid name token at {pos}"),
256            Self::NonXmlChar(c, pos) => write!(f, "a non-XML character {c:?} found at {pos}"),
257            Self::InvalidChar {
258                expected,
259                actual,
260                pos,
261            } => write!(
262                f,
263                "expected '{}' not '{}' at {pos}",
264                char::from(*expected),
265                char::from(*actual)
266            ),
267            Self::ExpectedChar {
268                expected,
269                actual,
270                pos,
271            } => write!(
272                f,
273                "expected {expected} not '{}' at {pos}",
274                char::from(*actual)
275            ),
276            Self::InvalidString(expected, pos) => write!(f, "expected '{expected}' at {pos}"),
277            Self::InvalidComment(pos) => write!(f, "comment at {pos} contains '--'"),
278            Self::InvalidCharacterData(pos) => {
279                write!(f, "']]>' at {pos} is not allowed inside a character data")
280            }
281            Self::UnknownToken(pos) => write!(f, "unknown token at {pos}"),
282            Self::UnexpectedEndOfStream => f.write_str("unexpected end of stream"),
283            Self::InvalidCharacterReference(pos) => write!(
284                f,
285                "the character reference at {pos} is not a Unicode scalar value"
286            ),
287            Self::InvalidPiTarget(pos) => write!(
288                f,
289                "the processing instruction target at {pos} is reserved or contains ':'"
290            ),
291            Self::PiWithoutWhitespace(pos) => write!(
292                f,
293                "expected a whitespace between the processing instruction target and its data at {pos}"
294            ),
295            Self::InvalidXmlDeclaration(reason, pos) => {
296                write!(f, "invalid XML declaration at {pos}: {reason}")
297            }
298            Self::InvalidQName(pos) => write!(f, "a name with an empty prefix at {pos}"),
299            Self::EmptyPrefixedNamespace(prefix, pos) => write!(
300                f,
301                "the prefix '{prefix}' at {pos} is bound to an empty namespace name"
302            ),
303            Self::XmlnsPrefixDeclared(pos) => {
304                write!(
305                    f,
306                    "the 'xmlns' prefix is declared at {pos}, but it must not be"
307                )
308            }
309            Self::DuplicatedNamespaceDeclaration(name, pos) => {
310                write!(
311                    f,
312                    "namespace declaration '{name}' at {pos} is already defined"
313                )
314            }
315            Self::PrefixedXmlnsAttribute(name, pos) => write!(
316                f,
317                "attribute '{name}' at {pos}: a prefixed attribute named 'xmlns' is not supported"
318            ),
319            Self::DepthLimitReached => f.write_str("elements nested deeper than the limit"),
320        }
321    }
322}
323
324impl std::error::Error for Error {}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    #[test]
331    fn positions_count_lines_and_characters() {
332        let text = "ab\n\u{e9}cd\r\nx";
333        assert_eq!(TextPos::at(text, 0), TextPos::new(1, 1));
334        assert_eq!(TextPos::at(text, 2), TextPos::new(1, 3));
335        assert_eq!(TextPos::at(text, 3), TextPos::new(2, 1));
336        assert_eq!(TextPos::at(text, 5), TextPos::new(2, 2));
337        // A carriage return is a character of the line; only line feeds end lines.
338        assert_eq!(TextPos::at(text, 8), TextPos::new(2, 5));
339        assert_eq!(TextPos::at(text, 9), TextPos::new(3, 1));
340        assert_eq!(TextPos::at(text, 1000), TextPos::new(3, 2));
341        assert_eq!(TextPos::new(3, 7).to_string(), "3:7");
342    }
343}