| @@ -30,8 +30,8 @@ |
| 30 | 30 | use std::collections::BTreeMap; |
| 31 | 31 | |
| 32 | 32 | 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, |
| 35 | 35 | }; |
| 36 | 36 | #[cfg(not(feature = "xpath-regex"))] |
| 37 | 37 | use feel_core::FeelRegex; |
| @@ -51,13 +51,14 @@ |
| 51 | 51 | /// A null arising from a type/domain error is returned as `None`; see |
| 52 | 52 | /// `evaluate_strict` to raise instead. |
| 53 | 53 | #[pyfunction] |
| 54 | | -#[pyo3(signature = (expr, context=None))] |
| 54 | +#[pyo3(signature = (expr, context=None, functions=None))] |
| 55 | 55 | fn evaluate<'py>( |
| 56 | 56 | py: Python<'py>, |
| 57 | 57 | expr: &str, |
| 58 | 58 | context: Option<&Bound<'py, PyAny>>, |
| 59 | + functions: Option<&Bound<'py, PyAny>>, |
| 59 | 60 | ) -> PyResult<Bound<'py, PyAny>> { |
| 60 | | - run(py, &compile_core(expr)?, context, false) |
| 61 | + run(py, &compile_core(expr)?, context, functions, false) |
| 61 | 62 | } |
| 62 | 63 | |
| 63 | 64 | /// Evaluate a FEEL expression (strict boundary policy): if the result is, or |
| @@ -65,13 +66,14 @@ |
| 65 | 66 | /// of letting it pass silently as `None` (ADR-14). A plain value-null is still |
| 66 | 67 | /// returned as `None`. |
| 67 | 68 | #[pyfunction] |
| 68 | | -#[pyo3(signature = (expr, context=None))] |
| 69 | +#[pyo3(signature = (expr, context=None, functions=None))] |
| 69 | 70 | fn evaluate_strict<'py>( |
| 70 | 71 | py: Python<'py>, |
| 71 | 72 | expr: &str, |
| 72 | 73 | context: Option<&Bound<'py, PyAny>>, |
| 74 | + functions: Option<&Bound<'py, PyAny>>, |
| 73 | 75 | ) -> PyResult<Bound<'py, PyAny>> { |
| 74 | | - run(py, &compile_core(expr)?, context, true) |
| 76 | + run(py, &compile_core(expr)?, context, functions, true) |
| 75 | 77 | } |
| 76 | 78 | |
| 77 | 79 | /// Parse a FEEL expression into a reusable `CompiledExpr` (raises `FeelError` on a |
| @@ -93,23 +95,25 @@ |
| 93 | 95 | #[pymethods] |
| 94 | 96 | impl CompiledExpr { |
| 95 | 97 | /// Evaluate this compiled expression against a context (lenient policy). |
| 96 | | - #[pyo3(signature = (context=None))] |
| 98 | + #[pyo3(signature = (context=None, functions=None))] |
| 97 | 99 | fn evaluate<'py>( |
| 98 | 100 | &self, |
| 99 | 101 | py: Python<'py>, |
| 100 | 102 | context: Option<&Bound<'py, PyAny>>, |
| 103 | + functions: Option<&Bound<'py, PyAny>>, |
| 101 | 104 | ) -> PyResult<Bound<'py, PyAny>> { |
| 102 | | - run(py, &self.inner, context, false) |
| 105 | + run(py, &self.inner, context, functions, false) |
| 103 | 106 | } |
| 104 | 107 | |
| 105 | 108 | /// Evaluate this compiled expression against a context (strict policy). |
| 106 | | - #[pyo3(signature = (context=None))] |
| 109 | + #[pyo3(signature = (context=None, functions=None))] |
| 107 | 110 | fn evaluate_strict<'py>( |
| 108 | 111 | &self, |
| 109 | 112 | py: Python<'py>, |
| 110 | 113 | context: Option<&Bound<'py, PyAny>>, |
| 114 | + functions: Option<&Bound<'py, PyAny>>, |
| 111 | 115 | ) -> PyResult<Bound<'py, PyAny>> { |
| 112 | | - run(py, &self.inner, context, true) |
| 116 | + run(py, &self.inner, context, functions, true) |
| 113 | 117 | } |
| 114 | 118 | } |
| 115 | 119 | |
| @@ -124,10 +128,16 @@ |
| 124 | 128 | py: Python<'py>, |
| 125 | 129 | compiled: &CoreCompiled, |
| 126 | 130 | context: Option<&Bound<'py, PyAny>>, |
| 131 | + functions: Option<&Bound<'py, PyAny>>, |
| 127 | 132 | strict: bool, |
| 128 | 133 | ) -> PyResult<Bound<'py, PyAny>> { |
| 129 | 134 | let ctx = context_to_ctx(context)?; |
| 130 | 135 | 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 | + }; |
| 131 | 141 | |
| 132 | 142 | // With the default Python `re` provider the regex builtins call back into |
| 133 | 143 | // Python, so the GIL must be held for the whole evaluation. The `xpath-regex` |
| @@ -136,14 +146,14 @@ |
| 136 | 146 | #[cfg(not(feature = "xpath-regex"))] |
| 137 | 147 | let value = { |
| 138 | 148 | let regex = PyRegex { py }; |
| 139 | | - let env = EvalEnv::new(®ex, now); |
| 149 | + let env = EvalEnv::with_functions(®ex, now, ®istry); |
| 140 | 150 | compiled |
| 141 | 151 | .evaluate_with_env(&ctx, &env) |
| 142 | 152 | .map_err(|e| FeelError::new_err(e.to_string()))? |
| 143 | 153 | }; |
| 144 | 154 | #[cfg(feature = "xpath-regex")] |
| 145 | 155 | let value = { |
| 146 | | - let env = EvalEnv::new(&feel_core::RustRegex, now); |
| 156 | + let env = EvalEnv::with_functions(&feel_core::RustRegex, now, ®istry); |
| 147 | 157 | compiled |
| 148 | 158 | .evaluate_with_env(&ctx, &env) |
| 149 | 159 | .map_err(|e| FeelError::new_err(e.to_string()))? |
| @@ -231,6 +241,15 @@ |
| 231 | 241 | items.push(shallow_convert(&item)?); |
| 232 | 242 | } |
| 233 | 243 | 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()); |
| 234 | 253 | } |
| 235 | 254 | // A `dict` or any other object: wrap lazily; members resolve on access. |
| 236 | 255 | Ok(Value::Foreign(Foreign(Arc::new(PyForeign { |
| @@ -304,6 +323,72 @@ |
| 304 | 323 | |
| 305 | 324 | fn as_any(&self) -> &dyn std::any::Any { |
| 306 | 325 | 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 | + }) |
| 307 | 392 | } |
| 308 | 393 | } |
| 309 | 394 | |
| @@ -435,6 +520,16 @@ |
| 435 | 520 | Value::Foreign(f) => match f.0.as_any().downcast_ref::<PyForeign>() { |
| 436 | 521 | Some(pf) => pf.obj.clone_ref(py).into_bound(py), |
| 437 | 522 | 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), |
| 438 | 533 | }, |
| 439 | 534 | }) |
| 440 | 535 | } |