Skip to main content

einvoice_xpath_eval/
error.rs

1//! Static and dynamic errors, with the error codes of XPath 2.0, F&O 2.0 and XSLT 2.0
2//! that Saxon-HE reports.
3
4use std::fmt;
5
6use einvoice_xdm::{ErrorCode as XdmCode, XdmError};
7
8use crate::limit::LimitExceeded;
9
10/// The error code of a failed compilation or evaluation.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12#[non_exhaustive]
13pub enum ErrorCode {
14    /// `XPST0008`: a variable that is not in scope (static).
15    Xpst0008,
16    /// `XPST0017`: no function with that name and arity (static).
17    Xpst0017,
18    /// `XPDY0002`: the context item is absent.
19    Xpdy0002,
20    /// `XPDY0050`: the root of the tree containing the context item is not a document node.
21    Xpdy0050,
22    /// `XPTY0004`: type error.
23    Xpty0004,
24    /// `XPTY0018`: the last step of a path returns both nodes and atomic values.
25    Xpty0018,
26    /// `XPTY0019`: a step of a path (other than the last) returns an atomic value.
27    Xpty0019,
28    /// `XPTY0020`: the context item of an axis step is not a node.
29    Xpty0020,
30    /// `FOAR0001`: division by zero.
31    Foar0001,
32    /// `FOAR0002`: numeric operation overflow.
33    Foar0002,
34    /// `FOCA0002`: invalid lexical value.
35    Foca0002,
36    /// `FOCH0001`: a code point that is not a valid XML character.
37    Foch0001,
38    /// `FODC0001`: no document node at the root of the tree (`id()`).
39    Fodc0001,
40    /// `FODT0001`: date/time value out of range.
41    Fodt0001,
42    /// `FORG0001`: invalid value for a cast or constructor.
43    Forg0001,
44    /// `FORG0006`: invalid argument type (effective boolean value, `sum`).
45    Forg0006,
46    /// `FORX0001`: invalid regular expression flags.
47    Forx0001,
48    /// `FORX0002`: invalid regular expression.
49    Forx0002,
50    /// `FORX0003`: the regular expression matches a zero-length string.
51    Forx0003,
52    /// `FORX0004`: invalid replacement string.
53    Forx0004,
54    /// `XTDE1360`: `current()` where no current item exists (XSLT).
55    Xtde1360,
56    /// `XTDE1390`: the argument of `system-property()` is not a valid `QName` (XSLT).
57    Xtde1390,
58    /// An error reported by the host (the XSLT layer): variables, user functions,
59    /// `document()`. The code is in the message.
60    Host,
61    /// Not an XPath error: a valid construct or value that this crate refuses on purpose
62    /// rather than evaluating it differently from the reference engine.
63    Unsupported,
64    /// Not an XPath error: a broken invariant of this crate (a bug).
65    Internal,
66    /// Not an XPath error: the evaluation went beyond a limit that keeps it within a
67    /// bounded call stack ([`Error::limit`]).
68    Limit,
69}
70
71impl ErrorCode {
72    /// The code as written in the specifications, e.g. `"XPTY0004"`.
73    #[must_use]
74    pub const fn as_str(self) -> &'static str {
75        match self {
76            Self::Xpst0008 => "XPST0008",
77            Self::Xpst0017 => "XPST0017",
78            Self::Xpdy0002 => "XPDY0002",
79            Self::Xpdy0050 => "XPDY0050",
80            Self::Xpty0004 => "XPTY0004",
81            Self::Xpty0018 => "XPTY0018",
82            Self::Xpty0019 => "XPTY0019",
83            Self::Xpty0020 => "XPTY0020",
84            Self::Foar0001 => "FOAR0001",
85            Self::Foar0002 => "FOAR0002",
86            Self::Foca0002 => "FOCA0002",
87            Self::Foch0001 => "FOCH0001",
88            Self::Fodc0001 => "FODC0001",
89            Self::Fodt0001 => "FODT0001",
90            Self::Forg0001 => "FORG0001",
91            Self::Forg0006 => "FORG0006",
92            Self::Forx0001 => "FORX0001",
93            Self::Forx0002 => "FORX0002",
94            Self::Forx0003 => "FORX0003",
95            Self::Forx0004 => "FORX0004",
96            Self::Xtde1360 => "XTDE1360",
97            Self::Xtde1390 => "XTDE1390",
98            Self::Host => "HOST",
99            Self::Unsupported => "UNSUPPORTED",
100            Self::Internal => "INTERNAL",
101            Self::Limit => "LIMIT",
102        }
103    }
104
105    /// Whether the error is raised when an expression is compiled rather than evaluated.
106    #[must_use]
107    pub const fn is_static(self) -> bool {
108        matches!(self, Self::Xpst0008 | Self::Xpst0017)
109    }
110}
111
112impl fmt::Display for ErrorCode {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.write_str(self.as_str())
115    }
116}
117
118/// A failed compilation or evaluation. One pointer wide: the results of the
119/// evaluator, one on every level of its recursion, stay small.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Error(Box<Inner>);
122
123#[derive(Debug, Clone, PartialEq, Eq)]
124struct Inner {
125    code: ErrorCode,
126    message: String,
127    limit: Option<LimitExceeded>,
128}
129
130impl Error {
131    /// A new error.
132    #[must_use]
133    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
134        Self(Box::new(Inner {
135            code,
136            message: message.into(),
137            limit: None,
138        }))
139    }
140
141    /// The error of an evaluation beyond a limit ([`ErrorCode::Limit`]).
142    #[must_use]
143    pub fn limit_exceeded(limit: LimitExceeded) -> Self {
144        Self(Box::new(Inner {
145            code: ErrorCode::Limit,
146            message: limit.to_string(),
147            limit: Some(limit),
148        }))
149    }
150
151    /// The limit exceeded, for an [`ErrorCode::Limit`] error.
152    #[must_use]
153    pub fn limit(&self) -> Option<LimitExceeded> {
154        self.0.limit
155    }
156
157    /// The error code.
158    #[must_use]
159    pub fn code(&self) -> ErrorCode {
160        self.0.code
161    }
162
163    /// The explanation.
164    #[must_use]
165    pub fn message(&self) -> &str {
166        &self.0.message
167    }
168}
169
170impl fmt::Display for Error {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        write!(f, "{}: {}", self.0.code, self.0.message)
173    }
174}
175
176impl std::error::Error for Error {}
177
178impl From<XdmError> for Error {
179    fn from(e: XdmError) -> Self {
180        let code = match e.code() {
181            XdmCode::Foar0001 => ErrorCode::Foar0001,
182            XdmCode::Foar0002 => ErrorCode::Foar0002,
183            XdmCode::Foca0002 => ErrorCode::Foca0002,
184            XdmCode::Fodt0001 => ErrorCode::Fodt0001,
185            XdmCode::Forg0001 => ErrorCode::Forg0001,
186            XdmCode::Forg0006 => ErrorCode::Forg0006,
187            XdmCode::Forx0001 => ErrorCode::Forx0001,
188            XdmCode::Forx0002 => ErrorCode::Forx0002,
189            XdmCode::Forx0003 => ErrorCode::Forx0003,
190            XdmCode::Forx0004 => ErrorCode::Forx0004,
191            XdmCode::Xpty0004 => ErrorCode::Xpty0004,
192            _ => ErrorCode::Unsupported,
193        };
194        Self::new(code, e.message())
195    }
196}
197
198/// The result of a compilation or evaluation.
199pub type Result<T> = std::result::Result<T, Error>;
200
201pub(crate) fn err<T>(code: ErrorCode, message: impl Into<String>) -> Result<T> {
202    Err(Error::new(code, message))
203}