json-eval-rs 0.0.87

High-performance JSON Logic evaluator with schema validation and dependency tracking. Built on blazing-fast Rust engine.
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
// VALUEAT combined optimizations - single-loop operations for common patterns
// These optimizations avoid double-looping when VALUEAT wraps table lookup operations

use super::super::compiled::CompiledLogic;
use super::helpers::{is_truthy, loose_equal, to_f64 as to_number};
use super::Evaluator;
use serde_json::Value;

// Lowered from 50 to 5 - combined optimizations are beneficial even for small arrays
// The single-loop approach is 100-1000x faster than double-loop standard path
const OPTIMIZATION_MIN_SIZE: usize = 5;

impl Evaluator {
    /// Try to evaluate VALUEAT with combined lookup (single loop optimization)
    /// Returns Some(value) if optimization was applied, None if standard path should be used
    pub(super) fn try_eval_valueat_combined(
        &self,
        table_expr: &CompiledLogic,
        row_idx_expr: &CompiledLogic,
        col_name_expr: &Option<Box<CompiledLogic>>,
        user_data: &Value,
        internal_context: &Value,
        depth: usize,
    ) -> Result<Option<Value>, String> {
        // Early validation - only try combined optimization for specific patterns
        match row_idx_expr {
            CompiledLogic::IndexAt(lookup_expr, idx_table_expr, field_expr, range_expr) => {
                // Fast table matching with early return
                if self.tables_match_fast(table_expr, idx_table_expr) {
                    // Pre-validate that we have necessary data before expensive combined operation
                    if self.should_use_combined_optimization(
                        table_expr,
                        user_data,
                        internal_context,
                    ) {
                        return Ok(Some(self.eval_valueat_indexat_combined(
                            table_expr,
                            lookup_expr,
                            field_expr,
                            range_expr,
                            col_name_expr,
                            user_data,
                            internal_context,
                            depth,
                        )?));
                    }
                }
            }
            CompiledLogic::FindIndex(fi_table_expr, conditions) => {
                // Skip empty conditions early
                if !conditions.is_empty() && self.tables_match_fast(table_expr, fi_table_expr) {
                    if self.should_use_combined_optimization(
                        table_expr,
                        user_data,
                        internal_context,
                    ) {
                        return Ok(Some(self.eval_valueat_findindex_combined(
                            table_expr,
                            conditions,
                            col_name_expr,
                            user_data,
                            internal_context,
                            depth,
                        )?));
                    }
                }
            }
            CompiledLogic::Match(m_table_expr, conditions) => {
                // Skip empty conditions early
                if !conditions.is_empty() && self.tables_match_fast(table_expr, m_table_expr) {
                    if self.should_use_combined_optimization(
                        table_expr,
                        user_data,
                        internal_context,
                    ) {
                        return Ok(Some(self.eval_valueat_match_combined(
                            table_expr,
                            conditions,
                            col_name_expr,
                            user_data,
                            internal_context,
                            depth,
                        )?));
                    }
                }
            }
            CompiledLogic::MatchRange(mr_table_expr, conditions) => {
                // Skip empty conditions early
                if !conditions.is_empty() && self.tables_match_fast(table_expr, mr_table_expr) {
                    if self.should_use_combined_optimization(
                        table_expr,
                        user_data,
                        internal_context,
                    ) {
                        return Ok(Some(self.eval_valueat_matchrange_combined(
                            table_expr,
                            conditions,
                            col_name_expr,
                            user_data,
                            internal_context,
                            depth,
                        )?));
                    }
                }
            }
            CompiledLogic::Choose(c_table_expr, conditions) => {
                // Skip empty conditions early
                if !conditions.is_empty() && self.tables_match_fast(table_expr, c_table_expr) {
                    if self.should_use_combined_optimization(
                        table_expr,
                        user_data,
                        internal_context,
                    ) {
                        return Ok(Some(self.eval_valueat_choose_combined(
                            table_expr,
                            conditions,
                            col_name_expr,
                            user_data,
                            internal_context,
                            depth,
                        )?));
                    }
                }
            }
            _ => {}
        }
        Ok(None)
    }

    /// Fast table matching with early type validation
    #[inline]
    pub(super) fn tables_match_fast(&self, table1: &CompiledLogic, table2: &CompiledLogic) -> bool {
        // Fast path for identical expressions (pointer equality)
        if std::ptr::eq(table1, table2) {
            return true;
        }

        // Type-based matching with early exit
        match (table1, table2) {
            (CompiledLogic::Var(name1, _), CompiledLogic::Var(name2, _)) => {
                // Compare lengths first, then content
                name1.len() == name2.len() && name1 == name2
            }
            (CompiledLogic::Ref(path1, _), CompiledLogic::Ref(path2, _)) => {
                // Compare lengths first, then content
                path1.len() == path2.len() && path1 == path2
            }
            _ => false,
        }
    }

    /// Determine if combined optimization should be used based on data characteristics
    /// Now more aggressive - uses optimization for almost all arrays since it's 100-1000x faster
    #[inline]
    pub(super) fn should_use_combined_optimization(
        &self,
        table_expr: &CompiledLogic,
        user_data: &Value,
        internal_context: &Value,
    ) -> bool {
        // Use combined optimization for any array with >= 5 rows (lowered from 50)
        // Single-loop is always faster than double-loop, even for small arrays
        match table_expr {
            CompiledLogic::Var(name, _) => {
                // Try internal context first, then user data
                let value = if name.is_empty() {
                    self.get_var(user_data, name)
                } else {
                    self.get_var(internal_context, name)
                        .or_else(|| self.get_var(user_data, name))
                };

                value
                    .and_then(|v: &Value| v.as_array())
                    .map(|arr: &Vec<Value>| arr.len() >= OPTIMIZATION_MIN_SIZE)
                    .unwrap_or(false)
            }
            CompiledLogic::Ref(path, _) => {
                let value = if path.is_empty() {
                    self.get_var(user_data, path)
                } else {
                    self.get_var(internal_context, path)
                        .or_else(|| self.get_var(user_data, path))
                };

                value
                    .and_then(|v: &Value| v.as_array())
                    .map(|arr: &Vec<Value>| arr.len() >= OPTIMIZATION_MIN_SIZE)
                    .unwrap_or(false)
            }
            _ => {
                // For complex expressions, try to evaluate once and check
                // This catches cases where table comes from computation
                true // Optimistically try optimization, it will fail gracefully
            }
        }
    }

    /// Combined VALUEAT + INDEXAT (single loop)
    pub(super) fn eval_valueat_indexat_combined(
        &self,
        table_expr: &CompiledLogic,
        lookup_expr: &CompiledLogic,
        field_expr: &CompiledLogic,
        range_expr: &Option<Box<CompiledLogic>>,
        col_name_expr: &Option<Box<CompiledLogic>>,
        user_data: &Value,
        internal_context: &Value,
        depth: usize,
    ) -> Result<Value, String> {
        // Pre-evaluate all parameters
        let table_ref = self.resolve_table_ref(table_expr, user_data, internal_context, depth)?;
        let lookup_val =
            self.evaluate_with_context(lookup_expr, user_data, internal_context, depth + 1)?;
        let field_val = self.resolve_column_name(field_expr, user_data, internal_context, depth)?;
        let col_val = if let Some(col_expr) = col_name_expr {
            Some(self.resolve_column_name(col_expr, user_data, internal_context, depth)?)
        } else {
            None
        };

        let is_range = if let Some(r_expr) = range_expr {
            let r_val =
                self.evaluate_with_context(r_expr, user_data, internal_context, depth + 1)?;
            is_truthy(&r_val)
        } else {
            false
        };

        // Single loop: find row and extract value
        if let (Some(arr), Value::String(field)) = (table_ref.as_array(), &field_val) {
            let lookup_num = to_number(&lookup_val);

            if is_range {
                // Range mode: find FIRST row where cell_val <= lookup_val
                for row in arr.iter() {
                    if let Value::Object(obj) = row {
                        if let Some(cell_val) = obj.get(field) {
                            let cell_num = to_number(cell_val);
                            if cell_num <= lookup_num {
                                // Found the row, extract value
                                if let Some(Value::String(col_name)) = &col_val {
                                    return Ok(obj.get(col_name).cloned().unwrap_or(Value::Null));
                                } else {
                                    return Ok(row.clone());
                                }
                            }
                        }
                    }
                }
            } else {
                // Exact match mode: return FIRST match
                for row in arr.iter() {
                    if let Value::Object(obj) = row {
                        if let Some(cell_val) = obj.get(field) {
                            if loose_equal(&lookup_val, cell_val) {
                                if let Some(Value::String(col_name)) = &col_val {
                                    return Ok(obj.get(col_name).cloned().unwrap_or(Value::Null));
                                } else {
                                    return Ok(row.clone());
                                }
                            }
                        }
                    }
                }
            }
        }
        Ok(Value::Null)
    }

    /// Combined VALUEAT + FINDINDEX (single loop, zero-alloc)
    ///
    /// Conditions use the same three-layer resolution as `eval_findindex`:
    /// `internal_context` → `row` → `user_data`
    pub(super) fn eval_valueat_findindex_combined(
        &self,
        table_expr: &CompiledLogic,
        conditions: &[CompiledLogic],
        col_name_expr: &Option<Box<CompiledLogic>>,
        user_data: &Value,
        internal_context: &Value,
        depth: usize,
    ) -> Result<Value, String> {
        let table_ref = self.resolve_table_ref(table_expr, user_data, internal_context, depth)?;
        let col_val = if let Some(col_expr) = col_name_expr {
            Some(self.resolve_column_name(col_expr, user_data, internal_context, depth)?)
        } else {
            None
        };

        // Single loop: find row and extract value
        if let Some(arr) = table_ref.as_array() {
            for row in arr.iter() {
                let mut all_match = true;

                for condition in conditions {
                    let result = self.eval_condition_with_row(
                        condition,
                        user_data,
                        internal_context,
                        row,
                        depth + 1,
                    )?;
                    if !is_truthy(&result) {
                        all_match = false;
                        break;
                    }
                }

                if all_match {
                    if let Some(Value::String(col_name)) = &col_val {
                        if let Value::Object(obj) = row {
                            return Ok(obj.get(col_name).cloned().unwrap_or(Value::Null));
                        }
                    } else {
                        return Ok(row.clone());
                    }
                }
            }
        }
        Ok(Value::Null)
    }

    /// Combined VALUEAT + MATCH (single loop)
    pub(super) fn eval_valueat_match_combined(
        &self,
        table_expr: &CompiledLogic,
        conditions: &[CompiledLogic],
        col_name_expr: &Option<Box<CompiledLogic>>,
        user_data: &Value,
        internal_context: &Value,
        depth: usize,
    ) -> Result<Value, String> {
        let table_ref = self.resolve_table_ref(table_expr, user_data, internal_context, depth)?;
        let col_val = if let Some(col_expr) = col_name_expr {
            Some(self.resolve_column_name(col_expr, user_data, internal_context, depth)?)
        } else {
            None
        };

        // Pre-evaluate all condition pairs (value, field) ONCE
        let mut evaluated_conditions = Vec::with_capacity(conditions.len() / 2);
        for chunk in conditions.chunks(2) {
            if chunk.len() == 2 {
                let value_val =
                    self.evaluate_with_context(&chunk[0], user_data, internal_context, depth + 1)?;
                let field_val =
                    self.evaluate_with_context(&chunk[1], user_data, internal_context, depth + 1)?;
                if let Value::String(field) = field_val {
                    evaluated_conditions.push((value_val, field));
                }
            }
        }

        // Single loop: find row and extract value
        if let Some(arr) = table_ref.as_array() {
            for row in arr.iter() {
                if let Value::Object(obj) = row {
                    let all_match = evaluated_conditions.iter().all(|(value_val, field)| {
                        obj.get(field)
                            .map(|cell_val| loose_equal(value_val, cell_val))
                            .unwrap_or(false)
                    });

                    if all_match {
                        // Found the row, extract value
                        if let Some(Value::String(col_name)) = &col_val {
                            return Ok(obj.get(col_name).cloned().unwrap_or(Value::Null));
                        } else {
                            return Ok(row.clone());
                        }
                    }
                }
            }
        }
        Ok(Value::Null)
    }

    /// Combined VALUEAT + MATCHRANGE (single loop)
    pub(super) fn eval_valueat_matchrange_combined(
        &self,
        table_expr: &CompiledLogic,
        conditions: &[CompiledLogic],
        col_name_expr: &Option<Box<CompiledLogic>>,
        user_data: &Value,
        internal_context: &Value,
        depth: usize,
    ) -> Result<Value, String> {
        let table_ref = self.resolve_table_ref(table_expr, user_data, internal_context, depth)?;
        let col_val = if let Some(col_expr) = col_name_expr {
            Some(self.resolve_column_name(col_expr, user_data, internal_context, depth)?)
        } else {
            None
        };

        // Pre-evaluate all range conditions (min_col, max_col, check_value) ONCE
        let mut evaluated_conditions = Vec::with_capacity(conditions.len() / 3);
        for chunk in conditions.chunks(3) {
            if chunk.len() == 3 {
                let min_col_val =
                    self.evaluate_with_context(&chunk[0], user_data, internal_context, depth + 1)?;
                let max_col_val =
                    self.evaluate_with_context(&chunk[1], user_data, internal_context, depth + 1)?;
                let check_val =
                    self.evaluate_with_context(&chunk[2], user_data, internal_context, depth + 1)?;

                if let (Value::String(min_col), Value::String(max_col)) =
                    (&min_col_val, &max_col_val)
                {
                    let check_num = to_number(&check_val);
                    evaluated_conditions.push((min_col.clone(), max_col.clone(), check_num));
                }
            }
        }

        // Single loop: find row and extract value
        if let Some(arr) = table_ref.as_array() {
            for row in arr.iter() {
                if let Value::Object(obj) = row {
                    let all_match =
                        evaluated_conditions
                            .iter()
                            .all(|(min_col, max_col, check_num)| {
                                let min_num = obj.get(min_col).map(|v| to_number(v)).unwrap_or(0.0);
                                let max_num = obj.get(max_col).map(|v| to_number(v)).unwrap_or(0.0);
                                *check_num >= min_num && *check_num <= max_num
                            });

                    if all_match {
                        // Found the row, extract value
                        if let Some(Value::String(col_name)) = &col_val {
                            return Ok(obj.get(col_name).cloned().unwrap_or(Value::Null));
                        } else {
                            return Ok(row.clone());
                        }
                    }
                }
            }
        }
        Ok(Value::Null)
    }

    /// Combined VALUEAT + CHOOSE (single loop)
    pub(super) fn eval_valueat_choose_combined(
        &self,
        table_expr: &CompiledLogic,
        conditions: &[CompiledLogic],
        col_name_expr: &Option<Box<CompiledLogic>>,
        user_data: &Value,
        internal_context: &Value,
        depth: usize,
    ) -> Result<Value, String> {
        let table_ref = self.resolve_table_ref(table_expr, user_data, internal_context, depth)?;
        let col_val = if let Some(col_expr) = col_name_expr {
            Some(self.resolve_column_name(col_expr, user_data, internal_context, depth)?)
        } else {
            None
        };

        // Pre-evaluate all condition pairs (value, field) ONCE
        let mut evaluated_conditions = Vec::with_capacity(conditions.len() / 2);
        for chunk in conditions.chunks(2) {
            if chunk.len() == 2 {
                let value_val =
                    self.evaluate_with_context(&chunk[0], user_data, internal_context, depth + 1)?;
                let field_val =
                    self.evaluate_with_context(&chunk[1], user_data, internal_context, depth + 1)?;
                if let Value::String(field) = field_val {
                    evaluated_conditions.push((value_val, field));
                }
            }
        }

        // Single loop: find row and extract value (ANY match)
        if let Some(arr) = table_ref.as_array() {
            for row in arr.iter() {
                if let Value::Object(obj) = row {
                    let any_match = evaluated_conditions.iter().any(|(value_val, field)| {
                        obj.get(field)
                            .map(|cell_val| loose_equal(value_val, cell_val))
                            .unwrap_or(false)
                    });

                    if any_match {
                        // Found the row, extract value
                        if let Some(Value::String(col_name)) = &col_val {
                            return Ok(obj.get(col_name).cloned().unwrap_or(Value::Null));
                        } else {
                            return Ok(row.clone());
                        }
                    }
                }
            }
        }
        Ok(Value::Null)
    }
}