Skip to main content

sheet_engine/
error.rs

1//! The engine's error taxonomy — one error per failure domain, plus the
2//! circular-reference report.
3//!
4//! Deliberately exhaustive (no `#[non_exhaustive]`): callers match every
5//! variant, and a new variant is a semver-minor event. The three wrapped
6//! error types are the three dependencies' own — no information is
7//! re-wrapped away.
8
9use crate::CellId;
10use core::fmt;
11use formula_lang::FormulaError;
12use sheet_xlsx::XlsxError;
13
14/// Everything that can fail while driving the calculation engine.
15///
16/// Parsing, dependency extraction, and XLSX coding delegate to their
17/// crates' own errors. The engine adds exactly two of its own: a rejected
18/// workbook (duplicate sheet names on load) and the circular-reference
19/// report.
20#[derive(Debug)]
21pub enum EngineError {
22    /// The formula text did not tokenize or parse
23    /// (`=SUM(`, `=Nope(1)`, `=A1048577`).
24    Formula(FormulaError),
25    /// The formula's references could not be modeled as dependency edges —
26    /// most commonly [`sheet_core::GraphError::RangeTooLarge`] for a range
27    /// wider than `sheet_core::refs::RANGE_CELL_CAP` cells.
28    Graph(sheet_core::GraphError),
29    /// The XLSX codec failed to read or write a workbook.
30    Xlsx(XlsxError),
31    /// The workbook contains circular references. The payload lists every
32    /// cell that sits on a cycle (members of multi-cell cycles, plus
33    /// self-references), sorted for determinism. Everything *not* on a
34    /// cycle was still evaluated before this error was raised — Excel
35    /// semantics: the rest of the workbook computes.
36    CircularReference(Vec<CellId>),
37    /// `from_xlsx` met two `<sheet>` elements with the same name. The
38    /// engine keys sheets by name; it refuses to silently merge them.
39    DuplicateSheet(String),
40    /// The formula references the very last grid cell *and* a
41    /// sheet-qualified reference: no stub coordinate space remains above
42    /// its local references for the cross-sheet rewrite. Rare to the
43    /// point of pathology — `XFD1048576` plus a cross-sheet read.
44    StubSpaceExhausted,
45}
46
47impl fmt::Display for EngineError {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::Formula(e) => write!(f, "formula error: {e}"),
51            Self::Graph(e) => write!(f, "dependency graph error: {e}"),
52            Self::Xlsx(e) => write!(f, "xlsx error: {e}"),
53            Self::CircularReference(cells) => {
54                write!(f, "circular reference involving ")?;
55                for (i, (sheet, row, col)) in cells.iter().enumerate() {
56                    if i > 0 {
57                        write!(f, ", ")?;
58                    }
59                    write!(f, "{sheet}!r{row}c{col}")?;
60                }
61                Ok(())
62            }
63            Self::DuplicateSheet(name) => write!(f, "duplicate sheet name {name:?}"),
64            Self::StubSpaceExhausted => write!(
65                f,
66                "formula mixes a reference to XFD1048576 with a sheet-qualified \
67                 reference; no stub coordinate space remains for the rewrite"
68            ),
69        }
70    }
71}
72
73impl std::error::Error for EngineError {
74    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
75        match self {
76            Self::Formula(e) => Some(e),
77            Self::Graph(e) => Some(e),
78            Self::Xlsx(e) => Some(e),
79            Self::CircularReference(_) | Self::DuplicateSheet(_) | Self::StubSpaceExhausted => None,
80        }
81    }
82}
83
84impl From<FormulaError> for EngineError {
85    fn from(e: FormulaError) -> Self {
86        Self::Formula(e)
87    }
88}
89
90impl From<sheet_core::GraphError> for EngineError {
91    fn from(e: sheet_core::GraphError) -> Self {
92        Self::Graph(e)
93    }
94}
95
96impl From<XlsxError> for EngineError {
97    fn from(e: XlsxError) -> Self {
98        Self::Xlsx(e)
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
105
106    use super::EngineError;
107
108    #[test]
109    fn graph_errors_display_and_chain() {
110        let e = EngineError::Graph(sheet_core::GraphError::EmptyFormula);
111        assert!(e.to_string().starts_with("dependency graph error:"));
112        let source = std::error::Error::source(&e).expect("chains");
113        assert!(source.to_string().contains("formula"));
114    }
115
116    #[test]
117    fn xlsx_errors_display_and_chain() {
118        let e = EngineError::Xlsx(sheet_xlsx::XlsxError::MissingPart {
119            part: String::from("p"),
120        });
121        assert!(e.to_string().starts_with("xlsx error:"));
122        assert!(std::error::Error::source(&e).is_some());
123    }
124
125    #[test]
126    fn from_impls_wrap_without_loss() {
127        let f: EngineError = formula_lang::FormulaError::InvalidRange.into();
128        assert!(matches!(f, EngineError::Formula(_)));
129        let g: EngineError = sheet_core::GraphError::EmptyFormula.into();
130        assert!(matches!(g, EngineError::Graph(_)));
131    }
132}