Public repository: timo / feel

Reader

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

feat(wrappers): scope-adaptive compile, `names` option, registry contains (ADR-48)

draft feat/name-resolution-v2

feat(wrappers): scope-adaptive compile, `names` option, registry contains (ADR-48)

- py/lua/wasm: `compile` is scope-adaptive (each call follows its context
  and functions registry); one-shot `evaluate` stays a single pinned parse.
- `names="symbols"|"quoted"` on `evaluate`/`evaluate_strict`/`compile`
  (Lua and JS: optional last argument); unknown spellings raise.
- Allocation-free `FunctionRegistry::contains` per wrapper.
- feel-lua fix: selection on a lazy sequence maps over its elements
  (`o.items.x` over `{ {x=1}, {x=2} }` was nil instead of `[1, 2]`).
- Tests: adaptive compile, levels, backticks, nested hyphen members.

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

modified crates/feel-lua/src/lib.rs +80 −36

@@ -33,9 +33,9 @@
3333
 use std::sync::Arc;
3434
 
3535
 use feel_core::{
36
-    compile as core_compile, compile_with_probe as core_compile_with_probe, Args,
36
+    compile_with as core_compile_with, compile_with_probe as core_compile_with_probe, Args,
3737
     CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
38
-    FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value,
38
+    FunctionRegistry, NameResolution, ParseOptions, ScopeProbe, ScopeWithFunctions, Value,
3939
 };
4040
 use mlua::{Lua, Table, Value as LuaValue, Variadic};
4141
 
@@ -53,35 +53,46 @@
5353
 /// Rust integration tests call directly against an embedded VM. It registers
5454
 /// `evaluate`, `evaluate_strict` and `compile` on a fresh table and returns it.
5555
 ///
56
-/// The one-shot `evaluate`/`evaluate_strict` parse with the context as the
57
-/// §10.3.1.6 name oracle (ADR-47): a name like `a-b` resolves to the table key
58
-/// `a-b` when present, and to subtraction otherwise. `compile` (and the userdata
59
-/// it returns) stay probe-free — a compiled program pins no scope.
56
+/// Special-character names (§10.3.1.6): a name like `a-b` resolves to the table
57
+/// key `a-b` when present, and to subtraction otherwise — in the one-shot
58
+/// `evaluate`/`evaluate_strict` and, per call, in the scope-adaptive `compile`
59
+/// userdata (ADR-48). An optional last argument `names` selects the level:
60
+/// `"symbols"` (default) or `"quoted"` (backticks only; `` `a-b` `` always works).
6061
 pub fn build_module(lua: &Lua) -> mlua::Result<Table> {
6162
     let exports = lua.create_table()?;
6263
     exports.set(
6364
         "evaluate",
64
-        lua.create_function(|lua, (expr, context, functions): (String, LuaValue, LuaValue)| {
65
-            // Build the context and registry first: together they are the
66
-            // parse-time name oracle (ADR-47).
67
-            let ctx = context_from_lua(&context)?;
68
-            let registry = registry_from_lua(&functions);
69
-            let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
70
-            run_with_ctx(lua, &compile_with_probe_core(&expr, &scope)?, &ctx, &registry, false)
71
-        })?,
65
+        lua.create_function(
66
+            |lua, (expr, context, functions, names): (String, LuaValue, LuaValue, Option<String>)| {
67
+                // Build the context and registry first: together they are the
68
+                // parse-time name oracle (ADR-47).
69
+                let options = parse_options(names.as_deref())?;
70
+                let ctx = context_from_lua(&context)?;
71
+                let registry = registry_from_lua(&functions);
72
+                let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
73
+                let compiled = compile_with_probe_core(&expr, &scope, &options)?;
74
+                run_with_ctx(lua, &compiled, &ctx, &registry, false)
75
+            },
76
+        )?,
7277
     )?;
7378
     exports.set(
7479
         "evaluate_strict",
75
-        lua.create_function(|lua, (expr, context, functions): (String, LuaValue, LuaValue)| {
76
-            let ctx = context_from_lua(&context)?;
77
-            let registry = registry_from_lua(&functions);
78
-            let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
79
-            run_with_ctx(lua, &compile_with_probe_core(&expr, &scope)?, &ctx, &registry, true)
80
-        })?,
80
+        lua.create_function(
81
+            |lua, (expr, context, functions, names): (String, LuaValue, LuaValue, Option<String>)| {
82
+                let options = parse_options(names.as_deref())?;
83
+                let ctx = context_from_lua(&context)?;
84
+                let registry = registry_from_lua(&functions);
85
+                let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
86
+                let compiled = compile_with_probe_core(&expr, &scope, &options)?;
87
+                run_with_ctx(lua, &compiled, &ctx, &registry, true)
88
+            },
89
+        )?,
8190
     )?;
8291
     exports.set(
8392
         "compile",
84
-        lua.create_function(|_, expr: String| compile_expr(&expr))?,
93
+        lua.create_function(|_, (expr, names): (String, Option<String>)| {
94
+            compile_expr(&expr, &parse_options(names.as_deref())?)
95
+        })?,
8596
     )?;
8697
     Ok(exports)
8798
 }
@@ -97,8 +108,8 @@
97108
 
98109
 /// A parsed FEEL expression, reusable across many evaluations (the `feel.compile`
99110
 /// result). Exposed to Lua as userdata with `:evaluate` / `:evaluate_strict`.
100
-/// Parsed **probe-free** (ADR-47): a name like `a-b` is arithmetic on this path —
101
-/// use the one-shot `feel.evaluate` for scope-dependent name resolution.
111
+/// **Scope-adaptive** (ADR-48): each call resolves special-character names
112
+/// against its own context, with a small cache of per-scope parses.
102113
 struct CompiledExpr {
103114
     inner: CoreCompiled,
104115
 }
@@ -120,23 +131,34 @@
120131
     }
121132
 }
122133
 
123
-/// Parse into the core's reusable form, mapping a parse error to a Lua error.
124
-fn compile_core(expr: &str) -> mlua::Result<CoreCompiled> {
125
-    core_compile(expr).map_err(|e| mlua::Error::RuntimeError(e.to_string()))
126
-}
127
-
128
-/// Parse with the call's scope (context + function registry) as the §10.3.1.6
129
-/// name oracle (ADR-47): special-character name runs (`a-b`) fuse into names
130
-/// exactly when that scope binds them.
131
-fn compile_with_probe_core(expr: &str, probe: &dyn ScopeProbe) -> mlua::Result<CoreCompiled> {
132
-    core_compile_with_probe(expr, probe)
134
+/// The optional `names` argument as [`ParseOptions`] (ADR-48).
135
+fn parse_options(names: Option<&str>) -> mlua::Result<ParseOptions> {
136
+    match names {
137
+        None => Ok(ParseOptions::default()),
138
+        Some(n) => NameResolution::from_name(n).map(ParseOptions::names).ok_or_else(|| {
139
+            mlua::Error::RuntimeError(format!(
140
+                "unknown names {n:?} (expected \"symbols\" or \"quoted\")"
141
+            ))
142
+        }),
143
+    }
144
+}
145
+
146
+/// Parse pinned to the call's scope (context + function registry) as the
147
+/// §10.3.1.6 name oracle (ADR-47) — one parse, one-shot use.
148
+fn compile_with_probe_core(
149
+    expr: &str,
150
+    probe: &dyn ScopeProbe,
151
+    options: &ParseOptions,
152
+) -> mlua::Result<CoreCompiled> {
153
+    core_compile_with_probe(expr, probe, options)
133154
         .map_err(|e| mlua::Error::RuntimeError(e.to_string()))
134155
 }
135156
 
136
-/// Parse into the `feel.compile` userdata wrapper.
137
-fn compile_expr(expr: &str) -> mlua::Result<CompiledExpr> {
157
+/// Parse into the `feel.compile` userdata wrapper (scope-adaptive, ADR-48).
158
+fn compile_expr(expr: &str, options: &ParseOptions) -> mlua::Result<CompiledExpr> {
138159
     Ok(CompiledExpr {
139
-        inner: compile_core(expr)?,
160
+        inner: core_compile_with(expr, options)
161
+            .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?,
140162
     })
141163
 }
142164
 
@@ -254,6 +276,21 @@
254276
 /// `table[key]`, which fires an `__index` metamethod. An absent member (`nil`) or a
255277
 /// raised metamethod is a **value-null**. The returned value is shallow.
256278
 fn lua_get_member(table: &Table, key: &str) -> Value {
279
+    // A sequence is a FEEL list (see `lua_force`): selection maps over its
280
+    // elements (DMN §10.3.2.5) — `[{x:1},{x:2}].x = [1, 2]`. The evaluator does
281
+    // this for an owned `Value::List`, but a lazy sequence arrives as one
282
+    // `Foreign`. A non-table element yields a value-null in its slot.
283
+    let len = table.raw_len();
284
+    if len > 0 {
285
+        return Value::List(
286
+            (1..=len)
287
+                .map(|i| match table.get::<LuaValue>(i as i64) {
288
+                    Ok(LuaValue::Table(el)) if el.raw_len() == 0 => lua_get_member(&el, key),
289
+                    _ => Value::Null,
290
+                })
291
+                .collect(),
292
+        );
293
+    }
257294
     match table.get::<LuaValue>(key) {
258295
         Ok(v) => shallow_convert_lua(&v),
259296
         Err(_) => Value::Null,
@@ -391,6 +428,13 @@
391428
             Ok(LuaValue::Function(f)) => Some(Arc::new(LuaForeignFn { func: f })),
392429
             _ => None,
393430
         }
431
+    }
432
+
433
+    /// The per-candidate scope check (ADR-48): no wrapper `Arc` is built.
434
+    fn contains(&self, name: &str) -> bool {
435
+        self.funcs
436
+            .as_ref()
437
+            .is_some_and(|f| matches!(f.get::<LuaValue>(name), Ok(LuaValue::Function(_))))
394438
     }
395439
 }
396440
 

modified crates/feel-lua/tests/feel.rs +45 −6

@@ -169,20 +169,59 @@
169169
 }
170170
 
171171
 #[test]
172
-fn compile_userdata_is_probe_free() {
173
-    let lua = vm();
174
-    // A compiled program pins no scope (ADR-47): `a-b` stays arithmetic, whatever
175
-    // the later contexts bind.
176
-    let v: Value = lua
172
+fn compile_userdata_is_scope_adaptive() {
173
+    let lua = vm();
174
+    // ADR-48: one compiled program follows each call's context.
175
+    let n: f64 = lua
177176
         .load(r#"local p = feel.compile("a-b"); return p:evaluate({ ["a-b"] = 5 })"#)
178177
         .eval()
179178
         .unwrap();
180
-    assert!(matches!(v, Value::Nil));
179
+    assert_eq!(n, 5.0);
181180
     let n: f64 = lua
182181
         .load(r#"local p = feel.compile("a-b"); return p:evaluate({ a = 7, b = 3 })"#)
183182
         .eval()
184183
         .unwrap();
185184
     assert_eq!(n, 4.0);
185
+}
186
+
187
+#[test]
188
+fn names_levels_backticks_and_members() {
189
+    let lua = vm();
190
+    let n: f64 = lua
191
+        .load(r#"return feel.evaluate("a-b", { a = 7, b = 3, ["a-b"] = 100 }, nil, "quoted")"#)
192
+        .eval()
193
+        .unwrap();
194
+    assert_eq!(n, 4.0);
195
+    let n: f64 = lua
196
+        .load(r#"return feel.compile("a-b", "quoted"):evaluate({ a = 7, b = 3, ["a-b"] = 100 })"#)
197
+        .eval()
198
+        .unwrap();
199
+    assert_eq!(n, 4.0);
200
+    let n: f64 = lua
201
+        .load(r#"return feel.evaluate("`Profit and loss`", { ["Profit and loss"] = 1 })"#)
202
+        .eval()
203
+        .unwrap();
204
+    assert_eq!(n, 1.0);
205
+    let s: String = lua
206
+        .load(r#"return feel.evaluate("applicant.first-name", { applicant = { ["first-name"] = "Ada" } })"#)
207
+        .eval()
208
+        .unwrap();
209
+    assert_eq!(s, "Ada");
210
+    // Selection maps over a sequence (§10.3.2.5) — plain and hyphen members.
211
+    let n: i64 = lua
212
+        .load(r#"return feel.evaluate("o.items.x", { o = { items = { { x = 1 }, { x = 2 } } } })[2]"#)
213
+        .eval()
214
+        .unwrap();
215
+    assert_eq!(n, 2);
216
+    let n: i64 = lua
217
+        .load(r#"return feel.evaluate("orders.unit-price", { orders = { { ["unit-price"] = 3 } } })[1]"#)
218
+        .eval()
219
+        .unwrap();
220
+    assert_eq!(n, 3);
221
+    assert!(lua
222
+        .load(r#"return feel.evaluate("1", {}, nil, "full")"#)
223
+        .eval::<Value>()
224
+        .is_err());
186225
 }
187226
 
188227
 // --------------------------------------------------------------------------- //

modified crates/feel-py/src/lib.rs +56 −26

@@ -30,9 +30,9 @@
3030
 use std::collections::BTreeMap;
3131
 
3232
 use feel_core::{
33
-    compile as core_compile, compile_with_probe as core_compile_with_probe, Args,
33
+    compile_with as core_compile_with, compile_with_probe as core_compile_with_probe, Args,
3434
     CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
35
-    FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value,
35
+    FunctionRegistry, NameResolution, ParseOptions, ScopeProbe, ScopeWithFunctions, Value,
3636
 };
3737
 #[cfg(not(feature = "xpath-regex"))]
3838
 use feel_core::FeelRegex;
@@ -57,15 +57,19 @@
5757
 /// subtraction otherwise. The ambient `functions` registry (ADR-23) counts as
5858
 /// scope too — mirroring `eval_call`, which resolves a call head against
5959
 /// context, built-ins and (third) the registry — so a hyphen-named host
60
-/// function is callable as `my-fn(1)`.
60
+/// function is callable as `my-fn(1)`. `names` selects the level (ADR-48):
61
+/// `"symbols"` (default) or `"quoted"` — backticks only, `a-b` always
62
+/// subtraction (Camunda semantics); `` `a-b` `` works at every level.
6163
 #[pyfunction]
62
-#[pyo3(signature = (expr, context=None, functions=None))]
64
+#[pyo3(signature = (expr, context=None, functions=None, names=None))]
6365
 fn evaluate<'py>(
6466
     py: Python<'py>,
6567
     expr: &str,
6668
     context: Option<&Bound<'py, PyAny>>,
6769
     functions: Option<&Bound<'py, PyAny>>,
70
+    names: Option<&str>,
6871
 ) -> PyResult<Bound<'py, PyAny>> {
72
+    let options = parse_options(names)?;
6973
     // Build the context and the function registry first so both can act as the
7074
     // parse-time name oracle.
7175
     let ctx = context_to_ctx(context)?;
@@ -73,7 +77,7 @@
7377
         funcs: functions.map(|f| f.clone().unbind()),
7478
     };
7579
     let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
76
-    run_with_ctx(py, &compile_with_probe_core(expr, &scope)?, &ctx, &registry, false)
80
+    run_with_ctx(py, &compile_with_probe_core(expr, &scope, &options)?, &ctx, &registry, false)
7781
 }
7882
 
7983
 /// Evaluate a FEEL expression (strict boundary policy): if the result is, or
@@ -81,41 +85,43 @@
8185
 /// of letting it pass silently as `None` (ADR-14). A plain value-null is still
8286
 /// returned as `None`. Scope-dependent names resolve as in [`evaluate`].
8387
 #[pyfunction]
84
-#[pyo3(signature = (expr, context=None, functions=None))]
88
+#[pyo3(signature = (expr, context=None, functions=None, names=None))]
8589
 fn evaluate_strict<'py>(
8690
     py: Python<'py>,
8791
     expr: &str,
8892
     context: Option<&Bound<'py, PyAny>>,
8993
     functions: Option<&Bound<'py, PyAny>>,
94
+    names: Option<&str>,
9095
 ) -> PyResult<Bound<'py, PyAny>> {
96
+    let options = parse_options(names)?;
9197
     let ctx = context_to_ctx(context)?;
9298
     let registry = PyFunctionRegistry {
9399
         funcs: functions.map(|f| f.clone().unbind()),
94100
     };
95101
     let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
96
-    run_with_ctx(py, &compile_with_probe_core(expr, &scope)?, &ctx, &registry, true)
102
+    run_with_ctx(py, &compile_with_probe_core(expr, &scope, &options)?, &ctx, &registry, true)
97103
 }
98104
 
99105
 /// Parse a FEEL expression into a reusable `CompiledExpr` (raises `FeelError` on a
100106
 /// parse error). Does not evaluate.
101107
 ///
102
-/// **Probe-free** (ADR-47): special-character name runs (`a-b`) parse as
103
-/// arithmetic here — a compiled program must not pin one scope. Use the
104
-/// one-shot [`evaluate`] when the context should act as the name scope.
108
+/// **Scope-adaptive** (ADR-48): special-character names (`a-b`,
109
+/// `applicant.first-name`) resolve per evaluation against that call's context
110
+/// and `functions`, exactly like the one-shot [`evaluate`]. `names` as there.
105111
 #[pyfunction]
106
-fn compile(expr: &str) -> PyResult<CompiledExpr> {
112
+#[pyo3(signature = (expr, names=None))]
113
+fn compile(expr: &str, names: Option<&str>) -> PyResult<CompiledExpr> {
114
+    let options = parse_options(names)?;
107115
     Ok(CompiledExpr {
108
-        inner: compile_core(expr)?,
116
+        inner: core_compile_with(expr, &options).map_err(|e| FeelError::new_err(e.to_string()))?,
109117
     })
110118
 }
111119
 
112120
 /// A parsed FEEL expression, reusable across many evaluations: parsing happens
113121
 /// once, each call only maps the context across the boundary.
114122
 ///
115
-/// Parsed **probe-free** (ADR-47): special-character name runs (`a-b`) are
116
-/// arithmetic on this path, whatever the later contexts bind — a compiled
117
-/// program must not pin one scope. Use the one-shot [`evaluate`] for
118
-/// scope-dependent name resolution (§10.3.1.6).
123
+/// **Scope-adaptive** (ADR-48): each evaluation resolves special-character
124
+/// names against its own context, with a small cache of per-scope parses.
119125
 #[pyclass(name = "CompiledExpr", module = "feel")]
120126
 struct CompiledExpr {
121127
     inner: CoreCompiled,
@@ -146,16 +152,27 @@
146152
     }
147153
 }
148154
 
149
-fn compile_core(expr: &str) -> PyResult<CoreCompiled> {
150
-    core_compile(expr).map_err(|e| FeelError::new_err(e.to_string()))
151
-}
152
-
153
-/// Parse with the call's scope (context + function registry) as the §10.3.1.6
154
-/// name oracle (ADR-47): special-character name runs (`a-b`) fuse into names
155
-/// exactly when that scope binds them.
156
-fn compile_with_probe_core(expr: &str, probe: &dyn ScopeProbe) -> PyResult<CoreCompiled> {
157
-    core_compile_with_probe(expr, probe)
158
-        .map_err(|e| FeelError::new_err(e.to_string()))
155
+/// The `names=` argument as [`ParseOptions`] (ADR-48); `None` is the default.
156
+fn parse_options(names: Option<&str>) -> PyResult<ParseOptions> {
157
+    match names {
158
+        None => Ok(ParseOptions::default()),
159
+        Some(n) => NameResolution::from_name(n).map(ParseOptions::names).ok_or_else(|| {
160
+            FeelError::new_err(format!(
161
+                "unknown names={n:?} (expected \"symbols\" or \"quoted\")"
162
+            ))
163
+        }),
164
+    }
165
+}
166
+
167
+/// Parse pinned to the call's scope (context + function registry) as the
168
+/// §10.3.1.6 name oracle (ADR-47): special-character name runs (`a-b`) fuse
169
+/// into names exactly when that scope binds them — one parse, one-shot use.
170
+fn compile_with_probe_core(
171
+    expr: &str,
172
+    probe: &dyn ScopeProbe,
173
+    options: &ParseOptions,
174
+) -> PyResult<CoreCompiled> {
175
+    core_compile_with_probe(expr, probe, options).map_err(|e| FeelError::new_err(e.to_string()))
159176
 }
160177
 
161178
 /// Shared per-call boundary: map the Python context in, evaluate against the host
@@ -448,6 +465,19 @@
448465
             item.is_callable().then(|| {
449466
                 Arc::new(PyForeignFn { obj: item.unbind() }) as Arc<dyn ForeignFunction>
450467
             })
468
+        })
469
+    }
470
+
471
+    /// The per-candidate scope check (ADR-48): no wrapper `Arc` is built.
472
+    fn contains(&self, name: &str) -> bool {
473
+        let Some(funcs) = self.funcs.as_ref() else {
474
+            return false;
475
+        };
476
+        Python::attach(|py| {
477
+            funcs
478
+                .bind(py)
479
+                .get_item(name)
480
+                .is_ok_and(|item| item.is_callable())
451481
         })
452482
     }
453483
 }

modified crates/feel-py/tests/test_feel.py +25 −4

@@ -291,12 +291,33 @@
291291
     assert feel.evaluate("my-fn(2)", {}) is None
292292
 
293293
 
294
-def test_compile_class_is_probe_free():
295
-    # A compiled program pins no scope (ADR-47): `a-b` stays arithmetic, whatever
296
-    # the later contexts bind. Use the one-shot `evaluate` for scope resolution.
294
+def test_compile_class_is_scope_adaptive():
295
+    # ADR-48: one compiled program, both readings — it follows each context.
297296
     prog = feel.compile("a-b")
298
-    assert prog.evaluate({"a-b": 5}) is None
297
+    assert prog.evaluate({"a-b": 5}) == 5
299298
     assert prog.evaluate({"a": 7, "b": 3}) == 4
299
+    # The registry is part of the compiled path's scope too.
300
+    call = feel.compile("my-fn(2)")
301
+    assert call.evaluate({}, functions={"my-fn": lambda x: x * 10}) == 20
302
+    assert call.evaluate({}) is None
303
+
304
+
305
+def test_names_levels_and_backticks():
306
+    ctx = {"a": 7, "b": 3, "a-b": 100}
307
+    assert feel.evaluate("a-b", ctx) == 100
308
+    assert feel.evaluate("a-b", ctx, names="quoted") == 4
309
+    assert feel.compile("a-b", names="quoted").evaluate(ctx) == 4
310
+    assert feel.evaluate("`a-b`", ctx, names="quoted") == 100
311
+    assert feel.evaluate("`Profit and loss`", {"Profit and loss": 1}) == 1
312
+    with pytest.raises(feel.FeelError):
313
+        feel.evaluate("1", {}, names="full")
314
+
315
+
316
+def test_nested_hyphen_members():
317
+    # The member probe navigates lazy host objects (ADR-48).
318
+    assert feel.evaluate("applicant.first-name", {"applicant": {"first-name": "Ada"}}) == "Ada"
319
+    assert feel.evaluate("orders.unit-price", {"orders": [{"unit-price": 2}, {"unit-price": 3}]}) == [2, 3]
320
+    assert feel.evaluate("o.items.x", {"o": {"items": [{"x": 1}, {"x": 2}]}}) == [1, 2]
300321
 
301322
 
302323
 # --- host callables: Python functions invoked from FEEL (ADR-23) ---------- #

modified crates/feel-wasm/smoke.mjs +19 −2

@@ -192,7 +192,7 @@
192192
 // is the in-scope NAME when the object binds it, subtraction otherwise; `a - b`
193193
 // is the same candidate (spaces are not part of the name); `(a)-(b)` is the
194194
 // escape hatch; a hyphen name works as a path base. The compiled class is
195
-// probe-free (a compiled program pins no scope): `a-b` stays arithmetic there.
195
+// scope-adaptive (ADR-48): it follows each call's context.
196196
 const nameCases = [
197197
   ["a-b", { "a-b": 5 }, 5],
198198
   ["a - b", { "a-b": 5 }, 5],
@@ -219,10 +219,27 @@
219219
     ok = false;
220220
   }
221221
 }
222
+// ADR-48: backticks, levels, nested members, list selection over arrays.
223
+const v2Cases = [
224
+  [["`Profit and loss`", { "Profit and loss": 1 }], 1],
225
+  [["a-b", { a: 7, b: 3, "a-b": 100 }, undefined, "quoted"], 4],
226
+  [["`a-b`", { "a-b": 5 }, undefined, "quoted"], 5],
227
+  [["applicant.first-name", { applicant: { "first-name": "Ada" } }], "Ada"],
228
+  [["orders.unit-price", { orders: [{ "unit-price": 2 }, { "unit-price": 3 }] }], [2, 3]],
229
+  [["o.items.x", { o: { items: [{ x: 1 }, { x: 2 }] } }], [1, 2]],
230
+];
231
+for (const [args, expected] of v2Cases) {
232
+  const got = evaluate(...args);
233
+  console.log(`${args[0]} (ADR-48) => ${JSON.stringify(got)}`);
234
+  if (!eq(got, expected)) {
235
+    console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
236
+    ok = false;
237
+  }
238
+}
222239
 {
223240
   const prog2 = compile("a-b");
224241
   const compiledNameCases = [
225
-    [{ "a-b": 5 }, null], // probe-free: subtraction of unbound names, not the key
242
+    [{ "a-b": 5 }, 5], // scope-adaptive (ADR-48): the key, per call
226243
     [{ a: 7, b: 3 }, 4],
227244
   ];
228245
   for (const [ctx, expected] of compiledNameCases) {

modified crates/feel-wasm/src/lib.rs +49 −23

@@ -21,9 +21,9 @@
2121
 use std::sync::Arc;
2222
 
2323
 use feel_core::{
24
-    compile as core_compile, compile_with_probe as core_compile_with_probe, Args,
24
+    compile_with as core_compile_with, compile_with_probe as core_compile_with_probe, Args,
2525
     CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
26
-    FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value,
26
+    FunctionRegistry, NameResolution, ParseOptions, ScopeProbe, ScopeWithFunctions, Value,
2727
 };
2828
 use serde::Serialize;
2929
 use wasm_bindgen::prelude::*;
@@ -39,15 +39,23 @@
3939
 ///
4040
 /// The context **is** the scope for §10.3.1.6 name resolution (ADR-47): a name
4141
 /// like `a-b` resolves to the context binding `a-b` when one exists, and to
42
-/// subtraction otherwise.
42
+/// subtraction otherwise. `names` selects the level (ADR-48): `"symbols"`
43
+/// (default when omitted) or `"quoted"` — backticks only, `a-b` always
44
+/// subtraction (Camunda semantics); `` `a-b` `` works at every level.
4345
 #[wasm_bindgen]
44
-pub fn evaluate(expr: &str, context: JsValue, functions: JsValue) -> Result<JsValue, JsError> {
46
+pub fn evaluate(
47
+    expr: &str,
48
+    context: JsValue,
49
+    functions: JsValue,
50
+    names: Option<String>,
51
+) -> Result<JsValue, JsError> {
4552
     // Build the context and registry first: together they are the parse-time
4653
     // name oracle (ADR-47).
54
+    let options = parse_options(names.as_deref())?;
4755
     let ctx = context_from_js(&context)?;
4856
     let registry = JsFunctionRegistry { funcs: functions };
4957
     let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
50
-    run_with_ctx(&compile_with_probe_core(expr, &scope)?, &ctx, &registry, false)
58
+    run_with_ctx(&compile_with_probe_core(expr, &scope, &options)?, &ctx, &registry, false)
5159
 }
5260
 
5361
 /// Evaluate a FEEL expression (strict boundary policy): if the result is, or
@@ -59,11 +67,13 @@
5967
     expr: &str,
6068
     context: JsValue,
6169
     functions: JsValue,
70
+    names: Option<String>,
6271
 ) -> Result<JsValue, JsError> {
72
+    let options = parse_options(names.as_deref())?;
6373
     let ctx = context_from_js(&context)?;
6474
     let registry = JsFunctionRegistry { funcs: functions };
6575
     let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
66
-    run_with_ctx(&compile_with_probe_core(expr, &scope)?, &ctx, &registry, true)
76
+    run_with_ctx(&compile_with_probe_core(expr, &scope, &options)?, &ctx, &registry, true)
6777
 }
6878
 
6979
 /// A parsed FEEL expression, reusable across many evaluations.
@@ -74,21 +84,21 @@
7484
 /// `FinalizationRegistry`, so the WASM-side memory is reclaimed on GC; calling
7585
 /// `free()` explicitly is an optional escape hatch, not required.
7686
 ///
77
-/// Parsed **probe-free** (ADR-47): special-character name runs (`a-b`) are
78
-/// arithmetic on this path, whatever the later contexts bind — a compiled
79
-/// program must not pin one scope. Use the one-shot [`evaluate`] for
80
-/// scope-dependent name resolution (§10.3.1.6).
87
+/// **Scope-adaptive** (ADR-48): each evaluation resolves special-character
88
+/// names against its own context, with a small cache of per-scope parses.
8189
 #[wasm_bindgen]
8290
 pub struct CompiledExpr {
8391
     inner: CoreCompiled,
8492
 }
8593
 
8694
 /// Parse a FEEL expression into a reusable [`CompiledExpr`] (throws on a parse
87
-/// error). Does not evaluate. Probe-free — see [`CompiledExpr`].
95
+/// error). Does not evaluate. Scope-adaptive — see [`CompiledExpr`]; `names`
96
+/// as for [`evaluate`].
8897
 #[wasm_bindgen]
89
-pub fn compile(expr: &str) -> Result<CompiledExpr, JsError> {
98
+pub fn compile(expr: &str, names: Option<String>) -> Result<CompiledExpr, JsError> {
99
+    let options = parse_options(names.as_deref())?;
90100
     Ok(CompiledExpr {
91
-        inner: compile_core(expr)?,
101
+        inner: core_compile_with(expr, &options).map_err(|e| JsError::new(&e.to_string()))?,
92102
     })
93103
 }
94104
 
@@ -110,16 +120,24 @@
110120
     }
111121
 }
112122
 
113
-fn compile_core(expr: &str) -> Result<CoreCompiled, JsError> {
114
-    core_compile(expr).map_err(|e| JsError::new(&e.to_string()))
115
-}
116
-
117
-/// Parse with the call's scope (context + function registry) as the §10.3.1.6
118
-/// name oracle (ADR-47): special-character name runs (`a-b`) fuse into names
119
-/// exactly when that scope binds them.
120
-fn compile_with_probe_core(expr: &str, probe: &dyn ScopeProbe) -> Result<CoreCompiled, JsError> {
121
-    core_compile_with_probe(expr, probe)
122
-        .map_err(|e| JsError::new(&e.to_string()))
123
+/// The optional `names` argument as [`ParseOptions`] (ADR-48).
124
+fn parse_options(names: Option<&str>) -> Result<ParseOptions, JsError> {
125
+    match names {
126
+        None => Ok(ParseOptions::default()),
127
+        Some(n) => NameResolution::from_name(n).map(ParseOptions::names).ok_or_else(|| {
128
+            JsError::new(&format!("unknown names {n:?} (expected \"symbols\" or \"quoted\")"))
129
+        }),
130
+    }
131
+}
132
+
133
+/// Parse pinned to the call's scope (context + function registry) as the
134
+/// §10.3.1.6 name oracle (ADR-47) — one parse, one-shot use.
135
+fn compile_with_probe_core(
136
+    expr: &str,
137
+    probe: &dyn ScopeProbe,
138
+    options: &ParseOptions,
139
+) -> Result<CoreCompiled, JsError> {
140
+    core_compile_with_probe(expr, probe, options).map_err(|e| JsError::new(&e.to_string()))
123141
 }
124142
 
125143
 /// Shared per-call boundary: map the JS context in (accepting native `Date`
@@ -480,6 +498,14 @@
480498
             None
481499
         }
482500
     }
501
+
502
+    /// The per-candidate scope check (ADR-48): no wrapper `Arc` is built.
503
+    fn contains(&self, name: &str) -> bool {
504
+        !self.funcs.is_undefined()
505
+            && !self.funcs.is_null()
506
+            && js_sys::Reflect::get(&self.funcs, &JsValue::from_str(name))
507
+                .is_ok_and(|item| item.is_function())
508
+    }
483509
 }
484510
 
485511
 // --------------------------------------------------------------------------- //