Public repository: timo / feel

Reader

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

feel / crates / feel-py / src / lib.rs · 33.6 KB · at da382279c66c · raw

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