Public repository: timo / feel

Reader

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

feat(wrappers): probe-aware one-shot evaluation for special-char names

draft feat/special-char-names

feat(wrappers): probe-aware one-shot evaluation for special-char names

The one-shot evaluate/evaluate_strict entry points now build the context
first and parse with it as the section 10.3.1.6 name oracle (ADR-47): a
name like a-b resolves to the context binding when one exists, and to
subtraction otherwise. The compile()/CompiledExpr classes stay
probe-free - a compiled program must not pin one scope - and are
documented as such (use the one-shot evaluate for scope resolution).

- feel-py: evaluate/evaluate_strict via compile_with_probe; run splits
  into run (context mapping) + run_with_ctx. 2 new tests (49 total).
- feel-wasm: same split; smoke.mjs gains the name cases incl. the
  compiled probe-free contrast.
- feel-lua: same split in build_module; 2 new tests (27 total).
Changeset9ea85e0a23f46497e8c50ac3c2ce75da6daecf09
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parents1149ec6ba1b3
Children
Pushlog
by timo via ssh

modified crates/feel-lua/src/lib.rs +38 −13

@@ -33,8 +33,9 @@
3333
 use std::sync::Arc;
3434
 
3535
 use feel_core::{
36
-    compile as core_compile, Args, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign,
37
-    ForeignFunction, ForeignObject, Func, FunctionRegistry, Value,
36
+    compile as core_compile, compile_with_probe as core_compile_with_probe, Args,
37
+    CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
38
+    FunctionRegistry, ScopeProbe, Value,
3839
 };
3940
 use mlua::{Lua, Table, Value as LuaValue, Variadic};
4041
 
@@ -51,23 +52,27 @@
5152
 /// This is the entry the loadable module (`luaopen_feel`) calls, and the one the
5253
 /// Rust integration tests call directly against an embedded VM. It registers
5354
 /// `evaluate`, `evaluate_strict` and `compile` on a fresh table and returns it.
55
+///
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.
5460
 pub fn build_module(lua: &Lua) -> mlua::Result<Table> {
5561
     let exports = lua.create_table()?;
5662
     exports.set(
5763
         "evaluate",
58
-        lua.create_function(
59
-            |lua, (expr, context, functions): (String, LuaValue, LuaValue)| {
60
-                run(lua, &compile_core(&expr)?, context, functions, false)
61
-            },
62
-        )?,
64
+        lua.create_function(|lua, (expr, context, functions): (String, LuaValue, LuaValue)| {
65
+            // Build the context first so it can act as the parse-time name oracle.
66
+            let ctx = context_from_lua(&context)?;
67
+            run_with_ctx(lua, &compile_with_probe_core(&expr, &ctx)?, ctx, functions, false)
68
+        })?,
6369
     )?;
6470
     exports.set(
6571
         "evaluate_strict",
66
-        lua.create_function(
67
-            |lua, (expr, context, functions): (String, LuaValue, LuaValue)| {
68
-                run(lua, &compile_core(&expr)?, context, functions, true)
69
-            },
70
-        )?,
72
+        lua.create_function(|lua, (expr, context, functions): (String, LuaValue, LuaValue)| {
73
+            let ctx = context_from_lua(&context)?;
74
+            run_with_ctx(lua, &compile_with_probe_core(&expr, &ctx)?, ctx, functions, true)
75
+        })?,
7176
     )?;
7277
     exports.set(
7378
         "compile",
@@ -87,6 +92,8 @@
8792
 
8893
 /// A parsed FEEL expression, reusable across many evaluations (the `feel.compile`
8994
 /// result). Exposed to Lua as userdata with `:evaluate` / `:evaluate_strict`.
95
+/// Parsed **probe-free** (ADR-47): a name like `a-b` is arithmetic on this path —
96
+/// use the one-shot `feel.evaluate` for scope-dependent name resolution.
9097
 struct CompiledExpr {
9198
     inner: CoreCompiled,
9299
 }
@@ -113,6 +120,13 @@
113120
     core_compile(expr).map_err(|e| mlua::Error::RuntimeError(e.to_string()))
114121
 }
115122
 
123
+/// Parse with the context as the §10.3.1.6 name oracle (ADR-47): special-character
124
+/// name runs (`a-b`) fuse into names exactly when the context binds them.
125
+fn compile_with_probe_core(expr: &str, probe: &Context) -> mlua::Result<CoreCompiled> {
126
+    core_compile_with_probe(expr, probe as &dyn ScopeProbe)
127
+        .map_err(|e| mlua::Error::RuntimeError(e.to_string()))
128
+}
129
+
116130
 /// Parse into the `feel.compile` userdata wrapper.
117131
 fn compile_expr(expr: &str) -> mlua::Result<CompiledExpr> {
118132
     Ok(CompiledExpr {
@@ -130,7 +144,18 @@
130144
     functions: LuaValue,
131145
     strict: bool,
132146
 ) -> mlua::Result<LuaValue> {
133
-    let ctx = context_from_lua(&context)?;
147
+    run_with_ctx(lua, compiled, context_from_lua(&context)?, functions, strict)
148
+}
149
+
150
+/// [`run`] with the context already built — the one-shot entry points have it
151
+/// in hand first, because it doubles as the parse-time scope probe.
152
+fn run_with_ctx(
153
+    lua: &Lua,
154
+    compiled: &CoreCompiled,
155
+    ctx: Context,
156
+    functions: LuaValue,
157
+    strict: bool,
158
+) -> mlua::Result<LuaValue> {
134159
     // Ambient host functions (ADR-23): a Lua table of `name -> function`, consulted
135160
     // after context bindings and built-ins. A non-table (e.g. `nil`) -> no registry.
136161
     let registry = LuaFunctionRegistry {

modified crates/feel-lua/tests/feel.rs +55 −0

@@ -105,6 +105,61 @@
105105
         .load(r#"return feel.evaluate("if x then")"#)
106106
         .eval::<Value>()
107107
         .is_err());
108
+}
109
+
110
+// --------------------------------------------------------------------------- //
111
+// Special-character names (§10.3.1.6, ADR-47)
112
+// --------------------------------------------------------------------------- //
113
+
114
+#[test]
115
+fn special_char_name_resolves_against_scope() {
116
+    let lua = vm();
117
+    // `a-b` is the in-scope NAME when the table binds it, subtraction otherwise;
118
+    // `a - b` is the same candidate (spaces are not part of the name).
119
+    let n: f64 = lua
120
+        .load(r#"return feel.evaluate("a-b", { ["a-b"] = 5 })"#)
121
+        .eval()
122
+        .unwrap();
123
+    assert_eq!(n, 5.0);
124
+    let n: f64 = lua
125
+        .load(r#"return feel.evaluate("a - b", { ["a-b"] = 5 })"#)
126
+        .eval()
127
+        .unwrap();
128
+    assert_eq!(n, 5.0);
129
+    let n: f64 = lua
130
+        .load(r#"return feel.evaluate("a-b", { a = 7, b = 3 })"#)
131
+        .eval()
132
+        .unwrap();
133
+    assert_eq!(n, 4.0);
134
+    // `(a)-(b)` is the escape hatch: subtraction even when `a-b` is the name.
135
+    let n: f64 = lua
136
+        .load(r#"return feel.evaluate("(a)-(b)", { a = 7, b = 3, ["a-b"] = 100 })"#)
137
+        .eval()
138
+        .unwrap();
139
+    assert_eq!(n, 4.0);
140
+    // A hyphen name as a path base: `x-y.hour` fuses `x-y`, `.hour` stays a member.
141
+    let n: i64 = lua
142
+        .load(r#"return feel.evaluate("x-y.hour", { ["x-y"] = { hour = 3 } })"#)
143
+        .eval()
144
+        .unwrap();
145
+    assert_eq!(n, 3);
146
+}
147
+
148
+#[test]
149
+fn compile_userdata_is_probe_free() {
150
+    let lua = vm();
151
+    // A compiled program pins no scope (ADR-47): `a-b` stays arithmetic, whatever
152
+    // the later contexts bind.
153
+    let v: Value = lua
154
+        .load(r#"local p = feel.compile("a-b"); return p:evaluate({ ["a-b"] = 5 })"#)
155
+        .eval()
156
+        .unwrap();
157
+    assert!(matches!(v, Value::Nil));
158
+    let n: f64 = lua
159
+        .load(r#"local p = feel.compile("a-b"); return p:evaluate({ a = 7, b = 3 })"#)
160
+        .eval()
161
+        .unwrap();
162
+    assert_eq!(n, 4.0);
108163
 }
109164
 
110165
 // --------------------------------------------------------------------------- //

modified crates/feel-py/src/lib.rs +41 −6

@@ -30,8 +30,9 @@
3030
 use std::collections::BTreeMap;
3131
 
3232
 use feel_core::{
33
-    compile as core_compile, Args, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign,
34
-    ForeignFunction, ForeignObject, Func, FunctionRegistry, Value,
33
+    compile as core_compile, compile_with_probe as core_compile_with_probe, Args,
34
+    CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
35
+    FunctionRegistry, ScopeProbe, Value,
3536
 };
3637
 #[cfg(not(feature = "xpath-regex"))]
3738
 use feel_core::FeelRegex;
@@ -50,6 +51,10 @@
5051
 /// `context` is a native Python value (e.g. a `dict`); `None` is an empty context.
5152
 /// A null arising from a type/domain error is returned as `None`; see
5253
 /// `evaluate_strict` to raise instead.
54
+///
55
+/// The context **is** the scope for §10.3.1.6 name resolution (ADR-47): a name
56
+/// like `a-b` resolves to the context binding `a-b` when one exists, and to
57
+/// subtraction otherwise.
5358
 #[pyfunction]
5459
 #[pyo3(signature = (expr, context=None, functions=None))]
5560
 fn evaluate<'py>(
@@ -58,13 +63,15 @@
5863
     context: Option<&Bound<'py, PyAny>>,
5964
     functions: Option<&Bound<'py, PyAny>>,
6065
 ) -> PyResult<Bound<'py, PyAny>> {
61
-    run(py, &compile_core(expr)?, context, functions, false)
66
+    // Build the context first so it can act as the parse-time name oracle.
67
+    let ctx = context_to_ctx(context)?;
68
+    run_with_ctx(py, &compile_with_probe_core(expr, &ctx)?, ctx, functions, false)
6269
 }
6370
 
6471
 /// Evaluate a FEEL expression (strict boundary policy): if the result is, or
6572
 /// contains, a null that arose from a type/domain error, raise `FeelError` instead
6673
 /// of letting it pass silently as `None` (ADR-14). A plain value-null is still
67
-/// returned as `None`.
74
+/// returned as `None`. Scope-dependent names resolve as in [`evaluate`].
6875
 #[pyfunction]
6976
 #[pyo3(signature = (expr, context=None, functions=None))]
7077
 fn evaluate_strict<'py>(
@@ -73,11 +80,16 @@
7380
     context: Option<&Bound<'py, PyAny>>,
7481
     functions: Option<&Bound<'py, PyAny>>,
7582
 ) -> PyResult<Bound<'py, PyAny>> {
76
-    run(py, &compile_core(expr)?, context, functions, true)
83
+    let ctx = context_to_ctx(context)?;
84
+    run_with_ctx(py, &compile_with_probe_core(expr, &ctx)?, ctx, functions, true)
7785
 }
7886
 
7987
 /// Parse a FEEL expression into a reusable `CompiledExpr` (raises `FeelError` on a
8088
 /// parse error). Does not evaluate.
89
+///
90
+/// **Probe-free** (ADR-47): special-character name runs (`a-b`) parse as
91
+/// arithmetic here — a compiled program must not pin one scope. Use the
92
+/// one-shot [`evaluate`] when the context should act as the name scope.
8193
 #[pyfunction]
8294
 fn compile(expr: &str) -> PyResult<CompiledExpr> {
8395
     Ok(CompiledExpr {
@@ -87,6 +99,11 @@
8799
 
88100
 /// A parsed FEEL expression, reusable across many evaluations: parsing happens
89101
 /// once, each call only maps the context across the boundary.
102
+///
103
+/// Parsed **probe-free** (ADR-47): special-character name runs (`a-b`) are
104
+/// arithmetic on this path, whatever the later contexts bind — a compiled
105
+/// program must not pin one scope. Use the one-shot [`evaluate`] for
106
+/// scope-dependent name resolution (§10.3.1.6).
90107
 #[pyclass(name = "CompiledExpr", module = "feel")]
91108
 struct CompiledExpr {
92109
     inner: CoreCompiled,
@@ -121,6 +138,13 @@
121138
     core_compile(expr).map_err(|e| FeelError::new_err(e.to_string()))
122139
 }
123140
 
141
+/// Parse with the context as the §10.3.1.6 name oracle (ADR-47): special-character
142
+/// name runs (`a-b`) fuse into names exactly when the context binds them.
143
+fn compile_with_probe_core(expr: &str, probe: &Context) -> PyResult<CoreCompiled> {
144
+    core_compile_with_probe(expr, probe as &dyn ScopeProbe)
145
+        .map_err(|e| FeelError::new_err(e.to_string()))
146
+}
147
+
124148
 /// Shared per-call boundary: map the Python context in, evaluate against the host
125149
 /// regex provider and the system clock, optionally surface error-nulls strictly,
126150
 /// map the result back out.
@@ -131,7 +155,18 @@
131155
     functions: Option<&Bound<'py, PyAny>>,
132156
     strict: bool,
133157
 ) -> PyResult<Bound<'py, PyAny>> {
134
-    let ctx = context_to_ctx(context)?;
158
+    run_with_ctx(py, compiled, context_to_ctx(context)?, functions, strict)
159
+}
160
+
161
+/// [`run`] with the context already built — the one-shot entry points have it
162
+/// in hand first, because it doubles as the parse-time scope probe.
163
+fn run_with_ctx<'py>(
164
+    py: Python<'py>,
165
+    compiled: &CoreCompiled,
166
+    ctx: Context,
167
+    functions: Option<&Bound<'py, PyAny>>,
168
+    strict: bool,
169
+) -> PyResult<Bound<'py, PyAny>> {
135170
     let now = now_zoned();
136171
     // Ambient host functions (ADR-23): a `name -> callable` mapping, consulted after
137172
     // context bindings and built-ins. Absent -> an empty registry (no-op).

modified crates/feel-py/tests/test_feel.py +22 −0

@@ -264,6 +264,28 @@
264264
     prog = feel.compile("a + 1")
265265
     assert prog.evaluate({"a": 1}) == 2
266266
     assert prog.evaluate({"a": 41}) == 42
267
+
268
+
269
+# --- special-character names (§10.3.1.6, ADR-47) --------------------------- #
270
+
271
+def test_special_char_name_resolves_against_scope():
272
+    # `a-b` is the in-scope NAME when the dict binds it, subtraction otherwise;
273
+    # `a - b` is the same candidate (spaces are not part of the name).
274
+    assert feel.evaluate("a-b", {"a-b": 5}) == 5
275
+    assert feel.evaluate("a - b", {"a-b": 5}) == 5
276
+    assert feel.evaluate("a-b", {"a": 7, "b": 3}) == 4
277
+    # `(a)-(b)` is the escape hatch: subtraction even when `a-b` is the name.
278
+    assert feel.evaluate("(a)-(b)", {"a": 7, "b": 3, "a-b": 100}) == 4
279
+    # A hyphen name as a path base: `x-y.hour` fuses `x-y`, `.hour` stays a member.
280
+    assert feel.evaluate("x-y.hour", {"x-y": {"hour": 3}}) == 3
281
+
282
+
283
+def test_compile_class_is_probe_free():
284
+    # A compiled program pins no scope (ADR-47): `a-b` stays arithmetic, whatever
285
+    # the later contexts bind. Use the one-shot `evaluate` for scope resolution.
286
+    prog = feel.compile("a-b")
287
+    assert prog.evaluate({"a-b": 5}) is None
288
+    assert prog.evaluate({"a": 7, "b": 3}) == 4
267289
 
268290
 
269291
 # --- host callables: Python functions invoked from FEEL (ADR-23) ---------- #

modified crates/feel-wasm/smoke.mjs +36 −0

@@ -188,6 +188,42 @@
188188
 }
189189
 prog.free();
190190
 
191
+// Special-character names (§10.3.1.6, ADR-47): the context is the scope. `a-b`
192
+// is the in-scope NAME when the object binds it, subtraction otherwise; `a - b`
193
+// is the same candidate (spaces are not part of the name); `(a)-(b)` is the
194
+// 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.
196
+const nameCases = [
197
+  ["a-b", { "a-b": 5 }, 5],
198
+  ["a - b", { "a-b": 5 }, 5],
199
+  ["a-b", { a: 7, b: 3 }, 4],
200
+  ["(a)-(b)", { a: 7, b: 3, "a-b": 100 }, 4],
201
+  ["x-y.hour", { "x-y": { hour: 3 } }, 3],
202
+];
203
+for (const [expr, ctx, expected] of nameCases) {
204
+  const got = evaluate(expr, ctx);
205
+  console.log(`${expr} (special-char name) => ${JSON.stringify(got)}`);
206
+  if (!eq(got, expected)) {
207
+    console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
208
+    ok = false;
209
+  }
210
+}
211
+{
212
+  const prog2 = compile("a-b");
213
+  const compiledNameCases = [
214
+    [{ "a-b": 5 }, null], // probe-free: subtraction of unbound names, not the key
215
+    [{ a: 7, b: 3 }, 4],
216
+  ];
217
+  for (const [ctx, expected] of compiledNameCases) {
218
+    const got = prog2.evaluate(ctx);
219
+    if (!eq(got, expected)) {
220
+      console.error(`FAIL: compiled "a-b" expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
221
+      ok = false;
222
+    }
223
+  }
224
+  prog2.free();
225
+}
226
+
191227
 // Host callables (ADR-23): a JS function in the context is a FEEL function the
192228
 // expression can invoke. Positional FEEL args -> positional JS args; named FEEL
193229
 // args -> a single trailing options object (JS has no keyword arguments).

modified crates/feel-wasm/src/lib.rs +34 −9

@@ -21,8 +21,9 @@
2121
 use std::sync::Arc;
2222
 
2323
 use feel_core::{
24
-    compile as core_compile, Args, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign,
25
-    ForeignFunction, ForeignObject, Func, FunctionRegistry, Value,
24
+    compile as core_compile, compile_with_probe as core_compile_with_probe, Args,
25
+    CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
26
+    FunctionRegistry, ScopeProbe, Value,
2627
 };
2728
 use serde::Serialize;
2829
 use wasm_bindgen::prelude::*;
@@ -35,22 +36,29 @@
3536
 /// errors are thrown as JS exceptions. A null arising from a type/domain error is
3637
 /// returned as plain `null` (the spec-shaped result); see `evaluate_strict` to
3738
 /// surface such errors as a thrown exception instead.
39
+///
40
+/// The context **is** the scope for §10.3.1.6 name resolution (ADR-47): a name
41
+/// like `a-b` resolves to the context binding `a-b` when one exists, and to
42
+/// subtraction otherwise.
3843
 #[wasm_bindgen]
3944
 pub fn evaluate(expr: &str, context: JsValue, functions: JsValue) -> Result<JsValue, JsError> {
40
-    run(&compile_core(expr)?, context, functions, false)
45
+    // Build the context first so it can act as the parse-time name oracle.
46
+    let ctx = context_from_js(&context)?;
47
+    run_with_ctx(&compile_with_probe_core(expr, &ctx)?, ctx, functions, false)
4148
 }
4249
 
4350
 /// Evaluate a FEEL expression (strict boundary policy): if the result is, or
4451
 /// contains, a null that arose from a type/domain error, throw instead of letting
4552
 /// the error pass silently as `null` (ADR-14). A plain (value) null is still
46
-/// returned as `null`.
53
+/// returned as `null`. Scope-dependent names resolve as in [`evaluate`].
4754
 #[wasm_bindgen]
4855
 pub fn evaluate_strict(
4956
     expr: &str,
5057
     context: JsValue,
5158
     functions: JsValue,
5259
 ) -> Result<JsValue, JsError> {
53
-    run(&compile_core(expr)?, context, functions, true)
60
+    let ctx = context_from_js(&context)?;
61
+    run_with_ctx(&compile_with_probe_core(expr, &ctx)?, ctx, functions, true)
5462
 }
5563
 
5664
 /// A parsed FEEL expression, reusable across many evaluations.
@@ -60,13 +68,18 @@
6068
 /// wasm-bindgen exposes a `free()` method and registers instances with a
6169
 /// `FinalizationRegistry`, so the WASM-side memory is reclaimed on GC; calling
6270
 /// `free()` explicitly is an optional escape hatch, not required.
71
+///
72
+/// Parsed **probe-free** (ADR-47): special-character name runs (`a-b`) are
73
+/// arithmetic on this path, whatever the later contexts bind — a compiled
74
+/// program must not pin one scope. Use the one-shot [`evaluate`] for
75
+/// scope-dependent name resolution (§10.3.1.6).
6376
 #[wasm_bindgen]
6477
 pub struct CompiledExpr {
6578
     inner: CoreCompiled,
6679
 }
6780
 
6881
 /// Parse a FEEL expression into a reusable [`CompiledExpr`] (throws on a parse
69
-/// error). Does not evaluate.
82
+/// error). Does not evaluate. Probe-free — see [`CompiledExpr`].
7083
 #[wasm_bindgen]
7184
 pub fn compile(expr: &str) -> Result<CompiledExpr, JsError> {
7285
     Ok(CompiledExpr {
@@ -96,17 +109,29 @@
96109
     core_compile(expr).map_err(|e| JsError::new(&e.to_string()))
97110
 }
98111
 
112
+/// Parse with the context as the §10.3.1.6 name oracle (ADR-47): special-character
113
+/// name runs (`a-b`) fuse into names exactly when the context binds them.
114
+fn compile_with_probe_core(expr: &str, probe: &Context) -> Result<CoreCompiled, JsError> {
115
+    core_compile_with_probe(expr, probe as &dyn ScopeProbe)
116
+        .map_err(|e| JsError::new(&e.to_string()))
117
+}
118
+
99119
 /// Shared per-call boundary: map the JS context in (accepting native `Date`
100120
 /// objects), evaluate the compiled program against the host regex provider and
101121
 /// the `Date.now()` instant, optionally surface error-nulls strictly, map the
102122
 /// result back out (date/date-and-time as native `Date` objects).
103
-fn run(
123
+fn run(compiled: &CoreCompiled, context: JsValue, functions: JsValue, strict: bool) -> Result<JsValue, JsError> {
124
+    run_with_ctx(compiled, context_from_js(&context)?, functions, strict)
125
+}
126
+
127
+/// [`run`] with the context already built — the one-shot entry points have it
128
+/// in hand first, because it doubles as the parse-time scope probe.
129
+fn run_with_ctx(
104130
     compiled: &CoreCompiled,
105
-    context: JsValue,
131
+    ctx: Context,
106132
     functions: JsValue,
107133
     strict: bool,
108134
 ) -> Result<JsValue, JsError> {
109
-    let ctx = context_from_js(&context)?;
110135
     // Ambient host functions (ADR-23): a JS object of `name -> function`, consulted
111136
     // after context bindings and built-ins. `undefined`/`null` -> no-op registry.
112137
     let registry = JsFunctionRegistry { funcs: functions };