truecalc_core/engine/
mod.rs1use std::collections::HashMap;
2
3use crate::eval::{evaluate_expr, Context, EvalCtx};
4use crate::eval::functions::Registry;
5use crate::parser::parse;
6use crate::types::{ErrorKind, Value};
7
8pub struct Engine {
9 registry: Registry,
10}
11
12impl Engine {
13 pub fn google_sheets() -> Self {
14 Self { registry: Registry::new() }
15 }
16
17 pub fn evaluate(&self, formula: &str, variables: &HashMap<String, Value>) -> Value {
18 match parse(formula) {
19 Err(_) => Value::Error(ErrorKind::Value),
20 Ok(expr) => {
21 let ctx = Context::new(variables.clone());
22 let mut eval_ctx = EvalCtx::new(ctx, &self.registry);
23 first_of_array(evaluate_expr(&expr, &mut eval_ctx))
24 }
25 }
26 }
27}
28
29fn first_of_array(v: Value) -> Value {
30 match v {
31 Value::Array(elems) if !elems.is_empty() => {
32 first_of_array(elems.into_iter().next().unwrap())
33 }
34 other => other,
35 }
36}
37
38#[cfg(test)]
39mod tests;