Public repository: timo / feel

Reader

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

fix(feel-core): never member-probe a shadowed or filter-local path root (ADR-48)

draft feat/name-resolution-v2

fix(feel-core): never member-probe a shadowed or filter-local path root (ADR-48)

The member probe navigates from the root binding. When the path's root is
bound by the expression itself — a for/some/every variable, a function
parameter, a context-literal key — or the path sits inside a filter
bracket, the root value is the wrong one: `for item in items return
item.unit-price` read the ROOT item's member for every element. Such paths
now keep the arithmetic reading (backticks override). Tests per case,
verified failing without the fix; plus tests that backtick content keeps
every space. README: guidance on choosing a level and on backticks.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Changeset7690f6d5c4ed8e849d0c5ad403c976cb7901b0d5
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents87c40d282078
Children
Pushlog
by timo via ssh

modified DECISIONS.md +13 −4

@@ -2520,10 +2520,19 @@
25202520
     a lazy **Lua sequence** returned null instead of mapping over the elements
25212521
     (`orders.x` over `[{"x":1},{"x":2}]` → `[1, 2]`, §10.3.2.5). Python and JS arrays become
25222522
     lists at the boundary and were unaffected.
2523
-  - *Known limits*: the member probe navigates from the **root** binding, so a loop variable
2524
-    or parameter shadowing a root key (`for item in items return item.unit-price` with a root
2525
-    `item`) is probed against the root value; dynamic bases and filter-element keys stay
2526
-    arithmetic — backticks cover all of these.
2523
+  - *Safety rule for shadowed roots* (added after review): the member probe navigates from the
2524
+    **root** binding, which is the wrong value when the path's root is bound by the expression
2525
+    itself — a `for`/`some`/`every` variable, a function parameter, a context-literal key —
2526
+    or when the path sits inside a filter bracket (names there may be element keys). Such
2527
+    paths are never member-probed; the arithmetic reading stands (`for item in items return
2528
+    item.unit-price` with a root `item` that has `unit-price` used to read the *root's*
2529
+    member for every element). The bound-name scan is scope-insensitive on purpose: the
2530
+    over-approximation only ever falls back to arithmetic.
2531
+  - *Backtick content is verbatim*: every character counts, spaces included (`` `a  b` `` ≠
2532
+    `a b`, `` ` a` `` ≠ `a`) — unlike unquoted multi-word names, whose spaces collapse.
2533
+  - *Known limits*: loop elements, parameters, sibling entries and filter elements are not
2534
+    probed (see the safety rule), and dynamic bases (`f(x).a-b`) stay arithmetic —
2535
+    backticks cover all of these.
25272536
 
25282537
 - **Measurements (2026-10-14; criterion medians, `cargo bench -p feel-core --bench names`;
25292538
   feel-pg: `count(feel_eval(…))` over 100 000 rows, best of 5, release build, PG 18.4).**

modified README.md +20 −1

@@ -65,7 +65,26 @@
6565
   syntax, so Camunda expressions run unchanged): one name, decided by the text,
6666
   in every name slot. A `names` option selects `"symbols"` (default) or
6767
   `"quoted"` (backticks only, `a-b` always subtraction — Camunda semantics);
68
-  feel-pg takes it as the `name_resolution` argument (ADR-48).
68
+  feel-pg takes it as the `name_resolution` argument (ADR-48). Inside
69
+  backticks every character counts, spaces included: `` `a  b` `` is the key
70
+  with two spaces, `` ` a` `` the one with a leading space — unlike unquoted
71
+  multi-word names, whose spaces collapse to one.
72
+
73
+  **Which to use?** If you read FEEL like a programming language, write every
74
+  name that contains `- + * / .` (or a keyword) in **backticks** — the meaning
75
+  then comes from the text alone, never from the data, and it runs the same in
76
+  Camunda. Under the spec's own rule (`"symbols"`), spaces do *not* separate:
77
+  with `unit`, `price` and `unit-price` all in the context, both `unit-price`
78
+  and `unit - price` read the key `unit-price`, so adding that key to a row
79
+  silently turns a subtraction into a lookup; `(unit)-(price)` forces the
80
+  subtraction. For data you do not control (external jsonb), `"quoted"` makes
81
+  `-` always mean minus.
82
+
83
+  | context `unit`, `price`, `unit-price` | `"symbols"` | `"quoted"` |
84
+  |---|---|---|
85
+  | `unit-price`, `unit - price` | key `unit-price` | `unit` − `price` |
86
+  | `(unit)-(price)` | `unit` − `price` | `unit` − `price` |
87
+  | `` `unit-price` `` | key `unit-price` | key `unit-price` |
6988
 - **User-defined functions:** FEEL `function(a, b) a + b` closures, and
7089
   host-provided functions — a Python callable, JS function or Lua function passed in
7190
   the context (or an ambient `functions` registry) and invoked from the expression,

modified crates/feel-core/src/lexer.rs +99 −2

@@ -410,6 +410,7 @@
410410
             | Tok::Str(_)
411411
             | Tok::TemporalLit(_)
412412
             | Tok::Name(_)
413
+            | Tok::QuotedName(_)
413414
             | Tok::True
414415
             | Tok::False
415416
             | Tok::Null
@@ -739,6 +740,76 @@
739740
     Some(idxs)
740741
 }
741742
 
743
+/// A plain or backtick-quoted name token's text.
744
+fn name_text(t: &Spanned) -> Option<&str> {
745
+    match t {
746
+        Ok((_, Tok::Name(s) | Tok::QuotedName(s), _)) => Some(s),
747
+        _ => None,
748
+    }
749
+}
750
+
751
+/// Whether input token `i` is exactly `tok` (a unit variant).
752
+fn tok_is(toks: &[Spanned], i: usize, tok: &Tok) -> bool {
753
+    matches!(toks.get(i), Some(Ok((_, t, _))) if t == tok)
754
+}
755
+
756
+/// Names the expression binds **itself** (ADR-48 safety rule): `for`/`some`/
757
+/// `every` variables (`for x in`, `, y in`), function parameters
758
+/// (`function(a, b: number)`) and context-literal keys (`{k: …, j: …}`). A static
759
+/// path rooted at one of them may mean the local binding — a loop element, an
760
+/// argument, a sibling entry — whose value the parser cannot know, so it is
761
+/// never member-probed (the root-scope value of the same name would be the
762
+/// wrong answer). Scope-insensitive on purpose: the over-approximation only
763
+/// ever falls back to the arithmetic reading, which backticks override.
764
+fn locally_bound(toks: &[Spanned]) -> Vec<&str> {
765
+    let mut out = Vec::new();
766
+    let mut i = 0;
767
+    while i < toks.len() {
768
+        if let Some(name) = name_text(&toks[i]) {
769
+            let prev_is = |t: &Tok| i > 0 && tok_is(toks, i - 1, t);
770
+            // `for x in` / `some x in` / `every x in` / `…, y in`.
771
+            let iter_var = tok_is(toks, i + 1, &Tok::In)
772
+                && (prev_is(&Tok::For) || prev_is(&Tok::Some) || prev_is(&Tok::Every) || prev_is(&Tok::Comma));
773
+            // `{k: …}` / `…, k: …` — context keys (and, harmlessly, named args).
774
+            let key = tok_is(toks, i + 1, &Tok::Colon) && (prev_is(&Tok::LBrace) || prev_is(&Tok::Comma));
775
+            if iter_var || key {
776
+                out.push(name);
777
+            }
778
+        }
779
+        // `function(` params `)`: names right after `(` or a depth-0 `,`.
780
+        if tok_is(toks, i, &Tok::Function) && tok_is(toks, i + 1, &Tok::LParen) {
781
+            let mut depth = 0usize;
782
+            let mut j = i + 2;
783
+            let mut expect_name = true;
784
+            while j < toks.len() {
785
+                match &toks[j] {
786
+                    Ok((_, Tok::LParen | Tok::LBracket | Tok::LBrace, _)) => depth += 1,
787
+                    Ok((_, Tok::RParen, _)) if depth == 0 => break,
788
+                    Ok((_, Tok::RParen | Tok::RBracket | Tok::RBrace, _)) => depth = depth.saturating_sub(1),
789
+                    Ok((_, Tok::Comma, _)) if depth == 0 => {
790
+                        expect_name = true;
791
+                        j += 1;
792
+                        continue;
793
+                    }
794
+                    t => {
795
+                        if expect_name {
796
+                            if let Some(n) = name_text(t) {
797
+                                out.push(n);
798
+                            }
799
+                        }
800
+                    }
801
+                }
802
+                expect_name = false;
803
+                j += 1;
804
+            }
805
+            i = j;
806
+            continue;
807
+        }
808
+        i += 1;
809
+    }
810
+    out
811
+}
812
+
742813
 /// Try a run's prefixes longest first (§10.3.1.6), recording every answer in
743814
 /// `trace`; the first in-scope prefix wins as `(units, name)`.
744815
 fn longest_in_scope(
@@ -771,23 +842,49 @@
771842
 /// not turn `x.y-z` into `x.(y-z)` — but, on a *static* path ([`static_path`]),
772843
 /// asks [`crate::ScopeProbe::contains_member`] whether the navigated value has
773844
 /// that key: `applicant.first-name` fuses `first-name` when `applicant` has it.
774
-/// Every answer is appended to `trace`.
845
+/// Never, though, inside a **filter** bracket (`items[detail.a-b > 1]` — names
846
+/// there may be element keys) or when the path's root is **bound by the
847
+/// expression itself** ([`locally_bound`] — `for item in … return item.a-b`):
848
+/// the root-scope value would be the wrong one, so the arithmetic reading
849
+/// stands (backticks override). Every answer is appended to `trace`.
775850
 fn plan(toks: &[Spanned], probe: &dyn crate::ScopeProbe, trace: &mut Trace) -> Vec<Planned> {
776851
     let mut out: Vec<Planned> = Vec::with_capacity(toks.len());
777852
     let mut buf = String::new();
778853
     let may_root = probe.may_bind_special();
854
+    // Open brackets, `true` for a filter (`[` right after a value).
855
+    let mut brackets: Vec<bool> = Vec::new();
856
+    let mut locals: Option<Vec<&str>> = None;
779857
     let mut i = 0;
780858
     while i < toks.len() {
859
+        match &toks[i] {
860
+            Ok((_, Tok::LBracket, _)) => brackets.push(
861
+                i > 0 && toks[i - 1].as_ref().is_ok_and(|(_, t, _)| ends_value(t)),
862
+            ),
863
+            Ok((_, Tok::RBracket, _)) => {
864
+                brackets.pop();
865
+            }
866
+            _ => {}
867
+        }
781868
         let member = after_dot(toks, i);
782869
         let fused = match scan_name_run(toks, i, member) {
783870
             None => None,
784871
             Some((units, seps)) if member => match static_path(&out, toks) {
872
+                Some(_) if brackets.iter().any(|&filter| filter) => None,
785873
                 Some(idxs) => {
786874
                     let path: Vec<&str> = idxs
787875
                         .iter()
788876
                         .map(|&k| planned_name(&out[k], toks).expect("static path element is a name"))
789877
                         .collect();
790
-                    longest_in_scope(&units, &seps, &mut buf, trace, |c| probe.contains_member(&path, c))
878
+                    let local = locals
879
+                        .get_or_insert_with(|| locally_bound(toks))
880
+                        .contains(&path[0]);
881
+                    if local {
882
+                        None
883
+                    } else {
884
+                        longest_in_scope(&units, &seps, &mut buf, trace, |c| {
885
+                            probe.contains_member(&path, c)
886
+                        })
887
+                    }
791888
                 }
792889
                 None => None,
793890
             },

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

@@ -1078,6 +1078,63 @@
10781078
         let ctx = &[("o", ctx_value(&[("a.b", num(1.0)), ("a", ctx_value(&[("b", num(2.0))]))]))];
10791079
         assert_eq!(eval_in("o.a.b", ctx), num(2.0));
10801080
         assert_eq!(eval_in("o.`a.b`", ctx), num(1.0));
1081
+    }
1082
+
1083
+    #[test]
1084
+    fn member_probe_never_uses_a_shadowed_root() {
1085
+        // Each case has a ROOT binding of the path's root name WITH the hyphen
1086
+        // key, while the name actually in play (loop element, parameter,
1087
+        // sibling entry, filter element) has only `net`: the root value must
1088
+        // not decide the parse — the arithmetic reading `….net - income` stands.
1089
+        let shadowed = ctx_value(&[("net-income", num(999.0))]);
1090
+        let local = ctx_value(&[("net", num(10.0))]);
1091
+        let base = |root: &str| {
1092
+            ctx_of(&[
1093
+                (root, shadowed.clone()),
1094
+                ("income", num(1.0)),
1095
+                ("x", local.clone()),
1096
+                ("items", Value::List(vec![local.clone()])),
1097
+                ("rows", Value::List(vec![ctx_value(&[("detail", local.clone())])])),
1098
+            ])
1099
+        };
1100
+        let ev = |src: &str, ctx: &Context| evaluate(src, ctx).unwrap().into_lenient();
1101
+        // Loop variable.
1102
+        assert_eq!(
1103
+            ev("for item in items return item.net-income", &base("item")),
1104
+            list(vec![num(9.0)])
1105
+        );
1106
+        assert_eq!(ev("some item in items satisfies item.net-income = 9", &base("item")), b(true));
1107
+        // Function parameter.
1108
+        assert_eq!(ev("{f: function(p) p.net-income, r: f(x)}.r", &base("p")), num(9.0));
1109
+        // Context-literal key.
1110
+        assert_eq!(ev("{applicant: x, r: applicant.net-income}.r", &base("applicant")), num(9.0));
1111
+        // Inside a filter bracket (`detail` is an element key there).
1112
+        assert_eq!(
1113
+            ev("count(rows[detail.net-income > 5])", &base("detail")),
1114
+            num(1.0)
1115
+        );
1116
+        // The compiled path agrees.
1117
+        let prog = compile("for item in items return item.net-income").unwrap();
1118
+        assert_eq!(prog.evaluate(&base("item")).unwrap().into_lenient(), list(vec![num(9.0)]));
1119
+        // Backticks still reach the member explicitly.
1120
+        let keyed = ctx_of(&[("items", Value::List(vec![ctx_value(&[("net-income", num(3.0))])]))]);
1121
+        assert_eq!(
1122
+            ev("for item in items return item.`net-income`", &keyed),
1123
+            list(vec![num(3.0)])
1124
+        );
1125
+        // A root path that is NOT shadowed is still probed.
1126
+        assert_eq!(ev("item.net-income", &base("item")), num(999.0));
1127
+    }
1128
+
1129
+    #[test]
1130
+    fn backtick_spaces_count() {
1131
+        // Inside backticks every space is part of the name — leading, trailing
1132
+        // and repeated — unlike unquoted multi-word names (one space).
1133
+        assert_eq!(eval_in("` a`", &[(" a", num(1.0))]), num(1.0));
1134
+        assert_eq!(eval_in("`a `", &[("a ", num(2.0))]), num(2.0));
1135
+        assert_eq!(eval_in("`a  b`", &[("a  b", num(3.0)), ("a b", num(4.0))]), num(3.0));
1136
+        assert_eq!(eval_in("a  b", &[("a  b", num(3.0)), ("a b", num(4.0))]), num(4.0));
1137
+        assert_eq!(eval_in("` a`", &[("a", num(5.0))]), Value::Null);
10811138
     }
10821139
 
10831140
     #[test]