Public repository: timo / feel

Reader

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

feat(feel): add descendant operator `e ... name` (DMN §10.3.2.7)

public

feat(feel): add descendant operator `e ... name` (DMN §10.3.2.7)

Add support for the DMN 1.4 descendant navigation operator (`e ... name`) that
recursively collects every value bound to `name` in a context or list of
contexts, depth-first. The operator traverses nested structures including
host foreign objects and includes cycle detection via a visited-set of foreign
object identities.

- Add `Expr::Descendant` AST node and evaluation logic in `eval.rs`
- Implement `descendant_collect` with depth limit (`DESCENDANT_MAX_DEPTH`)
- Add `identity()` method to `ForeignObject` trait for cycle detection
- Add grammar rule `Postfix: "..." Name => Expr::Descendant` in feel.lalrpop
- Add `Tok::DotDotDot` lexer token
- Add comprehensive test suite covering:
  - Spec canonical example `{a:{b:{b:1}}} ... b`
  - List of contexts `[{x:1},{x:2}] ... x`
  - Null/scalar edge cases
  - Foreign object traversal with cyclic graphs
- Update FEEL coverage documentation
Changeset9628dc752e3238a2fe1f6204ec2b9c71b318c531
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parentsc8030dbae9eb
Children
Pushlog
by timo via ssh

modified crates/feel-core/src/ast.rs +8 −0

@@ -31,6 +31,13 @@
3131
     /// side is a list of contexts, the access is mapped over the list and returns
3232
     /// a list of selections (DMN §10.3.2.5), e.g. `[{x:1},{x:2}].x = [1, 2]`.
3333
     Path(Box<Expr>, String),
34
+    /// Descendant navigation `e ... name` (DMN §10.3.2.7, grammar rule 68): collect
35
+    /// every value bound to `name` in `e` and all of its nested contexts (and lists
36
+    /// of contexts), depth-first, into a list. Unlike [`Path`](Expr::Path) (a shallow
37
+    /// single-level selection), this is a recursive traversal — the engine's first
38
+    /// *unbounded* collection, so a cyclic host graph behind [`Value::Foreign`]
39
+    /// requires a visited-set guard in the evaluator (see `descendant_collect`).
40
+    Descendant(Box<Expr>, String),
3441
     /// Filter / index `collection[bracket]` (DMN §10.3.2.5). A numeric bracket is
3542
     /// a 1-based index (negative-from-end, out-of-range → null); any other bracket
3643
     /// is a boolean filter evaluated per element with the element bound as `item`.
@@ -371,6 +378,7 @@
371378
             Expr::RangeLit(iv) => interval_is_clock_free(iv),
372379
             Expr::ContextLit(entries) => entries.iter().all(|(_, e)| e.is_clock_free()),
373380
             Expr::Path(target, _) => target.is_clock_free(),
381
+            Expr::Descendant(target, _) => target.is_clock_free(),
374382
             Expr::Filter(source, bracket) => {
375383
                 source.is_clock_free() && bracket.is_clock_free()
376384
             }

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

@@ -9,7 +9,7 @@
99
 
1010
 use std::cell::Cell;
1111
 use std::cmp::Ordering;
12
-use std::collections::BTreeMap;
12
+use std::collections::{BTreeMap, HashSet};
1313
 use std::sync::Arc;
1414
 
1515
 use crate::ast::{ArithOp, CallArgs, CmpOp, Expr, FeelType, IterSource, Quantifier, UnaryTest};
@@ -27,6 +27,13 @@
2727
 /// small thread stack (a deeply nested tree-walk costs several native frames per
2828
 /// FEEL call).
2929
 const MAX_CALL_DEPTH: usize = 64;
30
+
31
+/// Recursion cap for the descendant traversal (`e ... name`, DMN §10.3.2.7). The
32
+/// primary cycle guard is the visited-set of `Foreign` identities in
33
+/// [`descendant_collect`]; this depth cap is a secondary backstop against
34
+/// pathologically deep (but acyclic) data — the same defensive spirit as
35
+/// `EQ_MAX_DEPTH`.
36
+const DESCENDANT_MAX_DEPTH: usize = 1024;
3037
 
3138
 /// A tree-walking evaluator carrying the evaluation environment (host regex
3239
 /// provider + `now()`/`today()` instant + host function registry;
@@ -117,6 +124,28 @@
117124
                 }
118125
                 other => member_access(other, name),
119126
             }),
127
+            // Descendant `e ... name` (DMN §10.3.2.7, grammar rule 68): collect every
128
+            // value bound to `name` in `e` and all nested contexts/lists, depth-first,
129
+            // into a list. A null/error target propagates; a non-navigable scalar is
130
+            // null (the `.` operator behaves the same). The recursive walk is the
131
+            // engine's first *unbounded* collection, so a cyclic host graph behind
132
+            // `Value::Foreign` needs a visited-set guard — see [`descendant_collect`].
133
+            Expr::Descendant(target, name) => {
134
+                let v = self.eval(target, ctx)?.forced();
135
+                Ok(match &v {
136
+                    Value::Null => Value::Null,
137
+                    Value::Error => Value::Error,
138
+                    Value::Context(_) | Value::List(_) | Value::Foreign(_) => {
139
+                        let mut out = Vec::new();
140
+                        let mut seen = HashSet::new();
141
+                        descendant_collect(&v, name, &mut seen, &mut out, 0);
142
+                        Value::List(out)
143
+                    }
144
+                    // A non-navigable scalar/range/function: applicability "type e is
145
+                    // a context" fails -> null (mirrors `.` on a non-context).
146
+                    _ => Value::Null,
147
+                })
148
+            }
120149
             Expr::Filter(source, bracket) => self.eval_filter(source, bracket, ctx),
121150
             // A function literal captures the current scope (lexical closure, ADR-23).
122151
             Expr::FnDef { params, body } => Ok(Func::Closure(Closure {
@@ -1051,6 +1080,57 @@
10511080
     }
10521081
 }
10531082
 
1083
+/// Recursively collect every value bound to `name` in `root` and all nested
1084
+/// contexts/lists, depth-first, appending to `out` (DMN §10.3.2.7, the descendant
1085
+/// `e ... name` operator). Pre-order: at each context the match for `name` is
1086
+/// collected *before* descending into its children, so
1087
+/// `{a:{b:{b:1}}} ... b` → `[{b:1}, 1]`.
1088
+///
1089
+/// **Cycle guard.** Only an `Arc`-backed [`Value::Foreign`] can form a cycle
1090
+/// (pure-Rust values are owned trees). `seen` keys on
1091
+/// [`ForeignObject::identity`](crate::foreign::ForeignObject::identity) — the *host
1092
+/// object's* identity, not the Rust allocation address — so a host that mints a
1093
+/// fresh `Arc` per `force`/`get` (feel-py/lua/wasm) still has the back-edge broken
1094
+/// once its `identity()` override returns a stable value (feel-pg is exempt:
1095
+/// `jsonb` cannot cycle). [`DESCENDANT_MAX_DEPTH`] is a secondary backstop.
1096
+fn descendant_collect(
1097
+    root: &Value,
1098
+    name: &str,
1099
+    seen: &mut HashSet<usize>,
1100
+    out: &mut Vec<Value>,
1101
+    depth: usize,
1102
+) {
1103
+    if depth >= DESCENDANT_MAX_DEPTH {
1104
+        return;
1105
+    }
1106
+    match root {
1107
+        Value::Context(map) => {
1108
+            if let Some(val) = map.get(name) {
1109
+                out.push(val.clone());
1110
+            }
1111
+            for child in map.values() {
1112
+                descendant_collect(child, name, seen, out, depth + 1);
1113
+            }
1114
+        }
1115
+        Value::List(items) => {
1116
+            for child in items {
1117
+                descendant_collect(child, name, seen, out, depth + 1);
1118
+            }
1119
+        }
1120
+        Value::Foreign(f) => {
1121
+            // Break a back-edge into an already-visited host object: the cycle's
1122
+            // duplicate is skipped, leaving the finite DAG unfolding.
1123
+            if !seen.insert(f.0.identity()) {
1124
+                return;
1125
+            }
1126
+            // Force one level and continue the descent (its own members are collected
1127
+            // by the Context/List arms; nested Foreigns re-check `seen`).
1128
+            descendant_collect(&f.0.force(), name, seen, out, depth + 1);
1129
+        }
1130
+        _ => {} // scalars, ranges, functions: nothing to descend into
1131
+    }
1132
+}
1133
+
10541134
 /// 1-based positional index into `items` (DMN §10.3.2.5): a positive `n` counts
10551135
 /// from the front, a negative `n` from the end. A non-integer or out-of-range
10561136
 /// `n` is a value-null. Reuses [`resolve_index`] — the same 1-based / negative

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

@@ -59,6 +59,7 @@
5959
         "**" => Tok::StarStar,
6060
         "." => Tok::Dot,
6161
         ".." => Tok::DotDot,
62
+        "..." => Tok::DotDotDot,
6263
         "(" => Tok::LParen,
6364
         ")" => Tok::RParen,
6465
         "[" => Tok::LBracket,
@@ -216,6 +217,14 @@
216217
 // conflict-free).
217218
 Postfix: Expr = {
218219
     <e:Postfix> "." <n:Name> => Expr::Path(Box::new(e), n),
220
+    // Descendant navigation `e ... name` (DMN §10.3.2.7, grammar rule 68): collect
221
+    // every value bound to `name` in `e` and all nested contexts, depth-first. Same
222
+    // precedence/position as the `.` path operator (it too binds tighter than unary
223
+    // minus); `...` is its own (longest) token, so it never collides with `.`/`..`.
224
+    // LR(1)-clean (the build.rs no-conflict gate proves it): `...` is a unique
225
+    // lookahead after a completed `Postfix`, distinct from the `.` path and the `..`
226
+    // range/iteration tokens.
227
+    <e:Postfix> "..." <n:Name> => Expr::Descendant(Box::new(e), n),
219228
     <e:Postfix> "[" <idx:Expr> "]" => Expr::Filter(Box::new(e), Box::new(idx)),
220229
     <n:Name> "(" ")" => Expr::FnCall(n, CallArgs::default()),
221230
     <n:Name> "(" <a:Comma<Arg>> ")" => Expr::FnCall(n, callargs_from(a)),

modified crates/feel-core/src/foreign.rs +23 −0

@@ -48,6 +48,29 @@
4848
 
4949
     /// Recover the concrete host handle (for identity pass-through on output).
5050
     fn as_any(&self) -> &dyn Any;
51
+
52
+    /// Stable identity for cycle detection in *unbounded* traversals — currently
53
+    /// only the descendant operator `e ... name` ([`crate::eval`]'s
54
+    /// `descendant_collect`). The engine keeps a visited-set keyed on this `usize`
55
+    /// to break back-edges in a cyclic host graph; pure-Rust FEEL values are owned
56
+    /// trees and cannot cycle, so only an `Arc`-backed `Foreign` handle can.
57
+    ///
58
+    /// The default is the Rust allocation address. That is correct only for hosts
59
+    /// that **intern** their wrappers (one `Arc` per host object) or that can never
60
+    /// form cycles. A host that mints a *fresh* `Arc` per access (feel-py, feel-lua,
61
+    /// feel-wasm — they wrap via `Arc::new` on every `force`/`get`) **and** whose
62
+    /// host objects can be cyclic MUST override this with the underlying object's
63
+    /// own identity, so two wrappers around the *same* host object compare equal:
64
+    /// feel-py returns `self.obj.as_ptr()` (= Python `id()`); feel-wasm uses a
65
+    /// JS-side `WeakMap<object, number>`. feel-pg is exempt — `jsonb` is a
66
+    /// serialized value tree and cannot cycle.
67
+    fn identity(&self) -> usize {
68
+        // `self` is a `&dyn ForeignObject` (fat pointer); cast through the thin data
69
+        // pointer to the object's address. This is the Rust *allocation* address, so
70
+        // it is a sound identity only when one `Arc` maps to one host object — hosts
71
+        // that mint a fresh `Arc` per access must override (see the doc above).
72
+        std::ptr::addr_of!(*self) as *const () as usize
73
+    }
5174
 }
5275
 
5376
 /// A reference-counted [`ForeignObject`] carried inside [`Value::Foreign`].

modified crates/feel-core/src/lexer.rs +3 −0

@@ -108,6 +108,8 @@
108108
     Star,
109109
     #[token("/")]
110110
     Slash,
111
+    #[token("...")]
112
+    DotDotDot,
111113
     #[token("..")]
112114
     DotDot,
113115
     #[token(".")]
@@ -569,6 +571,7 @@
569571
             Tok::StarStar => "**",
570572
             Tok::Star => "*",
571573
             Tok::Slash => "/",
574
+            Tok::DotDotDot => "...",
572575
             Tok::DotDot => "..",
573576
             Tok::Dot => ".",
574577
             Tok::LParen => "(",

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

@@ -2277,6 +2277,169 @@
22772277
         assert_eq!(std::mem::size_of::<Foreign>(), 16);
22782278
         assert_eq!(std::mem::size_of::<Value>(), 40);
22792279
     }
2280
+
2281
+    // ---- descendant expression `e ... name` (DMN §10.3.2.7, grammar rule 68) ----
2282
+
2283
+    #[test]
2284
+    fn descendant_spec_example() {
2285
+        // The spec's canonical example (§10.3.2.7): collect every `b` nested anywhere,
2286
+        // pre-order. `{a:{b:{b:1}}} ... b` -> [{b:1}, 1].
2287
+        let ctx = Context::empty();
2288
+        assert_eq!(
2289
+            run("{a: {b: {b: 1}}} ... b", &ctx),
2290
+            Value::List(vec![
2291
+                Value::Context(BTreeMap::from([("b".to_string(), Value::Number(1.0))])),
2292
+                Value::Number(1.0),
2293
+            ])
2294
+        );
2295
+    }
2296
+
2297
+    #[test]
2298
+    fn descendant_collects_across_a_list_of_contexts() {
2299
+        let ctx = Context::empty();
2300
+        assert_eq!(
2301
+            run("[{x:1},{x:2}] ... x", &ctx),
2302
+            Value::List(vec![Value::Number(1.0), Value::Number(2.0)])
2303
+        );
2304
+    }
2305
+
2306
+    #[test]
2307
+    fn descendant_no_match_is_empty_list() {
2308
+        // A search that finds nothing still yields a (flat) list, not null.
2309
+        let ctx = Context::empty();
2310
+        assert_eq!(run("{a:1} ... z", &ctx), Value::List(vec![]));
2311
+    }
2312
+
2313
+    #[test]
2314
+    fn descendant_on_null_and_scalar() {
2315
+        let ctx = Context::empty();
2316
+        // null propagates.
2317
+        assert_eq!(run("null ... x", &ctx), Value::Null);
2318
+        // A non-navigable scalar: applicability "type e is a context" fails -> null
2319
+        // (mirrors `.` on a non-context).
2320
+        assert_eq!(run("5 ... x", &ctx), Value::Null);
2321
+    }
2322
+
2323
+    #[test]
2324
+    fn descendant_descends_into_foreign() {
2325
+        // order -> { customer -> { name: "Ada" } }, all lazy Foreigns.
2326
+        let (gets, forces) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
2327
+        let customer = obj(&[("name", Value::String("Ada".into()))], &gets, &forces);
2328
+        let order = obj(&[("customer", customer)], &gets, &forces);
2329
+        let mut ctx = Context::empty();
2330
+        ctx.insert("order", order);
2331
+        // Descendant forces its way down the lazy graph and collects `name`.
2332
+        assert_eq!(
2333
+            run("order ... name", &ctx),
2334
+            Value::List(vec![Value::String("Ada".into())])
2335
+        );
2336
+    }
2337
+
2338
+    /// A cyclic foreign graph that mimics a host (feel-py) wrapping the *same*
2339
+    /// object with a *fresh* `Arc` on every access: `force`/`get("next")` mint a new
2340
+    /// `Arc<Cycle>` carrying the same `id`, so the Rust allocation address differs
2341
+    /// every time. Only the `identity()` override (the stable `id`) lets the
2342
+    /// descendant guard break the cycle — exactly the feel-py/lua/wasm scenario.
2343
+    #[derive(Debug)]
2344
+    struct Cycle {
2345
+        id: usize,
2346
+        value: f64,
2347
+    }
2348
+    impl ForeignObject for Cycle {
2349
+        fn get(&self, key: &str) -> Value {
2350
+            match key {
2351
+                "value" => Value::Number(self.value),
2352
+                "next" => Value::Foreign(Foreign(Arc::new(Cycle {
2353
+                    id: self.id,
2354
+                    value: self.value,
2355
+                }))),
2356
+                _ => Value::Null,
2357
+            }
2358
+        }
2359
+        fn force(&self) -> Value {
2360
+            let mut map = BTreeMap::new();
2361
+            map.insert("value".to_string(), Value::Number(self.value));
2362
+            map.insert(
2363
+                "next".to_string(),
2364
+                Value::Foreign(Foreign(Arc::new(Cycle {
2365
+                    id: self.id,
2366
+                    value: self.value,
2367
+                }))),
2368
+            );
2369
+            Value::Context(map)
2370
+        }
2371
+        fn as_any(&self) -> &dyn std::any::Any {
2372
+            self
2373
+        }
2374
+        fn identity(&self) -> usize {
2375
+            self.id
2376
+        }
2377
+    }
2378
+
2379
+    #[test]
2380
+    fn descendant_terminates_on_a_cyclic_foreign_with_fresh_arcs() {
2381
+        // Without the identity() override this would loop forever; with it, the
2382
+        // back-edge into the same `id` is skipped after the first descent.
2383
+        let mut ctx = Context::empty();
2384
+        ctx.insert(
2385
+            "c",
2386
+            Value::Foreign(Foreign(Arc::new(Cycle { id: 7, value: 42.0 }))),
2387
+        );
2388
+        // value=42 at the top, then once more at the (single) re-entered node before
2389
+        // the back-edge is cut -> [42, 42].
2390
+        assert_eq!(
2391
+            run("c ... value", &ctx),
2392
+            Value::List(vec![Value::Number(42.0), Value::Number(42.0)])
2393
+        );
2394
+    }
2395
+
2396
+    /// A self-referential cycle via a *single shared* `Arc` (the allocation address
2397
+    /// is reused), so the DEFAULT `identity()` (allocation address) suffices — this
2398
+    /// exercises the default code path rather than an override.
2399
+    #[derive(Debug)]
2400
+    struct SharedCycle {
2401
+        next: std::sync::OnceLock<Value>,
2402
+        value: f64,
2403
+    }
2404
+    impl ForeignObject for SharedCycle {
2405
+        fn get(&self, key: &str) -> Value {
2406
+            match key {
2407
+                "value" => Value::Number(self.value),
2408
+                "next" => self.next.get().cloned().unwrap_or(Value::Null),
2409
+                _ => Value::Null,
2410
+            }
2411
+        }
2412
+        fn force(&self) -> Value {
2413
+            let mut map = BTreeMap::new();
2414
+            map.insert("value".to_string(), Value::Number(self.value));
2415
+            map.insert(
2416
+                "next".to_string(),
2417
+                self.next.get().cloned().unwrap_or(Value::Null),
2418
+            );
2419
+            Value::Context(map)
2420
+        }
2421
+        fn as_any(&self) -> &dyn std::any::Any {
2422
+            self
2423
+        }
2424
+    }
2425
+
2426
+    #[test]
2427
+    fn descendant_terminates_on_a_cyclic_foreign_with_a_shared_arc() {
2428
+        let arc = Arc::new(SharedCycle {
2429
+            next: std::sync::OnceLock::new(),
2430
+            value: 9.0,
2431
+        });
2432
+        // Wire the self-reference after the Arc exists (same allocation reused).
2433
+        arc.next
2434
+            .set(Value::Foreign(Foreign(arc.clone())))
2435
+            .unwrap();
2436
+        let mut ctx = Context::empty();
2437
+        ctx.insert("c", Value::Foreign(Foreign(arc)));
2438
+        assert_eq!(
2439
+            run("c ... value", &ctx),
2440
+            Value::List(vec![Value::Number(9.0), Value::Number(9.0)])
2441
+        );
2442
+    }
22802443
 }
22812444
 
22822445
 /// User-defined functions: native FEEL closures and host callables (ADR-23).

modified docs/feel-coverage.md +1 −0

@@ -63,6 +63,7 @@
6363
 | Context literals `{a: 1, b: "x"}`          | §10.3.2.6 | ADR-12         | `0057-feel-context`    |
6464
 | Path access `ctx.member`, multi-word names | §10.3.2.6 | ADR-12, ADR-17 | `0074-feel-properties` |
6565
 | Nested contexts, missing key → `null`      | §10.3.2.6 | ADR-12         | `0057`, `0074`         |
66
+| Descendant `e ... name` (deep navigation) | §10.3.2.7 | ADR-46         | (no TCK case exists)   |
6667
 
6768
 ### Ranges (§10.3.2.7, §10.3.4.6)
6869