Public repository: timo / feel

Reader

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

feat(core): list filter, index & projection — `list[…]` (DMN §10.3.2.5)

public

feat(core): list filter, index & projection — `list[…]` (DMN §10.3.2.5)

Add the postfix `[…]` operator at the `Postfix` precedence layer (alongside
path access), plus list-of-contexts projection on `.field`:

- `list[1]` / `list[-1]`: 1-based index, negative-from-end, out-of-range → null.
- `list[item > 5]`: boolean filter; `item` binds the element, and a context
  element's entries are referenceable directly (unless it carries an `item`
  key). Index vs. filter is disambiguated at runtime by the bracket's value
  type (number → index, else → predicate).
- `[{x:1},{x:2}].y`: `.field` over a list of contexts maps the access.

A non-list source is coerced to a singleton; a null source stays null. Reuses
`resolve_index` (now `pub(crate)`) for the 1-based/negative resolution.

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

modified crates/feel-core/src/ast.rs +10 −1

@@ -22,8 +22,14 @@
2222
     ContextLit(Vec<(String, Box<Expr>)>),
2323
     /// Variable / name reference (e.g. a `for`/`some`/`every` loop variable).
2424
     Var(String),
25
-    /// Member / path access on a context, e.g. `person.age`.
25
+    /// Member / path access on a context, e.g. `person.age`. When the left-hand
26
+    /// side is a list of contexts, the access is mapped over the list and returns
27
+    /// a list of selections (DMN §10.3.2.5), e.g. `[{x:1},{x:2}].x = [1, 2]`.
2628
     Path(Box<Expr>, String),
29
+    /// Filter / index `collection[bracket]` (DMN §10.3.2.5). A numeric bracket is
30
+    /// a 1-based index (negative-from-end, out-of-range → null); any other bracket
31
+    /// is a boolean filter evaluated per element with the element bound as `item`.
32
+    Filter(Box<Expr>, Box<Expr>),
2733
     /// A function call by name, e.g. `count([1,2,3])`, `abs(-1)`, or — for a
2834
     /// user-defined / host function bound in scope — `myFn(a, b: 2)`. The string is
2935
     /// the function name; [`CallArgs`] carries the (possibly mixed) positional and
@@ -178,6 +184,9 @@
178184
             Expr::List(items) => items.iter().all(Expr::is_clock_free),
179185
             Expr::ContextLit(entries) => entries.iter().all(|(_, e)| e.is_clock_free()),
180186
             Expr::Path(target, _) => target.is_clock_free(),
187
+            Expr::Filter(source, bracket) => {
188
+                source.is_clock_free() && bracket.is_clock_free()
189
+            }
181190
             // `now`/`today` are the only clock-reading built-ins (ADR-18). Any
182191
             // call by those names is treated as a clock read regardless of args.
183192
             Expr::FnCall(name, args) => {

modified crates/feel-core/src/builtins.rs +1 −1

@@ -529,7 +529,7 @@
529529
 
530530
 /// Resolve a 1-based FEEL position (negative counts from the end) to a 0-based
531531
 /// index in `[0, len]`. Position 0 is invalid. Returns `None` when out of range.
532
-fn resolve_index(pos: i64, len: i64) -> Option<i64> {
532
+pub(crate) fn resolve_index(pos: i64, len: i64) -> Option<i64> {
533533
     if pos == 0 {
534534
         return None;
535535
     }

modified crates/feel-core/src/eval.rs +91 −12

@@ -13,6 +13,7 @@
1313
 use std::sync::Arc;
1414
 
1515
 use crate::ast::{ArithOp, CallArgs, CmpOp, Expr, Interval, IterSource, Quantifier};
16
+use crate::builtins::resolve_index;
1617
 use crate::function::{Args, Closure, Func};
1718
 use crate::{temporal, Context, EvalEnv, FeelError, Value};
1819
 
@@ -73,19 +74,17 @@
7374
             Expr::Var(name) => Ok(ctx.get(name).cloned().unwrap_or(Value::Null)),
7475
             Expr::ContextLit(entries) => self.eval_context_lit(entries, ctx),
7576
             Expr::Path(target, name) => Ok(match self.eval(target, ctx)? {
76
-                // A missing member is a value-null (like an unbound variable);
77
-                // a path on a non-context is a type error -> error-null.
78
-                Value::Context(map) => map.get(name).cloned().unwrap_or(Value::Null),
79
-                // A lazy host value resolves the dot by name, on demand (ADR-21).
80
-                // This is the *only* place a `Foreign` is not forced first, so a
81
-                // graph is walked exactly as deep as the expression navigates.
82
-                Value::Foreign(f) => f.0.get(name),
83
-                // Component access on a temporal value (`d.year`, `dur.seconds`);
84
-                // an unknown property is a value-null (ADR-18).
85
-                v if temporal::is_temporal(&v) => temporal::get_property(&v, name),
86
-                Value::Error => Value::Error,
87
-                _ => Value::Error,
77
+                // Selection on a list of contexts maps over the list and returns a
78
+                // list of selections (DMN §10.3.2.5): `[{x:1},{x:2}].x = [1, 2]`,
79
+                // a missing key in an element yielding a value-null in that slot.
80
+                // The list is *not* `forced()` first, so a `Foreign` left intact
81
+                // here keeps the single-object lazy path below (ADR-21).
82
+                Value::List(items) => {
83
+                    Value::List(items.into_iter().map(|it| member_access(it, name)).collect())
84
+                }
85
+                other => member_access(other, name),
8886
             }),
87
+            Expr::Filter(source, bracket) => self.eval_filter(source, bracket, ctx),
8988
             // A function literal captures the current scope (lexical closure, ADR-23).
9089
             Expr::FnDef { params, body } => Ok(Func::Closure(Closure {
9190
                 params: params.clone(),
@@ -614,6 +613,36 @@
614613
         Ok(Value::List(out))
615614
     }
616615
 
616
+    /// Evaluate a postfix filter / index `source[bracket]` (DMN §10.3.2.5).
617
+    ///
618
+    /// The source is coerced to a list: a non-list, non-null value becomes a
619
+    /// singleton (implicit conversion §10.3.2.9.4); `null` and error-null
620
+    /// short-circuit. The bracket is then disambiguated by its value type — a
621
+    /// number is a 1-based positional index (negative-from-end, out of range →
622
+    /// value-null); anything else is a boolean filter, re-evaluated per element
623
+    /// with the element bound as `item` (see [`filter_scope`]), keeping only the
624
+    /// elements whose result is `true`. The disambiguation evaluates the bracket
625
+    /// in the *outer* scope, where `item` is unbound, so a genuine predicate like
626
+    /// `item > 2` is null there and correctly falls through to the filter path.
627
+    fn eval_filter(&self, source: &Expr, bracket: &Expr, ctx: &Context) -> EvalResult {
628
+        let items = match self.eval(source, ctx)?.forced() {
629
+            Value::Null => return Ok(Value::Null),
630
+            Value::Error => return Ok(Value::Error),
631
+            Value::List(items) => items,
632
+            other => vec![other],
633
+        };
634
+        if let Value::Number(n) = self.eval(bracket, ctx)?.forced() {
635
+            return Ok(index_into(&items, n));
636
+        }
637
+        let mut out = Vec::new();
638
+        for item in items {
639
+            if let Value::Boolean(true) = self.eval(bracket, &filter_scope(ctx, &item))?.forced() {
640
+                out.push(item);
641
+            }
642
+        }
643
+        Ok(Value::List(out))
644
+    }
645
+
617646
     fn eval_quantified(
618647
         &self,
619648
         kind: Quantifier,
@@ -656,6 +685,56 @@
656685
     }
657686
 }
658687
 
688
+/// Select member `name` from one value — the per-element rule shared by scalar
689
+/// path access and list projection (DMN §10.3.2.5). A missing context key is a
690
+/// value-null (like an unbound variable); a `Foreign` resolves the dot lazily
691
+/// (ADR-21); a temporal value exposes its components (ADR-18); anything else is a
692
+/// type error (error-null).
693
+fn member_access(value: Value, name: &str) -> Value {
694
+    match value {
695
+        Value::Context(map) => map.get(name).cloned().unwrap_or(Value::Null),
696
+        Value::Foreign(f) => f.0.get(name),
697
+        v if temporal::is_temporal(&v) => temporal::get_property(&v, name),
698
+        _ => Value::Error,
699
+    }
700
+}
701
+
702
+/// 1-based positional index into `items` (DMN §10.3.2.5): a positive `n` counts
703
+/// from the front, a negative `n` from the end. A non-integer or out-of-range
704
+/// `n` is a value-null. Reuses [`resolve_index`] — the same 1-based / negative
705
+/// resolution the list built-ins use (`out` of `[0, len]`, so guard `< len`).
706
+fn index_into(items: &[Value], n: f64) -> Value {
707
+    if n.fract() != 0.0 {
708
+        return Value::Null;
709
+    }
710
+    match resolve_index(n as i64, items.len() as i64) {
711
+        Some(idx) if (idx as usize) < items.len() => items[idx as usize].clone(),
712
+        _ => Value::Null,
713
+    }
714
+}
715
+
716
+/// Build the scope a filter predicate is evaluated in for one element. The element
717
+/// is bound as `item`; if it is a context, its entries are also spread into scope
718
+/// so they can be referenced without an `item.` prefix — but a context that
719
+/// already carries an `item` key keeps that key as `item` (DMN §10.3.2.5). The
720
+/// element is forced first so a lazy host context's entries are visible, while the
721
+/// `item` binding stays the original value (preserving `Foreign` identity, ADR-21).
722
+fn filter_scope(ctx: &Context, item: &Value) -> Context {
723
+    let mut scope = ctx.clone();
724
+    if let Value::Context(map) = item.clone().forced() {
725
+        let has_item = map.contains_key("item");
726
+        for (k, v) in map {
727
+            scope.insert(k, v);
728
+        }
729
+        if !has_item {
730
+            scope.insert("item", item.clone());
731
+        }
732
+    } else {
733
+        scope.insert("item", item.clone());
734
+    }
735
+    scope
736
+}
737
+
659738
 /// Inclusive integer range with a ±1 step: `2..4` -> [2,3,4], `4..2` -> [4,3,2].
660739
 fn int_range(lo: f64, hi: f64) -> Vec<Value> {
661740
     // Guard against pathological/non-integer bounds producing huge or endless

modified crates/feel-core/src/feel.lalrpop +7 −0

@@ -160,8 +160,15 @@
160160
 // sees them (the lexer joined them), so this production needs no change.
161161
 // `not(...)` keeps its own Primary rule because `not` is a keyword token (not a
162162
 // `Name`), so it never reaches this production.
163
+// A postfix filter / index `value[expr]` (DMN §10.3.2.5) also lives here, at the
164
+// same precedence as path access. A `[` in *primary* position is a list literal
165
+// (`Primary → List`); a `[` directly after a completed `Postfix` is unambiguously
166
+// a subscript; interval `[a..b]` only follows `in`. This mirrors the shift-after-
167
+// value pattern of the `.` rule above and stays LR(1) (verified: lalrpop builds
168
+// conflict-free).
163169
 Postfix: Expr = {
164170
     <e:Postfix> "." <n:Name> => Expr::Path(Box::new(e), n),
171
+    <e:Postfix> "[" <idx:Expr> "]" => Expr::Filter(Box::new(e), Box::new(idx)),
165172
     <n:Name> "(" ")" => Expr::FnCall(n, CallArgs::default()),
166173
     <n:Name> "(" <a:Comma<Arg>> ")" => Expr::FnCall(n, callargs_from(a)),
167174
     Primary,

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

@@ -623,6 +623,93 @@
623623
         assert_eq!(ev("{a: {b: {c: 7}}}.a.b.c"), num(7.0));
624624
     }
625625
 
626
+    /// A context-`Value` builder for the filter/projection tests below.
627
+    fn ctx_val(pairs: &[(&str, Value)]) -> Value {
628
+        use std::collections::BTreeMap;
629
+        Value::Context(
630
+            pairs
631
+                .iter()
632
+                .map(|(k, v)| (k.to_string(), v.clone()))
633
+                .collect::<BTreeMap<_, _>>(),
634
+        )
635
+    }
636
+
637
+    #[test]
638
+    fn list_index_access() {
639
+        // 1-based positional index; negative counts from the end (DMN §10.3.2.5).
640
+        assert_eq!(ev("[1, 2, 3][1]"), num(1.0));
641
+        assert_eq!(ev("[1, 2, 3][3]"), num(3.0));
642
+        assert_eq!(ev("[1, 2, 3][-1]"), num(3.0));
643
+        assert_eq!(ev("[1, 2, 3][-3]"), num(1.0));
644
+        // Out of range (either direction), zero, and non-integer -> null.
645
+        assert_eq!(ev("[1, 2, 3][4]"), Value::Null);
646
+        assert_eq!(ev("[1, 2, 3][-4]"), Value::Null);
647
+        assert_eq!(ev("[1, 2, 3][0]"), Value::Null);
648
+        assert_eq!(ev("[1, 2, 3][1.5]"), Value::Null);
649
+        // A non-list source is a singleton; a null source stays null.
650
+        assert_eq!(ev("5[1]"), num(5.0));
651
+        assert_eq!(ev("5[2]"), Value::Null);
652
+        assert_eq!(ev("null[1]"), Value::Null);
653
+        // The index is an arbitrary expression evaluated in the outer scope.
654
+        assert_eq!(ev("[10, 20, 30][1 + 1]"), num(20.0));
655
+    }
656
+
657
+    #[test]
658
+    fn list_boolean_filter() {
659
+        // The predicate keeps elements where it is true; `item` is the element.
660
+        assert_eq!(ev("[1, 2, 3, 4][item > 2]"), list(vec![num(3.0), num(4.0)]));
661
+        assert_eq!(ev("[1, 2, 3][item > 9]"), list(vec![]));
662
+        // A constant boolean filter selects all / none.
663
+        assert_eq!(
664
+            ev("[1, 2, 3][true]"),
665
+            list(vec![num(1.0), num(2.0), num(3.0)])
666
+        );
667
+        assert_eq!(ev("[1, 2, 3][false]"), list(vec![]));
668
+        // A non-list source filters as a singleton.
669
+        assert_eq!(ev("5[item > 3]"), list(vec![num(5.0)]));
670
+        assert_eq!(ev("5[item < 3]"), list(vec![]));
671
+    }
672
+
673
+    #[test]
674
+    fn list_filter_over_contexts() {
675
+        // A context element's entries are referenceable without an `item.` prefix...
676
+        assert_eq!(
677
+            ev("[{x: 1, y: 2}, {x: 2, y: 3}][x = 1]"),
678
+            list(vec![ctx_val(&[("x", num(1.0)), ("y", num(2.0))])])
679
+        );
680
+        // ...or via the explicit `item` binding.
681
+        assert_eq!(
682
+            ev("[{x: 1, y: 2}, {x: 2, y: 3}][item.x = 2]"),
683
+            list(vec![ctx_val(&[("x", num(2.0)), ("y", num(3.0))])])
684
+        );
685
+        // A null key compares to null (not true), so that row is dropped.
686
+        assert_eq!(
687
+            ev("[{x: 1, y: 2}, {x: null, y: 3}][x < 2]"),
688
+            list(vec![ctx_val(&[("x", num(1.0)), ("y", num(2.0))])])
689
+        );
690
+        // When the element itself carries an `item` key, that key wins as `item`.
691
+        assert_eq!(
692
+            ev("[{item: 7, x: 1}][item = 7]"),
693
+            list(vec![ctx_val(&[("item", num(7.0)), ("x", num(1.0))])])
694
+        );
695
+    }
696
+
697
+    #[test]
698
+    fn list_projection_over_contexts() {
699
+        // `.field` over a list of contexts maps the access (DMN §10.3.2.5).
700
+        assert_eq!(
701
+            ev("[{x: 1, y: 2}, {x: 2, y: 3}].y"),
702
+            list(vec![num(2.0), num(3.0)])
703
+        );
704
+        // A missing key yields a null in that slot.
705
+        assert_eq!(
706
+            ev("[{x: 1, y: 2}, {x: 2}].y"),
707
+            list(vec![num(2.0), Value::Null])
708
+        );
709
+        // Projection then index composes left-to-right: `(xs.x)[2]`.
710
+        assert_eq!(ev("[{x: 1}, {x: 2}, {x: 3}].x[2]"), num(2.0));
711
+    }
712
+
626713
     #[test]
627714
     fn path_access_on_context_variable() {
628715
         let mut inner = std::collections::BTreeMap::new();