//! WASM wrapper for `feel-core`, built with wasm-bindgen. //! //! Exposes the one-shot `evaluate(expr, context) -> JsValue` plus a //! `compile(expr) -> CompiledExpr` class for parse-once / evaluate-many: parsing //! is the per-call cost that does not depend on the context, so callers that //! evaluate the same expression against many contexts should compile once and //! reuse. The context is a native JS object and the result a native JS value. The //! boundary mapping lives here (not in `feel-core`), per the project's //! boundary-mapping decision. //! //! Context input is **lazy** (ADR-21): an object is wrapped behind feel-core's //! `ForeignObject` seam, so `order.customer.address` resolves one segment at a time //! via `Reflect.get` (which fires JS accessor getters) instead of the whole graph //! being walked up front. Scalars and `Date` values are converted eagerly; a //! `Foreign` that reaches the result passes the original `JsValue` back untouched. //! A finite expression can only navigate a finite path, so cyclic objects need no //! cycle guard (the previous `js_to_value` guard is gone). use std::cell::RefCell; use std::collections::BTreeMap; use std::sync::Arc; use feel_core::{ compile as core_compile, compile_with_probe as core_compile_with_probe, Args, CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func, FunctionRegistry, ScopeProbe, ScopeWithFunctions, Value, }; use serde::Serialize; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; /// Evaluate a FEEL expression (lenient boundary policy). /// /// `context` is a native JS object (e.g. `{}`); `undefined`/`null` is treated as /// an empty context. The result is returned as a native JS value. Parse and eval /// errors are thrown as JS exceptions. A null arising from a type/domain error is /// returned as plain `null` (the spec-shaped result); see `evaluate_strict` to /// surface such errors as a thrown exception instead. /// /// The context **is** the scope for §10.3.1.6 name resolution (ADR-47): a name /// like `a-b` resolves to the context binding `a-b` when one exists, and to /// subtraction otherwise. #[wasm_bindgen] pub fn evaluate(expr: &str, context: JsValue, functions: JsValue) -> Result { // Build the context and registry first: together they are the parse-time // name oracle (ADR-47). let ctx = context_from_js(&context)?; let registry = JsFunctionRegistry { funcs: functions }; let scope = ScopeWithFunctions { context: &ctx, functions: ®istry }; run_with_ctx(&compile_with_probe_core(expr, &scope)?, &ctx, ®istry, false) } /// Evaluate a FEEL expression (strict boundary policy): if the result is, or /// contains, a null that arose from a type/domain error, throw instead of letting /// the error pass silently as `null` (ADR-14). A plain (value) null is still /// returned as `null`. Scope-dependent names resolve as in [`evaluate`]. #[wasm_bindgen] pub fn evaluate_strict( expr: &str, context: JsValue, functions: JsValue, ) -> Result { let ctx = context_from_js(&context)?; let registry = JsFunctionRegistry { funcs: functions }; let scope = ScopeWithFunctions { context: &ctx, functions: ®istry }; run_with_ctx(&compile_with_probe_core(expr, &scope)?, &ctx, ®istry, true) } /// A parsed FEEL expression, reusable across many evaluations. /// /// Build one with [`compile`], then call [`CompiledExpr::evaluate`] repeatedly — /// parsing happens once, each call only maps the context across the boundary. /// wasm-bindgen exposes a `free()` method and registers instances with a /// `FinalizationRegistry`, so the WASM-side memory is reclaimed on GC; calling /// `free()` explicitly is an optional escape hatch, not required. /// /// Parsed **probe-free** (ADR-47): special-character name runs (`a-b`) are /// arithmetic on this path, whatever the later contexts bind — a compiled /// program must not pin one scope. Use the one-shot [`evaluate`] for /// scope-dependent name resolution (§10.3.1.6). #[wasm_bindgen] pub struct CompiledExpr { inner: CoreCompiled, } /// Parse a FEEL expression into a reusable [`CompiledExpr`] (throws on a parse /// error). Does not evaluate. Probe-free — see [`CompiledExpr`]. #[wasm_bindgen] pub fn compile(expr: &str) -> Result { Ok(CompiledExpr { inner: compile_core(expr)?, }) } #[wasm_bindgen] impl CompiledExpr { /// Evaluate this compiled expression against a context (lenient policy). pub fn evaluate(&self, context: JsValue, functions: JsValue) -> Result { run(&self.inner, context, functions, false) } /// Evaluate this compiled expression against a context (strict policy; see /// the free `evaluate_strict`). pub fn evaluate_strict( &self, context: JsValue, functions: JsValue, ) -> Result { run(&self.inner, context, functions, true) } } fn compile_core(expr: &str) -> Result { core_compile(expr).map_err(|e| JsError::new(&e.to_string())) } /// Parse with the call's scope (context + function registry) as the §10.3.1.6 /// name oracle (ADR-47): special-character name runs (`a-b`) fuse into names /// exactly when that scope binds them. fn compile_with_probe_core(expr: &str, probe: &dyn ScopeProbe) -> Result { core_compile_with_probe(expr, probe) .map_err(|e| JsError::new(&e.to_string())) } /// Shared per-call boundary: map the JS context in (accepting native `Date` /// objects), evaluate the compiled program against the host regex provider and /// the `Date.now()` instant, optionally surface error-nulls strictly, map the /// result back out (date/date-and-time as native `Date` objects). fn run(compiled: &CoreCompiled, context: JsValue, functions: JsValue, strict: bool) -> Result { // Ambient host functions (ADR-23): a JS object of `name -> function`, consulted // after context bindings and built-ins. `undefined`/`null` -> no-op registry. let registry = JsFunctionRegistry { funcs: functions }; run_with_ctx(compiled, &context_from_js(&context)?, ®istry, strict) } /// [`run`] with the context and registry already built — the one-shot entry /// points have them in hand first, because together they are the parse-time /// scope probe. fn run_with_ctx( compiled: &CoreCompiled, ctx: &Context, registry: &JsFunctionRegistry, strict: bool, ) -> Result { let env = EvalEnv::with_functions(®EX, now_zoned(), registry); let value = compiled .evaluate_with_env(ctx, &env) .map_err(|e| JsError::new(&e.to_string()))?; if strict && value.contains_error() { return Err(JsError::new( "evaluation produced a null from a type or domain error", )); } value_to_js(&value) } /// The evaluation instant for `now()`/`today()`: `Date.now()` as a UTC `Zoned` /// (a fixed offset, so `now()` serialises as `…+00:00`). fn now_zoned() -> jiff::Zoned { let utc = jiff::tz::TimeZone::fixed(jiff::tz::Offset::UTC); jiff::Timestamp::from_millisecond(js_sys::Date::now() as i64) .unwrap_or(jiff::Timestamp::UNIX_EPOCH) .to_zoned(utc) } // --------------------------------------------------------------------------- // // Result mapping (feel-core Value -> native JsValue) // --------------------------------------------------------------------------- // /// Map a `feel-core` [`Value`] to a native `JsValue`. Date and date-and-time /// values become native JS `Date` objects (ADR-18; falling back to the ISO string /// if `Date` cannot represent them); `time` and durations stay ISO-8601 strings. /// Lists/contexts are mapped recursively so nested temporal values are preserved. fn value_to_js(value: &Value) -> Result { match value { Value::Date(_) | Value::DateTime(_) => { let iso = feel_core::temporal::to_iso(value).unwrap_or_default(); let date = js_sys::Date::new(&JsValue::from_str(&iso)); // An unrepresentable date (e.g. sub-millisecond precision JS drops, or // a parse gap) yields `Invalid Date`; fall back to the ISO string. if date.get_time().is_nan() { Ok(JsValue::from_str(&iso)) } else { Ok(date.into()) } } Value::Time(_) | Value::YearsMonthsDuration(_) | Value::DaysTimeDuration(_) => { Ok(JsValue::from_str(&feel_core::temporal::to_iso(value).unwrap_or_default())) } Value::List(items) => { let arr = js_sys::Array::new(); for item in items { arr.push(&value_to_js(item)?); } Ok(arr.into()) } Value::Context(map) => { let obj = js_sys::Object::new(); for (k, v) in map { js_sys::Reflect::set(&obj, &JsValue::from_str(k), &value_to_js(v)?) .map_err(|_| JsError::new("failed to build result object"))?; } Ok(obj.into()) } // Identity pass-through (ADR-21): a lazy host value that reached the result // is handed back as the *original* `JsValue`, untouched. The downcast cannot // miss (`JsForeign` is the only impl); fall back to forcing if it ever does. Value::Foreign(f) => match f.0.as_any().downcast_ref::() { Some(jf) => Ok(jf.obj.clone()), None => value_to_js(&f.0.force()), }, // A function value (ADR-23): a host callable is handed back as the original // JS function (identity pass-through); a native FEEL closure has no JS // representation and crosses out as `null`. Value::Function(f) => match &**f { Func::Foreign(host_fn) => match host_fn.as_any().downcast_ref::() { Some(jf) => Ok(jf.obj.clone()), None => Ok(JsValue::NULL), }, Func::Closure(_) | Func::Builtin(_) => Ok(JsValue::NULL), }, // Scalars (number/bool/string/null) go through the JSON-compatible path so // integral numbers stay JS numbers (`1 + 1` -> `2`, not `2.0`). _ => to_js(&value_to_json(value)), } } /// Serialize a JSON value to a native `JsValue`. The `json_compatible` serializer /// maps objects to plain JS objects (not `Map`); integral numbers stay JS numbers. fn to_js(value: &serde_json::Value) -> Result { let serializer = serde_wasm_bindgen::Serializer::json_compatible(); value .serialize(&serializer) .map_err(|e| JsError::new(&e.to_string())) } /// Map a scalar `feel-core` [`Value`] to JSON. Only the non-temporal scalars reach /// here ([`value_to_js`] handles temporal, lists and contexts). Integral numbers /// are emitted as JSON integers so e.g. `1 + 1` yields `2` rather than `2.0`. fn value_to_json(value: &Value) -> serde_json::Value { match value { Value::Number(n) => number_to_json(*n), Value::Boolean(b) => serde_json::Value::Bool(*b), Value::String(s) => serde_json::Value::String(s.clone()), // Lenient: an error-null serialises like a plain null. Strict callers // check `Value::contains_error` before reaching here. _ => serde_json::Value::Null, } } fn number_to_json(n: f64) -> serde_json::Value { if n.is_finite() && n.fract() == 0.0 && n.abs() < 9.007_199_254_740_992e15 { serde_json::Value::Number((n as i64).into()) } else { serde_json::Number::from_f64(n) .map(serde_json::Value::Number) .unwrap_or(serde_json::Value::Null) } } // --------------------------------------------------------------------------- // // Context mapping (native JsValue -> feel-core Value) // --------------------------------------------------------------------------- // /// Build a [`Context`] from a native JS object. `undefined`/`null` is the empty /// context; a plain object maps to a context (its top-level members /// shallow-converted, so nested objects become lazy `Foreign`s); any other /// top-level value is an error. fn context_from_js(value: &JsValue) -> Result { if value.is_null() || value.is_undefined() { return Ok(Context::new()); } match js_force(value) { Value::Context(map) => { let mut ctx = Context::new(); for (key, val) in map { ctx.insert(key, val); } Ok(ctx) } _ => Err(JsError::new("expected an object context")), } } /// Convert a single `JsValue` to a [`Value`] **shallowly** (ADR-21): numbers, /// booleans, strings and `Date` eagerly; an array to a `Value::List` whose elements /// are themselves shallow (an object element becomes a lazy `Foreign`); any other /// object to a `Value::Foreign` resolved on demand. Nothing is walked beyond this /// one level, so cyclic graphs are harmless here. fn shallow_convert_js(value: &JsValue) -> Value { if value.is_null() || value.is_undefined() { return Value::Null; } if let Some(b) = value.as_bool() { return Value::Boolean(b); } if let Some(n) = value.as_f64() { return Value::Number(n); } if let Some(s) = value.as_string() { return Value::String(s); } if value.is_instance_of::() { let date: &js_sys::Date = value.unchecked_ref(); let iso = date.to_iso_string().as_string().unwrap_or_default(); return feel_core::temporal_from_iso("date and time", &iso).unwrap_or(Value::Null); } // Array before object (an array *is* an object): build the spine, elements stay // shallow so an object element becomes a lazy `Foreign`. if js_sys::Array::is_array(value) { let arr: &js_sys::Array = value.unchecked_ref(); return Value::List(arr.iter().map(|x| shallow_convert_js(&x)).collect()); } // A JS function becomes a FEEL function value the host can invoke (ADR-23). // Checked before `is_object` (a function has `typeof === "function"`, not // `"object"`, but be explicit about ordering). if value.is_function() { return Func::Foreign(Arc::new(JsForeignFn { obj: value.clone() })).into_value(); } if value.is_object() { return Value::Foreign(Foreign(Arc::new(JsForeign { obj: value.clone() }))); } Value::Null } /// Resolve one member of a JS value by name — the FEEL dot (ADR-21) — via /// `Reflect.get`, which fires JS accessor getters. An absent member (`undefined`) /// is a value-null. The returned value is shallow. fn js_get_member(obj: &JsValue, key: &str) -> Value { match js_sys::Reflect::get(obj, &JsValue::from_str(key)) { Ok(v) if v.is_undefined() => Value::Null, Ok(v) => shallow_convert_js(&v), Err(_) => Value::Null, } } /// Materialise a `JsValue` *one level* into a concrete [`Value`] (ADR-21): an array /// to a `Value::List`; any other object to a `Value::Context` of its own enumerable /// keys (`Object.keys`); everything else to null. Members are shallow-converted, so /// nested objects stay lazy. fn js_force(value: &JsValue) -> Value { if js_sys::Array::is_array(value) { let arr: &js_sys::Array = value.unchecked_ref(); return Value::List(arr.iter().map(|x| shallow_convert_js(&x)).collect()); } if value.is_object() { let obj: &js_sys::Object = value.unchecked_ref(); let mut map = BTreeMap::new(); for key in js_sys::Object::keys(obj).iter() { let val = js_sys::Reflect::get(value, &key).unwrap_or(JsValue::NULL); map.insert(key.as_string().unwrap_or_default(), shallow_convert_js(&val)); } return Value::Context(map); } Value::Null } /// A lazily-resolved JS object behind feel-core's [`ForeignObject`] seam. WASM is /// single-threaded, so the `JsValue` handle is used directly (no GIL/token). #[derive(Debug)] struct JsForeign { obj: JsValue, } impl ForeignObject for JsForeign { fn get(&self, key: &str) -> Value { js_get_member(&self.obj, key) } fn force(&self) -> Value { js_force(&self.obj) } fn as_any(&self) -> &dyn std::any::Any { self } /// JS object identity for cycle detection in unbounded traversals (the /// descendant `...` operator). feel-wasm mints a fresh `Arc` per wrap /// (`shallow_convert_js` re-runs on every `force`/`get`), and a `JsValue` handle /// index is NOT object identity across different reads of the same object, so the /// default (allocation address) guard would miss a cycle. We map each distinct /// object to a stable integer via a process-wide `WeakMap` ([`js_identity`]). fn identity(&self) -> usize { js_identity(&self.obj) } } /// Assign each distinct JS object a stable integer identity via a process-wide /// `WeakMap`. Its keys are weakly referenced, so it neither pins objects nor grows /// unboundedly with live data — entries are GC'd once the object is unreferenced /// elsewhere. This is the JS analogue of feel-py's `id()` / feel-lua's table /// pointer: JS exposes no cheap object address, so a `WeakMap` is /// the standard way to derive a hashable, stable identity. fn js_identity(obj: &JsValue) -> usize { thread_local! { static IDS: RefCell<(js_sys::WeakMap, u32)> = RefCell::new((js_sys::WeakMap::new(), 0)); } IDS.with(|cell| { let (map, next) = &mut *cell.borrow_mut(); // A Foreign always wraps an object; `unchecked_ref` is the zero-cost view. let key: &js_sys::Object = obj.unchecked_ref(); if let Some(v) = map.get_checked(key) { v.as_f64().map(|n| n as usize).unwrap_or(0) } else { let n = *next; *next += 1; let _ = map.set(key, &JsValue::from(n)); n as usize } }) } // --------------------------------------------------------------------------- // // Host callables (ADR-23): a JS function invoked from FEEL // --------------------------------------------------------------------------- // /// A JS function behind feel-core's [`ForeignFunction`] seam. `obj` is the original /// `JsValue` (a function), kept whole for identity pass-through on output. #[derive(Debug)] struct JsForeignFn { obj: JsValue, } impl ForeignFunction for JsForeignFn { fn call(&self, args: Args) -> Value { let func: &js_sys::Function = self.obj.unchecked_ref(); match js_call(func, args) { Ok(v) => shallow_convert_js(&v), Err(_) => Value::Error, // a thrown JS exception -> error-null (ADR-14) } } fn as_any(&self) -> &dyn std::any::Any { self } } /// Invoke a JS function with FEEL arguments (ADR-23). JS has no keyword arguments, /// so positional FEEL args become positional JS args and — if any named args are /// present — a single trailing options object `{name: value, …}` is appended (the /// idiomatic JS convention). A thrown exception propagates as `Err`. fn js_call(func: &js_sys::Function, args: Args) -> Result { let arr = js_sys::Array::new(); for v in &args.positional { arr.push(&value_to_js(v).map_err(|_| JsValue::NULL)?); } if !args.named.is_empty() { let opts = js_sys::Object::new(); for (name, v) in &args.named { js_sys::Reflect::set( &opts, &JsValue::from_str(name), &value_to_js(v).map_err(|_| JsValue::NULL)?, )?; } arr.push(&opts.into()); } func.apply(&JsValue::NULL, &arr) } /// A host function registry backed by a JS object `name -> function` (the third /// `functions` argument; ADR-23). The ambient-function path, beside binding a /// function directly in the context. `undefined`/`null` means no registry. #[derive(Debug)] struct JsFunctionRegistry { funcs: JsValue, } impl FunctionRegistry for JsFunctionRegistry { fn get(&self, name: &str) -> Option> { if self.funcs.is_undefined() || self.funcs.is_null() { return None; } let item = js_sys::Reflect::get(&self.funcs, &JsValue::from_str(name)).ok()?; if item.is_function() { Some(Arc::new(JsForeignFn { obj: item })) } else { None } } } // --------------------------------------------------------------------------- // // Host regex provider (ADR-16) // --------------------------------------------------------------------------- // // // The FEEL `matches`/`replace`/`split` builtins run on the **host** regex engine. // In WASM that is the JS `RegExp`, so the ECMAScript dialect applies here — and // the whole Rust regex stack stays out of the bundle. The purist `xpath-regex` // feature instead re-bundles feel-core's `RustRegex` for cross-target identical // results (at the regex stack's size cost). /// The provider used for every evaluation. Both candidates are zero-sized. #[cfg(not(feature = "xpath-regex"))] static REGEX: JsRegex = JsRegex; #[cfg(feature = "xpath-regex")] static REGEX: feel_core::RustRegex = feel_core::RustRegex; /// JS-`RegExp`-backed [`feel_core::FeelRegex`]. A `null` from the shims means the /// pattern/flags were invalid in the JS dialect, which maps to a FEEL null. #[cfg(not(feature = "xpath-regex"))] struct JsRegex; #[cfg(not(feature = "xpath-regex"))] impl feel_core::FeelRegex for JsRegex { fn is_match(&self, input: &str, pattern: &str, flags: &str) -> Option { let (pattern, js_flags) = to_js_pattern(pattern, flags)?; let r = js_regex_test(input, &pattern, &js_flags); if r.is_null() { None } else { r.as_bool() } } fn replace( &self, input: &str, pattern: &str, replacement: &str, flags: &str, ) -> Option { let (pattern, js_flags) = to_js_pattern(pattern, flags)?; let r = js_regex_replace(input, &pattern, &js_flags, replacement); if r.is_null() { None } else { r.as_string() } } fn split(&self, input: &str, delimiter: &str) -> Option> { let r = js_regex_split(input, delimiter); if r.is_null() { return None; } serde_wasm_bindgen::from_value(r).ok() } } /// Map FEEL/XPath flags (`i s m x q`) to (JS pattern, JS RegExp flags). An /// out-of-set flag letter -> `None` (FEEL null), matching the Rust provider's /// validation. `q` escapes the pattern (literal match); `x` /// (whitespace-insensitive) has no JS equivalent and is ignored. #[cfg(not(feature = "xpath-regex"))] fn to_js_pattern(pattern: &str, flags: &str) -> Option<(String, String)> { if flags.chars().any(|c| !matches!(c, 'i' | 's' | 'm' | 'x' | 'q')) { return None; } let js_flags: String = flags.chars().filter(|c| matches!(c, 'i' | 's' | 'm')).collect(); let pattern = if flags.contains('q') { js_escape(pattern) } else { pattern.to_string() }; Some((pattern, js_flags)) } /// Backslash-escape ECMAScript regex metacharacters (for the `q` flag). #[cfg(not(feature = "xpath-regex"))] fn js_escape(pattern: &str) -> String { const SPECIAL: &str = r"\^$.|?*+()[]{}"; let mut out = String::with_capacity(pattern.len()); for c in pattern.chars() { if SPECIAL.contains(c) { out.push('\\'); } out.push(c); } out } // `try/catch` shims so an invalid pattern/flags becomes `null` (-> FEEL null) // instead of a thrown JS exception. `replace` adds the `g` flag because XPath // `replace` replaces all matches, whereas JS `String.replace(regex, …)` only // replaces the first without it. #[cfg(not(feature = "xpath-regex"))] #[wasm_bindgen(inline_js = r#" export function feel_regex_test(input, pattern, flags) { try { return new RegExp(pattern, flags).test(input); } catch (e) { return null; } } export function feel_regex_replace(input, pattern, flags, replacement) { try { return input.replace(new RegExp(pattern, flags + "g"), replacement); } catch (e) { return null; } } export function feel_regex_split(input, delimiter) { try { return input.split(new RegExp(delimiter)); } catch (e) { return null; } } "#)] extern "C" { #[wasm_bindgen(js_name = feel_regex_test)] fn js_regex_test(input: &str, pattern: &str, flags: &str) -> JsValue; #[wasm_bindgen(js_name = feel_regex_replace)] fn js_regex_replace(input: &str, pattern: &str, flags: &str, replacement: &str) -> JsValue; #[wasm_bindgen(js_name = feel_regex_split)] fn js_regex_split(input: &str, delimiter: &str) -> JsValue; }