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 · 29.9 KB · at 90f493059be5 · raw

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