datalogic-rs 4.0.21

A fast, type-safe Rust implementation of JSONLogic for evaluating logical rules as JSON. Perfect for business rules engines and dynamic filtering in Rust applications.
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
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
//! Execution tracing for step-by-step debugging.
//!
//! This module provides execution tracing capabilities for debugging JSONLogic
//! expressions. It generates an expression tree with unique IDs and records
//! each evaluation step for replay in the Web UI.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

use crate::{CompiledNode, OpCode};

/// The result of a traced evaluation, containing both the result and execution trace.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TracedResult {
    /// The evaluation result
    pub result: Value,
    /// Expression tree with unique IDs for flow diagram rendering
    pub expression_tree: ExpressionNode,
    /// Ordered execution steps for replay
    pub steps: Vec<ExecutionStep>,
    /// Top-level error message if evaluation failed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Represents a node in the expression tree for flow diagram rendering.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpressionNode {
    /// Unique identifier for this node
    pub id: u32,
    /// JSON string of this sub-expression
    pub expression: String,
    /// Child nodes (arguments/operands that are operators, not literals)
    pub children: Vec<ExpressionNode>,
}

impl ExpressionNode {
    /// Build an expression tree from a CompiledNode, assigning unique IDs.
    ///
    /// Returns the expression tree and a mapping from node pointers to IDs.
    pub fn build_from_compiled(node: &CompiledNode) -> (ExpressionNode, HashMap<usize, u32>) {
        let mut id_counter = 0u32;
        let mut node_id_map = HashMap::new();
        let tree = Self::build_node(node, &mut id_counter, &mut node_id_map);
        (tree, node_id_map)
    }

    fn build_node(
        node: &CompiledNode,
        id_counter: &mut u32,
        node_id_map: &mut HashMap<usize, u32>,
    ) -> ExpressionNode {
        let id = *id_counter;
        *id_counter += 1;

        // Store the mapping from node pointer to ID
        let node_ptr = node as *const CompiledNode as usize;
        node_id_map.insert(node_ptr, id);

        match node {
            CompiledNode::Value { value, .. } => {
                // Literals don't have children but we still need to represent them
                // in the tree for completeness
                ExpressionNode {
                    id,
                    expression: value.to_string(),
                    children: vec![],
                }
            }
            CompiledNode::Array { nodes, .. } => {
                let children: Vec<ExpressionNode> = nodes
                    .iter()
                    .filter(|n| Self::is_operator_node(n))
                    .map(|n| Self::build_node(n, id_counter, node_id_map))
                    .collect();

                ExpressionNode {
                    id,
                    expression: Self::node_to_json_string(node),
                    children,
                }
            }
            CompiledNode::BuiltinOperator { opcode, args, .. } => {
                let children: Vec<ExpressionNode> = args
                    .iter()
                    .filter(|n| Self::is_operator_node(n))
                    .map(|n| Self::build_node(n, id_counter, node_id_map))
                    .collect();

                ExpressionNode {
                    id,
                    expression: Self::builtin_to_json_string(opcode, args),
                    children,
                }
            }
            CompiledNode::CustomOperator(data) => {
                let children: Vec<ExpressionNode> = data
                    .args
                    .iter()
                    .filter(|n| Self::is_operator_node(n))
                    .map(|n| Self::build_node(n, id_counter, node_id_map))
                    .collect();

                ExpressionNode {
                    id,
                    expression: Self::custom_to_json_string(&data.name, &data.args),
                    children,
                }
            }
            CompiledNode::StructuredObject(data) => {
                let children: Vec<ExpressionNode> = data
                    .fields
                    .iter()
                    .filter(|(_, n)| Self::is_operator_node(n))
                    .map(|(_, n)| Self::build_node(n, id_counter, node_id_map))
                    .collect();

                ExpressionNode {
                    id,
                    expression: Self::structured_to_json_string(&data.fields),
                    children,
                }
            }

            CompiledNode::CompiledVar {
                scope_level,
                segments,
                default_value,
                ..
            } => {
                // CompiledVar has no operator children (default_value is a literal typically)
                let mut children = Vec::new();
                if let Some(def) = default_value
                    && Self::is_operator_node(def)
                {
                    children.push(Self::build_node(def, id_counter, node_id_map));
                }
                ExpressionNode {
                    id,
                    expression: Self::compiled_var_to_json_string(
                        *scope_level,
                        segments,
                        default_value.as_deref(),
                    ),
                    children,
                }
            }

            CompiledNode::CompiledExists(data) => ExpressionNode {
                id,
                expression: Self::compiled_exists_to_json_string(data.scope_level, &data.segments),
                children: vec![],
            },

            CompiledNode::CompiledSplitRegex(data) => {
                let children: Vec<ExpressionNode> = data
                    .args
                    .iter()
                    .filter(|n| Self::is_operator_node(n))
                    .map(|n| Self::build_node(n, id_counter, node_id_map))
                    .collect();
                ExpressionNode {
                    id,
                    expression: format!(
                        "{{\"split\": [{}, \"{}\"]}}",
                        Self::node_to_json_string(&data.args[0]),
                        data.regex.as_str()
                    ),
                    children,
                }
            }

            CompiledNode::CompiledThrow(_) => ExpressionNode {
                id,
                expression: Self::node_to_json_string(node),
                children: vec![],
            },
        }
    }

    /// Check if a node is an operator (not a literal value)
    fn is_operator_node(node: &CompiledNode) -> bool {
        !matches!(node, CompiledNode::Value { .. })
    }

    /// Convert a CompiledNode to its JSON string representation
    fn node_to_json_string(node: &CompiledNode) -> String {
        match node {
            CompiledNode::Value { value, .. } => value.to_string(),
            CompiledNode::Array { nodes, .. } => {
                let items: Vec<String> = nodes.iter().map(Self::node_to_json_string).collect();
                format!("[{}]", items.join(", "))
            }
            CompiledNode::BuiltinOperator { opcode, args, .. } => {
                Self::builtin_to_json_string(opcode, args)
            }
            CompiledNode::CustomOperator(data) => {
                Self::custom_to_json_string(&data.name, &data.args)
            }
            CompiledNode::StructuredObject(data) => Self::structured_to_json_string(&data.fields),
            CompiledNode::CompiledVar {
                scope_level,
                segments,
                default_value,
                ..
            } => {
                Self::compiled_var_to_json_string(*scope_level, segments, default_value.as_deref())
            }
            CompiledNode::CompiledExists(data) => {
                Self::compiled_exists_to_json_string(data.scope_level, &data.segments)
            }
            CompiledNode::CompiledSplitRegex(data) => {
                format!(
                    "{{\"split\": [{}, \"{}\"]}}",
                    Self::node_to_json_string(&data.args[0]),
                    data.regex.as_str()
                )
            }
            CompiledNode::CompiledThrow(error_obj) => {
                if let serde_json::Value::Object(err_map) = error_obj.as_ref()
                    && let Some(serde_json::Value::String(s)) = err_map.get("type")
                {
                    return format!("{{\"throw\": \"{}\"}}", s);
                }
                format!("{{\"throw\": {}}}", error_obj)
            }
        }
    }

    fn builtin_to_json_string(opcode: &OpCode, args: &[CompiledNode]) -> String {
        let op_str = opcode.as_str();
        let args_str = if args.len() == 1 {
            Self::node_to_json_string(&args[0])
        } else {
            let items: Vec<String> = args.iter().map(Self::node_to_json_string).collect();
            format!("[{}]", items.join(", "))
        };
        format!("{{\"{}\": {}}}", op_str, args_str)
    }

    fn custom_to_json_string(name: &str, args: &[CompiledNode]) -> String {
        let args_str = if args.len() == 1 {
            Self::node_to_json_string(&args[0])
        } else {
            let items: Vec<String> = args.iter().map(Self::node_to_json_string).collect();
            format!("[{}]", items.join(", "))
        };
        format!("{{\"{}\": {}}}", name, args_str)
    }

    fn structured_to_json_string(fields: &[(String, CompiledNode)]) -> String {
        let items: Vec<String> = fields
            .iter()
            .map(|(key, node)| format!("\"{}\": {}", key, Self::node_to_json_string(node)))
            .collect();
        format!("{{{}}}", items.join(", "))
    }

    fn compiled_var_to_json_string(
        scope_level: u32,
        segments: &[crate::node::PathSegment],
        default_value: Option<&CompiledNode>,
    ) -> String {
        use crate::node::PathSegment;
        if scope_level == 0 {
            let path: String = segments
                .iter()
                .map(|seg| match seg {
                    PathSegment::Field(s) | PathSegment::FieldOrIndex(s, _) => s.to_string(),
                    PathSegment::Index(i) => i.to_string(),
                })
                .collect::<Vec<_>>()
                .join(".");
            match default_value {
                Some(def) => {
                    format!(
                        "{{\"var\": [\"{}\", {}]}}",
                        path,
                        Self::node_to_json_string(def)
                    )
                }
                None => format!("{{\"var\": \"{}\"}}", path),
            }
        } else {
            let mut parts = vec![format!("[{}]", scope_level)];
            for seg in segments {
                match seg {
                    PathSegment::Field(s) | PathSegment::FieldOrIndex(s, _) => {
                        parts.push(format!("\"{}\"", s))
                    }
                    PathSegment::Index(i) => parts.push(i.to_string()),
                }
            }
            format!("{{\"val\": [{}]}}", parts.join(", "))
        }
    }

    fn compiled_exists_to_json_string(
        _scope_level: u32,
        segments: &[crate::node::PathSegment],
    ) -> String {
        use crate::node::PathSegment;
        if segments.len() == 1 {
            match &segments[0] {
                PathSegment::Field(s) | PathSegment::FieldOrIndex(s, _) => {
                    format!("{{\"exists\": \"{}\"}}", s)
                }
                PathSegment::Index(i) => format!("{{\"exists\": {}}}", i),
            }
        } else {
            let parts: Vec<String> = segments
                .iter()
                .map(|seg| match seg {
                    PathSegment::Field(s) | PathSegment::FieldOrIndex(s, _) => {
                        format!("\"{}\"", s)
                    }
                    PathSegment::Index(i) => i.to_string(),
                })
                .collect();
            format!("{{\"exists\": [{}]}}", parts.join(", "))
        }
    }
}

/// Captures state at each evaluation step.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionStep {
    /// Sequential step number
    pub id: u32,
    /// ID of the node being evaluated
    pub node_id: u32,
    /// Current context/scope data at this step
    pub context: Value,
    /// Result after evaluating this node (None if error)
    pub result: Option<Value>,
    /// Error message if evaluation failed (None if success)
    pub error: Option<String>,
    /// Current iteration index (only for iterator body evaluations)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iteration_index: Option<u32>,
    /// Total iteration count (only for iterator body evaluations)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iteration_total: Option<u32>,
}

/// Collector for execution steps during traced evaluation.
pub struct TraceCollector {
    /// Recorded execution steps
    steps: Vec<ExecutionStep>,
    /// Counter for generating step IDs
    step_counter: u32,
    /// Stack of iteration info (index, total) for nested iterations
    iteration_stack: Vec<(u32, u32)>,
}

impl TraceCollector {
    /// Create a new trace collector
    pub fn new() -> Self {
        Self {
            steps: Vec::new(),
            step_counter: 0,
            iteration_stack: Vec::new(),
        }
    }

    /// Record a successful execution step
    pub fn record_step(&mut self, node_id: u32, context: Value, result: Value) {
        let (iteration_index, iteration_total) = self.current_iteration();
        let step = ExecutionStep {
            id: self.step_counter,
            node_id,
            context,
            result: Some(result),
            error: None,
            iteration_index,
            iteration_total,
        };
        self.steps.push(step);
        self.step_counter += 1;
    }

    /// Record an error execution step
    pub fn record_error(&mut self, node_id: u32, context: Value, error: String) {
        let (iteration_index, iteration_total) = self.current_iteration();
        let step = ExecutionStep {
            id: self.step_counter,
            node_id,
            context,
            result: None,
            error: Some(error),
            iteration_index,
            iteration_total,
        };
        self.steps.push(step);
        self.step_counter += 1;
    }

    /// Push iteration context for map/filter/reduce operations
    pub fn push_iteration(&mut self, index: u32, total: u32) {
        self.iteration_stack.push((index, total));
    }

    /// Pop iteration context
    pub fn pop_iteration(&mut self) {
        self.iteration_stack.pop();
    }

    /// Get current iteration info if inside an iteration
    fn current_iteration(&self) -> (Option<u32>, Option<u32>) {
        self.iteration_stack
            .last()
            .map(|(i, t)| (Some(*i), Some(*t)))
            .unwrap_or((None, None))
    }

    /// Consume the collector and return the recorded steps
    pub fn into_steps(self) -> Vec<ExecutionStep> {
        self.steps
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::OpCode;

    #[test]
    fn test_expression_node_from_simple_operator() {
        // Create a simple {"var": "age"} node
        let node = CompiledNode::BuiltinOperator {
            opcode: OpCode::Var,
            args: vec![CompiledNode::Value {
                value: serde_json::json!("age"),
            }]
            .into_boxed_slice(),
        };

        let (tree, node_id_map) = ExpressionNode::build_from_compiled(&node);

        assert_eq!(tree.id, 0);
        assert_eq!(tree.expression, r#"{"var": "age"}"#);
        assert!(tree.children.is_empty()); // "age" is a literal, not a child
        assert_eq!(node_id_map.len(), 1);
    }

    #[test]
    fn test_expression_node_from_nested_operator() {
        // Create {">=": [{"var": "age"}, 18]}
        let var_node = CompiledNode::BuiltinOperator {
            opcode: OpCode::Var,
            args: vec![CompiledNode::Value {
                value: serde_json::json!("age"),
            }]
            .into_boxed_slice(),
        };
        let node = CompiledNode::BuiltinOperator {
            opcode: OpCode::GreaterThanEqual,
            args: vec![
                var_node,
                CompiledNode::Value {
                    value: serde_json::json!(18),
                },
            ]
            .into_boxed_slice(),
        };

        let (tree, node_id_map) = ExpressionNode::build_from_compiled(&node);

        assert_eq!(tree.id, 0);
        assert!(tree.expression.contains(">="));
        assert_eq!(tree.children.len(), 1); // var node is a child
        assert_eq!(tree.children[0].id, 1);
        assert!(tree.children[0].expression.contains("var"));
        assert_eq!(node_id_map.len(), 2);
    }

    #[test]
    fn test_trace_collector_records_steps() {
        let mut collector = TraceCollector::new();

        collector.record_step(0, serde_json::json!({"age": 25}), serde_json::json!(25));
        collector.record_step(1, serde_json::json!({"age": 25}), serde_json::json!(true));

        let steps = collector.into_steps();
        assert_eq!(steps.len(), 2);
        assert_eq!(steps[0].id, 0);
        assert_eq!(steps[0].node_id, 0);
        assert_eq!(steps[1].id, 1);
        assert_eq!(steps[1].node_id, 1);
    }

    #[test]
    fn test_trace_collector_iteration_context() {
        let mut collector = TraceCollector::new();

        collector.push_iteration(0, 3);
        collector.record_step(2, serde_json::json!(1), serde_json::json!(2));

        let steps = collector.into_steps();
        assert_eq!(steps[0].iteration_index, Some(0));
        assert_eq!(steps[0].iteration_total, Some(3));
    }
}