use alloc::string::String;
use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExcelError {
DivZero,
NA,
Name,
Null,
Num,
Ref,
Value,
}
impl ExcelError {
#[must_use]
pub const fn literal(self) -> &'static str {
match self {
Self::DivZero => "#DIV/0!",
Self::NA => "#N/A",
Self::Name => "#NAME?",
Self::Null => "#NULL!",
Self::Num => "#NUM!",
Self::Ref => "#REF!",
Self::Value => "#VALUE!",
}
}
#[must_use]
pub fn from_literal(lit: &str) -> Option<Self> {
const LITERALS: [(ExcelError, &str); 7] = [
(ExcelError::DivZero, "#DIV/0!"),
(ExcelError::Value, "#VALUE!"),
(ExcelError::Name, "#NAME?"),
(ExcelError::Null, "#NULL!"),
(ExcelError::Num, "#NUM!"),
(ExcelError::Ref, "#REF!"),
(ExcelError::NA, "#N/A"),
];
LITERALS
.iter()
.find(|(_, s)| lit.eq_ignore_ascii_case(s))
.map(|(e, _)| *e)
}
}
impl fmt::Display for ExcelError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.literal())
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum FormulaError {
#[error("tokenize error at byte {pos}: unexpected {char:?}")]
Tokenize {
pos: usize,
char: char,
},
#[error("parse error at byte {pos}: expected {expected}, got {got}")]
Parse {
pos: usize,
expected: &'static str,
got: String,
},
#[error("evaluation error: {0}")]
Eval(ExcelError),
#[error("unknown function: {0}")]
UnknownFunction(String),
#[error("recursion limit exceeded")]
RecursionLimit,
#[error("invalid range argument")]
InvalidRange,
}
impl From<ExcelError> for FormulaError {
fn from(e: ExcelError) -> Self {
Self::Eval(e)
}
}
impl FormulaError {
#[must_use]
pub const fn excel_error(&self) -> Option<ExcelError> {
match self {
Self::Eval(e) => Some(*e),
_ => None,
}
}
}