use crate::ast::{normalize_range, Expr};
use crate::error::{ExcelError, FormulaError};
use crate::funcs::{dispatch, Ctx};
use crate::parser::MAX_DEPTH;
use crate::resolver::CellResolver;
use crate::value::Value;
use alloc::vec;
use alloc::vec::Vec;
pub fn evaluate(expr: &Expr, resolver: &dyn CellResolver) -> Result<Value, FormulaError> {
evaluate_with_clock(expr, resolver, system_now_serial())
}
pub fn evaluate_with_clock(
expr: &Expr,
resolver: &dyn CellResolver,
now_serial: f64,
) -> Result<Value, FormulaError> {
let now = if now_serial.is_finite() && now_serial >= 0.0 {
now_serial
} else {
0.0
};
let mut ctx = Ctx {
resolver,
now,
depth: 0,
};
eval(&mut ctx, expr)
}
#[must_use]
pub fn is_volatile(expr: &Expr) -> bool {
let mut stack: Vec<&Expr> = vec![expr];
while let Some(e) = stack.pop() {
match e {
Expr::Function { name, args } => {
if matches!(name.as_str(), "TODAY" | "NOW" | "OFFSET") {
return true;
}
stack.extend(args.iter());
}
Expr::Binary { left, right, .. } => {
stack.push(left);
stack.push(right);
}
Expr::Unary { expr, .. } => stack.push(expr),
_ => {}
}
}
false
}
#[cfg(feature = "std")]
fn system_now_serial() -> f64 {
use ::std::time::{SystemTime, UNIX_EPOCH};
let Ok(d) = SystemTime::now().duration_since(UNIX_EPOCH) else {
return 0.0;
};
let days = d.as_secs_f64() / 86_400.0;
crate::date::UNIX_EPOCH_SERIAL as f64 + days
}
#[cfg(not(feature = "std"))]
fn system_now_serial() -> f64 {
0.0
}
pub(crate) fn eval(ctx: &mut Ctx<'_>, e: &Expr) -> Result<Value, FormulaError> {
ctx.depth += 1;
if ctx.depth > MAX_DEPTH {
return Err(FormulaError::RecursionLimit);
}
let out = eval_inner(ctx, e);
ctx.depth -= 1;
out
}
fn eval_inner(ctx: &mut Ctx<'_>, e: &Expr) -> Result<Value, FormulaError> {
match e {
Expr::Number(n) => {
if n.is_finite() {
Ok(Value::Number(*n))
} else {
Err(ExcelError::Num.into())
}
}
Expr::Text(s) => Ok(Value::Text(s.clone())),
Expr::Boolean(b) => Ok(Value::Boolean(*b)),
Expr::Error(err) => Err(FormulaError::Eval(*err)),
Expr::CellRef { col, row, .. } => {
Ok(ctx.resolver.get(*col, *row).unwrap_or(Value::Empty))
}
Expr::Range { .. } => Err(ExcelError::Value.into()),
Expr::Unary { op, expr } => eval_unary(ctx, *op, expr),
Expr::Binary { op, left, right } => eval_binary(ctx, *op, left, right),
Expr::Function { name, args } => dispatch(ctx, name, args),
}
}
fn eval_unary(
ctx: &mut Ctx<'_>,
op: crate::ast::UnaryOp,
expr: &Expr,
) -> Result<Value, FormulaError> {
use crate::ast::UnaryOp;
let v = eval(ctx, expr)?;
match op {
UnaryOp::Percent => {
let n = checked_num(v)?;
fin(n / 100.0)
}
UnaryOp::Neg => {
let n = checked_num(v)?;
fin(-n)
}
UnaryOp::Pos => {
let n = checked_num(v)?;
fin(n)
}
}
}
fn eval_binary(
ctx: &mut Ctx<'_>,
op: crate::ast::BinaryOp,
left: &Expr,
right: &Expr,
) -> Result<Value, FormulaError> {
use crate::ast::BinaryOp;
use crate::value::{coerce_text, compare};
match op {
BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge => {
let l = eval(ctx, left)?;
let r = eval(ctx, right)?;
let ord = compare(&l, &r).map_err(FormulaError::Eval)?;
let b = match op {
BinaryOp::Eq => ord.is_eq(),
BinaryOp::Ne => !ord.is_eq(),
BinaryOp::Lt => ord.is_lt(),
BinaryOp::Gt => ord.is_gt(),
BinaryOp::Le => !ord.is_gt(),
BinaryOp::Ge => !ord.is_lt(),
_ => unreachable!("comparison arm"),
};
Ok(Value::Boolean(b))
}
BinaryOp::Concat => {
let l = eval(ctx, left)?;
let r = eval(ctx, right)?;
let mut ls = coerce_text(&l).map_err(FormulaError::Eval)?;
let rs = coerce_text(&r).map_err(FormulaError::Eval)?;
ls.push_str(&rs);
Ok(Value::Text(ls))
}
BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Pow => {
let l = checked_num(eval(ctx, left)?)?;
let r = checked_num(eval(ctx, right)?)?;
match op {
BinaryOp::Add => fin(l + r),
BinaryOp::Sub => fin(l - r),
BinaryOp::Mul => fin(l * r),
BinaryOp::Div => {
if r == 0.0 {
Err(ExcelError::DivZero.into())
} else {
fin(l / r)
}
}
BinaryOp::Pow => {
if l == 0.0 && r == 0.0 {
Err(ExcelError::Num.into())
} else if l == 0.0 && r < 0.0 {
Err(ExcelError::DivZero.into())
} else {
fin(libm::pow(l, r))
}
}
_ => unreachable!("arithmetic arm"),
}
}
}
}
fn checked_num(v: Value) -> Result<f64, FormulaError> {
crate::value::coerce_number(&v).map_err(FormulaError::Eval)
}
fn fin(n: f64) -> Result<Value, FormulaError> {
if n.is_finite() {
Ok(Value::Number(n))
} else {
Err(ExcelError::Num.into())
}
}
pub(crate) fn cell_values(ctx: &Ctx<'_>, e: &Expr) -> Result<Option<Vec<Value>>, FormulaError> {
match e {
Expr::CellRef { col, row, .. } => Ok(Some(vec![ctx
.resolver
.get(*col, *row)
.unwrap_or(Value::Empty)])),
Expr::Range { start, end } => {
let (c0, r0, c1, r1) = normalize_range(start, end);
Ok(Some(ctx.resolver.get_range((c0, r0), (c1, r1))))
}
_ => Ok(None),
}
}
pub(crate) fn range_bounds(e: &Expr) -> Result<(u32, u32, u32, u32), FormulaError> {
match e {
Expr::CellRef { col, row, .. } => Ok((*col, *row, *col, *row)),
Expr::Range { start, end } => {
let (c0, r0, c1, r1) = normalize_range(start, end);
if c0 == 0 || c1 == 0 || r0 == 0 || r1 == 0 {
Err(FormulaError::InvalidRange)
} else {
Ok((c0, r0, c1, r1))
}
}
_ => Err(FormulaError::InvalidRange),
}
}
pub(crate) fn is_ref_expr(e: &Expr) -> bool {
matches!(e, Expr::CellRef { .. } | Expr::Range { .. })
}