json-eval-rs 0.0.125

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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
use super::compiled::CompiledLogic;
use super::config::RLogicConfig;
use index::TableIndex;
use serde_json::Value;
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::sync::RwLock;

pub mod arithmetic;
pub mod array_lookup;
pub mod array_ops;
pub mod comparison;
pub mod date_ops;
pub mod helpers;
pub mod index;
pub mod logical;
pub mod math_ops;
pub mod optimizations;
pub mod string_ops;
pub mod types;

pub use helpers::*;
pub use types::*;

/// Active self-table scope set during `evaluate_table_inner`.
///
/// # Safety
/// `rows` is a raw pointer to `local_rows` on the stack of `evaluate_table_inner`.
/// Valid lifetime: from `enter_table_scope()` to `TableScopeGuard::drop()`.
/// Evaluation is single-threaded (protected by `eval_lock` in `evaluate_internal`).
const EMPTY_CACHE_SLOT: std::cell::Cell<(usize, u32, u32)> = std::cell::Cell::new((0, 0, 0));

pub(crate) struct TableScope {
    /// Normalized JSON pointer path to the table being evaluated
    pub path: String,
    /// Path without leading '#' for zero-overhead matching
    pub path_no_hash: String,
    /// Pointer to the local rows being built in table_evaluate_inner
    pub rows: *const Vec<Value>,
    /// Pointer to flat cells storage (total_rows * col_count) during Repeat
    pub flat_cells: *mut Value,
    pub col_count: usize,
    pub total_rows: usize,
    pub existing_row_count: usize,
    /// Fast mapping from column name to column index
    pub col_map: rapidhash::RapidHashMap<String, usize>,
    /// Direct-mapped 256-slot cache with pointer-identity fast path for rapid column resolution
    pub col_cache: [std::cell::Cell<(usize, u32, u32)>; 256],
    /// Optional cursor to the current row index being evaluated (for fast $column lookup)
    pub current_row: Option<usize>,
    /// Precomputed row base pointer in flat_cells for O(1) cell access
    pub current_row_base: *mut Value,
    /// Raw iteration integer value
    pub iteration_raw: Option<i64>,
    /// Optional pre-computed iteration value for O(1) $iteration resolution
    pub iteration_val: Option<Value>,
    /// Optional pre-computed threshold value for O(1) $threshold resolution
    pub threshold_val: Option<Value>,
    /// Memoization cache for combined array lookups on immutable borrowed reference tables
    pub lookup_cache:
        std::cell::RefCell<rapidhash::RapidHashMap<types::CombinedLookupKey, Option<usize>>>,
}

impl TableScope {
    #[inline(always)]
    pub fn get_col_idx(&self, col_name: &str) -> Option<usize> {
        let ptr = col_name.as_ptr() as usize;
        let len = col_name.len() as u32;
        let slot = (ptr ^ (ptr >> 6) ^ (len as usize)) & 255;
        let entry = self.col_cache[slot].get();
        if entry.0 == ptr && entry.1 == len && ptr != 0 {
            return Some(entry.2 as usize);
        }
        if let Some(&col_idx) = self.col_map.get(col_name) {
            self.col_cache[slot].set((ptr, len, col_idx as u32));
            Some(col_idx)
        } else {
            None
        }
    }
}

thread_local! {
    static TABLE_SCOPE: UnsafeCell<Option<TableScope>> = const { UnsafeCell::new(None) };
    static STATIC_ARRAYS: UnsafeCell<Option<std::sync::Arc<indexmap::IndexMap<String, std::sync::Arc<Value>>>>> = const { UnsafeCell::new(None) };
}

// SAFETY: TableScope and STATIC_ARRAYS are accessed only by the current thread via thread_local storage.
unsafe impl Send for TableScope {}
unsafe impl Send for Evaluator {}
unsafe impl Sync for Evaluator {}

/// RAII guard that restores the previous active STATIC_ARRAYS on drop
pub struct StaticArraysGuard {
    previous: Option<std::sync::Arc<indexmap::IndexMap<String, std::sync::Arc<Value>>>>,
}

impl Drop for StaticArraysGuard {
    fn drop(&mut self) {
        STATIC_ARRAYS.with(|cell| unsafe {
            *cell.get() = self.previous.take();
        });
    }
}

/// RAII guard that clears the active TableScope on drop
pub struct TableScopeGuard<'a> {
    evaluator: &'a Evaluator,
}

impl<'a> Drop for TableScopeGuard<'a> {
    fn drop(&mut self) {
        unsafe {
            *self.evaluator.table_scope_mut() = None;
        }
    }
}

/// High-performance zero-copy evaluator with dual-context support
///
/// ## Design Principles
/// 1. **Zero-copy**: All data access via references, no cloning
/// 2. **Dual-context**: Separate user_data and internal_context for scoped variables
/// 3. **Recursive**: Clean recursive evaluation with depth tracking
///
/// ## Context Resolution
/// - Variables ($var) lookup order: internal_context → user_data
/// - Internal context holds: $iteration, $threshold, $loopIteration, etc.
pub struct Evaluator {
    config: RLogicConfig,
    /// Upfront indices for large tables (name -> index)
    indices: RwLock<HashMap<String, TableIndex>>,
}

impl Evaluator {
    pub fn new() -> Self {
        Self {
            config: RLogicConfig::default(),
            indices: RwLock::new(HashMap::new()),
        }
    }

    #[inline(always)]
    pub(crate) unsafe fn table_scope_ref(&self) -> &Option<TableScope> {
        TABLE_SCOPE.with(|cell| &*cell.get())
    }

    #[inline(always)]
    pub(crate) unsafe fn table_scope_mut(&self) -> &mut Option<TableScope> {
        TABLE_SCOPE.with(|cell| &mut *cell.get())
    }

    #[inline(always)]
    pub(crate) unsafe fn static_arrays_ref(
        &self,
    ) -> &Option<std::sync::Arc<indexmap::IndexMap<String, std::sync::Arc<Value>>>> {
        STATIC_ARRAYS.with(|cell| &*cell.get())
    }

    #[inline(always)]
    pub(crate) unsafe fn static_arrays_mut(
        &self,
    ) -> &mut Option<std::sync::Arc<indexmap::IndexMap<String, std::sync::Arc<Value>>>> {
        STATIC_ARRAYS.with(|cell| &mut *cell.get())
    }

    /// Register a table scope for self-reference interception.
    ///
    /// Returns a guard that clears the scope on drop.
    ///
    /// # Safety
    /// `rows` must outlive the returned guard. The guard MUST be dropped before
    /// `rows` is moved or dropped. Caller (table_evaluate_inner) is responsible.
    pub(crate) fn enter_table_scope<'a>(
        &'a self,
        path: String,
        rows: &Vec<Value>,
    ) -> TableScopeGuard<'a> {
        let path_no_hash = path.trim_start_matches('#').to_string();
        unsafe {
            *self.table_scope_mut() = Some(TableScope {
                path,
                path_no_hash,
                rows: rows as *const Vec<Value>,
                flat_cells: std::ptr::null_mut(),
                col_count: 0,
                total_rows: 0,
                existing_row_count: 0,
                col_map: rapidhash::RapidHashMap::default(),
                col_cache: [EMPTY_CACHE_SLOT; 256],
                current_row: None,
                current_row_base: std::ptr::null_mut(),
                iteration_raw: None,
                iteration_val: None,
                threshold_val: None,
                lookup_cache: std::cell::RefCell::new(rapidhash::RapidHashMap::default()),
            });
        }
        TableScopeGuard { evaluator: self }
    }

    /// Register flat cell buffer and column mappings for fast direct indexed evaluation
    pub(crate) fn set_table_scope_flat_cells(
        &self,
        cells: *mut Value,
        col_count: usize,
        total_rows: usize,
        existing_row_count: usize,
        col_map: rapidhash::RapidHashMap<String, usize>,
    ) {
        unsafe {
            if let Some(ts) = (*self.table_scope_mut()).as_mut() {
                ts.flat_cells = cells;
                ts.col_count = col_count;
                ts.total_rows = total_rows;
                ts.existing_row_count = existing_row_count;
                ts.col_map = col_map;
                ts.col_cache = [EMPTY_CACHE_SLOT; 256];
                ts.current_row_base = std::ptr::null_mut();
            }
        }
    }

    /// Update the rows pointer in the active table scope.
    pub(crate) fn update_table_scope_rows(&self, rows: &Vec<Value>) {
        unsafe {
            if let Some(ts) = (*self.table_scope_mut()).as_mut() {
                ts.rows = rows as *const Vec<Value>;
            }
        }
    }

    /// Set the row cursor for the active table scope
    pub(crate) fn set_table_scope_row(&self, row_idx: Option<usize>) {
        unsafe {
            if let Some(ts) = (*self.table_scope_mut()).as_mut() {
                ts.current_row = row_idx;
                if let Some(r) = row_idx {
                    if ts.col_count > 0
                        && !ts.flat_cells.is_null()
                        && r >= ts.existing_row_count
                        && r < ts.existing_row_count + ts.total_rows
                    {
                        ts.current_row_base = ts
                            .flat_cells
                            .add((r - ts.existing_row_count) * ts.col_count);
                    } else {
                        ts.current_row_base = std::ptr::null_mut();
                    }
                } else {
                    ts.current_row_base = std::ptr::null_mut();
                }
            }
        }
    }

    /// Set the row cursor and pre-computed iteration value for the active table scope
    pub(crate) fn set_table_scope_cursor(&self, row_idx: Option<usize>, iteration: Option<i64>) {
        unsafe {
            if let Some(ts) = (*self.table_scope_mut()).as_mut() {
                ts.current_row = row_idx;
                ts.iteration_raw = iteration;
                ts.iteration_val = iteration.map(Value::from);
                if let Some(r) = row_idx {
                    if ts.col_count > 0
                        && !ts.flat_cells.is_null()
                        && r >= ts.existing_row_count
                        && r < ts.existing_row_count + ts.total_rows
                    {
                        ts.current_row_base = ts
                            .flat_cells
                            .add((r - ts.existing_row_count) * ts.col_count);
                    } else {
                        ts.current_row_base = std::ptr::null_mut();
                    }
                } else {
                    ts.current_row_base = std::ptr::null_mut();
                }
            }
        }
    }

    /// Set the threshold value for the active table scope
    pub(crate) fn set_table_scope_threshold(&self, threshold: i64) {
        unsafe {
            if let Some(ts) = (*self.table_scope_mut()).as_mut() {
                ts.threshold_val = Some(Value::from(threshold));
            }
        }
    }

    pub fn with_config(mut self, config: RLogicConfig) -> Self {
        self.config = config;
        self
    }

    /// Bind static arrays to the current thread for the duration of a scope
    pub fn bind_static_arrays_scope(
        &self,
        static_arrays: std::sync::Arc<indexmap::IndexMap<String, std::sync::Arc<Value>>>,
    ) -> StaticArraysGuard {
        let previous = STATIC_ARRAYS.with(|cell| unsafe {
            let prev = (*cell.get()).take();
            *cell.get() = Some(static_arrays);
            prev
        });
        StaticArraysGuard { previous }
    }

    /// Set static arrays for evaluation context on the current thread
    pub fn set_static_arrays(
        &self,
        static_arrays: std::sync::Arc<indexmap::IndexMap<String, std::sync::Arc<Value>>>,
    ) {
        unsafe {
            *self.static_arrays_mut() = Some(static_arrays);
        }
    }

    /// Clear static arrays for the current thread
    pub fn clear_static_arrays(&self) {
        unsafe {
            *self.static_arrays_mut() = None;
        }
    }

    /// Build and store index for a table
    pub fn index_table(&self, name: &str, data: &Value) {
        if let Some(index) = TableIndex::new(data) {
            if let Ok(mut indices) = self.indices.write() {
                indices.insert(name.to_string(), index);
            }
        }
    }

    /// Clear all stored indices
    pub fn clear_indices(&self) {
        if let Ok(mut indices) = self.indices.write() {
            indices.clear();
        }
    }

    /// Public API: Evaluate compiled logic with user data only
    /// Uses fast path for simple cases to avoid recursion overhead
    #[inline]
    pub fn evaluate(&self, logic: &CompiledLogic, data: &Value) -> Result<Value, String> {
        // Fast path for literals (most common cases)
        match logic {
            CompiledLogic::Null => return Ok(Value::Null),
            CompiledLogic::Bool(b) => return Ok(Value::Bool(*b)),
            CompiledLogic::Number(n) => {
                return Ok(self.f64_to_json(*n));
            }
            CompiledLogic::String(s) => return Ok(Value::String(s.clone())),
            CompiledLogic::Var(name, None) if !name.is_empty() => {
                // Simple variable without default
                return self.eval_var_or_default(name, &None, data, &Value::Null, 0);
            }
            CompiledLogic::Ref(path, None) if !path.is_empty() => {
                // Simple variable without default
                return self.eval_var_or_default(path, &None, data, &Value::Null, 0);
            }
            // Fast path for arithmetic operations
            CompiledLogic::Add(_)
            | CompiledLogic::Subtract(_)
            | CompiledLogic::Multiply(_)
            | CompiledLogic::Divide(_) => {
                if let Some(result) = self.eval_f64(logic, data, &Value::Null, 0)? {
                    return Ok(self.f64_to_json(result));
                }
            }
            _ => {}
        }

        // Fall back to full evaluation for complex cases
        self.evaluate_with_context(logic, data, &Value::Null, 0)
    }

    /// Evaluate with internal context (for scoped variables)
    ///
    /// # Arguments
    /// * `logic` - The compiled logic expression to evaluate
    /// * `user_data` - User's data (primary lookup source)
    /// * `internal_context` - Internal variables (e.g., $iteration, $loopIteration)
    ///
    /// # Zero-Copy Guarantee
    /// This method uses only references and never clones the data contexts.
    /// Internal variables are looked up first in `internal_context`, then fall back to `user_data`.
    #[inline]
    pub fn evaluate_with_internal_context(
        &self,
        logic: &CompiledLogic,
        user_data: &Value,
        internal_context: &Value,
    ) -> Result<Value, String> {
        self.evaluate_with_context(logic, user_data, internal_context, 0)
    }

    /// Internal recursive evaluation with depth tracking
    ///
    /// # Context Resolution Order
    /// 1. Check internal_context first (for scoped variables like $loopIteration)
    /// 2. Fall back to user_data (for regular user variables)
    ///
    /// This enables zero-copy scoped variable handling without merging contexts.
    fn evaluate_with_context(
        &self,
        logic: &CompiledLogic,
        user_data: &Value,
        internal_context: &Value,
        depth: usize,
    ) -> Result<Value, String> {
        // Recursion limit check
        if depth > self.config.recursion_limit {
            return Err("Recursion limit exceeded".to_string());
        }

        match logic {
            // ========== Literals ==========
            CompiledLogic::Null => Ok(Value::Null),
            CompiledLogic::Bool(b) => Ok(Value::Bool(*b)),
            CompiledLogic::Number(n) => Ok(self.f64_to_json(*n)),
            CompiledLogic::String(s) => Ok(Value::String(s.clone())),
            CompiledLogic::Array(arr) => {
                let results: Result<Vec<_>, _> = arr
                    .iter()
                    .map(|item| {
                        self.evaluate_with_context(item, user_data, internal_context, depth + 1)
                    })
                    .collect();
                Ok(Value::Array(results?))
            }

            // ========== Variable Access (Zero-Copy) ==========
            CompiledLogic::Var(name, default) => {
                self.eval_var_or_default(name, default, user_data, internal_context, depth)
            }

            CompiledLogic::Ref(path, default) => {
                self.eval_var_or_default(path, default, user_data, internal_context, depth)
            }

            // ========== Logical Operators ==========
            CompiledLogic::And(items) => {
                self.eval_and_or(items, true, user_data, internal_context, depth)
            }
            CompiledLogic::Or(items) => {
                self.eval_and_or(items, false, user_data, internal_context, depth)
            }
            CompiledLogic::Not(expr) => {
                let result =
                    self.evaluate_with_context(expr, user_data, internal_context, depth + 1)?;
                Ok(Value::Bool(!is_truthy(&result)))
            }
            CompiledLogic::If(cond, then_expr, else_expr) => {
                if self.eval_truthy(cond, user_data, internal_context, depth + 1)? {
                    self.evaluate_with_context(then_expr, user_data, internal_context, depth + 1)
                } else {
                    self.evaluate_with_context(else_expr, user_data, internal_context, depth + 1)
                }
            }

            // ========== Comparison Operators ==========
            CompiledLogic::Equal(a, b) => {
                self.eval_binary_compare(CompOp::Eq, a, b, user_data, internal_context, depth)
            }
            CompiledLogic::StrictEqual(a, b) => {
                self.eval_binary_compare(CompOp::StrictEq, a, b, user_data, internal_context, depth)
            }
            CompiledLogic::NotEqual(a, b) => {
                self.eval_binary_compare(CompOp::Ne, a, b, user_data, internal_context, depth)
            }
            CompiledLogic::StrictNotEqual(a, b) => {
                self.eval_binary_compare(CompOp::StrictNe, a, b, user_data, internal_context, depth)
            }
            CompiledLogic::LessThan(a, b) => {
                self.eval_binary_compare(CompOp::Lt, a, b, user_data, internal_context, depth)
            }
            CompiledLogic::LessThanOrEqual(a, b) => {
                self.eval_binary_compare(CompOp::Le, a, b, user_data, internal_context, depth)
            }
            CompiledLogic::GreaterThan(a, b) => {
                self.eval_binary_compare(CompOp::Gt, a, b, user_data, internal_context, depth)
            }
            CompiledLogic::GreaterThanOrEqual(a, b) => {
                self.eval_binary_compare(CompOp::Ge, a, b, user_data, internal_context, depth)
            }

            // ========== Arithmetic Operators ==========
            CompiledLogic::Add(_)
            | CompiledLogic::Subtract(_)
            | CompiledLogic::Multiply(_)
            | CompiledLogic::Divide(_)
            | CompiledLogic::Power(_, _)
            | CompiledLogic::Modulo(_, _) => {
                match self.eval_f64(logic, user_data, internal_context, depth)? {
                    Some(result) => Ok(self.f64_to_json(result)),
                    None => Ok(Value::Null),
                }
            }

            // ========== Array Operations ==========
            CompiledLogic::Map(array_expr, logic_expr) => {
                self.eval_map(array_expr, logic_expr, user_data, internal_context, depth)
            }
            CompiledLogic::Filter(array_expr, logic_expr) => {
                self.eval_filter(array_expr, logic_expr, user_data, internal_context, depth)
            }
            CompiledLogic::Reduce(array_expr, logic_expr, initial_expr) => self.eval_reduce(
                array_expr,
                logic_expr,
                initial_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::All(array_expr, logic_expr) => self.eval_quantifier(
                Quantifier::All,
                array_expr,
                logic_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::Some(array_expr, logic_expr) => self.eval_quantifier(
                Quantifier::Some,
                array_expr,
                logic_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::None(array_expr, logic_expr) => self.eval_quantifier(
                Quantifier::None,
                array_expr,
                logic_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::Merge(items) => {
                self.eval_merge(items, user_data, internal_context, depth)
            }
            CompiledLogic::In(value_expr, array_expr) => {
                self.eval_in(value_expr, array_expr, user_data, internal_context, depth)
            }
            CompiledLogic::Sum(array_expr, field_expr, threshold_expr) => self.eval_sum(
                array_expr,
                field_expr,
                threshold_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::For(start_expr, end_expr, logic_expr) => self.eval_for(
                start_expr,
                end_expr,
                logic_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::Multiplies(items) => {
                self.eval_multiplies(items, user_data, internal_context, depth)
            }
            CompiledLogic::Divides(items) => {
                self.eval_divides(items, user_data, internal_context, depth)
            }

            // ========== Array Lookup Operations ==========
            CompiledLogic::ValueAt(table_expr, row_idx_expr, col_name_expr) => self.eval_valueat(
                table_expr,
                row_idx_expr,
                col_name_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::MaxAt(table_expr, col_name_expr) => self.eval_maxat(
                table_expr,
                col_name_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::IndexAt(lookup_expr, table_expr, field_expr, range_expr) => self
                .eval_indexat(
                    lookup_expr,
                    table_expr,
                    field_expr,
                    range_expr,
                    user_data,
                    internal_context,
                    depth,
                ),
            CompiledLogic::Match(table_expr, conditions) => {
                self.eval_match(table_expr, conditions, user_data, internal_context, depth)
            }
            CompiledLogic::MatchRange(table_expr, conditions) => {
                self.eval_matchrange(table_expr, conditions, user_data, internal_context, depth)
            }
            CompiledLogic::Choose(table_expr, conditions) => {
                self.eval_choose(table_expr, conditions, user_data, internal_context, depth)
            }
            CompiledLogic::FindIndex(table_expr, conditions) => {
                self.eval_findindex(table_expr, conditions, user_data, internal_context, depth)
            }

            // ========== String Operations ==========
            CompiledLogic::Cat(items) => {
                self.concat_strings(items, user_data, internal_context, depth)
            }
            CompiledLogic::Substr(string_expr, start_expr, length_expr) => self.eval_substr(
                string_expr,
                start_expr,
                length_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::Search(find_expr, within_expr, start_expr) => self.eval_search(
                find_expr,
                within_expr,
                start_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::Left(text_expr, num_expr) => self.extract_text_side(
                text_expr,
                num_expr.as_deref(),
                true,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::Right(text_expr, num_expr) => self.extract_text_side(
                text_expr,
                num_expr.as_deref(),
                false,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::Mid(text_expr, start_expr, num_expr) => self.eval_mid(
                text_expr,
                start_expr,
                num_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::SplitText(value_expr, sep_expr, index_expr) => self.eval_split_text(
                value_expr,
                sep_expr,
                index_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::Concat(items) => {
                self.concat_strings(items, user_data, internal_context, depth)
            }
            CompiledLogic::SplitValue(string_expr, sep_expr) => {
                self.eval_split_value(string_expr, sep_expr, user_data, internal_context, depth)
            }
            CompiledLogic::StringFormat(value_expr, decimals, prefix, suffix, thousands_sep) => {
                self.eval_string_format(
                    value_expr,
                    decimals,
                    prefix,
                    suffix,
                    thousands_sep,
                    user_data,
                    internal_context,
                    depth,
                )
            }
            CompiledLogic::Length(expr) => {
                self.eval_length(expr, user_data, internal_context, depth)
            }
            CompiledLogic::Len(expr) => self.eval_len(expr, user_data, internal_context, depth),

            // ========== Math Operations ==========
            CompiledLogic::Abs(expr) => {
                self.eval_unary_math(expr, |n| n.abs(), user_data, internal_context, depth)
            }
            CompiledLogic::Max(items) => {
                self.eval_min_max(items, true, user_data, internal_context, depth)
            }
            CompiledLogic::Min(items) => {
                self.eval_min_max(items, false, user_data, internal_context, depth)
            }
            CompiledLogic::Pow(base_expr, exp_expr) => {
                self.eval_pow(base_expr, exp_expr, user_data, internal_context, depth)
            }
            CompiledLogic::Round(expr, decimals) => {
                self.apply_round(expr, decimals, 0, user_data, internal_context, depth)
            }
            CompiledLogic::RoundUp(expr, decimals) => {
                self.apply_round(expr, decimals, 1, user_data, internal_context, depth)
            }
            CompiledLogic::RoundDown(expr, decimals) => {
                self.apply_round(expr, decimals, 2, user_data, internal_context, depth)
            }
            CompiledLogic::Ceiling(expr, significance) => {
                self.eval_ceiling(expr, significance, user_data, internal_context, depth)
            }
            CompiledLogic::Floor(expr, significance) => {
                self.eval_floor(expr, significance, user_data, internal_context, depth)
            }
            CompiledLogic::Trunc(expr, decimals) => {
                self.eval_trunc(expr, decimals, user_data, internal_context, depth)
            }
            CompiledLogic::Mround(value_expr, multiple_expr) => self.eval_mround(
                value_expr,
                multiple_expr,
                user_data,
                internal_context,
                depth,
            ),

            // ========== Date Operations ==========
            CompiledLogic::Today => self.eval_today(),
            CompiledLogic::Now => self.eval_now(),
            CompiledLogic::Days(end_expr, start_expr) => {
                self.eval_days(end_expr, start_expr, user_data, internal_context, depth)
            }
            CompiledLogic::Year(expr) => {
                self.extract_date_component(expr, "year", user_data, internal_context, depth)
            }
            CompiledLogic::Month(expr) => {
                self.extract_date_component(expr, "month", user_data, internal_context, depth)
            }
            CompiledLogic::Day(expr) => {
                self.extract_date_component(expr, "day", user_data, internal_context, depth)
            }
            CompiledLogic::Date(year_expr, month_expr, day_expr) => self.eval_date(
                year_expr,
                month_expr,
                day_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::DateFormat(date_expr, format_expr) => {
                self.eval_date_format(date_expr, format_expr, user_data, internal_context, depth)
            }
            CompiledLogic::YearFrac(start_expr, end_expr, basis_expr) => self.eval_year_frac(
                start_expr,
                end_expr,
                basis_expr,
                user_data,
                internal_context,
                depth,
            ),
            CompiledLogic::DateDif(start_expr, end_expr, unit_expr) => self.eval_date_dif(
                start_expr,
                end_expr,
                unit_expr,
                user_data,
                internal_context,
                depth,
            ),

            // ========== Utility Operators ==========
            CompiledLogic::Missing(keys) => {
                let missing: Vec<_> = keys
                    .iter()
                    .filter(|key| self.is_key_missing(user_data, key))
                    .map(|k| Value::String(k.clone()))
                    .collect();
                Ok(Value::Array(missing))
            }
            CompiledLogic::MissingSome(min_expr, keys) => {
                let min_val =
                    self.evaluate_with_context(min_expr, user_data, internal_context, depth + 1)?;
                let minimum = to_number(&min_val) as usize;

                let present = keys
                    .iter()
                    .filter(|key| !self.is_key_missing(user_data, key))
                    .count();

                if present >= minimum {
                    Ok(Value::Array(vec![]))
                } else {
                    let missing: Vec<_> = keys
                        .iter()
                        .filter(|key| self.is_key_missing(user_data, key))
                        .map(|k| Value::String(k.clone()))
                        .collect();
                    Ok(Value::Array(missing))
                }
            }

            // ========== Logical Utility Operators ==========
            CompiledLogic::Xor(a_expr, b_expr) => {
                let a_val =
                    self.evaluate_with_context(a_expr, user_data, internal_context, depth + 1)?;
                let b_val =
                    self.evaluate_with_context(b_expr, user_data, internal_context, depth + 1)?;
                Ok(Value::Bool(is_truthy(&a_val) ^ is_truthy(&b_val)))
            }
            CompiledLogic::IfNull(cond_expr, alt_expr) => {
                let cond_val =
                    self.evaluate_with_context(cond_expr, user_data, internal_context, depth + 1)?;
                if is_null_like(&cond_val) {
                    self.evaluate_with_context(alt_expr, user_data, internal_context, depth + 1)
                } else {
                    Ok(cond_val)
                }
            }
            CompiledLogic::IsEmpty(expr) => {
                let val =
                    self.evaluate_with_context(expr, user_data, internal_context, depth + 1)?;
                let empty = match &val {
                    Value::Null => true,
                    Value::String(s) => s.is_empty(),
                    _ => false,
                };
                Ok(Value::Bool(empty))
            }
            CompiledLogic::Empty => Ok(Value::String(String::new())),

            // ========== UI Helper Operators ==========
            CompiledLogic::RangeOptions(min_expr, max_expr) => {
                let min_val =
                    self.evaluate_with_context(min_expr, user_data, internal_context, depth + 1)?;
                let max_val =
                    self.evaluate_with_context(max_expr, user_data, internal_context, depth + 1)?;

                let min = to_number(&min_val) as i32;
                let max = to_number(&max_val) as i32;

                if min > max {
                    return Ok(Value::Array(vec![]));
                }

                let options: Vec<Value> = (min..=max)
                    .map(|i| {
                        serde_json::json!({
                            "label": i.to_string(),
                            "value": i.to_string()
                        })
                    })
                    .collect();

                Ok(Value::Array(options))
            }
            CompiledLogic::MapOptions(table_expr, label_expr, value_expr) => {
                let table_val =
                    self.evaluate_with_context(table_expr, user_data, internal_context, depth + 1)?;
                let label_val =
                    self.evaluate_with_context(label_expr, user_data, internal_context, depth + 1)?;
                let value_val =
                    self.evaluate_with_context(value_expr, user_data, internal_context, depth + 1)?;

                if let (Value::Array(arr), Value::String(label_field), Value::String(value_field)) =
                    (&table_val, &label_val, &value_val)
                {
                    let options: Vec<Value> = arr
                        .iter()
                        .filter_map(|row| {
                            row.as_object().and_then(|obj| {
                                Some(create_option(obj.get(label_field)?, obj.get(value_field)?))
                            })
                        })
                        .collect();
                    Ok(Value::Array(options))
                } else {
                    Ok(Value::Array(vec![]))
                }
            }
            CompiledLogic::MapOptionsIf(table_expr, label_expr, value_expr, conditions) => {
                let table_val =
                    self.evaluate_with_context(table_expr, user_data, internal_context, depth + 1)?;
                let label_val =
                    self.evaluate_with_context(label_expr, user_data, internal_context, depth + 1)?;
                let value_val =
                    self.evaluate_with_context(value_expr, user_data, internal_context, depth + 1)?;

                if let (Value::Array(arr), Value::String(label_field), Value::String(value_field)) =
                    (&table_val, &label_val, &value_val)
                {
                    let mut options = Vec::new();

                    for row in arr {
                        let obj = match row.as_object() {
                            Some(obj) => obj,
                            None => continue,
                        };

                        let mut all_match = true;

                        for condition in conditions {
                            // Evaluate condition with row as primary context, user_data as fallback
                            let result =
                                self.evaluate_with_context(condition, row, user_data, depth + 1)?;
                            if !is_truthy(&result) {
                                all_match = false;
                                break;
                            }
                        }

                        if all_match {
                            if let (Some(label), Some(value)) =
                                (obj.get(label_field), obj.get(value_field))
                            {
                                options.push(create_option(label, value));
                            }
                        }
                    }

                    Ok(Value::Array(options))
                } else {
                    Ok(Value::Array(vec![]))
                }
            }
            CompiledLogic::Return(value) => {
                // Return the raw value as-is without any evaluation
                Ok(value.as_ref().clone())
            }
        }
    }

    /// Helper for evaluating variable/ref with default (zero-copy)
    #[inline]
    fn eval_var_or_default(
        &self,
        name: &str,
        default: &Option<Box<CompiledLogic>>,
        user_data: &Value,
        internal_context: &Value,
        depth: usize,
    ) -> Result<Value, String> {
        // Fast path: check active table scope first.
        // When evaluating a table's own columns (forward/backward pass), Var/Ref nodes
        // that resolve to the table's own path (e.g. used in MAP/FILTER/REDUCE over self)
        // must see local_rows, not stale data in scope_data.
        if !name.is_empty() {
            let scope = unsafe { self.table_scope_ref() };
            if let Some(ts) = scope.as_ref() {
                if name == ts.path || name.trim_start_matches('#') == ts.path_no_hash.as_str() {
                    if ts.col_count > 0 && !ts.flat_cells.is_null() {
                        let mut arr = Vec::with_capacity(ts.existing_row_count + ts.total_rows);
                        let rows = unsafe { &*ts.rows };
                        for r in 0..ts.existing_row_count {
                            if let Some(row) = rows.get(r) {
                                arr.push(row.clone());
                            }
                        }
                        for r in 0..ts.total_rows {
                            let mut row_map = serde_json::Map::with_capacity(ts.col_count);
                            let row_offset = r * ts.col_count;
                            for (c_name, &c_idx) in ts.col_map.iter() {
                                let cell = unsafe { &*ts.flat_cells.add(row_offset + c_idx) };
                                row_map.insert(c_name.clone(), cell.clone());
                            }
                            arr.push(Value::Object(row_map));
                        }
                        return Ok(Value::Array(arr));
                    }
                    // SAFETY: local_rows outlives this evaluation frame
                    let rows = unsafe { &*ts.rows };
                    return Ok(Value::Array(rows.clone()));
                }
            }
        }

        // Special case: empty name "" refers to root context (user_data only)
        // For named variables, try internal context first (for $loopIteration, $iteration, etc.)
        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))
        };
        match value {
            Some(v) if !v.is_null() => Ok(v.clone()), // Only clone the resolved value
            _ => {
                if let Some(def) = default {
                    self.evaluate_with_context(def, user_data, internal_context, depth + 1)
                } else {
                    Ok(Value::Null)
                }
            }
        }
    }

    /// Convert f64 to JSON number
    #[inline(always)]
    pub fn f64_to_value(&self, f: f64) -> Value {
        helpers::f64_to_json(f, self.config.safe_nan_handling)
    }

    #[inline(always)]
    fn f64_to_json(&self, f: f64) -> Value {
        self.f64_to_value(f)
    }

    #[inline(always)]
    pub fn eval_fast_f64(
        &self,
        logic: &CompiledLogic,
        user_data: &Value,
        internal_context: &Value,
    ) -> Result<Option<f64>, String> {
        self.eval_f64(logic, user_data, internal_context, 0)
    }
}

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