tabnas-expr 0.6.2

Pratt expression-operator plugin for the tabnas parsing engine, over the jsonic base grammar
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
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
// In-language behaviour: what a shared fixture cannot express.
//
// The Pratt core is exercised directly here, as the TypeScript
// `testing.prattify` cases and the Go `TestPrattifyBasic` /
// `TestPrattifyAssoc` do, along with the parse-level behaviours the `.tsv`
// files do not reach: comma-op suppression, the evaluator, the operator
// table's instance token binding, and the serialized shape of a parsed
// expression.

mod common;

use std::collections::HashMap;

use serde_json::json;
use tabnas::{Context, LexCheckResult, Rule, Tabnas, Value};
use tabnas_expr::{
    is_op, opify, prattify, simplify, ContentDef, EvalSite, ExprOptions, Op, OpDef, OpRef,
    PrevalDef, NODE_LIMIT,
};

use common::{norm, parse_simplified, parser_for, parser_with};

/// An operator built by hand, as the Go suite's `moT` does: the name comes
/// from the source when it is not given, and the term count is derived.
fn mo(mut spec: Op) -> OpRef {
    if spec.name.is_empty() {
        spec.name = spec.src.clone();
    }
    OpRef::new(opify(spec))
}

fn infix(src: &str, left: i64, right: i64) -> OpRef {
    mo(Op {
        infix: true,
        src: src.into(),
        left,
        right,
        ..Default::default()
    })
}

fn prefix(src: &str, right: i64) -> OpRef {
    mo(Op {
        prefix: true,
        src: src.into(),
        right,
        ..Default::default()
    })
}

fn suffix(src: &str, left: i64) -> OpRef {
    mo(Op {
        suffix: true,
        src: src.into(),
        left,
        ..Default::default()
    })
}

/// An expression node, the canonical `makeExpr`.
fn expr(op: &OpRef, terms: &[f64]) -> Value {
    op.node(terms.iter().map(|term| Value::Number(*term)).collect())
}

/// An expression node whose terms are already built.
fn nest(op: &OpRef, terms: Vec<Value>) -> Value {
    op.node(terms)
}

/// Compare a node's S-expression against a JSON literal, mirroring the
/// TypeScript tests' `C(S(x))` comparisons.
fn check(label: &str, node: &Value, want: &str) {
    let got = norm(simplify(node).to_json());
    let want: serde_json::Value = serde_json::from_str(want).expect("the expectation is JSON");
    assert_eq!(got, norm(want), "{label}");
}

/// Parse and compare the S-expression, mirroring the Go `parseSx`.
fn check_parse(parser: &Tabnas, src: &str, want: &str) {
    let got =
        parse_simplified(parser, src).unwrap_or_else(|error| panic!("parse {src:?}: {error}"));
    let want: serde_json::Value = serde_json::from_str(want).expect("the expectation is JSON");
    assert_eq!(norm(got), norm(want), "parse {src:?}");
}

// --- the Pratt core --------------------------------------------------------

/// The canonical `prattify-basic` cases: each one checks the returned
/// attachment point and the rewritten expression tree.
#[test]
fn prattify_basic() {
    let plus_la = infix("+", 140, 150);
    let plus_ra = infix("+", 150, 140);
    let mul_la = infix("*", 160, 170);
    let pipe_la = infix("|", 18000, 17000);
    let at_p = prefix("@", 1500);
    let per_p = prefix("%", 1300);
    let bang_s = suffix("!", 1600);
    let quest_s = suffix("?", 1400);

    // 1+2+N is (1+2)+N
    let tree = expr(&plus_la, &[1.0, 2.0]);
    check("1+2+N T", &prattify(&tree, &plus_la), r#"["+",["+",1,2]]"#);
    check("1+2+N E", &tree, r#"["+",["+",1,2]]"#);

    // 1+2+N is 1+(2+N) when the operator is right-associative
    let tree = expr(&plus_ra, &[1.0, 2.0]);
    check("1+2+N ra T", &prattify(&tree, &plus_ra), r#"["+",2]"#);
    check("1+2+N ra E", &tree, r#"["+",1,["+",2]]"#);

    // 1+2*N is 1+(2*N)
    let tree = expr(&plus_la, &[1.0, 2.0]);
    check("1+2*N T", &prattify(&tree, &mul_la), r#"["*",2]"#);
    check("1+2*N E", &tree, r#"["+",1,["*",2]]"#);

    // 1*2+N is (1*2)+N
    let tree = expr(&mul_la, &[1.0, 2.0]);
    check("1*2+N T", &prattify(&tree, &plus_la), r#"["+",["*",1,2]]"#);
    check("1*2+N E", &tree, r#"["+",["*",1,2]]"#);

    // @1+N is (@1)+N
    let tree = expr(&at_p, &[1.0]);
    check("@1+N T", &prattify(&tree, &plus_la), r#"["+",["@",1]]"#);
    check("@1+N E", &tree, r#"["+",["@",1]]"#);

    // 1!+N is (1!)+N
    let tree = expr(&bang_s, &[1.0]);
    check("1!+N T", &prattify(&tree, &plus_la), r#"["+",["!",1]]"#);
    check("1!+N E", &tree, r#"["+",["!",1]]"#);

    // @1|N is @(1|N)
    let tree = expr(&at_p, &[1.0]);
    check("@1|N T", &prattify(&tree, &pipe_la), r#"["|",1]"#);
    check("@1|N E", &tree, r#"["@",["|",1]]"#);

    // 1|@N is 1|(@N)
    let tree = expr(&pipe_la, &[1.0]);
    check("1|@N T", &prattify(&tree, &at_p), r#"["@"]"#);
    check("1|@N E", &tree, r#"["|",1,["@"]]"#);

    // 1!|N is (1!)|N
    let tree = expr(&bang_s, &[1.0]);
    check("1!|N T", &prattify(&tree, &pipe_la), r#"["|",["!",1]]"#);
    check("1!|N E", &tree, r#"["|",["!",1]]"#);

    // 1+@N is 1+(@N)
    let tree = expr(&plus_la, &[1.0]);
    check("1+@N T", &prattify(&tree, &at_p), r#"["@"]"#);
    check("1+@N E", &tree, r#"["+",1,["@"]]"#);

    // @@N is @(@N)
    let tree = expr(&at_p, &[]);
    check("@@N T", &prattify(&tree, &at_p), r#"["@"]"#);
    check("@@N E", &tree, r#"["@",["@"]]"#);

    // %@N is %(@N)
    let tree = expr(&per_p, &[]);
    check("%@N T", &prattify(&tree, &at_p), r#"["@"]"#);
    check("%@N E", &tree, r#"["%",["@"]]"#);

    // @%N is @(%N)
    let tree = expr(&at_p, &[]);
    check("@%N T", &prattify(&tree, &per_p), r#"["%"]"#);
    check("@%N E", &tree, r#"["@",["%"]]"#);

    // 1+2! is 1+(2!)
    let tree = expr(&plus_la, &[1.0, 2.0]);
    check("1+2! T", &prattify(&tree, &bang_s), r#"["+",1,["!",2]]"#);
    check("1+2! E", &tree, r#"["+",1,["!",2]]"#);

    // 1|2! is (1|2)!
    let tree = expr(&pipe_la, &[1.0, 2.0]);
    check("1|2! T", &prattify(&tree, &bang_s), r#"["!",["|",1,2]]"#);
    check("1|2! E", &tree, r#"["!",["|",1,2]]"#);

    // 1!! is (1!)!
    let tree = expr(&bang_s, &[1.0]);
    check("1!! T", &prattify(&tree, &bang_s), r#"["!",["!",1]]"#);
    check("1!! E", &tree, r#"["!",["!",1]]"#);

    // 1!? is (1!)?
    let tree = expr(&bang_s, &[1.0]);
    check("1!? T", &prattify(&tree, &quest_s), r#"["?",["!",1]]"#);
    check("1!? E", &tree, r#"["?",["!",1]]"#);

    // 1?! is (1?)!
    let tree = expr(&quest_s, &[1.0]);
    check("1?! T", &prattify(&tree, &bang_s), r#"["!",["?",1]]"#);
    check("1?! E", &tree, r#"["!",["?",1]]"#);

    // @1! is @(1!)
    let tree = expr(&at_p, &[1.0]);
    check("@1! T", &prattify(&tree, &bang_s), r#"["@",["!",1]]"#);
    check("@1! E", &tree, r#"["@",["!",1]]"#);

    // @1? is (@1)?
    let tree = expr(&at_p, &[1.0]);
    check("@1? T", &prattify(&tree, &quest_s), r#"["?",["@",1]]"#);
    check("@1? E", &tree, r#"["?",["@",1]]"#);

    // @@1! is @(@(1!))
    let tree = nest(&at_p, vec![expr(&at_p, &[1.0])]);
    check(
        "@@1! T",
        &prattify(&tree, &bang_s),
        r#"["@",["@",["!",1]]]"#,
    );
    check("@@1! E", &tree, r#"["@",["@",["!",1]]]"#);

    // @@1? is (@(@1))?
    let tree = nest(&at_p, vec![expr(&at_p, &[1.0])]);
    check(
        "@@1? T",
        &prattify(&tree, &quest_s),
        r#"["?",["@",["@",1]]]"#,
    );
    check("@@1? E", &tree, r#"["?",["@",["@",1]]]"#);
}

/// The canonical `prattify-assoc` cases: left- and right-associative
/// infix chains.
#[test]
fn prattify_assoc() {
    let at_la = infix("@", 14, 15);
    let per_ra = infix("%", 17, 16);

    let tree = expr(&at_la, &[1.0, 2.0]);
    check("1@2@N T", &prattify(&tree, &at_la), r#"["@",["@",1,2]]"#);
    check("1@2@N E", &tree, r#"["@",["@",1,2]]"#);

    let tree = nest(&at_la, vec![expr(&at_la, &[1.0, 2.0]), Value::Number(3.0)]);
    check(
        "1@2@3@N T",
        &prattify(&tree, &at_la),
        r#"["@",["@",["@",1,2],3]]"#,
    );
    check("1@2@3@N E", &tree, r#"["@",["@",["@",1,2],3]]"#);

    let tree = nest(
        &at_la,
        vec![
            nest(&at_la, vec![expr(&at_la, &[1.0, 2.0]), Value::Number(3.0)]),
            Value::Number(4.0),
        ],
    );
    check(
        "1@2@3@4@N T",
        &prattify(&tree, &at_la),
        r#"["@",["@",["@",["@",1,2],3],4]]"#,
    );
    check("1@2@3@4@N E", &tree, r#"["@",["@",["@",["@",1,2],3],4]]"#);

    let tree = nest(
        &at_la,
        vec![
            nest(
                &at_la,
                vec![
                    nest(&at_la, vec![expr(&at_la, &[1.0, 2.0]), Value::Number(3.0)]),
                    Value::Number(4.0),
                ],
            ),
            Value::Number(5.0),
        ],
    );
    check(
        "1@2@3@4@5@N T",
        &prattify(&tree, &at_la),
        r#"["@",["@",["@",["@",["@",1,2],3],4],5]]"#,
    );
    check(
        "1@2@3@4@5@N E",
        &tree,
        r#"["@",["@",["@",["@",["@",1,2],3],4],5]]"#,
    );

    let tree = expr(&per_ra, &[1.0, 2.0]);
    check("1%2%N T", &prattify(&tree, &per_ra), r#"["%",2]"#);
    check("1%2%N E", &tree, r#"["%",1,["%",2]]"#);

    let tree = nest(
        &per_ra,
        vec![Value::Number(1.0), expr(&per_ra, &[2.0, 3.0])],
    );
    check("1%2%3%N T", &prattify(&tree, &per_ra), r#"["%",3]"#);
    check("1%2%3%N E", &tree, r#"["%",1,["%",2,["%",3]]]"#);

    let tree = nest(
        &per_ra,
        vec![
            Value::Number(1.0),
            nest(
                &per_ra,
                vec![Value::Number(2.0), expr(&per_ra, &[3.0, 4.0])],
            ),
        ],
    );
    check("1%2%3%4%N T", &prattify(&tree, &per_ra), r#"["%",4]"#);
    check("1%2%3%4%N E", &tree, r#"["%",1,["%",2,["%",3,["%",4]]]]"#);

    let tree = nest(
        &per_ra,
        vec![
            Value::Number(1.0),
            nest(
                &per_ra,
                vec![
                    Value::Number(2.0),
                    nest(
                        &per_ra,
                        vec![Value::Number(3.0), expr(&per_ra, &[4.0, 5.0])],
                    ),
                ],
            ),
        ],
    );
    check("1%2%3%4%5%N T", &prattify(&tree, &per_ra), r#"["%",5]"#);
    check(
        "1%2%3%4%5%N E",
        &tree,
        r#"["%",1,["%",2,["%",3,["%",4,["%",5]]]]]"#,
    );
}

// --- comma-op suppression --------------------------------------------------

/// With `,` defined as an infix operator it is absorbed as the comma
/// operator everywhere; a host rule setting `n.no_comma_op` suppresses it,
/// so the bail alternates leave `,` for the enclosing rule to consume as a
/// separator.
#[test]
fn no_comma_op_suppression() {
    let comma_op = || {
        json!({
            "op": {
                "comma_op": { "infix": true, "src": ",", "left": 1000000, "right": 1100000 },
            }
        })
    };

    // Baseline: with the comma operator defined, `,` is absorbed
    // everywhere, including inside list and paren contexts where it would
    // otherwise have been a separator.
    let base = parser_for(comma_op());
    check_parse(&base, "1,2", r#"[",",1,2]"#);
    check_parse(&base, "[1,2]", r#"[[",",1,2]]"#);
    check_parse(&base, "(1,2)", r#"["(",[",",1,2]]"#);

    // Suppression: hook the base grammar's list rule so any expression
    // parsed inside `[...]` sees n.no_comma_op set. This mirrors how a
    // host grammar uses the counter around boundary expressions to keep
    // `,` out of the comma operator's reach.
    let mut parser = parser_for(comma_op());
    parser.define_rule("list", |spec| {
        spec.add_bo(|rule: &mut Rule, _context: &mut Context| {
            let depth = rule.n.get("no_comma_op").copied().unwrap_or(0);
            rule.n_mut().insert("no_comma_op".into(), depth + 1);
        });
    });

    // Inside `[...]`, `,` is a separator again, not the comma operator.
    check_parse(&parser, "[1,2]", "[1,2]");
    check_parse(&parser, "[1,2,3]", "[1,2,3]");
    // Other operators inside the list still work.
    check_parse(&parser, "[1+2,3+4]", r#"[["+",1,2],["+",3,4]]"#);
    // Outside the list the comma operator still applies: n.no_comma_op is
    // scoped to the list rule and the val and expr rules under it.
    check_parse(&parser, "1,2", r#"[",",1,2]"#);
}

// --- the evaluator ---------------------------------------------------------

fn number(value: Option<&Value>) -> f64 {
    match value {
        Some(Value::Number(number)) => *number,
        _ => 0.0,
    }
}

/// The ternary rule's after-close fires the evaluator even for a ternary
/// that is not wrapped in an expr rule. Without it the result would leak
/// as a raw S-expression.
#[test]
fn ternary_evaluate() {
    let parser = parser_with(
        ExprOptions::new()
            .with_op("q", OpDef::ternary("?", ":"))
            .with_evaluate(|_site, op, terms| {
                if "q-ternary" == op.name {
                    return if 0.0 != number(terms.first()) {
                        terms.get(1).cloned().unwrap_or(Value::Undefined)
                    } else {
                        terms.get(2).cloned().unwrap_or(Value::Undefined)
                    };
                }
                Value::Number(f64::NAN)
            }),
    );

    for (src, want) in [
        // A direct ternary at the top level evaluates through the
        // after-close.
        ("1?2:3", 2.0),
        ("0?2:3", 3.0),
        // Right-associative chains evaluate fully.
        ("1?2: 0?4:5", 2.0),
        ("0?2: 1?4:5", 4.0),
        ("0?2: 0?4:5", 5.0),
    ] {
        let got = tabnas_expr::parse_with(&parser, src)
            .unwrap_or_else(|error| panic!("parse {src:?}: {error}"));
        assert_eq!(got, Value::Number(want), "parse {src:?}");
    }
}

/// A small evaluated expression language: preval function parens with
/// custom delimiters and with overloaded `(...)`, plain parens, implicit
/// lists and map and list embedding, all through the evaluator.
#[test]
fn mini_config() {
    fn reduce(site: &EvalSite<'_>, name: &str, terms: &[Value]) -> Value {
        let mut terms = terms.to_vec();
        if "func-paren" == name && !site.flag("paren_preval") {
            terms.insert(0, Value::String(String::new()));
        }
        match name {
            "addition-infix" => Value::Number(number(terms.first()) + number(terms.get(1))),
            "subtraction-infix" => Value::Number(number(terms.first()) - number(terms.get(1))),
            "plain-paren" => terms.first().cloned().unwrap_or(Value::Null),
            "func-paren" => {
                let Some(Value::String(function)) = terms.first().cloned() else {
                    return terms.get(1).cloned().unwrap_or(Value::Null);
                };
                if function.is_empty() {
                    return terms.get(1).cloned().unwrap_or(Value::Null);
                }
                if "floor" != function {
                    return Value::Null;
                }
                match terms.get(1) {
                    Some(Value::Number(value)) => Value::Number(value.floor()),
                    _ => Value::Null,
                }
            }
            _ => Value::Null,
        }
    }

    let angle = parser_with(
        ExprOptions::new()
            .with_op(
                "func",
                OpDef::paren("<", ">").with_preval(PrevalDef {
                    active: true,
                    required: false,
                    allow: None,
                }),
            )
            .with_evaluate(|site, op, terms| reduce(site, &op.name, terms)),
    );

    for (src, want) in [
        ("11+22", "33"),
        ("44-33", "11"),
        ("(44-33)+11", "22"),
        ("44-(33+11)", "0"),
        ("44-33+11", "22"),
        ("(1.1)", "1.1"),
        ("[0,(1)]", "[0,1]"),
        ("[0 (1)]", "[0,1]"),
        ("floor<1.5>", "1"),
        ("a:floor<2.5>", r#"{"a":2}"#),
        ("{b:floor<3.5>}", r#"{"b":3}"#),
        ("[floor<4.5>]", "[4]"),
        ("[0 floor<5.5>]", "[0,5]"),
        ("1+floor<1.5>", "2"),
        ("1+floor<1.5>+3", "5"),
        ("floor<1.5>+4", "5"),
        ("a:floor<1.5>+4", r#"{"a":5}"#),
        ("a:(1+2) b:floor<1.9>", r#"{"a":3,"b":1}"#),
        ("()", "null"),
        ("<>", "null"),
        ("<1>", "1"),
        ("c:<2>", r#"{"c":2}"#),
        ("a:floor<>", r#"{"a":null}"#),
        ("floor<>", "null"),
        ("[floor<>]", "[null]"),
        (r#"floor<"a">"#, "null"),
        (r#"a:floor<"a">"#, r#"{"a":null}"#),
        ("[1 (2) (2+1) floor<4.5>]", "[1,2,3,4]"),
        ("1 (2) (2+1) floor<4.5>", "[1,2,3,4]"),
        ("bad<9>", "null"),
    ] {
        check_parse(&angle, src, want);
    }

    let round = parser_with(
        ExprOptions::new()
            .without_op("plain")
            .with_op(
                "func",
                OpDef::paren("(", ")").with_preval(PrevalDef {
                    active: true,
                    required: false,
                    allow: Some(vec!["floor".into()]),
                }),
            )
            .with_evaluate(|site, op, terms| reduce(site, &op.name, terms)),
    );

    for (src, want) in [
        ("()", "null"),
        ("(0)", "0"),
        ("(0+1)", "1"),
        ("[(0) 1]", "[0,1]"),
        ("[0,(1),2]", "[0,1,2]"),
        ("[0,(1)]", "[0,1]"),
        ("[(1)]", "[1]"),
        ("[(0),(1)]", "[0,1]"),
        ("(0),(1)", "[0,1]"),
        ("floor(1.1)", "1"),
        ("floor (1.1)", "1"),
        ("floor(0.5)", "0"),
        ("a:floor(2.5)", r#"{"a":2}"#),
        ("{b:floor(3.5)}", r#"{"b":3}"#),
        ("[floor(4.5)]", "[4]"),
        ("[0 floor(5.5)]", "[0,5]"),
        ("[(0) 1 floor(5.5)]", "[0,1,5]"),
        ("[(0) floor(5.5)]", "[0,5]"),
        ("[0,(1),floor(5.5)]", "[0,1,5]"),
        ("[1,(2),(2+1)]", "[1,2,3]"),
        ("[1,(2),(2+1),floor(4.5)]", "[1,2,3,4]"),
        ("a:floor(1.5)", r#"{"a":1}"#),
        ("[3+2]", "[5]"),
        ("[3+(2)]", "[5]"),
        ("[(3)+2]", "[5]"),
        ("[(3)+(2)]", "[5]"),
        ("[(3+2)]", "[5]"),
        ("[(3+(2))]", "[5]"),
        ("[((3)+2)]", "[5]"),
        ("[((3)+(2))]", "[5]"),
        ("[1,3+2]", "[1,5]"),
        ("[1,(3+(2))]", "[1,5]"),
        ("[3+2,4]", "[5,4]"),
        ("[((3)+(2)),4]", "[5,4]"),
        ("[1,3+2,4]", "[1,5,4]"),
        ("[1,((3)+(2)),4]", "[1,5,4]"),
        ("1+floor(1.1)", "2"),
        ("floor(1.1)+1", "2"),
        ("1+floor(1.1)+1", "3"),
        ("a:(2)+1", r#"{"a":3}"#),
        ("a:1+floor(1.1)", r#"{"a":2}"#),
        ("a:(1.1)+1", r#"{"a":2.1}"#),
        ("a:floor(1.1)+1", r#"{"a":2}"#),
        ("a:1+floor(1.1)+1", r#"{"a":3}"#),
        ("[1+floor(1.1)]", "[2]"),
        ("[floor(1.1)+2]", "[3]"),
        ("[3+floor(1.1)+2]", "[6]"),
        ("b:1.1+1,c:C0", r#"{"b":2.1,"c":"C0"}"#),
        ("b:(1.1+1),c:C0a", r#"{"b":2.1,"c":"C0a"}"#),
        ("b:(1.1)+1,c:C1", r#"{"b":2.1,"c":"C1"}"#),
        ("b:((1.1)+1),c:C1a", r#"{"b":2.1,"c":"C1a"}"#),
        ("b:1+floor(1.1),c:C2c", r#"{"b":2,"c":"C2c"}"#),
        ("b:floor(1.1)+1,c:C2d", r#"{"b":2,"c":"C2d"}"#),
        ("b:(floor(1.1)),c:C2a", r#"{"b":1,"c":"C2a"}"#),
        ("b:(1+floor(1.1)),c:C2b", r#"{"b":2,"c":"C2b"}"#),
        ("1+(floor(1.1))", "2"),
        ("(11,22)", "[11,22]"),
        ("21+31", "52"),
        ("(21)+31", "52"),
        ("(21+31)", "52"),
        ("(floor(2.2))", "2"),
        ("((floor(2.2)))", "2"),
        ("(floor(2.2))+1", "3"),
        ("floor(2.2)+3", "5"),
        ("(floor(1.1)+2)", "3"),
        ("b:(floor(1.1)+2),c:C2c", r#"{"b":3,"c":"C2c"}"#),
    ] {
        check_parse(&round, src, want);
    }
}

/// The evaluator is free to return another S-expression and to have
/// effects, so a member of an implicit list must not be reduced twice: it
/// is reduced when it closes and the list is reduced again as a whole.
#[test]
fn evaluate_called_once_per_operator() {
    for src in [
        "f(1+2,3+4,5+6)",
        "f(1+2,3+4)",
        "1+2,3+4,5+6",
        "f(1+2,3)",
        "f(-1+2,3+4)",
        "f(g(1+2,3+4),5+6)",
        "f(1+2,(3+4,5+6))",
        "(1+2,3+4)",
        "[f(1+2,3+4)]",
        "{k:f(1+2,3+4)}",
        "f(1+2,3+4),f(5+6,7+8)",
    ] {
        let counts: std::sync::Arc<std::sync::Mutex<HashMap<String, usize>>> =
            std::sync::Arc::new(std::sync::Mutex::new(HashMap::new()));
        let seen = counts.clone();
        let parser = parser_with(
            ExprOptions::new()
                .with_op(
                    "func",
                    OpDef::paren("(", ")").with_preval(PrevalDef {
                        active: true,
                        required: false,
                        allow: None,
                    }),
                )
                .with_evaluate(move |_site, op, terms| {
                    let key = format!(
                        "{}{}",
                        op.name,
                        simplify(&Value::array(terms.to_vec())).to_json()
                    );
                    *seen.lock().unwrap().entry(key).or_insert(0) += 1;
                    let mut out = vec![];
                    out.extend(terms.iter().cloned());
                    OpRef {
                        op: std::sync::Arc::new(op.clone()),
                        token: None,
                    }
                    .node(out)
                }),
        );

        tabnas_expr::parse_with(&parser, src).unwrap_or_else(|error| panic!("{src}: {error}"));

        for (key, count) in counts.lock().unwrap().iter() {
            assert_eq!(
                1, *count,
                "{src}: the evaluator ran {count} times for {key}"
            );
        }
    }
}

/// The default group, `plain`, gives way to a paren operator of the table
/// on the same opener and closer, so a lone call whose preval is active and
/// not required serves both forms, as it always has. The Rust half of the
/// TypeScript suite's `paren-default-plain-yields`.
#[test]
fn paren_default_plain_yields() {
    let named = |options: ExprOptions| {
        parser_with(options.with_evaluate(|_site, op, terms| {
            let mut items = vec![Value::String(op.name.clone())];
            items.extend(terms.iter().cloned());
            Value::array(items)
        }))
    };
    let paren = |active: bool, required: bool| {
        OpDef::paren("(", ")").with_preval(PrevalDef {
            active,
            required,
            allow: None,
        })
    };
    let check = |parser: &Tabnas, src: &str, want: &str| {
        let value =
            tabnas_expr::parse_with(parser, src).unwrap_or_else(|error| panic!("{src}: {error}"));
        assert_eq!(
            norm(value.to_json()),
            norm(serde_json::from_str(want).unwrap()),
            "{src}"
        );
    };

    let func = named(ExprOptions::new().with_op("func", paren(true, false)));
    check(&func, "(1)", r#"["func-paren",1]"#);
    check(&func, "f(1)", r#"["func-paren","f",1]"#);

    // A paren operator on another opener leaves it in place.
    let angle = named(ExprOptions::new().with_op("angle", OpDef::paren("<", ">")));
    check(&angle, "(1)", r#"["plain-paren",1]"#);

    // A `plain` the options change is theirs, and stays: here it is the
    // group beside the call.
    let both = named(
        ExprOptions::new()
            .with_op("plain", paren(false, false))
            .with_op("func", paren(true, false)),
    );
    check(&both, "(1)", r#"["plain-paren",1]"#);
    check(&both, "f(1)", r#"["func-paren","f",1]"#);

    // A call whose preval is required serves only its own form.
    let index = named(ExprOptions::new().with_op("index", paren(true, true)));
    check(&index, "f(1)", r#"["index-paren","f",1]"#);
    assert!(
        tabnas_expr::parse_with(&index, "(1)").is_err(),
        "(1) with only a required-preval paren on ( should fail"
    );
}

/// Each operation of the tree is reduced once, after its terms, so the
/// calls follow the S-expression. A prefix inside an operand (`-2` in
/// `1+-2`) is not reduced with the enclosing tree before that tree is
/// complete, and a suffix that drills into a prefix (`-1!`, which is
/// `-(1!)`) is reduced before the prefix, not after it. The Rust half of
/// the TypeScript suite's `evaluate-once-in-tree-order`.
///
/// (See also `options_repeat_by_replacement` and `options_cast_shape`
/// below, the halves of the TypeScript suite's tests of the same names.)
#[test]
fn evaluate_once_in_tree_order() {
    let calls: std::sync::Arc<std::sync::Mutex<Vec<String>>> =
        std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let seen = calls.clone();
    let parser = parser_with(
        ExprOptions::new()
            .with_op("factorial", OpDef::suffix("!", 6000000))
            .with_op("question", OpDef::suffix("?", 3500000))
            .with_evaluate(move |_site, op, terms| {
                let parts: Vec<String> = terms
                    .iter()
                    .map(|term| match term {
                        Value::String(text) => text.clone(),
                        other => other.to_string(),
                    })
                    .collect();
                let name = op.name.split('-').next().unwrap_or_default();
                let out = format!("{name}({})", parts.join(","));
                seen.lock().unwrap().push(out.clone());
                Value::String(out)
            }),
    );

    for (src, want) in [
        ("1+-2", vec!["negative(2)", "addition(1,negative(2))"]),
        ("--1", vec!["negative(1)", "negative(negative(1))"]),
        ("-1!", vec!["factorial(1)", "negative(factorial(1))"]),
        (
            "--1!",
            vec![
                "factorial(1)",
                "negative(factorial(1))",
                "negative(negative(factorial(1)))",
            ],
        ),
        (
            "1+-2!",
            vec![
                "factorial(2)",
                "negative(factorial(2))",
                "addition(1,negative(factorial(2)))",
            ],
        ),
        ("-1?", vec!["negative(1)", "question(negative(1))"]),
        (
            "-(1)!",
            vec![
                "plain(1)",
                "factorial(plain(1))",
                "negative(factorial(plain(1)))",
            ],
        ),
        ("[1+-2,3]", vec!["negative(2)", "addition(1,negative(2))"]),
        ("x:-1!", vec!["factorial(1)", "negative(factorial(1))"]),
    ] {
        calls.lock().unwrap().clear();
        tabnas_expr::parse_with(&parser, src).unwrap_or_else(|error| panic!("{src}: {error}"));
        assert_eq!(*calls.lock().unwrap(), want, "{src}: the evaluator's calls");
    }
}

/// Reducing a finished tree outside a parse, the exported entry point.
#[test]
fn evaluation_reduces_a_finished_tree() {
    let parser = parser_for(json!({}));
    let math: tabnas_expr::Evaluate =
        std::sync::Arc::new(|_site: &mut EvalSite<'_>, op: &Op, terms: &[Value]| {
            let left = number(terms.first());
            let right = number(terms.get(1));
            match op.name.as_str() {
                "addition-infix" => Value::Number(left + right),
                "subtraction-infix" => Value::Number(left - right),
                "multiplication-infix" => Value::Number(left * right),
                "negative-prefix" => Value::Number(-left),
                "positive-prefix" => Value::Number(left),
                "plain-paren" => terms.first().cloned().unwrap_or(Value::Null),
                _ => Value::Null,
            }
        });

    for (src, want) in [
        ("1+2", 3.0),
        ("1+2+3", 6.0),
        ("1*2+3", 5.0),
        ("1+2*3", 7.0),
        ("(1+2)*3", 9.0),
        ("3*(1+2)", 9.0),
        ("(1)", 1.0),
        ("(1+2)", 3.0),
        ("3+(1+2)", 6.0),
        ("(1+2)+3", 6.0),
        ("111+222", 333.0),
        ("((1+2)*4)", 12.0),
        ("(1+(2*4))", 9.0),
        ("((114))", 114.0),
        ("(((115)))", 115.0),
        ("1-3", -2.0),
        ("-1", -1.0),
        ("+1", 1.0),
        ("1+(-3)", -2.0),
    ] {
        // The tree has to be reduced inside the parse's arena lifetime,
        // which `parse_scope` holds open.
        let got = tabnas_expr::parse_scope(&parser, src, |value| {
            tabnas_expr::evaluation(&mut EvalSite::detached(), &value, &math)
        })
        .unwrap_or_else(|error| panic!("parse {src:?}: {error}"));
        assert_eq!(got, Value::Number(want), "evaluate {src:?}");
    }
}

/// The evaluator is told which OCCURRENCE of an operator it is reducing.
///
/// The `Op` it receives is the shared description, one per entry in the
/// operator table, so it is the same value for every `+` in a document.
/// The canonical `makeOp` copies the description and attaches the token
/// for exactly that reason; this port keeps the token beside the node and
/// hands it over on the site. Without it an evaluator could not report the
/// row and column of the operator it is reducing.
#[test]
fn the_evaluator_is_given_the_occurrence_token() {
    let parser = parser_for(json!({}));
    let seen: std::sync::Arc<std::sync::Mutex<Vec<String>>> = Default::default();
    let record = seen.clone();
    let note: tabnas_expr::Evaluate =
        std::sync::Arc::new(move |site: &mut EvalSite<'_>, op: &Op, terms: &[Value]| {
            let token = site.token().expect("an occurrence carries its token");
            record.lock().expect("not poisoned").push(format!(
                "{} {} {} {} {}",
                op.name, token.src, token.site.pos, token.site.ri, token.site.ci
            ));
            terms.first().cloned().unwrap_or(Value::Null)
        });

    tabnas_expr::parse_scope(&parser, "1+2*3", |value| {
        tabnas_expr::evaluation(&mut EvalSite::detached(), &value, &note)
    })
    .expect("parses");

    // Innermost first, and each one carries its own token: the `*` at
    // column 4 and the `+` at column 2, the positions the canonical
    // attaches to its copy of the description.
    assert_eq!(
        *seen.lock().expect("not poisoned"),
        vec![
            "multiplication-infix * 3 1 4".to_string(),
            "addition-infix + 1 1 2".to_string(),
        ]
    );
}

/// A tree built without a parse behind it has no token to report, and
/// says so rather than inventing one.
#[test]
fn a_handmade_node_has_no_occurrence_token() {
    let add = infix("+", 2000000, 2100000);
    let node = expr(&add, &[1.0, 2.0]);
    let asked: tabnas_expr::Evaluate =
        std::sync::Arc::new(|site: &mut EvalSite<'_>, _op: &Op, _terms: &[Value]| {
            Value::Bool(site.token().is_none())
        });
    assert_eq!(
        tabnas_expr::evaluation(&mut EvalSite::detached(), &node, &asked),
        Value::Bool(true)
    );
}

// --- the operator table ----------------------------------------------------

/// An operator's token identity comes from the INSTANCE, not from a global
/// table. A host grammar registers its punctuation as instance-level fixed
/// tokens before this plugin runs, and an operator bound to a fresh
/// identity instead would leave its alternate waiting on a token the host
/// lexer never emits.
#[test]
fn operators_bind_to_instance_fixed_tokens() {
    let mut parser = tabnas_jsonic::make();
    let host = parser.token_with_source("#AT", "@");
    assert_eq!(Some(host), parser.fixed("@"));

    parser
        .use_plugin(
            tabnas_expr::plugin(),
            Some(Value::from_json(&json!({
                "op": { "at": { "infix": true, "left": 2000000, "right": 2100000, "src": "@" } }
            }))),
        )
        .expect("the plugin installs");

    // The operator matches the token the host lexer emits, so the
    // expression parses rather than failing as an unexpected character.
    assert_eq!(
        norm(parse_simplified(&parser, "1 @ 2").expect("1 @ 2 parses")),
        norm(json!(["@", 1, 2]))
    );
    // The host's identity is still the one bound to the source.
    assert_eq!(Some(host), parser.fixed("@"));
}

/// A host that already configured `options.fixed.check` still gets its
/// comments lexed as comments.
///
/// The default `/` operator is a prefix of both `//` and `/*`, and the
/// fixed matcher runs before the comment one, so the plugin makes the
/// fixed family stand aside where a comment starts. Omitting that because
/// the host had claimed the hook cut `// note` into two `/` operators and
/// the document failed with `unexpected`. The canonical reorders the
/// matchers instead, so a host check never sees a comment opener there
/// either, and `1/2 // note` parses in TypeScript whether or not a host
/// check is installed.
#[test]
fn a_host_fixed_check_keeps_the_comment_guard() {
    let mut parser = tabnas_jsonic::make();
    parser.lex_check_ref("@host-fixed", |_remaining: &str| LexCheckResult::Continue);
    parser
        .grammar_json(r#"{"options":{"fixed":{"check":"@host-fixed"}}}"#)
        .expect("the host check installs");
    parser
        .use_plugin(tabnas_expr::plugin(), None)
        .expect("the plugin installs");

    for (src, want) in [
        ("1/2 // note", json!(["/", 1, 2])),
        ("1/2 /* note */", json!(["/", 1, 2])),
        ("a:1/2 // note", json!({ "a": ["/", 1, 2] })),
    ] {
        assert_eq!(
            norm(parse_simplified(&parser, src).unwrap_or_else(|error| panic!("{src:?}: {error}"))),
            norm(want),
            "parse {src:?}"
        );
    }
}

/// A comment marker adjacent to a value is read as a comment.
///
/// The fixed matcher stands aside wherever a contested marker begins, so
/// `1//c` is the value `1` followed by a comment. TypeScript rejects the
/// same document, and `../DIVERGENCE.md` records why: bare jsonic reads it
/// in every runtime, and registering `/` as a fixed token is what breaks
/// it there, which puts the repair on the canonical engine rather than on
/// this port. This pin fails if this port is ever brought down to the
/// TypeScript behaviour instead, and the register entry says so.
#[test]
fn a_comment_marker_adjacent_to_a_value_is_read() {
    let parser = parser_for(json!({}));
    for (src, want) in [
        ("1//c", json!(1)),
        ("1/2//c", json!(["/", 1, 2])),
        ("a:1//c", json!({ "a": 1 })),
        ("1/*c*/", json!(1)),
    ] {
        assert_eq!(
            norm(parse_simplified(&parser, src).unwrap_or_else(|error| panic!("{src:?}: {error}"))),
            norm(want),
            "parse {src:?}"
        );
    }
}

/// Operator setup is deterministic, so precedence never varies between
/// runs: `1 + 2 * 3` is `1 + (2*3)` every time.
#[test]
fn precedence_is_stable() {
    for _ in 0..25 {
        let parser = parser_for(json!({}));
        assert_eq!(
            norm(parse_simplified(&parser, "1 + 2 * 3").expect("parses")),
            norm(json!(["+", 1, ["*", 2, 3]]))
        );
    }
}

/// A user operator claiming a default's source wins, because the
/// operator table is insertion-ordered and the later entry resolves the
/// token. The default `plain` paren and a `func` paren both on `(`…`)` is
/// the case that matters.
#[test]
fn a_later_operator_wins_a_shared_source() {
    let parser = parser_for(json!({
        "op": {
            "func": {
                "paren": true, "osrc": "(", "csrc": ")",
                "preval": { "active": true },
            }
        }
    }));
    assert_eq!(
        norm(parse_simplified(&parser, "f(1)").expect("parses")),
        norm(json!(["(", "f", 1]))
    );
}

/// A binding power of ZERO is an UNSET binding power, as it is in the
/// canonical `opdef.left || Number.MIN_SAFE_INTEGER` and
/// `opdef.right || Number.MAX_SAFE_INTEGER`: JavaScript's `||` is
/// falsy-based, so a zero falls through to the fallback exactly as an
/// absent power does.
///
/// It shows in the tree when a zero-power operator meets one with a
/// NEGATIVE power, the only way to sit below zero. Keeping the zero made
/// `1@2~3` parse as `["@",1,["~",2,3]]`, because `~`'s left of `0` no
/// longer bound looser than `@`'s right of `-2`. All three runtimes take
/// the fallback now, so the behaviour is also a shared fixture
/// (`binding-power-zero.tsv`); this case keeps the small powers the
/// original measurement used.
#[test]
fn a_zero_binding_power_is_unset() {
    let parser = parser_for(json!({
        "op": {
            "at": { "infix": true, "src": "@", "left": -2, "right": -2 },
            "tilde": { "infix": true, "src": "~", "left": 0, "right": 0 },
        }
    }));
    for (src, want) in [
        ("1@2~3", json!(["~", ["@", 1, 2], 3])),
        ("1~2@3", json!(["@", ["~", 1, 2], 3])),
        ("1~2~3", json!(["~", ["~", 1, 2], 3])),
        ("1@2@3", json!(["@", ["@", 1, 2], 3])),
    ] {
        assert_eq!(
            norm(parse_simplified(&parser, src).expect("parses")),
            norm(want),
            "parse {src:?}"
        );
    }
}

/// The plugin layers on the base grammar, and says so rather than
/// installing alternates on a rule that is not there.
#[test]
fn a_bare_engine_is_refused() {
    let mut bare = Tabnas::new();
    let Err(error) = bare.use_plugin(tabnas_expr::plugin(), None) else {
        panic!("a bare engine has no val rule to install on");
    };
    assert!(error.0.contains("val"), "{}", error.0);
}

/// Installing the plugin twice on one instance leaves one copy of the
/// grammar, not two.
#[test]
fn a_second_install_is_a_no_op() {
    let mut parser = tabnas_jsonic::make();
    assert!(parser.use_plugin(tabnas_expr::plugin(), None).is_ok());
    let once = parser.rule_names().len();
    assert!(parser.use_plugin(tabnas_expr::plugin(), None).is_ok());
    assert_eq!(once, parser.rule_names().len());
    assert_eq!(
        norm(parse_simplified(&parser, "1+2*3").expect("parses")),
        norm(json!(["+", 1, ["*", 2, 3]]))
    );
}

/// A derived instance rebuilds the grammar against its own options, so it
/// parses the same documents as its parent.
#[test]
fn a_derived_instance_keeps_the_grammar() {
    let parser = parser_for(json!({}));
    let derived = parser
        .derive(|options| options.tag = "derived".into())
        .expect("derives");
    assert_eq!(
        norm(parse_simplified(&derived, "1+2*3").expect("parses")),
        norm(json!(["+", 1, ["*", 2, 3]]))
    );
}

// --- the parsed shape ------------------------------------------------------

/// The parsed AST is TypeScript's: the term list directly, with the
/// operator described by an object whose keys are lower-case.
///
/// The Go port wraps the term list and emits Go field names, which
/// `DIVERGENCE.md` records; this port must not copy either half.
#[test]
fn the_ast_shape_is_the_typescript_one() {
    let value = tabnas_expr::parse("{a:1+2}").expect("parses");
    let doc = value.to_json();
    let term = doc.get("a").expect("the document has an `a` key");

    // The term list directly, not an object wrapping it.
    let terms = term
        .as_array()
        .unwrap_or_else(|| panic!("`a` is {term}, not the term list"));
    assert_eq!(3, terms.len());

    let op = terms[0]
        .as_object()
        .expect("the first term is the operator");
    // Lower-case keys, as TypeScript emits.
    assert_eq!(Some("addition-infix"), op["name"].as_str());
    assert_eq!(Some("+"), op["src"].as_str());
    assert_eq!(Some(2000000.0), op["left"].as_f64());
    assert_eq!(Some(2100000.0), op["right"].as_f64());
    assert!(op.contains_key("terms"));
    assert!(op.contains_key("preval"));
    assert!(!op.contains_key("Name"), "no Go field names");
    assert!(!op.contains_key("Val"), "no Go field names");

    // The operand terms follow the operator.
    assert_eq!(Some(1.0), terms[1].as_f64());
    assert_eq!(Some(2.0), terms[2].as_f64());

    // The operator carries the token it was matched from, so an evaluator
    // can report where a term came from.
    let token = op["token"].as_object().expect("the operator has a token");
    assert_eq!(Some(4.0), token["sI"].as_f64());
    assert_eq!(Some(1.0), token["rI"].as_f64());
    assert_eq!(Some(5.0), token["cI"].as_f64());
}

/// `simplify` reduces the same tree to the S-expression the shared
/// fixtures compare.
#[test]
fn simplify_reduces_to_source_text() {
    let value = tabnas_expr::parse("{a:1+2}").expect("parses");
    assert_eq!(
        norm(simplify(&value).to_json()),
        norm(json!({"a": ["+", 1, 2]}))
    );
}

/// The convenience parse reuses one instance and realizes its result.
#[test]
fn parse_is_a_convenience_over_one_instance() {
    let first = tabnas_expr::parse("1+2").expect("parses");
    let second = tabnas_expr::parse("a:1+2").expect("parses");
    assert_eq!(norm(simplify(&first).to_json()), norm(json!(["+", 1, 2])));
    assert_eq!(
        norm(simplify(&second).to_json()),
        norm(json!({"a": ["+", 1, 2]}))
    );
    // The first result survives the second parse: it was realized at the
    // parse boundary rather than left as a handle into the arena.
    assert_eq!(norm(simplify(&first).to_json()), norm(json!(["+", 1, 2])));
}

/// A parse driven straight through the engine hands back expression
/// handles, which `realize` turns into the plain arrays a caller reads.
#[test]
fn realize_converts_an_engine_parse() {
    let parser = parser_for(json!({}));
    let raw = parser.parse("1+2").expect("parses");
    assert!(
        is_op(&raw),
        "an unrealized expression is an expression node"
    );
    let value = tabnas_expr::realize(&raw);
    assert_eq!(norm(simplify(&value).to_json()), norm(json!(["+", 1, 2])));
}

/// A handle that escapes `parse_scope` is REFUSED, not quietly reported
/// as an empty expression.
///
/// The closure's return type is a type parameter, so the signature can
/// neither realize what comes back nor stop a handle from being in it.
/// The arena is released as `parse_scope` returns, and a later walk of an
/// escaped handle used to hand back `[]`: a well-formed value that had
/// silently lost the whole expression, which no caller could tell from a
/// parse of an empty document.
#[test]
fn a_handle_that_escapes_the_scope_is_refused() {
    let parser = parser_for(json!({}));

    // Returned directly.
    let escaped = tabnas_expr::parse_scope(&parser, "1+2*3", |value| value).expect("parses");
    let realized = std::panic::catch_unwind(|| tabnas_expr::realize(&escaped));
    assert!(realized.is_err(), "realize must refuse a released handle");

    // Embedded in another return value.
    let wrapped = tabnas_expr::parse_scope(&parser, "1+2*3", |value| vec![value]).expect("parses");
    let simplified = std::panic::catch_unwind(|| simplify(&wrapped[0]));
    assert!(simplified.is_err(), "simplify must refuse it too");

    // Realizing INSIDE the scope is what a caller does instead, and the
    // realized value outlives the arena.
    let kept = tabnas_expr::parse_scope(&parser, "1+2*3", |value| tabnas_expr::realize(&value))
        .expect("parses");
    assert_eq!(
        norm(simplify(&kept).to_json()),
        norm(json!(["+", 1, ["*", 2, 3]]))
    );
}

/// The expression arena is per-thread, so parsers are usable from several
/// threads at once, as the engine's own instances are.
#[test]
fn parsing_is_thread_safe() {
    let parser = std::sync::Arc::new(parser_for(json!({})));
    let mut threads = Vec::new();
    for index in 0..4 {
        let parser = parser.clone();
        threads.push(std::thread::spawn(move || {
            for _ in 0..50 {
                let got = parse_simplified(&parser, "1+2*3").expect("parses");
                assert_eq!(
                    norm(got),
                    norm(json!(["+", 1, ["*", 2, 3]])),
                    "thread {index}"
                );
            }
        }));
    }
    for thread in threads {
        thread.join().expect("the thread finished");
    }
}

// --- untrusted input -------------------------------------------------------

/// An expression past the node limit is refused, rather than building a
/// tree deep enough for the engine's recursive value walks to end the
/// process. The limit and its measurements are in `../DIVERGENCE.md`.
///
/// This fails if the limit is REMOVED as well as if it regresses, which
/// is what keeps the record honest.
#[test]
fn an_expression_past_the_node_limit_is_refused() {
    let parser = parser_for(json!({}));
    let sum = |terms: usize| {
        (0..terms)
            .map(|term| term.to_string())
            .collect::<Vec<_>>()
            .join("+")
    };

    // A flat sum of n terms is n-1 nodes, so the limit allows one more
    // term than it allows nodes.
    let largest = tabnas_expr::NODE_LIMIT + 1;
    assert!(
        parse_simplified(&parser, &sum(largest)).is_ok(),
        "a sum of {largest} terms is within the limit"
    );

    let error =
        parse_simplified(&parser, &sum(largest + 1)).expect_err("a sum past the limit is refused");
    assert_eq!("cancel", error.code, "{error}");

    // Far past it, the refusal is still an error rather than an abort.
    let error = parse_simplified(&parser, &sum(5000)).expect_err("still refused");
    assert_eq!("cancel", error.code);

    // Nesting counts the same way, because a paren expression takes the
    // expression inside it as a term.
    let deep = format!("{}1{}", "(".repeat(500), ")".repeat(500));
    let error = parse_simplified(&parser, &deep).expect_err("deep nesting is refused");
    assert_eq!("cancel", error.code);

    // An UNTERMINATED nesting builds no expression at all, so the node
    // limit never sees it: the rule stack is what bounds it. Without that
    // bound the parse was quadratic in the opener count, which is the
    // super-linear behaviour hostile input must not be able to buy.
    let opens = "(".repeat(8 * tabnas_expr::RULE_LIMIT);
    let error = parse_simplified(&parser, &opens).expect_err("deep openers are refused");
    assert_eq!("cancel", error.code, "{error}");
}

/// Deep nesting, long input, unterminated constructs, empty input and odd
/// characters must not panic, hang or overflow the stack. An error is a
/// fine answer; a crash is not.
#[test]
fn hostile_input_is_refused_rather_than_fatal() {
    let parser = parser_for(json!({}));
    let deep_open = "(".repeat(2000);
    let long_sum = (0..5000)
        .map(|n| n.to_string())
        .collect::<Vec<_>>()
        .join("+");
    for src in [
        "",
        "(",
        ")",
        "1+",
        "+",
        "((((",
        "1+2)",
        "\u{0}",
        "a\u{7f}b",
        "\u{feff}1+2",
        &deep_open,
        &"(1)".repeat(2000),
        &long_sum,
    ] {
        // Either answer is acceptable; neither may abort the process.
        let _ = parse_simplified(&parser, src);
    }
}

/// The canonical simplify's reading where the Go port's `Simplify` differs
/// (`DIVERGENCE.md`): the member order a parse found, a null term kept,
/// and a list whose head carries a `src` text read as an operation. The
/// Go port's `SimplifyOrdered` gives the same values, and the TypeScript
/// `simplify` is pinned to them in `ts/test/expr.test.ts`.
#[test]
fn simplify_reads_the_canonical_value() {
    let parser = parser_for(json!({}));
    for (src, want) in [
        ("{b:1,a:2+3}", r#"{"b":1.0,"a":["+",2.0,3.0]}"#),
        ("1+null", r#"["+",1.0,null]"#),
        ("[{src:x},1]", r#"["x",1.0]"#),
    ] {
        let value =
            parse_simplified(&parser, src).unwrap_or_else(|error| panic!("{src:?}: {error}"));
        // `preserve_order` keeps the members in the order simplify gave
        // them, and `norm` spells every number as a float.
        assert_eq!(
            serde_json::to_string(&norm(value)).expect("a value is JSON"),
            want,
            "{src}"
        );
    }
}

/// A comma list or a chain of postfix operators adds no rule depth with its
/// length: many items reach the deepest rule one item reaches. The Rust half
/// of the TypeScript suite's `options-repeat-by-replacement`.
///
/// Every form runs at 10,000 items, as in TypeScript and Go. The forms that
/// build a node per item make an expression past [`NODE_LIMIT`], so the
/// parser raises its limit (`ExprOptions::node_limit`), and the tree is
/// never realized: the depth is the rules', measured as they run.
#[test]
fn options_repeat_by_replacement() {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    const N: usize = 10_000;
    let preval = |active: bool| PrevalDef {
        active,
        required: false,
        allow: None,
    };
    let table = |tern: bool| {
        let options = ExprOptions::new()
            .with_op(
                "comma",
                OpDef::infix(",", 1_000_000, 1_100_000).with_separator(),
            )
            .with_op("dot", OpDef::infix(".", 5_000_000, 5_100_000))
            .with_op("paren", OpDef::paren("(", ")").with_preval(preval(false)))
            .with_op(
                "call",
                OpDef::paren("(", ")")
                    .with_preval(preval(true))
                    .with_left(5_000_000)
                    .with_content(ContentDef {
                        required: false,
                        separated: true,
                    }),
            )
            .with_node_limit(usize::MAX);
        if tern {
            options.with_op(
                "tern",
                OpDef::ternary("?", ":")
                    .with_left(1_700_000)
                    .with_right(1_600_000),
            )
        } else {
            options
        }
    };
    let deepest = |options: ExprOptions, src: &str| -> usize {
        let mut parser = parser_with(options);
        let deepest = Arc::new(AtomicUsize::new(0));
        let seen = deepest.clone();
        parser.subscribe_rules(move |rule: &mut Rule, _context: &mut Context| {
            seen.fetch_max(rule.d, Ordering::Relaxed);
        });
        if let Err(error) = tabnas_expr::parse_scope(&parser, src, |_| ()) {
            panic!("{:.40}...: {error}", src);
        }
        deepest.load(Ordering::Relaxed)
    };
    let many =
        |sep: &str, item: &dyn Fn(usize) -> String| (0..N).map(item).collect::<Vec<_>>().join(sep);
    let name = |i: usize| format!("a{i}");
    let call = |i: usize| format!("({i})");
    let tern = |i: usize| format!("a{i} ? b{i} :");

    for (what, with_tern, long, short) in [
        // The arguments of a separated call.
        (
            "arguments",
            false,
            format!("f({})", many(", ", &name)),
            "f(a0)".to_string(),
        ),
        // The comma operator in a group.
        (
            "comma operator",
            false,
            format!("({})", many(", ", &name)),
            "(a0, a1)".to_string(),
        ),
        // Calls chained on a value, and after an operator they bind looser
        // than, which places them as postfix operators.
        (
            "chained calls",
            false,
            format!("f{}", many("", &call)),
            "f(0)".to_string(),
        ),
        (
            "postfix calls",
            false,
            format!("x.f{}", many("", &call)),
            "x.f(0)".to_string(),
        ),
        // Ternaries with a binding power, chained through their last terms.
        (
            "bound ternaries",
            true,
            format!("x = {} z", many(" ", &tern)),
            "x = a0 ? b0 : z".to_string(),
        ),
    ] {
        assert_eq!(
            deepest(table(with_tern), &long),
            deepest(table(with_tern), &short),
            "{what}"
        );
    }
}

/// A tree as deep as a long chain of operators is built and evaluated
/// without the call stack growing with its depth: ten thousand terms of a
/// left-associative chain, which evaluation walks to the bottom, and of a
/// right-associative one, which each new operator is placed down to. The
/// Rust half of the TypeScript suite's `deep-trees`. The evaluator gives
/// each operation its depth, so no value as deep as the tree is built:
/// this port realizes and simplifies no tree past [`NODE_LIMIT`].
#[test]
fn deep_trees() {
    const N: usize = 10_000;
    let depth = |term: &Value| match term {
        Value::Number(depth) => *depth,
        _ => 0.0,
    };
    let parser = parser_with(
        ExprOptions::new()
            .with_op("assign", OpDef::infix("=", 1_500_000, 1_400_000))
            .with_node_limit(usize::MAX)
            .with_evaluate(move |_site, _op, terms| {
                Value::Number(1.0 + terms.iter().map(depth).fold(0.0, f64::max))
            }),
    );
    for sep in ["+", "="] {
        let src = vec!["a"; N].join(sep);
        let value = tabnas_expr::parse_with(&parser, &src)
            .unwrap_or_else(|error| panic!("a chain of {sep}: {error}"));
        assert_eq!(Value::Number((N - 1) as f64), value, "a chain of {sep}");
    }
}

/// The limit on an expression's nodes is the parser's to raise: a sum past
/// [`NODE_LIMIT`] is refused by default and read under a higher limit,
/// which refuses a sum past it in turn.
#[test]
fn the_node_limit_is_the_parsers_to_raise() {
    let sum = |terms: usize| vec!["1"; terms].join("+");
    let default = parser_with(ExprOptions::new());
    let raised = parser_with(ExprOptions::new().with_node_limit(200));
    let read = |parser: &Tabnas, terms: usize| {
        tabnas_expr::parse_scope(parser, &sum(terms), |_| ()).map_err(|error| error.code)
    };
    assert_eq!(Err("cancel".to_string()), read(&default, NODE_LIMIT + 2));
    assert_eq!(Ok(()), read(&raised, NODE_LIMIT + 2));
    assert_eq!(Ok(()), read(&raised, 201));
    assert_eq!(Err("cancel".to_string()), read(&raised, 202));
}

/// `simplify` writes a cast by its `src`, the group's opener and closer
/// together, so it reads apart from a call; `accept` sees the group's
/// content as the parse built it. The Rust half of the TypeScript suite's
/// `options-cast-shape`.
#[test]
fn options_cast_shape() {
    use std::sync::{Arc, Mutex};

    let seen: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
    let record = seen.clone();
    let preval = |active: bool| PrevalDef {
        active,
        required: false,
        allow: None,
    };
    let parser = parser_with(
        ExprOptions::new()
            .with_op("paren", OpDef::paren("(", ")").with_preval(preval(false)))
            .with_op("call", OpDef::paren("(", ")").with_preval(preval(true)))
            .with_op(
                "cast",
                OpDef::cast("(", ")", 4_000_000, move |term| {
                    record.lock().unwrap().push(simplify(term).to_json());
                    matches!(term, Value::String(name) if "int" == name)
                }),
            ),
    );
    for (src, want) in [
        ("(int)a", json!(["()", "int", "a"])),
        ("int(a)", json!(["(", "int", "a"])),
        ("(1+2)(a)", json!(["(", ["(", ["+", 1, 2]], "a"])),
    ] {
        assert_eq!(
            norm(parse_simplified(&parser, src).expect("parses")),
            norm(want),
            "{src}"
        );
    }
    let seen = serde_json::Value::Array(seen.lock().unwrap().clone());
    assert_eq!(norm(seen), norm(json!(["int", ["+", 1, 2]])));
}