Public repository: timo / feel

Reader

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

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

public

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

A Python callable in the context (or in the new functions= mapping) becomes a
FEEL function value invocable from the expression. PyForeignFn wraps the
callable behind feel-core's ForeignFunction seam and invokes it as
f(*positional, **named), so FEEL named arguments are real Python kwargs and the
host's defaults / keyword-only / positional-only parameters all apply; a raised
exception becomes an error-null. A returned host callable passes back out by
identity. evaluate/evaluate_strict/CompiledExpr gain an optional functions=
registry (the ambient path beside binding a callable in the context).

pytest: callable-in-context, named→kwargs, mixed args, host defaults,
keyword-only, object-argument round-trip, registry, exception→None,
identity pass-through, and context-binding-shadows-builtin. Type stub updated.

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

modified crates/feel-py/python/feel/__init__.pyi +20 −6

@@ -2,7 +2,9 @@
22
 
33
 A FEEL `context` is any Python value: `dict`s map by key, other objects by their
44
 instance `__dict__`, and `datetime`/`dateutil` values map to the FEEL temporal
5
-types. Results come back as native Python values; an error-null is `None` under the
5
+types. A Python callable in the context (or in `functions`) is a FEEL function that
6
+can be invoked from the expression; named FEEL arguments become keyword arguments.
7
+Results come back as native Python values; an error-null is `None` under the
68
 lenient policy, or raises `FeelError` under the strict policy.
79
 """
810
 
@@ -16,14 +18,26 @@
1618
 class CompiledExpr:
1719
     """A parsed FEEL expression, reusable across many evaluations."""
1820
 
19
-    def evaluate(self, context: Optional[Any] = ...) -> Any: ...
20
-    def evaluate_strict(self, context: Optional[Any] = ...) -> Any: ...
21
+    def evaluate(
22
+        self, context: Optional[Any] = ..., functions: Optional[Any] = ...
23
+    ) -> Any: ...
24
+    def evaluate_strict(
25
+        self, context: Optional[Any] = ..., functions: Optional[Any] = ...
26
+    ) -> Any: ...
2127
 
22
-def evaluate(expr: str, context: Optional[Any] = ...) -> Any:
23
-    """Evaluate a FEEL expression (lenient: error-null -> None)."""
28
+def evaluate(
29
+    expr: str, context: Optional[Any] = ..., functions: Optional[Any] = ...
30
+) -> Any:
31
+    """Evaluate a FEEL expression (lenient: error-null -> None).
32
+
33
+    `functions` is an optional mapping of name -> callable exposing ambient host
34
+    functions, callable from the expression alongside the built-ins.
35
+    """
2436
     ...
2537
 
26
-def evaluate_strict(expr: str, context: Optional[Any] = ...) -> Any:
38
+def evaluate_strict(
39
+    expr: str, context: Optional[Any] = ..., functions: Optional[Any] = ...
40
+) -> Any:
2741
     """Evaluate a FEEL expression (strict: error-null raises FeelError)."""
2842
     ...
2943
 

modified crates/feel-py/src/lib.rs +107 −12

@@ -30,8 +30,8 @@
3030
 use std::collections::BTreeMap;
3131
 
3232
 use feel_core::{
33
-    compile as core_compile, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign,
34
-    ForeignObject, Value,
33
+    compile as core_compile, Args, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign,
34
+    ForeignFunction, ForeignObject, Func, FunctionRegistry, Value,
3535
 };
3636
 #[cfg(not(feature = "xpath-regex"))]
3737
 use feel_core::FeelRegex;
@@ -51,13 +51,14 @@
5151
 /// A null arising from a type/domain error is returned as `None`; see
5252
 /// `evaluate_strict` to raise instead.
5353
 #[pyfunction]
54
-#[pyo3(signature = (expr, context=None))]
54
+#[pyo3(signature = (expr, context=None, functions=None))]
5555
 fn evaluate<'py>(
5656
     py: Python<'py>,
5757
     expr: &str,
5858
     context: Option<&Bound<'py, PyAny>>,
59
+    functions: Option<&Bound<'py, PyAny>>,
5960
 ) -> PyResult<Bound<'py, PyAny>> {
60
-    run(py, &compile_core(expr)?, context, false)
61
+    run(py, &compile_core(expr)?, context, functions, false)
6162
 }
6263
 
6364
 /// Evaluate a FEEL expression (strict boundary policy): if the result is, or
@@ -65,13 +66,14 @@
6566
 /// of letting it pass silently as `None` (ADR-14). A plain value-null is still
6667
 /// returned as `None`.
6768
 #[pyfunction]
68
-#[pyo3(signature = (expr, context=None))]
69
+#[pyo3(signature = (expr, context=None, functions=None))]
6970
 fn evaluate_strict<'py>(
7071
     py: Python<'py>,
7172
     expr: &str,
7273
     context: Option<&Bound<'py, PyAny>>,
74
+    functions: Option<&Bound<'py, PyAny>>,
7375
 ) -> PyResult<Bound<'py, PyAny>> {
74
-    run(py, &compile_core(expr)?, context, true)
76
+    run(py, &compile_core(expr)?, context, functions, true)
7577
 }
7678
 
7779
 /// Parse a FEEL expression into a reusable `CompiledExpr` (raises `FeelError` on a
@@ -93,23 +95,25 @@
9395
 #[pymethods]
9496
 impl CompiledExpr {
9597
     /// Evaluate this compiled expression against a context (lenient policy).
96
-    #[pyo3(signature = (context=None))]
98
+    #[pyo3(signature = (context=None, functions=None))]
9799
     fn evaluate<'py>(
98100
         &self,
99101
         py: Python<'py>,
100102
         context: Option<&Bound<'py, PyAny>>,
103
+        functions: Option<&Bound<'py, PyAny>>,
101104
     ) -> PyResult<Bound<'py, PyAny>> {
102
-        run(py, &self.inner, context, false)
105
+        run(py, &self.inner, context, functions, false)
103106
     }
104107
 
105108
     /// Evaluate this compiled expression against a context (strict policy).
106
-    #[pyo3(signature = (context=None))]
109
+    #[pyo3(signature = (context=None, functions=None))]
107110
     fn evaluate_strict<'py>(
108111
         &self,
109112
         py: Python<'py>,
110113
         context: Option<&Bound<'py, PyAny>>,
114
+        functions: Option<&Bound<'py, PyAny>>,
111115
     ) -> PyResult<Bound<'py, PyAny>> {
112
-        run(py, &self.inner, context, true)
116
+        run(py, &self.inner, context, functions, true)
113117
     }
114118
 }
115119
 
@@ -124,10 +128,16 @@
124128
     py: Python<'py>,
125129
     compiled: &CoreCompiled,
126130
     context: Option<&Bound<'py, PyAny>>,
131
+    functions: Option<&Bound<'py, PyAny>>,
127132
     strict: bool,
128133
 ) -> PyResult<Bound<'py, PyAny>> {
129134
     let ctx = context_to_ctx(context)?;
130135
     let now = now_zoned();
136
+    // Ambient host functions (ADR-23): a `name -> callable` mapping, consulted after
137
+    // context bindings and built-ins. Absent -> an empty registry (no-op).
138
+    let registry = PyFunctionRegistry {
139
+        funcs: functions.map(|f| f.clone().unbind()),
140
+    };
131141
 
132142
     // With the default Python `re` provider the regex builtins call back into
133143
     // Python, so the GIL must be held for the whole evaluation. The `xpath-regex`
@@ -136,14 +146,14 @@
136146
     #[cfg(not(feature = "xpath-regex"))]
137147
     let value = {
138148
         let regex = PyRegex { py };
139
-        let env = EvalEnv::new(&regex, now);
149
+        let env = EvalEnv::with_functions(&regex, now, &registry);
140150
         compiled
141151
             .evaluate_with_env(&ctx, &env)
142152
             .map_err(|e| FeelError::new_err(e.to_string()))?
143153
     };
144154
     #[cfg(feature = "xpath-regex")]
145155
     let value = {
146
-        let env = EvalEnv::new(&feel_core::RustRegex, now);
156
+        let env = EvalEnv::with_functions(&feel_core::RustRegex, now, &registry);
147157
         compiled
148158
             .evaluate_with_env(&ctx, &env)
149159
             .map_err(|e| FeelError::new_err(e.to_string()))?
@@ -231,6 +241,15 @@
231241
             items.push(shallow_convert(&item)?);
232242
         }
233243
         return Ok(Value::List(items));
244
+    }
245
+    // A Python callable (function, lambda, bound method, callable object) becomes a
246
+    // FEEL function value the host can invoke (ADR-23). Checked after the data types
247
+    // above so a normal mapping/object still maps to a lazy `Foreign`.
248
+    if obj.is_callable() {
249
+        return Ok(Func::Foreign(Arc::new(PyForeignFn {
250
+            obj: obj.clone().unbind(),
251
+        }))
252
+        .into_value());
234253
     }
235254
     // A `dict` or any other object: wrap lazily; members resolve on access.
236255
     Ok(Value::Foreign(Foreign(Arc::new(PyForeign {
@@ -304,6 +323,72 @@
304323
 
305324
     fn as_any(&self) -> &dyn std::any::Any {
306325
         self
326
+    }
327
+}
328
+
329
+// --------------------------------------------------------------------------- //
330
+// Host callables (ADR-23): a Python callable invoked from FEEL
331
+// --------------------------------------------------------------------------- //
332
+
333
+/// A Python callable behind feel-core's [`ForeignFunction`] seam. Holds a
334
+/// GIL-independent `Py<PyAny>`; the call reattaches via `Python::attach`.
335
+#[derive(Debug)]
336
+struct PyForeignFn {
337
+    obj: Py<PyAny>,
338
+}
339
+
340
+impl ForeignFunction for PyForeignFn {
341
+    fn call(&self, args: Args) -> Value {
342
+        Python::attach(|py| py_call(self.obj.bind(py), args).unwrap_or(Value::Error))
343
+    }
344
+
345
+    fn as_any(&self) -> &dyn std::any::Any {
346
+        self
347
+    }
348
+}
349
+
350
+/// Invoke a Python callable, mapping FEEL arguments to `f(*positional, **named)`
351
+/// (ADR-23): positional FEEL args become positional Python args, named FEEL args
352
+/// become keyword arguments — so the host's defaults, keyword-only and
353
+/// positional-only parameters all apply naturally. A raised exception (including a
354
+/// `TypeError` for a missing/unknown/duplicate argument) is an error-null.
355
+fn py_call(obj: &Bound<'_, PyAny>, args: Args) -> PyResult<Value> {
356
+    let py = obj.py();
357
+    let mut positional = Vec::with_capacity(args.positional.len());
358
+    for v in &args.positional {
359
+        positional.push(value_to_py(py, v)?);
360
+    }
361
+    let pos = PyTuple::new(py, positional)?;
362
+    let result = if args.named.is_empty() {
363
+        obj.call1(&pos)?
364
+    } else {
365
+        let kwargs = PyDict::new(py);
366
+        for (name, v) in &args.named {
367
+            kwargs.set_item(name, value_to_py(py, v)?)?;
368
+        }
369
+        obj.call(&pos, Some(&kwargs))?
370
+    };
371
+    // Convert the result shallowly, so a returned object stays a lazy `Foreign`.
372
+    shallow_convert(&result)
373
+}
374
+
375
+/// A host function registry backed by a Python mapping `name -> callable` (the
376
+/// `functions=` argument; ADR-23). The ambient-function path, beside binding a
377
+/// callable directly in the context. `None` means no registry was supplied.
378
+#[derive(Debug)]
379
+struct PyFunctionRegistry {
380
+    funcs: Option<Py<PyAny>>,
381
+}
382
+
383
+impl FunctionRegistry for PyFunctionRegistry {
384
+    fn get(&self, name: &str) -> Option<Arc<dyn ForeignFunction>> {
385
+        let funcs = self.funcs.as_ref()?;
386
+        Python::attach(|py| {
387
+            let item = funcs.bind(py).get_item(name).ok()?;
388
+            item.is_callable().then(|| {
389
+                Arc::new(PyForeignFn { obj: item.unbind() }) as Arc<dyn ForeignFunction>
390
+            })
391
+        })
307392
     }
308393
 }
309394
 
@@ -435,6 +520,16 @@
435520
         Value::Foreign(f) => match f.0.as_any().downcast_ref::<PyForeign>() {
436521
             Some(pf) => pf.obj.clone_ref(py).into_bound(py),
437522
             None => value_to_py(py, &f.0.force())?,
523
+        },
524
+        // A function value (ADR-23): a host callable is handed back as the original
525
+        // Python callable (identity pass-through); a native FEEL closure has no
526
+        // Python representation and crosses out as `None`.
527
+        Value::Function(f) => match &**f {
528
+            Func::Foreign(host_fn) => match host_fn.as_any().downcast_ref::<PyForeignFn>() {
529
+                Some(pf) => pf.obj.clone_ref(py).into_bound(py),
530
+                None => py.None().into_bound(py),
531
+            },
532
+            Func::Closure(_) => py.None().into_bound(py),
438533
         },
439534
     })
440535
 }

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

@@ -207,3 +207,80 @@
207207
     prog = feel.compile("a + 1")
208208
     assert prog.evaluate({"a": 1}) == 2
209209
     assert prog.evaluate({"a": 41}) == 42
210
+
211
+
212
+# --- host callables: Python functions invoked from FEEL (ADR-23) ---------- #
213
+
214
+def test_callable_in_context_is_invoked():
215
+    # A Python callable bound in the context is invoked by name from FEEL.
216
+    assert feel.evaluate("f(2, 3)", {"f": lambda a, b: a + b}) == 5
217
+
218
+
219
+def test_named_args_become_kwargs():
220
+    # FEEL named arguments map to Python keyword arguments.
221
+    assert feel.evaluate("f(b: 3, a: 2)", {"f": lambda a, b: a - b}) == -1
222
+
223
+
224
+def test_mixed_positional_and_named():
225
+    # Mixed positional + named (a tolerant superset of FEEL spec rule 39): 2 - 3.
226
+    assert feel.evaluate("f(2, b: 3)", {"f": lambda a, b: a - b}) == -1
227
+
228
+
229
+def test_host_default_applies_when_arg_omitted():
230
+    # feel-core does no arity check for host callables, so the host's default fills in.
231
+    assert feel.evaluate("f(2)", {"f": lambda a, b=10: a + b}) == 12
232
+
233
+
234
+def test_keyword_only_parameter():
235
+    # A keyword-only parameter is reachable via the named form.
236
+    def f(a, *, b):
237
+        return a - b
238
+
239
+    assert feel.evaluate("f(2, b: 3)", {"f": f}) == -1
240
+
241
+
242
+def test_host_function_receives_object_argument():
243
+    # A host object passed as an argument round-trips: the function sees the
244
+    # original object (identity), not a snapshot.
245
+    class Order:
246
+        def __init__(self):
247
+            self.total = 99
248
+
249
+    seen = {}
250
+
251
+    def grab(o):
252
+        seen["o"] = o
253
+        return o.total
254
+
255
+    order = Order()
256
+    assert feel.evaluate("grab(o)", {"grab": grab, "o": order}) == 99
257
+    assert seen["o"] is order
258
+
259
+
260
+def test_host_function_via_registry():
261
+    # The second injection path: an ambient `functions=` registry, separate from data.
262
+    assert feel.evaluate("add(2, 3)", functions={"add": lambda a, b: a + b}) == 5
263
+    # Combined with a data context.
264
+    assert (
265
+        feel.evaluate("add(x, 3)", {"x": 2}, functions={"add": lambda a, b: a + b}) == 5
266
+    )
267
+
268
+
269
+def test_host_exception_is_lenient_none():
270
+    # A raised exception inside the host callable becomes an error-null (-> None).
271
+    def boom(a):
272
+        raise ValueError("nope")
273
+
274
+    assert feel.evaluate("f(1)", {"f": boom}) is None
275
+
276
+
277
+def test_returned_callable_passes_through_by_identity():
278
+    # A host callable that reaches the result is handed back as the same object.
279
+    f = lambda a: a
280
+    assert feel.evaluate("f", {"f": f}) is f
281
+
282
+
283
+def test_context_binding_shadows_builtin():
284
+    # A function-valued context binding takes precedence over a built-in of the
285
+    # same name (host override; ADR-23).
286
+    assert feel.evaluate("count(1, 2)", {"count": lambda a, b: a * b}) == 2