exprimo 0.7.0

Exprimo is a JavaScript expression evaluator written in Rust.
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
use exprimo::Evaluator;
use std::collections::HashMap;

#[cfg(test)]
#[test]
fn test_basic_evaluate_with_context() {
    let mut context = HashMap::new();

    context.insert("a".to_string(), serde_json::Value::Bool(true));
    context.insert("b".to_string(), serde_json::Value::Bool(false));

    let evaluator = Evaluator::new(
        context,
        HashMap::new(), // custom_functions
    );

    let expr1 = "a && b";
    let expr2 = "a || b";
    let expr3 = "a && !b";
    let expr4 = "a || !b";
    let expr5 = "a && b || a && !b";
    let res1 = evaluator.evaluate(&expr1).unwrap();
    let res2 = evaluator.evaluate(&expr2).unwrap();
    let res3 = evaluator.evaluate(&expr3).unwrap();
    let res4 = evaluator.evaluate(&expr4).unwrap();
    let res5 = evaluator.evaluate(&expr5).unwrap();

    assert_eq!(res1, false);
    assert_eq!(res2, true);
    assert_eq!(res3, true);
    assert_eq!(res4, true);
    assert_eq!(res5, true);
}

#[test]
fn test_basic_evaluate_with_nulls() {
    let mut context = HashMap::new();

    context.insert("a".to_string(), serde_json::Value::Null);
    context.insert("b".to_string(), serde_json::Value::Bool(true));

    let evaluator = Evaluator::new(
        context,
        HashMap::new(), // custom_functions
    );

    let expr1 = "a && b";
    let expr2 = "a || b";
    let expr3 = "a && !b";
    let expr4 = "a || !b";
    let expr5 = "a && b || a && !b";
    let res1 = evaluator.evaluate(&expr1).unwrap();
    let res2 = evaluator.evaluate(&expr2).unwrap();
    let res3 = evaluator.evaluate(&expr3).unwrap();
    let res4 = evaluator.evaluate(&expr4).unwrap();
    let res5 = evaluator.evaluate(&expr5).unwrap();

    assert_eq!(res1, false);
    assert_eq!(res2, true);
    assert_eq!(res3, false);
    assert_eq!(res4, false);
    assert_eq!(res5, false);
}

// #[test]
// fn test_basic_evaluate_with_empty_strings() {
//     let mut context = HashMap::new();
//
//     context.insert(
//         "a".to_string(),
//         serde_json::Value::String("".to_string()),
//     );
//     context.insert("b".to_string(), serde_json::Value::Bool(true));
//
//     #[cfg(feature = "logging")]
//     let logger = Logger::default();
//
//     let evaluator = Evaluator::new(
//         context,
//         #[cfg(feature = "logging")]
//         logger,
//     );
//
//     let expr1 = "a && b";
//     let expr2 = "a || b";
//     let expr3 = "a && !b";
//     let expr4 = "a || !b";
//     let expr5 = "a && b || a && !b";
//     let res1 = evaluator.evaluate(&expr1).unwrap();
//     let res2 = evaluator.evaluate(&expr2).unwrap();
//     let res3 = evaluator.evaluate(&expr3).unwrap();
//     let res4 = evaluator.evaluate(&expr4).unwrap();
//     let res5 = evaluator.evaluate(&expr5).unwrap();
//
//     assert_eq!(res1, false);
//     assert_eq!(res2, true);
//     assert_eq!(res3, false);
//     assert_eq!(res4, false);
//     assert_eq!(res5, false);
// }

#[test]
fn test_single_quotes_expressions() {
    let mut context = HashMap::new();

    context.insert(
        "a".to_string(),
        serde_json::Value::String("true".to_string()),
    );
    let evaluator = Evaluator::new(
        context,
        HashMap::new(), // custom_functions
    );

    let expr1 = "a == 'true'";

    let res1 = evaluator.evaluate(&expr1).unwrap();

    assert_eq!(res1, true);
}

// --- Custom Function Tests ---

// Imports needed for custom function tests
use exprimo::{CustomFuncError, CustomFunction, EvaluationError};
use serde_json::Value; // Already imported at top level if this is the same file
use std::fmt::Debug;
use std::sync::Arc; // Required for CustomFunction trait
                    // HashMap is already imported at top level

#[derive(Debug)] // Debug is required by the CustomFunction trait
struct MyTestAdder;

impl CustomFunction for MyTestAdder {
    fn call(&self, args: &[Value]) -> Result<Value, CustomFuncError> {
        if args.len() != 2 {
            return Err(CustomFuncError::ArityError {
                expected: 2,
                got: args.len(),
            });
        }
        match (&args[0], &args[1]) {
            (Value::Number(a), Value::Number(b)) => {
                if let (Some(val_a), Some(val_b)) = (a.as_f64(), b.as_f64()) {
                    Ok(Value::Number(
                        serde_json::Number::from_f64(val_a + val_b).unwrap(),
                    ))
                } else {
                    Err(CustomFuncError::ArgumentError(
                        "Non-finite number provided".to_string(),
                    ))
                }
            }
            _ => Err(CustomFuncError::ArgumentError(
                "Arguments must be numbers".to_string(),
            )),
        }
    }
}

#[test]
fn test_parenthesized_expressions() {
    let mut context = HashMap::new();
    context.insert(
        "a".to_string(),
        serde_json::Value::Number(serde_json::Number::from_f64(1.0).unwrap()),
    );
    context.insert(
        "b".to_string(),
        serde_json::Value::Number(serde_json::Number::from_f64(2.0).unwrap()),
    );
    context.insert(
        "c".to_string(),
        serde_json::Value::Number(serde_json::Number::from_f64(3.0).unwrap()),
    );
    context.insert(
        "d".to_string(),
        serde_json::Value::Number(serde_json::Number::from_f64(4.0).unwrap()),
    );

    let evaluator = Evaluator::new(
        context,
        HashMap::new(), // custom_functions
    );

    // Simple case: (1 + 2) * 3 = 9
    let expr1 = "(a + b) * c";
    let res1 = evaluator.evaluate(expr1).unwrap();
    assert_eq!(
        res1,
        serde_json::Value::Number(serde_json::Number::from_f64(9.0).unwrap())
    );

    // Nested parentheses: ((1 + 2) * 3) / 4 = 2.25
    let expr2 = "((a + b) * c) / d";
    let res2 = evaluator.evaluate(expr2).unwrap();
    assert_eq!(
        res2,
        serde_json::Value::Number(serde_json::Number::from_f64(2.25).unwrap())
    );

    // More complex expression: ( (4-2) * ( (1+2)*3 ) ) / (10/5) = (2 * 9) / 2 = 9
    // Using direct numbers for clarity here, assuming context a,b,c,d are not used or are shadowed by literals
    let expr3 = "((d-b) * ((a+b)*c)) / (10/5)";
    let res3 = evaluator.evaluate(expr3).unwrap();
    assert_eq!(
        res3,
        serde_json::Value::Number(serde_json::Number::from_f64(9.0).unwrap())
    );

    // Expression with unary operator
    let expr4 = "-(a + b)";
    let res4 = evaluator.evaluate(expr4).unwrap();
    assert_eq!(
        res4,
        serde_json::Value::Number(serde_json::Number::from_f64(-3.0).unwrap())
    );

    // Expression with unary operator inside parentheses
    let expr5 = "c * (-a - b)"; // 3 * (-1 - 2) = 3 * (-3) = -9
    let res5 = evaluator.evaluate(expr5).unwrap();
    assert_eq!(
        res5,
        serde_json::Value::Number(serde_json::Number::from_f64(-9.0).unwrap())
    );

    // Expression with boolean logic
    let expr6 = "(a < b) && (c > d)"; // (1 < 2) && (3 > 4) -> true && false -> false
    let res6 = evaluator.evaluate(expr6).unwrap();
    assert_eq!(res6, serde_json::Value::Bool(false));

    // Expression with boolean logic and parentheses for precedence
    let expr7 = "a < b && c > d || a == 1"; // (1<2 && 3>4) || 1==1 -> (true && false) || true -> false || true -> true
    let res7 = evaluator.evaluate(expr7).unwrap();
    assert_eq!(res7, serde_json::Value::Bool(true));

    let expr8 = "a < b && (c > d || a == 1)"; // 1<2 && (3>4 || 1==1) -> true && (false || true) -> true && true -> true
    let res8 = evaluator.evaluate(expr8).unwrap();
    assert_eq!(res8, serde_json::Value::Bool(true));
}

// --- Object.hasOwnProperty() Tests ---

#[test]
fn test_object_has_own_property_success() {
    let mut context = HashMap::new();
    let mut obj = serde_json::Map::new();
    obj.insert("name".to_string(), Value::String("Alice".to_string()));
    obj.insert("age".to_string(), Value::Number(30.into()));
    obj.insert(
        "".to_string(),
        Value::String("empty_string_key".to_string()),
    ); // Empty string as key
    context.insert("myObj".to_string(), Value::Object(obj));

    let evaluator = Evaluator::new(context, HashMap::new());

    assert_eq!(
        evaluator.evaluate("myObj.hasOwnProperty('name')").unwrap(),
        Value::Bool(true)
    );
    assert_eq!(
        evaluator.evaluate("myObj.hasOwnProperty(\"age\")").unwrap(),
        Value::Bool(true)
    );
    assert_eq!(
        evaluator
            .evaluate("myObj.hasOwnProperty('nonExistent')")
            .unwrap(),
        Value::Bool(false)
    );
    assert_eq!(
        evaluator.evaluate("myObj.hasOwnProperty('')").unwrap(),
        Value::Bool(true)
    ); // Test empty string key

    // Test coercion of argument to string for a key that doesn't exist on myObj
    assert_eq!(
        evaluator.evaluate("myObj.hasOwnProperty(123)").unwrap(),
        Value::Bool(false)
    ); // effectively myObj.hasOwnProperty("123")
    assert_eq!(
        evaluator.evaluate("myObj.hasOwnProperty(true)").unwrap(),
        Value::Bool(false)
    ); // effectively myObj.hasOwnProperty("true")

    // Setup a new context for an object that has stringified number as key
    let mut context2 = HashMap::new();
    let mut obj_with_true_key = serde_json::Map::new();
    obj_with_true_key.insert(
        "true".to_string(),
        Value::String("test value for boolean true key".to_string()),
    );
    context2.insert("objTrueKey".to_string(), Value::Object(obj_with_true_key));

    let evaluator2_true = Evaluator::new(context2.clone(), HashMap::new());

    assert_eq!(
        evaluator2_true
            .evaluate("objTrueKey.hasOwnProperty(true)")
            .unwrap(), // Evaluates to objTrueKey.hasOwnProperty("true")
        Value::Bool(true),
        "objTrueKey should have property 'true' when called with boolean true"
    );
    assert_eq!(
        evaluator2_true
            .evaluate("objTrueKey.hasOwnProperty(false)")
            .unwrap(), // Evaluates to objTrueKey.hasOwnProperty("false")
        Value::Bool(false),
        "objTrueKey should not have property 'false'"
    );

    // Test with a key that looks like a number
    let mut context3 = HashMap::new();
    let mut obj_with_num_key_str = serde_json::Map::new();
    obj_with_num_key_str.insert("123".to_string(), Value::Bool(true));
    context3.insert(
        "objNumStrKey".to_string(),
        Value::Object(obj_with_num_key_str),
    );

    let evaluator3_num = Evaluator::new(context3, HashMap::new());

    assert_eq!(
        evaluator3_num
            .evaluate("objNumStrKey.hasOwnProperty(123)")
            .unwrap(),
        Value::Bool(false)
    );
    assert_eq!(
        evaluator3_num
            .evaluate("objNumStrKey.hasOwnProperty('123')")
            .unwrap(),
        Value::Bool(true)
    );
}

#[test]
fn test_object_has_own_property_arity_error() {
    let mut context = HashMap::new();
    context.insert("myObj".to_string(), Value::Object(serde_json::Map::new()));
    let evaluator = Evaluator::new(context, HashMap::new());

    let res_no_args = evaluator.evaluate("myObj.hasOwnProperty()");
    match res_no_args {
        Err(EvaluationError::CustomFunction(CustomFuncError::ArityError { expected, got })) => {
            assert_eq!(expected, 1);
            assert_eq!(got, 0);
        }
        _ => panic!(
            "Expected ArityError for no arguments, got {:?}",
            res_no_args
        ),
    }

    let res_many_args = evaluator.evaluate("myObj.hasOwnProperty('prop', 'extra')");
    match res_many_args {
        Err(EvaluationError::CustomFunction(CustomFuncError::ArityError { expected, got })) => {
            assert_eq!(expected, 1);
            assert_eq!(got, 2);
        }
        _ => panic!(
            "Expected ArityError for many arguments, got {:?}",
            res_many_args
        ),
    }
}

#[test]
fn test_object_has_own_property_on_non_object() {
    let mut context = HashMap::new();
    context.insert("myArr".to_string(), Value::Array(vec![]));
    context.insert("myStr".to_string(), Value::String("text".to_string()));

    let evaluator = Evaluator::new(context, HashMap::new());

    // Case 1: Array
    let expr_arr = "myArr.hasOwnProperty('length')";
    let result_arr = evaluator.evaluate(expr_arr);
    match result_arr {
        Err(EvaluationError::TypeError(msg)) => {
            assert_eq!(
                msg,
                "'null' (resulting from expression 'myArr.hasOwnProperty') is not a function."
            );
        }
        _ => panic!(
            "Expected TypeError for myArr.hasOwnProperty, got {:?}",
            result_arr
        ),
    }

    // Case 2: String
    let expr_str = "myStr.hasOwnProperty('length')";
    let result_str = evaluator.evaluate(expr_str);
    match result_str {
        Err(EvaluationError::TypeError(msg)) => {
            assert_eq!(msg, "Cannot read properties of null or primitive value: text (trying to access property: hasOwnProperty)");
        }
        _ => panic!(
            "Expected TypeError for myStr.hasOwnProperty, got {:?}",
            result_str
        ),
    }
}

#[test]
fn test_object_has_own_property_nested() {
    let mut context = HashMap::new();
    let mut inner_obj = serde_json::Map::new();
    inner_obj.insert("value".to_string(), Value::Bool(true));
    let mut outer_obj = serde_json::Map::new();
    outer_obj.insert("nestedObj".to_string(), Value::Object(inner_obj));
    context.insert("item".to_string(), Value::Object(outer_obj));

    let evaluator = Evaluator::new(context, HashMap::new());

    assert_eq!(
        evaluator
            .evaluate("item.nestedObj.hasOwnProperty('value')")
            .unwrap(),
        Value::Bool(true)
    );
    assert_eq!(
        evaluator
            .evaluate("item.nestedObj.hasOwnProperty('nonExistent')")
            .unwrap(),
        Value::Bool(false)
    );
}

// --- Array.includes() Tests ---

#[test]
fn test_array_includes_success() {
    let mut context = HashMap::new();
    let arr = Value::Array(vec![
        Value::Number(10.into()),
        Value::String("hello".to_string()),
        Value::Bool(true),
        Value::Null,
    ]);
    context.insert("myArr".to_string(), arr);

    let evaluator = Evaluator::new(context, HashMap::new());

    assert_eq!(
        evaluator.evaluate("myArr.includes(10)").unwrap(),
        Value::Bool(true)
    );
    assert_eq!(
        evaluator.evaluate("myArr.includes(\"hello\")").unwrap(),
        Value::Bool(true)
    );
    assert_eq!(
        evaluator.evaluate("myArr.includes(true)").unwrap(),
        Value::Bool(true)
    );
    assert_eq!(
        evaluator.evaluate("myArr.includes(null)").unwrap(),
        Value::Bool(true)
    );

    assert_eq!(
        evaluator.evaluate("myArr.includes(20)").unwrap(),
        Value::Bool(false)
    );
    assert_eq!(
        evaluator.evaluate("myArr.includes(\"world\")").unwrap(),
        Value::Bool(false)
    );
    assert_eq!(
        evaluator.evaluate("myArr.includes(false)").unwrap(),
        Value::Bool(false)
    );
    // Note: Value::Null is present, so `myArr.includes(something_else_that_is_not_null)` should be false.
    // serde_json::Value::Object(Map::new()) is not in the array.
    assert_eq!(
        evaluator.evaluate("myArr.includes({})").unwrap(),
        Value::Bool(false)
    );
}

#[test]
fn test_array_includes_arity_error() {
    let mut context = HashMap::new();
    context.insert("myArr".to_string(), Value::Array(vec![]));
    let evaluator = Evaluator::new(context, HashMap::new());

    let res_no_args = evaluator.evaluate("myArr.includes()");
    match res_no_args {
        Err(EvaluationError::CustomFunction(CustomFuncError::ArityError { expected, got })) => {
            assert_eq!(expected, 1);
            assert_eq!(got, 0);
        }
        _ => panic!(
            "Expected ArityError for no arguments, got {:?}",
            res_no_args
        ),
    }

    let res_many_args = evaluator.evaluate("myArr.includes(1, 2)");
    match res_many_args {
        Err(EvaluationError::CustomFunction(CustomFuncError::ArityError { expected, got })) => {
            assert_eq!(expected, 1);
            assert_eq!(got, 2);
        }
        _ => panic!(
            "Expected ArityError for many arguments, got {:?}",
            res_many_args
        ),
    }
}

#[test]
fn test_array_includes_on_non_array() {
    let mut context = HashMap::new();
    context.insert("notAnArray".to_string(), Value::String("hello".to_string()));
    let evaluator = Evaluator::new(context, HashMap::new());

    let result = evaluator.evaluate("notAnArray.includes(1)");
    match result {
        Err(EvaluationError::TypeError(msg)) => {
            // This error is from evaluate_dot_expr directly when trying to access 'includes' on a string "hello".
            assert_eq!(msg, "Cannot read properties of null or primitive value: hello (trying to access property: includes)");
        }
        _ => panic!(
            "Expected TypeError when calling .includes on non-array, got {:?}",
            result
        ),
    }
}

#[test]
fn test_array_includes_nested() {
    let mut context = HashMap::new();
    let mut obj = serde_json::Map::new();
    let arr = Value::Array(vec![Value::Number(42.into())]);
    obj.insert("nestedArr".to_string(), arr);
    context.insert("myObj".to_string(), Value::Object(obj));

    let evaluator = Evaluator::new(context, HashMap::new());

    assert_eq!(
        evaluator.evaluate("myObj.nestedArr.includes(42)").unwrap(),
        Value::Bool(true)
    );
    assert_eq!(
        evaluator.evaluate("myObj.nestedArr.includes(100)").unwrap(),
        Value::Bool(false)
    );
}

#[test]
fn test_custom_adder_success() {
    let context = HashMap::new();
    let mut custom_funcs: HashMap<String, Arc<dyn CustomFunction>> = HashMap::new();
    custom_funcs.insert("custom_add".to_string(), Arc::new(MyTestAdder));

    let evaluator = Evaluator::new(
        // Evaluator is already imported
        context,
        custom_funcs,
    );

    let result = evaluator.evaluate("custom_add(10, 20.5)").unwrap();
    assert_eq!(result.as_f64(), Some(30.5));

    let result_neg = evaluator.evaluate("custom_add(-5, -2)").unwrap();
    assert_eq!(result_neg.as_f64(), Some(-7.0));
}

#[test]
fn test_custom_adder_arity_error_few_args() {
    let context = HashMap::new();
    let mut custom_funcs: HashMap<String, Arc<dyn CustomFunction>> = HashMap::new();
    custom_funcs.insert("custom_add".to_string(), Arc::new(MyTestAdder));

    let evaluator = Evaluator::new(context, custom_funcs);

    let result = evaluator.evaluate("custom_add(10)");
    match result {
        Err(EvaluationError::CustomFunction(CustomFuncError::ArityError { expected, got })) => {
            assert_eq!(expected, 2);
            assert_eq!(got, 1);
        }
        _ => panic!("Expected ArityError, got {:?}", result),
    }
}

#[test]
fn test_custom_adder_arity_error_many_args() {
    let context = HashMap::new();
    let mut custom_funcs: HashMap<String, Arc<dyn CustomFunction>> = HashMap::new();
    custom_funcs.insert("custom_add".to_string(), Arc::new(MyTestAdder));

    let evaluator = Evaluator::new(context, custom_funcs);

    let result = evaluator.evaluate("custom_add(10, 20, 30)");
    match result {
        Err(EvaluationError::CustomFunction(CustomFuncError::ArityError { expected, got })) => {
            assert_eq!(expected, 2);
            assert_eq!(got, 3);
        }
        _ => panic!("Expected ArityError, got {:?}", result),
    }
}

#[test]
fn test_custom_adder_type_error_arg1() {
    let context = HashMap::new();
    let mut custom_funcs: HashMap<String, Arc<dyn CustomFunction>> = HashMap::new();
    custom_funcs.insert("custom_add".to_string(), Arc::new(MyTestAdder));

    let evaluator = Evaluator::new(context, custom_funcs);

    let result = evaluator.evaluate("custom_add('not_a_number', 10)");
    match result {
        Err(EvaluationError::CustomFunction(CustomFuncError::ArgumentError(msg))) => {
            assert_eq!(msg, "Arguments must be numbers");
        }
        _ => panic!("Expected ArgumentError, got {:?}", result),
    }
}

#[test]
fn test_custom_adder_type_error_arg2() {
    let context = HashMap::new();
    let mut custom_funcs: HashMap<String, Arc<dyn CustomFunction>> = HashMap::new();
    custom_funcs.insert("custom_add".to_string(), Arc::new(MyTestAdder));

    let evaluator = Evaluator::new(context, custom_funcs);

    let result = evaluator.evaluate("custom_add(10, 'not_a_number')");
    match result {
        Err(EvaluationError::CustomFunction(CustomFuncError::ArgumentError(msg))) => {
            assert_eq!(msg, "Arguments must be numbers");
        }
        _ => panic!("Expected ArgumentError, got {:?}", result),
    }
}

#[test]
fn test_custom_adder_non_finite_number_error() {
    let context = HashMap::new();
    let mut custom_funcs: HashMap<String, Arc<dyn CustomFunction>> = HashMap::new();
    custom_funcs.insert("custom_add".to_string(), Arc::new(MyTestAdder));

    let evaluator = Evaluator::new(context, custom_funcs);

    // Create a NaN Value::Number (Note: serde_json::Number cannot directly represent NaN/Infinity)
    // This test relies on the internal f64 conversion and check.
    // For the purpose of this test, we'll assume that if a Value::Number
    // somehow contained a non-finite f64, our function would catch it.
    // Direct creation of such a serde_json::Value::Number is tricky,
    // as it typically only supports finite numbers.
    // The error "Non-finite number provided" is more of a safeguard
    // if such a value were to be constructed manually or via other means.
    // We can't directly test this path with standard expression strings
    // if the parser/evaluator only produces finite Value::Number.
    // However, if a custom function internally constructed such a value and passed it
    // to another custom function, this check would be relevant.
    // For now, we acknowledge this path is hard to test via string expressions.
    // A direct call to `MyTestAdder.call()` would be needed to test this,
    // which is outside the scope of `evaluator.evaluate()`.
    // So, this specific error condition "Non-finite number provided"
    // is not easily testable through the evaluator's `evaluate` method
    // if the parser only generates valid numbers.
    // The existing type error tests cover cases where types are not numbers.
}

// --- Property Access Tests ---

#[test]
fn test_array_length_direct() {
    let mut context = HashMap::new();
    let my_array = Value::Array(vec![Value::from(1), Value::from(2), Value::from(3)]);
    context.insert("myArray".to_string(), my_array);

    let evaluator = Evaluator::new(context, HashMap::new());

    let result = evaluator.evaluate("myArray.length").unwrap();
    assert_eq!(
        result,
        Value::Number(serde_json::Number::from_f64(3.0).unwrap())
    );
}

#[test]
fn test_array_length_nested_in_object() {
    let mut context = HashMap::new();
    let my_array = Value::Array(vec![Value::from("a"), Value::from("b")]);
    let mut obj = serde_json::Map::new();
    obj.insert("arr".to_string(), my_array);
    context.insert("myObj".to_string(), Value::Object(obj));

    let evaluator = Evaluator::new(context, HashMap::new());

    let result = evaluator.evaluate("myObj.arr.length").unwrap();
    assert_eq!(
        result,
        Value::Number(serde_json::Number::from_f64(2.0).unwrap())
    );
}

#[test]
fn test_length_on_non_array() {
    let mut context = HashMap::new();
    context.insert("myString".to_string(), Value::String("hello".to_string()));
    context.insert("myNum".to_string(), Value::Number(123.into()));
    let mut obj_without_length = serde_json::Map::new();
    obj_without_length.insert("prop".to_string(), Value::from("value"));
    context.insert("myObj".to_string(), Value::Object(obj_without_length));
    context.insert("nullVar".to_string(), Value::Null);

    let evaluator = Evaluator::new(context.clone(), HashMap::new());

    // String.length is not yet implemented, should fall into the generic "cannot read props of primitive" or specific "length" error
    let res_str = evaluator.evaluate("myString.length");
    match res_str {
        Err(EvaluationError::TypeError(msg)) => {
            assert_eq!(
                msg,
                "Cannot read property 'length' of non-array/non-object value: hello"
            );
        }
        _ => panic!("Expected TypeError for string.length, got {:?}", res_str),
    }

    let res_num = evaluator.evaluate("myNum.length");
    match res_num {
        Err(EvaluationError::TypeError(msg)) => {
            assert_eq!(
                msg,
                "Cannot read property 'length' of non-array/non-object value: 123"
            );
        }
        _ => panic!("Expected TypeError for number.length, got {:?}", res_num),
    }

    // Accessing .length on an object that doesn't have it should return Value::Null
    let res_obj = evaluator.evaluate("myObj.length").unwrap();
    assert_eq!(res_obj, Value::Null);

    let res_null = evaluator.evaluate("nullVar.length");
    match res_null {
        Err(EvaluationError::TypeError(msg)) => {
            assert_eq!(
                msg,
                "Cannot read property 'length' of non-array/non-object value: null"
            );
        }
        _ => panic!("Expected TypeError for null.length, got {:?}", res_null),
    }
}

#[test]
fn test_other_property_on_array() {
    let mut context = HashMap::new();
    let my_array = Value::Array(vec![Value::from(1)]);
    context.insert("myArray".to_string(), my_array);

    let evaluator = Evaluator::new(context, HashMap::new());

    let result = evaluator.evaluate("myArray.foo").unwrap();
    assert_eq!(result, Value::Null); // JS returns undefined, so we return Null
}

#[test]
fn test_property_access_on_object() {
    let mut context = HashMap::new();
    let mut obj = serde_json::Map::new();
    obj.insert("name".to_string(), Value::String("Tester".to_string()));
    obj.insert("age".to_string(), Value::Number(30.into()));
    context.insert("user".to_string(), Value::Object(obj));

    let evaluator = Evaluator::new(context, HashMap::new());

    assert_eq!(
        evaluator.evaluate("user.name").unwrap(),
        Value::String("Tester".to_string())
    );
    assert_eq!(
        evaluator.evaluate("user.age").unwrap(),
        Value::Number(30.into())
    );
    assert_eq!(evaluator.evaluate("user.nonexistent").unwrap(), Value::Null);
}

#[test]
fn test_property_access_on_nested_object() {
    let mut context = HashMap::new();
    let mut inner_obj = serde_json::Map::new();
    inner_obj.insert("value".to_string(), Value::Bool(true));
    let mut outer_obj = serde_json::Map::new();
    outer_obj.insert("nested".to_string(), Value::Object(inner_obj));
    context.insert("item".to_string(), Value::Object(outer_obj));

    let evaluator = Evaluator::new(context, HashMap::new());

    assert_eq!(
        evaluator.evaluate("item.nested.value").unwrap(),
        Value::Bool(true)
    );
    assert_eq!(evaluator.evaluate("item.nested.foo").unwrap(), Value::Null);

    let res_access_on_null = evaluator.evaluate("item.nonexistent.bar"); // item.nonexistent is Null, then .bar on Null
    match res_access_on_null {
        Err(EvaluationError::TypeError(msg)) => {
            assert!(msg.contains("Cannot read properties of null or primitive value: null (trying to access property: bar)"));
        }
        _ => panic!(
            "Expected TypeError for item.nonexistent.bar, got {:?}",
            res_access_on_null
        ),
    }
}

#[test]
fn test_property_access_on_null_or_primitive_object_error() {
    let mut context = HashMap::new();
    context.insert("s".to_string(), Value::String("text".to_string()));
    context.insert("n".to_string(), Value::Number(123.into()));
    context.insert("b".to_string(), Value::Bool(true));
    context.insert("nl".to_string(), Value::Null);

    let evaluator = Evaluator::new(context, HashMap::new());

    let cases = vec!["s.foo", "n.bar", "b.baz", "nl.qux"];
    for case in cases {
        let result = evaluator.evaluate(case);
        match result {
            Err(EvaluationError::TypeError(msg)) => {
                assert!(msg.starts_with("Cannot read properties of null or primitive value:"));
            }
            _ => panic!(
                "Expected TypeError for property access on primitive/null, got {:?}",
                result
            ),
        }
    }
}