formcalc 0.1.0

A powerful formula evaluation engine with dependency management and parallel execution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use crate::cache::{FormulaResultCache, FunctionCache, FunctionResultCache, VariableCache};
use crate::error::{CalculatorError, Result};
use crate::formula::{Formula, FormulaT};
use crate::function::{build_function_id, Function};
use crate::graph::DAGraph;
use crate::parser::{Evaluator, Parser};
use crate::value::Value;
use rayon::prelude::*;
use std::collections::HashMap;
use std::sync::Arc;

/// Main engine for parsing and executing formulas with dependency resolution.
///
/// The `Engine` manages variables, functions, formula results, and automatically
/// resolves dependencies between formulas to execute them in the correct order.
/// Formulas in the same dependency layer are executed in parallel for optimal performance.
///
/// # Examples
///
/// ```
/// use formcalc::{Engine, Formula, Value};
///
/// let mut engine = Engine::new();
/// engine.set_variable("x".to_string(), Value::Number(10.0));
///
/// let formula = Formula::new("doubled", "return x * 2");
/// engine.execute(vec![formula]).unwrap();
///
/// let result = engine.get_result("doubled").unwrap();
/// assert_eq!(result, Value::Number(20.0));
/// ```
pub struct Engine {
    variable_cache: VariableCache,
    formula_result_cache: FormulaResultCache,
    function_cache: FunctionCache,
    function_result_cache: FunctionResultCache,
    errors: HashMap<String, String>,
}

impl Engine {
    /// Creates a new `Engine` instance with empty caches.
    ///
    /// # Examples
    ///
    /// ```
    /// use formcalc::Engine;
    ///
    /// let engine = Engine::new();
    /// ```
    pub fn new() -> Self {
        Self {
            variable_cache: VariableCache::new(),
            formula_result_cache: FormulaResultCache::new(),
            function_cache: FunctionCache::new(),
            function_result_cache: FunctionResultCache::new(),
            errors: HashMap::new(),
        }
    }

    /// Sets a variable that can be referenced in formulas.
    ///
    /// Variables can be used directly in formula expressions by name.
    ///
    /// # Arguments
    ///
    /// * `name` - The variable name
    /// * `value` - The value to assign to the variable
    ///
    /// # Examples
    ///
    /// ```
    /// use formcalc::{Engine, Value};
    ///
    /// let mut engine = Engine::new();
    /// engine.set_variable("pi".to_string(), Value::Number(3.14159));
    /// ```
    pub fn set_variable(&mut self, name: String, value: Value) {
        self.variable_cache.set(name, value);
    }

    /// Registers a custom function that can be called from formulas.
    ///
    /// Functions are identified by their name and number of arguments.
    /// You can register multiple functions with the same name but different arities.
    ///
    /// # Arguments
    ///
    /// * `function` - An `Arc` containing a type implementing the [`Function`] trait
    ///
    /// # Examples
    ///
    /// ```
    /// use formcalc::{Engine, Function, Value, Result, CalculatorError};
    /// use std::sync::Arc;
    ///
    /// struct SquareFunction;
    ///
    /// impl Function for SquareFunction {
    ///     fn name(&self) -> &str { "square" }
    ///     fn num_args(&self) -> usize { 1 }
    ///     fn execute(&self, params: &[Value]) -> Result<Value> {
    ///         match params[0] {
    ///             Value::Number(n) => Ok(Value::Number(n * n)),
    ///             _ => Err(CalculatorError::TypeError("Expected number".to_string())),
    ///         }
    ///     }
    /// }
    ///
    /// let mut engine = Engine::new();
    /// engine.register_function(Arc::new(SquareFunction));
    /// ```
    pub fn register_function(&mut self, function: Arc<dyn Function>) {
        let function_id = build_function_id(function.name(), function.num_args());
        self.function_cache.set(function_id, function);
    }

    /// Executes multiple formulas with automatic dependency resolution.
    ///
    /// The engine analyzes dependencies between formulas (via `get_output_from` calls),
    /// builds a dependency graph, and executes formulas in topological order.
    /// Formulas in the same dependency layer are executed in parallel for performance.
    ///
    /// # Arguments
    ///
    /// * `formulas` - A vector of [`Formula`] instances to execute
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if dependency resolution succeeds, or an error if there are
    /// circular dependencies or invalid graph structures.
    ///
    /// Individual formula execution errors are captured and available via [`Engine::get_errors`].
    ///
    /// # Examples
    ///
    /// ```
    /// use formcalc::{Engine, Formula, Value};
    ///
    /// let mut engine = Engine::new();
    ///
    /// let f1 = Formula::new("a", "return 10");
    /// let f2 = Formula::new("b", "return get_output_from('a') * 2");
    /// let f3 = Formula::new("c", "return get_output_from('b') + 5");
    ///
    /// engine.execute(vec![f1, f2, f3]).unwrap();
    ///
    /// assert_eq!(engine.get_result("c"), Some(Value::Number(25.0)));
    /// ```
    pub fn execute(&mut self, formulas: Vec<Formula>) -> Result<()> {
        let mut graph = DAGraph::new();

        // Build dependency graph
        for formula in &formulas {
            graph
                .add_node(
                    formula.name().to_string(),
                    formula.clone(),
                    formula.depends_on().to_vec(),
                )
                .map_err(CalculatorError::DependencyError)?;
        }

        // Topological sort to get execution order
        let (layers, detached) = graph.topological_sort();

        // Handle detached (unresolvable) formulas
        for formula_name in detached {
            let error_msg = format!(
                "Could not resolve dependency path for formula: '{}'",
                formula_name
            );
            self.errors.insert(formula_name, error_msg);
        }

        // Execute formulas layer by layer
        // Formulas in the same layer can be executed in parallel
        for layer in layers {
            self.execute_layer_parallel(&graph, layer);
        }

        Ok(())
    }

    /// Execute all formulas in a layer in parallel
    fn execute_layer_parallel(&mut self, graph: &DAGraph<String, Formula>, layer: Vec<String>) {
        // Execute formulas in parallel
        let results: Vec<(String, Result<Value>)> = layer
            .par_iter()
            .filter_map(|formula_name| {
                graph.get(formula_name).map(|formula| {
                    let result = self.try_execute_formula(formula);
                    (formula_name.clone(), result)
                })
            })
            .collect();

        // Process results sequentially to update caches and collect errors
        for (formula_name, result) in results {
            match result {
                Ok(value) => {
                    self.formula_result_cache.set(formula_name, value);
                }
                Err(e) => {
                    let error_msg = format!("Error executing formula '{}': {}", formula_name, e);
                    self.errors.insert(formula_name, error_msg);
                }
            }
        }
    }

    fn try_execute_formula(&self, formula: &Formula) -> Result<Value> {
        let mut parser = Parser::new(formula.body())?;
        let program = parser.parse()?;

        let evaluator = Evaluator::new(
            self.variable_cache.clone(),
            self.formula_result_cache.clone(),
            self.function_cache.clone(),
            self.function_result_cache.clone(),
        );

        evaluator.evaluate(&program)
    }

    /// Retrieves the result of a previously executed formula.
    ///
    /// # Arguments
    ///
    /// * `formula_name` - The name of the formula whose result to retrieve
    ///
    /// # Returns
    ///
    /// Returns `Some(Value)` if the formula executed successfully, or `None` if the
    /// formula hasn't been executed or failed with an error.
    ///
    /// # Examples
    ///
    /// ```
    /// use formcalc::{Engine, Formula, Value};
    ///
    /// let mut engine = Engine::new();
    /// let formula = Formula::new("test", "return 42");
    /// engine.execute(vec![formula]).unwrap();
    ///
    /// assert_eq!(engine.get_result("test"), Some(Value::Number(42.0)));
    /// assert_eq!(engine.get_result("nonexistent"), None);
    /// ```
    pub fn get_result(&self, formula_name: &str) -> Option<Value> {
        self.formula_result_cache.get(formula_name)
    }

    /// Returns a map of all errors that occurred during the last execution.
    ///
    /// The map keys are formula names and values are error messages.
    ///
    /// # Examples
    ///
    /// ```
    /// use formcalc::{Engine, Formula};
    ///
    /// let mut engine = Engine::new();
    /// let formula = Formula::new("bad", "return 1 / 0");
    /// engine.execute(vec![formula]).unwrap();
    ///
    /// assert!(!engine.get_errors().is_empty());
    /// ```
    pub fn get_errors(&self) -> &HashMap<String, String> {
        &self.errors
    }

    /// Clears all variables, formula results, function result caches, and errors.
    ///
    /// Note: Registered custom functions are preserved.
    ///
    /// # Examples
    ///
    /// ```
    /// use formcalc::{Engine, Formula, Value};
    ///
    /// let mut engine = Engine::new();
    /// engine.set_variable("x".to_string(), Value::Number(10.0));
    /// let formula = Formula::new("test", "return x");
    /// engine.execute(vec![formula]).unwrap();
    ///
    /// engine.clear();
    ///
    /// assert_eq!(engine.get_result("test"), None);
    /// ```
    pub fn clear(&mut self) {
        self.variable_cache.clear();
        self.formula_result_cache.clear();
        self.function_result_cache.clear();
        self.errors.clear();
    }
}

impl Default for Engine {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_formula() {
        let mut engine = Engine::new();
        let formula = Formula::new("test", "return 2 + 2");

        engine.execute(vec![formula]).unwrap();

        let result = engine.get_result("test").unwrap();
        assert_eq!(result, Value::Number(4.0));
    }

    #[test]
    fn test_formula_with_variable() {
        let mut engine = Engine::new();
        engine.set_variable("x".to_string(), Value::Number(10.0));

        let formula = Formula::new("test", "return x * 2");
        engine.execute(vec![formula]).unwrap();

        let result = engine.get_result("test").unwrap();
        assert_eq!(result, Value::Number(20.0));
    }

    #[test]
    fn test_formula_dependencies() {
        let mut engine = Engine::new();

        let formula1 = Formula::new("first", "return 10");
        let formula2 = Formula::new("second", "return get_output_from('first') * 2");

        engine.execute(vec![formula1, formula2]).unwrap();

        // Check for errors
        if !engine.get_errors().is_empty() {
            for (name, error) in engine.get_errors() {
                eprintln!("Error in {}: {}", name, error);
            }
        }

        let result = engine
            .get_result("second")
            .expect("second formula should have result");
        assert_eq!(result, Value::Number(20.0));
    }

    #[test]
    fn test_if_statement() {
        let mut engine = Engine::new();
        let formula = Formula::new("test", "if (5 > 3) then return 100 else return 200 end");

        engine.execute(vec![formula]).unwrap();

        let result = engine.get_result("test").unwrap();
        assert_eq!(result, Value::Number(100.0));
    }

    #[test]
    fn test_parallel_execution() {
        let mut engine = Engine::new();

        // Create multiple independent formulas that can be executed in parallel
        let formulas = vec![
            Formula::new("a", "return 1 + 1"),
            Formula::new("b", "return 2 + 2"),
            Formula::new("c", "return 3 + 3"),
            Formula::new("d", "return 4 + 4"),
            Formula::new("e", "return 5 + 5"),
        ];

        engine.execute(formulas).unwrap();

        assert_eq!(engine.get_result("a").unwrap(), Value::Number(2.0));
        assert_eq!(engine.get_result("b").unwrap(), Value::Number(4.0));
        assert_eq!(engine.get_result("c").unwrap(), Value::Number(6.0));
        assert_eq!(engine.get_result("d").unwrap(), Value::Number(8.0));
        assert_eq!(engine.get_result("e").unwrap(), Value::Number(10.0));
    }

    #[test]
    fn test_parallel_with_dependencies() {
        let mut engine = Engine::new();

        // Layer 0: a, b (can execute in parallel)
        // Layer 1: c, d (can execute in parallel, both depend on layer 0)
        // Layer 2: e (depends on layer 1)
        let formulas = vec![
            Formula::new("a", "return 10"),
            Formula::new("b", "return 20"),
            Formula::new("c", "return get_output_from('a') * 2"),
            Formula::new("d", "return get_output_from('b') * 2"),
            Formula::new("e", "return get_output_from('c') + get_output_from('d')"),
        ];

        engine.execute(formulas).unwrap();

        assert_eq!(engine.get_result("a").unwrap(), Value::Number(10.0));
        assert_eq!(engine.get_result("b").unwrap(), Value::Number(20.0));
        assert_eq!(engine.get_result("c").unwrap(), Value::Number(20.0));
        assert_eq!(engine.get_result("d").unwrap(), Value::Number(40.0));
        assert_eq!(engine.get_result("e").unwrap(), Value::Number(60.0));
    }
}