Skip to main content

datalogic_rs/error/
mod.rs

1//! `Error` — the unified error type returned by every public engine
2//! operation. Submodules are structured by concern:
3//!
4//! - [`kind`] — `ErrorKind` enum + `CustomErrorSource` trait alias.
5//! - [`path`] — `ErrorPath`, the internal breadcrumb storage.
6//! - [`serde`] — `Display`, `std::error::Error`, `Serialize`, and `From`
7//!   impls for foreign error types.
8//!
9//! Re-exports below preserve the pre-split `crate::error::*` import paths so
10//! callers elsewhere in the crate are unaffected by the file split.
11
12mod kind;
13mod path;
14mod serde;
15
16pub use kind::{CustomErrorSource, ErrorKind};
17pub(crate) use path::ErrorPath;
18
19use datavalue::OwnedDataValue;
20use std::borrow::Cow;
21use std::fmt;
22use std::sync::Arc;
23
24/// Canonical "Invalid Arguments" error message — used wherever an
25/// operator rejects a malformed args list before evaluating.
26pub(crate) const INVALID_ARGS: &str = "Invalid Arguments";
27
28/// Canonical "NaN" string used as the `type` field of the thrown error
29/// object that arithmetic and comparison ops raise on non-numeric input.
30pub(crate) const NAN_ERROR: &str = "NaN";
31
32/// String-only custom error — used by [`Error::custom_message`] to wrap a
33/// bare message in a `dyn Error` shell.
34#[derive(Debug)]
35struct MessageError(String);
36
37impl fmt::Display for MessageError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        f.write_str(&self.0)
40    }
41}
42
43impl std::error::Error for MessageError {}
44
45/// Error returned by every [`crate::Engine`] operation.
46///
47/// The `kind` field carries the failure category and any variant-specific
48/// payload. `operator` and `node_ids` are populated by the public
49/// `evaluate*` entry points: `operator` names the outermost operator that
50/// produced the error, and `node_ids` is a breadcrumb of compiled-node ids
51/// from the failure site toward the root (leaf-to-root). Use
52/// [`Error::resolve_path`] to translate the ids into structured
53/// [`crate::PathStep`]s callers can act on.
54///
55/// # Wire format
56///
57/// `Error` serialises as:
58/// `{"type": <kind tag>, "message": <Display>, ...kind-extras, "operator"?, "node_ids"?}`.
59/// `operator` is omitted when `None`; `node_ids` is omitted when empty. JS
60/// consumers can `JSON.parse(err)` and switch on `err.type`.
61///
62/// # Source chains
63///
64/// `std::error::Error::source` returns `Some` only for [`ErrorKind::Custom`]
65/// — the variant produced by [`Error::wrap`]. Every other variant carries
66/// a flat string or structured payload, not a typed cause. To attach a
67/// typed source error, wrap it via `Error::wrap` instead of constructing
68/// e.g. `Error::invalid_arguments("...")` directly.
69#[non_exhaustive]
70#[derive(Debug, Clone)]
71pub struct Error {
72    /// What went wrong. Pattern-matched by callers; stays public.
73    pub kind: ErrorKind,
74    /// Outermost operator that produced the error, when known. Stored as
75    /// `Cow<'static, str>` so built-in op names (the dominant case) are
76    /// zero-allocation `Cow::Borrowed` references; only dynamic
77    /// custom-operator names carry an owned `String` via `Cow::Owned`.
78    /// Read via [`Self::operator`].
79    ///
80    /// Kept inline rather than boxed: a boxed-metadata variant (Error at
81    /// 40 bytes instead of 80) was measured and rejected — the box cost
82    /// ~14 ns per boundary-escaping error, regressing error-dense
83    /// workloads 15-45%, while the thinner `Result` slot produced no
84    /// measurable win on error-free suites.
85    operator: Option<Cow<'static, str>>,
86    /// Breadcrumb of compiled-node ids from the failure site toward the
87    /// root (leaf-to-root). Empty when the error came from parse/compile
88    /// or wasn't routed through the public `evaluate*` path. Read via
89    /// [`Self::node_ids`].
90    node_ids: ErrorPath,
91}
92
93impl Error {
94    /// Construct an [`Error`] with the given kind and no contextual metadata.
95    #[inline]
96    pub fn new(kind: ErrorKind) -> Self {
97        Self {
98            kind,
99            operator: None,
100            node_ids: ErrorPath::default(),
101        }
102    }
103
104    /// Outermost operator that produced this error, when known.
105    /// Returns `None` for parse/compile errors and for raw constructor sites
106    /// that didn't call [`Self::with_operator`].
107    #[inline]
108    pub fn operator(&self) -> Option<&str> {
109        self.operator.as_deref()
110    }
111
112    /// Breadcrumb of compiled-node ids from the failure site toward the root
113    /// (leaf-to-root). Returns an empty slice when the error came from
114    /// parse/compile or wasn't routed through the public `evaluate*` path.
115    /// Use [`Self::resolve_path`] to convert ids into named [`crate::PathStep`]s.
116    #[inline]
117    pub fn node_ids(&self) -> &[u32] {
118        self.node_ids.as_slice()
119    }
120
121    /// Get a stable string tag for the error kind. Stable across releases.
122    pub fn tag(&self) -> &'static str {
123        match self.kind {
124            ErrorKind::InvalidOperator(_) => "InvalidOperator",
125            ErrorKind::InvalidArguments(_) => "InvalidArguments",
126            ErrorKind::VariableNotFound(_) => "VariableNotFound",
127            ErrorKind::InvalidContextLevel(_) => "InvalidContextLevel",
128            ErrorKind::TypeError(_) => "TypeError",
129            ErrorKind::ArithmeticError(_) => "ArithmeticError",
130            ErrorKind::Custom(_) => "Custom",
131            ErrorKind::ParseError(_) => "ParseError",
132            ErrorKind::Thrown(_) => "Thrown",
133            ErrorKind::FormatError(_) => "FormatError",
134            ErrorKind::IndexOutOfBounds { .. } => "IndexOutOfBounds",
135            ErrorKind::ConfigurationError(_) => "ConfigurationError",
136        }
137    }
138
139    /// Attach the outermost operator name and return self.
140    ///
141    /// Accepts anything convertible to `Cow<'static, str>` — passing a
142    /// `&'static str` literal stays zero-allocation; a `String` becomes
143    /// `Cow::Owned` (one move, no copy).
144    #[must_use = "builder methods return the modified Error; bind or return it"]
145    pub fn with_operator(mut self, operator: impl Into<Cow<'static, str>>) -> Self {
146        self.operator = Some(operator.into());
147        self
148    }
149
150    /// Attach the breadcrumb path and return self.
151    ///
152    /// Takes a `Vec<u32>` of compiled-node ids (leaf-to-root). The internal
153    /// storage is private; future versions may swap its layout without an
154    /// API change.
155    #[must_use = "builder methods return the modified Error; bind or return it"]
156    pub fn with_node_ids(mut self, ids: Vec<u32>) -> Self {
157        self.node_ids = ids.into();
158        self
159    }
160
161    /// Resolve the raw [`Self::node_ids`] breadcrumb into structured
162    /// [`crate::PathStep`]s (root-to-leaf). Walks the compiled tree once.
163    ///
164    /// Returns an empty vector when `self.node_ids` is empty. Ids absent
165    /// from the compiled tree (e.g. when the error came from compile-time,
166    /// before evaluation populated the breadcrumb) are skipped.
167    ///
168    /// **Why on demand**: an earlier design eagerly cached the resolved
169    /// steps on `Error` so callers could read them without holding the
170    /// `Logic`. That walk allocates a HashMap of every node + a `String`
171    /// JSON pointer per node, and paying it on every boundary error
172    /// inflated error-heavy benchmark suites by 17×. Resolving on demand
173    /// at the catch site puts the cost where the caller actually needs
174    /// the data — and most callers either inspect raw [`Self::node_ids`]
175    /// only, or already hold the compiled `Logic` at the catch site.
176    pub fn resolve_path(&self, compiled: &crate::Logic) -> Vec<crate::PathStep> {
177        compiled.resolve_node_ids(self.node_ids())
178    }
179
180    // ---- 4.x convenience constructors ----
181    //
182    // The pre-merge enum used `Error::Variant(x)` directly. With the merged
183    // struct/enum split the right form is `ErrorKind::Variant(x).into()`.
184    // The shorthand below keeps the 33 internal call sites readable without
185    // pulling `ErrorKind` into every file's import list.
186
187    /// Shorthand for `ErrorKind::InvalidOperator(name).into()`.
188    #[inline]
189    pub fn invalid_operator(name: impl Into<Cow<'static, str>>) -> Self {
190        ErrorKind::InvalidOperator(name.into()).into()
191    }
192    /// Shorthand for `ErrorKind::InvalidArguments(msg).into()`.
193    #[inline]
194    pub fn invalid_arguments(msg: impl Into<Cow<'static, str>>) -> Self {
195        ErrorKind::InvalidArguments(msg.into()).into()
196    }
197    /// Shorthand for `ErrorKind::VariableNotFound(name).into()`.
198    #[inline]
199    pub fn variable_not_found(name: impl Into<Cow<'static, str>>) -> Self {
200        ErrorKind::VariableNotFound(name.into()).into()
201    }
202    /// Shorthand for `ErrorKind::InvalidContextLevel(level).into()`.
203    #[inline]
204    pub fn invalid_context_level(level: isize) -> Self {
205        ErrorKind::InvalidContextLevel(level).into()
206    }
207    /// Shorthand for `ErrorKind::TypeError(msg).into()`.
208    #[inline]
209    pub fn type_error(msg: impl Into<Cow<'static, str>>) -> Self {
210        ErrorKind::TypeError(msg.into()).into()
211    }
212    /// Shorthand for `ErrorKind::ArithmeticError(msg).into()`.
213    #[inline]
214    pub fn arithmetic_error(msg: impl Into<Cow<'static, str>>) -> Self {
215        ErrorKind::ArithmeticError(msg.into()).into()
216    }
217    /// Shorthand for a message-only [`ErrorKind::Custom`]. Equivalent to
218    /// [`Self::wrap`] with a string-shaped error inside. Reach for
219    /// [`Self::wrap`] directly when you have a typed `std::error::Error`
220    /// to preserve.
221    #[inline]
222    pub fn custom_message(msg: impl Into<String>) -> Self {
223        Self::wrap(MessageError(msg.into()))
224    }
225
226    /// Wrap any `std::error::Error + Send + Sync + 'static` into an
227    /// [`ErrorKind::Custom`], preserving the source chain so consumers can
228    /// walk it via [`std::error::Error::source`]:
229    ///
230    /// ```ignore
231    /// some_io_call().map_err(Error::wrap)?;
232    /// ```
233    ///
234    /// The original error stays inspectable: `error.source()` returns
235    /// `Some(&original)`. Standard chain-walking via
236    /// [`std::error::Error::source`] applies all the way down.
237    ///
238    /// Wrapping an existing [`Error`] is a no-op — the input is returned
239    /// unchanged rather than producing `Custom(Custom(...))`.
240    #[inline]
241    pub fn wrap<E: std::error::Error + Send + Sync + 'static>(err: E) -> Self {
242        // No-op when E is already `Error`. We hold `err` inside an `Option`
243        // and downcast that — `TypeId::of::<Option<E>>() == TypeId::of::<Option<Error>>()`
244        // iff `E == Error`, so the downcast succeeds exactly when we'd
245        // otherwise double-wrap.
246        let mut slot: Option<E> = Some(err);
247        if let Some(slot_as_error) =
248            (&mut slot as &mut dyn std::any::Any).downcast_mut::<Option<Error>>()
249        {
250            return slot_as_error.take().expect("just stored `Some`");
251        }
252        let err = slot.take().expect("just stored `Some`");
253        ErrorKind::Custom(Arc::new(err)).into()
254    }
255    /// Shorthand for `ErrorKind::ParseError(msg).into()`.
256    #[inline]
257    pub fn parse_error(msg: impl Into<Cow<'static, str>>) -> Self {
258        ErrorKind::ParseError(msg.into()).into()
259    }
260    /// Shorthand for `ErrorKind::Thrown(value).into()`.
261    #[inline]
262    pub fn thrown(value: OwnedDataValue) -> Self {
263        ErrorKind::Thrown(value).into()
264    }
265
266    /// If this is an [`ErrorKind::Thrown`], return its payload. Convenience
267    /// accessor so consumers (loggers, structured-error walkers, the test
268    /// runner) don't have to pattern-match on the kind themselves.
269    #[inline]
270    pub fn thrown_value(&self) -> Option<&OwnedDataValue> {
271        if let ErrorKind::Thrown(v) = &self.kind {
272            Some(v)
273        } else {
274            None
275        }
276    }
277    /// Shorthand for `ErrorKind::FormatError(msg).into()`.
278    #[inline]
279    pub fn format_error(msg: impl Into<Cow<'static, str>>) -> Self {
280        ErrorKind::FormatError(msg.into()).into()
281    }
282    /// Shorthand for `ErrorKind::IndexOutOfBounds { index, length }.into()`.
283    #[inline]
284    pub fn index_out_of_bounds(index: isize, length: usize) -> Self {
285        ErrorKind::IndexOutOfBounds { index, length }.into()
286    }
287    /// Shorthand for `ErrorKind::ConfigurationError(msg).into()`.
288    #[inline]
289    pub fn configuration_error(msg: impl Into<Cow<'static, str>>) -> Self {
290        ErrorKind::ConfigurationError(msg.into()).into()
291    }
292
293    /// Canonical "Invalid Arguments" error. Used wherever an operator
294    /// rejects malformed args before evaluating.
295    #[inline]
296    pub(crate) fn invalid_args() -> Self {
297        Error::invalid_arguments(INVALID_ARGS)
298    }
299
300    /// Decorate an error from a public `evaluate*` boundary with the
301    /// breadcrumb path (raw ids only — see below) and the outermost
302    /// operator name. Marked `#[cold]` + `#[inline(never)]` so the
303    /// dispatch caller's `Err` arm shrinks to a single call instruction,
304    /// keeping the hot `Ok` arm's I-cache footprint tight.
305    ///
306    /// **Lazy path resolution.** The boundary attaches raw compiled-node
307    /// ids only — it does *not* call `Logic::resolve_node_ids` here. That
308    /// walk allocates a HashMap of every node + a `String` JSON pointer
309    /// per node and was measured to balloon try.json from 51 ns/op to
310    /// 898 ns/op (17×) and arithmetic/plus.json from 22 to 84 ns
311    /// (4×) on error-heavy suites where every iteration constructs an
312    /// Error. Consumers that need structured steps call
313    /// [`Self::resolve_path`] (takes a `&Logic`) on demand, which is
314    /// the same cost paid once at the catch site rather than at every
315    /// boundary crossing.
316    ///
317    /// `prefer_existing_op` controls whether to fall back to
318    /// `compiled.root_op_name` when no operator was already attached:
319    /// the `Engine::evaluate*` sites pass `true` (only attach if a
320    /// deeper site didn't name a more specific failing op);
321    /// `TracedSession` passes `false` to preserve its prior
322    /// unconditional-overwrite behavior.
323    #[cold]
324    #[inline(never)]
325    pub(crate) fn decorated(
326        mut self,
327        node_ids: Vec<u32>,
328        compiled: &crate::Logic,
329        prefer_existing_op: bool,
330    ) -> Self {
331        self.node_ids = node_ids.into();
332        if !prefer_existing_op || self.operator.is_none() {
333            if let Some(name) = compiled.root_op_name.clone() {
334                self.operator = Some(name);
335            }
336        }
337        self
338    }
339
340    /// Canonical NaN error — `{"type": "NaN"}` thrown via [`Error::thrown`].
341    /// Used by arithmetic and comparison ops on non-numeric input.
342    #[inline]
343    pub(crate) fn nan() -> Self {
344        Error::thrown(OwnedDataValue::object([("type", NAN_ERROR)]))
345    }
346
347    /// Placeholder `Thrown` error for the deferred fast lane.
348    ///
349    /// **Invariant:** only construct this while
350    /// `ContextStack::in_catch_scope()` is `true` (inside a protected —
351    /// non-final — arm of a multi-arg `try`), with the real payload parked
352    /// in the context's thrown slot via `ContextStack::set_thrown_slot`.
353    /// Under that invariant the error is guaranteed to be consumed by the
354    /// nearest enclosing `try`'s arm loop, so the `Null` payload is never
355    /// observable: `try`'s catch arm reads the slot, and the error never
356    /// reaches a public boundary or user code. Escaping throws must go
357    /// through [`Error::thrown`] with the fully built owned payload.
358    #[cfg(feature = "error-handling")]
359    #[inline]
360    pub(crate) fn deferred_thrown() -> Self {
361        ErrorKind::Thrown(OwnedDataValue::Null).into()
362    }
363
364    /// NaN error with the deferred fast lane: inside a `try` protected arm
365    /// (and when no tracer is attached — traced steps render the payload),
366    /// park the static arena-form `{"type": "NaN"}` object in the context's
367    /// thrown slot and skip the three-allocation owned build entirely.
368    /// Anywhere else this is exactly [`Error::nan`].
369    #[cfg(feature = "error-handling")]
370    #[inline]
371    pub(crate) fn nan_at(ctx: &mut crate::arena::ContextStack<'_>) -> Self {
372        if ctx.in_catch_scope() && !ctx.is_tracing() {
373            ctx.set_thrown_slot(&NAN_THROWN);
374            return Self::deferred_thrown();
375        }
376        Self::nan()
377    }
378
379    /// Fallback when `try`/`throw` are compiled out: no catch scope can
380    /// exist, so this is always the eager [`Error::nan`].
381    #[cfg(not(feature = "error-handling"))]
382    #[inline]
383    pub(crate) fn nan_at(_ctx: &mut crate::arena::ContextStack<'_>) -> Self {
384        Self::nan()
385    }
386}
387
388/// Arena-form of the canonical NaN error object, `{"type": "NaN"}` — the
389/// payload [`Error::nan_at`] parks in the context's thrown slot instead of
390/// heap-building the owned form. `'static` and arena-free, so it can be
391/// borrowed at any arena lifetime (same soundness argument as
392/// `crate::arena::singletons`).
393#[cfg(feature = "error-handling")]
394static NAN_THROWN: crate::arena::DataValue<'static> =
395    crate::arena::DataValue::Object(&[("type", crate::arena::DataValue::String(NAN_ERROR))]);
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    #[test]
402    fn wrap_renders_via_display() {
403        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "missing key");
404        let err = Error::wrap(io_err);
405        assert_eq!(err.tag(), "Custom");
406        assert!(err.to_string().contains("missing key"));
407    }
408
409    #[test]
410    fn wrap_preserves_source_chain() {
411        use std::error::Error as _;
412        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "missing key");
413        let err = Error::wrap(io_err);
414        // `Error::source` returns the original typed error so consumers can
415        // walk the chain — the previous Display-only `wrap` lost this.
416        let src = err.source().expect("Custom should expose its source");
417        assert!(src.to_string().contains("missing key"));
418        // And the source itself can be downcast to the original type.
419        assert!(src.downcast_ref::<std::io::Error>().is_some());
420    }
421
422    #[test]
423    fn wrap_threads_through_question_mark() {
424        // Smoke test for the `?` ergonomic — `Error::wrap` slots into a
425        // `map_err` chain so foreign errors flow up unchanged.
426        fn inner() -> std::result::Result<(), Error> {
427            "not_an_int".parse::<i32>().map_err(Error::wrap)?;
428            Ok(())
429        }
430        let err = inner().expect_err("parse should fail");
431        assert!(matches!(err.kind, ErrorKind::Custom(_)));
432    }
433
434    #[test]
435    fn wrap_of_existing_error_is_noop() {
436        // `Error::wrap(some_error)` would otherwise produce `Custom(Custom(...))`
437        // — the no-op short-circuit returns the input unchanged.
438        let inner = Error::variable_not_found("x");
439        let wrapped = Error::wrap(inner.clone());
440        assert_eq!(wrapped.tag(), "VariableNotFound");
441        assert!(matches!(wrapped.kind, ErrorKind::VariableNotFound(ref name) if name == "x"));
442        // operator + node_ids metadata round-trip too.
443        let with_meta = inner.with_operator("var").with_node_ids(vec![1, 2, 3]);
444        let wrapped = Error::wrap(with_meta);
445        assert_eq!(wrapped.operator(), Some("var"));
446        assert_eq!(wrapped.node_ids(), &[1, 2, 3]);
447    }
448
449    #[test]
450    fn error_path_default_is_empty() {
451        let p = ErrorPath::default();
452        assert!(p.as_slice().is_empty());
453        assert_eq!(p.as_slice(), &[] as &[u32]);
454    }
455
456    #[test]
457    fn error_path_from_vec_round_trips() {
458        let p: ErrorPath = vec![10, 20, 30].into();
459        assert_eq!(p.as_slice(), &[10, 20, 30]);
460    }
461
462    #[test]
463    fn with_node_ids_round_trips() {
464        // Engine boundary calls `with_node_ids` once per escaping error;
465        // the ids land in the boxed metadata slot and read back unchanged.
466        let err = Error::invalid_arguments("x").with_node_ids(vec![1, 2, 3]);
467        assert_eq!(err.node_ids(), &[1, 2, 3]);
468        // Metadata-free errors read back as empty without allocating.
469        assert!(Error::invalid_arguments("x").node_ids().is_empty());
470    }
471}