Skip to main content

predicator_rs/
error.rs

1//! The errors the crate answers: one enum over four error types (a parse
2//! error and the three evaluation error types the conformance corpus names),
3//! each carrying its reason, a message and, where one is known, a position
4//! in the source.
5
6use core::fmt;
7
8/// A place in source text: a line and a column, both counted from 1.
9///
10/// The column counts characters (Unicode scalar values) from the start of
11/// the line.
12///
13/// ```
14/// let position = predicator_rs::Position { line: 1, column: 7 };
15/// assert_eq!(position.line, 1);
16/// assert_eq!(position.column, 7);
17/// ```
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub struct Position {
20    /// The line, counted from 1.
21    pub line: usize,
22    /// The column, counted from 1.
23    pub column: usize,
24}
25
26/// Declares one of the four error types: a reason, a message and an optional
27/// position, with the same methods on each, and any further optional fields
28/// one type alone carries (each `None` until that type's own method sets it).
29macro_rules! error_type {
30    ($(#[$doc:meta])* $name:ident, $variant:ident $(, $field:ident: $type:ty)*) => {
31        $(#[$doc])*
32        #[derive(Debug, Clone, PartialEq, Eq)]
33        pub struct $name {
34            reason: String,
35            message: String,
36            position: Option<Position>,
37            $($field: Option<$type>,)*
38        }
39
40        impl $name {
41            /// An error with a reason (the corpus's token) and a message (a
42            /// sentence for a person), at no position.
43            ///
44            /// ```
45            #[doc = concat!("use predicator_rs::{", stringify!($name), ", Position};")]
46            ///
47            #[doc = concat!("let error = ", stringify!($name), "::new(\"some_reason\", \"a sentence\");")]
48            /// assert_eq!(error.reason(), "some_reason");
49            /// assert_eq!(error.position(), None);
50            /// ```
51            pub fn new(reason: impl Into<String>, message: impl Into<String>) -> Self {
52                Self {
53                    reason: reason.into(),
54                    message: message.into(),
55                    position: None,
56                    $($field: None,)*
57                }
58            }
59
60            /// The same error at `position`.
61            ///
62            /// ```
63            #[doc = concat!("use predicator_rs::{", stringify!($name), ", Position};")]
64            ///
65            #[doc = concat!("let error = ", stringify!($name), "::new(\"some_reason\", \"a sentence\");")]
66            /// let at = Position { line: 2, column: 3 };
67            /// assert_eq!(error.with_position(at).position(), Some(at));
68            /// ```
69            #[must_use]
70            pub fn with_position(mut self, position: Position) -> Self {
71                self.position = Some(position);
72                self
73            }
74
75            /// The reason: the structured token the corpus names, which is
76            /// normative.
77            ///
78            /// ```
79            #[doc = concat!("use predicator_rs::{", stringify!($name), ", Position};")]
80            ///
81            #[doc = concat!("let error = ", stringify!($name), "::new(\"some_reason\", \"a sentence\");")]
82            /// assert_eq!(error.reason(), "some_reason");
83            /// ```
84            pub fn reason(&self) -> &str {
85                &self.reason
86            }
87
88            /// The message: a sentence for a person, which is not normative.
89            ///
90            /// ```
91            #[doc = concat!("use predicator_rs::{", stringify!($name), ", Position};")]
92            ///
93            #[doc = concat!("let error = ", stringify!($name), "::new(\"some_reason\", \"a sentence\");")]
94            /// assert_eq!(error.message(), "a sentence");
95            /// assert_eq!(error.to_string(), "a sentence");
96            /// ```
97            pub fn message(&self) -> &str {
98                &self.message
99            }
100
101            /// Where in the source the failure is, when that is known.
102            ///
103            /// ```
104            #[doc = concat!("use predicator_rs::{", stringify!($name), ", Position};")]
105            ///
106            #[doc = concat!("let error = ", stringify!($name), "::new(\"some_reason\", \"a sentence\");")]
107            /// assert_eq!(error.position(), None);
108            /// let at = Position { line: 1, column: 1 };
109            /// assert_eq!(error.with_position(at).position(), Some(at));
110            /// ```
111            pub fn position(&self) -> Option<Position> {
112                self.position
113            }
114        }
115
116        impl fmt::Display for $name {
117            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118                f.write_str(&self.message)
119            }
120        }
121
122        impl std::error::Error for $name {}
123
124        impl From<$name> for Error {
125            fn from(error: $name) -> Error {
126                Error::$variant(error)
127            }
128        }
129    };
130}
131
132error_type! {
133    /// A text that does not parse: a source, or a text handed to
134    /// [`tagged::decode`](crate::tagged::decode). It knows its position.
135    ///
136    /// ```
137    /// use predicator_rs::{ParseError, Position};
138    ///
139    /// let error = ParseError::new("malformed_json", "the text ends inside a list")
140    ///     .with_position(Position { line: 1, column: 3 });
141    /// assert_eq!(error.reason(), "malformed_json");
142    /// assert_eq!(error.position(), Some(Position { line: 1, column: 3 }));
143    /// ```
144    ParseError, Parse
145}
146
147error_type! {
148    /// An evaluation failure that is neither a type mismatch nor an unbound
149    /// variable, and a value refused where it crosses into the crate (a
150    /// float that is not finite, a value nested too deep).
151    ///
152    /// ```
153    /// use predicator_rs::EvaluationError;
154    ///
155    /// let error = EvaluationError::new("division_by_zero", "the divisor is zero");
156    /// assert_eq!(error.reason(), "division_by_zero");
157    /// assert_eq!(error.to_string(), "the divisor is zero");
158    /// assert_eq!(error.position(), None);
159    /// ```
160    EvaluationError, Evaluation, root: String
161}
162
163impl EvaluationError {
164    /// The context root a refusal names, when it names one: the root a
165    /// `store` was refused because the options protect it (reason
166    /// `protected_root`; [`Options::protected_roots`](crate::Options::protected_roots)).
167    ///
168    /// ```
169    /// use predicator_rs::EvaluationError;
170    ///
171    /// assert_eq!(EvaluationError::new("division_by_zero", "the divisor is zero").root(), None);
172    /// ```
173    pub fn root(&self) -> Option<&str> {
174        self.root.as_deref()
175    }
176
177    /// The same error naming `root` as the root it refuses.
178    pub(crate) fn with_root(mut self, root: impl Into<String>) -> Self {
179        self.root = Some(root.into());
180        self
181    }
182}
183
184error_type! {
185    /// An operand an operation refused on its type. The reason names the
186    /// operation.
187    ///
188    /// ```
189    /// use predicator_rs::TypeMismatchError;
190    ///
191    /// let error = TypeMismatchError::new("add", "add takes two numbers");
192    /// assert_eq!(error.reason(), "add");
193    /// ```
194    TypeMismatchError, TypeMismatch
195}
196
197error_type! {
198    /// A variable the context does not bind, reported as an error rather
199    /// than as undefined.
200    ///
201    /// ```
202    /// use predicator_rs::UndefinedVariableError;
203    ///
204    /// let error = UndefinedVariableError::new("unbound_variable", "x is not bound");
205    /// assert_eq!(error.reason(), "unbound_variable");
206    /// ```
207    UndefinedVariableError, UndefinedVariable
208}
209
210/// Every error the crate answers. The variant is the error's type, which
211/// with the reason is normative where the conformance corpus expects an
212/// error (it names the three evaluation types); the message is not.
213///
214/// ```
215/// use predicator_rs::{Error, EvaluationError};
216///
217/// let error = Error::from(EvaluationError::new("empty_stack", "nothing is left"));
218/// assert_eq!(error.type_name(), "EvaluationError");
219/// assert_eq!(error.reason(), "empty_stack");
220/// assert_eq!(error.message(), "nothing is left");
221/// assert_eq!(error.position(), None);
222/// ```
223#[non_exhaustive]
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub enum Error {
226    /// A text that does not parse.
227    Parse(ParseError),
228    /// An evaluation failure, or a value refused where it crosses in.
229    Evaluation(EvaluationError),
230    /// An operand refused on its type.
231    TypeMismatch(TypeMismatchError),
232    /// A variable the context does not bind.
233    UndefinedVariable(UndefinedVariableError),
234}
235
236impl Error {
237    /// The error's type as the corpus spells it: `"ParseError"`,
238    /// `"EvaluationError"`, `"TypeMismatchError"` or
239    /// `"UndefinedVariableError"`.
240    ///
241    /// ```
242    /// use predicator_rs::compile;
243    ///
244    /// assert_eq!(compile("x >").unwrap_err().type_name(), "ParseError");
245    /// ```
246    pub fn type_name(&self) -> &'static str {
247        match self {
248            Error::Parse(_) => "ParseError",
249            Error::Evaluation(_) => "EvaluationError",
250            Error::TypeMismatch(_) => "TypeMismatchError",
251            Error::UndefinedVariable(_) => "UndefinedVariableError",
252        }
253    }
254
255    /// The reason: the structured token the corpus names, which is
256    /// normative.
257    ///
258    /// ```
259    /// use predicator_rs::{Context, Options, evaluate};
260    ///
261    /// let refused = evaluate("1 / 0", &Context::new(), &Options::new());
262    /// assert_eq!(refused.unwrap_err().reason(), "division_by_zero");
263    /// ```
264    pub fn reason(&self) -> &str {
265        match self {
266            Error::Parse(error) => error.reason(),
267            Error::Evaluation(error) => error.reason(),
268            Error::TypeMismatch(error) => error.reason(),
269            Error::UndefinedVariable(error) => error.reason(),
270        }
271    }
272
273    /// The message: a sentence for a person, which is not normative.
274    ///
275    /// ```
276    /// use predicator_rs::{Error, TypeMismatchError};
277    ///
278    /// let error = Error::from(TypeMismatchError::new("add", "add takes numbers"));
279    /// assert_eq!(error.message(), "add takes numbers");
280    /// assert_eq!(error.to_string(), "add takes numbers");
281    /// ```
282    pub fn message(&self) -> &str {
283        match self {
284            Error::Parse(error) => error.message(),
285            Error::Evaluation(error) => error.message(),
286            Error::TypeMismatch(error) => error.message(),
287            Error::UndefinedVariable(error) => error.message(),
288        }
289    }
290
291    /// Where in the source the failure is, when that is known.
292    ///
293    /// ```
294    /// use predicator_rs::{Context, Options, Position, compile, evaluate};
295    ///
296    /// let parse = compile("x >").unwrap_err();
297    /// assert_eq!(parse.position(), Some(Position { line: 1, column: 4 }));
298    /// let run = evaluate("1 / 0", &Context::new(), &Options::new()).unwrap_err();
299    /// assert_eq!(run.position(), None);
300    /// ```
301    pub fn position(&self) -> Option<Position> {
302        match self {
303            Error::Parse(error) => error.position(),
304            Error::Evaluation(error) => error.position(),
305            Error::TypeMismatch(error) => error.position(),
306            Error::UndefinedVariable(error) => error.position(),
307        }
308    }
309}
310
311impl fmt::Display for Error {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        f.write_str(self.message())
314    }
315}
316
317impl std::error::Error for Error {}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322
323    // Sabotage: with type_name's TypeMismatchError arm answering
324    // "TypeMismatch", this test fails.
325    #[test]
326    fn each_variant_carries_its_corpus_type_reason_message_and_position() {
327        let at = Position { line: 2, column: 5 };
328        let errors = [
329            (
330                Error::from(ParseError::new("p", "parse").with_position(at)),
331                "ParseError",
332                "p",
333                "parse",
334                Some(at),
335            ),
336            (
337                Error::from(EvaluationError::new("e", "evaluation")),
338                "EvaluationError",
339                "e",
340                "evaluation",
341                None,
342            ),
343            (
344                Error::from(TypeMismatchError::new("t", "mismatch").with_position(at)),
345                "TypeMismatchError",
346                "t",
347                "mismatch",
348                Some(at),
349            ),
350            (
351                Error::from(UndefinedVariableError::new("u", "unbound")),
352                "UndefinedVariableError",
353                "u",
354                "unbound",
355                None,
356            ),
357        ];
358        for (error, type_name, reason, message, position) in errors {
359            assert_eq!(error.type_name(), type_name);
360            assert_eq!(error.reason(), reason);
361            assert_eq!(error.message(), message);
362            assert_eq!(error.to_string(), message);
363            assert_eq!(error.position(), position);
364            let source: &dyn std::error::Error = &error;
365            assert!(source.source().is_none());
366        }
367    }
368}