microsoft-webui-expressions 3.0.3

Core expression evaluation for WebUI framework
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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! WebUI expression evaluation module.
//!
//! This module handles the evaluation of condition expressions in WebUI templates.

use std::borrow::Cow;

use serde_json::Value;
use thiserror::Error;
use webui_protocol::{
    condition_expr, ComparisonOperator, CompoundCondition, ConditionExpr, LogicalOperator,
    Predicate,
};
use webui_state::find_value_by_dotted_path_ref;

/// Error types for expression evaluation.
#[derive(Debug, Error)]
pub enum ExpressionError {
    #[error("Evaluation error: {0}")]
    Evaluation(String),

    #[error("Missing value: {0}")]
    MissingValue(String),

    #[error("Type error: {0}")]
    TypeError(String),

    #[error("Mixed logical operators: Cannot mix AND and OR operators")]
    MixedOperators,

    #[error("Too many logical operators: Maximum of 5 allowed, found {0}")]
    TooManyOperators(usize),

    #[error("Value comparison error: {0}")]
    Comparison(String),
}

pub type Result<T> = std::result::Result<T, ExpressionError>;

/// Evaluate a condition expression with the given state.
///
/// Missing identifier paths are falsy operands. Missing values used by
/// comparison predicates remain evaluation errors.
pub fn evaluate(condition: &ConditionExpr, state: &Value) -> Result<bool> {
    evaluate_with_resolver(condition, |path| find_value_by_dotted_path_ref(path, state))
}

/// Evaluate a condition expression using a custom resolver for value lookups.
///
/// The `resolver` closure takes a dotted path (e.g., `"contact.name"`) and
/// returns the resolved value. This allows callers to provide merged views
/// (e.g., local variables overlaid on global state) without cloning the
/// entire state tree.
pub fn evaluate_with_resolver<'a, F>(condition: &ConditionExpr, resolver: F) -> Result<bool>
where
    F: Fn(&str) -> Option<Cow<'a, Value>>,
{
    // Single-term conditions carry no logical operators, so the traversal in
    // `count_logical_operators` is pure overhead for the most common template
    // conditions.
    if matches!(
        condition.expr,
        Some(condition_expr::Expr::Identifier(_)) | Some(condition_expr::Expr::Predicate(_))
    ) {
        return evaluate_expr(condition, &resolver);
    }

    let (logical_op_count, has_mixed_ops) = count_logical_operators(condition);

    if logical_op_count > 5 {
        return Err(ExpressionError::TooManyOperators(logical_op_count));
    }

    if has_mixed_ops {
        return Err(ExpressionError::MixedOperators);
    }

    evaluate_expr(condition, &resolver)
}

/// Inline capacity of [`PendingExprs`].
///
/// The depth-first walk keeps at most one pending node per open compound plus
/// the node being visited, so any condition within the five-operator limit
/// fits inline and only trees that will be rejected anyway reach the heap.
const INLINE_PENDING_EXPRS: usize = 8;

/// LIFO stack of sub-expressions still to visit, kept on the call stack.
///
/// Compound conditions are evaluated on every render of every `<if>` and
/// boolean attribute, so the operator check must not allocate per call.
struct PendingExprs<'a> {
    inline: [Option<&'a ConditionExpr>; INLINE_PENDING_EXPRS],
    inline_len: usize,
    overflow: Vec<&'a ConditionExpr>,
}

impl<'a> PendingExprs<'a> {
    fn new(root: &'a ConditionExpr) -> Self {
        let mut inline = [None; INLINE_PENDING_EXPRS];
        inline[0] = Some(root);
        Self {
            inline,
            inline_len: 1,
            overflow: Vec::new(),
        }
    }

    fn push(&mut self, expr: &'a ConditionExpr) {
        if self.inline_len < INLINE_PENDING_EXPRS {
            self.inline[self.inline_len] = Some(expr);
            self.inline_len += 1;
        } else {
            self.overflow.push(expr);
        }
    }

    fn pop(&mut self) -> Option<&'a ConditionExpr> {
        if let Some(expr) = self.overflow.pop() {
            return Some(expr);
        }
        if self.inline_len == 0 {
            return None;
        }
        self.inline_len -= 1;
        self.inline[self.inline_len].take()
    }
}

// Helper function to count logical operators and check if they're mixed
fn count_logical_operators(condition: &ConditionExpr) -> (usize, bool) {
    let mut count = 0;
    let mut last_op: Option<i32> = None;
    let mut has_mixed = false;

    // We need to use a stack to avoid recursion
    let mut stack = PendingExprs::new(condition);

    while let Some(expr) = stack.pop() {
        match &expr.expr {
            Some(condition_expr::Expr::Compound(compound)) => {
                count += 1;

                // Check if we're mixing operators
                if let Some(last) = last_op {
                    if last != compound.op {
                        has_mixed = true;
                    }
                } else {
                    last_op = Some(compound.op);
                }

                // Push sub-expressions to stack
                if let Some(right) = compound.right.as_ref() {
                    stack.push(right);
                }
                if let Some(left) = compound.left.as_ref() {
                    stack.push(left);
                }
            }
            Some(condition_expr::Expr::Not(not_cond)) => {
                if let Some(inner) = not_cond.condition.as_ref() {
                    stack.push(inner);
                }
            }
            _ => {} // Predicates and identifiers don't have logical operators
        }
    }

    (count, has_mixed)
}

// Iterative evaluation of expressions using a resolver closure
fn evaluate_expr<'a, F>(condition: &ConditionExpr, resolver: &F) -> Result<bool>
where
    F: Fn(&str) -> Option<Cow<'a, Value>>,
{
    match &condition.expr {
        Some(condition_expr::Expr::Predicate(pred)) => evaluate_predicate(pred, resolver),
        Some(condition_expr::Expr::Not(not_cond)) => {
            let inner = not_cond.condition.as_ref().ok_or_else(|| {
                ExpressionError::Evaluation("Not condition missing inner expression".to_string())
            })?;
            let result = evaluate_expr(inner, resolver)?;
            Ok(!result)
        }
        Some(condition_expr::Expr::Compound(compound)) => evaluate_compound(compound, resolver),
        Some(condition_expr::Expr::Identifier(id)) if id.value == "true" => Ok(true),
        Some(condition_expr::Expr::Identifier(id)) if id.value == "false" => Ok(false),
        Some(condition_expr::Expr::Identifier(id)) => {
            if let Some(val) = resolver(&id.value) {
                match val.as_ref() {
                    Value::Bool(b) => Ok(*b),
                    Value::Null => Ok(false),
                    Value::Number(n) => Ok(!(n.as_f64() == Some(0.0))),
                    Value::String(s) => Ok(!s.is_empty()),
                    Value::Array(a) => Ok(!a.is_empty()),
                    Value::Object(o) => Ok(!o.is_empty()),
                }
            } else {
                Ok(false)
            }
        }
        None => Err(ExpressionError::Evaluation(
            "Empty condition expression".to_string(),
        )),
    }
}

fn evaluate_compound<'a, F>(compound: &CompoundCondition, resolver: &F) -> Result<bool>
where
    F: Fn(&str) -> Option<Cow<'a, Value>>,
{
    let left = compound.left.as_ref().ok_or_else(|| {
        ExpressionError::Evaluation("Compound missing left expression".to_string())
    })?;
    let right = compound.right.as_ref().ok_or_else(|| {
        ExpressionError::Evaluation("Compound missing right expression".to_string())
    })?;

    let left_result = evaluate_expr(left, resolver)?;
    let op = LogicalOperator::try_from(compound.op).map_err(|_| {
        ExpressionError::Evaluation(format!("Invalid logical operator: {}", compound.op))
    })?;

    match op {
        LogicalOperator::And => {
            if !left_result {
                return Ok(false);
            }
            evaluate_expr(right, resolver)
        }
        LogicalOperator::Or => {
            if left_result {
                return Ok(true);
            }
            evaluate_expr(right, resolver)
        }
        LogicalOperator::Unspecified => Err(ExpressionError::Evaluation(
            "Unspecified logical operator".to_string(),
        )),
    }
}

fn evaluate_predicate<'a, F>(predicate: &Predicate, resolver: &F) -> Result<bool>
where
    F: Fn(&str) -> Option<Cow<'a, Value>>,
{
    let left_val = match resolver(&predicate.left) {
        Some(val) => val,
        None => return Err(ExpressionError::MissingValue(predicate.left.clone())),
    };

    let right_val = if is_literal(&predicate.right) {
        Cow::Owned(parse_literal(&predicate.right)?)
    } else {
        match resolver(&predicate.right) {
            Some(val) => val,
            None => return Err(ExpressionError::MissingValue(predicate.right.clone())),
        }
    };

    let op = ComparisonOperator::try_from(predicate.operator).map_err(|_| {
        ExpressionError::Evaluation(format!(
            "Invalid comparison operator: {}",
            predicate.operator
        ))
    })?;

    compare_values(left_val.as_ref(), &op, right_val.as_ref())
}

// Check if a string is a literal value
fn is_literal(s: &str) -> bool {
    // A string is a literal if:
    // - It starts with a quote (single or double)
    // - It's a number (starts with a digit or negative sign followed by a digit)
    // - It's a boolean ("true" or "false")
    s.starts_with('"')
        || s.starts_with('\'')
        || s.starts_with(|c: char| {
            c.is_ascii_digit()
                || (c == '-' && s.len() > 1 && s.chars().nth(1).is_some_and(|c| c.is_ascii_digit()))
        })
        || s == "true"
        || s == "false"
}

// Parse a literal string into a JSON value
fn parse_literal(s: &str) -> Result<Value> {
    // Handle quoted strings
    if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
        let content = &s[1..s.len() - 1];
        return Ok(Value::String(content.to_string()));
    }

    // Handle booleans
    if s == "true" {
        return Ok(Value::Bool(true));
    }
    if s == "false" {
        return Ok(Value::Bool(false));
    }

    // Handle numbers
    if let Ok(num) = s.parse::<i64>() {
        return Ok(Value::Number(num.into()));
    }

    if let Ok(num) = s.parse::<f64>() {
        // Create a JSON number from f64, handling error if it's not representable
        match serde_json::Number::from_f64(num) {
            Some(n) => return Ok(Value::Number(n)),
            None => {
                return Err(ExpressionError::TypeError(format!(
                    "Cannot convert {} to JSON number",
                    s
                )))
            }
        }
    }

    // If we get here, it's not a recognized literal
    Err(ExpressionError::TypeError(format!(
        "Invalid literal: {}",
        s
    )))
}

// Compare two JSON values based on the comparison operator
fn compare_values(left: &Value, op: &ComparisonOperator, right: &Value) -> Result<bool> {
    match op {
        ComparisonOperator::Equal => Ok(left == right),
        ComparisonOperator::NotEqual => Ok(left != right),

        // Handle numeric comparisons
        ComparisonOperator::GreaterThan => compare_ordered(left, right, |a, b| a > b),
        ComparisonOperator::LessThan => compare_ordered(left, right, |a, b| a < b),
        ComparisonOperator::GreaterThanOrEqual => compare_ordered(left, right, |a, b| a >= b),
        ComparisonOperator::LessThanOrEqual => compare_ordered(left, right, |a, b| a <= b),
        ComparisonOperator::Unspecified => Err(ExpressionError::Evaluation(
            "Unspecified comparison operator".to_string(),
        )),
    }
}

// Helper for ordered comparisons
fn compare_ordered<F>(left: &Value, right: &Value, compare_fn: F) -> Result<bool>
where
    F: Fn(&f64, &f64) -> bool,
{
    // Extract numeric values
    let left_num = extract_number(left)?;
    let right_num = extract_number(right)?;

    Ok(compare_fn(&left_num, &right_num))
}

// Extract a numeric value from a JSON value
fn extract_number(val: &Value) -> Result<f64> {
    match val {
        Value::Number(n) => {
            if let Some(f) = n.as_f64() {
                Ok(f)
            } else {
                Err(ExpressionError::TypeError(format!(
                    "Cannot convert number to f64: {:?}",
                    n
                )))
            }
        }
        Value::String(s) => match s.parse::<f64>() {
            Ok(num) => Ok(num),
            Err(_) => Err(ExpressionError::TypeError(format!(
                "Cannot convert string to number: {}",
                s
            ))),
        },
        Value::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }),
        _ => Err(ExpressionError::TypeError(format!(
            "Cannot convert to number: {:?}",
            val
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::borrow::Cow;
    use webui_protocol::{ComparisonOperator, ConditionExpr, LogicalOperator};
    use webui_test_utils::test_json;

    #[test]
    fn boolean_literals_do_not_resolve_state_keys() {
        let state = test_json!({"true": false, "false": true});
        assert_eq!(
            evaluate(&ConditionExpr::identifier("true"), &state).unwrap(),
            true
        );
        assert_eq!(
            evaluate(&ConditionExpr::identifier("false"), &state).unwrap(),
            false
        );
    }

    #[test]
    fn test_simple_identifier() {
        // Test true identifier
        let condition = ConditionExpr::identifier("flag");

        let state = test_json!({
            "flag": true
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );

        // Test false identifier
        let condition = ConditionExpr::identifier("flag");

        let state = test_json!({
            "flag": false
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(false)),
            "Expected Ok(false), got {:?}",
            result
        );

        // Test non-boolean identifier treated as boolean
        let condition = ConditionExpr::identifier("name");

        let state = test_json!({
            "name": "John"
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        ); // Non-empty string is truthy
    }

    #[test]
    fn test_predicate() {
        let condition = ConditionExpr::predicate("age", ComparisonOperator::GreaterThan, "18");

        // Test with age > 18
        let state = test_json!({
            "age": 21
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );

        // Test with age < 18
        let state = test_json!({
            "age": 16
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(false)),
            "Expected Ok(false), got {:?}",
            result
        );
    }

    #[test]
    fn test_not_expression() {
        let condition = ConditionExpr::negated(ConditionExpr::identifier("flag"));

        // Test with flag = true
        let state = test_json!({
            "flag": true
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(false)),
            "Expected Ok(false), got {:?}",
            result
        );

        // Test with flag = false
        let state = test_json!({
            "flag": false
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_compound_expression() {
        // Test AND
        let condition = ConditionExpr::compound(
            ConditionExpr::identifier("isAdmin"),
            LogicalOperator::And,
            ConditionExpr::identifier("isActive"),
        );

        let state = test_json!({
            "isAdmin": true,
            "isActive": true
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );

        // Test OR
        let condition = ConditionExpr::compound(
            ConditionExpr::identifier("isAdmin"),
            LogicalOperator::Or,
            ConditionExpr::identifier("isEditor"),
        );

        let state = test_json!({
            "isAdmin": false,
            "isEditor": true
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_mixed_operators_error() {
        // Create a condition with mixed operators (AND and OR)
        let condition = ConditionExpr::compound(
            ConditionExpr::compound(
                ConditionExpr::identifier("a"),
                LogicalOperator::And,
                ConditionExpr::identifier("b"),
            ),
            LogicalOperator::Or,
            ConditionExpr::identifier("c"),
        );

        let state = test_json!({
            "a": true, "b": true, "c": true
        });

        let result = evaluate(&condition, &state);
        assert!(matches!(result, Err(ExpressionError::MixedOperators)));
    }

    #[test]
    fn test_too_many_operators_error() {
        // Create a condition with more than 5 operators
        let mut condition = ConditionExpr::identifier("a");

        // Add 6 logical operators (exceeding the limit of 5)
        for i in 0..6 {
            condition = ConditionExpr::compound(
                condition,
                LogicalOperator::And,
                ConditionExpr::identifier(format!("var{}", i)),
            );
        }

        let state = test_json!({
            "a": true, "var0": true, "var1": true,
            "var2": true, "var3": true, "var4": true, "var5": true
        });

        let result = evaluate(&condition, &state);
        assert!(matches!(result, Err(ExpressionError::TooManyOperators(_))));
    }

    #[test]
    fn test_comparison_operators() {
        let state = test_json!({
            "value": 10
        });

        // Test each comparison operator
        let ops = [
            (ComparisonOperator::GreaterThan, "5", true),
            (ComparisonOperator::GreaterThan, "15", false),
            (ComparisonOperator::LessThan, "15", true),
            (ComparisonOperator::LessThan, "5", false),
            (ComparisonOperator::Equal, "10", true),
            (ComparisonOperator::Equal, "11", false),
            (ComparisonOperator::NotEqual, "11", true),
            (ComparisonOperator::NotEqual, "10", false),
            (ComparisonOperator::GreaterThanOrEqual, "10", true),
            (ComparisonOperator::GreaterThanOrEqual, "11", false),
            (ComparisonOperator::LessThanOrEqual, "10", true),
            (ComparisonOperator::LessThanOrEqual, "9", false),
        ];

        for (op, right, expected) in ops.iter() {
            let condition = ConditionExpr::predicate("value", *op, *right);

            let result = evaluate(&condition, &state);
            assert!(
                matches!(result, Ok(val) if val == *expected),
                "Failed for operator {:?} with right value {}: expected Ok({}), got {:?}",
                op,
                right,
                expected,
                result
            );
        }
    }

    #[test]
    fn test_string_comparison() {
        let state = test_json!({
            "name": "John"
        });

        // Test string equality
        let condition = ConditionExpr::predicate("name", ComparisonOperator::Equal, "\"John\"");

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );

        // Test string inequality
        let condition = ConditionExpr::predicate("name", ComparisonOperator::NotEqual, "\"Jane\"");

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_dotted_path() {
        let state = test_json!({
            "user": {
                "profile": {
                    "age": 25,
                    "name": "John"
                }
            }
        });

        // Test nested property access
        let condition =
            ConditionExpr::predicate("user.profile.age", ComparisonOperator::GreaterThan, "18");

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_borrowed_resolver_value() {
        let condition = ConditionExpr::identifier("flag");
        let value = Value::Bool(true);

        let result = evaluate_with_resolver(&condition, |path| {
            if path == "flag" {
                Some(Cow::Borrowed(&value))
            } else {
                None
            }
        });

        assert!(matches!(result, Ok(true)));
    }

    #[test]
    fn test_missing_value() {
        let state = test_json!({
            "user": {
                "name": "John"
            }
        });

        // Test with a missing value
        let condition = ConditionExpr::predicate("user.age", ComparisonOperator::GreaterThan, "18");

        let result = evaluate(&condition, &state);
        assert!(matches!(result, Err(ExpressionError::MissingValue(_))));
    }

    // === Identifier Edge Cases ===

    #[test]
    fn test_missing_identifier_is_falsy_before_negation() {
        let condition = ConditionExpr::identifier("notExist");
        let negated = ConditionExpr::negated(condition.clone());
        let state = test_json!({ "flag": true });

        assert!(
            matches!(evaluate(&condition, &state), Ok(false)),
            "a missing identifier must be a falsy operand"
        );
        assert!(
            matches!(evaluate(&negated, &state), Ok(true)),
            "negating a missing identifier must evaluate to true"
        );
    }

    #[test]
    fn test_zero_field() {
        let condition = ConditionExpr::identifier("zero");
        let state = test_json!({ "zero": 0 });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(false)),
            "Expected Ok(false), got {:?}",
            result
        );
    }

    #[test]
    fn test_empty_string_field() {
        let condition = ConditionExpr::identifier("empty");
        let state = test_json!({ "empty": "" });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(false)),
            "Expected Ok(false), got {:?}",
            result
        );
    }

    #[test]
    fn test_nonempty_array() {
        let condition = ConditionExpr::identifier("myList");
        let state = test_json!({ "myList": [1, 2, 3] });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_empty_array() {
        let condition = ConditionExpr::identifier("emptyList");
        let state = test_json!({ "emptyList": [] });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(false)),
            "Expected Ok(false), got {:?}",
            result
        );
    }

    // === Deep Dotted Path ===

    #[test]
    fn test_dotted_path_deep() {
        let condition = ConditionExpr::identifier("outer.nested.deep.value");
        let state = test_json!({
            "outer": { "nested": { "deep": { "value": true } } }
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    // === Comparison Edge Cases ===

    #[test]
    fn test_string_eq() {
        let condition =
            ConditionExpr::predicate("appearance", ComparisonOperator::Equal, "\"hub\"");
        let state = test_json!({ "appearance": "hub" });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_string_ne() {
        let condition =
            ConditionExpr::predicate("appearance", ComparisonOperator::NotEqual, "\"full-page\"");
        let state = test_json!({ "appearance": "hub" });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_number_eq() {
        let condition = ConditionExpr::predicate("x", ComparisonOperator::Equal, "5");
        let state = test_json!({ "x": 5 });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_less_than() {
        let condition = ConditionExpr::predicate("x", ComparisonOperator::LessThan, "y");
        let state = test_json!({ "x": 5, "y": 10 });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_greater_than() {
        let condition = ConditionExpr::predicate("y", ComparisonOperator::GreaterThan, "x");
        let state = test_json!({ "x": 5, "y": 10 });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_less_equal() {
        let condition = ConditionExpr::predicate("x", ComparisonOperator::LessThanOrEqual, "5");
        let state = test_json!({ "x": 5 });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_greater_equal() {
        let condition = ConditionExpr::predicate("y", ComparisonOperator::GreaterThanOrEqual, "10");
        let state = test_json!({ "y": 10 });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_nested_eq() {
        let condition = ConditionExpr::predicate("outer.inner", ComparisonOperator::Equal, "42");
        let state = test_json!({ "outer": { "inner": 42 } });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    // === Short-Circuit Evaluation ===

    #[test]
    fn test_and_true_true() {
        let condition = ConditionExpr::compound(
            ConditionExpr::identifier("isEnabled"),
            LogicalOperator::And,
            ConditionExpr::identifier("x"),
        );
        let state = test_json!({ "isEnabled": true, "x": 5 });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_and_true_false() {
        let condition = ConditionExpr::compound(
            ConditionExpr::identifier("isEnabled"),
            LogicalOperator::And,
            ConditionExpr::identifier("isDisabled"),
        );
        let state = test_json!({ "isEnabled": true, "isDisabled": false });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(false)),
            "Expected Ok(false), got {:?}",
            result
        );
    }

    #[test]
    fn test_or_false_false() {
        let condition = ConditionExpr::compound(
            ConditionExpr::identifier("isDisabled"),
            LogicalOperator::Or,
            ConditionExpr::identifier("zero"),
        );
        let state = test_json!({ "isDisabled": false, "zero": 0 });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(false)),
            "Expected Ok(false), got {:?}",
            result
        );
    }

    #[test]
    fn test_or_false_true() {
        let condition = ConditionExpr::compound(
            ConditionExpr::identifier("isDisabled"),
            LogicalOperator::Or,
            ConditionExpr::identifier("isEnabled"),
        );
        let state = test_json!({ "isDisabled": false, "isEnabled": true });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    // === Complex Expressions ===

    #[test]
    fn test_appearance_and_actions() {
        let condition = ConditionExpr::compound(
            ConditionExpr::predicate("appearance", ComparisonOperator::Equal, "\"hub\""),
            LogicalOperator::And,
            ConditionExpr::identifier("actions.trailing"),
        );
        let state = test_json!({
            "appearance": "hub",
            "actions": { "trailing": true }
        });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    #[test]
    fn test_negated_binary() {
        let condition = ConditionExpr::negated(ConditionExpr::predicate(
            "appearance",
            ComparisonOperator::Equal,
            "\"hub\"",
        ));
        let state = test_json!({ "appearance": "sidepanel" });

        let result = evaluate(&condition, &state);
        assert!(
            matches!(result, Ok(true)),
            "Expected Ok(true), got {:?}",
            result
        );
    }

    // === Single-term fast path ===

    #[test]
    fn test_single_term_matches_operator_guard_semantics() {
        let state = test_json!({
            "flag": true,
            "off": false,
            "count": 0,
            "name": "Alice",
            "user": { "age": 25 }
        });

        // Single identifiers and predicates carry no logical operators, so they
        // must evaluate normally and never surface an operator-limit error.
        let cases: [(ConditionExpr, bool); 6] = [
            (ConditionExpr::identifier("flag"), true),
            (ConditionExpr::identifier("off"), false),
            (ConditionExpr::identifier("count"), false),
            (ConditionExpr::identifier("name"), true),
            (
                ConditionExpr::predicate("user.age", ComparisonOperator::GreaterThan, "18"),
                true,
            ),
            (
                ConditionExpr::predicate("name", ComparisonOperator::Equal, "'Bob'"),
                false,
            ),
        ];

        for (condition, expected) in cases {
            assert_eq!(
                evaluate(&condition, &state).ok(),
                Some(expected),
                "single-term condition {:?} must evaluate to {}",
                condition,
                expected
            );
        }
    }

    #[test]
    fn test_single_term_predicate_still_reports_missing_value() {
        let state = test_json!({ "user": { "name": "John" } });
        let condition = ConditionExpr::predicate("user.age", ComparisonOperator::LessThan, "18");

        assert!(matches!(
            evaluate(&condition, &state),
            Err(ExpressionError::MissingValue(_))
        ));
    }

    #[test]
    fn test_negated_tree_still_enforces_operator_limit() {
        // A `Not` wrapper must not be mistaken for a single term: the operator
        // guard has to keep walking the tree underneath it.
        let mut inner = ConditionExpr::identifier("a");
        for i in 0..6 {
            inner = ConditionExpr::compound(
                inner,
                LogicalOperator::And,
                ConditionExpr::identifier(format!("var{}", i)),
            );
        }
        let condition = ConditionExpr::negated(inner);

        let state = test_json!({
            "a": true, "var0": true, "var1": true,
            "var2": true, "var3": true, "var4": true, "var5": true
        });

        assert!(matches!(
            evaluate(&condition, &state),
            Err(ExpressionError::TooManyOperators(6))
        ));
    }

    #[test]
    fn test_operator_count_is_exact_beyond_inline_stack() {
        // A left-deep tree keeps one pending node per open compound, so twelve
        // operators spill past the inline stack; the reported count must
        // still cover every node.
        let mut condition = ConditionExpr::identifier("a");
        for i in 0..12 {
            condition = ConditionExpr::compound(
                condition,
                LogicalOperator::Or,
                ConditionExpr::identifier(format!("var{}", i)),
            );
        }

        let state = test_json!({ "a": true });

        assert!(matches!(
            evaluate(&condition, &state),
            Err(ExpressionError::TooManyOperators(12))
        ));
    }

    #[test]
    fn test_negated_tree_still_rejects_mixed_operators() {
        let condition = ConditionExpr::negated(ConditionExpr::compound(
            ConditionExpr::compound(
                ConditionExpr::identifier("a"),
                LogicalOperator::And,
                ConditionExpr::identifier("b"),
            ),
            LogicalOperator::Or,
            ConditionExpr::identifier("c"),
        ));

        let state = test_json!({ "a": true, "b": true, "c": true });

        assert!(matches!(
            evaluate(&condition, &state),
            Err(ExpressionError::MixedOperators)
        ));
    }

    #[test]
    fn test_single_term_fast_path_uses_same_resolver_contract() {
        let value = Value::String("active".to_string());
        let lookups = std::cell::Cell::new(0usize);

        let condition = ConditionExpr::predicate("status", ComparisonOperator::Equal, "'active'");
        let result = evaluate_with_resolver(&condition, |path| {
            lookups.set(lookups.get() + 1);
            if path == "status" {
                Some(Cow::Borrowed(&value))
            } else {
                None
            }
        });

        assert!(matches!(result, Ok(true)));
        assert_eq!(
            lookups.get(),
            1,
            "a single-term predicate must resolve exactly one path"
        );
    }
}