Skip to main content

einvoice_xpath/
error.rs

1//! Parse errors.
2
3use std::fmt;
4
5/// What went wrong.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub enum ErrorKind {
8    /// The text is not valid XPath 2.0 (or not a valid pattern, sequence type or attribute
9    /// value template): `err:XPST0003`, or `err:XTSE0350`/`err:XTSE0370` for templates.
10    Syntax,
11    /// The text is valid but uses a construct outside the supported subset.
12    Unsupported,
13    /// A prefix is not bound to a namespace (`err:XPST0081`).
14    UndeclaredPrefix,
15    /// A type name that is not an atomic type (`err:XPST0051`).
16    UnknownType,
17    /// The expression (or pattern) is nested deeper than [`MAX_DEPTH`](crate::MAX_DEPTH):
18    /// it is refused rather than read, compiled and evaluated with a call stack in
19    /// proportion to its depth.
20    TooDeep,
21}
22
23/// A parse error, with its position in the parsed text.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Error {
26    /// What went wrong.
27    pub kind: ErrorKind,
28    /// The byte offset in the parsed text where the problem was found.
29    pub offset: usize,
30    /// The column of that offset, counted in characters from 1.
31    pub column: usize,
32    /// A description naming the offending construct.
33    pub message: String,
34}
35
36impl Error {
37    pub(crate) fn new(kind: ErrorKind, src: &str, offset: usize, message: String) -> Self {
38        let column = src.get(..offset).map_or(offset, |s| s.chars().count()) + 1;
39        Self {
40            kind,
41            offset,
42            column,
43            message,
44        }
45    }
46}
47
48impl fmt::Display for Error {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        let kind = match self.kind {
51            ErrorKind::Syntax => "syntax error",
52            ErrorKind::Unsupported => "unsupported",
53            ErrorKind::UndeclaredPrefix => "undeclared namespace prefix",
54            ErrorKind::UnknownType => "unknown type",
55            ErrorKind::TooDeep => "too deep",
56        };
57        write!(f, "{kind} at column {}: {}", self.column, self.message)
58    }
59}
60
61impl std::error::Error for Error {}
62
63/// The result of a parse.
64pub type Result<T> = std::result::Result<T, Error>;