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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
// Enable the `#[doc(cfg(...))]` attribute on docs.rs builds so feature-gated
// public items render with a "Available on crate feature X only" badge. The
// matching `--cfg docsrs` is passed by `[package.metadata.docs.rs]` in
// Cargo.toml; on a regular stable build this attribute is inert.
//! # datalogic-rs
//!
//! A high-performance, thread-safe Rust implementation of JSONLogic.
//!
//! ## Overview
//!
//! `datalogic-rs` provides a powerful rule evaluation engine that compiles JSONLogic
//! expressions into optimized, reusable structures that can be evaluated across
//! multiple threads with zero overhead.
//!
//! ## Key Features
//!
//! - **Compilation-based optimization**: Parse once, evaluate many times
//! - **Thread-safe by design**: Share compiled logic across threads with `Arc`
//! - **84 built-in operators**: Complete JSONLogic compatibility plus extensions
//! - **Arena-allocated evaluation**: Results live in a `bumpalo::Bump` arena and can borrow directly into caller input for zero-copy paths
//! - **Extensible**: Add custom operators via the [`CustomOperator`] trait
//! - **Structured templates**: Preserve object structure for dynamic outputs
//!
//! ## Quick Start (one-shot)
//!
//! ```rust
//! use datalogic_rs::Engine;
//!
//! let engine = Engine::new();
//! let result = engine.eval_str(
//! r#"{"==": [{"var": "status"}, "active"]}"#,
//! r#"{"status": "active"}"#,
//! ).unwrap();
//! assert_eq!(result, "true");
//! ```
//!
//! ## Reusing the arena across many evaluations
//!
//! For high-throughput callers, open a [`Session`] handle. It owns a
//! [`bumpalo::Bump`], resets it between calls, and returns owned results so
//! you don't have to juggle arena lifetimes:
//!
//! ```rust
//! use datalogic_rs::Engine;
//!
//! let engine = Engine::new();
//! let compiled = engine.compile(r#"{"+": [{"var": "x"}, 1]}"#).unwrap();
//! let mut session = engine.session();
//!
//! for x in 0..3 {
//! let payload = format!(r#"{{"x": {}}}"#, x);
//! let result = session.eval_str(&compiled, &payload).unwrap();
//! assert_eq!(result, (x + 1).to_string());
//! // The session does not auto-reset; bound peak memory by
//! // resetting between iterations (constant-time, reuses chunks).
//! session.reset();
//! }
//! ```
//!
//! ## Power-user (compile once, evaluate many, zero-copy results)
//!
//! When the result borrow can stay scoped to a caller-managed
//! [`bumpalo::Bump`], skip the deep-clone and use [`Engine::evaluate`]
//! directly. `evaluate` accepts any input shape via [`EvalInput`]:
//! `&str`, `&OwnedDataValue`, `&serde_json::Value`, an owned `DataValue<'a>`,
//! or an existing `&'a DataValue<'a>`.
//!
//! ```rust
//! use bumpalo::Bump;
//! use datalogic_rs::Engine;
//!
//! let engine = Engine::new();
//! let compiled = engine.compile(r#"{"==": [{"var": "status"}, "active"]}"#).unwrap();
//!
//! let arena = Bump::new();
//! let result = engine.evaluate(&compiled, r#"{"status": "active"}"#, &arena).unwrap();
//! assert_eq!(result.as_bool(), Some(true));
//! ```
//!
//! ## Architecture
//!
//! The library uses a two-phase approach:
//!
//! 1. **Compilation**: JSON logic is parsed into `Logic` with OpCode dispatch
//! 2. **Evaluation**: Compiled logic is evaluated through arena dispatch — results
//! are `&'a DataValue<'a>` allocated in a `bumpalo::Bump` for the duration of
//! one evaluate call.
//!
//! This design enables sharing compiled logic across threads, eliminates
//! repeated parsing overhead, and lets read-through operations like `var`
//! return zero-copy borrows into the caller's input data.
// Compile and run the crate README's Rust blocks as doctests, so the
// README crates.io renders cannot drift from the API. Gated on the
// features its examples use; `cargo test --all-features` runs them.
;
pub use DataValue;
pub use ArenaExt;
pub use EngineBuilder;
/// The [`bumpalo`] arena allocator, re-exported.
///
/// `Engine::evaluate` and the [`CustomOperator`] trait both take a
/// `&'a bumpalo::Bump` parameter, so callers need a way to construct
/// arenas. Re-exporting locks the major version of `bumpalo` to whatever
/// `datalogic-rs` itself depends on — pair with `use datalogic_rs::bumpalo`
/// instead of an independent `bumpalo` dep to avoid major-version skew.
pub use bumpalo;
pub use ;
pub use ;
/// The `datavalue` crate, re-exported. `datalogic-rs` builds on `datavalue`'s
/// owned and borrowed value types — accessing them through this module makes
/// the dependency explicit at the use site.
///
/// # Working with `DataValue`
///
/// Evaluation returns [`DataValue`] (re-exported at the crate root and
/// also reachable as `datalogic_rs::datavalue::DataValue`). It's an
/// arena-allocated JSON-shaped value tree borrowed from a
/// [`bumpalo::Bump`]. The accessors most callers reach for live in this
/// re-exported crate:
///
/// - **Type predicates** — `.is_null()`, `.is_bool()`, `.is_number()`,
/// `.is_string()`, `.is_array()`, `.is_object()`.
/// - **Owned readers** — `.as_bool()`, `.as_i64()`, `.as_f64()`,
/// `.as_str()`, `.as_array()`, `.as_object()`. Each returns
/// `Option<…>`; the `None` case is "wrong variant," not a runtime error.
/// - **Indexing** — `value["key"]` / `value[idx]` returns `&DataValue`
/// (or the `Null` singleton on miss, matching `serde_json::Value`).
///
/// # Owned vs borrowed
///
/// [`DataValue<'a>`](datavalue::DataValue) borrows from a `Bump`;
/// [`OwnedDataValue`](datavalue::OwnedDataValue) is the heap-owned
/// counterpart. Use the owned form when you need to outlive the arena —
/// caching a result, returning across an `await`, sending across a
/// channel. Convert via `borrowed.to_owned()` and `owned.to_arena(&bump)`.
///
/// # Crossing the `serde_json` boundary
///
/// Conversions to / from `serde_json::Value` are gated behind the
/// `serde_json` feature (kept off by default so the crate has zero
/// external dependencies in the minimal build). With `serde_json`
/// enabled, pass a `&serde_json::Value` into any `eval*` method via
/// [`EvalInput`] / [`IntoLogic`] (a `T: Serialize` is converted first with
/// `serde_json::to_value`; there is no blanket `&T: Serialize` impl), and
/// ask for a `serde_json::Value` (or any `T: DeserializeOwned`) back via
// `Engine::eval_into` / `Session::eval_into` are gated behind
// `serde_json`; link them when the feature is on, otherwise emit them
// as code text so default-features `cargo doc` doesn't break.
/// → JSON String` path use the standard `value.to_string()`, which is
/// what [`Engine::eval_str`] uses internally.
pub use datavalue;
pub use Engine;
pub use Metered;
pub use ;
pub use ;
pub use ;
pub use IntoLogic;
pub use Logic;
pub use ;
pub use Family;
pub use ParsedData;
pub use PathStep;
pub use FromDataValue;
pub use ;
pub use ;
pub use eval_into;
pub use ;
pub use ;
pub use TruthyInput;
// `CompiledNode`, `OpCode`, `MetadataHint`, `PathSegment`, `ReduceHint` were
// public in 4.x. They are compile-internal in v5; consumers reach for them
// via `crate::node::*` / `crate::OpCode` directly.
pub use CompiledNode;
/// Not public API. The operator table's full catalogue, every family
/// whether compiled in or not, for the conformance runner and repository
/// tooling to tell a gated-off operator from a misspelled one.
pub use OpCode;
/// Result type for Engine operations
pub type Result<T> = Result;
/// Custom operator hook for the [`Engine`].
///
/// Implementations receive args **already evaluated** as borrowed
/// [`DataValue`] references and return a `&'a DataValue<'a>` result
/// allocated in the supplied [`bumpalo::Bump`] arena.
///
/// ## Lifetime
///
/// `'a` is the arena lifetime, tied to the [`bumpalo::Bump`] allocator
/// that lives for the duration of one [`Engine::evaluate`] call. Args
/// borrow from the caller's input and from prior arena allocations; the
/// returned `&'a DataValue<'a>` must be allocated in the arena (or be a
/// preallocated singleton) — never a stack reference.
///
/// ## Example
///
/// ```rust
/// use datalogic_rs::{CustomOperator, DataValue, Engine, Result, operator::EvalContext};
/// use bumpalo::Bump;
///
/// struct DoubleArena;
/// impl CustomOperator for DoubleArena {
/// fn evaluate<'a>(
/// &self,
/// args: &[&'a DataValue<'a>],
/// _ctx: &mut EvalContext<'_, 'a>,
/// arena: &'a Bump,
/// ) -> Result<&'a DataValue<'a>> {
/// let n = args.first().and_then(|v| v.as_f64()).unwrap_or(0.0);
/// Ok(arena.alloc(DataValue::from_f64(n * 2.0)))
/// }
/// }
///
/// let engine = Engine::builder().add_operator("double", DoubleArena).build();
///
/// let result = engine.eval_str(r#"{"double": 21}"#, "null").unwrap();
/// assert_eq!(result, "42");
/// ```
///
/// ## Stability
///
/// This trait is the headline extension point of the crate and is
/// intentionally not sealed. Within the **5.x series** the only changes
/// that will be made to this trait are *default-method additions* — no
/// new required methods, no signature changes to [`Self::evaluate`], no
/// lifetime restructuring. Implementations written against 5.0 will
/// compile against every 5.x release without modification. Any breaking
/// change here requires a 6.0 bump.
///
/// The opaque types in the signature ([`crate::DataValue`],
/// [`operator::EvalContext`], [`bumpalo::Bump`]) may evolve internally
/// without breaking this contract, since their public surface is the
/// stable boundary.
/// What the engine may assume about a [`CustomOperator`], returned by
/// [`CustomOperator::info`].
///
/// Build one from [`Self::opaque`] or [`Self::pure`] and the `with` / `-ing`
/// methods; the struct is `#[non_exhaustive]` so fields can be added in 5.x.
///
/// ```rust
/// use datalogic_rs::CustomOperatorInfo;
///
/// // Depends only on its one or two arguments.
/// let info = CustomOperatorInfo::pure().with_args(1, Some(2));
/// assert!(info.deterministic && !info.reads_context);
/// ```
// `Box<dyn CustomOperator>` itself implements `CustomOperator` by
// delegating to the inner trait object. This collapses what used to be
// two separate registration methods on `EngineBuilder` (`add_operator`
// for typed operators, `add_operator_box` for pre-boxed trait objects)
// into a single entry point: `EngineBuilder::add_operator(name, op)`
// accepts either a typed `T: CustomOperator + 'static` or a
// `Box<dyn CustomOperator>` produced by a runtime registry.
// `Arc<T>` delegates the same way, so one operator instance (and any state
// it holds) can be registered on several engines: a host that rebuilds its
// engine on hot reload keeps its operators in a registry of
// `Arc<dyn CustomOperator>` and hands each new builder a clone, with no
// wrapper type of its own.