Public repository: timo / feel

Reader

An interpreter of FEEL, written in Rust, with integrations for PostgreSQL, WASM, Lua, and Python.

feat(core): multiple iteration contexts for for/some/every (FEEL 44/46)

public

feat(core): multiple iteration contexts for for/some/every (FEEL 44/46)

Generalize `for`, `some` and `every` from a single iteration context to one
or more comma-separated contexts (`for i in a, j in b return …`,
`some/every i in a, j in b satisfies …`).

- ast: `Expr::For`/`Expr::Quantified` now hold `Vec<(String, IterSource)>`
  bindings instead of a single `var`/`source`; `is_clock_free` folds over them.
- grammar: a new `IterCtx` rule (`name in source`) fed through the existing
  `Comma<T>` helper over the shared `IterSrc`. A top-level `,` is only consumed
  here (never by `IterSrc`), so it stays LR(1) — lalrpop builds conflict-free.
- eval: `eval_for`/`eval_quantified` recurse over the bindings, evaluating the
  body/predicate over the Cartesian product in declaration order with the
  rightmost context varying fastest. Each source is resolved in the scope of the
  contexts to its left (`for i in [1,2], j in i..3 …`). A non-iterable source at
  any level is an error-null (parity with the single-context rule); the
  quantifier short-circuit and sticky error-provenance are preserved.

The body special variable `partial` remains out of scope (unsupported for a
single context too).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Changesetdbb76c42df1dfceea50747f51887506d6674152d
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents8ad7192806ae
Children
Pushlog
by timo via ssh

modified crates/feel-core/src/ast.rs +17 −9

@@ -66,17 +66,21 @@
6666
     // --- control flow ---
6767
     /// `if cond then then_branch else else_branch`.
6868
     If(Box<Expr>, Box<Expr>, Box<Expr>),
69
-    /// `for var in source return body`.
69
+    /// `for var in source { , var in source } return body`. One or more
70
+    /// iteration contexts (FEEL grammar rule 44): the body is evaluated over the
71
+    /// Cartesian product of the sources, in declaration order with the rightmost
72
+    /// context varying fastest. Each source may reference the variables of the
73
+    /// contexts to its left (it is evaluated in their scope).
7074
     For {
71
-        var: String,
72
-        source: IterSource,
75
+        bindings: Vec<(String, IterSource)>,
7376
         body: Box<Expr>,
7477
     },
75
-    /// `some|every var in source satisfies predicate`.
78
+    /// `some|every var in source { , var in source } satisfies predicate` (FEEL
79
+    /// grammar rule 46). Like [`Expr::For`], the predicate ranges over the
80
+    /// Cartesian product of the (left-to-right scoped) sources.
7681
     Quantified {
7782
         kind: Quantifier,
78
-        var: String,
79
-        source: IterSource,
83
+        bindings: Vec<(String, IterSource)>,
8084
         predicate: Box<Expr>,
8185
     },
8286
 }
@@ -208,10 +212,14 @@
208212
                     && interval.start.is_clock_free()
209213
                     && interval.end.is_clock_free()
210214
             }
211
-            Expr::For { source, body, .. } => source.is_clock_free() && body.is_clock_free(),
215
+            Expr::For { bindings, body } => {
216
+                bindings.iter().all(|(_, s)| s.is_clock_free()) && body.is_clock_free()
217
+            }
212218
             Expr::Quantified {
213
-                source, predicate, ..
214
-            } => source.is_clock_free() && predicate.is_clock_free(),
219
+                bindings,
220
+                predicate,
221
+                ..
222
+            } => bindings.iter().all(|(_, s)| s.is_clock_free()) && predicate.is_clock_free(),
215223
         }
216224
     }
217225
 }

modified crates/feel-core/src/eval.rs +111 −39

@@ -155,13 +155,12 @@
155155
                 Value::Boolean(false) | Value::Null => self.eval(e, ctx),
156156
                 _ => Ok(Value::Error),
157157
             },
158
-            Expr::For { var, source, body } => self.eval_for(var, source, body, ctx),
158
+            Expr::For { bindings, body } => self.eval_for(bindings, body, ctx),
159159
             Expr::Quantified {
160160
                 kind,
161
-                var,
162
-                source,
161
+                bindings,
163162
                 predicate,
164
-            } => self.eval_quantified(*kind, var, source, predicate, ctx),
163
+            } => self.eval_quantified(*kind, bindings, predicate, ctx),
165164
         }
166165
     }
167166
 
@@ -602,15 +601,42 @@
602601
         }
603602
     }
604603
 
605
-    fn eval_for(&self, var: &str, source: &IterSource, body: &Expr, ctx: &Context) -> EvalResult {
604
+    /// Evaluate a `for` over one or more iteration contexts (FEEL rule 44). The
605
+    /// body runs over the Cartesian product of the sources, in declaration order
606
+    /// with the rightmost context varying fastest; each source is resolved in the
607
+    /// scope of the contexts to its left. A non-iterable source (at any level)
608
+    /// makes the whole expression an error-null, matching the single-context rule.
609
+    fn eval_for(&self, bindings: &[(String, IterSource)], body: &Expr, ctx: &Context) -> EvalResult {
610
+        let mut out = Vec::new();
611
+        if self.for_product(bindings, body, ctx, &mut out)? {
612
+            Ok(Value::List(out))
613
+        } else {
614
+            Ok(Value::Error) // a (nested) source was non-iterable
615
+        }
616
+    }
617
+
618
+    /// Walk the Cartesian product of `bindings`, pushing one body result per tuple
619
+    /// into `out`. Returns `Ok(false)` (aborting) if a source was non-iterable.
620
+    fn for_product(
621
+        &self,
622
+        bindings: &[(String, IterSource)],
623
+        body: &Expr,
624
+        ctx: &Context,
625
+        out: &mut Vec<Value>,
626
+    ) -> Result<bool, FeelError> {
627
+        let Some(((var, source), rest)) = bindings.split_first() else {
628
+            out.push(self.eval(body, ctx)?);
629
+            return Ok(true);
630
+        };
606631
         let Some(items) = self.iter_values(source, ctx)? else {
607
-            return Ok(Value::Error); // non-iterable source: type error
608
-        };
609
-        let mut out = Vec::with_capacity(items.len());
632
+            return Ok(false);
633
+        };
610634
         for item in items {
611
-            out.push(self.eval(body, &ctx.with(var, item))?);
612
-        }
613
-        Ok(Value::List(out))
635
+            if !self.for_product(rest, body, &ctx.with(var, item), out)? {
636
+                return Ok(false);
637
+            }
638
+        }
639
+        Ok(true)
614640
     }
615641
 
616642
     /// Evaluate a postfix filter / index `source[bracket]` (DMN §10.3.2.5).
@@ -643,46 +669,92 @@
643669
         Ok(Value::List(out))
644670
     }
645671
 
672
+    /// Evaluate `some`/`every` over one or more iteration contexts (FEEL rule 46).
673
+    /// The predicate ranges over the Cartesian product of the (left-to-right
674
+    /// scoped) sources — see [`Self::eval_for`] for the iteration order — with
675
+    /// short-circuit on the first dominating result (`some`→true / `every`→false).
646676
     fn eval_quantified(
647677
         &self,
648678
         kind: Quantifier,
649
-        var: &str,
650
-        source: &IterSource,
679
+        bindings: &[(String, IterSource)],
651680
         predicate: &Expr,
652681
         ctx: &Context,
653682
     ) -> EvalResult {
654
-        let Some(items) = self.iter_values(source, ctx)? else {
655
-            return Ok(Value::Error); // non-iterable source: type error
656
-        };
657683
         // A quantifier is a folded and/or, so it carries the same sticky-provenance
658684
         // rule (Design 1): a dominating result short-circuits; otherwise the unknown
659685
         // result is an error-null iff a non-boolean predicate result tainted it.
660686
         let mut saw_unknown = false;
661687
         let mut tainted = false;
688
+        match self.quant_product(kind, bindings, predicate, ctx, &mut saw_unknown, &mut tainted)? {
689
+            QuantOutcome::Short(v) => Ok(v),
690
+            QuantOutcome::NonIterable => Ok(Value::Error), // type error
691
+            QuantOutcome::Exhausted => Ok(if saw_unknown {
692
+                nullish(tainted)
693
+            } else {
694
+                match kind {
695
+                    Quantifier::Some => Value::Boolean(false),
696
+                    Quantifier::Every => Value::Boolean(true),
697
+                }
698
+            }),
699
+        }
700
+    }
701
+
702
+    /// Walk the Cartesian product of `bindings` for a quantifier, threading the
703
+    /// sticky-provenance flags. Short-circuits on the first dominating boolean and
704
+    /// aborts on a non-iterable source.
705
+    fn quant_product(
706
+        &self,
707
+        kind: Quantifier,
708
+        bindings: &[(String, IterSource)],
709
+        predicate: &Expr,
710
+        ctx: &Context,
711
+        saw_unknown: &mut bool,
712
+        tainted: &mut bool,
713
+    ) -> Result<QuantOutcome, FeelError> {
714
+        let Some(((var, source), rest)) = bindings.split_first() else {
715
+            return Ok(match self.eval(predicate, ctx)? {
716
+                Value::Boolean(true) if kind == Quantifier::Some => {
717
+                    QuantOutcome::Short(Value::Boolean(true))
718
+                }
719
+                Value::Boolean(false) if kind == Quantifier::Every => {
720
+                    QuantOutcome::Short(Value::Boolean(false))
721
+                }
722
+                Value::Boolean(_) => QuantOutcome::Exhausted,
723
+                other => {
724
+                    *saw_unknown = true;
725
+                    *tainted |= taints(&other);
726
+                    QuantOutcome::Exhausted
727
+                }
728
+            });
729
+        };
730
+        let Some(items) = self.iter_values(source, ctx)? else {
731
+            return Ok(QuantOutcome::NonIterable);
732
+        };
662733
         for item in items {
663
-            match self.eval(predicate, &ctx.with(var, item))? {
664
-                Value::Boolean(true) if kind == Quantifier::Some => {
665
-                    return Ok(Value::Boolean(true))
666
-                }
667
-                Value::Boolean(false) if kind == Quantifier::Every => {
668
-                    return Ok(Value::Boolean(false))
669
-                }
670
-                Value::Boolean(_) => {}
671
-                other => {
672
-                    saw_unknown = true;
673
-                    tainted |= taints(&other);
674
-                }
675
-            }
676
-        }
677
-        Ok(if saw_unknown {
678
-            nullish(tainted)
679
-        } else {
680
-            match kind {
681
-                Quantifier::Some => Value::Boolean(false),
682
-                Quantifier::Every => Value::Boolean(true),
683
-            }
684
-        })
685
-    }
734
+            match self.quant_product(
735
+                kind,
736
+                rest,
737
+                predicate,
738
+                &ctx.with(var, item),
739
+                saw_unknown,
740
+                tainted,
741
+            )? {
742
+                QuantOutcome::Exhausted => {}
743
+                short_or_abort => return Ok(short_or_abort),
744
+            }
745
+        }
746
+        Ok(QuantOutcome::Exhausted)
747
+    }
748
+}
749
+
750
+/// Outcome of walking a (sub-)product for a quantifier ([`Evaluator::quant_product`]).
751
+enum QuantOutcome {
752
+    /// A dominating boolean ended iteration early (`some`→true / `every`→false).
753
+    Short(Value),
754
+    /// A (nested) source was non-iterable: the whole quantifier is an error-null.
755
+    NonIterable,
756
+    /// This sub-product was exhausted without short-circuiting.
757
+    Exhausted,
686758
 }
687759
 
688760
 /// Select member `name` from one value — the per-element rule shared by scalar

modified crates/feel-core/src/feel.lalrpop +17 −6

@@ -78,14 +78,19 @@
7878
 // sub-expressions (which are themselves full TextualExprs), enabling nesting
7979
 // like `for i in [1,2,3] return if i > 0 then i else -i`.
8080
 TextualExpr: Expr = {
81
-    "for" <v:Name> "in" <s:IterSrc> "return" <b:TextualExpr> =>
82
-        Expr::For { var: v, source: s, body: Box::new(b) },
81
+    // `for`/`some`/`every` take one *or more* comma-separated iteration contexts
82
+    // (`for i in a, j in b return …`; FEEL rules 44/46) via the `Comma<IterCtx>`
83
+    // helper. A top-level `,` is only consumed here — `IterSrc` never eats one —
84
+    // so after each context the parser sees `,` or `return`/`satisfies`, which
85
+    // keeps it LR(1) (the `build.rs` gate fails on any conflict).
86
+    "for" <bs:Comma<IterCtx>> "return" <b:TextualExpr> =>
87
+        Expr::For { bindings: bs, body: Box::new(b) },
8388
     "if" <c:TextualExpr> "then" <t:TextualExpr> "else" <e:TextualExpr> =>
8489
         Expr::If(Box::new(c), Box::new(t), Box::new(e)),
85
-    "some" <v:Name> "in" <s:IterSrc> "satisfies" <p:TextualExpr> =>
86
-        Expr::Quantified { kind: Quantifier::Some, var: v, source: s, predicate: Box::new(p) },
87
-    "every" <v:Name> "in" <s:IterSrc> "satisfies" <p:TextualExpr> =>
88
-        Expr::Quantified { kind: Quantifier::Every, var: v, source: s, predicate: Box::new(p) },
90
+    "some" <bs:Comma<IterCtx>> "satisfies" <p:TextualExpr> =>
91
+        Expr::Quantified { kind: Quantifier::Some, bindings: bs, predicate: Box::new(p) },
92
+    "every" <bs:Comma<IterCtx>> "satisfies" <p:TextualExpr> =>
93
+        Expr::Quantified { kind: Quantifier::Every, bindings: bs, predicate: Box::new(p) },
8994
     // A FEEL function literal `function(a, b) body` (ADR-23). Like `if`/`for`, the
9095
     // body is a full TextualExpr, so it extends to the end of the sub-expression.
9196
     // `function` is a keyword token, so `function(` is unambiguously a literal (not
@@ -224,6 +229,12 @@
224229
     <mut v:(<T> ",")*> <last:T> => { v.push(last); v },
225230
 };
226231
 
232
+// One iteration context `name in source` (FEEL rules 44/46). Collected into a
233
+// list by `Comma<IterCtx>` in the `for`/`some`/`every` rules above.
234
+IterCtx: (String, IterSource) = {
235
+    <v:Name> "in" <s:IterSrc> => (v, s),
236
+};
237
+
227238
 // Iteration source for `for`/`some`/`every`: a bare integer range `a..b`
228239
 // (generates an ascending/descending integer list) or a list expression.
229240
 IterSrc: IterSource = {

modified crates/feel-core/src/lib.rs +54 −0

@@ -562,6 +562,47 @@
562562
     }
563563
 
564564
     #[test]
565
+    fn for_multiple_iteration_contexts() {
566
+        // Cartesian product, rightmost context varies fastest (FEEL rule 44).
567
+        assert_eq!(
568
+            ev("for x in [1,2,3], y in [10,20] return x + y"),
569
+            list(vec![
570
+                num(11.0),
571
+                num(21.0),
572
+                num(12.0),
573
+                num(22.0),
574
+                num(13.0),
575
+                num(23.0),
576
+            ])
577
+        );
578
+        // Matches DMN-TCK 0033-for-loops: `for h in heights, w in widths`.
579
+        assert_eq!(
580
+            ev("for h in [10,20,30], w in [2,3] return h * w"),
581
+            list(vec![
582
+                num(20.0),
583
+                num(30.0),
584
+                num(40.0),
585
+                num(60.0),
586
+                num(60.0),
587
+                num(90.0),
588
+            ])
589
+        );
590
+        // A later source may reference an earlier variable (left-to-right scope).
591
+        assert_eq!(
592
+            ev("for i in [1,2], j in i..3 return j"),
593
+            list(vec![num(1.0), num(2.0), num(3.0), num(2.0), num(3.0)])
594
+        );
595
+        // An empty source anywhere yields an empty product.
596
+        assert_eq!(ev("for i in [1,2], j in [] return i"), list(vec![]));
597
+        assert_eq!(ev("for i in [], j in [1] return i"), list(vec![]));
598
+        // Three contexts compose.
599
+        assert_eq!(
600
+            ev("for a in [1], b in [2,3], c in [4,5] return a + b + c"),
601
+            list(vec![num(7.0), num(8.0), num(8.0), num(9.0)])
602
+        );
603
+    }
604
+
605
+    #[test]
565606
     fn quantifiers() {
566607
         assert_eq!(ev("some i in [1,2,3] satisfies i > 2"), b(true));
567608
         assert_eq!(ev("some i in [1,2,3] satisfies i > 5"), b(false));
@@ -572,6 +613,19 @@
572613
         assert_eq!(ev("every i in [] satisfies i > 0"), b(true));
573614
         // range source
574615
         assert_eq!(ev("every i in 1..5 satisfies i > 0"), b(true));
616
+    }
617
+
618
+    #[test]
619
+    fn quantifiers_multiple_iteration_contexts() {
620
+        // `some` short-circuits to true on the first satisfying tuple (1+4 = 5).
621
+        assert_eq!(ev("some x in [1,2], y in [3,4] satisfies x + y = 5"), b(true));
622
+        assert_eq!(ev("some x in [1,2], y in [3,4] satisfies x + y = 99"), b(false));
623
+        // `every` is true only when all product tuples satisfy the predicate.
624
+        assert_eq!(ev("every x in [1,2], y in [3,4] satisfies x < y"), b(true));
625
+        assert_eq!(ev("every x in [1,2], y in [1,2] satisfies x <= y"), b(false));
626
+        // An empty source: the product is empty (some -> false, every -> true).
627
+        assert_eq!(ev("some x in [1,2], y in [] satisfies x = y"), b(false));
628
+        assert_eq!(ev("every x in [1,2], y in [] satisfies x = y"), b(true));
575629
     }
576630
 
577631
     #[test]