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>
| Changeset | 479c1b5e83874a8ed5521d4e1a059d15639aab1c |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | 826338f9286a |
| Children | |
| Pushlog | by timo via ssh |
modified crates/feel-lua/src/lib.rs +80 −36
| @@ -33,9 +33,9 @@ | ||
| 33 | 33 | use std::sync::Arc; |
| 34 | 34 | |
| 35 | 35 | 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, | |
| 37 | 37 | CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func, |
| 38 | - FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value, | |
| 38 | + FunctionRegistry, NameResolution, ParseOptions, ScopeProbe, ScopeWithFunctions, Value, | |
| 39 | 39 | }; |
| 40 | 40 | use mlua::{Lua, Table, Value as LuaValue, Variadic}; |
| 41 | 41 | |
| @@ -53,35 +53,46 @@ | ||
| 53 | 53 | /// Rust integration tests call directly against an embedded VM. It registers |
| 54 | 54 | /// `evaluate`, `evaluate_strict` and `compile` on a fresh table and returns it. |
| 55 | 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. | |
| 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). | |
| 60 | 61 | pub fn build_module(lua: &Lua) -> mlua::Result<Table> { |
| 61 | 62 | let exports = lua.create_table()?; |
| 62 | 63 | exports.set( |
| 63 | 64 | "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: ®istry }; | |
| 70 | - run_with_ctx(lua, &compile_with_probe_core(&expr, &scope)?, &ctx, ®istry, 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: ®istry }; | |
| 73 | + let compiled = compile_with_probe_core(&expr, &scope, &options)?; | |
| 74 | + run_with_ctx(lua, &compiled, &ctx, ®istry, false) | |
| 75 | + }, | |
| 76 | + )?, | |
| 72 | 77 | )?; |
| 73 | 78 | exports.set( |
| 74 | 79 | "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: ®istry }; | |
| 79 | - run_with_ctx(lua, &compile_with_probe_core(&expr, &scope)?, &ctx, ®istry, 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: ®istry }; | |
| 86 | + let compiled = compile_with_probe_core(&expr, &scope, &options)?; | |
| 87 | + run_with_ctx(lua, &compiled, &ctx, ®istry, true) | |
| 88 | + }, | |
| 89 | + )?, | |
| 81 | 90 | )?; |
| 82 | 91 | exports.set( |
| 83 | 92 | "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 | + })?, | |
| 85 | 96 | )?; |
| 86 | 97 | Ok(exports) |
| 87 | 98 | } |
| @@ -97,8 +108,8 @@ | ||
| 97 | 108 | |
| 98 | 109 | /// A parsed FEEL expression, reusable across many evaluations (the `feel.compile` |
| 99 | 110 | /// 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. | |
| 102 | 113 | struct CompiledExpr { |
| 103 | 114 | inner: CoreCompiled, |
| 104 | 115 | } |
| @@ -120,23 +131,34 @@ | ||
| 120 | 131 | } |
| 121 | 132 | } |
| 122 | 133 | |
| 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) | |
| 133 | 154 | .map_err(|e| mlua::Error::RuntimeError(e.to_string())) |
| 134 | 155 | } |
| 135 | 156 | |
| 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> { | |
| 138 | 159 | Ok(CompiledExpr { |
| 139 | - inner: compile_core(expr)?, | |
| 160 | + inner: core_compile_with(expr, options) | |
| 161 | + .map_err(|e| mlua::Error::RuntimeError(e.to_string()))?, | |
| 140 | 162 | }) |
| 141 | 163 | } |
| 142 | 164 | |
| @@ -254,6 +276,21 @@ | ||
| 254 | 276 | /// `table[key]`, which fires an `__index` metamethod. An absent member (`nil`) or a |
| 255 | 277 | /// raised metamethod is a **value-null**. The returned value is shallow. |
| 256 | 278 | 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 | + } | |
| 257 | 294 | match table.get::<LuaValue>(key) { |
| 258 | 295 | Ok(v) => shallow_convert_lua(&v), |
| 259 | 296 | Err(_) => Value::Null, |
| @@ -391,6 +428,13 @@ | ||
| 391 | 428 | Ok(LuaValue::Function(f)) => Some(Arc::new(LuaForeignFn { func: f })), |
| 392 | 429 | _ => None, |
| 393 | 430 | } |
| 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(_)))) | |
| 394 | 438 | } |
| 395 | 439 | } |
| 396 | 440 | |
modified crates/feel-lua/tests/feel.rs +45 −6
| @@ -169,20 +169,59 @@ | ||
| 169 | 169 | } |
| 170 | 170 | |
| 171 | 171 | #[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 | |
| 177 | 176 | .load(r#"local p = feel.compile("a-b"); return p:evaluate({ ["a-b"] = 5 })"#) |
| 178 | 177 | .eval() |
| 179 | 178 | .unwrap(); |
| 180 | - assert!(matches!(v, Value::Nil)); | |
| 179 | + assert_eq!(n, 5.0); | |
| 181 | 180 | let n: f64 = lua |
| 182 | 181 | .load(r#"local p = feel.compile("a-b"); return p:evaluate({ a = 7, b = 3 })"#) |
| 183 | 182 | .eval() |
| 184 | 183 | .unwrap(); |
| 185 | 184 | 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()); | |
| 186 | 225 | } |
| 187 | 226 | |
| 188 | 227 | // --------------------------------------------------------------------------- // |
modified crates/feel-py/src/lib.rs +56 −26
| @@ -30,9 +30,9 @@ | ||
| 30 | 30 | use std::collections::BTreeMap; |
| 31 | 31 | |
| 32 | 32 | 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, | |
| 34 | 34 | CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func, |
| 35 | - FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value, | |
| 35 | + FunctionRegistry, NameResolution, ParseOptions, ScopeProbe, ScopeWithFunctions, Value, | |
| 36 | 36 | }; |
| 37 | 37 | #[cfg(not(feature = "xpath-regex"))] |
| 38 | 38 | use feel_core::FeelRegex; |
| @@ -57,15 +57,19 @@ | ||
| 57 | 57 | /// subtraction otherwise. The ambient `functions` registry (ADR-23) counts as |
| 58 | 58 | /// scope too — mirroring `eval_call`, which resolves a call head against |
| 59 | 59 | /// 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. | |
| 61 | 63 | #[pyfunction] |
| 62 | -#[pyo3(signature = (expr, context=None, functions=None))] | |
| 64 | +#[pyo3(signature = (expr, context=None, functions=None, names=None))] | |
| 63 | 65 | fn evaluate<'py>( |
| 64 | 66 | py: Python<'py>, |
| 65 | 67 | expr: &str, |
| 66 | 68 | context: Option<&Bound<'py, PyAny>>, |
| 67 | 69 | functions: Option<&Bound<'py, PyAny>>, |
| 70 | + names: Option<&str>, | |
| 68 | 71 | ) -> PyResult<Bound<'py, PyAny>> { |
| 72 | + let options = parse_options(names)?; | |
| 69 | 73 | // Build the context and the function registry first so both can act as the |
| 70 | 74 | // parse-time name oracle. |
| 71 | 75 | let ctx = context_to_ctx(context)?; |
| @@ -73,7 +77,7 @@ | ||
| 73 | 77 | funcs: functions.map(|f| f.clone().unbind()), |
| 74 | 78 | }; |
| 75 | 79 | let scope = ScopeWithFunctions { context: &ctx, functions: ®istry }; |
| 76 | - run_with_ctx(py, &compile_with_probe_core(expr, &scope)?, &ctx, ®istry, false) | |
| 80 | + run_with_ctx(py, &compile_with_probe_core(expr, &scope, &options)?, &ctx, ®istry, false) | |
| 77 | 81 | } |
| 78 | 82 | |
| 79 | 83 | /// Evaluate a FEEL expression (strict boundary policy): if the result is, or |
| @@ -81,41 +85,43 @@ | ||
| 81 | 85 | /// of letting it pass silently as `None` (ADR-14). A plain value-null is still |
| 82 | 86 | /// returned as `None`. Scope-dependent names resolve as in [`evaluate`]. |
| 83 | 87 | #[pyfunction] |
| 84 | -#[pyo3(signature = (expr, context=None, functions=None))] | |
| 88 | +#[pyo3(signature = (expr, context=None, functions=None, names=None))] | |
| 85 | 89 | fn evaluate_strict<'py>( |
| 86 | 90 | py: Python<'py>, |
| 87 | 91 | expr: &str, |
| 88 | 92 | context: Option<&Bound<'py, PyAny>>, |
| 89 | 93 | functions: Option<&Bound<'py, PyAny>>, |
| 94 | + names: Option<&str>, | |
| 90 | 95 | ) -> PyResult<Bound<'py, PyAny>> { |
| 96 | + let options = parse_options(names)?; | |
| 91 | 97 | let ctx = context_to_ctx(context)?; |
| 92 | 98 | let registry = PyFunctionRegistry { |
| 93 | 99 | funcs: functions.map(|f| f.clone().unbind()), |
| 94 | 100 | }; |
| 95 | 101 | let scope = ScopeWithFunctions { context: &ctx, functions: ®istry }; |
| 96 | - run_with_ctx(py, &compile_with_probe_core(expr, &scope)?, &ctx, ®istry, true) | |
| 102 | + run_with_ctx(py, &compile_with_probe_core(expr, &scope, &options)?, &ctx, ®istry, true) | |
| 97 | 103 | } |
| 98 | 104 | |
| 99 | 105 | /// Parse a FEEL expression into a reusable `CompiledExpr` (raises `FeelError` on a |
| 100 | 106 | /// parse error). Does not evaluate. |
| 101 | 107 | /// |
| 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. | |
| 105 | 111 | #[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)?; | |
| 107 | 115 | Ok(CompiledExpr { |
| 108 | - inner: compile_core(expr)?, | |
| 116 | + inner: core_compile_with(expr, &options).map_err(|e| FeelError::new_err(e.to_string()))?, | |
| 109 | 117 | }) |
| 110 | 118 | } |
| 111 | 119 | |
| 112 | 120 | /// A parsed FEEL expression, reusable across many evaluations: parsing happens |
| 113 | 121 | /// once, each call only maps the context across the boundary. |
| 114 | 122 | /// |
| 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. | |
| 119 | 125 | #[pyclass(name = "CompiledExpr", module = "feel")] |
| 120 | 126 | struct CompiledExpr { |
| 121 | 127 | inner: CoreCompiled, |
| @@ -146,16 +152,27 @@ | ||
| 146 | 152 | } |
| 147 | 153 | } |
| 148 | 154 | |
| 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())) | |
| 159 | 176 | } |
| 160 | 177 | |
| 161 | 178 | /// Shared per-call boundary: map the Python context in, evaluate against the host |
| @@ -448,6 +465,19 @@ | ||
| 448 | 465 | item.is_callable().then(|| { |
| 449 | 466 | Arc::new(PyForeignFn { obj: item.unbind() }) as Arc<dyn ForeignFunction> |
| 450 | 467 | }) |
| 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()) | |
| 451 | 481 | }) |
| 452 | 482 | } |
| 453 | 483 | } |
modified crates/feel-py/tests/test_feel.py +25 −4
| @@ -291,12 +291,33 @@ | ||
| 291 | 291 | assert feel.evaluate("my-fn(2)", {}) is None |
| 292 | 292 | |
| 293 | 293 | |
| 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. | |
| 297 | 296 | prog = feel.compile("a-b") |
| 298 | - assert prog.evaluate({"a-b": 5}) is None | |
| 297 | + assert prog.evaluate({"a-b": 5}) == 5 | |
| 299 | 298 | 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] | |
| 300 | 321 | |
| 301 | 322 | |
| 302 | 323 | # --- host callables: Python functions invoked from FEEL (ADR-23) ---------- # |
modified crates/feel-wasm/smoke.mjs +19 −2
| @@ -192,7 +192,7 @@ | ||
| 192 | 192 | // is the in-scope NAME when the object binds it, subtraction otherwise; `a - b` |
| 193 | 193 | // is the same candidate (spaces are not part of the name); `(a)-(b)` is the |
| 194 | 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. | |
| 195 | +// scope-adaptive (ADR-48): it follows each call's context. | |
| 196 | 196 | const nameCases = [ |
| 197 | 197 | ["a-b", { "a-b": 5 }, 5], |
| 198 | 198 | ["a - b", { "a-b": 5 }, 5], |
| @@ -219,10 +219,27 @@ | ||
| 219 | 219 | ok = false; |
| 220 | 220 | } |
| 221 | 221 | } |
| 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 | +} | |
| 222 | 239 | { |
| 223 | 240 | const prog2 = compile("a-b"); |
| 224 | 241 | 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 | |
| 226 | 243 | [{ a: 7, b: 3 }, 4], |
| 227 | 244 | ]; |
| 228 | 245 | for (const [ctx, expected] of compiledNameCases) { |
modified crates/feel-wasm/src/lib.rs +49 −23
| @@ -21,9 +21,9 @@ | ||
| 21 | 21 | use std::sync::Arc; |
| 22 | 22 | |
| 23 | 23 | 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, | |
| 25 | 25 | CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func, |
| 26 | - FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value, | |
| 26 | + FunctionRegistry, NameResolution, ParseOptions, ScopeProbe, ScopeWithFunctions, Value, | |
| 27 | 27 | }; |
| 28 | 28 | use serde::Serialize; |
| 29 | 29 | use wasm_bindgen::prelude::*; |
| @@ -39,15 +39,23 @@ | ||
| 39 | 39 | /// |
| 40 | 40 | /// The context **is** the scope for §10.3.1.6 name resolution (ADR-47): a name |
| 41 | 41 | /// 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. | |
| 43 | 45 | #[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> { | |
| 45 | 52 | // Build the context and registry first: together they are the parse-time |
| 46 | 53 | // name oracle (ADR-47). |
| 54 | + let options = parse_options(names.as_deref())?; | |
| 47 | 55 | let ctx = context_from_js(&context)?; |
| 48 | 56 | let registry = JsFunctionRegistry { funcs: functions }; |
| 49 | 57 | let scope = ScopeWithFunctions { context: &ctx, functions: ®istry }; |
| 50 | - run_with_ctx(&compile_with_probe_core(expr, &scope)?, &ctx, ®istry, false) | |
| 58 | + run_with_ctx(&compile_with_probe_core(expr, &scope, &options)?, &ctx, ®istry, false) | |
| 51 | 59 | } |
| 52 | 60 | |
| 53 | 61 | /// Evaluate a FEEL expression (strict boundary policy): if the result is, or |
| @@ -59,11 +67,13 @@ | ||
| 59 | 67 | expr: &str, |
| 60 | 68 | context: JsValue, |
| 61 | 69 | functions: JsValue, |
| 70 | + names: Option<String>, | |
| 62 | 71 | ) -> Result<JsValue, JsError> { |
| 72 | + let options = parse_options(names.as_deref())?; | |
| 63 | 73 | let ctx = context_from_js(&context)?; |
| 64 | 74 | let registry = JsFunctionRegistry { funcs: functions }; |
| 65 | 75 | let scope = ScopeWithFunctions { context: &ctx, functions: ®istry }; |
| 66 | - run_with_ctx(&compile_with_probe_core(expr, &scope)?, &ctx, ®istry, true) | |
| 76 | + run_with_ctx(&compile_with_probe_core(expr, &scope, &options)?, &ctx, ®istry, true) | |
| 67 | 77 | } |
| 68 | 78 | |
| 69 | 79 | /// A parsed FEEL expression, reusable across many evaluations. |
| @@ -74,21 +84,21 @@ | ||
| 74 | 84 | /// `FinalizationRegistry`, so the WASM-side memory is reclaimed on GC; calling |
| 75 | 85 | /// `free()` explicitly is an optional escape hatch, not required. |
| 76 | 86 | /// |
| 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. | |
| 81 | 89 | #[wasm_bindgen] |
| 82 | 90 | pub struct CompiledExpr { |
| 83 | 91 | inner: CoreCompiled, |
| 84 | 92 | } |
| 85 | 93 | |
| 86 | 94 | /// 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`]. | |
| 88 | 97 | #[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())?; | |
| 90 | 100 | Ok(CompiledExpr { |
| 91 | - inner: compile_core(expr)?, | |
| 101 | + inner: core_compile_with(expr, &options).map_err(|e| JsError::new(&e.to_string()))?, | |
| 92 | 102 | }) |
| 93 | 103 | } |
| 94 | 104 | |
| @@ -110,16 +120,24 @@ | ||
| 110 | 120 | } |
| 111 | 121 | } |
| 112 | 122 | |
| 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())) | |
| 123 | 141 | } |
| 124 | 142 | |
| 125 | 143 | /// Shared per-call boundary: map the JS context in (accepting native `Date` |
| @@ -480,6 +498,14 @@ | ||
| 480 | 498 | None |
| 481 | 499 | } |
| 482 | 500 | } |
| 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 | + } | |
| 483 | 509 | } |
| 484 | 510 | |
| 485 | 511 | // --------------------------------------------------------------------------- // |