openjd-expr 0.1.0

Open Job Description expression language — types, evaluation, and path mapping
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
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Copyright by contributors to this project.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

//! Tests ported from Python test_error_formatting.py
//!
//! Gold standard: every error test asserts the full multi-line error message
//! (message + expression line + caret indicator) as a single concatenated string.

use openjd_expr::*;

fn eval_err(expr: &str) -> String {
    ParsedExpression::new(expr)
        .and_then(|p| p.evaluate(&SymbolTable::new()))
        .unwrap_err()
        .to_string()
}

fn eval_err_with(expr: &str, st: &SymbolTable) -> String {
    ParsedExpression::new(expr)
        .and_then(|p| p.evaluate(st))
        .unwrap_err()
        .to_string()
}

fn assert_err(expr: &str, expected: &[&str]) {
    let e = eval_err(expr);
    let joined = expected.concat();
    assert!(e.contains(&joined), "got:\n{e}\nexpected:\n{joined}");
}

fn assert_err_with(expr: &str, st: &SymbolTable, expected: &[&str]) {
    let e = eval_err_with(expr, st);
    let joined = expected.concat();
    assert!(e.contains(&joined), "got:\n{e}\nexpected:\n{joined}");
}

// === TestErrorCaretPointers ===

#[test]
fn type_error_in_middle() {
    assert_err(
        "1 + int('bad') + 2",
        &[
            "Cannot convert 'bad' to int\n",
            "  1 + int('bad') + 2\n",
            "      ^~~~~~~~~~",
        ],
    );
}

#[test]
fn type_error_at_start() {
    assert_err(
        "int('bad') + 1 + 2",
        &[
            "Cannot convert 'bad' to int\n",
            "  int('bad') + 1 + 2\n",
            "  ^~~~~~~~~~",
        ],
    );
}

#[test]
fn type_error_at_end() {
    assert_err(
        "1 + 2 + int('bad')",
        &[
            "Cannot convert 'bad' to int\n",
            "  1 + 2 + int('bad')\n",
            "          ^~~~~~~~~~",
        ],
    );
}

#[test]
fn operator_error_friendly_name() {
    assert_err(
        "'hello' + 5",
        &[
            "Cannot use '+' operator with string and int\n",
            "  'hello' + 5\n",
            "  ~~~~~~~~^~~",
        ],
    );
}

#[test]
fn operator_error_in_middle() {
    assert_err(
        "1 + 'hello' + 5",
        &[
            "Cannot use '+' operator with int and string\n",
            "  1 + 'hello' + 5\n",
            "  ~~^~~~~~~~~",
        ],
    );
}

#[test]
fn division_by_zero_in_middle() {
    assert_err(
        "10 + 5 / 0 + 2",
        &["Division by zero\n", "  10 + 5 / 0 + 2\n", "       ~~^~~"],
    );
}

#[test]
fn index_out_of_bounds_shows_length() {
    assert_err(
        "[1,2,3][10]",
        &[
            "Index 10 out of bounds for list of length 3\n",
            "  [1,2,3][10]\n",
            "  ~~~~~~~^~~~",
        ],
    );
}

#[test]
fn unknown_property_friendly_name() {
    assert_err(
        "path('/a/b').unknown",
        &[
            "Cannot access attribute 'unknown' on path\n",
            "  path('/a/b').unknown\n",
            "  ~~~~~~~~~~~~~^~~~~~~",
        ],
    );
}

#[test]
fn unknown_property_in_chain() {
    assert_err(
        "path('/a/b').parent.unknown",
        &[
            "Cannot access attribute 'unknown' on path\n",
            "  path('/a/b').parent.unknown\n",
            "  ~~~~~~~~~~~~~~~~~~~~^~~~~~~",
        ],
    );
}

#[test]
fn min_empty_list_error() {
    assert_err(
        "1 + min([]) + 2",
        &[
            "min() requires a non-empty list\n",
            "  1 + min([]) + 2\n",
            "      ^~~~~~~",
        ],
    );
}

#[test]
fn split_empty_separator() {
    assert_err(
        "10 + 'x'.split('') + 5",
        &[
            "split failed: empty separator\n",
            "  10 + 'x'.split('') + 5\n",
            "       ~~~~^~~~~~~~~",
        ],
    );
}

#[test]
fn deeply_nested_error() {
    assert_err(
        "1 + (2 + (3 + int('x')))",
        &[
            "Cannot convert 'x' to int\n",
            "  1 + (2 + (3 + int('x')))\n",
            "                ^~~~~~~~",
        ],
    );
}

#[test]
fn error_in_function_argument() {
    assert_err(
        "min(1, int('x'), 3)",
        &[
            "Cannot convert 'x' to int\n",
            "  min(1, int('x'), 3)\n",
            "         ^~~~~~~~",
        ],
    );
}

#[test]
fn error_in_condition() {
    assert_err(
        "1 if int('x') else 2",
        &[
            "Cannot convert 'x' to int\n",
            "  1 if int('x') else 2\n",
            "       ^~~~~~~~",
        ],
    );
}

#[test]
fn error_in_comprehension_body() {
    assert_err(
        "[int('x') for i in [1,2]]",
        &[
            "Cannot convert 'x' to int\n",
            "  [int('x') for i in [1,2]]\n",
            "   ^~~~~~~~",
        ],
    );
}

#[test]
fn error_in_comprehension_filter() {
    assert_err(
        "[i for i in [1,2] if int('x')]",
        &[
            "Cannot convert 'x' to int\n",
            "  [i for i in [1,2] if int('x')]\n",
            "                       ^~~~~~~~",
        ],
    );
}

#[test]
fn chained_method_error() {
    assert_err(
        "'hello'.upper().nonexistent()",
        &[
            "Unknown function: 'nonexistent'\n",
            "  'hello'.upper().nonexistent()\n",
            "  ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~",
        ],
    );
}

#[test]
fn undefined_variable() {
    assert_err("X + 1", &["Undefined variable: 'X'.\n", "  X + 1\n", "  ^"]);
}

#[test]
fn undefined_variable_with_suggestion() {
    // Param.Frane is close to Param.Frame — should suggest it
    let mut st = openjd_expr::SymbolTable::new();
    st.set("Param.Frame", openjd_expr::ExprValue::Int(1))
        .unwrap();
    st.set(
        "Param.Scene",
        openjd_expr::ExprValue::String("forest".into()),
    )
    .unwrap();
    let result =
        openjd_expr::ParsedExpression::new("Param.Frane + 1").and_then(|p| p.evaluate(&st));
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("Did you mean: Param.Frame"),
        "Expected suggestion in: {err}"
    );
}

#[test]
fn undefined_variable_no_suggestion_when_distant() {
    let mut st = openjd_expr::SymbolTable::new();
    st.set("Param.Frame", openjd_expr::ExprValue::Int(1))
        .unwrap();
    let result =
        openjd_expr::ParsedExpression::new("CompletelyWrong + 1").and_then(|p| p.evaluate(&st));
    let err = result.unwrap_err().to_string();
    assert!(
        !err.contains("Did you mean"),
        "Should not suggest for distant names: {err}"
    );
}

#[test]
fn float_literal_infinity() {
    assert_err(
        "1e3000",
        &[
            "Float operation produced infinity\n",
            "  1e3000\n",
            "  ^~~~~~",
        ],
    );
}

#[test]
fn float_literal_infinity_in_expression() {
    assert_err(
        "1e3000 + 1",
        &[
            "Float operation produced infinity\n",
            "  1e3000 + 1\n",
            "  ^~~~~~",
        ],
    );
}

// === TestErrorCaretWithWhitespace ===

#[test]
fn leading_whitespace_stripped() {
    assert_err(
        "  1 + int('bad')",
        &[
            "Cannot convert 'bad' to int\n",
            "  1 + int('bad')\n",
            "      ^~~~~~~~~~",
        ],
    );
}

#[test]
fn leading_whitespace_error_in_middle() {
    assert_err(
        "  1 + int('bad') + 2",
        &[
            "Cannot convert 'bad' to int\n",
            "  1 + int('bad') + 2\n",
            "      ^~~~~~~~~~",
        ],
    );
}

// === Exact format tests ===

#[test]
fn exact_division_by_zero_format() {
    assert_err("5 / 0", &["Division by zero\n", "  5 / 0\n", "  ~~^~~"]);
}

#[test]
fn exact_int_conversion_error_format() {
    assert_err(
        "int('bad')",
        &[
            "Cannot convert 'bad' to int\n",
            "  int('bad')\n",
            "  ^~~~~~~~~~",
        ],
    );
}

#[test]
fn exact_modulo_by_zero_format() {
    assert_err("10 % 0", &["Modulo by zero\n", "  10 % 0\n", "  ~~~^~~"]);
}

#[test]
fn exact_fail_format() {
    assert_err(
        "fail(\"oops\")",
        &["oops\n", "  fail(\"oops\")\n", "  ^~~~~~~~~~~~"],
    );
}

#[test]
fn exact_index_out_of_bounds_format() {
    assert_err(
        "[1, 2, 3][10]",
        &[
            "Index 10 out of bounds for list of length 3\n",
            "  [1, 2, 3][10]\n",
            "  ~~~~~~~~~^~~~",
        ],
    );
}

#[test]
fn exact_condition_must_be_bool() {
    assert_err(
        "1 if 'hello' else 2",
        &["  1 if 'hello' else 2\n", "       ^~~~~~~"],
    );
}

// === TestImprovedErrorMessages ===

#[test]
fn wrong_arg_count_zero() {
    assert_err(
        "len()",
        &[
            "len() takes 1 argument(s), but 0 were given\n",
            "  len()\n",
            "  ^~~~~",
        ],
    );
}

#[test]
fn wrong_arg_count_too_many() {
    assert_err(
        "len('a', 'b')",
        &[
            "len() takes 1 argument(s), but 2 were given\n",
            "  len('a', 'b')\n",
            "  ^~~~~~~~~~~~~",
        ],
    );
}

#[test]
fn wrong_arg_count_multiple_arities() {
    assert_err(
        "min()",
        &[
            "min() takes 1, 2, 3 arguments, but 0 were given\n",
            "  min()\n",
            "  ^~~~~",
        ],
    );
}

#[test]
fn method_on_wrong_type() {
    assert_err(
        "path(\"/a/b\").startswith(\"/a\")",
        &[
            "startswith() is not available for path. Available for: string\n",
            "  path(\"/a/b\").startswith(\"/a\")\n",
            "  ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~",
        ],
    );
}

#[test]
fn method_on_wrong_type_upper() {
    assert_err(
        "(5).upper()",
        &[
            "upper() is not available for int. Available for: string\n",
            "  (5).upper()\n",
            "  ~~~^~~~~~~~",
        ],
    );
}

#[test]
fn property_on_wrong_type() {
    assert_err(
        "True.stem",
        &[
            "'stem' property is not available for bool. Available for: path\n",
            "  True.stem\n",
            "  ~~~~~^~~~",
        ],
    );
}

#[test]
fn property_on_wrong_type_parent() {
    assert_err(
        "'hello'.parent",
        &[
            "'parent' property is not available for string. Available for: path\n",
            "  'hello'.parent\n",
            "  ~~~~~~~~^~~~~~",
        ],
    );
}

#[test]
fn attribute_without_call_suggests_parens() {
    assert_err(
        "'hello'.upper",
        &[
            "'upper' is a method, not a property. Did you mean upper()?\n",
            "  'hello'.upper\n",
            "  ~~~~~~~~^~~~~",
        ],
    );
}

#[test]
fn attribute_without_call_split() {
    assert_err(
        "'hello'.split",
        &[
            "'split' is a method, not a property. Did you mean split()?\n",
            "  'hello'.split\n",
            "  ~~~~~~~~^~~~~",
        ],
    );
}

#[test]
fn property_called_as_method() {
    assert_err(
        "path('/a/b').stem()",
        &[
            "'stem' is a property, not a method. Use .stem instead of .stem()\n",
            "  path('/a/b').stem()\n",
            "  ~~~~~~~~~~~~~^~~~~~",
        ],
    );
}

// === Additional caret tests ===

#[test]
fn division_by_zero_caret() {
    assert_err("10 / 0", &["Division by zero\n", "  10 / 0\n", "  ~~~^~~"]);
}

#[test]
fn index_out_of_bounds_caret() {
    let mut st = SymbolTable::new();
    st.set(
        "L",
        ExprValue::make_list(
            vec![ExprValue::Int(1), ExprValue::Int(2), ExprValue::Int(3)],
            ExprType::INT,
        )
        .unwrap(),
    )
    .unwrap();
    assert_err_with(
        "L[10]",
        &st,
        &[
            "Index 10 out of bounds for list of length 3\n",
            "  L[10]\n",
            "  ~^~~~",
        ],
    );
}

#[test]
fn operator_error_caret_at_operator() {
    assert_err(
        "'hello' + 5",
        &[
            "Cannot use '+' operator with string and int\n",
            "  'hello' + 5\n",
            "  ~~~~~~~~^~~",
        ],
    );
}

#[test]
fn function_call_error_caret() {
    assert_err(
        "int('bad')",
        &[
            "Cannot convert 'bad' to int\n",
            "  int('bad')\n",
            "  ^~~~~~~~~~",
        ],
    );
}

#[test]
fn method_call_error_caret() {
    assert_err(
        "'x'.split('')",
        &[
            "split failed: empty separator\n",
            "  'x'.split('')\n",
            "  ~~~~^~~~~~~~~",
        ],
    );
}

#[test]
fn power_error_caret() {
    assert_err(
        "0 ** -1",
        &[
            "Cannot raise zero to a negative power\n",
            "  0 ** -1\n",
            "  ~~^~~~~",
        ],
    );
}

#[test]
fn fail_function_caret() {
    assert_err(
        "fail('boom')",
        &["boom\n", "  fail('boom')\n", "  ^~~~~~~~~~~~"],
    );
}

#[test]
fn leading_whitespace_preserved() {
    assert_err("  1 / 0", &["Division by zero\n", "  1 / 0\n", "  ~~^~~"]);
}

#[test]
fn syntax_error_has_message() {
    assert_err(
        "1 +",
        &["Syntax error: Expected an expression\n", "  1 +\n", "  ^"],
    );
}

// === TestSyntaxErrorCarets ===

#[test]
fn unclosed_paren() {
    assert_err(
        "(1 + 2",
        &[
            "Syntax error: unexpected EOF while parsing\n",
            "  (1 + 2\n",
            "  ^",
        ],
    );
}

#[test]
fn unclosed_bracket() {
    assert_err(
        "[1, 2",
        &[
            "Syntax error: unexpected EOF while parsing\n",
            "  [1, 2\n",
            "  ^",
        ],
    );
}

#[test]
fn unclosed_string() {
    assert_err(
        "'hello",
        &[
            "Syntax error: missing closing quote in string literal\n",
            "  'hello\n",
            "  ^",
        ],
    );
}

// === TestMultiLineExpressions ===

#[test]
fn multiline_error_in_parens() {
    assert_err(
        "(\n  1 + int('bad')\n)",
        &[
            "Cannot convert 'bad' to int\n",
            "    1 + int('bad')\n",
            "        ^~~~~~~~~~",
        ],
    );
}

#[test]
fn multiline_error_in_list() {
    assert_err(
        "[\n  1,\n  int('bad'),\n  3\n]",
        &[
            "Cannot convert 'bad' to int\n",
            "    int('bad'),\n",
            "    ^~~~~~~~~~",
        ],
    );
}

#[test]
fn multiline_error_on_first_line() {
    assert_err(
        "(int('bad') +\n  1)",
        &[
            "Cannot convert 'bad' to int\n",
            "  (int('bad') +\n",
            "   ^~~~~~~~~~",
        ],
    );
}

#[test]
fn multiline_error_shows_correct_line() {
    assert_err(
        "(\n  1 +\n  int('bad') +\n  3\n)",
        &[
            "Cannot convert 'bad' to int\n",
            "    int('bad') +\n",
            "    ^~~~~~~~~~",
        ],
    );
}

// === TestImplicitLineContinuation ===

#[test]
fn multiline_addition() {
    let r = ParsedExpression::new("(\n  1 +\n  2 +\n  3\n)")
        .and_then(|p| p.evaluate(&SymbolTable::new()))
        .unwrap();
    assert_eq!(r.to_display_string(), "6");
}

#[test]
fn multiline_comparison() {
    let r = ParsedExpression::new("(\n  1 <\n  2\n)")
        .and_then(|p| p.evaluate(&SymbolTable::new()))
        .unwrap();
    assert_eq!(r.to_display_string(), "true");
}

#[test]
fn multiline_three_lines() {
    let r = ParsedExpression::new("(\n  'hello' +\n  ' ' +\n  'world'\n)")
        .and_then(|p| p.evaluate(&SymbolTable::new()))
        .unwrap();
    assert_eq!(r.to_display_string(), "hello world");
}

#[test]
fn multiline_error_shows_correct_line_v2() {
    assert_err(
        "(\n  1 +\n  int('bad') +\n  3\n)",
        &[
            "Cannot convert 'bad' to int\n",
            "    int('bad') +\n",
            "    ^~~~~~~~~~",
        ],
    );
}

#[test]
fn deeply_nested_multiline() {
    assert_err(
        "(\n  1 +\n  (2 + int('x'))\n)",
        &[
            "Cannot convert 'x' to int\n",
            "    (2 + int('x'))\n",
            "         ^~~~~~~~",
        ],
    );
}

#[test]
fn error_in_parentheses_multiline() {
    assert_err(
        "(\n  1 + int('bad')\n)",
        &[
            "Cannot convert 'bad' to int\n",
            "    1 + int('bad')\n",
            "        ^~~~~~~~~~",
        ],
    );
}

#[test]
fn error_in_list_multiline() {
    assert_err(
        "[\n  1,\n  int('bad'),\n  3\n]",
        &[
            "Cannot convert 'bad' to int\n",
            "    int('bad'),\n",
            "    ^~~~~~~~~~",
        ],
    );
}

#[test]
fn error_on_first_line_multiline() {
    assert_err(
        "(int('bad') +\n  1)",
        &[
            "Cannot convert 'bad' to int\n",
            "  (int('bad') +\n",
            "   ^~~~~~~~~~",
        ],
    );
}

// === Multiline success tests ===

#[test]
fn multiline_addition_works() {
    let r = ParsedExpression::new("1 +\n2")
        .and_then(|p| p.evaluate(&SymbolTable::new()))
        .unwrap();
    assert_eq!(r.to_display_string(), "3");
}

#[test]
fn multiline_comparison_works() {
    let r = ParsedExpression::new("1 <\n2")
        .and_then(|p| p.evaluate(&SymbolTable::new()))
        .unwrap();
    assert_eq!(r.to_display_string(), "true");
}

#[test]
fn multiline_three_lines_works() {
    let r = ParsedExpression::new("1 +\n2 +\n3")
        .and_then(|p| p.evaluate(&SymbolTable::new()))
        .unwrap();
    assert_eq!(r.to_display_string(), "6");
}

// ══════════════════════════════════════════════════════════════
// message_with_expr_prefix
// ══════════════════════════════════════════════════════════════

fn eval_err_obj(expr: &str) -> ExpressionError {
    ParsedExpression::new(expr)
        .and_then(|p| p.evaluate(&SymbolTable::new()))
        .unwrap_err()
}

fn eval_err_obj_with(expr: &str, st: &SymbolTable) -> ExpressionError {
    ParsedExpression::new(expr)
        .and_then(|p| p.evaluate(st))
        .unwrap_err()
}

#[test]
fn prefix_binop_type_error() {
    // Simulates: let x = Param.Frame + "oops"
    // The expression engine only sees: Param.Frame + "oops"
    let st = symtab! { "Param.Frame" => 42 };
    let err = eval_err_obj_with("Param.Frame + \"oops\"", &st);
    let prefixed = err.message_with_expr_prefix("x = ");

    // The prefix shifts the caret right by 4 ("x = ".len())
    assert!(
        prefixed.contains("x = Param.Frame + \"oops\""),
        "got:\n{prefixed}"
    );
    // The caret should point at the + operator, shifted by prefix
    // Without prefix: col 12 for the +
    // With prefix "x = ": col 16 for the +
    let lines: Vec<&str> = prefixed.lines().collect();
    let caret_line = lines.last().unwrap();
    let caret_pos = caret_line.find('^').unwrap();
    // "  " (2 indent) + "x = " (4 prefix) + "Param.Frame " (12) = 18
    assert_eq!(caret_pos, 18, "caret at wrong position in:\n{prefixed}");
}

#[test]
fn prefix_let_binding_style() {
    // Simulates: let result = 1 / 0
    let err = eval_err_obj("1 / 0");
    let prefixed = err.message_with_expr_prefix("result = ");
    assert!(prefixed.contains("result = 1 / 0"), "got:\n{prefixed}");
}

#[test]
fn prefix_single_caret() {
    // Error with a single-char span (just ^, no tildes)
    let err = eval_err_obj("xyz");
    let prefixed = err.message_with_expr_prefix("let v = ");
    assert!(prefixed.contains("let v = xyz"), "got:\n{prefixed}");
    let lines: Vec<&str> = prefixed.lines().collect();
    let caret_line = lines.last().unwrap();
    let caret_pos = caret_line.find('^').unwrap();
    // "  " (2) + "let v = " (8) + offset into "xyz"
    assert!(caret_pos >= 10, "caret at wrong position in:\n{prefixed}");
}

#[test]
fn prefix_no_context_falls_back() {
    // Error without expression context — prefix has no effect
    let err = ExpressionError::new("bare error");
    let prefixed = err.message_with_expr_prefix("ignored = ");
    assert_eq!(prefixed, "bare error");
}

#[test]
fn prefix_empty_string() {
    // Empty prefix — should produce same output as Display
    let err = eval_err_obj("1 + \"x\"");
    let normal = err.to_string();
    let prefixed = err.message_with_expr_prefix("");
    assert_eq!(prefixed, normal);
}

#[test]
fn prefix_preserves_tilde_span() {
    // The ~~~^~~~ pattern should be present and shifted
    let st = symtab! { "Param.X" => 42 };
    let err = eval_err_obj_with("Param.X + \"bad\"", &st);
    let prefixed = err.message_with_expr_prefix("val = ");
    // Should have tildes around the caret
    let lines: Vec<&str> = prefixed.lines().collect();
    let caret_line = lines.last().unwrap().trim();
    assert!(caret_line.contains('~'), "expected tildes in: {caret_line}");
    assert!(caret_line.contains('^'), "expected caret in: {caret_line}");
}

// ══════════════════════════════════════════════════════════════
// Tests ported from Python that were missing in Rust
// ══════════════════════════════════════════════════════════════

// --- TestErrorCaretPointers: operator_error_in_middle with symbol table ---

#[test]
fn operator_error_in_middle_with_symtab() {
    let st = symtab! { "Param.A" => 5, "Param.B" => "hello" };
    assert_err_with(
        "1 + (Param.A + Param.B) + 2",
        &st,
        &[
            "Cannot use '+' operator with int and string\n",
            "  1 + (Param.A + Param.B) + 2\n",
            "       ~~~~~~~~^~~~~~~~~",
        ],
    );
}

// --- TestErrorCaretPointers: index_out_of_bounds with symbol table ---

#[test]
fn index_out_of_bounds_with_symtab() {
    let mut st = SymbolTable::new();
    st.set(
        "Param.List",
        ExprValue::make_list(
            vec![ExprValue::Int(1), ExprValue::Int(2), ExprValue::Int(3)],
            ExprType::INT,
        )
        .unwrap(),
    )
    .unwrap();
    assert_err_with(
        "Param.List[10] + 1",
        &st,
        &[
            "Index 10 out of bounds for list of length 3\n",
            "  Param.List[10] + 1\n",
            "  ~~~~~~~~~~^~~~",
        ],
    );
}

// --- TestErrorCaretPointers: unknown_property_in_chain with path symbol table ---

#[test]
fn unknown_property_in_chain_with_path_symtab() {
    let mut st = SymbolTable::new();
    st.set(
        "Param.X",
        ExprValue::new_path("/test/file.exr", PathFormat::host()),
    )
    .unwrap();
    assert_err_with(
        "Param.X.name.unknown",
        &st,
        &[
            "Cannot access attribute 'unknown' on string\n",
            "  Param.X.name.unknown\n",
            "  ~~~~~~~~~~~~~^~~~~~~",
        ],
    );
}

// --- TestErrorCaretPointers: comprehension body matching Python expression ---

#[test]
fn error_in_comprehension_body_python() {
    assert_err(
        "[x + int('y') for x in [1,2,3]]",
        &[
            "Cannot convert 'y' to int\n",
            "  [x + int('y') for x in [1,2,3]]\n",
            "       ^~~~~~~~",
        ],
    );
}

// --- TestErrorCaretPointers: comprehension filter matching Python expression ---

#[test]
fn error_in_comprehension_filter_python() {
    assert_err(
        "[x for x in [1,2,3] if int('bad')]",
        &[
            "Cannot convert 'bad' to int\n",
            "  [x for x in [1,2,3] if int('bad')]\n",
            "                         ^~~~~~~~~~",
        ],
    );
}

// --- TestErrorCaretPointers: chained method error matching Python expression ---

#[test]
fn chained_method_error_python() {
    assert_err(
        "'a'.upper() + 'b'.split('')[0]",
        &[
            "split failed: empty separator\n",
            "  'a'.upper() + 'b'.split('')[0]\n",
            "                ~~~~^~~~~~~~~",
        ],
    );
}

// --- TestErrorCaretPointers: undefined dotted variable with suggestion ---

#[test]
fn undefined_dotted_variable_with_suggestion() {
    let mut st = SymbolTable::new();
    st.set(
        "Param.InputFile",
        ExprValue::new_path("/test/file.exr", PathFormat::Posix),
    )
    .unwrap();
    assert_err_with(
        "Param.InputFiel + 1",
        &st,
        &[
            "Undefined variable: 'Param.InputFiel'. Did you mean: Param.InputFile\n",
            "  Param.InputFiel + 1\n",
            "  ~~~~~~^~~~~~~~~",
        ],
    );
}

// --- TestMultiLineExpressions: type error variants matching Python ---

#[test]
fn multiline_type_error_in_parens() {
    assert_err(
        "(\n  1 + 'x'\n)",
        &[
            "Cannot use '+' operator with int and string\n",
            "    1 + 'x'\n",
            "    ~~~^~~~",
        ],
    );
}

#[test]
fn multiline_type_error_in_list() {
    assert_err(
        "[\n  1,\n  2 + 'x',\n  3\n]",
        &[
            "Cannot use '+' operator with int and string\n",
            "    2 + 'x',\n",
            "    ~~~^~~~",
        ],
    );
}

#[test]
fn multiline_type_error_on_first_line() {
    assert_err(
        "1 + 'x' + (\n2)",
        &[
            "Cannot use '+' operator with int and string\n",
            "  1 + 'x' + (\n",
            "  ~~~^~~~",
        ],
    );
}

#[test]
fn multiline_type_error_deeply_nested() {
    assert_err(
        "(\n  [\n    1 + 'x'\n  ]\n)",
        &[
            "Cannot use '+' operator with int and string\n",
            "      1 + 'x'\n",
            "      ~~~^~~~",
        ],
    );
}

// --- TestImplicitLineContinuation: bare multiline error ---

#[test]
fn bare_multiline_error_shows_correct_line() {
    assert_err(
        "1 +\n'x'",
        &[
            "Cannot use '+' operator with int and string\n",
            "  1 +\n",
            "  ~~^",
        ],
    );
}

// === Unified caret rendering across all three sites ===
// `Display for ExpressionError`, `message_with_expr_prefix`, and the
// if/else both-branches-fail renderer all share `write_caret_line`.
// These tests pin the exact output so a regression in any one of them
// shows up immediately.

#[test]
fn ifelse_both_branches_fail_exact_caret_format() {
    // Full multi-line assertion (AGENTS.md standard) — pins the exact
    // layout produced by the shared `write_caret_line` helper so a
    // regression in any of the three caret-rendering sites is caught
    // immediately.
    let mut st = SymbolTable::new();
    st.set("cond", ExprValue::unresolved(ExprType::BOOL))
        .unwrap();
    st.set("X", ExprValue::unresolved(ExprType::INT)).unwrap();
    st.set("Y", ExprValue::unresolved(ExprType::PATH)).unwrap();
    let e = eval_err_with("X + 'a' if cond else Y * 'b'", &st);
    let expected = "\
Both branches fail in the if/else:
  if-branch: Cannot use '+' operator with int and string
  X + 'a' if cond else Y * 'b'
  ~~^~~~~
  else-branch: Cannot use '*' operator with path and string
  X + 'a' if cond else Y * 'b'
                       ~~^~~~~
  X + 'a' if cond else Y * 'b'
  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~";
    assert_eq!(e, expected);
}

#[test]
fn format_string_parse_error_carries_caret() {
    // parse_segments now routes through with_span so the error includes
    // the raw format-string source and a caret over the failing {{...}}.
    let err = FormatString::new("hello {{ 1 + }} world").unwrap_err();
    let expected = "\
Failed to parse interpolation expression at [6, 15]. Reason: Syntax error: Expected an expression
  hello {{ 1 + }} world
        ^~~~~~~~~";
    assert_eq!(err.to_string(), expected);
}

#[test]
fn format_string_unclosed_interpolation_carries_caret() {
    let err = FormatString::new("prefix {{unclosed").unwrap_err();
    let expected = "\
Failed to parse interpolation expression at [7, 17]. Reason: Braces mismatch.
  prefix {{unclosed
         ^~";
    assert_eq!(err.to_string(), expected);
}

#[test]
fn range_expr_parse_error_carries_caret() {
    // A parse failure inside range_expr() surfaces with the outer call
    // expression as the source line and a caret spanning the whole call.
    // The range-internal position is captured in the message itself
    // ("Expected integer in '1-xx,5'"), and the outer caret tells the
    // user which expression node triggered the failure.
    let err = eval_err("range_expr('1-xx,5')");
    let expected = "\
Expected integer in '1-xx,5'
  range_expr('1-xx,5')
  ^~~~~~~~~~~~~~~~~~~~";
    assert_eq!(err, expected);
}

#[test]
fn range_expr_parse_error_has_parse_error_kind() {
    // Previously these all came through ExpressionError::new (Other kind),
    // losing programmatic classification. Now they carry ParseError kind.
    let err = ParsedExpression::new("range_expr('1-xx,5')")
        .and_then(|p| p.evaluate(&SymbolTable::new()))
        .unwrap_err();
    assert!(
        matches!(err.kind(), ExpressionErrorKind::ParseError(_)),
        "expected ParseError kind, got {:?}",
        err.kind()
    );
}

// === List comprehension filter must be boolean ===

#[test]
fn listcomp_filter_int_is_error() {
    assert_err(
        "[x for x in [1, 2, 3] if x]",
        &[
            "List comprehension filter must be a boolean, got int\n",
            "  [x for x in [1, 2, 3] if x]\n",
            "                           ^",
        ],
    );
}

#[test]
fn listcomp_filter_string_is_error() {
    assert_err(
        "[x for x in ['a', 'b', 'c'] if x]",
        &[
            "List comprehension filter must be a boolean, got string\n",
            "  [x for x in ['a', 'b', 'c'] if x]\n",
            "                                 ^",
        ],
    );
}

#[test]
fn listcomp_filter_float_is_error() {
    assert_err(
        "[x for x in [1.0, 2.0] if x]",
        &[
            "List comprehension filter must be a boolean, got float\n",
            "  [x for x in [1.0, 2.0] if x]\n",
            "                            ^",
        ],
    );
}

#[test]
fn listcomp_filter_bool_happy_path() {
    // [x for x in [1, 2, 3] if x > 1] should work fine
    let r = openjd_expr::ParsedExpression::new("[x for x in [1, 2, 3] if x > 1]")
        .and_then(|p| p.evaluate(&openjd_expr::SymbolTable::new()))
        .unwrap();
    assert_eq!(r.to_display_string(), "[2, 3]");
}

#[test]
fn listcomp_no_filter_happy_path() {
    let r = openjd_expr::ParsedExpression::new("[x for x in [1, 2, 3]]")
        .and_then(|p| p.evaluate(&openjd_expr::SymbolTable::new()))
        .unwrap();
    assert_eq!(r.to_display_string(), "[1, 2, 3]");
}

#[test]
fn ifelse_both_branches_fail_has_sub_errors() {
    let mut st = SymbolTable::new();
    st.set("cond", ExprValue::unresolved(ExprType::BOOL))
        .unwrap();
    st.set("X", ExprValue::unresolved(ExprType::INT)).unwrap();
    st.set("Y", ExprValue::unresolved(ExprType::PATH)).unwrap();
    let err = ParsedExpression::new("X + 'a' if cond else Y * 'b'")
        .and_then(|p| p.evaluate(&st))
        .unwrap_err();
    assert_eq!(err.sub_errors().len(), 2);
    // if-branch error
    let if_err = &err.sub_errors()[0];
    assert_eq!(
        if_err.message(),
        "Cannot use '+' operator with int and string"
    );
    assert!(if_err.col_offset().is_some());
    assert!(if_err.end_col_offset().is_some());
    // else-branch error
    let else_err = &err.sub_errors()[1];
    assert_eq!(
        else_err.message(),
        "Cannot use '*' operator with path and string"
    );
    assert!(else_err.col_offset().is_some());
    assert!(else_err.end_col_offset().is_some());
}

#[test]
fn format_string_validation_carries_expression_error_with_sub_errors() {
    let mut st = SymbolTable::new();
    st.set("cond", ExprValue::unresolved(ExprType::BOOL))
        .unwrap();
    st.set("X", ExprValue::unresolved(ExprType::INT)).unwrap();
    st.set("Y", ExprValue::unresolved(ExprType::PATH)).unwrap();
    let fs = FormatString::new("{{X + 'a' if cond else Y * 'b'}}").unwrap();
    let lib = FunctionLibrary::default();
    let err = fs.validate_expressions(&st, &lib).unwrap_err();
    assert_eq!(err.start, 0);
    assert_eq!(err.end, 32);
    let expr_err = err
        .expression_error
        .as_ref()
        .expect("expression_error should be Some");
    assert_eq!(expr_err.sub_errors().len(), 2);
    // Sub-error messages may differ from direct evaluation due to
    // unresolved type handling in format string validation
    assert!(!expr_err.sub_errors()[0].message().is_empty());
    assert!(!expr_err.sub_errors()[1].message().is_empty());
    // Each sub-error has span info
    assert!(expr_err.sub_errors()[0].col_offset().is_some());
    assert!(expr_err.sub_errors()[1].col_offset().is_some());
}

#[test]
fn simple_error_has_no_sub_errors() {
    let st = SymbolTable::new();
    let err = ParsedExpression::new("Param.Undefined")
        .and_then(|p| p.evaluate(&st))
        .unwrap_err();
    assert!(err.sub_errors().is_empty());
}