| 1 | //! Python wrapper for `feel-core`, built with PyO3. |
| 2 | //! |
| 3 | //! Exposes the one-shot `evaluate(expr, context) -> object` plus a |
| 4 | //! `compile(expr) -> CompiledExpr` class for parse-once / evaluate-many: parsing |
| 5 | //! is the per-call cost that does not depend on the context, so callers that |
| 6 | //! evaluate the same expression against many contexts should compile once and |
| 7 | //! reuse. The context is a native Python value and the result a native Python |
| 8 | //! value. The boundary mapping lives here (not in `feel-core`), per the project's |
| 9 | //! boundary-mapping decision (ADR-1). |
| 10 | //! |
| 11 | //! Regex dialect (ADR-16): by default the `matches`/`replace`/`split` builtins run |
| 12 | //! on Python's `re` engine, so the Python regex dialect applies. The FEEL/XPath |
| 13 | //! flags `i s m x q` map onto `re` (`i/s/m/x` as inline `(?…)`, `q` as |
| 14 | //! `re.escape`); inline flags in the pattern are passed through unchanged. The |
| 15 | //! purist `xpath-regex` feature instead re-bundles feel-core's `RustRegex` for |
| 16 | //! results identical to feel-core/TCK. |
| 17 | //! |
| 18 | //! Context input (RD-6, flipped by ADR-21): conversion is **lazy**. An object/dict |
| 19 | //! is wrapped behind feel-core's `ForeignObject` seam instead of being walked up |
| 20 | //! front, so `order.customer.address` resolves one segment at a time via |
| 21 | //! attribute access (`getattr`), which fires `@property`/descriptors — letting ORM |
| 22 | //! relations load on demand, exactly when the expression names them. Scalars and |
| 23 | //! temporal values are still converted eagerly at the boundary. A `Foreign` that |
| 24 | //! reaches the result passes back the original object untouched (identity, no |
| 25 | //! re-traversal). Because a (finite) expression can only navigate a finite path, |
| 26 | //! cyclic graphs need no cycle guard. |
| 27 | |
| 28 | use std::sync::Arc; |
| 29 | |
| 30 | use std::collections::BTreeMap; |
| 31 | |
| 32 | use feel_core::{ |
| 33 | compile as core_compile, compile_with_probe as core_compile_with_probe, Args, |
| 34 | CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func, |
| 35 | FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value, |
| 36 | }; |
| 37 | #[cfg(not(feature = "xpath-regex"))] |
| 38 | use feel_core::FeelRegex; |
| 39 | use pyo3::exceptions::PyValueError; |
| 40 | use pyo3::prelude::*; |
| 41 | use pyo3::types::{PyBool, PyDict, PyFloat, PyInt, PyList, PyString, PyTuple}; |
| 42 | |
| 43 | pyo3::create_exception!(feel, FeelError, PyValueError); |
| 44 | |
| 45 | // --------------------------------------------------------------------------- // |
| 46 | // Public API (free functions + the CompiledExpr class) |
| 47 | // --------------------------------------------------------------------------- // |
| 48 | |
| 49 | /// Evaluate a FEEL expression (lenient boundary policy). |
| 50 | /// |
| 51 | /// `context` is a native Python value (e.g. a `dict`); `None` is an empty context. |
| 52 | /// A null arising from a type/domain error is returned as `None`; see |
| 53 | /// `evaluate_strict` to raise instead. |
| 54 | /// |
| 55 | /// The context **is** the scope for §10.3.1.6 name resolution (ADR-47): a name |
| 56 | /// like `a-b` resolves to the context binding `a-b` when one exists, and to |
| 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)`. |
| 61 | #[pyfunction] |
| 62 | #[pyo3(signature = (expr, context=None, functions=None))] |
| 63 | fn evaluate<'py>( |
| 64 | py: Python<'py>, |
| 65 | expr: &str, |
| 66 | context: Option<&Bound<'py, PyAny>>, |
| 67 | functions: Option<&Bound<'py, PyAny>>, |
| 68 | ) -> PyResult<Bound<'py, PyAny>> { |
| 69 | // Build the context and the function registry first so both can act as the |
| 70 | // parse-time name oracle. |
| 71 | let ctx = context_to_ctx(context)?; |
| 72 | let registry = PyFunctionRegistry { |
| 73 | funcs: functions.map(|f| f.clone().unbind()), |
| 74 | }; |
| 75 | let scope = ScopeWithFunctions { context: &ctx, functions: ®istry }; |
| 76 | run_with_ctx(py, &compile_with_probe_core(expr, &scope)?, &ctx, ®istry, false) |
| 77 | } |
| 78 | |
| 79 | /// Evaluate a FEEL expression (strict boundary policy): if the result is, or |
| 80 | /// contains, a null that arose from a type/domain error, raise `FeelError` instead |
| 81 | /// of letting it pass silently as `None` (ADR-14). A plain value-null is still |
| 82 | /// returned as `None`. Scope-dependent names resolve as in [`evaluate`]. |
| 83 | #[pyfunction] |
| 84 | #[pyo3(signature = (expr, context=None, functions=None))] |
| 85 | fn evaluate_strict<'py>( |
| 86 | py: Python<'py>, |
| 87 | expr: &str, |
| 88 | context: Option<&Bound<'py, PyAny>>, |
| 89 | functions: Option<&Bound<'py, PyAny>>, |
| 90 | ) -> PyResult<Bound<'py, PyAny>> { |
| 91 | let ctx = context_to_ctx(context)?; |
| 92 | let registry = PyFunctionRegistry { |
| 93 | funcs: functions.map(|f| f.clone().unbind()), |
| 94 | }; |
| 95 | let scope = ScopeWithFunctions { context: &ctx, functions: ®istry }; |
| 96 | run_with_ctx(py, &compile_with_probe_core(expr, &scope)?, &ctx, ®istry, true) |
| 97 | } |
| 98 | |
| 99 | /// Parse a FEEL expression into a reusable `CompiledExpr` (raises `FeelError` on a |
| 100 | /// parse error). Does not evaluate. |
| 101 | /// |
| 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. |
| 105 | #[pyfunction] |
| 106 | fn compile(expr: &str) -> PyResult<CompiledExpr> { |
| 107 | Ok(CompiledExpr { |
| 108 | inner: compile_core(expr)?, |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | /// A parsed FEEL expression, reusable across many evaluations: parsing happens |
| 113 | /// once, each call only maps the context across the boundary. |
| 114 | /// |
| 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). |
| 119 | #[pyclass(name = "CompiledExpr", module = "feel")] |
| 120 | struct CompiledExpr { |
| 121 | inner: CoreCompiled, |
| 122 | } |
| 123 | |
| 124 | #[pymethods] |
| 125 | impl CompiledExpr { |
| 126 | /// Evaluate this compiled expression against a context (lenient policy). |
| 127 | #[pyo3(signature = (context=None, functions=None))] |
| 128 | fn evaluate<'py>( |
| 129 | &self, |
| 130 | py: Python<'py>, |
| 131 | context: Option<&Bound<'py, PyAny>>, |
| 132 | functions: Option<&Bound<'py, PyAny>>, |
| 133 | ) -> PyResult<Bound<'py, PyAny>> { |
| 134 | run(py, &self.inner, context, functions, false) |
| 135 | } |
| 136 | |
| 137 | /// Evaluate this compiled expression against a context (strict policy). |
| 138 | #[pyo3(signature = (context=None, functions=None))] |
| 139 | fn evaluate_strict<'py>( |
| 140 | &self, |
| 141 | py: Python<'py>, |
| 142 | context: Option<&Bound<'py, PyAny>>, |
| 143 | functions: Option<&Bound<'py, PyAny>>, |
| 144 | ) -> PyResult<Bound<'py, PyAny>> { |
| 145 | run(py, &self.inner, context, functions, true) |
| 146 | } |
| 147 | } |
| 148 | |
| 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())) |
| 159 | } |
| 160 | |
| 161 | /// Shared per-call boundary: map the Python context in, evaluate against the host |
| 162 | /// regex provider and the system clock, optionally surface error-nulls strictly, |
| 163 | /// map the result back out. |
| 164 | fn run<'py>( |
| 165 | py: Python<'py>, |
| 166 | compiled: &CoreCompiled, |
| 167 | context: Option<&Bound<'py, PyAny>>, |
| 168 | functions: Option<&Bound<'py, PyAny>>, |
| 169 | strict: bool, |
| 170 | ) -> PyResult<Bound<'py, PyAny>> { |
| 171 | // Ambient host functions (ADR-23): a `name -> callable` mapping, consulted after |
| 172 | // context bindings and built-ins. Absent -> an empty registry (no-op). |
| 173 | let registry = PyFunctionRegistry { |
| 174 | funcs: functions.map(|f| f.clone().unbind()), |
| 175 | }; |
| 176 | run_with_ctx(py, compiled, &context_to_ctx(context)?, ®istry, 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(); |
| 190 | |
| 191 | // With the default Python `re` provider the regex builtins call back into |
| 192 | // Python, so the GIL must be held for the whole evaluation. The `xpath-regex` |
| 193 | // provider (RustRegex) makes no Python call, so it could release the GIL — left |
| 194 | // as a future optimisation (the `&dyn FeelRegex` Send bound makes it fiddly). |
| 195 | #[cfg(not(feature = "xpath-regex"))] |
| 196 | let value = { |
| 197 | let regex = PyRegex { py }; |
| 198 | let env = EvalEnv::with_functions(®ex, now, registry); |
| 199 | compiled |
| 200 | .evaluate_with_env(ctx, &env) |
| 201 | .map_err(|e| FeelError::new_err(e.to_string()))? |
| 202 | }; |
| 203 | #[cfg(feature = "xpath-regex")] |
| 204 | let value = { |
| 205 | let env = EvalEnv::with_functions(&feel_core::RustRegex, now, registry); |
| 206 | compiled |
| 207 | .evaluate_with_env(ctx, &env) |
| 208 | .map_err(|e| FeelError::new_err(e.to_string()))? |
| 209 | }; |
| 210 | |
| 211 | if strict && value.contains_error() { |
| 212 | return Err(FeelError::new_err( |
| 213 | "evaluation produced a null from a type or domain error", |
| 214 | )); |
| 215 | } |
| 216 | value_to_py(py, &value) |
| 217 | } |
| 218 | |
| 219 | /// The evaluation instant for `now()`/`today()`: the system clock as a fixed-offset |
| 220 | /// UTC `Zoned`, so `now()` serialises as `…+00:00`. |
| 221 | fn now_zoned() -> jiff::Zoned { |
| 222 | let utc = jiff::tz::TimeZone::fixed(jiff::tz::Offset::UTC); |
| 223 | jiff::Timestamp::now().to_zoned(utc) |
| 224 | } |
| 225 | |
| 226 | // --------------------------------------------------------------------------- // |
| 227 | // Context mapping (Python -> feel-core Context/Value) |
| 228 | // --------------------------------------------------------------------------- // |
| 229 | |
| 230 | /// Build a [`Context`] from the top-level Python value. `None` is the empty |
| 231 | /// context; a `dict` or an object maps to a context (its top-level members |
| 232 | /// shallow-converted, so nested objects become lazy `Foreign`s); anything else is |
| 233 | /// an error. |
| 234 | fn context_to_ctx(context: Option<&Bound<'_, PyAny>>) -> PyResult<Context> { |
| 235 | let Some(obj) = context else { |
| 236 | return Ok(Context::new()); |
| 237 | }; |
| 238 | if obj.is_none() { |
| 239 | return Ok(Context::new()); |
| 240 | } |
| 241 | match py_force(obj)? { |
| 242 | Value::Context(map) => { |
| 243 | let mut ctx = Context::new(); |
| 244 | for (k, v) in map { |
| 245 | ctx.insert(k, v); |
| 246 | } |
| 247 | Ok(ctx) |
| 248 | } |
| 249 | _ => Err(FeelError::new_err( |
| 250 | "context must be a mapping or an object with attributes", |
| 251 | )), |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | /// Convert a single Python value to a [`Value`] **shallowly** (ADR-21): scalars and |
| 256 | /// temporal values eagerly; a `list`/`tuple` to a `Value::List` whose elements are |
| 257 | /// themselves shallow (so an object element becomes a lazy `Foreign`); a `dict` or |
| 258 | /// any other object to a `Value::Foreign` resolved on demand. Nothing is walked |
| 259 | /// beyond this one level. |
| 260 | fn shallow_convert(obj: &Bound<'_, PyAny>) -> PyResult<Value> { |
| 261 | if obj.is_none() { |
| 262 | return Ok(Value::Null); |
| 263 | } |
| 264 | // bool MUST be checked before int — in Python `bool` is a subclass of `int`. |
| 265 | if let Ok(b) = obj.cast::<PyBool>() { |
| 266 | return Ok(Value::Boolean(b.is_true())); |
| 267 | } |
| 268 | if let Ok(i) = obj.cast::<PyInt>() { |
| 269 | return Ok(Value::Number(i.extract::<f64>()?)); |
| 270 | } |
| 271 | if let Ok(f) = obj.cast::<PyFloat>() { |
| 272 | return Ok(Value::Number(f.extract::<f64>()?)); |
| 273 | } |
| 274 | if obj.cast::<PyString>().is_ok() { |
| 275 | return Ok(Value::String(obj.extract::<String>()?)); |
| 276 | } |
| 277 | if let Some(v) = py_temporal_to_value(obj)? { |
| 278 | return Ok(v); |
| 279 | } |
| 280 | if let Ok(list) = obj.cast::<PyList>() { |
| 281 | let mut items = Vec::with_capacity(list.len()); |
| 282 | for item in list.iter() { |
| 283 | items.push(shallow_convert(&item)?); |
| 284 | } |
| 285 | return Ok(Value::List(items)); |
| 286 | } |
| 287 | if let Ok(tuple) = obj.cast::<PyTuple>() { |
| 288 | let mut items = Vec::with_capacity(tuple.len()); |
| 289 | for item in tuple.iter() { |
| 290 | items.push(shallow_convert(&item)?); |
| 291 | } |
| 292 | return Ok(Value::List(items)); |
| 293 | } |
| 294 | // A Python callable (function, lambda, bound method, callable object) becomes a |
| 295 | // FEEL function value the host can invoke (ADR-23). Checked after the data types |
| 296 | // above so a normal mapping/object still maps to a lazy `Foreign`. |
| 297 | if obj.is_callable() { |
| 298 | return Ok(Func::Foreign(Arc::new(PyForeignFn { |
| 299 | obj: obj.clone().unbind(), |
| 300 | })) |
| 301 | .into_value()); |
| 302 | } |
| 303 | // A `dict` or any other object: wrap lazily; members resolve on access. |
| 304 | Ok(Value::Foreign(Foreign(Arc::new(PyForeign { |
| 305 | obj: obj.clone().unbind(), |
| 306 | })))) |
| 307 | } |
| 308 | |
| 309 | /// Resolve one member of a Python value by name — the FEEL dot (ADR-21). A `dict` |
| 310 | /// is keyed (`__getitem__`); any other object uses attribute access, which fires |
| 311 | /// `@property`/descriptors so an ORM relation loads on demand. An absent key or a |
| 312 | /// raised `AttributeError` is a value-null. The returned value is shallow. |
| 313 | fn py_get_member(obj: &Bound<'_, PyAny>, key: &str) -> PyResult<Value> { |
| 314 | if let Ok(dict) = obj.cast::<PyDict>() { |
| 315 | return match dict.get_item(key)? { |
| 316 | Some(v) => shallow_convert(&v), |
| 317 | None => Ok(Value::Null), |
| 318 | }; |
| 319 | } |
| 320 | match obj.getattr(key) { |
| 321 | Ok(v) => shallow_convert(&v), |
| 322 | Err(_) => Ok(Value::Null), |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | /// Materialise a Python value *one level* into a concrete [`Value`] (ADR-21): a |
| 327 | /// `dict` to a `Value::Context` of its items; any other object to a context of its |
| 328 | /// instance `__dict__` (data only, `_`-prefixed keys skipped — no `@property` |
| 329 | /// sweep, mirroring the old eager rule but only when a bulk view is actually |
| 330 | /// needed). A `__slots__` object (no `__dict__`) is not introspectable -> null. |
| 331 | /// Members are shallow-converted, so nested objects stay lazy. |
| 332 | fn py_force(obj: &Bound<'_, PyAny>) -> PyResult<Value> { |
| 333 | if let Ok(dict) = obj.cast::<PyDict>() { |
| 334 | let mut map = BTreeMap::new(); |
| 335 | for (k, v) in dict.iter() { |
| 336 | map.insert(key_to_string(&k)?, shallow_convert(&v)?); |
| 337 | } |
| 338 | return Ok(Value::Context(map)); |
| 339 | } |
| 340 | if let Ok(attrs) = obj.getattr("__dict__") { |
| 341 | if let Ok(dict) = attrs.cast::<PyDict>() { |
| 342 | let mut map = BTreeMap::new(); |
| 343 | for (k, v) in dict.iter() { |
| 344 | let key = key_to_string(&k)?; |
| 345 | if key.starts_with('_') { |
| 346 | continue; |
| 347 | } |
| 348 | map.insert(key, shallow_convert(&v)?); |
| 349 | } |
| 350 | return Ok(Value::Context(map)); |
| 351 | } |
| 352 | } |
| 353 | Ok(Value::Null) |
| 354 | } |
| 355 | |
| 356 | /// A lazily-resolved Python object behind feel-core's [`ForeignObject`] seam. Holds |
| 357 | /// a GIL-independent `Py<PyAny>`; each access reattaches via `Python::attach`, |
| 358 | /// which is cheap and reentrant because evaluation already holds the GIL. |
| 359 | #[derive(Debug)] |
| 360 | struct PyForeign { |
| 361 | obj: Py<PyAny>, |
| 362 | } |
| 363 | |
| 364 | impl ForeignObject for PyForeign { |
| 365 | fn get(&self, key: &str) -> Value { |
| 366 | Python::attach(|py| py_get_member(self.obj.bind(py), key).unwrap_or(Value::Null)) |
| 367 | } |
| 368 | |
| 369 | fn force(&self) -> Value { |
| 370 | Python::attach(|py| py_force(self.obj.bind(py)).unwrap_or(Value::Null)) |
| 371 | } |
| 372 | |
| 373 | fn as_any(&self) -> &dyn std::any::Any { |
| 374 | self |
| 375 | } |
| 376 | |
| 377 | /// Python object identity for cycle detection in unbounded traversals (the |
| 378 | /// descendant `...` operator). feel-py mints a fresh `Arc<PyForeign>` per wrap |
| 379 | /// (`shallow_convert` re-runs on every `force`/`get`), so the Rust allocation |
| 380 | /// address is *not* stable; the underlying Python object's pointer (= `id()`, |
| 381 | /// preserved across `Py::clone`) is. It is stable for the object's lifetime, and |
| 382 | /// the traversal holds `Py<PyAny>` clones keeping it alive, so the address cannot |
| 383 | /// be recycled mid-traversal. |
| 384 | fn identity(&self) -> usize { |
| 385 | self.obj.as_ptr() as usize |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | // --------------------------------------------------------------------------- // |
| 390 | // Host callables (ADR-23): a Python callable invoked from FEEL |
| 391 | // --------------------------------------------------------------------------- // |
| 392 | |
| 393 | /// A Python callable behind feel-core's [`ForeignFunction`] seam. Holds a |
| 394 | /// GIL-independent `Py<PyAny>`; the call reattaches via `Python::attach`. |
| 395 | #[derive(Debug)] |
| 396 | struct PyForeignFn { |
| 397 | obj: Py<PyAny>, |
| 398 | } |
| 399 | |
| 400 | impl ForeignFunction for PyForeignFn { |
| 401 | fn call(&self, args: Args) -> Value { |
| 402 | Python::attach(|py| py_call(self.obj.bind(py), args).unwrap_or(Value::Error)) |
| 403 | } |
| 404 | |
| 405 | fn as_any(&self) -> &dyn std::any::Any { |
| 406 | self |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | /// Invoke a Python callable, mapping FEEL arguments to `f(*positional, **named)` |
| 411 | /// (ADR-23): positional FEEL args become positional Python args, named FEEL args |
| 412 | /// become keyword arguments — so the host's defaults, keyword-only and |
| 413 | /// positional-only parameters all apply naturally. A raised exception (including a |
| 414 | /// `TypeError` for a missing/unknown/duplicate argument) is an error-null. |
| 415 | fn py_call(obj: &Bound<'_, PyAny>, args: Args) -> PyResult<Value> { |
| 416 | let py = obj.py(); |
| 417 | let mut positional = Vec::with_capacity(args.positional.len()); |
| 418 | for v in &args.positional { |
| 419 | positional.push(value_to_py(py, v)?); |
| 420 | } |
| 421 | let pos = PyTuple::new(py, positional)?; |
| 422 | let result = if args.named.is_empty() { |
| 423 | obj.call1(&pos)? |
| 424 | } else { |
| 425 | let kwargs = PyDict::new(py); |
| 426 | for (name, v) in &args.named { |
| 427 | kwargs.set_item(name, value_to_py(py, v)?)?; |
| 428 | } |
| 429 | obj.call(&pos, Some(&kwargs))? |
| 430 | }; |
| 431 | // Convert the result shallowly, so a returned object stays a lazy `Foreign`. |
| 432 | shallow_convert(&result) |
| 433 | } |
| 434 | |
| 435 | /// A host function registry backed by a Python mapping `name -> callable` (the |
| 436 | /// `functions=` argument; ADR-23). The ambient-function path, beside binding a |
| 437 | /// callable directly in the context. `None` means no registry was supplied. |
| 438 | #[derive(Debug)] |
| 439 | struct PyFunctionRegistry { |
| 440 | funcs: Option<Py<PyAny>>, |
| 441 | } |
| 442 | |
| 443 | impl FunctionRegistry for PyFunctionRegistry { |
| 444 | fn get(&self, name: &str) -> Option<Arc<dyn ForeignFunction>> { |
| 445 | let funcs = self.funcs.as_ref()?; |
| 446 | Python::attach(|py| { |
| 447 | let item = funcs.bind(py).get_item(name).ok()?; |
| 448 | item.is_callable().then(|| { |
| 449 | Arc::new(PyForeignFn { obj: item.unbind() }) as Arc<dyn ForeignFunction> |
| 450 | }) |
| 451 | }) |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | /// A context key as a string: the natural key if it is a `str`, else its `str()`. |
| 456 | fn key_to_string(key: &Bound<'_, PyAny>) -> PyResult<String> { |
| 457 | if let Ok(s) = key.extract::<String>() { |
| 458 | return Ok(s); |
| 459 | } |
| 460 | key.str()?.into_any().extract::<String>() |
| 461 | } |
| 462 | |
| 463 | /// Detect and map a Python temporal value to a FEEL temporal [`Value`] via the |
| 464 | /// canonical ISO bridge (ADR-18). Returns `None` if `obj` is not temporal. |
| 465 | fn py_temporal_to_value(obj: &Bound<'_, PyAny>) -> PyResult<Option<Value>> { |
| 466 | let py = obj.py(); |
| 467 | let dt = py.import("datetime")?; |
| 468 | // datetime before date: `datetime` is a subclass of `date`. |
| 469 | if obj.is_instance(&dt.getattr("datetime")?)? { |
| 470 | let iso: String = obj.call_method0("isoformat")?.extract()?; |
| 471 | return Ok(feel_core::temporal_from_iso("date and time", &iso)); |
| 472 | } |
| 473 | if obj.is_instance(&dt.getattr("date")?)? { |
| 474 | let iso: String = obj.call_method0("isoformat")?.extract()?; |
| 475 | return Ok(feel_core::temporal_from_iso("date", &iso)); |
| 476 | } |
| 477 | if obj.is_instance(&dt.getattr("time")?)? { |
| 478 | let iso: String = obj.call_method0("isoformat")?.extract()?; |
| 479 | return Ok(feel_core::temporal_from_iso("time", &iso)); |
| 480 | } |
| 481 | if obj.is_instance(&dt.getattr("timedelta")?)? { |
| 482 | let days: i64 = obj.getattr("days")?.extract()?; |
| 483 | let seconds: i64 = obj.getattr("seconds")?.extract()?; |
| 484 | let micros: i64 = obj.getattr("microseconds")?.extract()?; |
| 485 | let total_secs = days * 86_400 + seconds; |
| 486 | let nanos = (micros * 1_000) as i32; |
| 487 | return Ok(Some(Value::DaysTimeDuration(jiff::SignedDuration::new( |
| 488 | total_secs, nanos, |
| 489 | )))); |
| 490 | } |
| 491 | // years-months-duration has no native type: map dateutil.relativedelta's |
| 492 | // years/months (other fields are ignored — FEEL has no mixed duration). |
| 493 | if let Ok(rd_mod) = py.import("dateutil.relativedelta") { |
| 494 | if obj.is_instance(&rd_mod.getattr("relativedelta")?)? { |
| 495 | let years: i64 = obj.getattr("years")?.extract()?; |
| 496 | let months: i64 = obj.getattr("months")?.extract()?; |
| 497 | return Ok(Some(Value::YearsMonthsDuration(years * 12 + months))); |
| 498 | } |
| 499 | } |
| 500 | Ok(None) |
| 501 | } |
| 502 | |
| 503 | // --------------------------------------------------------------------------- // |
| 504 | // Result mapping (feel-core Value -> native Python) |
| 505 | // --------------------------------------------------------------------------- // |
| 506 | |
| 507 | /// Map a `feel-core` [`Value`] to a native Python object. Integral numbers become |
| 508 | /// `int` (so `1 + 1` is `2`, not `2.0`); temporal values become the native |
| 509 | /// `datetime`/`dateutil` types (ADR-18); error/value nulls become `None`. |
| 510 | fn value_to_py<'py>(py: Python<'py>, value: &Value) -> PyResult<Bound<'py, PyAny>> { |
| 511 | Ok(match value { |
| 512 | Value::Number(n) => number_to_py(py, *n), |
| 513 | Value::Boolean(b) => PyBool::new(py, *b).to_owned().into_any(), |
| 514 | Value::String(s) => PyString::new(py, s).into_any(), |
| 515 | Value::Null | Value::Error => py.None().into_bound(py), |
| 516 | Value::List(items) => { |
| 517 | let list = PyList::empty(py); |
| 518 | for item in items { |
| 519 | list.append(value_to_py(py, item)?)?; |
| 520 | } |
| 521 | list.into_any() |
| 522 | } |
| 523 | Value::Context(map) => { |
| 524 | let dict = PyDict::new(py); |
| 525 | for (k, v) in map { |
| 526 | dict.set_item(k, value_to_py(py, v)?)?; |
| 527 | } |
| 528 | dict.into_any() |
| 529 | } |
| 530 | // A range has no native Python type; hand it back as a dict carrying DMN's |
| 531 | // four range properties (§10.3.4.6), so `r["start included"]` reads naturally. |
| 532 | Value::Range(r) => { |
| 533 | // An unbounded endpoint (`[1..)`/`(..10]`; ADR-31) maps to host `None` and |
| 534 | // is never `included` (`±∞` is no member), regardless of the bracket. |
| 535 | let dict = PyDict::new(py); |
| 536 | dict.set_item("start", value_to_py(py, r.start.as_ref().unwrap_or(&Value::Null))?)?; |
| 537 | dict.set_item("end", value_to_py(py, r.end.as_ref().unwrap_or(&Value::Null))?)?; |
| 538 | dict.set_item("start included", r.start.is_some() && !r.start_open)?; |
| 539 | dict.set_item("end included", r.end.is_some() && !r.end_open)?; |
| 540 | dict.into_any() |
| 541 | } |
| 542 | Value::Date(d) => { |
| 543 | let dt = py.import("datetime")?; |
| 544 | dt.getattr("date")? |
| 545 | .call1((d.year() as i32, d.month() as i32, d.day() as i32))? |
| 546 | } |
| 547 | Value::Time(t) => { |
| 548 | let dt = py.import("datetime")?; |
| 549 | let tz = zone_to_tzinfo(py, &dt, &t.zone)?; |
| 550 | dt.getattr("time")?.call1(( |
| 551 | t.time.hour() as i32, |
| 552 | t.time.minute() as i32, |
| 553 | t.time.second() as i32, |
| 554 | t.time.subsec_nanosecond() / 1_000, |
| 555 | tz, |
| 556 | ))? |
| 557 | } |
| 558 | Value::DateTime(x) => { |
| 559 | let dt = py.import("datetime")?; |
| 560 | let tz = zone_to_tzinfo(py, &dt, &x.zone)?; |
| 561 | let d = x.dt.date(); |
| 562 | let ti = x.dt.time(); |
| 563 | dt.getattr("datetime")?.call1(( |
| 564 | d.year() as i32, |
| 565 | d.month() as i32, |
| 566 | d.day() as i32, |
| 567 | ti.hour() as i32, |
| 568 | ti.minute() as i32, |
| 569 | ti.second() as i32, |
| 570 | ti.subsec_nanosecond() / 1_000, |
| 571 | tz, |
| 572 | ))? |
| 573 | } |
| 574 | Value::YearsMonthsDuration(months) => { |
| 575 | let rd = py.import("dateutil.relativedelta")?.getattr("relativedelta")?; |
| 576 | let kw = PyDict::new(py); |
| 577 | kw.set_item("months", *months)?; |
| 578 | rd.call((), Some(&kw))? |
| 579 | } |
| 580 | Value::DaysTimeDuration(sd) => { |
| 581 | let dt = py.import("datetime")?; |
| 582 | dt.getattr("timedelta")?.call1(( |
| 583 | 0_i64, |
| 584 | sd.as_secs(), |
| 585 | (sd.subsec_nanos() / 1_000) as i64, |
| 586 | ))? |
| 587 | } |
| 588 | // Identity pass-through (ADR-21): a lazy host value that reached the result |
| 589 | // is handed back as the *original* object, untouched — no materialisation, |
| 590 | // no re-traversal. The downcast cannot miss (`PyForeign` is the only impl); |
| 591 | // fall back to forcing if it ever does. |
| 592 | Value::Foreign(f) => match f.0.as_any().downcast_ref::<PyForeign>() { |
| 593 | Some(pf) => pf.obj.clone_ref(py).into_bound(py), |
| 594 | None => value_to_py(py, &f.0.force())?, |
| 595 | }, |
| 596 | // A function value (ADR-23): a host callable is handed back as the original |
| 597 | // Python callable (identity pass-through); a native FEEL closure has no |
| 598 | // Python representation and crosses out as `None`. |
| 599 | Value::Function(f) => match &**f { |
| 600 | Func::Foreign(host_fn) => match host_fn.as_any().downcast_ref::<PyForeignFn>() { |
| 601 | Some(pf) => pf.obj.clone_ref(py).into_bound(py), |
| 602 | None => py.None().into_bound(py), |
| 603 | }, |
| 604 | Func::Closure(_) | Func::Builtin(_) => py.None().into_bound(py), |
| 605 | }, |
| 606 | // An opaque comparison-test value `(< 10)` (ADR-32) has no native Python type; |
| 607 | // like a native FEEL closure it crosses out as `None`. |
| 608 | Value::UnaryTestVal(_) => py.None().into_bound(py), |
| 609 | }) |
| 610 | } |
| 611 | |
| 612 | fn number_to_py<'py>(py: Python<'py>, n: f64) -> Bound<'py, PyAny> { |
| 613 | if n.is_finite() && n.fract() == 0.0 && n.abs() < 9.007_199_254_740_992e15 { |
| 614 | (n as i64) |
| 615 | .into_pyobject(py) |
| 616 | .expect("i64 -> int is infallible") |
| 617 | .into_any() |
| 618 | } else { |
| 619 | n.into_pyobject(py) |
| 620 | .expect("f64 -> float is infallible") |
| 621 | .into_any() |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | /// Build a Python `tzinfo` for a FEEL zone: `Utc` -> `timezone.utc`, an offset -> |
| 626 | /// `timezone(timedelta)`, a named zone -> `zoneinfo.ZoneInfo` (falling back to |
| 627 | /// `None` if the zone cannot be resolved). |
| 628 | fn zone_to_tzinfo<'py>( |
| 629 | py: Python<'py>, |
| 630 | dt: &Bound<'py, PyModule>, |
| 631 | zone: &Option<feel_core::temporal::Zone>, |
| 632 | ) -> PyResult<Bound<'py, PyAny>> { |
| 633 | use feel_core::temporal::Zone; |
| 634 | Ok(match zone { |
| 635 | None => py.None().into_bound(py), |
| 636 | Some(Zone::Utc) => dt.getattr("timezone")?.getattr("utc")?, |
| 637 | Some(Zone::Offset(o)) => { |
| 638 | let td = dt.getattr("timedelta")?.call1((0_i64, o.seconds() as i64))?; |
| 639 | dt.getattr("timezone")?.call1((td,))? |
| 640 | } |
| 641 | Some(Zone::Named(name)) => match py |
| 642 | .import("zoneinfo") |
| 643 | .and_then(|zi| zi.getattr("ZoneInfo")?.call1((name.as_str(),))) |
| 644 | { |
| 645 | Ok(z) => z, |
| 646 | Err(_) => py.None().into_bound(py), |
| 647 | }, |
| 648 | }) |
| 649 | } |
| 650 | |
| 651 | // --------------------------------------------------------------------------- // |
| 652 | // Host regex provider (ADR-16): Python `re` |
| 653 | // --------------------------------------------------------------------------- // |
| 654 | |
| 655 | /// Python-`re`-backed [`FeelRegex`]. Holds the GIL token, since the regex builtins |
| 656 | /// call back into Python during evaluation. A `None` means the pattern/flags were |
| 657 | /// invalid in the Python dialect, which maps to a FEEL null. |
| 658 | #[cfg(not(feature = "xpath-regex"))] |
| 659 | struct PyRegex<'py> { |
| 660 | py: Python<'py>, |
| 661 | } |
| 662 | |
| 663 | #[cfg(not(feature = "xpath-regex"))] |
| 664 | impl PyRegex<'_> { |
| 665 | /// Compile `pattern` with FEEL flags into a Python `re.Pattern`, or `Ok(None)` |
| 666 | /// if a flag letter is outside `i s m x q` or the pattern does not compile. |
| 667 | /// `i/s/m/x` are passed as inline `(?…)` flags; `q` escapes the pattern. |
| 668 | fn compiled<'a>(&'a self, pattern: &str, flags: &str) -> PyResult<Option<Bound<'a, PyAny>>> { |
| 669 | let mut inline = String::new(); |
| 670 | for c in flags.chars() { |
| 671 | match c { |
| 672 | 'i' | 's' | 'm' | 'x' => inline.push(c), |
| 673 | 'q' => {} // handled via re.escape below |
| 674 | _ => return Ok(None), |
| 675 | } |
| 676 | } |
| 677 | let re = self.py.import("re")?; |
| 678 | let pat = if flags.contains('q') { |
| 679 | re.getattr("escape")?.call1((pattern,))?.extract::<String>()? |
| 680 | } else { |
| 681 | pattern.to_string() |
| 682 | }; |
| 683 | let pat = if inline.is_empty() { |
| 684 | pat |
| 685 | } else { |
| 686 | format!("(?{inline}){pat}") |
| 687 | }; |
| 688 | match re.getattr("compile")?.call1((pat,)) { |
| 689 | Ok(compiled) => Ok(Some(compiled)), |
| 690 | Err(_) => Ok(None), // invalid pattern in the Python dialect -> FEEL null |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | fn do_is_match(&self, input: &str, pattern: &str, flags: &str) -> PyResult<Option<bool>> { |
| 695 | let Some(compiled) = self.compiled(pattern, flags)? else { |
| 696 | return Ok(None); |
| 697 | }; |
| 698 | let m = compiled.call_method1("search", (input,))?; |
| 699 | Ok(Some(!m.is_none())) |
| 700 | } |
| 701 | |
| 702 | fn do_replace( |
| 703 | &self, |
| 704 | input: &str, |
| 705 | pattern: &str, |
| 706 | replacement: &str, |
| 707 | flags: &str, |
| 708 | ) -> PyResult<Option<String>> { |
| 709 | let Some(compiled) = self.compiled(pattern, flags)? else { |
| 710 | return Ok(None); |
| 711 | }; |
| 712 | // `Pattern.sub` replaces all matches (matching XPath `replace`). |
| 713 | let out = compiled.call_method1("sub", (xpath_replacement_to_python(replacement), input))?; |
| 714 | Ok(Some(out.extract()?)) |
| 715 | } |
| 716 | |
| 717 | fn do_split(&self, input: &str, delimiter: &str) -> PyResult<Option<Vec<String>>> { |
| 718 | let re = self.py.import("re")?; |
| 719 | // Edge: a capturing group in `delimiter` makes `re.split` include the |
| 720 | // captures (XPath does not); such a delimiter then extracts as non-`str` |
| 721 | // and yields `None` (FEEL null). Documented divergence. |
| 722 | match re.getattr("split")?.call1((delimiter, input)) { |
| 723 | Ok(parts) => Ok(Some(parts.extract::<Vec<String>>()?)), |
| 724 | Err(_) => Ok(None), |
| 725 | } |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | #[cfg(not(feature = "xpath-regex"))] |
| 730 | impl FeelRegex for PyRegex<'_> { |
| 731 | fn is_match(&self, input: &str, pattern: &str, flags: &str) -> Option<bool> { |
| 732 | self.do_is_match(input, pattern, flags).ok().flatten() |
| 733 | } |
| 734 | |
| 735 | fn replace(&self, input: &str, pattern: &str, replacement: &str, flags: &str) -> Option<String> { |
| 736 | self.do_replace(input, pattern, replacement, flags).ok().flatten() |
| 737 | } |
| 738 | |
| 739 | fn split(&self, input: &str, delimiter: &str) -> Option<Vec<String>> { |
| 740 | self.do_split(input, delimiter).ok().flatten() |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | /// Translate an XPath/FEEL replacement string to Python `re` replacement syntax: |
| 745 | /// `$N` group references become `\g<N>`, `$$` becomes a literal `$`, and a literal |
| 746 | /// backslash is doubled so Python does not interpret it. Pendant to feel-core's |
| 747 | /// `xpath_replacement_to_rust`. |
| 748 | #[cfg(not(feature = "xpath-regex"))] |
| 749 | fn xpath_replacement_to_python(repl: &str) -> String { |
| 750 | let mut out = String::with_capacity(repl.len()); |
| 751 | let mut chars = repl.chars().peekable(); |
| 752 | while let Some(c) = chars.next() { |
| 753 | match c { |
| 754 | '\\' => out.push_str("\\\\"), |
| 755 | '$' => match chars.peek() { |
| 756 | Some('$') => { |
| 757 | chars.next(); |
| 758 | out.push('$'); |
| 759 | } |
| 760 | Some(d) if d.is_ascii_digit() => { |
| 761 | let mut num = String::new(); |
| 762 | while let Some(d) = chars.peek() { |
| 763 | if d.is_ascii_digit() { |
| 764 | num.push(*d); |
| 765 | chars.next(); |
| 766 | } else { |
| 767 | break; |
| 768 | } |
| 769 | } |
| 770 | out.push_str(&format!("\\g<{num}>")); |
| 771 | } |
| 772 | _ => out.push('$'), |
| 773 | }, |
| 774 | _ => out.push(c), |
| 775 | } |
| 776 | } |
| 777 | out |
| 778 | } |
| 779 | |
| 780 | // --------------------------------------------------------------------------- // |
| 781 | // Module |
| 782 | // --------------------------------------------------------------------------- // |
| 783 | |
| 784 | #[pymodule] |
| 785 | fn _feel(m: &Bound<'_, PyModule>) -> PyResult<()> { |
| 786 | m.add_function(wrap_pyfunction!(evaluate, m)?)?; |
| 787 | m.add_function(wrap_pyfunction!(evaluate_strict, m)?)?; |
| 788 | m.add_function(wrap_pyfunction!(compile, m)?)?; |
| 789 | m.add_class::<CompiledExpr>()?; |
| 790 | m.add("FeelError", m.py().get_type::<FeelError>())?; |
| 791 | Ok(()) |
| 792 | } |
| 793 | |
| 794 | #[cfg(test)] |
| 795 | mod tests { |
| 796 | // Boundary helpers that need no Python runtime are unit-tested here; behaviour |
| 797 | // that needs the interpreter is covered by the pytest suite (tests/). |
| 798 | #[cfg(not(feature = "xpath-regex"))] |
| 799 | use super::xpath_replacement_to_python; |
| 800 | |
| 801 | #[test] |
| 802 | #[cfg(not(feature = "xpath-regex"))] |
| 803 | fn replacement_group_refs() { |
| 804 | assert_eq!(xpath_replacement_to_python("$1"), "\\g<1>"); |
| 805 | assert_eq!(xpath_replacement_to_python("$12-$2"), "\\g<12>-\\g<2>"); |
| 806 | assert_eq!(xpath_replacement_to_python("$$"), "$"); |
| 807 | assert_eq!(xpath_replacement_to_python("a$1b"), "a\\g<1>b"); |
| 808 | assert_eq!(xpath_replacement_to_python("\\"), "\\\\"); |
| 809 | assert_eq!(xpath_replacement_to_python("$"), "$"); |
| 810 | } |
| 811 | } |