Skip to main content

einvoice_xslt_exec/
error.rs

1//! Errors: refusals and static errors found when a stylesheet is prepared, dynamic errors
2//! raised by a transformation.
3
4use std::fmt;
5
6use einvoice_xpath_eval::LimitExceeded;
7
8/// The code of [`TransformError::limit_exceeded`].
9pub(crate) const LIMIT: &str = "LIMIT";
10
11/// A problem found while preparing a stylesheet: an XPath expression that does not
12/// compile (unknown function or variable, ...), a static error of the stylesheet, or a
13/// construct outside the supported subset.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct PrepareError {
16    /// The 1-based line of the stylesheet element.
17    pub line: u32,
18    /// What is wrong.
19    pub message: String,
20}
21
22impl fmt::Display for PrepareError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        write!(f, "line {}: {}", self.line, self.message)
25    }
26}
27
28impl std::error::Error for PrepareError {}
29
30/// Every problem found while preparing a stylesheet (at least one).
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct PrepareErrors(pub Vec<PrepareError>);
33
34impl fmt::Display for PrepareErrors {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        for (i, error) in self.0.iter().enumerate() {
37            if i > 0 {
38                f.write_str("\n")?;
39            }
40            write!(f, "{error}")?;
41        }
42        Ok(())
43    }
44}
45
46impl std::error::Error for PrepareErrors {}
47
48/// A dynamic error that ended a transformation.
49///
50/// Its contents are boxed: a `Result` of the executor is then a pointer wide, which keeps
51/// small the frames of the functions every level of recursion through the templates goes
52/// through.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct TransformError(Box<Inner>);
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57struct Inner {
58    code: String,
59    message: String,
60    line: Option<u32>,
61    limit: Option<LimitExceeded>,
62}
63
64impl TransformError {
65    /// A new error with an XPath, XSLT or serialization error code.
66    #[must_use]
67    pub fn new(code: &str, message: impl Into<String>) -> Self {
68        Self(Box::new(Inner {
69            code: code.to_owned(),
70            message: message.into(),
71            line: None,
72            limit: None,
73        }))
74    }
75
76    /// The error for a limit exceeded, with the code `LIMIT`.
77    #[must_use]
78    pub fn limit_exceeded(limit: LimitExceeded) -> Self {
79        Self(Box::new(Inner {
80            code: LIMIT.to_owned(),
81            message: limit.to_string(),
82            line: None,
83            limit: Some(limit),
84        }))
85    }
86
87    /// The error code (`XPTY0004`, `XTDE0640`, ...). `UNSUPPORTED` marks a valid
88    /// construct or value that this crate refuses rather than evaluating it differently
89    /// from the reference engine, `LIMIT` a document or a transformation beyond a limit
90    /// of [`TransformOptions`](crate::TransformOptions) (see [`TransformError::limit`]),
91    /// `INTERNAL` a bug.
92    #[must_use]
93    pub fn code(&self) -> &str {
94        &self.0.code
95    }
96
97    /// The limit exceeded, for an error with the code `LIMIT`: an element of the
98    /// document, or of a document loaded by `document()`, nested deeper than
99    /// [`TransformOptions::max_depth`](crate::TransformOptions::max_depth), or
100    /// templates and functions invoked one inside another more than
101    /// [`TransformOptions::max_nesting`](crate::TransformOptions::max_nesting) deep.
102    #[must_use]
103    pub fn limit(&self) -> Option<LimitExceeded> {
104        self.0.limit
105    }
106
107    /// The explanation.
108    #[must_use]
109    pub fn message(&self) -> &str {
110        &self.0.message
111    }
112
113    /// The line of the stylesheet instruction that raised the error, when known.
114    #[must_use]
115    pub fn line(&self) -> Option<u32> {
116        self.0.line
117    }
118
119    /// The message prefixed with the URI of the document concerned (a document loaded
120    /// by `document()`).
121    #[must_use]
122    pub(crate) fn in_document(mut self, uri: &str) -> Self {
123        self.0.message = format!("{uri}: {}", self.0.message);
124        self
125    }
126
127    /// Sets the line if none is set yet (the innermost instruction wins).
128    #[must_use]
129    pub(crate) fn at(mut self, line: u32) -> Self {
130        if self.0.line.is_none() {
131            self.0.line = Some(line);
132        }
133        self
134    }
135}
136
137impl fmt::Display for TransformError {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        if let Some(line) = self.0.line {
140            write!(f, "line {line}: ")?;
141        }
142        write!(f, "{}: {}", self.0.code, self.0.message)
143    }
144}
145
146impl std::error::Error for TransformError {}
147
148impl From<einvoice_xpath_eval::Error> for TransformError {
149    fn from(e: einvoice_xpath_eval::Error) -> Self {
150        match e.limit() {
151            Some(limit) => Self::limit_exceeded(limit),
152            None => Self::new(e.code().as_str(), e.message()),
153        }
154    }
155}
156
157impl From<einvoice_xdm::XdmError> for TransformError {
158    fn from(e: einvoice_xdm::XdmError) -> Self {
159        einvoice_xpath_eval::Error::from(e).into()
160    }
161}
162
163/// The result of a transformation step.
164pub(crate) type Result<T> = std::result::Result<T, TransformError>;
165
166pub(crate) fn err<T>(code: &str, message: impl Into<String>) -> Result<T> {
167    Err(TransformError::new(code, message))
168}