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}
18
19/// A parse error, with its position in the parsed text.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Error {
22    /// What went wrong.
23    pub kind: ErrorKind,
24    /// The byte offset in the parsed text where the problem was found.
25    pub offset: usize,
26    /// The column of that offset, counted in characters from 1.
27    pub column: usize,
28    /// A description naming the offending construct.
29    pub message: String,
30}
31
32impl Error {
33    pub(crate) fn new(kind: ErrorKind, src: &str, offset: usize, message: String) -> Self {
34        let column = src.get(..offset).map_or(offset, |s| s.chars().count()) + 1;
35        Self {
36            kind,
37            offset,
38            column,
39            message,
40        }
41    }
42}
43
44impl fmt::Display for Error {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        let kind = match self.kind {
47            ErrorKind::Syntax => "syntax error",
48            ErrorKind::Unsupported => "unsupported",
49            ErrorKind::UndeclaredPrefix => "undeclared namespace prefix",
50            ErrorKind::UnknownType => "unknown type",
51        };
52        write!(f, "{kind} at column {}: {}", self.column, self.message)
53    }
54}
55
56impl std::error::Error for Error {}
57
58/// The result of a parse.
59pub type Result<T> = std::result::Result<T, Error>;