datalogic-rs 5.8.1

High-performance JSONLogic (json-logic) rules engine and sandboxed expression evaluator in Rust — one core, official bindings for Node.js, WASM, Python, Go, Java, .NET, and PHP. Compile once, evaluate in nanoseconds.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Builder for [`Engine`].
//!
//! The single entry point for non-default engine construction
//! (config, custom operators, templating). Replaces the four ad-hoc
//! 4.x constructors (`new`, `with_preserve_structure`, `with_config`,
//! `with_config_and_structure`).

use std::collections::HashMap;
use std::sync::Arc;

use crate::CustomOperator;
use crate::config::EvaluationConfig;
use crate::engine::Engine;

/// Builder for [`Engine`]. Construct via [`Engine::builder`].
///
/// ```
/// use datalogic_rs::Engine;
///
/// let engine = Engine::builder().build();
/// # let _ = engine;
/// ```
///
/// # Defaults
///
/// `Engine::builder().build()` produces the same engine as
/// [`Engine::new`] / [`Engine::default`]:
///
/// - **`config`** — [`EvaluationConfig::default`]: JavaScript-flavoured
///   truthiness, NaN errors on bad arithmetic input, `±f64::MAX` on
///   division by zero, `loose_equality_errors = true`,
///   `max_recursion_depth = 256`, and the implicit `null`/`bool`/
///   `""` → 0 numeric coercions enabled. Override with [`Self::with_config`];
///   [`EvaluationConfig::safe_arithmetic`] / [`EvaluationConfig::strict`]
///   are alternative starting points.
/// - **`templating`** — `false` (templating mode off). Set with
///   [`Self::with_templating`]; only effective when the crate is
///   built with `feature = "templating"`.
/// - **`template_key_escape`** — `None` (no escape prefix; a single-key
///   object whose key names an operator is always an operator
///   invocation). Set with [`Self::with_template_key_escape`].
/// - **`operators`** — empty. Add custom operators with
///   [`Self::add_operator`] before [`Self::build`] freezes the set.
/// - **`constant_folding`** — `true`. The compile pipeline pre-computes
///   constant sub-expressions during [`Engine::compile`]. Disable with
///   [`Self::with_constant_folding`] when you need every operator to
///   survive in the compiled tree (e.g. for tooling that walks the
///   structure or applies its own rewrites).
#[derive(Clone)]
#[must_use = "the builder is consumed by `.build()`"]
pub struct EngineBuilder {
    settings: EngineSettings,
    operators: HashMap<String, Arc<dyn CustomOperator>>,
}

/// Every family bit: the default family set.
pub(crate) const ALL_FAMILIES: u32 = u32::MAX;

/// The settings an [`EngineBuilder`] collects and an [`Engine`] keeps.
///
/// One struct, handed over whole in both directions
/// ([`EngineBuilder::build`], [`Engine::to_builder`]), so a setting is
/// declared and defaulted in one place and cannot be dropped or swapped
/// on the way through.
#[derive(Clone, Debug)]
pub(crate) struct EngineSettings {
    pub(crate) config: EvaluationConfig,
    /// Whether templating mode is enabled — multi-key objects compile
    /// to output-shaping templates and unknown operator keys pass through.
    /// Always `false` on an engine built without the `templating` feature.
    pub(crate) templating: bool,
    /// Escape prefix that marks a template object key as a literal output
    /// field rather than an operator invocation. See
    /// [`EngineBuilder::with_template_key_escape`].
    pub(crate) template_key_escape: Option<char>,
    /// Whether `Engine::compile` runs the constant-folding pass. See
    /// [`EngineBuilder::with_constant_folding`].
    pub(crate) constant_folding: bool,
    /// The built-in families the engine has, as [`crate::Family`] bits;
    /// see [`EngineBuilder::with_families`].
    pub(crate) families: u32,
    /// The names registered through [`EngineBuilder::try_add_operator`],
    /// which [`EngineBuilder::try_build`] checks again against the final
    /// settings. Kept on the engine so [`Engine::to_builder`] carries the
    /// check over.
    pub(crate) checked_names: Vec<String>,
}

impl Default for EngineSettings {
    fn default() -> Self {
        Self {
            config: EvaluationConfig::default(),
            templating: false,
            template_key_escape: None,
            constant_folding: true,
            families: ALL_FAMILIES,
            checked_names: Vec::new(),
        }
    }
}

impl Default for EngineBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl EngineBuilder {
    /// Fresh builder with default config and no custom operators.
    #[inline]
    pub fn new() -> Self {
        Self {
            settings: EngineSettings::default(),
            operators: HashMap::new(),
        }
    }

    /// Set the evaluation config.
    #[inline]
    #[must_use = "builder methods return a new builder; chain into `.build()`"]
    pub fn with_config(mut self, config: EvaluationConfig) -> Self {
        self.settings.config = config;
        self
    }

    /// Toggle templating mode (multi-key objects compile to output-shaping
    /// templates; unknown operator keys pass through verbatim). Only
    /// effective when the crate is built with `feature = "templating"`.
    #[inline]
    #[must_use = "builder methods return a new builder; chain into `.build()`"]
    pub fn with_templating(mut self, on: bool) -> Self {
        self.settings.templating = on;
        self
    }

    /// Set the escape prefix that marks a template object key as a literal
    /// output field instead of an operator invocation. Unset by default.
    ///
    /// Without it, a single-key object whose key names an operator is an
    /// operator call, so the built-in names (87 with every operator family:
    /// `type`, `map`, `if`, `keys`, `length`, `+`, …) and every registered
    /// custom operator are unreachable as output keys.
    /// With it, exactly one leading `prefix` is stripped from every template
    /// key, and an escaped key is never resolved as an operator:
    ///
    /// | Template key | Output key |
    /// |--------------|------------|
    /// | `$type`      | `type`     |
    /// | `$$type`     | `$type`    |
    /// | `$$$type`    | `$$type`   |
    /// | `$foo`       | `foo`      |
    /// | `type`       | not a key: still the `type` operator |
    ///
    /// Stripping is uniform across arities, so a key's source text always
    /// maps to the same output name whether or not it has siblings. Two
    /// consequences worth knowing: `{"$a": 1, "a": 2}` emits the key `a`
    /// twice (the engine keeps duplicate pairs, as `keys`/`values`/`entries`
    /// already do), and a bare `{"$": 1}` emits the empty key.
    ///
    /// `prefix` is a `char` rather than a fixed `$` because `$` already
    /// begins real keys in MongoDB documents and JSON Schema output; those
    /// callers can pick `~` or `#` and leave their `$` keys untouched.
    ///
    /// It applies wherever a rule compiles as a template, with
    /// `feature = "templating"`: on an engine in templating mode
    /// ([`Self::with_templating`]) and through `Engine::compile_template`
    /// on any engine. A strict compile reads
    /// every single-key object as an operator invocation, so there is
    /// nothing to escape *into* and the setting does nothing there.
    ///
    /// ```
    /// use datalogic_rs::Engine;
    ///
    /// let engine = Engine::builder()
    ///     .with_templating(true)
    ///     .with_template_key_escape('$')
    ///     .build();
    /// # let _ = engine;
    /// ```
    #[inline]
    #[must_use = "builder methods return a new builder; chain into `.build()`"]
    pub fn with_template_key_escape(mut self, prefix: char) -> Self {
        self.settings.template_key_escape = Some(prefix);
        self
    }

    /// Toggle the compile-time constant-folding pass. Default: `true`
    /// (folding enabled). Pass `false` when every operator must survive
    /// in the compiled tree — debuggers, alternate evaluators, or any
    /// caller that walks the compiled structure and would be surprised
    /// to see a `{"+": [1, 2]}` collapsed to a `3` literal.
    // The trace-feature addendum links to `Engine::trace`, which only
    // exists with `feature = "trace"`. Gate the whole paragraph behind
    // the same feature so `cargo doc` without `--all-features` doesn't
    // break on the intra-doc link.
    #[cfg_attr(feature = "trace", doc = "")]
    #[cfg_attr(
        feature = "trace",
        doc = "The trace surface ([`crate::Engine::trace`]) always disables folding"
    )]
    #[cfg_attr(
        feature = "trace",
        doc = "internally regardless of this setting, since traces would otherwise"
    )]
    #[cfg_attr(feature = "trace", doc = "lose the folded operators as steps.")]
    #[inline]
    #[must_use = "builder methods return a new builder; chain into `.build()`"]
    pub fn with_constant_folding(mut self, on: bool) -> Self {
        self.settings.constant_folding = on;
        self
    }

    /// Register a [`CustomOperator`] under `name`. Multiple calls with the
    /// same name overwrite the prior registration.
    ///
    /// Accepts both typed operators (`T: CustomOperator + 'static`) and
    /// pre-boxed trait objects (`Box<dyn CustomOperator>`) — the bare
    /// `Box<dyn CustomOperator>` itself implements `CustomOperator`
    /// (delegating to the inner), so a single entry point covers both
    /// shapes:
    ///
    /// ```ignore
    /// builder
    ///     .add_operator("typed", MyOp)                            // typed
    ///     .add_operator("dyn", boxed_op_from_registry as Box<_>)  // pre-boxed
    /// ```
    ///
    /// Operator registration is builder-only; once [`Self::build`] hands
    /// you an [`Engine`], its operator set is frozen.
    ///
    /// **Built-ins always win.** If `name` collides with a built-in
    /// JSONLogic operator (`+`, `if`, `var`, `map`, …), the built-in is
    /// dispatched and the registered custom op is never reached. To
    /// extend the operator set, choose a name that doesn't parse as a
    /// built-in, or register through [`Self::try_add_operator`], which
    /// refuses such a name instead.
    #[inline]
    #[must_use = "builder methods return a new builder; chain into `.build()`"]
    pub fn add_operator<T>(mut self, name: impl Into<String>, operator: T) -> Self
    where
        T: CustomOperator + 'static,
    {
        self.operators.insert(name.into(), Arc::new(operator));
        self
    }

    /// [`Self::add_operator`], refusing a name a built-in operator of this
    /// build answers to (a canonical name or an alias such as `var` or
    /// `?:`), where the custom operator would never run.
    ///
    /// Only operators compiled into this build count: without the
    /// `datetime` feature, `now` is a free name.
    ///
    /// # Errors
    ///
    /// [`crate::ErrorKind::ConfigurationError`] naming the built-in that
    /// would win.
    ///
    /// # Example
    ///
    /// ```rust
    /// use datalogic_rs::{
    ///     CustomOperator, DataValue, Engine, ErrorCode, Result, operator::EvalContext,
    /// };
    ///
    /// struct Answer;
    /// impl CustomOperator for Answer {
    ///     fn evaluate<'a>(
    ///         &self,
    ///         _args: &[&'a DataValue<'a>],
    ///         _ctx: &mut EvalContext<'_, 'a>,
    ///         arena: &'a bumpalo::Bump,
    ///     ) -> Result<&'a DataValue<'a>> {
    ///         Ok(arena.alloc(DataValue::from_f64(42.0)))
    ///     }
    /// }
    ///
    /// assert!(Engine::builder().try_add_operator("answer", Answer).is_ok());
    /// let err = Engine::builder().try_add_operator("if", Answer).err().unwrap();
    /// assert_eq!(err.code(), ErrorCode::ConfigurationError);
    /// ```
    pub fn try_add_operator<T>(self, name: impl Into<String>, operator: T) -> crate::Result<Self>
    where
        T: CustomOperator + 'static,
    {
        let name = name.into();
        self.check_operator_name(&name)?;
        let mut builder = self.add_operator(name.clone(), operator);
        builder.settings.checked_names.push(name);
        Ok(builder)
    }

    /// The refusal [`Self::try_add_operator`] gives a custom operator named
    /// `name`, without registering anything: a `ConfigurationError` when a
    /// built-in of this builder's families answers to the name, or when
    /// the name begins with the [template key
    /// escape](Self::with_template_key_escape), which makes such a key an
    /// output field. For a host that must keep the builder whether or not
    /// the name is taken.
    ///
    /// The check reads the builder's settings when it is called; set
    /// [`Self::with_families`] and the escape first, or build with
    /// [`Self::try_build`], which checks every such name again.
    ///
    /// ```rust
    /// use datalogic_rs::{Engine, Family};
    ///
    /// assert!(Engine::builder().check_operator_name("if").is_err());
    /// // `upper` is free once its family is left out.
    /// let core = Engine::builder().with_families([Family::ExtArray]);
    /// assert!(core.check_operator_name("upper").is_ok());
    /// ```
    pub fn check_operator_name(&self, name: &str) -> crate::Result<()> {
        if let Some(builtin) = crate::engine::builtin_in(self.settings.families, name) {
            return Err(crate::Error::configuration_error(format!(
                "custom operator `{name}` would never run: the built-in operator `{}` answers to that name",
                builtin.as_str()
            )));
        }
        if let Some(escape) = self.settings.template_key_escape
            && name.starts_with(escape)
        {
            return Err(crate::Error::configuration_error(format!(
                "custom operator `{name}` would never run in a template: it begins with the template key escape `{escape}`"
            )));
        }
        Ok(())
    }

    /// [`Self::check_operator_name`] for every name registered through
    /// [`Self::try_add_operator`], against the builder's settings now: a
    /// name checked before [`Self::with_families`] or
    /// [`Self::with_template_key_escape`] changed them may be taken since.
    ///
    /// # Errors
    ///
    /// The first name's `ConfigurationError`, in registration order.
    pub fn check_operator_names(&self) -> crate::Result<()> {
        self.settings
            .checked_names
            .iter()
            .try_for_each(|name| self.check_operator_name(name))
    }

    /// Keep the engine to the JSONLogic core and the extension families
    /// named here; by default it has every family this build compiled in.
    /// A family left out (or not compiled in) is not there for this engine:
    /// its operator names compile as unknown operators, as output fields in
    /// templating mode, or as a custom operator registered under that name.
    /// [`Engine::operators`] and [`Engine::builtin_operator_names`] list
    /// only what the engine has, and [`Self::try_add_operator`] refuses only
    /// those names. [`Family::Core`](crate::Family::Core) is always there,
    /// named or not.
    ///
    /// The set applies when a rule is compiled. A rule compiled on another
    /// engine keeps its operators wherever it is evaluated.
    ///
    /// ```rust
    /// use datalogic_rs::{Engine, Family};
    ///
    /// # #[cfg(all(feature = "ext-string", feature = "ext-array"))] {
    /// // The JSONLogic core and the string extensions, nothing else.
    /// let engine = Engine::builder().with_families([Family::ExtString]).build();
    /// assert_eq!(engine.eval_str(r#"{"upper": "a"}"#, "null").unwrap(), r#""A""#);
    /// // `sort` is an unknown operator here, as `length` would be on an
    /// // engine without `ExtString`.
    /// assert!(engine.eval_str(r#"{"sort": [[2, 1]]}"#, "null").is_err());
    /// assert!(engine.compile_checked(r#"{"sort": [[2, 1]]}"#).is_err());
    /// # }
    /// ```
    #[must_use = "builder methods return a new builder; chain into `.build()`"]
    pub fn with_families(mut self, families: impl IntoIterator<Item = crate::Family>) -> Self {
        self.settings.families = families
            .into_iter()
            .fold(crate::Family::Core.bit(), |set, f| set | f.bit());
        self
    }

    /// A builder holding `engine`'s operators and settings: the
    /// [`Engine::to_builder`] seam.
    pub(crate) fn from_engine_parts(
        settings: EngineSettings,
        operators: HashMap<String, Arc<dyn CustomOperator>>,
    ) -> Self {
        Self {
            settings,
            operators,
        }
    }

    /// [`Self::build`], first checking every name registered through
    /// [`Self::try_add_operator`] again ([`Self::check_operator_names`]),
    /// so the refusal holds whatever order the settings were given in.
    ///
    /// ```rust
    /// use datalogic_rs::{CustomOperator, DataValue, Engine, Family, Result, operator::EvalContext};
    ///
    /// struct Up;
    /// impl CustomOperator for Up {
    ///     fn evaluate<'a>(
    ///         &self,
    ///         args: &[&'a DataValue<'a>],
    ///         _ctx: &mut EvalContext<'_, 'a>,
    ///         _arena: &'a datalogic_rs::bumpalo::Bump,
    ///     ) -> Result<&'a DataValue<'a>> {
    ///         Ok(args[0])
    ///     }
    /// }
    ///
    /// # #[cfg(feature = "ext-string")] {
    /// // `upper` is free without the string family, then taken once it is
    /// // added back.
    /// let builder = Engine::builder()
    ///     .with_families([Family::ExtArray])
    ///     .try_add_operator("upper", Up)
    ///     .unwrap()
    ///     .with_families([Family::ExtString]);
    /// assert!(builder.try_build().is_err());
    /// # }
    /// ```
    ///
    /// It also refuses a config whose
    /// [`max_recursion_depth`](EvaluationConfig::max_recursion_depth) is 0,
    /// as `EvaluationConfig::from_json_str` does: at 0 no evaluation on
    /// an engine with custom operators could start.
    ///
    /// # Errors
    ///
    /// The first name's `ConfigurationError`, in registration order, or a
    /// `ConfigurationError` for a `max_recursion_depth` of 0.
    pub fn try_build(self) -> crate::Result<Engine> {
        self.check_operator_names()?;
        if self.settings.config.max_recursion_depth == 0 {
            return Err(crate::Error::configuration_error(format!(
                "max_recursion_depth must be an integer between 1 and {}",
                u32::MAX
            )));
        }
        Ok(self.build())
    }

    /// Finalise the builder into an immutable [`Engine`] engine.
    pub fn build(self) -> Engine {
        Engine::from_builder_parts(self.settings, self.operators)
    }
}