Public repository: timo / feel

Reader

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

Outline: 7 definitions
1
//! The lazy host-value seam: an opaque [`Value::Foreign`] resolved on demand.
2
//!
3
//! A wrapper crate (feel-py, feel-wasm) can hand the evaluator a *host* object
4
//! (a Python `PyObject`, a JS `JsValue`) wrapped behind [`ForeignObject`] instead
5
//! of eagerly materialising the whole object graph at the boundary. The FEEL dot
6
//! (`order.customer.address`) then resolves one segment at a time via
7
//! [`get`](ForeignObject::get), while any *other* operation
8
//! [`force`](ForeignObject::force)s the node into a concrete [`Value`] first.
9
//!
10
//! `feel-core` never constructs a `Foreign`, so a pure-Rust embedder never sees
11
//! one and pays nothing: the variant is a 16-byte fat pointer (no larger than the
12
//! existing `String`/`Vec`/`Context` variants, so [`Value`] does not grow), and
13
//! the force checks compile to a single, predicted tag test that always falls
14
//! through. This keeps the cardinal rule (ADR-1) intact — the trait is std-only
15
//! and target-agnostic, exactly like the [`FeelRegex`](crate::FeelRegex) seam
16
//! (ADR-16). See ADR-21.
17
18
use std::any::Any;
19
use std::fmt;
20
use std::sync::Arc;
21
22
use crate::value::Value;
23
24
/// A host value resolved lazily. Implemented per target (feel-py's `PyForeign`,
25
/// feel-wasm's `JsForeign`).
26
///
27
/// The contract is:
28
///
29
/// * [`get`](ForeignObject::get) is the FEEL dot — *by-name* access. It may fire
30
///   host descriptors/getters (a Python `@property`, a JS accessor), so an ORM
31
///   relation loads on demand. An absent member is a value-null ([`Value::Null`]),
32
///   like a missing context key. Returned values are *shallow*: a nested object
33
///   stays a `Foreign`.
34
/// * [`force`](ForeignObject::force) materialises this node **one level** for any
35
///   non-path use (arithmetic, comparison, iteration, builtins, output). It
36
///   enumerates own *instance data* only — never a blanket property sweep — and
37
///   must return a concrete [`Value`] (never another `Foreign`); its children may
38
///   themselves be `Foreign`, so laziness stays incremental.
39
/// * [`as_any`](ForeignObject::as_any) lets a wrapper recover its own host handle
40
///   for identity pass-through on output (return the original object untouched
41
///   instead of re-materialising it).
42
pub trait ForeignObject: fmt::Debug {
43
    /// Resolve a single member by name (the FEEL dot). Absent -> [`Value::Null`].
44
    fn get(&self, key: &str) -> Value;
45
46
    /// Materialise this node one level into a concrete (non-`Foreign`) [`Value`].
47
    fn force(&self) -> Value;
48
49
    /// Recover the concrete host handle (for identity pass-through on output).
50
    fn as_any(&self) -> &dyn Any;
51
52
    /// Stable identity for cycle detection in *unbounded* traversals — currently
53
    /// only the descendant operator `e ... name` ([`crate::eval`]'s
54
    /// `descendant_collect`). The engine keeps a visited-set keyed on this `usize`
55
    /// to break back-edges in a cyclic host graph; pure-Rust FEEL values are owned
56
    /// trees and cannot cycle, so only an `Arc`-backed `Foreign` handle can.
57
    ///
58
    /// The default is the Rust allocation address. That is correct only for hosts
59
    /// that **intern** their wrappers (one `Arc` per host object) or that can never
60
    /// form cycles. A host that mints a *fresh* `Arc` per access (feel-py, feel-lua,
61
    /// feel-wasm — they wrap via `Arc::new` on every `force`/`get`) **and** whose
62
    /// host objects can be cyclic MUST override this with the underlying object's
63
    /// own identity, so two wrappers around the *same* host object compare equal:
64
    /// feel-py returns `self.obj.as_ptr()` (= Python `id()`); feel-wasm uses a
65
    /// JS-side `WeakMap<object, number>`. feel-pg is exempt — `jsonb` is a
66
    /// serialized value tree and cannot cycle.
67
    fn identity(&self) -> usize {
68
        // `self` is a `&dyn ForeignObject` (fat pointer); cast through the thin data
69
        // pointer to the object's address. This is the Rust *allocation* address, so
70
        // it is a sound identity only when one `Arc` maps to one host object — hosts
71
        // that mint a fresh `Arc` per access must override (see the doc above).
72
        std::ptr::addr_of!(*self) as *const () as usize
73
    }
74
}
75
76
/// A reference-counted [`ForeignObject`] carried inside [`Value::Foreign`].
77
///
78
/// The newtype exists so [`Value`] keeps its `#[derive(Debug, Clone, PartialEq)]`:
79
/// a bare `Arc<dyn ForeignObject>` is neither `Debug` nor `PartialEq`, but this
80
/// wrapper hand-implements both. `PartialEq` here is **structural identity** (the
81
/// same `Arc`), *not* FEEL equality — FEEL `=` goes through `feel_equal`
82
/// (force-then-compare). The derive only needs *some* sound equivalence, e.g. for
83
/// `Context` comparison and tests.
84
#[derive(Clone)]
85
pub struct Foreign(pub Arc<dyn ForeignObject>);
86
87
impl PartialEq for Foreign {
88
    fn eq(&self, other: &Self) -> bool {
89
        Arc::ptr_eq(&self.0, &other.0)
90
    }
91
}
92
93
impl fmt::Debug for Foreign {
94
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95
        self.0.fmt(f)
96
    }
97
}