Skip to main content

zeno_std/
math.rs

1use zenocore::{Diagnostic, Engine, InputMeta, SlotMeta, Value};
2use zenocore::slots::resolve_node_value;
3use evalexpr::{ContextWithMutableFunctions, ContextWithMutableVariables};
4use std::collections::HashMap;
5use std::sync::Arc;
6
7pub fn register(engine: &mut Engine) {
8    // ==========================================
9    // MATH.CALC
10    // ==========================================
11    engine.register(
12        "math.calc",
13        Arc::new(|engine, _ctx, node, scope| {
14            let mut expression_str = String::new();
15            let mut target = "calc_result".to_string();
16
17            if node.value.is_some() {
18                expression_str = resolve_node_value(engine, node, scope).to_string_coerce();
19            }
20
21            for c in &node.children {
22                if c.name == "val" || c.name == "expr" {
23                    expression_str = engine.resolve_shorthand_value(c, scope).to_string_coerce();
24                }
25                if c.name == "as" {
26                    if let Some(ref cv) = c.value {
27                        target = cv.trim_start_matches('$').to_string();
28                    }
29                }
30            }
31
32            if expression_str.is_empty() {
33                return Err(Diagnostic {
34                    r#type: "error".to_string(),
35                    message: "math.calc: expression is required".to_string(),
36                    filename: node.filename.clone(),
37                    line: node.line,
38                    col: node.col,
39                    slot: Some("math.calc".to_string()),
40                });
41            }
42
43            let clean_expr = expression_str.replace('$', "");
44            let mut eval_context = evalexpr::HashMapContext::new();
45
46            for (k, v) in scope.to_map() {
47                let eval_val = match v {
48                    Value::Nil => evalexpr::Value::Empty,
49                    Value::Bool(b) => evalexpr::Value::Boolean(b),
50                    Value::Int(i) => evalexpr::Value::Float(i as f64),
51                    Value::Float(f) => evalexpr::Value::Float(f),
52                    Value::String(s) => {
53                        if let Ok(i) = s.parse::<i64>() {
54                            evalexpr::Value::Float(i as f64)
55                        } else if let Ok(f) = s.parse::<f64>() {
56                            evalexpr::Value::Float(f)
57                        } else {
58                            evalexpr::Value::String(s)
59                        }
60                    }
61                    _ => evalexpr::Value::Empty,
62                };
63                let _ = eval_context.set_value(k.into(), eval_val);
64            }
65
66            // Inject standard math functions
67            let _ = eval_context.set_function("ceil".into(), evalexpr::Function::new(|v| {
68                let f = match v {
69                    evalexpr::Value::Float(f) => *f,
70                    evalexpr::Value::Int(i) => *i as f64,
71                    _ => return Err(evalexpr::EvalexprError::expected_number(v.clone())),
72                };
73                Ok(evalexpr::Value::Float(f.ceil()))
74            }));
75            let _ = eval_context.set_function("floor".into(), evalexpr::Function::new(|v| {
76                let f = match v {
77                    evalexpr::Value::Float(f) => *f,
78                    evalexpr::Value::Int(i) => *i as f64,
79                    _ => return Err(evalexpr::EvalexprError::expected_number(v.clone())),
80                };
81                Ok(evalexpr::Value::Float(f.floor()))
82            }));
83            let _ = eval_context.set_function("round".into(), evalexpr::Function::new(|v| {
84                let f = match v {
85                    evalexpr::Value::Float(f) => *f,
86                    evalexpr::Value::Int(i) => *i as f64,
87                    _ => return Err(evalexpr::EvalexprError::expected_number(v.clone())),
88                };
89                Ok(evalexpr::Value::Float(f.round()))
90            }));
91            let _ = eval_context.set_function("abs".into(), evalexpr::Function::new(|v| {
92                match v {
93                    evalexpr::Value::Float(f) => Ok(evalexpr::Value::Float((*f).abs())),
94                    evalexpr::Value::Int(i) => Ok(evalexpr::Value::Int((*i).abs())),
95                    _ => Err(evalexpr::EvalexprError::expected_number(v.clone())),
96                }
97            }));
98            let _ = eval_context.set_function("sqrt".into(), evalexpr::Function::new(|v| {
99                let f = match v {
100                    evalexpr::Value::Float(f) => *f,
101                    evalexpr::Value::Int(i) => *i as f64,
102                    _ => return Err(evalexpr::EvalexprError::expected_number(v.clone())),
103                };
104                Ok(evalexpr::Value::Float(f.sqrt()))
105            }));
106            let _ = eval_context.set_function("pow".into(), evalexpr::Function::new(|v| {
107                let args = match v {
108                    evalexpr::Value::Tuple(vec) => vec,
109                    _ => return Err(evalexpr::EvalexprError::expected_tuple(v.clone())),
110                };
111                if args.len() != 2 {
112                    return Err(evalexpr::EvalexprError::expected_tuple(v.clone()));
113                }
114                let base = match &args[0] {
115                    evalexpr::Value::Float(f) => *f,
116                    evalexpr::Value::Int(i) => *i as f64,
117                    _ => return Err(evalexpr::EvalexprError::expected_number(args[0].clone())),
118                };
119                let exp = match &args[1] {
120                    evalexpr::Value::Float(f) => *f,
121                    evalexpr::Value::Int(i) => *i as f64,
122                    _ => return Err(evalexpr::EvalexprError::expected_number(args[1].clone())),
123                };
124                Ok(evalexpr::Value::Float(base.powf(exp)))
125            }));
126            let _ = eval_context.set_function("max".into(), evalexpr::Function::new(|v| {
127                let args = match v {
128                    evalexpr::Value::Tuple(vec) => vec,
129                    _ => return Err(evalexpr::EvalexprError::expected_tuple(v.clone())),
130                };
131                if args.is_empty() {
132                    return Err(evalexpr::EvalexprError::expected_tuple(v.clone()));
133                }
134                let mut max_val = f64::MIN;
135                for arg in args {
136                    let f = match arg {
137                        evalexpr::Value::Float(f) => *f,
138                        evalexpr::Value::Int(i) => *i as f64,
139                        _ => return Err(evalexpr::EvalexprError::expected_number(arg.clone())),
140                    };
141                    if f > max_val {
142                        max_val = f;
143                    }
144                }
145                Ok(evalexpr::Value::Float(max_val))
146            }));
147            let _ = eval_context.set_function("min".into(), evalexpr::Function::new(|v| {
148                let args = match v {
149                    evalexpr::Value::Tuple(vec) => vec,
150                    _ => return Err(evalexpr::EvalexprError::expected_tuple(v.clone())),
151                };
152                if args.is_empty() {
153                    return Err(evalexpr::EvalexprError::expected_tuple(v.clone()));
154                }
155                let mut min_val = f64::MAX;
156                for arg in args {
157                    let f = match arg {
158                        evalexpr::Value::Float(f) => *f,
159                        evalexpr::Value::Int(i) => *i as f64,
160                        _ => return Err(evalexpr::EvalexprError::expected_number(arg.clone())),
161                    };
162                    if f < min_val {
163                        min_val = f;
164                    }
165                }
166                Ok(evalexpr::Value::Float(min_val))
167            }));
168
169            let eval_result = evalexpr::eval_with_context(&clean_expr, &eval_context).map_err(|e| Diagnostic {
170                r#type: "error".to_string(),
171                message: format!("math.calc: error evaluating '{}': {}", expression_str, e),
172                filename: node.filename.clone(),
173                line: node.line,
174                col: node.col,
175                slot: Some("math.calc".to_string()),
176            })?;
177
178            let final_val = match eval_result {
179                evalexpr::Value::Int(i) => Value::Int(i),
180                evalexpr::Value::Float(f) => Value::Float(f),
181                evalexpr::Value::Boolean(b) => Value::Bool(b),
182                evalexpr::Value::String(s) => Value::String(s),
183                _ => Value::Nil,
184            };
185
186            scope.set(&target, final_val);
187            Ok(())
188        }),
189        SlotMeta {
190            description: "Evaluate a mathematical expression string.".to_string(),
191            example: "math.calc: ceil($total / 10)\n  as: $pages".to_string(),
192            inputs: {
193                let mut m = HashMap::new();
194                m.insert("as".to_string(), InputMeta { description: "Target variable".to_string(), required: false, r#type: "any".to_string() });
195                m.insert("val".to_string(), InputMeta { description: "Math expression".to_string(), required: false, r#type: "string".to_string() });
196                m.insert("expr".to_string(), InputMeta { description: "Math expression".to_string(), required: false, r#type: "string".to_string() });
197                m
198            },
199            required_blocks: Vec::new(),
200            value_type: String::new(),
201        },
202    );
203
204    // ==========================================
205    // MONEY.CALC
206    // ==========================================
207    engine.register(
208        "money.calc",
209        Arc::new(|engine, _ctx, node, scope| {
210            let mut expression_str = String::new();
211            let mut target = "money_result".to_string();
212
213            if node.value.is_some() {
214                expression_str = resolve_node_value(engine, node, scope).to_string_coerce();
215            }
216
217            for c in &node.children {
218                if c.name == "val" {
219                    expression_str = engine.resolve_shorthand_value(c, scope).to_string_coerce();
220                }
221                if c.name == "as" {
222                    if let Some(ref cv) = c.value {
223                        target = cv.trim_start_matches('$').to_string();
224                    }
225                }
226            }
227
228            if expression_str.is_empty() {
229                return Err(Diagnostic {
230                    r#type: "error".to_string(),
231                    message: "money.calc: expression is required".to_string(),
232                    filename: node.filename.clone(),
233                    line: node.line,
234                    col: node.col,
235                    slot: Some("money.calc".to_string()),
236                });
237            }
238
239            let clean_expr = expression_str.replace('$', "");
240            let mut eval_context = evalexpr::HashMapContext::new();
241
242            for (k, v) in scope.to_map() {
243                let eval_val = match v {
244                    Value::Nil => evalexpr::Value::Empty,
245                    Value::Bool(b) => evalexpr::Value::Boolean(b),
246                    Value::Int(i) => evalexpr::Value::Int(i),
247                    Value::Float(f) => evalexpr::Value::Float(f),
248                    Value::String(s) => {
249                        if let Ok(i) = s.parse::<i64>() {
250                            evalexpr::Value::Int(i)
251                        } else if let Ok(f) = s.parse::<f64>() {
252                            evalexpr::Value::Float(f)
253                        } else {
254                            evalexpr::Value::String(s)
255                        }
256                    }
257                    _ => evalexpr::Value::Empty,
258                };
259                let _ = eval_context.set_value(k.into(), eval_val);
260            }
261
262            let eval_result = evalexpr::eval_with_context(&clean_expr, &eval_context).map_err(|e| Diagnostic {
263                r#type: "error".to_string(),
264                message: format!("money.calc: error evaluating '{}': {}", expression_str, e),
265                filename: node.filename.clone(),
266                line: node.line,
267                col: node.col,
268                slot: Some("money.calc".to_string()),
269            })?;
270
271            let decimal_str = match eval_result {
272                evalexpr::Value::Int(i) => {
273                    use rust_decimal::prelude::FromPrimitive;
274                    if let Some(d) = rust_decimal::Decimal::from_i64(i) {
275                        d.to_string()
276                    } else {
277                        i.to_string()
278                    }
279                }
280                evalexpr::Value::Float(f) => {
281                    use rust_decimal::prelude::FromPrimitive;
282                    if let Some(d) = rust_decimal::Decimal::from_f64(f) {
283                        d.normalize().to_string()
284                    } else {
285                        f.to_string()
286                    }
287                }
288                evalexpr::Value::String(s) => s,
289                _ => "0".to_string(),
290            };
291
292            scope.set(&target, Value::String(decimal_str));
293            Ok(())
294        }),
295        SlotMeta {
296            description: "Financial math calculations using high precision decimals.".to_string(),
297            example: "money.calc: ($harga * $qty) - $diskon\n  as: $total".to_string(),
298            inputs: {
299                let mut m = HashMap::new();
300                m.insert("as".to_string(), InputMeta { description: "Target variable".to_string(), required: false, r#type: "any".to_string() });
301                m.insert("val".to_string(), InputMeta { description: "Financial expression".to_string(), required: false, r#type: "string".to_string() });
302                m
303            },
304            required_blocks: Vec::new(),
305            value_type: String::new(),
306        },
307    );
308}