Skip to main content

formula_lang/
error.rs

1//! Typed, exhaustive error taxonomy for the formula language.
2//!
3//! Two distinct error types, mirroring the two failure domains of a
4//! spreadsheet engine:
5//!
6//! - [`ExcelError`] — the seven **worksheet error values** (`#DIV/0!`,
7//!   `#N/A`, …). These are *data*: a formula like `=IFERROR(1/0, "safe")`
8//!   evaluates the `1/0`, observes the error, and recovers. Inside
9//!   [`evaluate`](crate::evaluate) they surface as
10//!   `Err(FormulaError::Eval(_))` when they are produced by *evaluation*
11//!   (arithmetic, coercion, lookup misses), and as `Value::Error` when they
12//!   are *stored* in a resolved cell (data passthrough — `=A1` where A1
13//!   holds `#REF!` yields the error as a value, exactly what
14//!   `ISERROR(A1)` needs to observe).
15//!
16//! - [`FormulaError`] — everything else: tokenization and parse failures
17//!   (with byte positions), unknown function names, the recursion limit,
18//!   and structurally invalid ranges. Never a panic: the lib target is
19//!   deny-linted against `unwrap`/`expect`/`panic`/`indexing` and fuzzed.
20//!
21//! Both enums are deliberately **exhaustive** (no `#[non_exhaustive]`):
22//! callers are expected to match every variant, and a new variant is a
23//! semver-minor event by design — the same policy as `wire-kit`'s
24//! `WireError` and `can-core`'s `CanError`.
25
26use alloc::string::String;
27use core::fmt;
28
29/// The seven Excel worksheet error values, in `#LITERAL!` form.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub enum ExcelError {
32    /// `#DIV/0!` — division by zero, including `MOD(x, 0)`,
33    /// `0^-1`, and `AVERAGE`/`STDEV`/`VAR` over zero numeric values.
34    DivZero,
35    /// `#N/A` — "no value available": lookup misses (`VLOOKUP`, `MATCH`),
36    /// the `#N/A` literal, `ISNA`.
37    NA,
38    /// `#NAME?` — unrecognized name text. In this crate the literal
39    /// `#NAME?` propagates as a value; unknown *function names* are a hard
40    /// [`FormulaError::UnknownFunction`] instead (see the crate docs for
41    /// the rationale).
42    Name,
43    /// `#NULL!` — the empty-intersection error. Also the crate's canonical
44    /// **omitted-argument marker**: `IF(A1,,5)` stores `Error(Null)` in the
45    /// AST for the empty second slot (see [`crate::is_omitted_arg`]).
46    Null,
47    /// `#NUM!` — a numeric problem: overflow to ±inf/NaN, `SQRT(-1)`,
48    /// `LOG` of a non-positive number, `POWER(0, 0)`, sign-mismatched
49    /// `CEILING`/`FLOOR`, a date serial outside 1900-9999.
50    Num,
51    /// `#REF!` — an invalid reference: out-of-grid `OFFSET`, an `INDEX`
52    /// position past the edge of its range, a `VLOOKUP` column index wider
53    /// than the table, the `#REF!` literal.
54    Ref,
55    /// `#VALUE!` — wrong type for the operation: arithmetic on
56    /// non-numeric text, `MID` with a zero start, `REPT` with a negative
57    /// count, wrong argument counts, a 2-D `MATCH` vector.
58    Value,
59}
60
61impl ExcelError {
62    /// The Excel worksheet literal for this error (`"#DIV/0!"`, `"#N/A"`, …).
63    #[must_use]
64    pub const fn literal(self) -> &'static str {
65        match self {
66            Self::DivZero => "#DIV/0!",
67            Self::NA => "#N/A",
68            Self::Name => "#NAME?",
69            Self::Null => "#NULL!",
70            Self::Num => "#NUM!",
71            Self::Ref => "#REF!",
72            Self::Value => "#VALUE!",
73        }
74    }
75
76    /// Parses an Excel error literal (`"#DIV/0!"`, `"#n/a"`, …),
77    /// case-insensitively. Returns `None` for anything else.
78    #[must_use]
79    pub fn from_literal(lit: &str) -> Option<Self> {
80        // Longest literals first so prefixes cannot shadow ("#N/A" vs "#NA").
81        const LITERALS: [(ExcelError, &str); 7] = [
82            (ExcelError::DivZero, "#DIV/0!"),
83            (ExcelError::Value, "#VALUE!"),
84            (ExcelError::Name, "#NAME?"),
85            (ExcelError::Null, "#NULL!"),
86            (ExcelError::Num, "#NUM!"),
87            (ExcelError::Ref, "#REF!"),
88            (ExcelError::NA, "#N/A"),
89        ];
90        LITERALS
91            .iter()
92            .find(|(_, s)| lit.eq_ignore_ascii_case(s))
93            .map(|(e, _)| *e)
94    }
95}
96
97impl fmt::Display for ExcelError {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.write_str(self.literal())
100    }
101}
102
103/// The single crate-level error for tokenizing, parsing, and evaluation.
104///
105/// Excel *values* that signal failure (`#DIV/0!` …) ride in
106/// [`FormulaError::Eval`] when produced by evaluation; see the module docs
107/// for the value-vs-error channel contract.
108#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
109pub enum FormulaError {
110    /// The tokenizer hit a character that cannot begin any token, a
111    /// malformed `#error` literal, an unterminated string, or a malformed
112    /// `$`-anchored reference. `pos` is the byte offset; `char` is the
113    /// offending character (the `#` or `"` that began the bad token, or the
114    /// unknown character itself).
115    #[error("tokenize error at byte {pos}: unexpected {char:?}")]
116    Tokenize {
117        /// Byte offset of the offending character.
118        pos: usize,
119        /// The offending character.
120        char: char,
121    },
122    /// The parser hit a token it could not accept. `pos` is the byte offset
123    /// of the offending token, `expected` a description of what would have
124    /// been legal, `got` the rendered offending token.
125    #[error("parse error at byte {pos}: expected {expected}, got {got}")]
126    Parse {
127        /// Byte offset of the offending token.
128        pos: usize,
129        /// What the parser would have accepted at this position.
130        expected: &'static str,
131        /// Rendered form of the token that was actually there.
132        got: String,
133    },
134    /// An Excel error value was produced by evaluation (arithmetic,
135    /// coercion, a lookup miss, the `#…!` literal itself). Catchable by
136    /// `IFERROR`/`IFNA`/`ISERROR`/`ISNA` *inside* the formula; at the top
137    /// level this is the `Err` arm.
138    #[error("evaluation error: {0}")]
139    Eval(ExcelError),
140    /// A function name not in the built-in table was called. Excel would
141    /// show `#NAME?`; this crate makes unknown functions a hard, typed
142    /// error instead (rationale in the crate docs). The name is uppercased.
143    #[error("unknown function: {0}")]
144    UnknownFunction(String),
145    /// Parse or evaluation recursion exceeded
146    /// [`MAX_DEPTH`](crate::MAX_DEPTH). Returned instead of overflowing the
147    /// stack — the crate is stack-safe by construction, fuzz-verified.
148    #[error("recursion limit exceeded")]
149    RecursionLimit,
150    /// A range argument was structurally impossible: a non-reference where
151    /// a range is required (`VLOOKUP(1, 5, 2)`), or a range not shaped as
152    /// its function demands (a 2-D table handed to `MATCH`).
153    #[error("invalid range argument")]
154    InvalidRange,
155}
156
157impl From<ExcelError> for FormulaError {
158    fn from(e: ExcelError) -> Self {
159        Self::Eval(e)
160    }
161}
162
163impl FormulaError {
164    /// The Excel worksheet error behind this failure, if any. Convenience
165    /// for callers that want to render `#DIV/0!`-style results.
166    #[must_use]
167    pub const fn excel_error(&self) -> Option<ExcelError> {
168        match self {
169            Self::Eval(e) => Some(*e),
170            _ => None,
171        }
172    }
173}