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

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