Public repository: timo / feel

Reader

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

feat(wasm): host callables and a function registry (ADR-23)

public

feat(wasm): host callables and a function registry (ADR-23)

A JS function in the context (or in the new third `functions` argument) becomes
a FEEL function value invocable from the expression. JsForeignFn wraps it behind
feel-core's ForeignFunction seam: positional FEEL args become positional JS
args, and named FEEL args become a single trailing options object {name: value}
(JS has no keyword arguments); a thrown exception becomes an error-null. A
returned host function passes back out by identity. evaluate / evaluate_strict /
CompiledExpr gain the optional functions= registry (the ambient path beside
binding a function in the context).

smoke.mjs: positional / named-as-options-object / mixed / host-default,
object-argument round-trip, builtin shadowing, ambient registry,
exception→null, and returned-function identity pass-through.

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

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

@@ -157,5 +157,60 @@
157157
 }
158158
 prog.free();
159159
 
160
+// Host callables (ADR-23): a JS function in the context is a FEEL function the
161
+// expression can invoke. Positional FEEL args -> positional JS args; named FEEL
162
+// args -> a single trailing options object (JS has no keyword arguments).
163
+const hostFnCases = [
164
+  // positional
165
+  ["f(2, 3)", { f: (a, b) => a + b }, 5],
166
+  // named -> options object {a, b}
167
+  ["f(b: 3, a: 2)", { f: (o) => o.a - o.b }, -1],
168
+  // mixed positional + named -> (positional…, {named})
169
+  ["f(2, b: 3)", { f: (a, o) => a - o.b }, -1],
170
+  // a host default applies (feel-core does no arity check for host callables)
171
+  ["f(2)", { f: (a, b = 10) => a + b }, 12],
172
+  // a host object argument round-trips by identity into the function
173
+  ["grab(o)", { grab: (o) => o.total, o: { total: 99 } }, 99],
174
+  // a function-valued binding shadows a built-in of the same name
175
+  ["count(2, 3)", { count: (a, b) => a * b }, 6],
176
+];
177
+for (const [expr, ctx, expected] of hostFnCases) {
178
+  const got = evaluate(expr, ctx);
179
+  console.log(`${expr} (host fn) => ${JSON.stringify(got)}`);
180
+  if (!eq(got, expected)) {
181
+    console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`);
182
+    ok = false;
183
+  }
184
+}
185
+
186
+// The ambient function registry (third argument): functions live apart from data.
187
+const regResult = evaluate("add(x, 3)", { x: 2 }, { add: (a, b) => a + b });
188
+console.log(`add(x, 3) (registry) => ${JSON.stringify(regResult)}`);
189
+if (regResult !== 5) {
190
+  console.error("FAIL: ambient function registry");
191
+  ok = false;
192
+}
193
+
194
+// A thrown exception inside a host callable is a lenient null (error-null).
195
+const threwResult = evaluate("boom(1)", {
196
+  boom: () => {
197
+    throw new Error("nope");
198
+  },
199
+});
200
+console.log(`boom(1) (throws) => ${JSON.stringify(threwResult)}`);
201
+if (threwResult !== null) {
202
+  console.error("FAIL: a host exception should be a lenient null");
203
+  ok = false;
204
+}
205
+
206
+// A host callable that reaches the result passes back as the same function.
207
+const idFn = (a) => a;
208
+const idResult = evaluate("f", { f: idFn });
209
+console.log(`f passthrough identity => ${idResult === idFn}`);
210
+if (idResult !== idFn) {
211
+  console.error("FAIL: a returned host function should pass through by identity");
212
+  ok = false;
213
+}
214
+
160215
 if (!ok) process.exit(1);
161216
 console.error("smoke test passed");

modified crates/feel-wasm/src/lib.rs +114 −12

@@ -20,8 +20,8 @@
2020
 use std::sync::Arc;
2121
 
2222
 use feel_core::{
23
-    compile as core_compile, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign,
24
-    ForeignObject, Value,
23
+    compile as core_compile, Args, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign,
24
+    ForeignFunction, ForeignObject, Func, FunctionRegistry, Value,
2525
 };
2626
 use serde::Serialize;
2727
 use wasm_bindgen::prelude::*;
@@ -35,8 +35,8 @@
3535
 /// returned as plain `null` (the spec-shaped result); see `evaluate_strict` to
3636
 /// surface such errors as a thrown exception instead.
3737
 #[wasm_bindgen]
38
-pub fn evaluate(expr: &str, context: JsValue) -> Result<JsValue, JsError> {
39
-    run(&compile_core(expr)?, context, false)
38
+pub fn evaluate(expr: &str, context: JsValue, functions: JsValue) -> Result<JsValue, JsError> {
39
+    run(&compile_core(expr)?, context, functions, false)
4040
 }
4141
 
4242
 /// Evaluate a FEEL expression (strict boundary policy): if the result is, or
@@ -44,8 +44,12 @@
4444
 /// the error pass silently as `null` (ADR-14). A plain (value) null is still
4545
 /// returned as `null`.
4646
 #[wasm_bindgen]
47
-pub fn evaluate_strict(expr: &str, context: JsValue) -> Result<JsValue, JsError> {
48
-    run(&compile_core(expr)?, context, true)
47
+pub fn evaluate_strict(
48
+    expr: &str,
49
+    context: JsValue,
50
+    functions: JsValue,
51
+) -> Result<JsValue, JsError> {
52
+    run(&compile_core(expr)?, context, functions, true)
4953
 }
5054
 
5155
 /// A parsed FEEL expression, reusable across many evaluations.
@@ -72,14 +76,18 @@
7276
 #[wasm_bindgen]
7377
 impl CompiledExpr {
7478
     /// Evaluate this compiled expression against a context (lenient policy).
75
-    pub fn evaluate(&self, context: JsValue) -> Result<JsValue, JsError> {
76
-        run(&self.inner, context, false)
79
+    pub fn evaluate(&self, context: JsValue, functions: JsValue) -> Result<JsValue, JsError> {
80
+        run(&self.inner, context, functions, false)
7781
     }
7882
 
7983
     /// Evaluate this compiled expression against a context (strict policy; see
8084
     /// the free `evaluate_strict`).
81
-    pub fn evaluate_strict(&self, context: JsValue) -> Result<JsValue, JsError> {
82
-        run(&self.inner, context, true)
85
+    pub fn evaluate_strict(
86
+        &self,
87
+        context: JsValue,
88
+        functions: JsValue,
89
+    ) -> Result<JsValue, JsError> {
90
+        run(&self.inner, context, functions, true)
8391
     }
8492
 }
8593
 
@@ -91,9 +99,17 @@
9199
 /// objects), evaluate the compiled program against the host regex provider and
92100
 /// the `Date.now()` instant, optionally surface error-nulls strictly, map the
93101
 /// result back out (date/date-and-time as native `Date` objects).
94
-fn run(compiled: &CoreCompiled, context: JsValue, strict: bool) -> Result<JsValue, JsError> {
102
+fn run(
103
+    compiled: &CoreCompiled,
104
+    context: JsValue,
105
+    functions: JsValue,
106
+    strict: bool,
107
+) -> Result<JsValue, JsError> {
95108
     let ctx = context_from_js(&context)?;
96
-    let env = EvalEnv::new(&REGEX, now_zoned());
109
+    // Ambient host functions (ADR-23): a JS object of `name -> function`, consulted
110
+    // after context bindings and built-ins. `undefined`/`null` -> no-op registry.
111
+    let registry = JsFunctionRegistry { funcs: functions };
112
+    let env = EvalEnv::with_functions(&REGEX, now_zoned(), &registry);
97113
     let value = compiled
98114
         .evaluate_with_env(&ctx, &env)
99115
         .map_err(|e| JsError::new(&e.to_string()))?;
@@ -160,6 +176,16 @@
160176
             Some(jf) => Ok(jf.obj.clone()),
161177
             None => value_to_js(&f.0.force()),
162178
         },
179
+        // A function value (ADR-23): a host callable is handed back as the original
180
+        // JS function (identity pass-through); a native FEEL closure has no JS
181
+        // representation and crosses out as `null`.
182
+        Value::Function(f) => match &**f {
183
+            Func::Foreign(host_fn) => match host_fn.as_any().downcast_ref::<JsForeignFn>() {
184
+                Some(jf) => Ok(jf.obj.clone()),
185
+                None => Ok(JsValue::NULL),
186
+            },
187
+            Func::Closure(_) => Ok(JsValue::NULL),
188
+        },
163189
         // Scalars (number/bool/string/null) go through the JSON-compatible path so
164190
         // integral numbers stay JS numbers (`1 + 1` -> `2`, not `2.0`).
165191
         _ => to_js(&value_to_json(value)),
@@ -252,6 +278,12 @@
252278
         let arr: &js_sys::Array = value.unchecked_ref();
253279
         return Value::List(arr.iter().map(|x| shallow_convert_js(&x)).collect());
254280
     }
281
+    // A JS function becomes a FEEL function value the host can invoke (ADR-23).
282
+    // Checked before `is_object` (a function has `typeof === "function"`, not
283
+    // `"object"`, but be explicit about ordering).
284
+    if value.is_function() {
285
+        return Func::Foreign(Arc::new(JsForeignFn { obj: value.clone() })).into_value();
286
+    }
255287
     if value.is_object() {
256288
         return Value::Foreign(Foreign(Arc::new(JsForeign { obj: value.clone() })));
257289
     }
@@ -308,6 +340,76 @@
308340
 
309341
     fn as_any(&self) -> &dyn std::any::Any {
310342
         self
343
+    }
344
+}
345
+
346
+// --------------------------------------------------------------------------- //
347
+// Host callables (ADR-23): a JS function invoked from FEEL
348
+// --------------------------------------------------------------------------- //
349
+
350
+/// A JS function behind feel-core's [`ForeignFunction`] seam. `obj` is the original
351
+/// `JsValue` (a function), kept whole for identity pass-through on output.
352
+#[derive(Debug)]
353
+struct JsForeignFn {
354
+    obj: JsValue,
355
+}
356
+
357
+impl ForeignFunction for JsForeignFn {
358
+    fn call(&self, args: Args) -> Value {
359
+        let func: &js_sys::Function = self.obj.unchecked_ref();
360
+        match js_call(func, args) {
361
+            Ok(v) => shallow_convert_js(&v),
362
+            Err(_) => Value::Error, // a thrown JS exception -> error-null (ADR-14)
363
+        }
364
+    }
365
+
366
+    fn as_any(&self) -> &dyn std::any::Any {
367
+        self
368
+    }
369
+}
370
+
371
+/// Invoke a JS function with FEEL arguments (ADR-23). JS has no keyword arguments,
372
+/// so positional FEEL args become positional JS args and — if any named args are
373
+/// present — a single trailing options object `{name: value, …}` is appended (the
374
+/// idiomatic JS convention). A thrown exception propagates as `Err`.
375
+fn js_call(func: &js_sys::Function, args: Args) -> Result<JsValue, JsValue> {
376
+    let arr = js_sys::Array::new();
377
+    for v in &args.positional {
378
+        arr.push(&value_to_js(v).map_err(|_| JsValue::NULL)?);
379
+    }
380
+    if !args.named.is_empty() {
381
+        let opts = js_sys::Object::new();
382
+        for (name, v) in &args.named {
383
+            js_sys::Reflect::set(
384
+                &opts,
385
+                &JsValue::from_str(name),
386
+                &value_to_js(v).map_err(|_| JsValue::NULL)?,
387
+            )?;
388
+        }
389
+        arr.push(&opts.into());
390
+    }
391
+    func.apply(&JsValue::NULL, &arr)
392
+}
393
+
394
+/// A host function registry backed by a JS object `name -> function` (the third
395
+/// `functions` argument; ADR-23). The ambient-function path, beside binding a
396
+/// function directly in the context. `undefined`/`null` means no registry.
397
+#[derive(Debug)]
398
+struct JsFunctionRegistry {
399
+    funcs: JsValue,
400
+}
401
+
402
+impl FunctionRegistry for JsFunctionRegistry {
403
+    fn get(&self, name: &str) -> Option<Arc<dyn ForeignFunction>> {
404
+        if self.funcs.is_undefined() || self.funcs.is_null() {
405
+            return None;
406
+        }
407
+        let item = js_sys::Reflect::get(&self.funcs, &JsValue::from_str(name)).ok()?;
408
+        if item.is_function() {
409
+            Some(Arc::new(JsForeignFn { obj: item }))
410
+        } else {
411
+            None
412
+        }
311413
     }
312414
 }
313415