Public repository: timo / feel

Reader

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

feel / crates / feel-wasm / src / lib.rs · 25.7 KB · at da382279c66c · raw

Outline: 55 definitions
1
//! WASM wrapper for `feel-core`, built with wasm-bindgen.
2
//!
3
//! Exposes the one-shot `evaluate(expr, context) -> JsValue` 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 JS object and the result a native JS value. The
8
//! boundary mapping lives here (not in `feel-core`), per the project's
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).
18
19
use std::cell::RefCell;
20
use std::collections::BTreeMap;
21
use std::sync::Arc;
22
23
use feel_core::{
24
    compile_with as core_compile_with, compile_with_probe as core_compile_with_probe, Args,
25
    CompiledExpr as CoreCompiled, Context, EvalEnv, Foreign, ForeignFunction, ForeignObject, Func,
26
    FunctionRegistry, NameResolution, ParseOptions, ScopeProbe, ScopeWithFunctions, Value,
27
};
28
use serde::Serialize;
29
use wasm_bindgen::prelude::*;
30
use wasm_bindgen::JsCast;
31
32
/// Evaluate a FEEL expression (lenient boundary policy).
33
///
34
/// `context` is a native JS object (e.g. `{}`); `undefined`/`null` is treated as
35
/// an empty context. The result is returned as a native JS value. Parse and eval
36
/// errors are thrown as JS exceptions. A null arising from a type/domain error is
37
/// returned as plain `null` (the spec-shaped result); see `evaluate_strict` to
38
/// surface such errors as a thrown exception instead.
39
///
40
/// Special-character names (ADR-48): `names` selects the level. The default
41
/// (omitted or `"quoted"`) reads `a-b` as subtraction and `` `a-b` `` as the
42
/// name — the text decides, as in Camunda. `"symbols"` opts into the DMN spec's
43
/// reading (§10.3.1.6, ADR-47): the context is the scope, so `a-b` resolves to
44
/// the binding `a-b` when one exists.
45
#[wasm_bindgen]
46
pub fn evaluate(
47
    expr: &str,
48
    context: JsValue,
49
    functions: JsValue,
50
    names: Option<String>,
51
) -> Result<JsValue, JsError> {
52
    // Build the context and registry first: together they are the parse-time
53
    // name oracle (ADR-47).
54
    let options = parse_options(names.as_deref())?;
55
    let ctx = context_from_js(&context)?;
56
    let registry = JsFunctionRegistry { funcs: functions };
57
    let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
58
    run_with_ctx(&compile_with_probe_core(expr, &scope, &options)?, &ctx, &registry, false)
59
}
60
61
/// Evaluate a FEEL expression (strict boundary policy): if the result is, or
62
/// contains, a null that arose from a type/domain error, throw instead of letting
63
/// the error pass silently as `null` (ADR-14). A plain (value) null is still
64
/// returned as `null`. Scope-dependent names resolve as in [`evaluate`].
65
#[wasm_bindgen]
66
pub fn evaluate_strict(
67
    expr: &str,
68
    context: JsValue,
69
    functions: JsValue,
70
    names: Option<String>,
71
) -> Result<JsValue, JsError> {
72
    let options = parse_options(names.as_deref())?;
73
    let ctx = context_from_js(&context)?;
74
    let registry = JsFunctionRegistry { funcs: functions };
75
    let scope = ScopeWithFunctions { context: &ctx, functions: &registry };
76
    run_with_ctx(&compile_with_probe_core(expr, &scope, &options)?, &ctx, &registry, true)
77
}
78
79
/// A parsed FEEL expression, reusable across many evaluations.
80
///
81
/// Build one with [`compile`], then call [`CompiledExpr::evaluate`] repeatedly —
82
/// parsing happens once, each call only maps the context across the boundary.
83
/// wasm-bindgen exposes a `free()` method and registers instances with a
84
/// `FinalizationRegistry`, so the WASM-side memory is reclaimed on GC; calling
85
/// `free()` explicitly is an optional escape hatch, not required.
86
///
87
/// Compiled with `"symbols"` it is **scope-adaptive** (ADR-48): each
88
/// evaluation resolves special-character names against its own context, with a
89
/// small cache of per-scope parses.
90
#[wasm_bindgen]
91
pub struct CompiledExpr {
92
    inner: CoreCompiled,
93
}
94
95
/// Parse a FEEL expression into a reusable [`CompiledExpr`] (throws on a parse
96
/// error). Does not evaluate. `names` as for [`evaluate`]; see [`CompiledExpr`].
97
#[wasm_bindgen]
98
pub fn compile(expr: &str, names: Option<String>) -> Result<CompiledExpr, JsError> {
99
    let options = parse_options(names.as_deref())?;
100
    Ok(CompiledExpr {
101
        inner: core_compile_with(expr, &options).map_err(|e| JsError::new(&e.to_string()))?,
102
    })
103
}
104
105
#[wasm_bindgen]
106
impl CompiledExpr {
107
    /// Evaluate this compiled expression against a context (lenient policy).
108
    pub fn evaluate(&self, context: JsValue, functions: JsValue) -> Result<JsValue, JsError> {
109
        run(&self.inner, context, functions, false)
110
    }
111
112
    /// Evaluate this compiled expression against a context (strict policy; see
113
    /// the free `evaluate_strict`).
114
    pub fn evaluate_strict(
115
        &self,
116
        context: JsValue,
117
        functions: JsValue,
118
    ) -> Result<JsValue, JsError> {
119
        run(&self.inner, context, functions, true)
120
    }
121
}
122
123
/// The optional `names` argument as [`ParseOptions`] (ADR-48).
124
fn parse_options(names: Option<&str>) -> Result<ParseOptions, JsError> {
125
    match names {
126
        None => Ok(ParseOptions::default()),
127
        Some(n) => NameResolution::from_name(n).map(ParseOptions::names).ok_or_else(|| {
128
            JsError::new(&format!("unknown names {n:?} (expected \"symbols\" or \"quoted\")"))
129
        }),
130
    }
131
}
132
133
/// Parse pinned to the call's scope (context + function registry) as the
134
/// §10.3.1.6 name oracle (ADR-47) — one parse, one-shot use.
135
fn compile_with_probe_core(
136
    expr: &str,
137
    probe: &dyn ScopeProbe,
138
    options: &ParseOptions,
139
) -> Result<CoreCompiled, JsError> {
140
    core_compile_with_probe(expr, probe, options).map_err(|e| JsError::new(&e.to_string()))
141
}
142
143
/// Shared per-call boundary: map the JS context in (accepting native `Date`
144
/// objects), evaluate the compiled program against the host regex provider and
145
/// the `Date.now()` instant, optionally surface error-nulls strictly, map the
146
/// result back out (date/date-and-time as native `Date` objects).
147
fn run(compiled: &CoreCompiled, context: JsValue, functions: JsValue, strict: bool) -> Result<JsValue, JsError> {
148
    // Ambient host functions (ADR-23): a JS object of `name -> function`, consulted
149
    // after context bindings and built-ins. `undefined`/`null` -> no-op registry.
150
    let registry = JsFunctionRegistry { funcs: functions };
151
    run_with_ctx(compiled, &context_from_js(&context)?, &registry, strict)
152
}
153
154
/// [`run`] with the context and registry already built — the one-shot entry
155
/// points have them in hand first, because together they are the parse-time
156
/// scope probe.
157
fn run_with_ctx(
158
    compiled: &CoreCompiled,
159
    ctx: &Context,
160
    registry: &JsFunctionRegistry,
161
    strict: bool,
162
) -> Result<JsValue, JsError> {
163
    let env = EvalEnv::with_functions(&REGEX, now_zoned(), registry);
164
    let value = compiled
165
        .evaluate_with_env(ctx, &env)
166
        .map_err(|e| JsError::new(&e.to_string()))?;
167
    if strict && value.contains_error() {
168
        return Err(JsError::new(
169
            "evaluation produced a null from a type or domain error",
170
        ));
171
    }
172
    value_to_js(&value)
173
}
174
175
/// The evaluation instant for `now()`/`today()`: `Date.now()` as a UTC `Zoned`
176
/// (a fixed offset, so `now()` serialises as `…+00:00`).
177
fn now_zoned() -> jiff::Zoned {
178
    let utc = jiff::tz::TimeZone::fixed(jiff::tz::Offset::UTC);
179
    jiff::Timestamp::from_millisecond(js_sys::Date::now() as i64)
180
        .unwrap_or(jiff::Timestamp::UNIX_EPOCH)
181
        .to_zoned(utc)
182
}
183
184
// --------------------------------------------------------------------------- //
185
// Result mapping (feel-core Value -> native JsValue)
186
// --------------------------------------------------------------------------- //
187
188
/// Map a `feel-core` [`Value`] to a native `JsValue`. Date and date-and-time
189
/// values become native JS `Date` objects (ADR-18; falling back to the ISO string
190
/// if `Date` cannot represent them); `time` and durations stay ISO-8601 strings.
191
/// Lists/contexts are mapped recursively so nested temporal values are preserved.
192
fn value_to_js(value: &Value) -> Result<JsValue, JsError> {
193
    match value {
194
        Value::Date(_) | Value::DateTime(_) => {
195
            let iso = feel_core::temporal::to_iso(value).unwrap_or_default();
196
            let date = js_sys::Date::new(&JsValue::from_str(&iso));
197
            // An unrepresentable date (e.g. sub-millisecond precision JS drops, or
198
            // a parse gap) yields `Invalid Date`; fall back to the ISO string.
199
            if date.get_time().is_nan() {
200
                Ok(JsValue::from_str(&iso))
201
            } else {
202
                Ok(date.into())
203
            }
204
        }
205
        Value::Time(_) | Value::YearsMonthsDuration(_) | Value::DaysTimeDuration(_) => {
206
            Ok(JsValue::from_str(&feel_core::temporal::to_iso(value).unwrap_or_default()))
207
        }
208
        Value::List(items) => {
209
            let arr = js_sys::Array::new();
210
            for item in items {
211
                arr.push(&value_to_js(item)?);
212
            }
213
            Ok(arr.into())
214
        }
215
        Value::Context(map) => {
216
            let obj = js_sys::Object::new();
217
            for (k, v) in map {
218
                js_sys::Reflect::set(&obj, &JsValue::from_str(k), &value_to_js(v)?)
219
                    .map_err(|_| JsError::new("failed to build result object"))?;
220
            }
221
            Ok(obj.into())
222
        }
223
        // Identity pass-through (ADR-21): a lazy host value that reached the result
224
        // is handed back as the *original* `JsValue`, untouched. The downcast cannot
225
        // miss (`JsForeign` is the only impl); fall back to forcing if it ever does.
226
        Value::Foreign(f) => match f.0.as_any().downcast_ref::<JsForeign>() {
227
            Some(jf) => Ok(jf.obj.clone()),
228
            None => value_to_js(&f.0.force()),
229
        },
230
        // A function value (ADR-23): a host callable is handed back as the original
231
        // JS function (identity pass-through); a native FEEL closure has no JS
232
        // representation and crosses out as `null`.
233
        Value::Function(f) => match &**f {
234
            Func::Foreign(host_fn) => match host_fn.as_any().downcast_ref::<JsForeignFn>() {
235
                Some(jf) => Ok(jf.obj.clone()),
236
                None => Ok(JsValue::NULL),
237
            },
238
            Func::Closure(_) | Func::Builtin(_) => Ok(JsValue::NULL),
239
        },
240
        // Scalars (number/bool/string/null) go through the JSON-compatible path so
241
        // integral numbers stay JS numbers (`1 + 1` -> `2`, not `2.0`).
242
        _ => to_js(&value_to_json(value)),
243
    }
244
}
245
246
/// Serialize a JSON value to a native `JsValue`. The `json_compatible` serializer
247
/// maps objects to plain JS objects (not `Map`); integral numbers stay JS numbers.
248
fn to_js(value: &serde_json::Value) -> Result<JsValue, JsError> {
249
    let serializer = serde_wasm_bindgen::Serializer::json_compatible();
250
    value
251
        .serialize(&serializer)
252
        .map_err(|e| JsError::new(&e.to_string()))
253
}
254
255
/// Map a scalar `feel-core` [`Value`] to JSON. Only the non-temporal scalars reach
256
/// here ([`value_to_js`] handles temporal, lists and contexts). Integral numbers
257
/// are emitted as JSON integers so e.g. `1 + 1` yields `2` rather than `2.0`.
258
fn value_to_json(value: &Value) -> serde_json::Value {
259
    match value {
260
        Value::Number(n) => number_to_json(*n),
261
        Value::Boolean(b) => serde_json::Value::Bool(*b),
262
        Value::String(s) => serde_json::Value::String(s.clone()),
263
        // Lenient: an error-null serialises like a plain null. Strict callers
264
        // check `Value::contains_error` before reaching here.
265
        _ => serde_json::Value::Null,
266
    }
267
}
268
269
fn number_to_json(n: f64) -> serde_json::Value {
270
    if n.is_finite() && n.fract() == 0.0 && n.abs() < 9.007_199_254_740_992e15 {
271
        serde_json::Value::Number((n as i64).into())
272
    } else {
273
        serde_json::Number::from_f64(n)
274
            .map(serde_json::Value::Number)
275
            .unwrap_or(serde_json::Value::Null)
276
    }
277
}
278
279
// --------------------------------------------------------------------------- //
280
// Context mapping (native JsValue -> feel-core Value)
281
// --------------------------------------------------------------------------- //
282
283
/// Build a [`Context`] from a native JS object. `undefined`/`null` is the empty
284
/// context; a plain object maps to a context (its top-level members
285
/// shallow-converted, so nested objects become lazy `Foreign`s); any other
286
/// top-level value is an error.
287
fn context_from_js(value: &JsValue) -> Result<Context, JsError> {
288
    if value.is_null() || value.is_undefined() {
289
        return Ok(Context::new());
290
    }
291
    match js_force(value) {
292
        Value::Context(map) => {
293
            let mut ctx = Context::new();
294
            for (key, val) in map {
295
                ctx.insert(key, val);
296
            }
297
            Ok(ctx)
298
        }
299
        _ => Err(JsError::new("expected an object context")),
300
    }
301
}
302
303
/// Convert a single `JsValue` to a [`Value`] **shallowly** (ADR-21): numbers,
304
/// booleans, strings and `Date` eagerly; an array to a `Value::List` whose elements
305
/// are themselves shallow (an object element becomes a lazy `Foreign`); any other
306
/// object to a `Value::Foreign` resolved on demand. Nothing is walked beyond this
307
/// one level, so cyclic graphs are harmless here.
308
fn shallow_convert_js(value: &JsValue) -> Value {
309
    if value.is_null() || value.is_undefined() {
310
        return Value::Null;
311
    }
312
    if let Some(b) = value.as_bool() {
313
        return Value::Boolean(b);
314
    }
315
    if let Some(n) = value.as_f64() {
316
        return Value::Number(n);
317
    }
318
    if let Some(s) = value.as_string() {
319
        return Value::String(s);
320
    }
321
    if value.is_instance_of::<js_sys::Date>() {
322
        let date: &js_sys::Date = value.unchecked_ref();
323
        let iso = date.to_iso_string().as_string().unwrap_or_default();
324
        return feel_core::temporal_from_iso("date and time", &iso).unwrap_or(Value::Null);
325
    }
326
    // Array before object (an array *is* an object): build the spine, elements stay
327
    // shallow so an object element becomes a lazy `Foreign`.
328
    if js_sys::Array::is_array(value) {
329
        let arr: &js_sys::Array = value.unchecked_ref();
330
        return Value::List(arr.iter().map(|x| shallow_convert_js(&x)).collect());
331
    }
332
    // A JS function becomes a FEEL function value the host can invoke (ADR-23).
333
    // Checked before `is_object` (a function has `typeof === "function"`, not
334
    // `"object"`, but be explicit about ordering).
335
    if value.is_function() {
336
        return Func::Foreign(Arc::new(JsForeignFn { obj: value.clone() })).into_value();
337
    }
338
    if value.is_object() {
339
        return Value::Foreign(Foreign(Arc::new(JsForeign { obj: value.clone() })));
340
    }
341
    Value::Null
342
}
343
344
/// Resolve one member of a JS value by name — the FEEL dot (ADR-21) — via
345
/// `Reflect.get`, which fires JS accessor getters. An absent member (`undefined`)
346
/// is a value-null. The returned value is shallow.
347
fn js_get_member(obj: &JsValue, key: &str) -> Value {
348
    match js_sys::Reflect::get(obj, &JsValue::from_str(key)) {
349
        Ok(v) if v.is_undefined() => Value::Null,
350
        Ok(v) => shallow_convert_js(&v),
351
        Err(_) => Value::Null,
352
    }
353
}
354
355
/// Materialise a `JsValue` *one level* into a concrete [`Value`] (ADR-21): an array
356
/// to a `Value::List`; any other object to a `Value::Context` of its own enumerable
357
/// keys (`Object.keys`); everything else to null. Members are shallow-converted, so
358
/// nested objects stay lazy.
359
fn js_force(value: &JsValue) -> Value {
360
    if js_sys::Array::is_array(value) {
361
        let arr: &js_sys::Array = value.unchecked_ref();
362
        return Value::List(arr.iter().map(|x| shallow_convert_js(&x)).collect());
363
    }
364
    if value.is_object() {
365
        let obj: &js_sys::Object = value.unchecked_ref();
366
        let mut map = BTreeMap::new();
367
        for key in js_sys::Object::keys(obj).iter() {
368
            let val = js_sys::Reflect::get(value, &key).unwrap_or(JsValue::NULL);
369
            map.insert(key.as_string().unwrap_or_default(), shallow_convert_js(&val));
370
        }
371
        return Value::Context(map);
372
    }
373
    Value::Null
374
}
375
376
/// A lazily-resolved JS object behind feel-core's [`ForeignObject`] seam. WASM is
377
/// single-threaded, so the `JsValue` handle is used directly (no GIL/token).
378
#[derive(Debug)]
379
struct JsForeign {
380
    obj: JsValue,
381
}
382
383
impl ForeignObject for JsForeign {
384
    fn get(&self, key: &str) -> Value {
385
        js_get_member(&self.obj, key)
386
    }
387
388
    fn force(&self) -> Value {
389
        js_force(&self.obj)
390
    }
391
392
    fn as_any(&self) -> &dyn std::any::Any {
393
        self
394
    }
395
396
    /// JS object identity for cycle detection in unbounded traversals (the
397
    /// descendant `...` operator). feel-wasm mints a fresh `Arc<JsForeign>` per wrap
398
    /// (`shallow_convert_js` re-runs on every `force`/`get`), and a `JsValue` handle
399
    /// index is NOT object identity across different reads of the same object, so the
400
    /// default (allocation address) guard would miss a cycle. We map each distinct
401
    /// object to a stable integer via a process-wide `WeakMap` ([`js_identity`]).
402
    fn identity(&self) -> usize {
403
        js_identity(&self.obj)
404
    }
405
}
406
407
/// Assign each distinct JS object a stable integer identity via a process-wide
408
/// `WeakMap`. Its keys are weakly referenced, so it neither pins objects nor grows
409
/// unboundedly with live data — entries are GC'd once the object is unreferenced
410
/// elsewhere. This is the JS analogue of feel-py's `id()` / feel-lua's table
411
/// pointer: JS exposes no cheap object address, so a `WeakMap<object, number>` is
412
/// the standard way to derive a hashable, stable identity.
413
fn js_identity(obj: &JsValue) -> usize {
414
    thread_local! {
415
        static IDS: RefCell<(js_sys::WeakMap, u32)> =
416
            RefCell::new((js_sys::WeakMap::new(), 0));
417
    }
418
    IDS.with(|cell| {
419
        let (map, next) = &mut *cell.borrow_mut();
420
        // A Foreign always wraps an object; `unchecked_ref` is the zero-cost view.
421
        let key: &js_sys::Object = obj.unchecked_ref();
422
        if let Some(v) = map.get_checked(key) {
423
            v.as_f64().map(|n| n as usize).unwrap_or(0)
424
        } else {
425
            let n = *next;
426
            *next += 1;
427
            let _ = map.set(key, &JsValue::from(n));
428
            n as usize
429
        }
430
    })
431
}
432
433
// --------------------------------------------------------------------------- //
434
// Host callables (ADR-23): a JS function invoked from FEEL
435
// --------------------------------------------------------------------------- //
436
437
/// A JS function behind feel-core's [`ForeignFunction`] seam. `obj` is the original
438
/// `JsValue` (a function), kept whole for identity pass-through on output.
439
#[derive(Debug)]
440
struct JsForeignFn {
441
    obj: JsValue,
442
}
443
444
impl ForeignFunction for JsForeignFn {
445
    fn call(&self, args: Args) -> Value {
446
        let func: &js_sys::Function = self.obj.unchecked_ref();
447
        match js_call(func, args) {
448
            Ok(v) => shallow_convert_js(&v),
449
            Err(_) => Value::Error, // a thrown JS exception -> error-null (ADR-14)
450
        }
451
    }
452
453
    fn as_any(&self) -> &dyn std::any::Any {
454
        self
455
    }
456
}
457
458
/// Invoke a JS function with FEEL arguments (ADR-23). JS has no keyword arguments,
459
/// so positional FEEL args become positional JS args and — if any named args are
460
/// present — a single trailing options object `{name: value, …}` is appended (the
461
/// idiomatic JS convention). A thrown exception propagates as `Err`.
462
fn js_call(func: &js_sys::Function, args: Args) -> Result<JsValue, JsValue> {
463
    let arr = js_sys::Array::new();
464
    for v in &args.positional {
465
        arr.push(&value_to_js(v).map_err(|_| JsValue::NULL)?);
466
    }
467
    if !args.named.is_empty() {
468
        let opts = js_sys::Object::new();
469
        for (name, v) in &args.named {
470
            js_sys::Reflect::set(
471
                &opts,
472
                &JsValue::from_str(name),
473
                &value_to_js(v).map_err(|_| JsValue::NULL)?,
474
            )?;
475
        }
476
        arr.push(&opts.into());
477
    }
478
    func.apply(&JsValue::NULL, &arr)
479
}
480
481
/// A host function registry backed by a JS object `name -> function` (the third
482
/// `functions` argument; ADR-23). The ambient-function path, beside binding a
483
/// function directly in the context. `undefined`/`null` means no registry.
484
#[derive(Debug)]
485
struct JsFunctionRegistry {
486
    funcs: JsValue,
487
}
488
489
impl FunctionRegistry for JsFunctionRegistry {
490
    fn get(&self, name: &str) -> Option<Arc<dyn ForeignFunction>> {
491
        if self.funcs.is_undefined() || self.funcs.is_null() {
492
            return None;
493
        }
494
        let item = js_sys::Reflect::get(&self.funcs, &JsValue::from_str(name)).ok()?;
495
        if item.is_function() {
496
            Some(Arc::new(JsForeignFn { obj: item }))
497
        } else {
498
            None
499
        }
500
    }
501
502
    /// Conservative (ADR-48): any supplied registry may hold a special name;
503
    /// none supplied lets the special-name pre-check skip all root lookups.
504
    fn may_have_special_names(&self) -> bool {
505
        !self.funcs.is_undefined() && !self.funcs.is_null()
506
    }
507
508
    /// The per-candidate scope check (ADR-48): no wrapper `Arc` is built.
509
    fn contains(&self, name: &str) -> bool {
510
        !self.funcs.is_undefined()
511
            && !self.funcs.is_null()
512
            && js_sys::Reflect::get(&self.funcs, &JsValue::from_str(name))
513
                .is_ok_and(|item| item.is_function())
514
    }
515
}
516
517
// --------------------------------------------------------------------------- //
518
// Host regex provider (ADR-16)
519
// --------------------------------------------------------------------------- //
520
//
521
// The FEEL `matches`/`replace`/`split` builtins run on the **host** regex engine.
522
// In WASM that is the JS `RegExp`, so the ECMAScript dialect applies here — and
523
// the whole Rust regex stack stays out of the bundle. The purist `xpath-regex`
524
// feature instead re-bundles feel-core's `RustRegex` for cross-target identical
525
// results (at the regex stack's size cost).
526
527
/// The provider used for every evaluation. Both candidates are zero-sized.
528
#[cfg(not(feature = "xpath-regex"))]
529
static REGEX: JsRegex = JsRegex;
530
#[cfg(feature = "xpath-regex")]
531
static REGEX: feel_core::RustRegex = feel_core::RustRegex;
532
533
/// JS-`RegExp`-backed [`feel_core::FeelRegex`]. A `null` from the shims means the
534
/// pattern/flags were invalid in the JS dialect, which maps to a FEEL null.
535
#[cfg(not(feature = "xpath-regex"))]
536
struct JsRegex;
537
538
#[cfg(not(feature = "xpath-regex"))]
539
impl feel_core::FeelRegex for JsRegex {
540
    fn is_match(&self, input: &str, pattern: &str, flags: &str) -> Option<bool> {
541
        let (pattern, js_flags) = to_js_pattern(pattern, flags)?;
542
        let r = js_regex_test(input, &pattern, &js_flags);
543
        if r.is_null() {
544
            None
545
        } else {
546
            r.as_bool()
547
        }
548
    }
549
550
    fn replace(
551
        &self,
552
        input: &str,
553
        pattern: &str,
554
        replacement: &str,
555
        flags: &str,
556
    ) -> Option<String> {
557
        let (pattern, js_flags) = to_js_pattern(pattern, flags)?;
558
        let r = js_regex_replace(input, &pattern, &js_flags, replacement);
559
        if r.is_null() {
560
            None
561
        } else {
562
            r.as_string()
563
        }
564
    }
565
566
    fn split(&self, input: &str, delimiter: &str) -> Option<Vec<String>> {
567
        let r = js_regex_split(input, delimiter);
568
        if r.is_null() {
569
            return None;
570
        }
571
        serde_wasm_bindgen::from_value(r).ok()
572
    }
573
}
574
575
/// Map FEEL/XPath flags (`i s m x q`) to (JS pattern, JS RegExp flags). An
576
/// out-of-set flag letter -> `None` (FEEL null), matching the Rust provider's
577
/// validation. `q` escapes the pattern (literal match); `x`
578
/// (whitespace-insensitive) has no JS equivalent and is ignored.
579
#[cfg(not(feature = "xpath-regex"))]
580
fn to_js_pattern(pattern: &str, flags: &str) -> Option<(String, String)> {
581
    if flags.chars().any(|c| !matches!(c, 'i' | 's' | 'm' | 'x' | 'q')) {
582
        return None;
583
    }
584
    let js_flags: String = flags.chars().filter(|c| matches!(c, 'i' | 's' | 'm')).collect();
585
    let pattern = if flags.contains('q') {
586
        js_escape(pattern)
587
    } else {
588
        pattern.to_string()
589
    };
590
    Some((pattern, js_flags))
591
}
592
593
/// Backslash-escape ECMAScript regex metacharacters (for the `q` flag).
594
#[cfg(not(feature = "xpath-regex"))]
595
fn js_escape(pattern: &str) -> String {
596
    const SPECIAL: &str = r"\^$.|?*+()[]{}";
597
    let mut out = String::with_capacity(pattern.len());
598
    for c in pattern.chars() {
599
        if SPECIAL.contains(c) {
600
            out.push('\\');
601
        }
602
        out.push(c);
603
    }
604
    out
605
}
606
607
// `try/catch` shims so an invalid pattern/flags becomes `null` (-> FEEL null)
608
// instead of a thrown JS exception. `replace` adds the `g` flag because XPath
609
// `replace` replaces all matches, whereas JS `String.replace(regex, …)` only
610
// replaces the first without it.
611
#[cfg(not(feature = "xpath-regex"))]
612
#[wasm_bindgen(inline_js = r#"
613
export function feel_regex_test(input, pattern, flags) {
614
  try { return new RegExp(pattern, flags).test(input); } catch (e) { return null; }
615
}
616
export function feel_regex_replace(input, pattern, flags, replacement) {
617
  try { return input.replace(new RegExp(pattern, flags + "g"), replacement); } catch (e) { return null; }
618
}
619
export function feel_regex_split(input, delimiter) {
620
  try { return input.split(new RegExp(delimiter)); } catch (e) { return null; }
621
}
622
"#)]
623
extern "C" {
624
    #[wasm_bindgen(js_name = feel_regex_test)]
625
    fn js_regex_test(input: &str, pattern: &str, flags: &str) -> JsValue;
626
    #[wasm_bindgen(js_name = feel_regex_replace)]
627
    fn js_regex_replace(input: &str, pattern: &str, flags: &str, replacement: &str) -> JsValue;
628
    #[wasm_bindgen(js_name = feel_regex_split)]
629
    fn js_regex_split(input: &str, delimiter: &str) -> JsValue;
630
}