1use serde::{Deserialize, Serialize};
12use serde_json::{Map, Number, Value};
13use std::fmt;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum BinOp {
18 Add,
19 Sub,
20 Mul,
21 Div,
22 Rem,
23 Eq,
24 Ne,
25 Lt,
26 Le,
27 Gt,
28 Ge,
29 And,
30 Or,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum UnOp {
36 Not,
37 Neg,
38}
39
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41pub struct ObjectField {
42 pub name: String,
43 pub value: Expr,
44}
45
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47#[serde(tag = "op", rename_all = "snake_case")]
48pub enum Expr {
49 Literal {
50 value: Value,
51 },
52 Input {
54 path: Vec<String>,
55 },
56 Step {
58 step: String,
59 path: Vec<String>,
60 },
61 Execution {
63 field: String,
64 },
65 Local {
67 name: String,
68 path: Vec<String>,
69 },
70 Index {
71 target: Box<Expr>,
72 index: Box<Expr>,
73 },
74 Object {
75 fields: Vec<ObjectField>,
76 },
77 List {
78 items: Vec<Expr>,
79 },
80 Binary {
81 operator: BinOp,
82 left: Box<Expr>,
83 right: Box<Expr>,
84 },
85 Unary {
86 operator: UnOp,
87 operand: Box<Expr>,
88 },
89 If {
90 condition: Box<Expr>,
91 then: Box<Expr>,
92 otherwise: Box<Expr>,
93 },
94 Call {
95 function: String,
96 args: Vec<Expr>,
97 },
98 Lambda {
101 param: String,
102 body: Box<Expr>,
103 },
104}
105
106impl Expr {
107 pub fn literal(value: Value) -> Expr {
108 Expr::Literal { value }
109 }
110
111 pub fn step_refs(&self, out: &mut Vec<String>) {
113 match self {
114 Expr::Step { step, .. } => {
115 if !out.contains(step) {
116 out.push(step.clone())
117 }
118 }
119 Expr::Index { target, index } => {
120 target.step_refs(out);
121 index.step_refs(out);
122 }
123 Expr::Object { fields } => fields.iter().for_each(|f| f.value.step_refs(out)),
124 Expr::List { items } | Expr::Call { args: items, .. } => {
125 items.iter().for_each(|e| e.step_refs(out))
126 }
127 Expr::Binary { left, right, .. } => {
128 left.step_refs(out);
129 right.step_refs(out);
130 }
131 Expr::Unary { operand, .. } => operand.step_refs(out),
132 Expr::If {
133 condition,
134 then,
135 otherwise,
136 } => {
137 condition.step_refs(out);
138 then.step_refs(out);
139 otherwise.step_refs(out);
140 }
141 Expr::Lambda { body, .. } => body.step_refs(out),
142 Expr::Literal { .. }
143 | Expr::Input { .. }
144 | Expr::Execution { .. }
145 | Expr::Local { .. } => {}
146 }
147 }
148
149 pub fn contains_lambda(&self) -> bool {
151 match self {
152 Expr::Lambda { .. } => true,
153 Expr::Index { target, index } => target.contains_lambda() || index.contains_lambda(),
154 Expr::Object { fields } => fields.iter().any(|f| f.value.contains_lambda()),
155 Expr::List { items } | Expr::Call { args: items, .. } => {
156 items.iter().any(Expr::contains_lambda)
157 }
158 Expr::Binary { left, right, .. } => left.contains_lambda() || right.contains_lambda(),
159 Expr::Unary { operand, .. } => operand.contains_lambda(),
160 Expr::If {
161 condition,
162 then,
163 otherwise,
164 } => {
165 condition.contains_lambda() || then.contains_lambda() || otherwise.contains_lambda()
166 }
167 Expr::Literal { .. }
168 | Expr::Input { .. }
169 | Expr::Step { .. }
170 | Expr::Execution { .. }
171 | Expr::Local { .. } => false,
172 }
173 }
174}
175
176struct Bound<'a> {
178 parent: &'a dyn Scope,
179 name: &'a str,
180 value: Value,
181}
182
183impl Scope for Bound<'_> {
184 fn input(&self) -> &Value {
185 self.parent.input()
186 }
187 fn step_output(&self, step: &str) -> Option<&Value> {
188 self.parent.step_output(step)
189 }
190 fn execution_field(&self, field: &str) -> Option<Value> {
191 self.parent.execution_field(field)
192 }
193 fn local(&self, name: &str) -> Option<&Value> {
194 if name == self.name {
195 Some(&self.value)
196 } else {
197 self.parent.local(name)
198 }
199 }
200}
201
202pub const HIGHER_ORDER: &[&str] = &["map", "filter", "any", "all", "find"];
204
205fn higher_order(function: &str, args: &[Expr], scope: &dyn Scope) -> Result<Value, EvalError> {
206 let list = match args.first().map(|a| eval(a, scope)).transpose()? {
207 Some(Value::Array(items)) => items,
208 Some(Value::Null) | None => vec![],
209 Some(v) => {
210 return err(format!(
211 "{function}() expects a list, found {}",
212 crate::types::describe(&v)
213 ))
214 }
215 };
216 let Some(Expr::Lambda { param, body }) = args.get(1) else {
217 return err(format!("{function}() expects a lambda such as `x => x`"));
218 };
219 let apply = |item: &Value| -> Result<Value, EvalError> {
220 let bound = Bound {
221 parent: scope,
222 name: param,
223 value: item.clone(),
224 };
225 eval(body, &bound)
226 };
227 let truthy = |v: Value, item: &Value| -> Result<bool, EvalError> {
228 match v {
229 Value::Bool(b) => Ok(b),
230 Value::Null => Ok(false),
231 other => err(format!(
232 "{function}() condition must be Bool, found {} for element {}",
233 crate::types::describe(&other),
234 item
235 )),
236 }
237 };
238 match function {
239 "map" => Ok(Value::Array(
240 list.iter().map(apply).collect::<Result<_, _>>()?,
241 )),
242 "filter" => {
243 let mut out = vec![];
244 for item in list {
245 if truthy(apply(&item)?, &item)? {
246 out.push(item);
247 }
248 }
249 Ok(Value::Array(out))
250 }
251 "any" => {
252 for item in &list {
253 if truthy(apply(item)?, item)? {
254 return Ok(Value::Bool(true));
255 }
256 }
257 Ok(Value::Bool(false))
258 }
259 "all" => {
260 for item in &list {
261 if !truthy(apply(item)?, item)? {
262 return Ok(Value::Bool(false));
263 }
264 }
265 Ok(Value::Bool(true))
266 }
267 "find" => {
268 for item in list {
269 if truthy(apply(&item)?, &item)? {
270 return Ok(item);
271 }
272 }
273 Ok(Value::Null)
274 }
275 _ => err(format!("unknown function `{function}`")),
276 }
277}
278
279pub trait Scope {
281 fn input(&self) -> &Value;
282 fn step_output(&self, step: &str) -> Option<&Value>;
284 fn execution_field(&self, field: &str) -> Option<Value>;
285 fn local(&self, _name: &str) -> Option<&Value> {
287 None
288 }
289}
290
291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
292pub struct EvalError(pub String);
293
294impl fmt::Display for EvalError {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 f.write_str(&self.0)
297 }
298}
299
300impl std::error::Error for EvalError {}
301
302fn err<T>(msg: impl Into<String>) -> Result<T, EvalError> {
303 Err(EvalError(msg.into()))
304}
305
306fn walk(mut v: Value, path: &[String]) -> Value {
307 for seg in path {
308 v = match v {
309 Value::Object(mut m) => m.remove(seg).unwrap_or(Value::Null),
310 _ => return Value::Null,
311 };
312 }
313 v
314}
315
316pub fn eval(expr: &Expr, scope: &dyn Scope) -> Result<Value, EvalError> {
317 match expr {
318 Expr::Literal { value } => Ok(value.clone()),
319 Expr::Input { path } => Ok(walk(scope.input().clone(), path)),
320 Expr::Step { step, path } => match scope.step_output(step) {
321 Some(v) => Ok(walk(v.clone(), path)),
322 None => err(format!("step `{step}` has not completed")),
323 },
324 Expr::Local { name, path } => match scope.local(name) {
325 Some(v) => Ok(walk(v.clone(), path)),
326 None => err(format!("loop variable `{name}` is not bound here")),
327 },
328 Expr::Execution { field } => scope
329 .execution_field(field)
330 .ok_or_else(|| EvalError(format!("unknown execution field `{field}`"))),
331 Expr::Index { target, index } => {
332 let t = eval(target, scope)?;
333 let i = eval(index, scope)?;
334 Ok(match (t, i) {
335 (Value::Null, _) => Value::Null,
336 (Value::Array(items), Value::Number(n)) => {
337 let Some(mut idx) = n.as_i64() else {
338 return err("list index must be an integer");
339 };
340 if idx < 0 {
341 idx += items.len() as i64;
342 }
343 items
344 .into_iter()
345 .nth(idx.max(0) as usize)
346 .filter(|_| idx >= 0)
347 .unwrap_or(Value::Null)
348 }
349 (Value::Object(mut m), Value::String(k)) => m.remove(&k).unwrap_or(Value::Null),
350 (t, i) => {
351 return err(format!(
352 "cannot index {} with {}",
353 crate::types::describe(&t),
354 crate::types::describe(&i)
355 ))
356 }
357 })
358 }
359 Expr::Object { fields } => {
360 let mut m = Map::new();
361 for f in fields {
362 m.insert(f.name.clone(), eval(&f.value, scope)?);
363 }
364 Ok(Value::Object(m))
365 }
366 Expr::List { items } => Ok(Value::Array(
367 items
368 .iter()
369 .map(|e| eval(e, scope))
370 .collect::<Result<_, _>>()?,
371 )),
372 Expr::Unary { operator, operand } => {
373 let v = eval(operand, scope)?;
374 match (operator, v) {
375 (UnOp::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
376 (UnOp::Neg, Value::Number(n)) => match n.as_i64() {
377 Some(i) => i
378 .checked_neg()
379 .map(Value::from)
380 .ok_or_else(|| EvalError("integer overflow".into())),
381 None => Ok(float(-n.as_f64().unwrap_or(0.0))),
382 },
383 (op, v) => err(format!(
384 "cannot apply {op:?} to {}",
385 crate::types::describe(&v)
386 )),
387 }
388 }
389 Expr::Binary {
390 operator,
391 left,
392 right,
393 } => {
394 if matches!(operator, BinOp::And | BinOp::Or) {
396 let l = eval(left, scope)?;
397 let Value::Bool(lb) = l else {
398 return err("logical operator expects Bool");
399 };
400 if (*operator == BinOp::And && !lb) || (*operator == BinOp::Or && lb) {
401 return Ok(Value::Bool(lb));
402 }
403 let r = eval(right, scope)?;
404 return match r {
405 Value::Bool(rb) => Ok(Value::Bool(rb)),
406 _ => err("logical operator expects Bool"),
407 };
408 }
409 let l = eval(left, scope)?;
410 let r = eval(right, scope)?;
411 binary(*operator, l, r)
412 }
413 Expr::If {
414 condition,
415 then,
416 otherwise,
417 } => match eval(condition, scope)? {
418 Value::Bool(true) => eval(then, scope),
419 Value::Bool(false) => eval(otherwise, scope),
420 Value::Null => eval(otherwise, scope),
421 v => err(format!(
422 "`if` condition must be Bool, found {}",
423 crate::types::describe(&v)
424 )),
425 },
426 Expr::Call { function, args } if HIGHER_ORDER.contains(&function.as_str()) => {
427 higher_order(function, args, scope)
428 }
429 Expr::Lambda { .. } => err("a lambda can only be passed to map, filter, any, all or find"),
430 Expr::Call { function, args } => {
431 let vals = args
432 .iter()
433 .map(|a| eval(a, scope))
434 .collect::<Result<Vec<_>, _>>()?;
435 call(function, vals)
436 }
437 }
438}
439
440fn float(f: f64) -> Value {
441 Number::from_f64(f)
442 .map(Value::Number)
443 .unwrap_or(Value::Null)
444}
445
446fn num(v: &Value) -> Option<f64> {
447 v.as_f64()
448}
449
450pub fn values_equal(a: &Value, b: &Value) -> bool {
452 match (a, b) {
453 (Value::Number(x), Value::Number(y)) => match (x.as_i64(), y.as_i64()) {
454 (Some(i), Some(j)) => i == j,
455 _ => x.as_f64() == y.as_f64(),
456 },
457 (Value::Array(x), Value::Array(y)) => {
458 x.len() == y.len() && x.iter().zip(y).all(|(a, b)| values_equal(a, b))
459 }
460 (Value::Object(x), Value::Object(y)) => {
461 x.len() == y.len()
462 && x.iter()
463 .all(|(k, v)| y.get(k).is_some_and(|w| values_equal(v, w)))
464 }
465 _ => a == b,
466 }
467}
468
469fn binary(op: BinOp, l: Value, r: Value) -> Result<Value, EvalError> {
470 use BinOp::*;
471 match op {
472 Eq => return Ok(Value::Bool(values_equal(&l, &r))),
473 Ne => return Ok(Value::Bool(!values_equal(&l, &r))),
474 _ => {}
475 }
476 match (op, &l, &r) {
477 (Add, Value::String(a), Value::String(b)) => Ok(Value::String(format!("{a}{b}"))),
478 (Add, Value::Array(a), Value::Array(b)) => {
479 Ok(Value::Array(a.iter().chain(b).cloned().collect()))
480 }
481 (Lt | Le | Gt | Ge, Value::String(a), Value::String(b)) => Ok(Value::Bool(match op {
482 Lt => a < b,
483 Le => a <= b,
484 Gt => a > b,
485 _ => a >= b,
486 })),
487 (_, Value::Number(a), Value::Number(b)) => {
488 if let (Some(x), Some(y)) = (a.as_i64(), b.as_i64()) {
489 let overflow = || EvalError("integer overflow".into());
490 return Ok(match op {
491 Add => x.checked_add(y).ok_or_else(overflow)?.into(),
492 Sub => x.checked_sub(y).ok_or_else(overflow)?.into(),
493 Mul => x.checked_mul(y).ok_or_else(overflow)?.into(),
494 Div => {
495 if y == 0 {
496 return err("division by zero");
497 }
498 x.checked_div(y).ok_or_else(overflow)?.into()
499 }
500 Rem => {
501 if y == 0 {
502 return err("division by zero");
503 }
504 x.checked_rem(y).ok_or_else(overflow)?.into()
505 }
506 Lt => (x < y).into(),
507 Le => (x <= y).into(),
508 Gt => (x > y).into(),
509 Ge => (x >= y).into(),
510 _ => unreachable!(),
511 });
512 }
513 let (x, y) = (num(&l).unwrap_or(0.0), num(&r).unwrap_or(0.0));
514 Ok(match op {
515 Add => float(x + y),
516 Sub => float(x - y),
517 Mul => float(x * y),
518 Div => {
519 if y == 0.0 {
520 return err("division by zero");
521 }
522 float(x / y)
523 }
524 Rem => {
525 if y == 0.0 {
526 return err("division by zero");
527 }
528 float(x % y)
529 }
530 Lt => (x < y).into(),
531 Le => (x <= y).into(),
532 Gt => (x > y).into(),
533 Ge => (x >= y).into(),
534 _ => unreachable!(),
535 })
536 }
537 (op, l, r) => err(format!(
538 "operator {op:?} is not defined for {} and {}",
539 crate::types::describe(l),
540 crate::types::describe(r)
541 )),
542 }
543}
544
545pub const BUILTINS: &[&str] = &[
547 "len", "coalesce", "string", "int", "float", "contains", "lower", "upper", "trim", "join",
548 "keys", "min", "max", "abs", "is_null", "sum", "map", "filter", "any", "all", "find",
549];
550
551pub fn call(function: &str, args: Vec<Value>) -> Result<Value, EvalError> {
552 let arg = |i: usize| args.get(i).cloned().unwrap_or(Value::Null);
553 match function {
554 "len" => match arg(0) {
555 Value::String(s) => Ok(Value::from(s.chars().count() as i64)),
556 Value::Array(a) => Ok(Value::from(a.len() as i64)),
557 Value::Object(o) => Ok(Value::from(o.len() as i64)),
558 Value::Null => Ok(Value::from(0)),
559 v => err(format!(
560 "len() not defined for {}",
561 crate::types::describe(&v)
562 )),
563 },
564 "coalesce" => Ok(args
565 .into_iter()
566 .find(|v| !v.is_null())
567 .unwrap_or(Value::Null)),
568 "is_null" => Ok(Value::Bool(arg(0).is_null())),
569 "string" => Ok(Value::String(match arg(0) {
570 Value::String(s) => s,
571 Value::Null => "null".into(),
572 v => v.to_string(),
573 })),
574 "int" => match arg(0) {
575 Value::Number(n) => Ok(n
576 .as_i64()
577 .map(Value::from)
578 .unwrap_or_else(|| Value::from(n.as_f64().unwrap_or(0.0).trunc() as i64))),
579 Value::String(s) => s
580 .trim()
581 .parse::<i64>()
582 .map(Value::from)
583 .map_err(|_| EvalError(format!("cannot convert {s:?} to Int"))),
584 Value::Bool(b) => Ok(Value::from(b as i64)),
585 v => err(format!(
586 "int() not defined for {}",
587 crate::types::describe(&v)
588 )),
589 },
590 "float" => match arg(0) {
591 Value::Number(n) => Ok(float(n.as_f64().unwrap_or(0.0))),
592 Value::String(s) => s
593 .trim()
594 .parse::<f64>()
595 .map(float)
596 .map_err(|_| EvalError(format!("cannot convert {s:?} to Float"))),
597 Value::Bool(b) => Ok(float(if b { 1.0 } else { 0.0 })),
598 v => err(format!(
599 "float() not defined for {}",
600 crate::types::describe(&v)
601 )),
602 },
603 "contains" => match (arg(0), arg(1)) {
604 (Value::String(s), Value::String(sub)) => Ok(Value::Bool(s.contains(&sub))),
605 (Value::Array(a), x) => Ok(Value::Bool(a.iter().any(|v| values_equal(v, &x)))),
606 (Value::Object(o), Value::String(k)) => Ok(Value::Bool(o.contains_key(&k))),
607 (Value::Null, _) => Ok(Value::Bool(false)),
608 _ => err("contains() expects (String, String), (List<T>, T) or (Map, String)"),
609 },
610 "lower" | "upper" | "trim" => match arg(0) {
611 Value::String(s) => Ok(Value::String(match function {
612 "lower" => s.to_lowercase(),
613 "upper" => s.to_uppercase(),
614 _ => s.trim().to_string(),
615 })),
616 Value::Null => Ok(Value::Null),
617 v => err(format!(
618 "{function}() expects String, found {}",
619 crate::types::describe(&v)
620 )),
621 },
622 "join" => match (arg(0), arg(1)) {
623 (Value::Array(a), Value::String(sep)) => Ok(Value::String(
624 a.iter()
625 .map(|v| match v {
626 Value::String(s) => s.clone(),
627 v => v.to_string(),
628 })
629 .collect::<Vec<_>>()
630 .join(&sep),
631 )),
632 _ => err("join() expects (List<String>, String)"),
633 },
634 "sum" => match arg(0) {
635 Value::Array(items) => {
636 let mut int_total: i64 = 0;
637 let mut float_total = 0.0;
638 let mut all_int = true;
639 for v in &items {
640 let Value::Number(n) = v else {
641 return err(format!(
642 "sum() expects numbers, found {}",
643 crate::types::describe(v)
644 ));
645 };
646 match (all_int, n.as_i64()) {
647 (true, Some(i)) => {
648 int_total = int_total
649 .checked_add(i)
650 .ok_or_else(|| EvalError("integer overflow".into()))?
651 }
652 _ => all_int = false,
653 }
654 float_total += n.as_f64().unwrap_or(0.0);
655 }
656 Ok(if all_int {
657 Value::from(int_total)
658 } else {
659 float(float_total)
660 })
661 }
662 Value::Null => Ok(Value::from(0)),
663 v => err(format!(
664 "sum() expects a list, found {}",
665 crate::types::describe(&v)
666 )),
667 },
668 "keys" => match arg(0) {
669 Value::Object(o) => Ok(Value::Array(
670 o.keys().map(|k| Value::String(k.clone())).collect(),
671 )),
672 _ => err("keys() expects a Map"),
673 },
674 "min" | "max" => {
675 let mut best: Option<Value> = None;
676 for v in args {
677 if !v.is_number() {
678 return err(format!("{function}() expects numbers"));
679 }
680 let better = match &best {
681 None => true,
682 Some(b) => {
683 let (x, y) = (v.as_f64().unwrap(), b.as_f64().unwrap());
684 if function == "min" {
685 x < y
686 } else {
687 x > y
688 }
689 }
690 };
691 if better {
692 best = Some(v);
693 }
694 }
695 Ok(best.unwrap_or(Value::Null))
696 }
697 "abs" => match arg(0) {
698 Value::Number(n) => match n.as_i64() {
699 Some(i) => i
700 .checked_abs()
701 .map(Value::from)
702 .ok_or_else(|| EvalError("integer overflow".into())),
703 None => Ok(float(n.as_f64().unwrap_or(0.0).abs())),
704 },
705 v => err(format!(
706 "abs() expects a number, found {}",
707 crate::types::describe(&v)
708 )),
709 },
710 other => err(format!("unknown function `{other}`")),
711 }
712}
713
714#[cfg(test)]
715mod tests {
716 use super::*;
717 use serde_json::json;
718
719 struct S(Value, Value);
720 impl Scope for S {
721 fn input(&self) -> &Value {
722 &self.0
723 }
724 fn step_output(&self, step: &str) -> Option<&Value> {
725 self.1.get(step)
726 }
727 fn execution_field(&self, f: &str) -> Option<Value> {
728 (f == "id").then(|| json!("exec-1"))
729 }
730 }
731
732 fn b(op: BinOp, l: Expr, r: Expr) -> Expr {
733 Expr::Binary {
734 operator: op,
735 left: Box::new(l),
736 right: Box::new(r),
737 }
738 }
739
740 #[test]
741 fn evaluates() {
742 let s = S(
743 json!({"a": 2, "name": "x"}),
744 json!({"risk": {"score": 0.5}, "skipped": null}),
745 );
746 let e = b(
747 BinOp::Lt,
748 Expr::Step {
749 step: "risk".into(),
750 path: vec!["score".into()],
751 },
752 Expr::literal(json!(0.8)),
753 );
754 assert_eq!(eval(&e, &s).unwrap(), json!(true));
755 let e = b(
756 BinOp::Add,
757 Expr::literal(json!("id-")),
758 Expr::Input {
759 path: vec!["name".into()],
760 },
761 );
762 assert_eq!(eval(&e, &s).unwrap(), json!("id-x"));
763 let e = Expr::Step {
764 step: "skipped".into(),
765 path: vec!["x".into(), "y".into()],
766 };
767 assert_eq!(eval(&e, &s).unwrap(), Value::Null);
768 let e = b(BinOp::Div, Expr::literal(json!(7)), Expr::literal(json!(2)));
769 assert_eq!(eval(&e, &s).unwrap(), json!(3));
770 let e = b(BinOp::Div, Expr::literal(json!(7)), Expr::literal(json!(0)));
771 assert!(eval(&e, &s).is_err());
772 assert_eq!(
773 eval(&Expr::Execution { field: "id".into() }, &s).unwrap(),
774 json!("exec-1")
775 );
776 assert!(values_equal(&json!(1), &json!(1.0)));
777 assert_eq!(
778 call("coalesce", vec![Value::Null, json!(3)]).unwrap(),
779 json!(3)
780 );
781 assert_eq!(
782 call("join", vec![json!(["a", "b"]), json!(",")]).unwrap(),
783 json!("a,b")
784 );
785 }
786}