Public repository: timo / feel

Reader

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

feat(wrappers): host-function registry joins the parse-time scope probe

draft feat/special-char-names

feat(wrappers): host-function registry joins the parse-time scope probe

A call head resolves against context, built-ins and — third — the ambient
`functions` registry (ADR-23, `eval_call`), so the name oracle must see the
registry too. New `feel_core::ScopeWithFunctions { context, functions }`;
the one-shot `evaluate`/`evaluate_strict` in feel-py, feel-lua and
feel-wasm build context + registry first and probe both, making a
hyphen-named host function callable as `my-fn(2)`. Tests per wrapper,
plus the `x.y-z` member case.

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

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

@@ -103,6 +103,28 @@
103103
         // name (a first-class function value, ADR-36), then null — the probe asks
104104
         // about the first two.
105105
         self.get(name).is_some() || crate::builtins::is_builtin(name)
106
+    }
107
+}
108
+
109
+/// A [`Context`] plus an ambient [`FunctionRegistry`] (ADR-23) as one parse-time
110
+/// scope (ADR-47): a call head resolves against context, built-ins and — third —
111
+/// the registry (`eval_call`), so a hyphen-named host function (`my-fn(1)`) must
112
+/// be in scope for the fusion too. The wrappers' one-shot `evaluate` parses
113
+/// against this when a `functions` registry is supplied.
114
+///
115
+/// Slightly wider than `Expr::Var` (which never consults the registry): a bare,
116
+/// uncalled `my-fn` fuses to a name that evaluates to null — the same null the
117
+/// arithmetic reading `my - fn` would give.
118
+pub struct ScopeWithFunctions<'a> {
119
+    /// The root-level bindings.
120
+    pub context: &'a Context,
121
+    /// The ambient host functions.
122
+    pub functions: &'a dyn FunctionRegistry,
123
+}
124
+
125
+impl ScopeProbe for ScopeWithFunctions<'_> {
126
+    fn contains(&self, name: &str) -> bool {
127
+        self.context.contains(name) || self.functions.get(name).is_some()
106128
     }
107129
 }
108130
 

modified crates/feel-lua/src/lib.rs +33 −22

@@ -35,7 +35,7 @@
3535
 use feel_core::{
3636
     compile as core_compile, compile_with_probe as core_compile_with_probe, Args,
3737
     CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
38
-    FunctionRegistry, ScopeProbe, Value,
38
+    FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value,
3939
 };
4040
 use mlua::{Lua, Table, Value as LuaValue, Variadic};
4141
 
@@ -62,16 +62,21 @@
6262
     exports.set(
6363
         "evaluate",
6464
         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.
65
+            // Build the context and registry first: together they are the
66
+            // parse-time name oracle (ADR-47).
6667
             let ctx = context_from_lua(&context)?;
67
-            run_with_ctx(lua, &compile_with_probe_core(&expr, &ctx)?, ctx, functions, false)
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)
6871
         })?,
6972
     )?;
7073
     exports.set(
7174
         "evaluate_strict",
7275
         lua.create_function(|lua, (expr, context, functions): (String, LuaValue, LuaValue)| {
7376
             let ctx = context_from_lua(&context)?;
74
-            run_with_ctx(lua, &compile_with_probe_core(&expr, &ctx)?, ctx, functions, true)
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)
7580
         })?,
7681
     )?;
7782
     exports.set(
@@ -120,10 +125,11 @@
120125
     core_compile(expr).map_err(|e| mlua::Error::RuntimeError(e.to_string()))
121126
 }
122127
 
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)
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)
127133
         .map_err(|e| mlua::Error::RuntimeError(e.to_string()))
128134
 }
129135
 
@@ -144,26 +150,31 @@
144150
     functions: LuaValue,
145151
     strict: bool,
146152
 ) -> mlua::Result<LuaValue> {
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.
153
+    let registry = registry_from_lua(&functions);
154
+    run_with_ctx(lua, compiled, &context_from_lua(&context)?, &registry, strict)
155
+}
156
+
157
+/// Ambient host functions (ADR-23): a Lua table of `name -> function`, consulted
158
+/// after context bindings and built-ins. A non-table (e.g. `nil`) -> no registry.
159
+fn registry_from_lua(functions: &LuaValue) -> LuaFunctionRegistry {
160
+    LuaFunctionRegistry {
161
+        funcs: table_or_none(functions),
162
+    }
163
+}
164
+
165
+/// [`run`] with the context and registry already built — the one-shot entry
166
+/// points have them in hand first, because together they are the parse-time
167
+/// scope probe.
152168
 fn run_with_ctx(
153169
     lua: &Lua,
154170
     compiled: &CoreCompiled,
155
-    ctx: Context,
156
-    functions: LuaValue,
171
+    ctx: &Context,
172
+    registry: &LuaFunctionRegistry,
157173
     strict: bool,
158174
 ) -> mlua::Result<LuaValue> {
159
-    // Ambient host functions (ADR-23): a Lua table of `name -> function`, consulted
160
-    // after context bindings and built-ins. A non-table (e.g. `nil`) -> no registry.
161
-    let registry = LuaFunctionRegistry {
162
-        funcs: table_or_none(&functions),
163
-    };
164
-    let env = EvalEnv::with_functions(&REGEX, now_zoned(), &registry);
175
+    let env = EvalEnv::with_functions(&REGEX, now_zoned(), registry);
165176
     let value = compiled
166
-        .evaluate_with_env(&ctx, &env)
177
+        .evaluate_with_env(ctx, &env)
167178
         .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?;
168179
     if strict && value.contains_error() {
169180
         return Err(mlua::Error::RuntimeError(

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

@@ -143,6 +143,29 @@
143143
         .eval()
144144
         .unwrap();
145145
     assert_eq!(n, 3);
146
+    // A member word never fuses against the root scope: `x.y-z` is (x.y) - z.
147
+    let n: i64 = lua
148
+        .load(r#"return feel.evaluate("x.y-z", { x = { y = 10 }, z = 3, ["y-z"] = 1 })"#)
149
+        .eval()
150
+        .unwrap();
151
+    assert_eq!(n, 7);
152
+}
153
+
154
+#[test]
155
+fn special_char_name_resolves_host_function_from_registry() {
156
+    let lua = vm();
157
+    // The ambient `functions` table is part of the parse-time scope (ADR-47): a
158
+    // hyphen-named host function is callable.
159
+    let n: i64 = lua
160
+        .load(r#"return feel.evaluate("my-fn(2)", {}, { ["my-fn"] = function(x) return x * 10 end })"#)
161
+        .eval()
162
+        .unwrap();
163
+    assert_eq!(n, 20);
164
+    let v: Value = lua
165
+        .load(r#"return feel.evaluate("my-fn(2)", {})"#)
166
+        .eval()
167
+        .unwrap();
168
+    assert!(matches!(v, Value::Nil));
146169
 }
147170
 
148171
 #[test]

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

@@ -32,7 +32,7 @@
3232
 use feel_core::{
3333
     compile as core_compile, compile_with_probe as core_compile_with_probe, Args,
3434
     CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
35
-    FunctionRegistry, ScopeProbe, Value,
35
+    FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value,
3636
 };
3737
 #[cfg(not(feature = "xpath-regex"))]
3838
 use feel_core::FeelRegex;
@@ -54,7 +54,10 @@
5454
 ///
5555
 /// The context **is** the scope for §10.3.1.6 name resolution (ADR-47): a name
5656
 /// like `a-b` resolves to the context binding `a-b` when one exists, and to
57
-/// subtraction otherwise.
57
+/// subtraction otherwise. The ambient `functions` registry (ADR-23) counts as
58
+/// scope too — mirroring `eval_call`, which resolves a call head against
59
+/// context, built-ins and (third) the registry — so a hyphen-named host
60
+/// function is callable as `my-fn(1)`.
5861
 #[pyfunction]
5962
 #[pyo3(signature = (expr, context=None, functions=None))]
6063
 fn evaluate<'py>(
@@ -63,9 +66,14 @@
6366
     context: Option<&Bound<'py, PyAny>>,
6467
     functions: Option<&Bound<'py, PyAny>>,
6568
 ) -> PyResult<Bound<'py, PyAny>> {
66
-    // Build the context first so it can act as the parse-time name oracle.
69
+    // Build the context and the function registry first so both can act as the
70
+    // parse-time name oracle.
6771
     let ctx = context_to_ctx(context)?;
68
-    run_with_ctx(py, &compile_with_probe_core(expr, &ctx)?, ctx, functions, false)
72
+    let registry = PyFunctionRegistry {
73
+        funcs: functions.map(|f| f.clone().unbind()),
74
+    };
75
+    let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
76
+    run_with_ctx(py, &compile_with_probe_core(expr, &scope)?, &ctx, &registry, false)
6977
 }
7078
 
7179
 /// Evaluate a FEEL expression (strict boundary policy): if the result is, or
@@ -81,7 +89,11 @@
8189
     functions: Option<&Bound<'py, PyAny>>,
8290
 ) -> PyResult<Bound<'py, PyAny>> {
8391
     let ctx = context_to_ctx(context)?;
84
-    run_with_ctx(py, &compile_with_probe_core(expr, &ctx)?, ctx, functions, true)
92
+    let registry = PyFunctionRegistry {
93
+        funcs: functions.map(|f| f.clone().unbind()),
94
+    };
95
+    let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
96
+    run_with_ctx(py, &compile_with_probe_core(expr, &scope)?, &ctx, &registry, true)
8597
 }
8698
 
8799
 /// Parse a FEEL expression into a reusable `CompiledExpr` (raises `FeelError` on a
@@ -138,10 +150,11 @@
138150
     core_compile(expr).map_err(|e| FeelError::new_err(e.to_string()))
139151
 }
140152
 
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)
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)
145158
         .map_err(|e| FeelError::new_err(e.to_string()))
146159
 }
147160
 
@@ -155,24 +168,25 @@
155168
     functions: Option<&Bound<'py, PyAny>>,
156169
     strict: bool,
157170
 ) -> PyResult<Bound<'py, PyAny>> {
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>> {
170
-    let now = now_zoned();
171171
     // Ambient host functions (ADR-23): a `name -> callable` mapping, consulted after
172172
     // context bindings and built-ins. Absent -> an empty registry (no-op).
173173
     let registry = PyFunctionRegistry {
174174
         funcs: functions.map(|f| f.clone().unbind()),
175175
     };
176
+    run_with_ctx(py, compiled, &context_to_ctx(context)?, &registry, strict)
177
+}
178
+
179
+/// [`run`] with the context and registry already built — the one-shot entry
180
+/// points have them in hand first, because together they are the parse-time
181
+/// scope probe.
182
+fn run_with_ctx<'py>(
183
+    py: Python<'py>,
184
+    compiled: &CoreCompiled,
185
+    ctx: &Context,
186
+    registry: &PyFunctionRegistry,
187
+    strict: bool,
188
+) -> PyResult<Bound<'py, PyAny>> {
189
+    let now = now_zoned();
176190
 
177191
     // With the default Python `re` provider the regex builtins call back into
178192
     // Python, so the GIL must be held for the whole evaluation. The `xpath-regex`
@@ -181,16 +195,16 @@
181195
     #[cfg(not(feature = "xpath-regex"))]
182196
     let value = {
183197
         let regex = PyRegex { py };
184
-        let env = EvalEnv::with_functions(&regex, now, &registry);
198
+        let env = EvalEnv::with_functions(&regex, now, registry);
185199
         compiled
186
-            .evaluate_with_env(&ctx, &env)
200
+            .evaluate_with_env(ctx, &env)
187201
             .map_err(|e| FeelError::new_err(e.to_string()))?
188202
     };
189203
     #[cfg(feature = "xpath-regex")]
190204
     let value = {
191
-        let env = EvalEnv::with_functions(&feel_core::RustRegex, now, &registry);
205
+        let env = EvalEnv::with_functions(&feel_core::RustRegex, now, registry);
192206
         compiled
193
-            .evaluate_with_env(&ctx, &env)
207
+            .evaluate_with_env(ctx, &env)
194208
             .map_err(|e| FeelError::new_err(e.to_string()))?
195209
     };
196210
 

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

@@ -278,6 +278,17 @@
278278
     assert feel.evaluate("(a)-(b)", {"a": 7, "b": 3, "a-b": 100}) == 4
279279
     # A hyphen name as a path base: `x-y.hour` fuses `x-y`, `.hour` stays a member.
280280
     assert feel.evaluate("x-y.hour", {"x-y": {"hour": 3}}) == 3
281
+    # A member word never fuses against the root scope: `x.y-z` is (x.y) - z.
282
+    assert feel.evaluate("x.y-z", {"x": {"y": 10}, "z": 3, "y-z": 1}) == 7
283
+
284
+
285
+def test_special_char_name_resolves_host_function_from_registry():
286
+    # The ambient `functions` registry is part of the parse-time scope: a call
287
+    # head resolves against it (third, after context and built-ins), so a
288
+    # hyphen-named host function is callable (ADR-47).
289
+    assert feel.evaluate("my-fn(2)", {}, functions={"my-fn": lambda x: x * 10}) == 20
290
+    # Without the registry entry the run stays arithmetic (`my - fn(2)` -> null).
291
+    assert feel.evaluate("my-fn(2)", {}) is None
281292
 
282293
 
283294
 def test_compile_class_is_probe_free():

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

@@ -199,12 +199,23 @@
199199
   ["a-b", { a: 7, b: 3 }, 4],
200200
   ["(a)-(b)", { a: 7, b: 3, "a-b": 100 }, 4],
201201
   ["x-y.hour", { "x-y": { hour: 3 } }, 3],
202
+  // A member word never fuses against the root scope: `x.y-z` is (x.y) - z.
203
+  ["x.y-z", { x: { y: 10 }, z: 3, "y-z": 1 }, 7],
202204
 ];
203205
 for (const [expr, ctx, expected] of nameCases) {
204206
   const got = evaluate(expr, ctx);
205207
   console.log(`${expr} (special-char name) => ${JSON.stringify(got)}`);
206208
   if (!eq(got, expected)) {
207209
     console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
210
+    ok = false;
211
+  }
212
+}
213
+{
214
+  // The ambient `functions` registry is part of the parse-time scope: a
215
+  // hyphen-named host function is callable.
216
+  const got = evaluate("my-fn(2)", {}, { "my-fn": (x) => x * 10 });
217
+  if (!eq(got, 20)) {
218
+    console.error(`FAIL: my-fn(2) via registry expected 20, got ${JSON.stringify(got)}`);
208219
     ok = false;
209220
   }
210221
 }

modified crates/feel-wasm/src/lib.rs +28 −21

@@ -23,7 +23,7 @@
2323
 use feel_core::{
2424
     compile as core_compile, compile_with_probe as core_compile_with_probe, Args,
2525
     CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
26
-    FunctionRegistry, ScopeProbe, Value,
26
+    FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value,
2727
 };
2828
 use serde::Serialize;
2929
 use wasm_bindgen::prelude::*;
@@ -42,9 +42,12 @@
4242
 /// subtraction otherwise.
4343
 #[wasm_bindgen]
4444
 pub fn evaluate(expr: &str, context: JsValue, functions: JsValue) -> Result<JsValue, JsError> {
45
-    // Build the context first so it can act as the parse-time name oracle.
45
+    // Build the context and registry first: together they are the parse-time
46
+    // name oracle (ADR-47).
4647
     let ctx = context_from_js(&context)?;
47
-    run_with_ctx(&compile_with_probe_core(expr, &ctx)?, ctx, functions, false)
48
+    let registry = JsFunctionRegistry { funcs: functions };
49
+    let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
50
+    run_with_ctx(&compile_with_probe_core(expr, &scope)?, &ctx, &registry, false)
4851
 }
4952
 
5053
 /// Evaluate a FEEL expression (strict boundary policy): if the result is, or
@@ -58,7 +61,9 @@
5861
     functions: JsValue,
5962
 ) -> Result<JsValue, JsError> {
6063
     let ctx = context_from_js(&context)?;
61
-    run_with_ctx(&compile_with_probe_core(expr, &ctx)?, ctx, functions, true)
64
+    let registry = JsFunctionRegistry { funcs: functions };
65
+    let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
66
+    run_with_ctx(&compile_with_probe_core(expr, &scope)?, &ctx, &registry, true)
6267
 }
6368
 
6469
 /// A parsed FEEL expression, reusable across many evaluations.
@@ -109,10 +114,11 @@
109114
     core_compile(expr).map_err(|e| JsError::new(&e.to_string()))
110115
 }
111116
 
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)
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)
116122
         .map_err(|e| JsError::new(&e.to_string()))
117123
 }
118124
 
@@ -121,23 +127,24 @@
121127
 /// the `Date.now()` instant, optionally surface error-nulls strictly, map the
122128
 /// result back out (date/date-and-time as native `Date` objects).
123129
 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(
130
-    compiled: &CoreCompiled,
131
-    ctx: Context,
132
-    functions: JsValue,
133
-    strict: bool,
134
-) -> Result<JsValue, JsError> {
135130
     // Ambient host functions (ADR-23): a JS object of `name -> function`, consulted
136131
     // after context bindings and built-ins. `undefined`/`null` -> no-op registry.
137132
     let registry = JsFunctionRegistry { funcs: functions };
138
-    let env = EvalEnv::with_functions(&REGEX, now_zoned(), &registry);
133
+    run_with_ctx(compiled, &context_from_js(&context)?, &registry, strict)
134
+}
135
+
136
+/// [`run`] with the context and registry already built — the one-shot entry
137
+/// points have them in hand first, because together they are the parse-time
138
+/// scope probe.
139
+fn run_with_ctx(
140
+    compiled: &CoreCompiled,
141
+    ctx: &Context,
142
+    registry: &JsFunctionRegistry,
143
+    strict: bool,
144
+) -> Result<JsValue, JsError> {
145
+    let env = EvalEnv::with_functions(&REGEX, now_zoned(), registry);
139146
     let value = compiled
140
-        .evaluate_with_env(&ctx, &env)
147
+        .evaluate_with_env(ctx, &env)
141148
         .map_err(|e| JsError::new(&e.to_string()))?;
142149
     if strict && value.contains_error() {
143150
         return Err(JsError::new(