use crate::CellId;
use core::fmt;
use formula_lang::FormulaError;
use sheet_xlsx::XlsxError;
#[derive(Debug)]
pub enum EngineError {
Formula(FormulaError),
Graph(sheet_core::GraphError),
Xlsx(XlsxError),
CircularReference(Vec<CellId>),
DuplicateSheet(String),
StubSpaceExhausted,
}
impl fmt::Display for EngineError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Formula(e) => write!(f, "formula error: {e}"),
Self::Graph(e) => write!(f, "dependency graph error: {e}"),
Self::Xlsx(e) => write!(f, "xlsx error: {e}"),
Self::CircularReference(cells) => {
write!(f, "circular reference involving ")?;
for (i, (sheet, row, col)) in cells.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{sheet}!r{row}c{col}")?;
}
Ok(())
}
Self::DuplicateSheet(name) => write!(f, "duplicate sheet name {name:?}"),
Self::StubSpaceExhausted => write!(
f,
"formula mixes a reference to XFD1048576 with a sheet-qualified \
reference; no stub coordinate space remains for the rewrite"
),
}
}
}
impl std::error::Error for EngineError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Formula(e) => Some(e),
Self::Graph(e) => Some(e),
Self::Xlsx(e) => Some(e),
Self::CircularReference(_) | Self::DuplicateSheet(_) | Self::StubSpaceExhausted => None,
}
}
}
impl From<FormulaError> for EngineError {
fn from(e: FormulaError) -> Self {
Self::Formula(e)
}
}
impl From<sheet_core::GraphError> for EngineError {
fn from(e: sheet_core::GraphError) -> Self {
Self::Graph(e)
}
}
impl From<XlsxError> for EngineError {
fn from(e: XlsxError) -> Self {
Self::Xlsx(e)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::EngineError;
#[test]
fn graph_errors_display_and_chain() {
let e = EngineError::Graph(sheet_core::GraphError::EmptyFormula);
assert!(e.to_string().starts_with("dependency graph error:"));
let source = std::error::Error::source(&e).expect("chains");
assert!(source.to_string().contains("formula"));
}
#[test]
fn xlsx_errors_display_and_chain() {
let e = EngineError::Xlsx(sheet_xlsx::XlsxError::MissingPart {
part: String::from("p"),
});
assert!(e.to_string().starts_with("xlsx error:"));
assert!(std::error::Error::source(&e).is_some());
}
#[test]
fn from_impls_wrap_without_loss() {
let f: EngineError = formula_lang::FormulaError::InvalidRange.into();
assert!(matches!(f, EngineError::Formula(_)));
let g: EngineError = sheet_core::GraphError::EmptyFormula.into();
assert!(matches!(g, EngineError::Graph(_)));
}
}