formualizer-common 3.0.0

Core value, reference, and error types shared across the Formualizer parser and engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Excel-style error representation that is both ergonomic **now**
//! *and* flexible enough to grow new, data-rich variants later.
//!
//! - **`ExcelErrorKind`** : the canonical set of Excel error codes  
//! - **`ErrorContext`**   : lightweight, sheet-agnostic location info  
//! - **`ExcelErrorExtra`**: per-kind “extension slot” (e.g. `Spill`)  
//! - **`ExcelError`**     : one struct that glues the three together
//!
//! When a future error needs its own payload, just add another variant
//! to `ExcelErrorExtra`; existing code does not break.

use std::{error::Error, fmt};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::LiteralValue;

/// All recognised Excel error codes.
///
/// **Note:** names are CamelCase (idiomatic Rust) while `Display`
/// renders them exactly as Excel shows them (`#DIV/0!`, …).
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ExcelErrorKind {
    Null,
    Ref,
    Name,
    Value,
    Div,
    Na,
    Num,
    Error,
    NImpl,
    Spill,
    Calc,
    Circ,
    Cancelled,
}

impl fmt::Display for ExcelErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Null => "#NULL!",
            Self::Ref => "#REF!",
            Self::Name => "#NAME?",
            Self::Value => "#VALUE!",
            Self::Div => "#DIV/0!",
            Self::Na => "#N/A",
            Self::Num => "#NUM!",
            Self::Error => "#ERROR!",
            Self::NImpl => "#N/IMPL!",
            Self::Spill => "#SPILL!",
            Self::Calc => "#CALC!",
            Self::Circ => "#CIRC!",
            Self::Cancelled => "#CANCELLED!",
        })
    }
}

impl ExcelErrorKind {
    pub fn try_parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "#null!" => Some(Self::Null),
            "#ref!" => Some(Self::Ref),
            "#name?" => Some(Self::Name),
            "#value!" => Some(Self::Value),
            "#div/0!" => Some(Self::Div),
            "#n/a" => Some(Self::Na),
            "#num!" => Some(Self::Num),
            "#error!" => Some(Self::Error),
            "#n/impl!" => Some(Self::NImpl),
            "#spill!" => Some(Self::Spill),
            "#calc!" => Some(Self::Calc),
            "#circ!" => Some(Self::Circ),
            "#cancelled!" => Some(Self::Cancelled),
            _ => None,
        }
    }

    pub fn parse(s: &str) -> Self {
        Self::try_parse(s).unwrap_or(Self::Error)
    }
}

/// Generic, lightweight metadata that *any* error may carry.
///
/// Keep this minimal—anything only one error kind needs belongs in
/// `ExcelErrorExtra`.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct ErrorContext {
    pub row: Option<u32>,
    pub col: Option<u32>,
    // Origin location where the error first occurred (if different from row/col)
    pub origin_row: Option<u32>,
    pub origin_col: Option<u32>,
    pub origin_sheet: Option<String>,
}

/// Stable reason for a resource exhaustion diagnostic.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ResourceExhaustionReason {
    Admission,
    RetainedMemory,
    ScratchMemory,
    WorkUnits,
    Deadline,
    GraphVertices,
    GraphEdges,
    MaterializationCells,
    ArithmeticOverflow,
}

impl ResourceExhaustionReason {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Admission => "admission",
            Self::RetainedMemory => "retained_memory",
            Self::ScratchMemory => "scratch_memory",
            Self::WorkUnits => "work_units",
            Self::Deadline => "deadline",
            Self::GraphVertices => "graph_vertices",
            Self::GraphEdges => "graph_edges",
            Self::MaterializationCells => "materialization_cells",
            Self::ArithmeticOverflow => "arithmetic_overflow",
        }
    }
}

/// Binding-safe typed resource exhaustion payload.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ResourceExhaustionDetail {
    pub reason: ResourceExhaustionReason,
    pub limit: u64,
    pub observed: u64,
    pub request_id: Option<u64>,
}

/// Stable category for a target-preparation plan rejected at its final boundary.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum PreparationStaleReason {
    Graph,
    Authority,
    Staged,
    Symbols,
    Semantic,
    Provider,
}

impl PreparationStaleReason {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Graph => "graph",
            Self::Authority => "authority",
            Self::Staged => "staged",
            Self::Symbols => "symbols",
            Self::Semantic => "semantic",
            Self::Provider => "provider",
        }
    }
}

/// Stable category for a reusable recalculation plan rejected before execution.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum PlanStaleReason {
    Engine,
    Provider,
    Semantic,
    Budget,
    Staged,
    Symbols,
    Authority,
    SpanGeneration,
    Graph,
}

impl PlanStaleReason {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Engine => "engine",
            Self::Provider => "provider",
            Self::Semantic => "semantic",
            Self::Budget => "budget",
            Self::Staged => "staged",
            Self::Symbols => "symbols",
            Self::Authority => "authority",
            Self::SpanGeneration => "span_generation",
            Self::Graph => "graph",
        }
    }
}

/// Kind-specific payloads (“extension slot”).
///
/// Only variants that need extra data get it—rest stay at `None`.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum ExcelErrorExtra {
    /// No additional payload (the vast majority of errors).
    #[default]
    None,

    /// `#SPILL!` – information about the intended spill size.
    Spill {
        expected_rows: u32,
        expected_cols: u32,
    },

    /// Typed resource exhaustion. The canonical Excel error kind remains
    /// unchanged so existing bindings and formula error handling stay compatible.
    Resource {
        detail: Box<ResourceExhaustionDetail>,
    },

    PreparationStale {
        reason: PreparationStaleReason,
    },

    PlanStale {
        reason: PlanStaleReason,
    },
    // --- Add future custom payloads below -------------------------------
    // AnotherKind { … },
}

/// The single struct your API passes around.
///
/// It combines:
/// * **kind**   – the mandatory Excel error code
/// * **message**– optional human explanation
/// * **context**– generic location†
/// * **extra**  – optional, kind-specific data
///
/// † If you *never* need row/col you can build the value with
///   `ExcelError::from(kind)`, which sets `context = None`.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExcelError {
    pub kind: ExcelErrorKind,
    pub message: Option<String>,
    pub context: Option<ErrorContext>,
    pub extra: ExcelErrorExtra,
}

/* ───────────────────── Constructors & helpers ─────────────────────── */

impl From<ExcelErrorKind> for ExcelError {
    fn from(kind: ExcelErrorKind) -> Self {
        Self {
            kind,
            message: None,
            context: None,
            extra: ExcelErrorExtra::None,
        }
    }
}

impl ExcelError {
    /// Basic constructor (no message, no location, no extra).
    pub fn new(kind: ExcelErrorKind) -> Self {
        kind.into()
    }

    /// Attach a human-readable explanation.
    pub fn with_message<S: Into<String>>(mut self, msg: S) -> Self {
        self.message = Some(msg.into());
        self
    }

    /// Attach generic row/column coordinates.
    pub fn with_location(mut self, row: u32, col: u32) -> Self {
        self.context = Some(ErrorContext {
            row: Some(row),
            col: Some(col),
            origin_row: None,
            origin_col: None,
            origin_sheet: None,
        });
        self
    }

    /// Attach origin location where the error first occurred.
    pub fn with_origin(mut self, sheet: Option<String>, row: u32, col: u32) -> Self {
        if let Some(ref mut ctx) = self.context {
            ctx.origin_sheet = sheet;
            ctx.origin_row = Some(row);
            ctx.origin_col = Some(col);
        } else {
            self.context = Some(ErrorContext {
                row: None,
                col: None,
                origin_row: Some(row),
                origin_col: Some(col),
                origin_sheet: sheet,
            });
        }
        self
    }

    /// Attach kind-specific extra data.
    pub fn with_extra(mut self, extra: ExcelErrorExtra) -> Self {
        self.extra = extra;
        self
    }

    pub fn from_error_string(s: &str) -> Self {
        match ExcelErrorKind::try_parse(s) {
            Some(kind) => Self::new(kind),
            None => {
                Self::new(ExcelErrorKind::Error).with_message(format!("Unknown error code: {s}"))
            }
        }
    }

    pub fn new_value() -> Self {
        Self::new(ExcelErrorKind::Value)
    }

    pub fn new_name() -> Self {
        Self::new(ExcelErrorKind::Name)
    }

    pub fn new_div() -> Self {
        Self::new(ExcelErrorKind::Div)
    }

    pub fn new_ref() -> Self {
        Self::new(ExcelErrorKind::Ref)
    }

    pub fn new_circ() -> Self {
        Self::new(ExcelErrorKind::Circ)
    }

    pub fn new_num() -> Self {
        Self::new(ExcelErrorKind::Num)
    }

    pub fn new_na() -> Self {
        Self::new(ExcelErrorKind::Na)
    }
}

/* ───────────────────────── Display / Error ────────────────────────── */

impl fmt::Display for ExcelError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Start with the canonical code:
        write!(f, "{}", self.kind)?;

        // Optional human message.
        if let Some(ref msg) = self.message {
            write!(f, ": {msg}")?;
        }

        // Optional row/col context.
        if let Some(ref ctx) = self.context {
            if let (Some(r), Some(c)) = (ctx.row, ctx.col) {
                write!(f, " (row {r}, col {c})")?;
            }

            // Show origin if different from the evaluation location
            if let (Some(or), Some(oc)) = (ctx.origin_row, ctx.origin_col) {
                if ctx.row != Some(or) || ctx.col != Some(oc) {
                    if let Some(ref sheet) = ctx.origin_sheet {
                        write!(f, " [origin: {sheet}!R{or}C{oc}]")?;
                    } else {
                        write!(f, " [origin: R{or}C{oc}]")?;
                    }
                }
            }
        }

        // Optional kind-specific payload - keep it terse for logs.
        match &self.extra {
            ExcelErrorExtra::None => {}
            ExcelErrorExtra::Spill {
                expected_rows,
                expected_cols,
            } => {
                write!(f, " [spill {expected_rows}×{expected_cols}]")?;
            }
            ExcelErrorExtra::Resource { detail } => {
                write!(
                    f,
                    " [resource {} {}/{}]",
                    detail.reason.as_str(),
                    detail.observed,
                    detail.limit
                )?;
            }
            ExcelErrorExtra::PreparationStale { reason } => {
                write!(f, " [preparation stale {}]", reason.as_str())?;
            }
            ExcelErrorExtra::PlanStale { reason } => {
                write!(f, " [plan stale {}]", reason.as_str())?;
            }
        }

        Ok(())
    }
}

impl Error for ExcelError {}
impl From<ExcelError> for String {
    fn from(error: ExcelError) -> Self {
        format!("{error}")
    }
}
impl From<ExcelError> for LiteralValue {
    fn from(error: ExcelError) -> Self {
        LiteralValue::Error(error)
    }
}

impl PartialEq<str> for ExcelErrorKind {
    fn eq(&self, other: &str) -> bool {
        format!("{self}") == other
    }
}

impl PartialEq<&str> for ExcelError {
    fn eq(&self, other: &&str) -> bool {
        self.kind.to_string() == *other
    }
}

impl PartialEq<str> for ExcelError {
    fn eq(&self, other: &str) -> bool {
        self.kind.to_string() == other
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_known_error_kind() {
        assert_eq!(ExcelErrorKind::parse("#DIV/0!"), ExcelErrorKind::Div);
        assert_eq!(ExcelErrorKind::parse("#n/a"), ExcelErrorKind::Na);
    }

    #[test]
    fn parse_unknown_error_kind_falls_back() {
        assert_eq!(ExcelErrorKind::parse("#BOGUS!"), ExcelErrorKind::Error);
        let err = ExcelError::from_error_string("#BOGUS!");
        assert_eq!(err.kind, ExcelErrorKind::Error);
        assert!(err.message.unwrap_or_default().contains("#BOGUS!"));
    }

    #[test]
    fn preparation_stale_reason_has_stable_snake_case_names() {
        assert_eq!(PreparationStaleReason::Graph.as_str(), "graph");
        assert_eq!(PreparationStaleReason::Authority.as_str(), "authority");
        assert_eq!(PreparationStaleReason::Staged.as_str(), "staged");
        assert_eq!(PreparationStaleReason::Symbols.as_str(), "symbols");
        assert_eq!(PreparationStaleReason::Semantic.as_str(), "semantic");
        assert_eq!(PreparationStaleReason::Provider.as_str(), "provider");
    }

    #[test]
    fn plan_stale_reason_has_stable_snake_case_names() {
        assert_eq!(PlanStaleReason::Engine.as_str(), "engine");
        assert_eq!(PlanStaleReason::Provider.as_str(), "provider");
        assert_eq!(PlanStaleReason::Semantic.as_str(), "semantic");
        assert_eq!(PlanStaleReason::Budget.as_str(), "budget");
        assert_eq!(PlanStaleReason::Staged.as_str(), "staged");
        assert_eq!(PlanStaleReason::Symbols.as_str(), "symbols");
        assert_eq!(PlanStaleReason::Authority.as_str(), "authority");
        assert_eq!(PlanStaleReason::SpanGeneration.as_str(), "span_generation");
        assert_eq!(PlanStaleReason::Graph.as_str(), "graph");
    }
}