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    /// A document in an encoding that [`decode`](crate::decode) does not read: the name
162    /// its XML declaration gives, or `UCS-4` or `EBCDIC` for a document whose first bytes
163    /// are in one of those.
164    UnsupportedEncoding(String),
165    /// The first bytes of a document (a byte order mark, or `<?` in UTF-16) and its XML
166    /// declaration name different encodings.
167    EncodingMismatch {
168        /// What the first bytes say.
169        found: &'static str,
170        /// The encoding the XML declaration names.
171        declared: String,
172    },
173    /// Bytes that are not a character in the encoding of the document.
174    InvalidEncodedBytes {
175        /// The encoding.
176        encoding: &'static str,
177        /// The position of the character they would be, in the decoded text.
178        pos: TextPos,
179    },
180}
181
182impl Error {
183    /// The position of the error; `1:1` for the errors that have none.
184    #[must_use]
185    pub fn pos(&self) -> TextPos {
186        match self {
187            Self::InvalidXmlPrefixUri(pos)
188            | Self::UnexpectedXmlUri(pos)
189            | Self::UnexpectedXmlnsUri(pos)
190            | Self::InvalidElementNamePrefix(pos)
191            | Self::DuplicatedNamespace(_, pos)
192            | Self::UnknownNamespace(_, pos)
193            | Self::UnexpectedCloseTag { pos, .. }
194            | Self::UnknownEntityReference(_, pos)
195            | Self::MalformedEntityReference(pos)
196            | Self::DuplicatedAttribute(_, pos)
197            | Self::UnexpectedDeclaration(pos)
198            | Self::InvalidName(pos)
199            | Self::NonXmlChar(_, pos)
200            | Self::InvalidChar { pos, .. }
201            | Self::ExpectedChar { pos, .. }
202            | Self::InvalidString(_, pos)
203            | Self::InvalidComment(pos)
204            | Self::InvalidCharacterData(pos)
205            | Self::UnknownToken(pos)
206            | Self::InvalidCharacterReference(pos)
207            | Self::InvalidPiTarget(pos)
208            | Self::PiWithoutWhitespace(pos)
209            | Self::InvalidXmlDeclaration(_, pos)
210            | Self::InvalidQName(pos)
211            | Self::EmptyPrefixedNamespace(_, pos)
212            | Self::XmlnsPrefixDeclared(pos)
213            | Self::DuplicatedNamespaceDeclaration(_, pos)
214            | Self::PrefixedXmlnsAttribute(_, pos)
215            | Self::InvalidEncodedBytes { pos, .. } => *pos,
216            Self::NoRootNode
217            | Self::UnclosedRootNode
218            | Self::DtdDetected
219            | Self::NodesLimitReached
220            | Self::AttributesLimitReached
221            | Self::NamespacesLimitReached
222            | Self::UnexpectedEndOfStream
223            | Self::DepthLimitReached
224            | Self::UnsupportedEncoding(_)
225            | Self::EncodingMismatch { .. } => TextPos::new(1, 1),
226        }
227    }
228}
229
230impl fmt::Display for Error {
231    #[expect(clippy::too_many_lines, reason = "one message per error, in one place")]
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        match self {
234            Self::InvalidXmlPrefixUri(pos) => {
235                write!(f, "'xml' namespace prefix mapped to wrong URI at {pos}")
236            }
237            Self::UnexpectedXmlUri(pos) => write!(
238                f,
239                "the 'xml' namespace URI is used for not 'xml' prefix at {pos}"
240            ),
241            Self::UnexpectedXmlnsUri(pos) => write!(
242                f,
243                "the 'xmlns' URI is used at {pos}, but it must not be declared"
244            ),
245            Self::InvalidElementNamePrefix(pos) => {
246                write!(f, "the 'xmlns' prefix is used at {pos}, but it must not be")
247            }
248            Self::DuplicatedNamespace(name, pos) => {
249                write!(f, "namespace '{name}' at {pos} is already defined")
250            }
251            Self::UnknownNamespace(name, pos) => {
252                write!(f, "an unknown namespace prefix '{name}' at {pos}")
253            }
254            Self::UnexpectedCloseTag {
255                expected,
256                actual,
257                pos,
258            } => write!(f, "expected '{expected}' tag, not '{actual}' at {pos}"),
259            Self::UnknownEntityReference(name, pos) => {
260                write!(f, "unknown entity reference '{name}' at {pos}")
261            }
262            Self::MalformedEntityReference(pos) => {
263                write!(f, "malformed entity reference at {pos}")
264            }
265            Self::DuplicatedAttribute(name, pos) => {
266                write!(f, "attribute '{name}' at {pos} is already defined")
267            }
268            Self::NoRootNode => f.write_str("the document does not have a root node"),
269            Self::UnclosedRootNode => f.write_str("the root node was opened but never closed"),
270            Self::UnexpectedDeclaration(pos) => write!(f, "unexpected XML declaration at {pos}"),
271            Self::DtdDetected => f.write_str("XML with DTD detected"),
272            Self::NodesLimitReached => f.write_str("nodes limit reached"),
273            Self::AttributesLimitReached => f.write_str("more than 2^32 attributes were parsed"),
274            Self::NamespacesLimitReached => {
275                f.write_str("more than 2^16 unique namespaces were parsed")
276            }
277            Self::InvalidName(pos) => write!(f, "invalid name token at {pos}"),
278            Self::NonXmlChar(c, pos) => write!(f, "a non-XML character {c:?} found at {pos}"),
279            Self::InvalidChar {
280                expected,
281                actual,
282                pos,
283            } => write!(
284                f,
285                "expected '{}' not '{}' at {pos}",
286                char::from(*expected),
287                char::from(*actual)
288            ),
289            Self::ExpectedChar {
290                expected,
291                actual,
292                pos,
293            } => write!(
294                f,
295                "expected {expected} not '{}' at {pos}",
296                char::from(*actual)
297            ),
298            Self::InvalidString(expected, pos) => write!(f, "expected '{expected}' at {pos}"),
299            Self::InvalidComment(pos) => write!(f, "comment at {pos} contains '--'"),
300            Self::InvalidCharacterData(pos) => {
301                write!(f, "']]>' at {pos} is not allowed inside a character data")
302            }
303            Self::UnknownToken(pos) => write!(f, "unknown token at {pos}"),
304            Self::UnexpectedEndOfStream => f.write_str("unexpected end of stream"),
305            Self::InvalidCharacterReference(pos) => write!(
306                f,
307                "the character reference at {pos} is not a Unicode scalar value"
308            ),
309            Self::InvalidPiTarget(pos) => write!(
310                f,
311                "the processing instruction target at {pos} is reserved or contains ':'"
312            ),
313            Self::PiWithoutWhitespace(pos) => write!(
314                f,
315                "expected a whitespace between the processing instruction target and its data at {pos}"
316            ),
317            Self::InvalidXmlDeclaration(reason, pos) => {
318                write!(f, "invalid XML declaration at {pos}: {reason}")
319            }
320            Self::InvalidQName(pos) => write!(f, "a name with an empty prefix at {pos}"),
321            Self::EmptyPrefixedNamespace(prefix, pos) => write!(
322                f,
323                "the prefix '{prefix}' at {pos} is bound to an empty namespace name"
324            ),
325            Self::XmlnsPrefixDeclared(pos) => {
326                write!(
327                    f,
328                    "the 'xmlns' prefix is declared at {pos}, but it must not be"
329                )
330            }
331            Self::DuplicatedNamespaceDeclaration(name, pos) => {
332                write!(
333                    f,
334                    "namespace declaration '{name}' at {pos} is already defined"
335                )
336            }
337            Self::PrefixedXmlnsAttribute(name, pos) => write!(
338                f,
339                "attribute '{name}' at {pos}: a prefixed attribute named 'xmlns' is not supported"
340            ),
341            Self::DepthLimitReached => f.write_str("elements nested deeper than the limit"),
342            Self::UnsupportedEncoding(name) => write!(f, "unsupported encoding '{name}'"),
343            Self::EncodingMismatch { found, declared } => write!(
344                f,
345                "{found}, but the XML declaration names the encoding '{declared}'"
346            ),
347            Self::InvalidEncodedBytes { encoding, pos } => {
348                write!(f, "bytes that are not {encoding} at {pos}")
349            }
350        }
351    }
352}
353
354impl std::error::Error for Error {}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    #[test]
361    fn positions_count_lines_and_characters() {
362        let text = "ab\n\u{e9}cd\r\nx";
363        assert_eq!(TextPos::at(text, 0), TextPos::new(1, 1));
364        assert_eq!(TextPos::at(text, 2), TextPos::new(1, 3));
365        assert_eq!(TextPos::at(text, 3), TextPos::new(2, 1));
366        assert_eq!(TextPos::at(text, 5), TextPos::new(2, 2));
367        // A carriage return is a character of the line; only line feeds end lines.
368        assert_eq!(TextPos::at(text, 8), TextPos::new(2, 5));
369        assert_eq!(TextPos::at(text, 9), TextPos::new(3, 1));
370        assert_eq!(TextPos::at(text, 1000), TextPos::new(3, 2));
371        assert_eq!(TextPos::new(3, 7).to_string(), "3:7");
372    }
373}