feat: descendant operator e ... name (DMN 10.3.2.7) — ADR-46, cycle-safe traversal in all wrappers
public
feat: descendant operator e ... name (DMN 10.3.2.7) — ADR-46, cycle-safe traversal in all wrappers
| Changeset | 603c5a20eb20d9e039342d5b1ab5e74226025b43 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | c8030dbae9eb a367f30c9e54 |
| Children | |
| Pushlog | by timo via ssh |
modified DECISIONS.md +74 −0
| @@ -2170,3 +2170,77 @@ | ||
| 2170 | 2170 | `0034-drg-scopes` (compliance-level-3) — 2 cases, `exact`; |
| 2171 | 2171 | `0070-feel-instance-of` (compliance-level-3) — 129 cases, `exact`. |
| 2172 | 2172 | **Suite 3003 → 3145.** |
| 2173 | + | |
| 2174 | +## ADR-46: Descendant expression `e ... name` + `ForeignObject::identity` (DMN §10.3.2.7, rule 68) | |
| 2175 | + | |
| 2176 | +- **Context:** Grammar rule 68 (`descendant expression = expression, "...", name`) was the | |
| 2177 | + one spec feature surfaced by reading the grammar rather than the TCK — no DMN-TCK case | |
| 2178 | + (level 2 or 3) exercises it, so it was documented as coverage gap #14. Semantics | |
| 2179 | + (§10.3.2.7, Table 68): where `e` is a context, `e ... name` returns a **list** of every | |
| 2180 | + value bound to `name` in `e` *and all nested contexts*, collected pre-order | |
| 2181 | + (`{a:{b:{b:1}}} ... b` → `[{b:1}, 1]`). The `.` operator already maps over a list of | |
| 2182 | + contexts; descendant recurses depth-first through the whole structure. | |
| 2183 | + | |
| 2184 | + The design crux: descendant is the engine's **first unbounded collection traversal**. | |
| 2185 | + ADR-21's laziness-terminates guarantee (a written `.`-path is finite, so cyclic host | |
| 2186 | + graphs are harmless — `lib.rs` test `unbounded_graph_terminates_along_a_finite_path`) | |
| 2187 | + does **not** apply: descendant recurses through the whole reachable graph, so a cyclic | |
| 2188 | + host graph behind `Value::Foreign` would loop forever. | |
| 2189 | + | |
| 2190 | +- **Decision:** Five-part change. | |
| 2191 | + | |
| 2192 | + 1. **Lexer** — a new `...` token (`DotDotDot`). logos longest-match keeps it disjoint | |
| 2193 | + from `.`/`..`; no LR interaction. | |
| 2194 | + 2. **Grammar** — one `Postfix` production `<e:Postfix> "..." <n:Name>` → `Expr::Descendant`, | |
| 2195 | + same precedence as the `.` path operator. `...` is a unique lookahead after a completed | |
| 2196 | + `Postfix`, so it is LR(1)-clean (the `build.rs` no-conflict gate is green). | |
| 2197 | + 3. **AST/eval** — `Expr::Descendant(Box<Expr>, String)`; the evaluator's `descendant_collect` | |
| 2198 | + walks pre-order over `Context`/`List` (collect the match, then recurse into every | |
| 2199 | + child) and `Foreign` (force one level, recurse). A null/error target propagates; a | |
| 2200 | + non-navigable scalar is `null` (mirrors `.`); otherwise the result is a list (possibly | |
| 2201 | + empty). A `DESCENDANT_MAX_DEPTH = 1024` cap is a secondary backstop. | |
| 2202 | + 4. **Cycle guard / DAG de-dup** — a `HashSet<usize>` visited-set keyed on a new | |
| 2203 | + `ForeignObject::identity() -> usize` trait method (default = the Rust allocation | |
| 2204 | + address). Only an `Arc`-backed `Value::Foreign` can form a cycle (pure-Rust values are | |
| 2205 | + owned trees), and **only** `Foreign` nodes are keyed in the set, so the guard is a no-op | |
| 2206 | + (empty set) for a pure-Rust embedder. The set stores plain integers — it owns nothing, | |
| 2207 | + cannot extend any object's lifetime, and is dropped at scope exit (RAII; the workspace | |
| 2208 | + uses `panic = unwind`, so also on panic): no leak. | |
| 2209 | + | |
| 2210 | + The set is **global** (threaded through the whole traversal, never cleared), so it does | |
| 2211 | + double duty: it breaks cycles *and* de-duplicates shared *acyclic* host sub-objects (a | |
| 2212 | + diamond/DAG reachable via two paths is collected once, not once per path). Pure-FEEL | |
| 2213 | + contexts are owned value trees and never `Foreign`, so they are never keyed — the spec | |
| 2214 | + domain keeps exact multiset semantics; only host-object sharing (out of DMN spec) is | |
| 2215 | + de-duped. The alternative, a *path-scoped* set (insert on entry, remove on exit), would | |
| 2216 | + match per-path multiset semantics and still terminate on cycles, but it risks | |
| 2217 | + **exponential blowup** on diamond-heavy DAGs (a subgraph reachable via 2ᵏ paths is | |
| 2218 | + traversed 2ᵏ times) — a real hazard for feel-py's ORM/object-graph target. The global set | |
| 2219 | + is therefore the deliberate choice: trade per-path multiset semantics for shared host | |
| 2220 | + data in exchange for cycle-safety *and* DAG-blow-up protection. | |
| 2221 | + 5. **Per-host identity overrides** — the default allocation address is sound only when one | |
| 2222 | + `Arc` maps to one host object. Every host wrapper mints a *fresh* `Arc` per wrap | |
| 2223 | + (`shallow_convert*` → `Arc::new` re-run on every `force`/`get`), so two wrappers around | |
| 2224 | + the *same* host object have distinct allocations. The correct identity is host-specific: | |
| 2225 | + - **feel-py** — `self.obj.as_ptr()` (= Python `id()`, stable across `Py::clone`, no GIL). | |
| 2226 | + - **feel-lua** — `self.table.to_pointer()` (mlua's Lua table pointer; stable across | |
| 2227 | + `Table::clone`). | |
| 2228 | + - **feel-wasm** — a process-wide `WeakMap<object, number>` (`js_identity`): JS exposes | |
| 2229 | + no cheap object address and a `JsValue` handle index is *not* object identity across | |
| 2230 | + different reads, so a WeakMap assigns each distinct object a stable integer. Its keys | |
| 2231 | + are weakly held → reclaimed by GC, so it neither pins objects nor grows unboundedly. | |
| 2232 | + - **feel-pg** — **exempt**: `jsonb` is a serialized value tree, so a `JsonbForeign` | |
| 2233 | + sub-graph is definitionally acyclic; no override, no cycle test. | |
| 2234 | + | |
| 2235 | + This keeps feel-core's guard a plain `HashSet<usize>` (target-agnostic) while pushing | |
| 2236 | + "what is the same object" into each host — symmetric with the existing | |
| 2237 | + `ForeignObject::as_any` output-identity seam (ADR-21). | |
| 2238 | + | |
| 2239 | +- **Consequence:** The last spec grammar rule (68) is implemented; the engine's FEEL slice | |
| 2240 | + is now rule-1–68 complete (modulo the DRG-only out-of-scope forms). No TCK case exists, so | |
| 2241 | + the fixture suite is unchanged (still 3145 cases / 110 files). Tests added: feel-core | |
| 2242 | + (`foreign_tests`, incl. two cyclic-Foreign shapes — a fresh-`Arc`-per-access `Cycle` keyed | |
| 2243 | + on `id` and a single-shared-`Arc` `SharedCycle` keyed on the allocation address), feel-py | |
| 2244 | + (cyclic dict + cyclic class instance), feel-lua (cyclic table), feel-wasm (cyclic object), | |
| 2245 | + feel-pg (jsonb tree — terminates by construction). All non-pg suites pass; feel-pg is | |
| 2246 | + exercised via `cargo pgx test` (the pgrx harness, not runnable without a managed Postgres). | |
modified crates/feel-core/src/ast.rs +8 −0
| @@ -31,6 +31,13 @@ | ||
| 31 | 31 | /// side is a list of contexts, the access is mapped over the list and returns |
| 32 | 32 | /// a list of selections (DMN §10.3.2.5), e.g. `[{x:1},{x:2}].x = [1, 2]`. |
| 33 | 33 | 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), | |
| 34 | 41 | /// Filter / index `collection[bracket]` (DMN §10.3.2.5). A numeric bracket is |
| 35 | 42 | /// a 1-based index (negative-from-end, out-of-range → null); any other bracket |
| 36 | 43 | /// is a boolean filter evaluated per element with the element bound as `item`. |
| @@ -371,6 +378,7 @@ | ||
| 371 | 378 | Expr::RangeLit(iv) => interval_is_clock_free(iv), |
| 372 | 379 | Expr::ContextLit(entries) => entries.iter().all(|(_, e)| e.is_clock_free()), |
| 373 | 380 | Expr::Path(target, _) => target.is_clock_free(), |
| 381 | + Expr::Descendant(target, _) => target.is_clock_free(), | |
| 374 | 382 | Expr::Filter(source, bracket) => { |
| 375 | 383 | source.is_clock_free() && bracket.is_clock_free() |
| 376 | 384 | } |
modified crates/feel-core/src/eval.rs +92 −1
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | |
| 10 | 10 | use std::cell::Cell; |
| 11 | 11 | use std::cmp::Ordering; |
| 12 | -use std::collections::BTreeMap; | |
| 12 | +use std::collections::{BTreeMap, HashSet}; | |
| 13 | 13 | use std::sync::Arc; |
| 14 | 14 | |
| 15 | 15 | use crate::ast::{ArithOp, CallArgs, CmpOp, Expr, FeelType, IterSource, Quantifier, UnaryTest}; |
| @@ -27,6 +27,13 @@ | ||
| 27 | 27 | /// small thread stack (a deeply nested tree-walk costs several native frames per |
| 28 | 28 | /// FEEL call). |
| 29 | 29 | 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; | |
| 30 | 37 | |
| 31 | 38 | /// A tree-walking evaluator carrying the evaluation environment (host regex |
| 32 | 39 | /// provider + `now()`/`today()` instant + host function registry; |
| @@ -117,6 +124,28 @@ | ||
| 117 | 124 | } |
| 118 | 125 | other => member_access(other, name), |
| 119 | 126 | }), |
| 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 | + } | |
| 120 | 149 | Expr::Filter(source, bracket) => self.eval_filter(source, bracket, ctx), |
| 121 | 150 | // A function literal captures the current scope (lexical closure, ADR-23). |
| 122 | 151 | Expr::FnDef { params, body } => Ok(Func::Closure(Closure { |
| @@ -1051,6 +1080,68 @@ | ||
| 1051 | 1080 | } |
| 1052 | 1081 | } |
| 1053 | 1082 | |
| 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 / DAG de-dup.** `seen` is a *global* visited-set — threaded | |
| 1090 | +/// through the whole traversal, never cleared — keyed on | |
| 1091 | +/// [`ForeignObject::identity`](crate::foreign::ForeignObject::identity), the *host | |
| 1092 | +/// object's* identity (not the Rust allocation address). Only an `Arc`-backed | |
| 1093 | +/// [`Value::Foreign`] is keyed; pure-Rust values are owned trees and never | |
| 1094 | +/// `Foreign`, so a pure-FEEL context is traversed in full (exact multiset | |
| 1095 | +/// semantics, per spec). A host that mints a fresh `Arc` per `force`/`get` | |
| 1096 | +/// (feel-py/lua/wasm) still has a back-edge broken once its `identity()` override | |
| 1097 | +/// returns a stable value (feel-pg is exempt: `jsonb` cannot cycle). | |
| 1098 | +/// | |
| 1099 | +/// Because the set is global and never cleared, it also **de-duplicates shared | |
| 1100 | +/// *acyclic* host sub-objects** (a diamond/DAG): a host object reachable via two | |
| 1101 | +/// distinct paths is collected once, not once per path. Host object graphs are out | |
| 1102 | +/// of DMN spec (spec defines descendant only over value-tree contexts), so there is | |
| 1103 | +/// no spec answer; the global set is chosen over a path-scoped set (insert on entry, | |
| 1104 | +/// remove on exit) to prevent *exponential blowup* on diamond-heavy DAGs, accepting | |
| 1105 | +/// per-path multiset semantics for shared host data as the trade-off. See ADR-46. | |
| 1106 | +/// [`DESCENDANT_MAX_DEPTH`] is a secondary backstop. | |
| 1107 | +fn descendant_collect( | |
| 1108 | + root: &Value, | |
| 1109 | + name: &str, | |
| 1110 | + seen: &mut HashSet<usize>, | |
| 1111 | + out: &mut Vec<Value>, | |
| 1112 | + depth: usize, | |
| 1113 | +) { | |
| 1114 | + if depth >= DESCENDANT_MAX_DEPTH { | |
| 1115 | + return; | |
| 1116 | + } | |
| 1117 | + match root { | |
| 1118 | + Value::Context(map) => { | |
| 1119 | + if let Some(val) = map.get(name) { | |
| 1120 | + out.push(val.clone()); | |
| 1121 | + } | |
| 1122 | + for child in map.values() { | |
| 1123 | + descendant_collect(child, name, seen, out, depth + 1); | |
| 1124 | + } | |
| 1125 | + } | |
| 1126 | + Value::List(items) => { | |
| 1127 | + for child in items { | |
| 1128 | + descendant_collect(child, name, seen, out, depth + 1); | |
| 1129 | + } | |
| 1130 | + } | |
| 1131 | + Value::Foreign(f) => { | |
| 1132 | + // Break a back-edge into an already-visited host object: the cycle's | |
| 1133 | + // duplicate is skipped, leaving the finite DAG unfolding. | |
| 1134 | + if !seen.insert(f.0.identity()) { | |
| 1135 | + return; | |
| 1136 | + } | |
| 1137 | + // Force one level and continue the descent (its own members are collected | |
| 1138 | + // by the Context/List arms; nested Foreigns re-check `seen`). | |
| 1139 | + descendant_collect(&f.0.force(), name, seen, out, depth + 1); | |
| 1140 | + } | |
| 1141 | + _ => {} // scalars, ranges, functions: nothing to descend into | |
| 1142 | + } | |
| 1143 | +} | |
| 1144 | + | |
| 1054 | 1145 | /// 1-based positional index into `items` (DMN §10.3.2.5): a positive `n` counts |
| 1055 | 1146 | /// from the front, a negative `n` from the end. A non-integer or out-of-range |
| 1056 | 1147 | /// `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 @@ | ||
| 59 | 59 | "**" => Tok::StarStar, |
| 60 | 60 | "." => Tok::Dot, |
| 61 | 61 | ".." => Tok::DotDot, |
| 62 | + "..." => Tok::DotDotDot, | |
| 62 | 63 | "(" => Tok::LParen, |
| 63 | 64 | ")" => Tok::RParen, |
| 64 | 65 | "[" => Tok::LBracket, |
| @@ -216,6 +217,14 @@ | ||
| 216 | 217 | // conflict-free). |
| 217 | 218 | Postfix: Expr = { |
| 218 | 219 | <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), | |
| 219 | 228 | <e:Postfix> "[" <idx:Expr> "]" => Expr::Filter(Box::new(e), Box::new(idx)), |
| 220 | 229 | <n:Name> "(" ")" => Expr::FnCall(n, CallArgs::default()), |
| 221 | 230 | <n:Name> "(" <a:Comma<Arg>> ")" => Expr::FnCall(n, callargs_from(a)), |
modified crates/feel-core/src/foreign.rs +23 −0
| @@ -48,6 +48,29 @@ | ||
| 48 | 48 | |
| 49 | 49 | /// Recover the concrete host handle (for identity pass-through on output). |
| 50 | 50 | 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 | + } | |
| 51 | 74 | } |
| 52 | 75 | |
| 53 | 76 | /// A reference-counted [`ForeignObject`] carried inside [`Value::Foreign`]. |
modified crates/feel-core/src/lexer.rs +3 −0
| @@ -108,6 +108,8 @@ | ||
| 108 | 108 | Star, |
| 109 | 109 | #[token("/")] |
| 110 | 110 | Slash, |
| 111 | + #[token("...")] | |
| 112 | + DotDotDot, | |
| 111 | 113 | #[token("..")] |
| 112 | 114 | DotDot, |
| 113 | 115 | #[token(".")] |
| @@ -569,6 +571,7 @@ | ||
| 569 | 571 | Tok::StarStar => "**", |
| 570 | 572 | Tok::Star => "*", |
| 571 | 573 | Tok::Slash => "/", |
| 574 | + Tok::DotDotDot => "...", | |
| 572 | 575 | Tok::DotDot => "..", |
| 573 | 576 | Tok::Dot => ".", |
| 574 | 577 | Tok::LParen => "(", |
modified crates/feel-core/src/lib.rs +191 −0
| @@ -2277,6 +2277,197 @@ | ||
| 2277 | 2277 | assert_eq!(std::mem::size_of::<Foreign>(), 16); |
| 2278 | 2278 | assert_eq!(std::mem::size_of::<Value>(), 40); |
| 2279 | 2279 | } |
| 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 | + } | |
| 2443 | + | |
| 2444 | + #[test] | |
| 2445 | + fn descendant_dedups_a_shared_acyclic_foreign_dag() { | |
| 2446 | + // Pure-FEEL contrast first: two DISTINCT value contexts (owned, never | |
| 2447 | + // Foreign) -> both traversed -> multiset [1, 1]. The spec domain is exact. | |
| 2448 | + let ctx = Context::empty(); | |
| 2449 | + assert_eq!( | |
| 2450 | + run("{x:{v:1}, y:{v:1}} ... v", &ctx), | |
| 2451 | + Value::List(vec![Value::Number(1.0), Value::Number(1.0)]) | |
| 2452 | + ); | |
| 2453 | + | |
| 2454 | + // Same shape but the inner object is ONE shared host object (a diamond/DAG, | |
| 2455 | + // not a cycle): both `x` and `y` reference the same `a` (same Foreign | |
| 2456 | + // identity). The GLOBAL visited-set collects `v` once, not once per path — | |
| 2457 | + // the intentional DAG de-dup (ADR-46). Host object graphs are out of DMN | |
| 2458 | + // spec; the global set is chosen over a path-scoped set to avoid exponential | |
| 2459 | + // blowup on diamond-heavy DAGs, accepting per-path multiset semantics for | |
| 2460 | + // shared host data. | |
| 2461 | + let (gets, forces) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); | |
| 2462 | + let a = obj(&[("v", Value::Number(1.0))], &gets, &forces); | |
| 2463 | + let g = obj(&[("x", a.clone()), ("y", a.clone())], &gets, &forces); | |
| 2464 | + let mut ctx = Context::empty(); | |
| 2465 | + ctx.insert("g", g); | |
| 2466 | + assert_eq!( | |
| 2467 | + run("g ... v", &ctx), | |
| 2468 | + Value::List(vec![Value::Number(1.0)]) | |
| 2469 | + ); | |
| 2470 | + } | |
| 2280 | 2471 | } |
| 2281 | 2472 | |
| 2282 | 2473 | /// User-defined functions: native FEEL closures and host callables (ADR-23). |
modified crates/feel-lua/src/lib.rs +9 −0
| @@ -269,6 +269,15 @@ | ||
| 269 | 269 | fn as_any(&self) -> &dyn Any { |
| 270 | 270 | self |
| 271 | 271 | } |
| 272 | + | |
| 273 | + /// Lua table identity for cycle detection in unbounded traversals (the | |
| 274 | + /// descendant `...` operator). feel-lua mints a fresh `Arc<LuaForeign>` per wrap | |
| 275 | + /// (`shallow_convert_lua` re-runs on every `force`/`get`), so the Rust allocation | |
| 276 | + /// address is *not* stable; the underlying Lua table's pointer (stable across | |
| 277 | + /// `Table::clone`, = the table's identity) is. `Table::to_pointer` exposes it. | |
| 278 | + fn identity(&self) -> usize { | |
| 279 | + self.table.to_pointer() as usize | |
| 280 | + } | |
| 272 | 281 | } |
| 273 | 282 | |
| 274 | 283 | // --------------------------------------------------------------------------- // |
modified crates/feel-lua/tests/feel.rs +54 −0
| @@ -324,3 +324,57 @@ | ||
| 324 | 324 | .unwrap(); |
| 325 | 325 | assert_eq!((a, b), (2, 42)); |
| 326 | 326 | } |
| 327 | + | |
| 328 | +// --------------------------------------------------------------------------- // | |
| 329 | +// Descendant `e ... name` (DMN 10.3.2.7, grammar rule 68) | |
| 330 | +// --------------------------------------------------------------------------- // | |
| 331 | + | |
| 332 | +#[test] | |
| 333 | +fn descendant_collects_across_a_list_of_tables() { | |
| 334 | + let lua = vm(); | |
| 335 | + let xs: Vec<i64> = lua | |
| 336 | + .load(r#"return feel.evaluate("[{x:1},{x:2}] ... x")"#) | |
| 337 | + .eval() | |
| 338 | + .unwrap(); | |
| 339 | + assert_eq!(xs, vec![1, 2]); | |
| 340 | +} | |
| 341 | + | |
| 342 | +#[test] | |
| 343 | +fn descendant_no_match_is_empty_list() { | |
| 344 | + let lua = vm(); | |
| 345 | + let xs: Vec<i64> = lua | |
| 346 | + .load(r#"return feel.evaluate("{a:1} ... z")"#) | |
| 347 | + .eval() | |
| 348 | + .unwrap(); | |
| 349 | + assert!(xs.is_empty()); | |
| 350 | +} | |
| 351 | + | |
| 352 | +#[test] | |
| 353 | +fn descendant_descends_into_nested_table() { | |
| 354 | + let lua = vm(); | |
| 355 | + let names: Vec<String> = lua | |
| 356 | + .load( | |
| 357 | + r#"return feel.evaluate("o ... name", { o = { customer = { name = "Ada" } } })"#, | |
| 358 | + ) | |
| 359 | + .eval() | |
| 360 | + .unwrap(); | |
| 361 | + assert_eq!(names, vec!["Ada".to_string()]); | |
| 362 | +} | |
| 363 | + | |
| 364 | +#[test] | |
| 365 | +fn descendant_terminates_on_a_cyclic_table() { | |
| 366 | + // Without the `Table::to_pointer`-based identity override this would loop | |
| 367 | + // forever; with it, the back-edge into the same table is cut after one re-entry. | |
| 368 | + let lua = vm(); | |
| 369 | + let xs: Vec<i64> = lua | |
| 370 | + .load( | |
| 371 | + r#" | |
| 372 | + local c = { value = 42 } | |
| 373 | + c.next = c -- self-referential (cyclic) Lua table | |
| 374 | + return feel.evaluate("c ... value", { c = c }) | |
| 375 | + "#, | |
| 376 | + ) | |
| 377 | + .eval() | |
| 378 | + .unwrap(); | |
| 379 | + assert_eq!(xs, vec![42, 42]); | |
| 380 | +} | |
modified crates/feel-pg/src/lib.rs +40 −0
| @@ -570,6 +570,46 @@ | ||
| 570 | 570 | ) |
| 571 | 571 | .expect("DDL should raise before this unwrap"); |
| 572 | 572 | } |
| 573 | + | |
| 574 | + // Descendant `e ... name` (DMN 10.3.2.7, grammar rule 68). jsonb is a serialized | |
| 575 | + // value tree, so the reachable JsonbForeign sub-graph is definitionally acyclic | |
| 576 | + // — feel-pg is EXEMPT from the cycle-guard question (no identity() override and | |
| 577 | + // no cycle test, because a cycle cannot be constructed in jsonb). | |
| 578 | + #[pg_test] | |
| 579 | + fn descendant_spec_example() { | |
| 580 | + let matched = Spi::get_one::<bool>( | |
| 581 | + r#"SELECT feel_eval('{a: {b: {b: 1}}} ... b') = '[{"b": 1}, 1]'::jsonb"#, | |
| 582 | + ) | |
| 583 | + .expect("SPI query failed"); | |
| 584 | + assert_eq!(matched, Some(true)); | |
| 585 | + } | |
| 586 | + | |
| 587 | + #[pg_test] | |
| 588 | + fn descendant_collects_across_a_list_of_contexts() { | |
| 589 | + let matched = Spi::get_one::<bool>( | |
| 590 | + r#"SELECT feel_eval('[{x:1},{x:2}] ... x') = '[1, 2]'::jsonb"#, | |
| 591 | + ) | |
| 592 | + .expect("SPI query failed"); | |
| 593 | + assert_eq!(matched, Some(true)); | |
| 594 | + } | |
| 595 | + | |
| 596 | + #[pg_test] | |
| 597 | + fn descendant_no_match_is_empty_list() { | |
| 598 | + let matched = | |
| 599 | + Spi::get_one::<bool>(r#"SELECT feel_eval('{a:1} ... z') = '[]'::jsonb"#) | |
| 600 | + .expect("SPI query failed"); | |
| 601 | + assert_eq!(matched, Some(true)); | |
| 602 | + } | |
| 603 | + | |
| 604 | + #[pg_test] | |
| 605 | + fn descendant_descends_into_nested_jsonb() { | |
| 606 | + let matched = Spi::get_one::<bool>( | |
| 607 | + r#"SELECT feel_eval('o ... name', '{"o": {"customer": {"name": "Ada"}}}'::jsonb) | |
| 608 | + = '["Ada"]'::jsonb"#, | |
| 609 | + ) | |
| 610 | + .expect("SPI query failed"); | |
| 611 | + assert_eq!(matched, Some(true)); | |
| 612 | + } | |
| 573 | 613 | } |
| 574 | 614 | |
| 575 | 615 | /// Required pgrx test harness hooks. |
modified crates/feel-py/src/lib.rs +11 −0
| @@ -323,6 +323,17 @@ | ||
| 323 | 323 | |
| 324 | 324 | fn as_any(&self) -> &dyn std::any::Any { |
| 325 | 325 | self |
| 326 | + } | |
| 327 | + | |
| 328 | + /// Python object identity for cycle detection in unbounded traversals (the | |
| 329 | + /// descendant `...` operator). feel-py mints a fresh `Arc<PyForeign>` per wrap | |
| 330 | + /// (`shallow_convert` re-runs on every `force`/`get`), so the Rust allocation | |
| 331 | + /// address is *not* stable; the underlying Python object's pointer (= `id()`, | |
| 332 | + /// preserved across `Py::clone`) is. It is stable for the object's lifetime, and | |
| 333 | + /// the traversal holds `Py<PyAny>` clones keeping it alive, so the address cannot | |
| 334 | + /// be recycled mid-traversal. | |
| 335 | + fn identity(&self) -> usize { | |
| 336 | + self.obj.as_ptr() as usize | |
| 326 | 337 | } |
| 327 | 338 | } |
| 328 | 339 | |
modified crates/feel-py/tests/test_feel.py +57 −0
| @@ -199,6 +199,63 @@ | ||
| 199 | 199 | assert feel.evaluate("x.self.self.self.a", {"x": d}) == 1 |
| 200 | 200 | # And the cyclic object passes through by identity. |
| 201 | 201 | assert feel.evaluate("x.self", {"x": d}) is d |
| 202 | + | |
| 203 | + | |
| 204 | +# --- descendant `e ... name` (DMN 10.3.2.7, grammar rule 68) -------------- # | |
| 205 | +# | |
| 206 | +# Descendant recursively collects every value bound to `name` in `e` and all nested | |
| 207 | +# contexts. Unlike the lazy `.`, it is an *unbounded* traversal, so a cyclic Python | |
| 208 | +# object would loop forever without the `identity()` override (which keys on the | |
| 209 | +# Python object pointer, i.e. `id()`). | |
| 210 | + | |
| 211 | +def test_descendant_spec_example(): | |
| 212 | + assert feel.evaluate("{a: {b: {b: 1}}} ... b") == [{"b": 1}, 1] | |
| 213 | + | |
| 214 | + | |
| 215 | +def test_descendant_collects_across_list_of_dicts(): | |
| 216 | + assert feel.evaluate("[{x:1},{x:2}] ... x") == [1, 2] | |
| 217 | + | |
| 218 | + | |
| 219 | +def test_descendant_no_match_is_empty_list(): | |
| 220 | + assert feel.evaluate("{a:1} ... z") == [] | |
| 221 | + | |
| 222 | + | |
| 223 | +def test_descendant_descends_into_nested_object(): | |
| 224 | + from dataclasses import dataclass | |
| 225 | + | |
| 226 | + @dataclass | |
| 227 | + class Customer: | |
| 228 | + name: str | |
| 229 | + | |
| 230 | + @dataclass | |
| 231 | + class Order: | |
| 232 | + customer: Customer | |
| 233 | + | |
| 234 | + assert feel.evaluate("o ... name", {"o": Order(Customer("Ada"))}) == ["Ada"] | |
| 235 | + | |
| 236 | + | |
| 237 | +def test_descendant_terminates_on_cyclic_dict(): | |
| 238 | + # A self-referential dict: `next` points back to the same object (same `id()`). | |
| 239 | + # The visited-set (keyed on the Python pointer) breaks the back-edge after the | |
| 240 | + # first re-entry, so this terminates and yields a finite, non-empty list. | |
| 241 | + d = {"value": 42} | |
| 242 | + d["next"] = d | |
| 243 | + result = feel.evaluate("c ... value", {"c": d}) | |
| 244 | + assert result == [42, 42] | |
| 245 | + | |
| 246 | + | |
| 247 | +def test_descendant_terminates_on_cyclic_instance(): | |
| 248 | + # Same cycle, but via a class instance with a self-referential attribute | |
| 249 | + # (the realistic ORM/object-graph shape). Distinct fresh `Arc`s per access are | |
| 250 | + # bridged by the `id()`-based identity. | |
| 251 | + class Node: | |
| 252 | + pass | |
| 253 | + | |
| 254 | + n = Node() | |
| 255 | + n.value = 7 | |
| 256 | + n.next = n | |
| 257 | + assert feel.evaluate("n ... value", {"n": n}) == [7, 7] | |
| 258 | + | |
| 202 | 259 | |
| 203 | 260 | |
| 204 | 261 | # --- compile reuse -------------------------------------------------------- # |
modified crates/feel-wasm/smoke.mjs +31 −0
| @@ -115,6 +115,37 @@ | ||
| 115 | 115 | ok = false; |
| 116 | 116 | } |
| 117 | 117 | |
| 118 | +// Descendant `e ... name` (DMN 10.3.2.7): recursively collect every value bound to | |
| 119 | +// `name` in `e` and all nested contexts. Unlike the lazy `.`, it is an *unbounded* | |
| 120 | +// traversal, so a cyclic object would loop forever without the WeakMap-based | |
| 121 | +// identity (JS exposes no cheap object address, so object identity is derived via a | |
| 122 | +// WeakMap<object, number>). | |
| 123 | +const descendantCases = [ | |
| 124 | + ["{a: {b: {b: 1}}} ... b", {}, [{ b: 1 }, 1]], | |
| 125 | + ["[{x:1},{x:2}] ... x", {}, [1, 2]], | |
| 126 | + ["{a:1} ... z", {}, []], | |
| 127 | + ["o ... name", { o: { customer: { name: "Ada" } } }, ["Ada"]], | |
| 128 | +]; | |
| 129 | +for (const [expr, ctx, expected] of descendantCases) { | |
| 130 | + const got = evaluate(expr, ctx); | |
| 131 | + console.log(`${expr} => ${JSON.stringify(got)}`); | |
| 132 | + if (!eq(got, expected)) { | |
| 133 | + console.error(`FAIL: ${expr} expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`); | |
| 134 | + ok = false; | |
| 135 | + } | |
| 136 | +} | |
| 137 | +// The descendant traversal over a *cyclic* object must terminate: the back-edge into | |
| 138 | +// the same object (same WeakMap id) is cut after the first re-entry. `cyc2.next` | |
| 139 | +// points back to `cyc2`, so `value` is collected twice before the cycle is broken. | |
| 140 | +const cyc2 = { value: 42 }; | |
| 141 | +cyc2.next = cyc2; | |
| 142 | +const cycDesc = evaluate("c ... value", { c: cyc2 }); | |
| 143 | +console.log(`c ... value (cyclic) => ${JSON.stringify(cycDesc)}`); | |
| 144 | +if (!eq(cycDesc, [42, 42])) { | |
| 145 | + console.error(`FAIL: descendant over a cyclic object should terminate with [42,42], got ${JSON.stringify(cycDesc)}`); | |
| 146 | + ok = false; | |
| 147 | +} | |
| 148 | + | |
| 118 | 149 | // Boundary policy (ADR-14): a type error is a lenient `null`, but `evaluate_strict` |
| 119 | 150 | // surfaces it as a thrown exception instead of letting it pass silently as `null`. |
| 120 | 151 | const threw = (fn) => { |
modified crates/feel-wasm/src/lib.rs +37 −0
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | //! A finite expression can only navigate a finite path, so cyclic objects need no |
| 17 | 17 | //! cycle guard (the previous `js_to_value` guard is gone). |
| 18 | 18 | |
| 19 | +use std::cell::RefCell; | |
| 19 | 20 | use std::collections::BTreeMap; |
| 20 | 21 | use std::sync::Arc; |
| 21 | 22 | |
| @@ -341,6 +342,42 @@ | ||
| 341 | 342 | fn as_any(&self) -> &dyn std::any::Any { |
| 342 | 343 | self |
| 343 | 344 | } |
| 345 | + | |
| 346 | + /// JS object identity for cycle detection in unbounded traversals (the | |
| 347 | + /// descendant `...` operator). feel-wasm mints a fresh `Arc<JsForeign>` per wrap | |
| 348 | + /// (`shallow_convert_js` re-runs on every `force`/`get`), and a `JsValue` handle | |
| 349 | + /// index is NOT object identity across different reads of the same object, so the | |
| 350 | + /// default (allocation address) guard would miss a cycle. We map each distinct | |
| 351 | + /// object to a stable integer via a process-wide `WeakMap` ([`js_identity`]). | |
| 352 | + fn identity(&self) -> usize { | |
| 353 | + js_identity(&self.obj) | |
| 354 | + } | |
| 355 | +} | |
| 356 | + | |
| 357 | +/// Assign each distinct JS object a stable integer identity via a process-wide | |
| 358 | +/// `WeakMap`. Its keys are weakly referenced, so it neither pins objects nor grows | |
| 359 | +/// unboundedly with live data — entries are GC'd once the object is unreferenced | |
| 360 | +/// elsewhere. This is the JS analogue of feel-py's `id()` / feel-lua's table | |
| 361 | +/// pointer: JS exposes no cheap object address, so a `WeakMap<object, number>` is | |
| 362 | +/// the standard way to derive a hashable, stable identity. | |
| 363 | +fn js_identity(obj: &JsValue) -> usize { | |
| 364 | + thread_local! { | |
| 365 | + static IDS: RefCell<(js_sys::WeakMap, u32)> = | |
| 366 | + RefCell::new((js_sys::WeakMap::new(), 0)); | |
| 367 | + } | |
| 368 | + IDS.with(|cell| { | |
| 369 | + let (map, next) = &mut *cell.borrow_mut(); | |
| 370 | + // A Foreign always wraps an object; `unchecked_ref` is the zero-cost view. | |
| 371 | + let key: &js_sys::Object = obj.unchecked_ref(); | |
| 372 | + if let Some(v) = map.get_checked(key) { | |
| 373 | + v.as_f64().map(|n| n as usize).unwrap_or(0) | |
| 374 | + } else { | |
| 375 | + let n = *next; | |
| 376 | + *next += 1; | |
| 377 | + let _ = map.set(key, &JsValue::from(n)); | |
| 378 | + n as usize | |
| 379 | + } | |
| 380 | + }) | |
| 344 | 381 | } |
| 345 | 382 | |
| 346 | 383 | // --------------------------------------------------------------------------- // |
modified docs/feel-coverage.md +1 −0
| @@ -63,6 +63,7 @@ | ||
| 63 | 63 | | Context literals `{a: 1, b: "x"}` | §10.3.2.6 | ADR-12 | `0057-feel-context` | |
| 64 | 64 | | Path access `ctx.member`, multi-word names | §10.3.2.6 | ADR-12, ADR-17 | `0074-feel-properties` | |
| 65 | 65 | | 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) | | |
| 66 | 67 | |
| 67 | 68 | ### Ranges (§10.3.2.7, §10.3.4.6) |
| 68 | 69 | |