Public repository: timo / feel

Reader

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

feat(wrappers): lazy context mapping — on-demand resolution + identity pass-through

public

feat(wrappers): lazy context mapping — on-demand resolution + identity pass-through

feel-py and feel-wasm now wrap host objects behind feel-core's `ForeignObject` seam
instead of eagerly walking the whole graph (RD-6 flipped). A dot resolves one hop at
a time via attribute access (`getattr` / `Reflect.get`), firing `@property`/accessor
getters so ORM relations load on demand; bulk `force` still reads instance data only.
A `Foreign` that reaches the result passes the original host object back by identity
(recovered via `as_any`) — no snapshot, no re-traversal. The eager input conversion
and both cycle/depth guards are removed: a finite expression navigates a finite path,
so cyclic graphs are harmless. feel-pg gains one defensive, unreachable `Foreign`
match arm.

Tests: feel-py pytest updated for lazy semantics (a getter fires on access, an
untouched sibling property does not, identity pass-through, cyclic finite path);
feel-wasm smoke gains the matching cases (Reflect.get getter, nested navigation,
pass-through identity, cyclic termination).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Changesetff653f7c0c0358d0a6b5591f0a18e5499eb4384f
Author (claimed)Timo Stolz <timo.stolz@gmail.com>,
Parentsc8dc741cee2d
Children
Pushlog
by timo via ssh

modified crates/feel-pg/src/lib.rs +3 −0

@@ -130,6 +130,9 @@
130130
         // Lenient: an error-null serialises like a plain null. Strict callers
131131
         // check `Value::contains_error` before reaching here.
132132
         Value::Null | Value::Error => serde_json::Value::Null,
133
+        // feel-pg never builds a `Foreign` (its input is JSONB, not host objects),
134
+        // so this is unreachable; map defensively to null rather than panic (ADR-21).
135
+        Value::Foreign(_) => serde_json::Value::Null,
133136
     }
134137
 }
135138
 

modified crates/feel-py/src/lib.rs +102 −60

@@ -15,17 +15,24 @@
1515
 //! purist `xpath-regex` feature instead re-bundles feel-core's `RustRegex` for
1616
 //! results identical to feel-core/TCK.
1717
 //!
18
-//! Context input (RD-6): conversion is **eager** at the boundary — feel-core
19
-//! evaluates against a fully materialised `Value` tree, never calling back into
20
-//! Python mid-evaluation. A `dict` maps by its keys; any other object maps via its
21
-//! instance `__dict__` (`vars(obj)`), reading only stored data — Python
22
-//! `@property`/descriptors live on the class and are therefore **never** fired, so
23
-//! no side effects / lazy-loads. A depth + identity guard breaks reference cycles
24
-//! (a back-edge becomes `null`).
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;
2529
 
2630
 use std::collections::BTreeMap;
2731
 
28
-use feel_core::{compile as core_compile, CompiledExpr as CoreCompiled, Context, EvalEnv, Value};
32
+use feel_core::{
33
+    compile as core_compile, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign,
34
+    ForeignObject, Value,
35
+};
2936
 #[cfg(not(feature = "xpath-regex"))]
3037
 use feel_core::FeelRegex;
3138
 use pyo3::exceptions::PyValueError;
@@ -33,10 +40,6 @@
3340
 use pyo3::types::{PyBool, PyDict, PyFloat, PyInt, PyList, PyString, PyTuple};
3441
 
3542
 pyo3::create_exception!(feel, FeelError, PyValueError);
36
-
37
-/// Maximum nesting depth converted from the Python context. A back-stop alongside
38
-/// the identity-based cycle guard; deeper than this maps to `null`.
39
-const MAX_DEPTH: usize = 256;
4043
 
4144
 // --------------------------------------------------------------------------- //
4245
 // Public API (free functions + the CompiledExpr class)
@@ -166,7 +169,9 @@
166169
 // --------------------------------------------------------------------------- //
167170
 
168171
 /// Build a [`Context`] from the top-level Python value. `None` is the empty
169
-/// context; a `dict` or an object maps to a context; anything else is an error.
172
+/// context; a `dict` or an object maps to a context (its top-level members
173
+/// shallow-converted, so nested objects become lazy `Foreign`s); anything else is
174
+/// an error.
170175
 fn context_to_ctx(context: Option<&Bound<'_, PyAny>>) -> PyResult<Context> {
171176
     let Some(obj) = context else {
172177
         return Ok(Context::new());
@@ -174,8 +179,7 @@
174179
     if obj.is_none() {
175180
         return Ok(Context::new());
176181
     }
177
-    let mut seen = Vec::new();
178
-    match py_to_value(obj, &mut seen, 0)? {
182
+    match py_force(obj)? {
179183
         Value::Context(map) => {
180184
             let mut ctx = Context::new();
181185
             for (k, v) in map {
@@ -189,10 +193,12 @@
189193
     }
190194
 }
191195
 
192
-/// Map a native Python value to a `feel-core` [`Value`]. Scalars, temporal types,
193
-/// `dict`/`list`/`tuple` and plain objects (via `__dict__`) are supported. `seen`
194
-/// holds the object ids on the current path (cycle guard); `depth` back-stops it.
195
-fn py_to_value(obj: &Bound<'_, PyAny>, seen: &mut Vec<usize>, depth: usize) -> PyResult<Value> {
196
+/// Convert a single Python value to a [`Value`] **shallowly** (ADR-21): scalars and
197
+/// temporal values eagerly; a `list`/`tuple` to a `Value::List` whose elements are
198
+/// themselves shallow (so an object element becomes a lazy `Foreign`); a `dict` or
199
+/// any other object to a `Value::Foreign` resolved on demand. Nothing is walked
200
+/// beyond this one level.
201
+fn shallow_convert(obj: &Bound<'_, PyAny>) -> PyResult<Value> {
196202
     if obj.is_none() {
197203
         return Ok(Value::Null);
198204
     }
@@ -212,65 +218,93 @@
212218
     if let Some(v) = py_temporal_to_value(obj)? {
213219
         return Ok(v);
214220
     }
215
-
216
-    // Containers / objects: guard against deep or cyclic graphs before recursing.
217
-    if depth > MAX_DEPTH {
218
-        return Ok(Value::Null);
219
-    }
220
-    let id = obj.as_ptr() as usize;
221
-    if seen.contains(&id) {
222
-        return Ok(Value::Null); // cycle back-edge
223
-    }
224
-
221
+    if let Ok(list) = obj.cast::<PyList>() {
222
+        let mut items = Vec::with_capacity(list.len());
223
+        for item in list.iter() {
224
+            items.push(shallow_convert(&item)?);
225
+        }
226
+        return Ok(Value::List(items));
227
+    }
228
+    if let Ok(tuple) = obj.cast::<PyTuple>() {
229
+        let mut items = Vec::with_capacity(tuple.len());
230
+        for item in tuple.iter() {
231
+            items.push(shallow_convert(&item)?);
232
+        }
233
+        return Ok(Value::List(items));
234
+    }
235
+    // A `dict` or any other object: wrap lazily; members resolve on access.
236
+    Ok(Value::Foreign(Foreign(Arc::new(PyForeign {
237
+        obj: obj.clone().unbind(),
238
+    }))))
239
+}
240
+
241
+/// Resolve one member of a Python value by name — the FEEL dot (ADR-21). A `dict`
242
+/// is keyed (`__getitem__`); any other object uses attribute access, which fires
243
+/// `@property`/descriptors so an ORM relation loads on demand. An absent key or a
244
+/// raised `AttributeError` is a value-null. The returned value is shallow.
245
+fn py_get_member(obj: &Bound<'_, PyAny>, key: &str) -> PyResult<Value> {
225246
     if let Ok(dict) = obj.cast::<PyDict>() {
226
-        seen.push(id);
247
+        return match dict.get_item(key)? {
248
+            Some(v) => shallow_convert(&v),
249
+            None => Ok(Value::Null),
250
+        };
251
+    }
252
+    match obj.getattr(key) {
253
+        Ok(v) => shallow_convert(&v),
254
+        Err(_) => Ok(Value::Null),
255
+    }
256
+}
257
+
258
+/// Materialise a Python value *one level* into a concrete [`Value`] (ADR-21): a
259
+/// `dict` to a `Value::Context` of its items; any other object to a context of its
260
+/// instance `__dict__` (data only, `_`-prefixed keys skipped — no `@property`
261
+/// sweep, mirroring the old eager rule but only when a bulk view is actually
262
+/// needed). A `__slots__` object (no `__dict__`) is not introspectable -> null.
263
+/// Members are shallow-converted, so nested objects stay lazy.
264
+fn py_force(obj: &Bound<'_, PyAny>) -> PyResult<Value> {
265
+    if let Ok(dict) = obj.cast::<PyDict>() {
227266
         let mut map = BTreeMap::new();
228267
         for (k, v) in dict.iter() {
229
-            map.insert(key_to_string(&k)?, py_to_value(&v, seen, depth + 1)?);
230
-        }
231
-        seen.pop();
268
+            map.insert(key_to_string(&k)?, shallow_convert(&v)?);
269
+        }
232270
         return Ok(Value::Context(map));
233271
     }
234
-    if let Ok(list) = obj.cast::<PyList>() {
235
-        seen.push(id);
236
-        let mut items = Vec::with_capacity(list.len());
237
-        for item in list.iter() {
238
-            items.push(py_to_value(&item, seen, depth + 1)?);
239
-        }
240
-        seen.pop();
241
-        return Ok(Value::List(items));
242
-    }
243
-    if let Ok(tuple) = obj.cast::<PyTuple>() {
244
-        seen.push(id);
245
-        let mut items = Vec::with_capacity(tuple.len());
246
-        for item in tuple.iter() {
247
-            items.push(py_to_value(&item, seen, depth + 1)?);
248
-        }
249
-        seen.pop();
250
-        return Ok(Value::List(items));
251
-    }
252
-
253
-    // Any other object: instance data via `__dict__` (no methods/properties). Keys
254
-    // beginning with `_` (dunders and internal/private bookkeeping like
255
-    // SQLAlchemy's `_sa_instance_state`) are skipped.
256272
     if let Ok(attrs) = obj.getattr("__dict__") {
257273
         if let Ok(dict) = attrs.cast::<PyDict>() {
258
-            seen.push(id);
259274
             let mut map = BTreeMap::new();
260275
             for (k, v) in dict.iter() {
261276
                 let key = key_to_string(&k)?;
262277
                 if key.starts_with('_') {
263278
                     continue;
264279
                 }
265
-                map.insert(key, py_to_value(&v, seen, depth + 1)?);
280
+                map.insert(key, shallow_convert(&v)?);
266281
             }
267
-            seen.pop();
268282
             return Ok(Value::Context(map));
269283
         }
270284
     }
271
-
272
-    // `__slots__` objects (no `__dict__`) and anything else: not introspectable.
273285
     Ok(Value::Null)
286
+}
287
+
288
+/// A lazily-resolved Python object behind feel-core's [`ForeignObject`] seam. Holds
289
+/// a GIL-independent `Py<PyAny>`; each access reattaches via `Python::attach`,
290
+/// which is cheap and reentrant because evaluation already holds the GIL.
291
+#[derive(Debug)]
292
+struct PyForeign {
293
+    obj: Py<PyAny>,
294
+}
295
+
296
+impl ForeignObject for PyForeign {
297
+    fn get(&self, key: &str) -> Value {
298
+        Python::attach(|py| py_get_member(self.obj.bind(py), key).unwrap_or(Value::Null))
299
+    }
300
+
301
+    fn force(&self) -> Value {
302
+        Python::attach(|py| py_force(self.obj.bind(py)).unwrap_or(Value::Null))
303
+    }
304
+
305
+    fn as_any(&self) -> &dyn std::any::Any {
306
+        self
307
+    }
274308
 }
275309
 
276310
 /// A context key as a string: the natural key if it is a `str`, else its `str()`.
@@ -394,6 +428,14 @@
394428
                 (sd.subsec_nanos() / 1_000) as i64,
395429
             ))?
396430
         }
431
+        // Identity pass-through (ADR-21): a lazy host value that reached the result
432
+        // is handed back as the *original* object, untouched — no materialisation,
433
+        // no re-traversal. The downcast cannot miss (`PyForeign` is the only impl);
434
+        // fall back to forcing if it ever does.
435
+        Value::Foreign(f) => match f.0.as_any().downcast_ref::<PyForeign>() {
436
+            Some(pf) => pf.obj.clone_ref(py).into_bound(py),
437
+            None => value_to_py(py, &f.0.force())?,
438
+        },
397439
     })
398440
 }
399441
 

modified crates/feel-py/tests/test_feel.py +81 −23

@@ -91,7 +91,7 @@
9191
     assert feel.evaluate('replace("abc", "(a)(b)", "$2$1")') == "bac"
9292
 
9393
 
94
-# --- object context: __dict__, no property firing ------------------------- #
94
+# --- object context: lazy attribute access (ADR-21) ----------------------- #
9595
 
9696
 def test_dataclass_context_reads_instance_data():
9797
     from dataclasses import dataclass
@@ -103,7 +103,38 @@
103103
     assert feel.evaluate("o.total", {"o": Order(99)}) == 99
104104
 
105105
 
106
-def test_property_is_not_fired():
106
+def test_nested_object_path():
107
+    from dataclasses import dataclass
108
+
109
+    @dataclass
110
+    class Customer:
111
+        name: str
112
+
113
+    @dataclass
114
+    class Order:
115
+        customer: Customer
116
+
117
+    assert feel.evaluate("o.customer.name", {"o": Order(Customer("Ada"))}) == "Ada"
118
+
119
+
120
+def test_property_fires_when_path_names_it():
121
+    # Lazy access is `getattr`, so naming a property in the path evaluates it —
122
+    # exactly once, on access. This is the ORM lazy-load use case.
123
+    fired = []
124
+
125
+    class Row:
126
+        @property
127
+        def computed(self):
128
+            fired.append(True)
129
+            return 7
130
+
131
+    assert feel.evaluate("r.computed", {"r": Row()}) == 7
132
+    assert fired == [True]
133
+
134
+
135
+def test_untouched_property_is_not_fired():
136
+    # Attribute-level laziness: reading one member never fires a *sibling*
137
+    # property — only the attributes the expression actually names are touched.
107138
     fired = []
108139
 
109140
     class Row:
@@ -116,31 +147,58 @@
116147
             return 1
117148
 
118149
     assert feel.evaluate("r.total", {"r": Row()}) == 5
119
-    assert fired == []  # the property was never evaluated
120
-
121
-
122
-def test_nested_object_path():
123
-    from dataclasses import dataclass
124
-
125
-    @dataclass
150
+    assert fired == []
151
+
152
+
153
+def test_lazy_relation_loads_only_when_navigated():
154
+    loads = []
155
+
156
+    class Address:
157
+        def __init__(self):
158
+            self.city = "Berlin"
159
+
126160
     class Customer:
127
-        name: str
128
-
129
-    @dataclass
161
+        @property
162
+        def address(self):  # a lazily-loaded relation (a DB hit, in real life)
163
+            loads.append(True)
164
+            return Address()
165
+
130166
     class Order:
131
-        customer: Customer
132
-
133
-    assert feel.evaluate("o.customer.name", {"o": Order(Customer("Ada"))}) == "Ada"
134
-
135
-
136
-# --- cycle guard ---------------------------------------------------------- #
137
-
138
-def test_self_referential_dict_terminates():
167
+        def __init__(self):
168
+            self.customer = Customer()
169
+
170
+    # Navigating into the relation triggers exactly one load.
171
+    assert feel.evaluate("o.customer.address.city", {"o": Order()}) == "Berlin"
172
+    assert loads == [True]
173
+    # Not naming the relation triggers no load.
174
+    loads.clear()
175
+    assert feel.evaluate("o.customer", {"o": Order()}) is not None
176
+    assert loads == []
177
+
178
+
179
+# --- output pass-through (ADR-21) ----------------------------------------- #
180
+
181
+def test_foreign_object_result_passes_through_by_identity():
182
+    # A host object that reaches the result comes back as the *same* object, not a
183
+    # snapshot dict — no re-traversal.
184
+    class Customer:
185
+        def __init__(self):
186
+            self.name = "Ada"
187
+
188
+    c = Customer()
189
+    assert feel.evaluate("o", {"o": c}) is c
190
+    assert feel.evaluate("o.self", {"o": {"self": c}}) is c
191
+
192
+
193
+# --- cyclic graphs need no guard in lazy mode (ADR-21) -------------------- #
194
+
195
+def test_self_referential_dict_terminates_via_finite_path():
139196
     d = {"a": 1}
140197
     d["self"] = d
141
-    # Must not hang/overflow; the back-edge becomes None.
142
-    result = feel.evaluate("x.self", {"x": d})
143
-    assert result is None or isinstance(result, dict)
198
+    # A finite expression names a finite path, so this terminates with no guard.
199
+    assert feel.evaluate("x.self.self.self.a", {"x": d}) == 1
200
+    # And the cyclic object passes through by identity.
201
+    assert feel.evaluate("x.self", {"x": d}) is d
144202
 
145203
 
146204
 # --- compile reuse -------------------------------------------------------- #

modified crates/feel-wasm/smoke.mjs +47 −0

@@ -68,6 +68,53 @@
6868
   ok = false;
6969
 }
7070
 
71
+// Lazy host-object access (ADR-21): an object in the context is wrapped and its
72
+// members resolve on demand via `Reflect.get`, which *fires JS accessor getters*.
73
+const getterObj = {
74
+  get name() {
75
+    return "Ada";
76
+  },
77
+};
78
+const getterResult = evaluate("o.name", { o: getterObj });
79
+console.log(`o.name (getter) => ${JSON.stringify(getterResult)}`);
80
+if (getterResult !== "Ada") {
81
+  console.error("FAIL: a JS getter should fire on path access");
82
+  ok = false;
83
+}
84
+// Lazy navigation through nested getters (the ORM lazy-load shape).
85
+const orderObj = {
86
+  get customer() {
87
+    return {
88
+      get address() {
89
+        return { city: "Paris" };
90
+      },
91
+    };
92
+  },
93
+};
94
+const nested = evaluate("o.customer.address.city", { o: orderObj });
95
+console.log(`o.customer.address.city => ${JSON.stringify(nested)}`);
96
+if (nested !== "Paris") {
97
+  console.error("FAIL: nested getter navigation");
98
+  ok = false;
99
+}
100
+// Output pass-through: a host object that reaches the result is the *same* object.
101
+const origObj = { city: "Berlin" };
102
+const passed = evaluate("o", { o: origObj });
103
+console.log(`o passthrough identity => ${passed === origObj}`);
104
+if (passed !== origObj) {
105
+  console.error("FAIL: a Foreign result should pass the original object through");
106
+  ok = false;
107
+}
108
+// A cyclic object needs no guard in lazy mode: a finite path terminates.
109
+const cyc = { a: 1 };
110
+cyc.self = cyc;
111
+const cycResult = evaluate("x.self.self.a", { x: cyc });
112
+console.log(`x.self.self.a (cyclic) => ${JSON.stringify(cycResult)}`);
113
+if (cycResult !== 1) {
114
+  console.error("FAIL: a finite path over a cyclic object should terminate");
115
+  ok = false;
116
+}
117
+
71118
 // Boundary policy (ADR-14): a type error is a lenient `null`, but `evaluate_strict`
72119
 // surfaces it as a thrown exception instead of letting it pass silently as `null`.
73120
 const threw = (fn) => {

modified crates/feel-wasm/src/lib.rs +84 −41

@@ -6,12 +6,23 @@
66
 //! evaluate the same expression against many contexts should compile once and
77
 //! reuse. The context is a native JS object and the result a native JS value. The
88
 //! boundary mapping lives here (not in `feel-core`), per the project's
9
-//! boundary-mapping decision: `JsValue` is bridged to `serde_json::Value` with
10
-//! `serde-wasm-bindgen`, then to `feel-core`'s [`Value`] by the helpers below.
9
+//! boundary-mapping decision.
10
+//!
11
+//! Context input is **lazy** (ADR-21): an object is wrapped behind feel-core's
12
+//! `ForeignObject` seam, so `order.customer.address` resolves one segment at a time
13
+//! via `Reflect.get` (which fires JS accessor getters) instead of the whole graph
14
+//! being walked up front. Scalars and `Date` values are converted eagerly; a
15
+//! `Foreign` that reaches the result passes the original `JsValue` back untouched.
16
+//! A finite expression can only navigate a finite path, so cyclic objects need no
17
+//! cycle guard (the previous `js_to_value` guard is gone).
1118
 
1219
 use std::collections::BTreeMap;
13
-
14
-use feel_core::{compile as core_compile, CompiledExpr as CoreCompiled, Context, EvalEnv, Value};
20
+use std::sync::Arc;
21
+
22
+use feel_core::{
23
+    compile as core_compile, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign,
24
+    ForeignObject, Value,
25
+};
1526
 use serde::Serialize;
1627
 use wasm_bindgen::prelude::*;
1728
 use wasm_bindgen::JsCast;
@@ -142,6 +153,13 @@
142153
             }
143154
             Ok(obj.into())
144155
         }
156
+        // Identity pass-through (ADR-21): a lazy host value that reached the result
157
+        // is handed back as the *original* `JsValue`, untouched. The downcast cannot
158
+        // miss (`JsForeign` is the only impl); fall back to forcing if it ever does.
159
+        Value::Foreign(f) => match f.0.as_any().downcast_ref::<JsForeign>() {
160
+            Some(jf) => Ok(jf.obj.clone()),
161
+            None => value_to_js(&f.0.force()),
162
+        },
145163
         // Scalars (number/bool/string/null) go through the JSON-compatible path so
146164
         // integral numbers stay JS numbers (`1 + 1` -> `2`, not `2.0`).
147165
         _ => to_js(&value_to_json(value)),
@@ -186,12 +204,14 @@
186204
 // --------------------------------------------------------------------------- //
187205
 
188206
 /// Build a [`Context`] from a native JS object. `undefined`/`null` is the empty
189
-/// context; any other top-level value is an error.
207
+/// context; a plain object maps to a context (its top-level members
208
+/// shallow-converted, so nested objects become lazy `Foreign`s); any other
209
+/// top-level value is an error.
190210
 fn context_from_js(value: &JsValue) -> Result<Context, JsError> {
191211
     if value.is_null() || value.is_undefined() {
192212
         return Ok(Context::new());
193213
     }
194
-    match js_to_value(value) {
214
+    match js_force(value) {
195215
         Value::Context(map) => {
196216
             let mut ctx = Context::new();
197217
             for (key, val) in map {
@@ -203,22 +223,12 @@
203223
     }
204224
 }
205225
 
206
-/// Maximum nesting depth converted from the JS context — a back-stop alongside
207
-/// the identity-based cycle guard below (deeper than this maps to `null`).
208
-const MAX_DEPTH: usize = 256;
209
-
210
-/// Map a native `JsValue` to a `feel-core` [`Value`], accepting a JS `Date`
211
-/// anywhere as a FEEL date and time (ADR-18). Numbers, booleans, strings, arrays
212
-/// (-> list), plain objects (-> context) and null/undefined are supported.
213
-fn js_to_value(value: &JsValue) -> Value {
214
-    js_to_value_guarded(value, &mut Vec::new(), 0)
215
-}
216
-
217
-/// As [`js_to_value`], threading a cycle/depth guard: a JS object graph can be
218
-/// cyclic (`a.b = a` is legal), which would recurse forever. `seen` holds the
219
-/// objects on the current path (a back-edge — an object identical to an ancestor —
220
-/// becomes `null`, giving DAG semantics); `depth` is the back-stop.
221
-fn js_to_value_guarded(value: &JsValue, seen: &mut Vec<JsValue>, depth: usize) -> Value {
226
+/// Convert a single `JsValue` to a [`Value`] **shallowly** (ADR-21): numbers,
227
+/// booleans, strings and `Date` eagerly; an array to a `Value::List` whose elements
228
+/// are themselves shallow (an object element becomes a lazy `Foreign`); any other
229
+/// object to a `Value::Foreign` resolved on demand. Nothing is walked beyond this
230
+/// one level, so cyclic graphs are harmless here.
231
+fn shallow_convert_js(value: &JsValue) -> Value {
222232
     if value.is_null() || value.is_undefined() {
223233
         return Value::Null;
224234
     }
@@ -236,36 +246,69 @@
236246
         let iso = date.to_iso_string().as_string().unwrap_or_default();
237247
         return feel_core::temporal_from_iso("date and time", &iso).unwrap_or(Value::Null);
238248
     }
239
-    // Only arrays/objects recurse, so the guard sits here: a cycle back-edge or an
240
-    // over-deep node collapses to `null` instead of overflowing the stack.
241
-    if depth > MAX_DEPTH || seen.iter().any(|s| js_sys::Object::is(s, value)) {
242
-        return Value::Null;
243
-    }
249
+    // Array before object (an array *is* an object): build the spine, elements stay
250
+    // shallow so an object element becomes a lazy `Foreign`.
244251
     if js_sys::Array::is_array(value) {
245252
         let arr: &js_sys::Array = value.unchecked_ref();
246
-        seen.push(value.clone());
247
-        let items = arr
248
-            .iter()
249
-            .map(|x| js_to_value_guarded(&x, seen, depth + 1))
250
-            .collect();
251
-        seen.pop();
252
-        return Value::List(items);
253
+        return Value::List(arr.iter().map(|x| shallow_convert_js(&x)).collect());
254
+    }
255
+    if value.is_object() {
256
+        return Value::Foreign(Foreign(Arc::new(JsForeign { obj: value.clone() })));
257
+    }
258
+    Value::Null
259
+}
260
+
261
+/// Resolve one member of a JS value by name — the FEEL dot (ADR-21) — via
262
+/// `Reflect.get`, which fires JS accessor getters. An absent member (`undefined`)
263
+/// is a value-null. The returned value is shallow.
264
+fn js_get_member(obj: &JsValue, key: &str) -> Value {
265
+    match js_sys::Reflect::get(obj, &JsValue::from_str(key)) {
266
+        Ok(v) if v.is_undefined() => Value::Null,
267
+        Ok(v) => shallow_convert_js(&v),
268
+        Err(_) => Value::Null,
269
+    }
270
+}
271
+
272
+/// Materialise a `JsValue` *one level* into a concrete [`Value`] (ADR-21): an array
273
+/// to a `Value::List`; any other object to a `Value::Context` of its own enumerable
274
+/// keys (`Object.keys`); everything else to null. Members are shallow-converted, so
275
+/// nested objects stay lazy.
276
+fn js_force(value: &JsValue) -> Value {
277
+    if js_sys::Array::is_array(value) {
278
+        let arr: &js_sys::Array = value.unchecked_ref();
279
+        return Value::List(arr.iter().map(|x| shallow_convert_js(&x)).collect());
253280
     }
254281
     if value.is_object() {
255282
         let obj: &js_sys::Object = value.unchecked_ref();
256
-        seen.push(value.clone());
257283
         let mut map = BTreeMap::new();
258284
         for key in js_sys::Object::keys(obj).iter() {
259285
             let val = js_sys::Reflect::get(value, &key).unwrap_or(JsValue::NULL);
260
-            map.insert(
261
-                key.as_string().unwrap_or_default(),
262
-                js_to_value_guarded(&val, seen, depth + 1),
263
-            );
264
-        }
265
-        seen.pop();
286
+            map.insert(key.as_string().unwrap_or_default(), shallow_convert_js(&val));
287
+        }
266288
         return Value::Context(map);
267289
     }
268290
     Value::Null
291
+}
292
+
293
+/// A lazily-resolved JS object behind feel-core's [`ForeignObject`] seam. WASM is
294
+/// single-threaded, so the `JsValue` handle is used directly (no GIL/token).
295
+#[derive(Debug)]
296
+struct JsForeign {
297
+    obj: JsValue,
298
+}
299
+
300
+impl ForeignObject for JsForeign {
301
+    fn get(&self, key: &str) -> Value {
302
+        js_get_member(&self.obj, key)
303
+    }
304
+
305
+    fn force(&self) -> Value {
306
+        js_force(&self.obj)
307
+    }
308
+
309
+    fn as_any(&self) -> &dyn std::any::Any {
310
+        self
311
+    }
269312
 }
270313
 
271314
 // --------------------------------------------------------------------------- //