use std::collections::HashMap;
use crate::eval::functions::Registry;
use crate::eval::{evaluate_expr, Context, EvalCtx};
use crate::parser::{parse_formula, Expr};
use crate::types::{ErrorKind, ParseError, Value};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Flavor {
Sheets,
Excel,
}
pub struct Engine {
flavor: Flavor,
registry: Registry,
}
impl Engine {
pub fn sheets() -> Self {
Self { flavor: Flavor::Sheets, registry: Registry::new() }
}
pub fn excel() -> Self {
Self { flavor: Flavor::Excel, registry: Registry::new() }
}
#[deprecated(note = "use Engine::sheets() — engine flavor is required; see ADR 2026-04-27")]
pub fn google_sheets() -> Self {
Self::sheets()
}
pub fn parse(&self, formula: &str) -> Result<Expr, ParseError> {
parse_formula(formula)
}
pub fn validate(&self, formula: &str) -> Result<(), ParseError> {
self.parse(formula).map(|_| ())
}
pub fn evaluate(&self, formula: &str, variables: &HashMap<String, Value>) -> Value {
if self.flavor == Flavor::Excel {
return Value::Error(ErrorKind::NA);
}
match parse_formula(formula) {
Err(_) => Value::Error(ErrorKind::Value),
Ok(expr) => {
let ctx = Context::new(variables.clone());
let mut eval_ctx = EvalCtx::new(ctx, &self.registry);
first_of_array(evaluate_expr(&expr, &mut eval_ctx))
}
}
}
}
fn first_of_array(v: Value) -> Value {
match v {
Value::Array(elems) if !elems.is_empty() => {
first_of_array(elems.into_iter().next().unwrap())
}
other => other,
}
}
#[cfg(test)]
mod tests;