brink-syntax-native 0.0.15

Lexer and error-resilient CST for the .brink native surface (B0.5 grammar skeleton)
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
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
//! Expressions & precedence. Family for #1193.
//!
//! Parity target studied: `brink-syntax/src/parser/tests/expression/{mod,cst}.rs`
//! (71 tests). This grammar is deliberately a *skeleton* (module doc on
//! `parser/expr.rs`): no array/fn-value sigil literals, no ranges, no
//! indexing, no field access, no postfix `++`/`--` — those don't exist as
//! `SyntaxKind`s here yet (checked against `syntax_kind.rs`). So this file
//! mirrors the parity target's *structure and depth* for the forms that DO
//! exist: literals, paths, prefix/infix expressions, parenthesization,
//! `CALL_EXPR`/`ARG_LIST`, `LAMBDA_EXPR`/`LAMBDA_PARAMS` (shape only here;
//! their lowering is tested in `brink-ir/tests/native_lambdas.rs`),
//! and — since B5 (issue #1464) — the one construction-initializer grammar
//! `TypeName { … }` (`CONSTRUCT_LITERAL`/`CONSTRUCT_ENTRY`), which is how
//! maps and struct construction are spelled on the native surface (there is
//! no `#{…}`/`Name#{…}` sigil here; that is the brink dialect's spelling),
//! and — since NG-D (issue #1490) — the array/sequence literal `[1, 2, 3]`
//! (`ARRAY_LITERAL`), the everyday collection literal's own lightest
//! spelling (no `#[…]` sigil on the native surface either).
//!
//! Entry point: every case below goes through `var name = <expr>` (or, for
//! the accessor tests, `const`), since that's the shortest reachable path
//! to `expr::expression` from `source_file` (`decl.rs::var_decl`).

use super::*;

// ── A. Literals ─────────────────────────────────────────────────────

#[test]
fn integer_literal() {
    let p = assert_lossless("var x = 5\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::INTEGER_LIT));
}

#[test]
fn float_literal() {
    let p = assert_lossless("var x = 3.14\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::FLOAT_LIT));
}

#[test]
fn boolean_literal_true() {
    let p = assert_lossless("var x = true\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::BOOLEAN_LIT));
}

#[test]
fn boolean_literal_false() {
    let p = assert_lossless("var x = false\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::BOOLEAN_LIT));
}

#[test]
fn string_literal() {
    let p = assert_lossless("var x = \"hello\"\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::STRING_LIT));
}

#[test]
fn string_literal_empty() {
    let p = assert_lossless("var x = \"\"\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::STRING_LIT));
}

/// `STRING_LIT` reuses `content::interpolation` for `{expr}` runs inside a
/// quoted string (the same `INTERPOLATION` node prose content uses, per
/// `expr::string_lit`'s doc comment) — a shape test at the boundary, not a
/// duplication of `content.rs`'s own interpolation-family coverage.
#[test]
fn string_literal_with_interpolation_nests_an_expression() {
    let p = assert_lossless("var x = \"hi {name}\"\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::STRING_LIT));
    assert!(has_node_kind(&p.syntax(), SyntaxKind::INTERPOLATION));
    let string_lit = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::STRING_LIT)
        .expect("STRING_LIT");
    assert!(has_node_kind(&string_lit, SyntaxKind::PATH_EXPR));
}

// ── B. Paths ─────────────────────────────────────────────────────────

#[test]
fn path_single_segment() {
    let p = assert_lossless("var x = y\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::PATH_EXPR));
    // `var`'s own LHS name is a bare `IDENT` token (decl.rs::var_decl), not
    // a `PATH_SEGMENT` — only the RHS initializer `y` goes through the
    // expression grammar's `path()`.
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::PATH_SEGMENT), 1);
}

#[test]
fn path_two_segments_dot() {
    let p = assert_lossless("var x = a.b\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let path_expr = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::PATH_EXPR)
        .expect("PATH_EXPR");
    let path: ast::Path = find_child(&path_expr).expect("PATH");
    let segs: Vec<_> = path.segments().map(|t| t.text().to_string()).collect();
    assert_eq!(segs, vec!["a".to_string(), "b".to_string()]);
    assert!(!path.crosses_module_wall());
}

#[test]
fn path_three_segments_dot() {
    let p = assert_lossless("var x = a.b.c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let path_expr = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::PATH_EXPR)
        .expect("PATH_EXPR");
    let path: ast::Path = find_child(&path_expr).expect("PATH");
    assert_eq!(path.segments().count(), 3);
}

#[test]
fn path_double_colon_crosses_module_wall() {
    let p = assert_lossless("var x = a::b\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let path_expr = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::PATH_EXPR)
        .expect("PATH_EXPR");
    let path: ast::Path = find_child(&path_expr).expect("PATH");
    assert!(path.crosses_module_wall());
}

#[test]
fn path_mixed_dot_and_double_colon() {
    let p = assert_lossless("var x = a::b.c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let path_expr = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::PATH_EXPR)
        .expect("PATH_EXPR");
    let path: ast::Path = find_child(&path_expr).expect("PATH");
    let segs: Vec<_> = path.segments().map(|t| t.text().to_string()).collect();
    assert_eq!(
        segs,
        vec!["a".to_string(), "b".to_string(), "c".to_string()]
    );
    assert!(path.crosses_module_wall());
}

// ── C. Prefix expressions ───────────────────────────────────────────

#[test]
fn prefix_negate_integer() {
    let p = assert_lossless("var x = -1\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::PREFIX_EXPR));
}

#[test]
fn prefix_bang_path() {
    let p = assert_lossless("var x = !flag\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::PREFIX_EXPR));
}

#[test]
fn prefix_negate_paren() {
    let p = assert_lossless("var x = -(a + b)\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let prefix = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::PREFIX_EXPR)
        .expect("PREFIX_EXPR");
    assert!(has_node_kind(&prefix, SyntaxKind::PAREN_EXPR));
}

/// `--x` — two adjacent `MINUS` tokens. There is no compound `--` token in
/// this lexer's punctuation set (unlike `brink-syntax`'s postfix `--`,
/// which doesn't exist here at all — `syntax_kind.rs` has no
/// `POSTFIX_EXPR`), so this is prefix-negate applied twice: `-(-x)`.
#[test]
fn prefix_double_negate_is_nested_prefix() {
    let p = assert_lossless("var x = --y\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::PREFIX_EXPR), 2);
    let outer: ast::PrefixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::PrefixExpr::cast)
        .expect("outer PREFIX_EXPR");
    let operand = outer.operand().expect("operand");
    assert_eq!(
        operand.kind(),
        SyntaxKind::PREFIX_EXPR,
        "outer's operand is the inner prefix"
    );
}

#[test]
fn prefix_bang_bang_is_nested_prefix() {
    let p = assert_lossless("var x = !!flag\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::PREFIX_EXPR), 2);
}

// ── D. Infix — one test per operator ────────────────────────────────

fn infix_op_test(src: &str, op: SyntaxKind) {
    let p = assert_lossless(src);
    assert!(p.errors().is_empty(), "{src:?} errors: {:?}", p.errors());
    let infix: ast::InfixExpr = p
        .syntax()
        .descendants()
        .find_map(ast::InfixExpr::cast)
        .expect("INFIX_EXPR should be present");
    assert_eq!(
        infix.op_token().map(|t| t.kind()),
        Some(op),
        "{src:?}: unexpected operator token"
    );
    assert!(infix.lhs().is_some(), "{src:?}: missing lhs");
    assert!(infix.rhs().is_some(), "{src:?}: missing rhs");
}

#[test]
fn infix_plus() {
    infix_op_test("var x = a + b\n", SyntaxKind::PLUS);
}

#[test]
fn infix_minus() {
    infix_op_test("var x = a - b\n", SyntaxKind::MINUS);
}

#[test]
fn infix_star() {
    infix_op_test("var x = a * b\n", SyntaxKind::STAR);
}

#[test]
fn infix_slash() {
    infix_op_test("var x = a / b\n", SyntaxKind::SLASH);
}

#[test]
fn infix_percent() {
    infix_op_test("var x = a % b\n", SyntaxKind::PERCENT);
}

#[test]
fn infix_lt() {
    infix_op_test("var x = a < b\n", SyntaxKind::LT);
}

#[test]
fn infix_gt() {
    infix_op_test("var x = a > b\n", SyntaxKind::GT);
}

#[test]
fn infix_lte() {
    infix_op_test("var x = a <= b\n", SyntaxKind::LT_EQ);
}

#[test]
fn infix_gte() {
    infix_op_test("var x = a >= b\n", SyntaxKind::GT_EQ);
}

#[test]
fn infix_eq_eq() {
    infix_op_test("var x = a == b\n", SyntaxKind::EQ_EQ);
}

#[test]
fn infix_bang_eq() {
    infix_op_test("var x = a != b\n", SyntaxKind::BANG_EQ);
}

#[test]
fn infix_amp_amp() {
    infix_op_test("var x = a && b\n", SyntaxKind::AMP_AMP);
}

/// `||` is two adjacent `PIPE` tokens, not one compound lexer token (module
/// doc on `expr::expression_bp`) — `op_token()` returns the first, and
/// `is_double_pipe()` disambiguates it from a bare single `|` (which can't
/// actually appear as an infix operator here, but the accessor still needs
/// covering).
#[test]
fn infix_pipe_pipe() {
    let p = assert_lossless("var x = a || b\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let infix: ast::InfixExpr = p
        .syntax()
        .descendants()
        .find_map(ast::InfixExpr::cast)
        .expect("INFIX_EXPR");
    assert_eq!(infix.op_token().map(|t| t.kind()), Some(SyntaxKind::PIPE));
    assert!(infix.is_double_pipe());
}

/// Regression precedent for the `brink-syntax` sibling: `||` must skip
/// whitespace before bumping the two `PIPE` tokens, else it would swallow a
/// trivia token instead of the second `|` and double-wrap a parenthesized
/// RHS. `expr.rs`'s `||` branch does call `p.skip_ws()` up front — this
/// pins that behavior against regression.
#[test]
fn infix_pipe_pipe_paren_rhs_does_not_double_wrap() {
    let p = assert_lossless("var x = 0 || (0)\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let infix: ast::InfixExpr = p
        .syntax()
        .descendants()
        .find_map(ast::InfixExpr::cast)
        .expect("INFIX_EXPR");
    let rhs = infix.rhs().expect("rhs");
    assert_eq!(rhs.kind(), SyntaxKind::PAREN_EXPR);
    // Exactly one PAREN_EXPR — a double-wrap bug would nest a second one.
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::PAREN_EXPR), 1);
}

// ── E. Precedence and associativity (Coalesce < Or < And < Eq < Cmp < Add < Mul) ──

/// `a or b == c` → `or` outer, `==` inner RHS (B1, `docs/stdlib-spec.md`
/// §1.6a, issue #1460: `Prec::Coalesce` sits looser than every other
/// operator, so an equality comparison on the fallback side stays nested
/// under `or`, never the other way around — `a or (b == c)`).
#[test]
fn prec_coalesce_over_eq() {
    let p = assert_lossless("var x = a or b == c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(outer.op_token().map(|t| t.kind()), Some(SyntaxKind::KW_OR));
    assert_eq!(
        outer.lhs().map(|n| n.kind()),
        Some(SyntaxKind::PATH_EXPR),
        "lhs should be the bare `a`"
    );
    let rhs = outer.rhs().expect("rhs");
    assert_eq!(
        rhs.kind(),
        SyntaxKind::INFIX_EXPR,
        "`b == c` should nest under `or` as its RHS — see the section doc above"
    );
    let inner = ast::InfixExpr::cast(rhs).expect("inner INFIX_EXPR");
    assert_eq!(inner.op_token().map(|t| t.kind()), Some(SyntaxKind::EQ_EQ));
}

/// `a || b or c` → `or` outer, `||` inner LHS (`or` is looser than `||`
/// too, not just the operators between them — the whole `a || b` disjunction
/// becomes the coalescing left-hand side).
#[test]
fn prec_coalesce_over_double_pipe() {
    let p = assert_lossless("var x = a || b or c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(outer.op_token().map(|t| t.kind()), Some(SyntaxKind::KW_OR));
    let lhs = outer.lhs().expect("lhs");
    assert_eq!(
        lhs.kind(),
        SyntaxKind::INFIX_EXPR,
        "`a || b` should nest under `or` as its LHS — see the section doc above"
    );
    let inner = ast::InfixExpr::cast(lhs).expect("inner INFIX_EXPR");
    assert!(inner.is_double_pipe());
    assert_eq!(
        outer.rhs().map(|n| n.kind()),
        Some(SyntaxKind::PATH_EXPR),
        "rhs should be the bare `c`"
    );
}

/// `a or b or c` → left-nested (`(a or b) or c`), same left-associativity
/// fix section F documents for every other symmetric-precedence operator —
/// `or` shares it, and it is also the ruled coalescing associativity
/// (`infer::ty::coalesce`'s doc: left-associative chaining).
#[test]
fn prec_coalesce_chain_is_left_associative() {
    let p = assert_lossless("var x = a or b or c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(outer.op_token().map(|t| t.kind()), Some(SyntaxKind::KW_OR));
    let lhs = outer.lhs().expect("lhs");
    assert_eq!(
        lhs.kind(),
        SyntaxKind::INFIX_EXPR,
        "`a or b or c` should parse left-associative as `(a or b) or c` \
         (INFIX_EXPR on the LHS)"
    );
    assert_eq!(
        outer.rhs().map(|n| n.kind()),
        Some(SyntaxKind::PATH_EXPR),
        "rhs should be the bare `c` under left-associative parsing"
    );
}

/// `1 + 2 * 3` → `+` outer, `*` inner right (mul binds tighter than add).
#[test]
fn prec_mul_over_add() {
    let p = assert_lossless("var x = 1 + 2 * 3\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(outer.op_token().map(|t| t.kind()), Some(SyntaxKind::PLUS));
    let rhs = outer.rhs().expect("rhs");
    assert_eq!(rhs.kind(), SyntaxKind::INFIX_EXPR);
    let inner = ast::InfixExpr::cast(rhs).expect("inner INFIX_EXPR");
    assert_eq!(inner.op_token().map(|t| t.kind()), Some(SyntaxKind::STAR));
}

/// `1 * 2 + 3` → `+` outer, `*` inner left.
#[test]
fn prec_mul_then_add() {
    let p = assert_lossless("var x = 1 * 2 + 3\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(outer.op_token().map(|t| t.kind()), Some(SyntaxKind::PLUS));
    let lhs = outer.lhs().expect("lhs");
    assert_eq!(lhs.kind(), SyntaxKind::INFIX_EXPR);
}

/// `a && b || c` → `||` outer, `&&` inner left (And binds tighter than Or).
#[test]
fn prec_and_over_or() {
    let p = assert_lossless("var x = a && b || c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert!(outer.is_double_pipe());
    let lhs = outer.lhs().expect("lhs");
    assert_eq!(lhs.kind(), SyntaxKind::INFIX_EXPR);
    let inner = ast::InfixExpr::cast(lhs).expect("inner INFIX_EXPR");
    assert_eq!(
        inner.op_token().map(|t| t.kind()),
        Some(SyntaxKind::AMP_AMP)
    );
}

/// `a == b && c` → `&&` outer, `==` inner left (Eq binds tighter than And).
#[test]
fn prec_eq_over_and() {
    let p = assert_lossless("var x = a == b && c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(
        outer.op_token().map(|t| t.kind()),
        Some(SyntaxKind::AMP_AMP)
    );
    let lhs = outer.lhs().expect("lhs");
    let inner = ast::InfixExpr::cast(lhs).expect("inner INFIX_EXPR");
    assert_eq!(inner.op_token().map(|t| t.kind()), Some(SyntaxKind::EQ_EQ));
}

/// `a < b == c` → `==` outer, `<` inner left (Cmp binds tighter than Eq).
#[test]
fn prec_cmp_over_eq() {
    let p = assert_lossless("var x = a < b == c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(outer.op_token().map(|t| t.kind()), Some(SyntaxKind::EQ_EQ));
    let lhs = outer.lhs().expect("lhs");
    let inner = ast::InfixExpr::cast(lhs).expect("inner INFIX_EXPR");
    assert_eq!(inner.op_token().map(|t| t.kind()), Some(SyntaxKind::LT));
}

/// `a + b < c` → `<` outer, `+` inner left (Add binds tighter than Cmp).
#[test]
fn prec_add_over_cmp() {
    let p = assert_lossless("var x = a + b < c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(outer.op_token().map(|t| t.kind()), Some(SyntaxKind::LT));
    let lhs = outer.lhs().expect("lhs");
    let inner = ast::InfixExpr::cast(lhs).expect("inner INFIX_EXPR");
    assert_eq!(inner.op_token().map(|t| t.kind()), Some(SyntaxKind::PLUS));
}

/// `1 + 2 * 3 > 4` → three-level nesting: `>` outer, `+` middle, `*` inner.
#[test]
fn mixed_precedence_three_levels() {
    let p = assert_lossless("var x = 1 + 2 * 3 > 4\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let gt: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(gt.op_token().map(|t| t.kind()), Some(SyntaxKind::GT));
    let plus = ast::InfixExpr::cast(gt.lhs().expect("lhs")).expect("+ node");
    assert_eq!(plus.op_token().map(|t| t.kind()), Some(SyntaxKind::PLUS));
    let star = ast::InfixExpr::cast(plus.rhs().expect("rhs")).expect("* node");
    assert_eq!(star.op_token().map(|t| t.kind()), Some(SyntaxKind::STAR));
}

/// `-a + b` → `INFIX_EXPR { PREFIX_EXPR { PATH_EXPR }, PATH_EXPR }`: prefix
/// binds tighter than every infix level (`Prec::Prefix` is the highest).
#[test]
fn prefix_binds_tighter_than_infix() {
    let p = assert_lossless("var x = -a + b\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let plus: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(plus.op_token().map(|t| t.kind()), Some(SyntaxKind::PLUS));
    let lhs = plus.lhs().expect("lhs");
    assert_eq!(lhs.kind(), SyntaxKind::PREFIX_EXPR);
}

// ── F. Symmetric-precedence operators are left-associative (#1251) ────
//
// `expr::expression_bp`'s recursive call for an infix RHS used to be
// `expression_bp(p, prec)` — reusing the JUST-CONSUMED operator's OWN
// precedence as the child's `min_bp`. Combined with the loop's strict
// `<` break check, a second operator at the SAME precedence didn't stop
// that recursive call — it got pulled into the child instead of being
// left for the parent's own loop. Net effect: every symmetric-precedence
// operator chain in this grammar (`-`, `/`, `%`, `<`, `>`, `<=`, `>=`,
// `==`, `!=`, `&&`, `||`, `or`) parsed RIGHT-associative, not left-associative.
// For `+`/`*` this was unobservable (they're mathematically associative),
// but for `-` and `/` it silently changed the computed VALUE: `10 - 3 - 2`
// grouped as `10 - (3 - 2)` (= 9 if evaluated naively), not
// `(10 - 3) - 2` (= 5).
//
// Fixed by recursing with `min_bp = prec.next()` (`prec + 1`, saturating
// at `Prec::Prefix`) — only strictly-higher-precedence operators get
// pulled into the RHS; a same-precedence operator now falls through to
// the parent's own loop, producing left-associative nesting.

#[test]
fn minus_chain_is_left_associative() {
    let p = assert_lossless("var x = a - b - c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(outer.op_token().map(|t| t.kind()), Some(SyntaxKind::MINUS));
    // Left-assoc shape puts the nested INFIX_EXPR on the LHS: `(a - b) - c`.
    let lhs = outer.lhs().expect("lhs");
    assert_eq!(
        lhs.kind(),
        SyntaxKind::INFIX_EXPR,
        "`a - b - c` should parse left-associative as `(a - b) - c` \
         (INFIX_EXPR on the LHS) — see the section doc above"
    );
    assert_eq!(
        outer.rhs().map(|n| n.kind()),
        Some(SyntaxKind::PATH_EXPR),
        "rhs should be the bare `c` under left-associative parsing"
    );
}

#[test]
fn slash_chain_is_left_associative() {
    let p = assert_lossless("var x = a / b / c\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let outer: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    let lhs = outer.lhs().expect("lhs");
    assert_eq!(
        lhs.kind(),
        SyntaxKind::INFIX_EXPR,
        "same left-associativity fix as `-`, see `minus_chain_is_left_associative`"
    );
}

// ── G. Parenthesized expressions ────────────────────────────────────

#[test]
fn paren_simple() {
    let p = assert_lossless("var x = (1 + 2)\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let paren: ast::ParenExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::ParenExpr::cast)
        .expect("PAREN_EXPR");
    let inner = paren.inner().expect("inner");
    assert_eq!(inner.kind(), SyntaxKind::INFIX_EXPR);
}

#[test]
fn paren_nested() {
    let p = assert_lossless("var x = ((a))\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::PAREN_EXPR), 2);
}

#[test]
fn paren_overrides_precedence() {
    let p = assert_lossless("var x = (1 + 2) * 3\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let star: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(star.op_token().map(|t| t.kind()), Some(SyntaxKind::STAR));
    let lhs = star.lhs().expect("lhs");
    assert_eq!(lhs.kind(), SyntaxKind::PAREN_EXPR);
}

// ── H. Function calls (CALL_EXPR / ARG_LIST) ────────────────────────

#[test]
fn call_zero_args() {
    let p = assert_lossless("var x = foo()\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let call: ast::CallExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::CallExpr::cast)
        .expect("CALL_EXPR");
    let callee = call.callee().expect("callee");
    assert_eq!(
        callee
            .segments()
            .map(|t| t.text().to_string())
            .collect::<Vec<_>>(),
        vec!["foo".to_string()]
    );
    let args = call.arg_list().expect("arg list");
    assert!(args.is_open());
    assert_eq!(args.syntax().children().count(), 0);
}

#[test]
fn call_one_arg() {
    let p = assert_lossless("var x = foo(1)\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let call: ast::CallExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::CallExpr::cast)
        .expect("CALL_EXPR");
    let args = call.arg_list().expect("arg list");
    assert_eq!(args.syntax().children().count(), 1);
}

#[test]
fn call_many_args() {
    let p = assert_lossless("var x = foo(1, 2, 3)\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let call: ast::CallExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::CallExpr::cast)
        .expect("CALL_EXPR");
    let args = call.arg_list().expect("arg list");
    assert_eq!(args.syntax().children().count(), 3);
}

#[test]
fn call_trailing_comma() {
    let p = assert_lossless("var x = foo(1, 2,)\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let call: ast::CallExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::CallExpr::cast)
        .expect("CALL_EXPR");
    let args = call.arg_list().expect("arg list");
    assert_eq!(args.syntax().children().count(), 2);
}

#[test]
fn call_arg_is_an_expression() {
    let p = assert_lossless("var x = foo(1 + 2)\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let call: ast::CallExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::CallExpr::cast)
        .expect("CALL_EXPR");
    let args = call.arg_list().expect("arg list");
    let first = args.syntax().children().next().expect("first arg");
    assert_eq!(first.kind(), SyntaxKind::INFIX_EXPR);
}

#[test]
fn call_nested() {
    let p = assert_lossless("var x = foo(bar(y))\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::CALL_EXPR), 2);
}

#[test]
fn call_dotted_callee() {
    let p = assert_lossless("var x = a.b.c(1)\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let call: ast::CallExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::CallExpr::cast)
        .expect("CALL_EXPR");
    let callee = call.callee().expect("callee");
    assert_eq!(callee.segments().count(), 3);
}

#[test]
fn call_as_infix_operand() {
    let p = assert_lossless("var x = foo(1) + bar(2)\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let plus: ast::InfixExpr = find_child(&p.syntax())
        .and_then(|vd: ast::VarDecl| vd.value())
        .and_then(ast::InfixExpr::cast)
        .expect("outer INFIX_EXPR");
    assert_eq!(plus.lhs().map(|n| n.kind()), Some(SyntaxKind::CALL_EXPR));
    assert_eq!(plus.rhs().map(|n| n.kind()), Some(SyntaxKind::CALL_EXPR));
}

/// `a.b` (no trailing `(`) is `PATH_EXPR`, never `CALL_EXPR` — the two
/// forms share `path_or_call`'s checkpoint and only diverge on lookahead.
#[test]
fn dotted_without_call_is_path_expr_not_call_expr() {
    let p = assert_lossless("var x = a.b\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::PATH_EXPR));
    let path_expr = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::PATH_EXPR)
        .expect("PATH_EXPR");
    assert!(!has_node_kind(&path_expr, SyntaxKind::CALL_EXPR));
}

// ── I. Lambda expressions ───────────────────────────────────────────
//
// These are parse-only *shape* tests: the semantic coverage for lambdas
// lives with the lowering that consumes these nodes
// (`brink-ir/tests/native_lambdas.rs`, issue #1685).

/// The declared names of a `LAMBDA_PARAMS` node's parameters, in source
/// order. Each one is a `PARAM` node (the same shape `fn`/`flow` headers
/// use) since NG-A gave lambda parameters optional `: type` annotations —
/// before that they were bare `IDENT` tokens directly under
/// `LAMBDA_PARAMS`.
fn lambda_param_names(params: &SyntaxNode) -> Vec<String> {
    params
        .children()
        .filter_map(ast::Param::cast)
        .filter_map(|p| p.name_token())
        .map(|t| t.text().to_string())
        .collect()
}

#[test]
fn lambda_pipe_tokenizes_and_parses() {
    let src = "var f = |x, y| x + y\n";
    let p = assert_lossless(src);
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
}

#[test]
fn lambda_zero_params() {
    let p = assert_lossless("var f = || 1\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::LAMBDA_EXPR)
        .expect("LAMBDA_EXPR");
    let params = lambda
        .children()
        .find(|n| n.kind() == SyntaxKind::LAMBDA_PARAMS)
        .expect("LAMBDA_PARAMS");
    assert_eq!(count_node_kind(&params, SyntaxKind::PATH), 0);
}

#[test]
fn lambda_one_param() {
    let p = assert_lossless("var f = |x| x\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::LAMBDA_EXPR)
        .expect("LAMBDA_EXPR");
    let params = lambda
        .children()
        .find(|n| n.kind() == SyntaxKind::LAMBDA_PARAMS)
        .expect("LAMBDA_PARAMS");
    let idents = lambda_param_names(&params);
    assert_eq!(idents, vec!["x".to_string()]);
}

#[test]
fn lambda_multiple_params() {
    let p = assert_lossless("var f = |x, y, z| x\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::LAMBDA_EXPR)
        .expect("LAMBDA_EXPR");
    let params = lambda
        .children()
        .find(|n| n.kind() == SyntaxKind::LAMBDA_PARAMS)
        .expect("LAMBDA_PARAMS");
    let idents = lambda_param_names(&params);
    assert_eq!(
        idents,
        vec!["x".to_string(), "y".to_string(), "z".to_string()]
    );
}

#[test]
fn lambda_params_trailing_comma() {
    let p = assert_lossless("var f = |x, y,| x\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::LAMBDA_EXPR)
        .expect("LAMBDA_EXPR");
    let params = lambda
        .children()
        .find(|n| n.kind() == SyntaxKind::LAMBDA_PARAMS)
        .expect("LAMBDA_PARAMS");
    let idents = lambda_param_names(&params);
    assert_eq!(idents, vec!["x".to_string(), "y".to_string()]);
}

#[test]
fn lambda_body_is_a_full_expression() {
    let p = assert_lossless("var f = |x| x + 1 * 2\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::LAMBDA_EXPR)
        .expect("LAMBDA_EXPR");
    assert!(has_node_kind(&lambda, SyntaxKind::INFIX_EXPR));
}

#[test]
fn lambda_nested_in_call_argument() {
    let p = assert_lossless("var x = apply(|n| n + 1, 5)\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::LAMBDA_EXPR));
    assert!(has_node_kind(&p.syntax(), SyntaxKind::CALL_EXPR));
}

// ── I-bis. Lambda type annotations (NG-A, issue #1487) ───────────────
//
// GRAMMAR ONLY here — the annotations' *lowering* (into `Param.annotation`
// and `LambdaExpr.return_type`) is covered by
// `brink-ir/tests/native_lambdas.rs` (issue #1685); these are parse-shape
// tests, exactly like every other lambda test above.

fn lambda_of(p: &Parse) -> ast::LambdaExpr {
    p.syntax()
        .descendants()
        .find_map(ast::LambdaExpr::cast)
        .expect("LAMBDA_EXPR")
}

fn lambda_params_of(lambda: &ast::LambdaExpr) -> SyntaxNode {
    lambda
        .syntax()
        .children()
        .find(|n| n.kind() == SyntaxKind::LAMBDA_PARAMS)
        .expect("LAMBDA_PARAMS")
}

#[test]
fn lambda_param_takes_a_type_annotation() {
    let p = assert_lossless("var f = |g: Guest| g\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = lambda_of(&p);
    let params = lambda_params_of(&lambda);
    assert_eq!(lambda_param_names(&params), vec!["g".to_string()]);
    let param = params.children().find_map(ast::Param::cast).expect("PARAM");
    let te = param
        .type_annotation()
        .expect("annotation")
        .type_expr()
        .expect("type expr");
    let Some(ast::TypeExprKind::Name(n)) = te.kind() else {
        unreachable!("expected a nominal type, tree: {:#?}", te.syntax())
    };
    assert_eq!(n.name(), Some("Guest".to_string()));
}

#[test]
fn lambda_takes_a_colon_return_annotation_before_a_braced_body() {
    // The ratified surface (2026-07-23): `|g: Guest|: bool { … }`. `bool`
    // is the *return type*, and the brace opens the body — it must NOT be
    // read as a `bool { … }` construction literal.
    let p = assert_lossless("var f = |g: Guest|: bool { g }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = lambda_of(&p);
    let annotation = lambda
        .syntax()
        .children()
        .find_map(ast::TypeAnnotation::cast)
        .expect("the lambda's own `: bool` return annotation");
    let te = annotation.type_expr().expect("type expr");
    let Some(ast::TypeExprKind::Name(n)) = te.kind() else {
        unreachable!("expected a nominal type, tree: {:#?}", te.syntax())
    };
    assert_eq!(n.name(), Some("bool".to_string()));
    assert!(
        !has_node_kind(lambda.syntax(), SyntaxKind::CONSTRUCT_LITERAL),
        "the body brace must not read as a construction literal, tree: {:#?}",
        lambda.syntax()
    );
    assert!(has_node_kind(lambda.syntax(), SyntaxKind::STMT_BLOCK));
}

/// Issue #2775: `lambda_param` calls the exact same `types::type_annotation`
/// entry point `VAR`/`CONST`/fn-params/return-types use, so a generic-typed
/// annotation was never lambda-specific — pin it so the coverage gap that
/// let `|y: Option[int]|` get mistaken for a real gap doesn't reopen.
/// `Option<int>` (angle brackets) is the RULED spelling
/// (`docs/decision-log.md` 2026-07-27 "Type-name surface ruled: angle
/// brackets"); `Option[int]` fails everywhere in this grammar, not just
/// here — see
/// `lambda_param_square_bracket_generic_fails_in_lambda_param_fn_param_and_return_position`.
#[test]
fn lambda_param_takes_a_generic_type_annotation() {
    let p = assert_lossless("var f = |y: Option<int>| { y }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = lambda_of(&p);
    let params = lambda_params_of(&lambda);
    let param = params.children().find_map(ast::Param::cast).expect("PARAM");
    let te = param
        .type_annotation()
        .expect("annotation")
        .type_expr()
        .expect("type expr");
    let Some(ast::TypeExprKind::Generic(g)) = te.kind() else {
        unreachable!("expected a generic type, tree: {:#?}", te.syntax())
    };
    assert_eq!(g.name(), Some("Option".to_string()));
    assert_eq!(g.args().count(), 1);
}

/// Same shape on the lambda's own return annotation — `type_expr` is
/// reached identically from the return-annotation call site
/// (`lambda_expr`) as from the per-param one (`lambda_param`).
#[test]
fn lambda_return_annotation_takes_a_generic_type() {
    let p = assert_lossless("var f = |y: int|: Option<int> { none }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = lambda_of(&p);
    let annotation = lambda
        .syntax()
        .children()
        .find_map(ast::TypeAnnotation::cast)
        .expect("the lambda's own return annotation");
    let te = annotation.type_expr().expect("type expr");
    let Some(ast::TypeExprKind::Generic(g)) = te.kind() else {
        unreachable!("expected a generic type, tree: {:#?}", te.syntax())
    };
    assert_eq!(g.name(), Some("Option".to_string()));
    assert_eq!(g.args().count(), 1);
}

/// The full annotation surface #2775 asked to be enumerated, not just
/// `Option<int>`: `Array<T>`, `Map<K, V>`, a nested `Option<Array<int>>`,
/// and a bare `Option` (no type args) all parse cleanly in lambda-param
/// position, exactly as they do in every other annotation position.
///
/// Each case asserts the actual node shape, not just `errors().is_empty()`
/// — a regression that consumed `<string, int>` but produced a one-arg
/// `TYPE_GENERIC`, or that flattened the nested case, or that mis-typed
/// bare `Option` as a `Generic`, would still parse with zero errors and
/// stay silent here otherwise (the silent-data-drop class CLAUDE.md says
/// to flag).
#[test]
fn lambda_param_generic_annotation_surface() {
    fn type_expr_of(src: &str) -> ast::TypeExpr {
        let p = assert_lossless(src);
        assert!(
            p.errors().is_empty(),
            "src={src:?} errors: {:?}",
            p.errors()
        );
        let lambda = lambda_of(&p);
        let params = lambda_params_of(&lambda);
        let param = params.children().find_map(ast::Param::cast).expect("PARAM");
        param
            .type_annotation()
            .expect("annotation")
            .type_expr()
            .expect("type expr")
    }

    // `Array<int>` — head name + one type argument.
    let te = type_expr_of("var f = |y: Array<int>| { y }\n");
    let Some(ast::TypeExprKind::Generic(g)) = te.kind() else {
        unreachable!("expected a generic type, tree: {:#?}", te.syntax())
    };
    assert_eq!(g.name(), Some("Array".to_string()));
    assert_eq!(g.args().count(), 1);

    // `Map<string, int>` — two type arguments. A regression that flattened
    // or truncated the arg list to one still parses cleanly without this
    // count check.
    let te = type_expr_of("var f = |y: Map<string, int>| { y }\n");
    let Some(ast::TypeExprKind::Generic(g)) = te.kind() else {
        unreachable!("expected a generic type, tree: {:#?}", te.syntax())
    };
    assert_eq!(g.name(), Some("Map".to_string()));
    assert_eq!(g.args().count(), 2);

    // `Option<Array<int>>` — the single type argument must itself be a
    // `Generic` named `Array`, not e.g. flattened into `Option`'s own
    // arg list.
    let te = type_expr_of("var f = |y: Option<Array<int>>| { y }\n");
    let Some(ast::TypeExprKind::Generic(g)) = te.kind() else {
        unreachable!("expected a generic type, tree: {:#?}", te.syntax())
    };
    assert_eq!(g.name(), Some("Option".to_string()));
    let mut args = g.args();
    let arg = args.next().expect("Option's single type argument");
    assert!(
        args.next().is_none(),
        "Option<Array<int>> takes exactly one type argument"
    );
    let Some(ast::TypeExprKind::Generic(inner)) = arg.kind() else {
        unreachable!(
            "expected the nested arg to be a generic type, tree: {:#?}",
            arg.syntax()
        )
    };
    assert_eq!(inner.name(), Some("Array".to_string()));
    assert_eq!(inner.args().count(), 1);

    // Bare `Option` (no type args) comes back as a `Name`, not a
    // `Generic` — pinning that no-args parsing doesn't spuriously produce
    // an empty-arg `TYPE_GENERIC` node instead.
    let te = type_expr_of("var f = |y: Option| { y }\n");
    let Some(ast::TypeExprKind::Name(n)) = te.kind() else {
        unreachable!("expected a nominal type, tree: {:#?}", te.syntax())
    };
    assert_eq!(n.name(), Some("Option".to_string()));
}

/// Negative control, pinning the *other* half of #2775's determination:
/// `[…]` is not a valid type-argument delimiter in lambda-param, `fn`-param,
/// `fn`-return, or `var`/`const` annotation position (reserved for array
/// literals, `[1, 2, 3]`, #1490) — it fails identically across all four.
/// This is why the fix is documentation, not parser acceptance of `[…]`:
/// widening only one position would make it the one place `[…]` silently
/// meant something, instead of consistently meaning nothing.
///
/// `var`/`const` position was carved out here at #2775 time: `var x:
/// Option[int] = none` produced **zero** diagnostics — it silently parsed
/// the bare `Option` and reinterpreted the trailing `[int] = none` as an
/// unrelated `CONTENT_LINE` (recorded in that PR body's "Scope found beyond
/// this issue" section as a real gap, deliberately left unfixed there since
/// it was outside #2775's parser-only fence). Issue #2781 closed that gap —
/// `var`/`const` now fails loudly here too, so the carve-out no longer
/// applies; the dedicated regression tests for the exact diagnostic text
/// live in `declaration.rs`
/// (`var_decl_square_bracket_after_type_name_fails_loudly_instead_of_dropping_to_content`
/// / the `const` sibling next to it).
///
/// **Issue #2792 unified the message itself**, not just "some error fires":
/// before #2792, `lambda`/`fn`-param/`fn`-return each failed for an
/// unrelated, incidental reason (a hard `expect` for the *next* required
/// token — `PIPE`, `R_PAREN` — that happened to trip on `[`), so each
/// produced a different, generic "expected X, found `L_BRACKET`" message,
/// while only `var`/`const` (#2785) had a real, targeted diagnostic. Every
/// position's `errors().first()` is now that same targeted message —
/// `types::reject_bracket_after_type_name` (`parser/types.rs`) fires it
/// once, right where `type_name_or_generic` finishes reading the bare type
/// name, so every calling position gets it "for free" with no per-site
/// wiring. What #2792 deliberately left alone is *recovery*: each
/// position's own pre-existing hard-`expect` cascade (unrelated additional
/// diagnostics, a stray `CONTENT_LINE`/`INTERPOLATION` holding the leftover
/// `[int]…` text) still fires exactly as before — this test only pins the
/// first, unified diagnostic, not the full cascade (see `declaration.rs`'s
/// sibling tests for `fn`-param/`fn`-return/struct-field cascades, and
/// `statement.rs` for `let`).
#[test]
fn lambda_param_square_bracket_generic_fails_in_lambda_param_fn_param_and_return_position() {
    const UNIFIED_MESSAGE: &str = "expected `<` or end of type name, found L_BRACKET";

    let lambda = assert_lossless("var f = |y: Option[int]| { y }\n");
    assert_eq!(
        lambda.errors().first().map(|e| e.message.as_str()),
        Some(UNIFIED_MESSAGE),
        "errors: {:?}",
        lambda.errors()
    );

    let fn_param = parse("fn f(x: Option[int]) {}\n");
    assert_eq!(
        fn_param.errors().first().map(|e| e.message.as_str()),
        Some(UNIFIED_MESSAGE),
        "errors: {:?}",
        fn_param.errors()
    );

    let fn_return = parse("fn f(): Option[int] { none }\n");
    assert_eq!(
        fn_return.errors().first().map(|e| e.message.as_str()),
        Some(UNIFIED_MESSAGE),
        "errors: {:?}",
        fn_return.errors()
    );

    let var_decl = parse("var x: Option[int] = none\n");
    assert_eq!(
        var_decl.errors().first().map(|e| e.message.as_str()),
        Some(UNIFIED_MESSAGE),
        "errors: {:?}",
        var_decl.errors()
    );

    let const_decl = parse("const MAX: Option[int] = none\n");
    assert_eq!(
        const_decl.errors().first().map(|e| e.message.as_str()),
        Some(UNIFIED_MESSAGE),
        "errors: {:?}",
        const_decl.errors()
    );
}

/// #2792 review (BLOCKING false positive): unlike every other annotation
/// position, a lambda's *own* return annotation is immediately followed by
/// an expression — the lambda body — and `[` legally starts one (the
/// array-literal atom, #1490). `var f = |x: int|: List<int> [1, 2]` is a
/// fully legal program: return type `List<int>`, body the two-element array
/// literal `[1, 2]`. An earlier version of this PR's shared bracket check
/// (`types::reject_bracket_after_type_name`) ran unconditionally at every
/// position it could reach, including this one, and misfired on exactly
/// this shape — a regression from zero errors at `main` — which is why
/// `types::lambda_return_type_annotation` (used only by `expr.rs::
/// lambda_expr`, not by `lambda_param`) exempts the outermost type at this
/// one call site. This is the corresponding negative control to
/// `lambda_return_annotation_takes_a_generic_type` above: that test proves
/// the closed-generic shape lowers correctly with no trailing bracket;
/// this one proves a *legal* trailing bracket (the next construct, not a
/// mistake) is left alone.
#[test]
fn lambda_return_annotation_array_literal_body_after_generic_return_type_is_not_a_false_positive() {
    let p = assert_lossless("var f = |x: int|: List<int> [1, 2]\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = lambda_of(&p);
    let annotation = lambda
        .syntax()
        .children()
        .find_map(ast::TypeAnnotation::cast)
        .expect("the lambda's own return annotation");
    let te = annotation.type_expr().expect("type expr");
    let Some(ast::TypeExprKind::Generic(g)) = te.kind() else {
        unreachable!("expected a generic type, tree: {:#?}", te.syntax())
    };
    assert_eq!(g.name(), Some("List".to_string()));
    let body = lambda.body().expect("lambda body");
    assert_eq!(
        body.kind(),
        SyntaxKind::ARRAY_LITERAL,
        "body should be the [1, 2] array literal, not swallowed into the return type; tree: {body:#?}"
    );
}

/// The trade-off finding 1's fix accepts, pinned so a future change doesn't
/// silently "improve" this back into a false positive without a maintainer
/// ruling (`docs/decision-log.md`'s note on this same PR): because the
/// check at `lambda_expr`'s own return-annotation call site is now fully
/// exempted (not just for the closed-generic case), `|y: int|:
/// Option[int] { none }` goes back to the pre-#2792 silent-data-drop
/// behavior — `expression(p)` reads `[int]` as the lambda's `ARRAY_LITERAL`
/// body, and the real ` { none }` body is dropped with **zero**
/// diagnostics, exactly as it did before this PR. `lambda_param`'s own
/// annotation is unaffected — see
/// `lambda_param_square_bracket_generic_fails_in_lambda_param_fn_param_and_return_position`
/// for that position (a `fn`-return-position case, not this one) still
/// failing loudly.
#[test]
fn lambda_return_annotation_square_bracket_mistake_is_a_known_silent_drop_not_a_diagnostic() {
    let p = parse("var f = |y: int|: Option[int] { none }\n");
    assert!(
        p.errors().is_empty(),
        "the false-positive fix (issue #2792 review) exempts this position \
         entirely, so this known silent drop should produce zero \
         diagnostics, not the unified message; errors: {:?}",
        p.errors()
    );
    let lambda = lambda_of(&p);
    let body = lambda.body().expect("lambda body");
    assert_eq!(
        body.kind(),
        SyntaxKind::ARRAY_LITERAL,
        "the leftover `[int]` is silently read as the body, dropping the \
         real ` {{ none }}` body; tree: {body:#?}"
    );
}

#[test]
fn zero_arg_lambda_takes_a_return_annotation() {
    let p = assert_lossless("var f = ||: int { 1 }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = lambda_of(&p);
    assert!(lambda_param_names(&lambda_params_of(&lambda)).is_empty());
    assert!(
        lambda
            .syntax()
            .children()
            .any(|n| n.kind() == SyntaxKind::TYPE_ANNOTATION)
    );
}

#[test]
fn unannotated_lambda_has_no_return_annotation() {
    let p = assert_lossless("var f = |x| x\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = lambda_of(&p);
    assert!(
        !lambda
            .syntax()
            .children()
            .any(|n| n.kind() == SyntaxKind::TYPE_ANNOTATION)
    );
}

#[test]
fn a_lambda_key_in_a_construction_entry_keeps_the_entry_colon() {
    // The one adjacency worth pinning: a `:` that follows a lambda *body*
    // belongs to the enclosing construction entry, not to the lambda —
    // only a `:` immediately after the closing `|` is a return annotation.
    let p = assert_lossless("var m = Map { \"k\": |x| x }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lambda = lambda_of(&p);
    assert!(
        !lambda
            .syntax()
            .children()
            .any(|n| n.kind() == SyntaxKind::TYPE_ANNOTATION)
    );
    assert!(has_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_ENTRY));
}

// ── J. Typed AST accessors (arithmetic/call accessor coverage — the ──
// ── B0.6 review's "zero coverage" finding this issue was seeded on)   ──

#[test]
fn integer_lit_value_accessor() {
    let p = parse("var x = 42\n");
    let file = ast::SourceFile::cast(p.syntax()).expect("SOURCE_FILE");
    let var_decl: ast::VarDecl = find_child(file.syntax()).expect("var decl");
    let value = var_decl.value().expect("initializer node");
    let lit = ast::IntegerLit::cast(value).expect("INTEGER_LIT");
    assert_eq!(lit.value(), Some(42));
}

#[test]
fn float_lit_value_accessor() {
    let p = parse("var x = 3.5\n");
    let file = ast::SourceFile::cast(p.syntax()).expect("SOURCE_FILE");
    let var_decl: ast::VarDecl = find_child(file.syntax()).expect("var decl");
    let value = var_decl.value().expect("initializer node");
    let lit = ast::FloatLit::cast(value).expect("FLOAT_LIT");
    assert!((lit.value().expect("float value") - 3.5).abs() < f64::EPSILON);
}

#[test]
fn boolean_lit_value_accessor_true_and_false() {
    for (src, expected) in [("var x = true\n", true), ("var x = false\n", false)] {
        let p = parse(src);
        let file = ast::SourceFile::cast(p.syntax()).expect("SOURCE_FILE");
        let var_decl: ast::VarDecl = find_child(file.syntax()).expect("var decl");
        let value = var_decl.value().expect("initializer node");
        let lit = ast::BooleanLit::cast(value).expect("BOOLEAN_LIT");
        assert_eq!(lit.value(), Some(expected), "{src:?}");
    }
}

#[test]
fn prefix_expr_op_token_and_operand_accessors() {
    let p = parse("var x = -a\n");
    let file = ast::SourceFile::cast(p.syntax()).expect("SOURCE_FILE");
    let var_decl: ast::VarDecl = find_child(file.syntax()).expect("var decl");
    let value = var_decl.value().expect("initializer node");
    let prefix = ast::PrefixExpr::cast(value).expect("PREFIX_EXPR");
    assert_eq!(prefix.op_token().map(|t| t.kind()), Some(SyntaxKind::MINUS));
    assert_eq!(
        prefix.operand().map(|n| n.kind()),
        Some(SyntaxKind::PATH_EXPR)
    );
}

#[test]
fn call_expr_callee_and_arg_list_accessors_multi_arg() {
    // Mirrors `ast::tests::call_expr_callee_resolves_the_path_not_a_path_expr`
    // (which only covers a 2-arg call's `is_open()`) — this exercises the
    // arg-list SHAPE (arg count, arg kinds) that finding didn't touch.
    let p = parse("const x = compute(a, 1 + 2, foo())\n");
    let file = ast::SourceFile::cast(p.syntax()).expect("SOURCE_FILE");
    let const_decl: ast::ConstDecl = find_child(file.syntax()).expect("const decl");
    let value = const_decl.value().expect("initializer node");
    let call = ast::CallExpr::cast(value).expect("CALL_EXPR");
    let callee = call.callee().expect("callee");
    assert_eq!(
        callee
            .segments()
            .map(|t| t.text().to_string())
            .collect::<Vec<_>>(),
        vec!["compute".to_string()]
    );
    let args = call.arg_list().expect("arg list");
    let kinds: Vec<_> = args.syntax().children().map(|n| n.kind()).collect();
    assert_eq!(
        kinds,
        vec![
            SyntaxKind::PATH_EXPR,
            SyntaxKind::INFIX_EXPR,
            SyntaxKind::CALL_EXPR,
        ]
    );
}

#[test]
fn paren_expr_inner_accessor() {
    let p = parse("var x = (a)\n");
    let file = ast::SourceFile::cast(p.syntax()).expect("SOURCE_FILE");
    let var_decl: ast::VarDecl = find_child(file.syntax()).expect("var decl");
    let value = var_decl.value().expect("initializer node");
    let paren = ast::ParenExpr::cast(value).expect("PAREN_EXPR");
    assert_eq!(paren.inner().map(|n| n.kind()), Some(SyntaxKind::PATH_EXPR));
}

#[test]
fn path_expr_path_accessor() {
    let p = parse("var x = knot.stitch\n");
    let file = ast::SourceFile::cast(p.syntax()).expect("SOURCE_FILE");
    let var_decl: ast::VarDecl = find_child(file.syntax()).expect("var decl");
    let value = var_decl.value().expect("initializer node");
    let path_expr = ast::PathExpr::cast(value).expect("PATH_EXPR");
    let path = path_expr.path().expect("path");
    assert_eq!(
        path.segments()
            .map(|t| t.text().to_string())
            .collect::<Vec<_>>(),
        vec!["knot".to_string(), "stitch".to_string()]
    );
}

// ── K. Structural invariants ────────────────────────────────────────

fn assert_infix_has_two_node_children(src: &str) {
    let p = parse(src);
    assert!(p.errors().is_empty(), "unexpected errors: {:?}", p.errors());
    for node in p.syntax().descendants() {
        if node.kind() == SyntaxKind::INFIX_EXPR {
            let child_count = node.children().count();
            assert_eq!(
                child_count, 2,
                "INFIX_EXPR should have exactly 2 node children, found {child_count} in `{src}`"
            );
        }
    }
}

fn assert_prefix_has_one_node_child(src: &str) {
    let p = parse(src);
    assert!(p.errors().is_empty(), "unexpected errors: {:?}", p.errors());
    for node in p.syntax().descendants() {
        if node.kind() == SyntaxKind::PREFIX_EXPR {
            let child_count = node.children().count();
            assert_eq!(
                child_count, 1,
                "PREFIX_EXPR should have exactly 1 node child, found {child_count} in `{src}`"
            );
        }
    }
}

#[test]
fn invariant_infix_simple() {
    assert_infix_has_two_node_children("var x = a + b\n");
}

#[test]
fn invariant_infix_chained_precedence() {
    assert_infix_has_two_node_children("var x = 1 + 2 * 3\n");
}

#[test]
fn invariant_infix_comparison() {
    assert_infix_has_two_node_children("var x = a > 5\n");
}

#[test]
fn invariant_infix_double_pipe() {
    assert_infix_has_two_node_children("var x = a || b\n");
}

#[test]
fn invariant_prefix_negate() {
    assert_prefix_has_one_node_child("var x = -1\n");
}

#[test]
fn invariant_prefix_bang() {
    assert_prefix_has_one_node_child("var x = !flag\n");
}

#[test]
fn invariant_call_expr_first_child_is_path() {
    for src in [
        "var x = foo()\n",
        "var x = foo(1, 2)\n",
        "var x = foo(bar(y))\n",
    ] {
        let p = parse(src);
        assert!(p.errors().is_empty(), "{src:?} errors: {:?}", p.errors());
        for node in p.syntax().descendants() {
            if node.kind() == SyntaxKind::CALL_EXPR {
                let first_child = node
                    .children()
                    .next()
                    .expect("CALL_EXPR should have at least one child");
                assert_eq!(
                    first_child.kind(),
                    SyntaxKind::PATH,
                    "CALL_EXPR first child should be PATH in `{src}`"
                );
            }
        }
    }
}

// ── L. Positive/negative assertions ─────────────────────────────────

#[test]
fn integer_literal_not_float_literal() {
    let p = parse("var x = 5\n");
    assert!(has_node_kind(&p.syntax(), SyntaxKind::INTEGER_LIT));
    assert!(!has_node_kind(&p.syntax(), SyntaxKind::FLOAT_LIT));
}

#[test]
fn float_literal_not_integer_literal() {
    let p = parse("var x = 5.0\n");
    assert!(has_node_kind(&p.syntax(), SyntaxKind::FLOAT_LIT));
    assert!(!has_node_kind(&p.syntax(), SyntaxKind::INTEGER_LIT));
}

#[test]
fn call_not_paren() {
    let p = parse("var x = foo(y)\n");
    assert!(has_node_kind(&p.syntax(), SyntaxKind::CALL_EXPR));
    assert!(!has_node_kind(&p.syntax(), SyntaxKind::PAREN_EXPR));
}

#[test]
fn paren_not_call() {
    let p = parse("var x = (1 + 2)\n");
    assert!(has_node_kind(&p.syntax(), SyntaxKind::PAREN_EXPR));
    assert!(!has_node_kind(&p.syntax(), SyntaxKind::CALL_EXPR));
}

#[test]
fn call_not_lambda() {
    let p = parse("var x = foo(1)\n");
    assert!(has_node_kind(&p.syntax(), SyntaxKind::CALL_EXPR));
    assert!(!has_node_kind(&p.syntax(), SyntaxKind::LAMBDA_EXPR));
}

// ── M. Error recovery ───────────────────────────────────────────────

#[test]
fn error_unterminated_string() {
    let src = "var x = \"hello\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(
        !p.errors().is_empty(),
        "expected parse error for unterminated string"
    );
}

#[test]
fn error_missing_rparen_call() {
    let src = "var x = foo(1, 2\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(
        !p.errors().is_empty(),
        "expected parse error for missing `)` in call"
    );
}

#[test]
fn error_missing_rparen_paren_expr() {
    let src = "var x = (1 + 2\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(
        !p.errors().is_empty(),
        "expected parse error for missing `)` in paren expression"
    );
}

#[test]
fn error_missing_operand_after_infix() {
    let src = "var x = 1 +\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(
        !p.errors().is_empty(),
        "expected parse error for a dangling infix operator"
    );
}

#[test]
fn error_missing_operand_at_eof_no_trailing_newline() {
    // No trailing NEWLINE token at all — pure EOF-adjacent malformed input.
    let src = "var x = 1 +";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
}

#[test]
fn error_empty_parens_has_no_expression() {
    // `()` — L_PAREN immediately followed by R_PAREN. `atom()` can't start
    // an expression on R_PAREN, so this records an error but still closes
    // the PAREN_EXPR node losslessly (no operand list here — unlike
    // `brink-syntax`, this grammar has no `LIST_EXPR` fallback).
    let src = "var x = ()\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
    let paren = p
        .syntax()
        .descendants()
        .find(|n| n.kind() == SyntaxKind::PAREN_EXPR)
        .expect("PAREN_EXPR still opens");
    assert_eq!(paren.children().count(), 0);
}

#[test]
fn error_malformed_arg_list_leading_comma() {
    // `foo(,)` — a stray leading COMMA can't start an expression;
    // `arg_list`'s zero-progress guard must recover via `error_recover`
    // (consume the COMMA as an ERROR-wrapped token) rather than looping
    // forever or panicking.
    let src = "var x = foo(,)\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::ERROR));
}

#[test]
fn error_malformed_arg_list_double_comma() {
    let src = "var x = foo(1,,2)\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
}

#[test]
fn error_unclosed_call_at_eof() {
    let src = "var x = foo(";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
}

#[test]
fn error_unclosed_lambda_pipe_still_recovers_a_body() {
    // `|x, y expr` — missing the closing `|`. `lambda_params` breaks its
    // loop on the un-comma'd `expr` token, `expect(PIPE)` records an error
    // without consuming, and the lambda body still parses from wherever
    // the cursor landed. Round-trip must still hold.
    let src = "var f = |x, y expr\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::LAMBDA_EXPR));
}

#[test]
fn error_unexpected_token_cannot_start_expression() {
    // A bare `+` is not a prefix operator here (only `-`/`!` are, per
    // `expr::is_prefix_op`) — it can't start an expression at all.
    let src = "var x = +\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
}

#[test]
fn error_unexpected_token_percent_cannot_start_expression() {
    let src = "var x = %5\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
}

// ── N. Adversarial / fuzz-style inputs ──────────────────────────────

#[test]
fn adversarial_deeply_nested_parens_does_not_panic() {
    // 300 > MAX_DEPTH (256, `parser::MAX_DEPTH`). `enter_depth` must bail
    // with an error at the limit rather than blowing the Rust call stack —
    // this is exactly the "guard against unbounded growth" rule
    // (CLAUDE.md) applied to the expression grammar's own recursion.
    let src = format!("var x = {}1{}\n", "(".repeat(300), ")".repeat(300));
    let p = parse(&src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(
        !p.errors().is_empty(),
        "expected a max-nesting-depth error, not silent success or a panic"
    );
}

#[test]
fn adversarial_deeply_nested_calls_does_not_panic() {
    let mut src = "var x = ".to_string();
    for _ in 0..300 {
        src.push_str("foo(");
    }
    src.push('1');
    src.push_str(&")".repeat(300));
    src.push('\n');
    let p = parse(&src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    // Either it hits MAX_DEPTH (error) or it parses clean — either way
    // it must not panic or hang, which reaching this assertion proves.
    let _ = p.errors();
}

#[test]
fn adversarial_long_infix_chain_does_not_panic() {
    // 500 `+`-chained terms. Left-associative parsing (see section F)
    // builds this iteratively in the loop rather than recursing once per
    // operator, but this still must not blow the stack or hang.
    let mut src = "var x = 1".to_string();
    for _ in 0..500 {
        src.push_str(" + 1");
    }
    src.push('\n');
    let p = parse(&src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
}

#[test]
fn adversarial_truncated_source_mid_operator() {
    let src = "var x = a =";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
}

#[test]
fn adversarial_unicode_in_string_literal() {
    let src = "var x = \"héllo wörld 🎉\"\n";
    let p = assert_lossless(src);
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
}

#[test]
fn adversarial_mixed_garbage_tokens_in_call_args() {
    let src = "var x = foo(1, @, )#, 2)\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    // Just must not panic; garbage tokens are expected to produce errors.
    assert!(!p.errors().is_empty());
}

// ── N2. Construction initializers, `TypeName { … }` (B5, #1464) ──────
// The grammar is one shape for all three ruled entry forms; *meaning* is
// the `construct` protocol's job one layer up (`brink_ir::hir::construct`),
// so these tests only ever assert CST shape, never per-type semantics.

/// The empty form — legal grammar, and the shortest thing that proves the
/// `IDENT`-then-`{` commit fires at all.
#[test]
fn construct_literal_empty() {
    let p = assert_lossless("var m = Map { }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL));
    assert!(!has_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_ENTRY));
}

#[test]
fn construct_literal_pair_form_produces_one_entry_per_pair() {
    let p = assert_lossless("var m = Map { \"a\": 1, \"b\": 2 }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_ENTRY), 2);
}

#[test]
fn construct_literal_element_form_produces_one_entry_per_element() {
    let p = assert_lossless("var f = Flags { Red, Blue, Green }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_ENTRY), 3);
}

/// The field form is *the same node shape* as the pair form — pair and
/// field differ only in what the target type makes of the left side, which
/// is dispatch, not grammar (`SyntaxKind::CONSTRUCT_ENTRY`'s doc).
#[test]
fn construct_literal_field_form_is_the_same_node_shape_as_the_pair_form() {
    let field = assert_lossless("var p = Point { x: 1, y: 2 }\n");
    let pair = assert_lossless("var m = Map { x: 1, y: 2 }\n");
    assert!(field.errors().is_empty(), "errors: {:?}", field.errors());
    assert_eq!(
        count_node_kind(&field.syntax(), SyntaxKind::CONSTRUCT_ENTRY),
        count_node_kind(&pair.syntax(), SyntaxKind::CONSTRUCT_ENTRY),
    );
}

#[test]
fn construct_literal_accepts_a_trailing_comma() {
    let p = assert_lossless("var m = Map { \"a\": 1, }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_ENTRY), 1);
}

#[test]
fn construct_literal_entries_may_span_lines() {
    let p = assert_lossless("var m = Map {\n  \"a\": 1,\n  \"b\": 2,\n}\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_ENTRY), 2);
}

#[test]
fn construct_literal_nests() {
    let p = assert_lossless("var m = Map { \"p\": Point { x: 1 } }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(
        count_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL),
        2
    );
}

/// A `::`-qualified type name is one `PATH`, so the whole spelling is still
/// a single construction literal (registry lookup is on the last segment).
#[test]
fn construct_literal_accepts_a_qualified_type_path() {
    let p = assert_lossless("var m = std::map::Map { \"a\": 1 }\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL));
}

/// The brace must sit on the type name's own line — a `NEWLINE` is never
/// trivia here, so this is a plain path followed by an unrelated block, not
/// a construction literal (the same rule a call's `(` already follows).
#[test]
fn a_brace_on_the_next_line_is_not_a_construct_literal() {
    let p = assert_lossless("var m = Map\n\nflow main() {\n}\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(!has_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL));
}

/// The `no-struct-literal` restriction (Rust's precedent): in an `if`/
/// `while`/`for` head the brace opens the body, so a bare path there must
/// stay a `PATH_EXPR` and the block must stay a `STMT_BLOCK`.
#[test]
fn a_control_flow_head_does_not_swallow_its_body_brace() {
    for src in [
        "var x = { if ready { 1; } };\n",
        "var x = { while ready { 1; } };\n",
        "var x = { for k in bag { 1; } };\n",
    ] {
        let p = assert_lossless(src);
        assert!(p.errors().is_empty(), "{src}: errors: {:?}", p.errors());
        assert!(
            !has_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL),
            "{src}: head brace must open the body, not a construction literal"
        );
        assert!(has_node_kind(&p.syntax(), SyntaxKind::STMT_BLOCK));
    }
}

/// …and the restriction lifts inside parentheses, so the literal form is
/// still reachable in a head when the author asks for it.
#[test]
fn parentheses_restore_the_construct_literal_inside_a_control_flow_head() {
    let p = assert_lossless("var x = { if (Point { x: 1 }) == p { 1; } };\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL));
    assert!(has_node_kind(&p.syntax(), SyntaxKind::STMT_BLOCK));
}

/// The same restriction on the *content-ground* `{if …}`/`{match …}` heads
/// (`parser::family`), whose arm bodies also open with `{`.
#[test]
fn a_content_ground_conditional_head_does_not_swallow_its_arm_brace() {
    for src in [
        "flow main() {\n  {if ready {\n    Yes\n  }}\n}\n",
        "flow main() {\n  {match mood {\n    calm => Calm\n  }}\n}\n",
    ] {
        let p = assert_lossless(src);
        assert!(p.errors().is_empty(), "{src}: errors: {:?}", p.errors());
        assert!(
            !has_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL),
            "{src}: head brace must open the arm, not a construction literal"
        );
    }
}

/// A construction literal nested *inside* a control-flow body is
/// unrestricted — the restriction is scoped to the head, and `stmt_block`
/// clears it again.
#[test]
fn a_control_flow_body_may_contain_a_construct_literal() {
    let p = assert_lossless("var x = { if ready { let m = Map { \"a\": 1 }; } };\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL));
}

/// A construction literal is an ordinary atom, so it composes with the rest
/// of the expression grammar (call argument position here).
#[test]
fn construct_literal_in_call_argument_position() {
    let p = assert_lossless("var x = size(Map { \"a\": 1 })\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL));
    assert!(has_node_kind(&p.syntax(), SyntaxKind::ARG_LIST));
}

#[test]
fn unterminated_construct_literal_never_panics() {
    let src = "var m = Map { \"a\": 1\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
}

#[test]
fn garbage_inside_a_construct_literal_never_panics() {
    let src = "var m = Map { @@@ }\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
}

/// Typed-AST accessors: form detection reads the `COLON` token, and
/// `key`/`value` line up with it.
#[test]
fn construct_entry_accessors_distinguish_the_two_forms() {
    let p = assert_lossless("var m = Map { \"a\": 1 }\n");
    let lit = p
        .syntax()
        .descendants()
        .find_map(ast::ConstructLiteral::cast)
        .expect("one CONSTRUCT_LITERAL");
    assert_eq!(
        lit.type_path()
            .expect("type path")
            .segments()
            .map(|t| t.text().to_string())
            .collect::<Vec<_>>(),
        vec!["Map".to_string()]
    );
    let entry = lit.entries().next().expect("one entry");
    assert!(entry.is_pair());
    assert_eq!(entry.key().expect("key").kind(), SyntaxKind::STRING_LIT);
    assert_eq!(
        entry.value().expect("value").kind(),
        SyntaxKind::INTEGER_LIT
    );

    let p = assert_lossless("var f = Flags { Red }\n");
    let lit = p
        .syntax()
        .descendants()
        .find_map(ast::ConstructLiteral::cast)
        .expect("one CONSTRUCT_LITERAL");
    let entry = lit.entries().next().expect("one entry");
    assert!(!entry.is_pair());
    assert!(entry.key().is_none());
    assert_eq!(entry.value().expect("value").kind(), SyntaxKind::PATH_EXPR);
}

// ── N3. Array/sequence literals, `[…]` (NG-D, issue #1490, RULED ─────
// ── 2026-07-27: "`[1, 2, 3]`. Bracket literal on the native surface") ─
// A plain atom, not a construction-registry entry — the B5-symmetric
// `Array { … }` spelling was weighed and rejected in the same ruling.
// Elements are bare expression children directly under `ARRAY_LITERAL`
// (mirrors `ARG_LIST`'s shape); there is no per-element wrapper node the
// way `CONSTRUCT_ENTRY` wraps a construction literal's entries, since an
// array element is never a key/value pair.

/// The empty form — legal grammar, and the shortest thing that proves the
/// `L_BRACKET` atom commits at all.
#[test]
fn array_literal_empty() {
    let p = assert_lossless("var a = []\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::ARRAY_LITERAL));
}

#[test]
fn array_literal_produces_one_child_per_element() {
    let p = assert_lossless("var a = [1, 2, 3]\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lit = p
        .syntax()
        .descendants()
        .find_map(ast::ArrayLiteral::cast)
        .expect("one ARRAY_LITERAL");
    assert_eq!(lit.elements().count(), 3);
}

#[test]
fn array_literal_accepts_a_trailing_comma() {
    let p = assert_lossless("var a = [1, 2, ]\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lit = p
        .syntax()
        .descendants()
        .find_map(ast::ArrayLiteral::cast)
        .expect("one ARRAY_LITERAL");
    assert_eq!(lit.elements().count(), 2);
}

#[test]
fn array_literal_elements_may_span_lines() {
    let p = assert_lossless("var a = [\n  1,\n  2,\n]\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    let lit = p
        .syntax()
        .descendants()
        .find_map(ast::ArrayLiteral::cast)
        .expect("one ARRAY_LITERAL");
    assert_eq!(lit.elements().count(), 2);
}

#[test]
fn array_literal_nests() {
    let p = assert_lossless("var a = [[1, 2], [3, 4]]\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(count_node_kind(&p.syntax(), SyntaxKind::ARRAY_LITERAL), 3);
}

/// An array literal is an ordinary atom, so it composes with the rest of
/// the expression grammar (call argument position here) — the same proof
/// `construct_literal_in_call_argument_position` gives the construction
/// initializer.
#[test]
fn array_literal_in_call_argument_position() {
    let p = assert_lossless("var x = size([1, 2, 3])\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::ARRAY_LITERAL));
    assert!(has_node_kind(&p.syntax(), SyntaxKind::ARG_LIST));
}

/// A construction literal composes inside an array element without the
/// no-construct-literal restriction ever engaging — `[` never triggers it
/// (unlike a bare path followed by `{` in a control-flow head, see
/// `a_control_flow_head_does_not_swallow_its_body_brace` above).
#[test]
fn array_literal_elements_may_be_construction_literals() {
    let p = assert_lossless("var a = [Point { x: 1 }, Point { x: 2 }]\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert_eq!(
        count_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL),
        2
    );
}

/// The array literal's own bracket lifts `no_construct_literal` for its
/// elements even when the array itself sits inside a genuinely restricted
/// head (`head_expression`, `control_flow.rs`'s `if`/`while`/`for-in`) —
/// unlike a bare path followed by `{`, the brackets already disambiguate
/// where the head's expression ends, so a construction literal composes
/// freely as an element without needing the parenthesized-restoration
/// escape hatch `parentheses_restore_the_construct_literal_inside_a_control_flow_head`
/// exercises above.
#[test]
fn array_literal_in_a_for_in_head_still_allows_construction_literal_elements() {
    let p = assert_lossless("var x = { for q in [Point { x: 1 }] { 1; } };\n");
    assert!(p.errors().is_empty(), "errors: {:?}", p.errors());
    assert!(has_node_kind(&p.syntax(), SyntaxKind::ARRAY_LITERAL));
    assert_eq!(
        count_node_kind(&p.syntax(), SyntaxKind::CONSTRUCT_LITERAL),
        1
    );
}

#[test]
fn unterminated_array_literal_never_panics() {
    let src = "var a = [1, 2\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
}

#[test]
fn garbage_inside_an_array_literal_never_panics() {
    let src = "var a = [ @@@ ]\n";
    let p = parse(src);
    assert_eq!(src, p.syntax().text().to_string(), "lossless round-trip");
    assert!(!p.errors().is_empty());
}

// ── O. Proptest round-trip generator (local to this family file — see  ──
// ── the PR discussion: #1199's own scope is `fuzz_repro.rs`, a         ──
// ── `.brink`-corpus round-trip test, and a new `fuzz/` crate, not      ──
// ── `tests/proptest_native.rs`, so this generator stays local here     ──
// ── rather than claiming ownership of the shared harness. Its keyword  ──
// ── filter reuses the crate's real classifier so it can never drift    ──
// ── from `classify_keyword`'s actual keyword set again.)               ──

mod proptest_roundtrip {
    use super::*;
    use proptest::prelude::*;

    fn arb_ident() -> impl Strategy<Value = String> {
        "[a-z][a-z0-9]{0,5}".prop_filter("not a keyword", |s| {
            crate::lexer::classify_keyword(s) == SyntaxKind::IDENT
        })
    }

    fn arb_integer() -> impl Strategy<Value = String> {
        (0..10_000i64).prop_map(|n| n.to_string())
    }

    fn arb_infix_op() -> impl Strategy<Value = &'static str> {
        prop_oneof![
            Just("+"),
            Just("-"),
            Just("*"),
            Just("/"),
            Just("%"),
            Just("<"),
            Just(">"),
            Just("<="),
            Just(">="),
            Just("=="),
            Just("!="),
            Just("&&"),
            Just("||"),
            Just("or"),
        ]
    }

    /// A self-contained, depth-bounded expression generator covering every
    /// operator this grammar's `infix_binding_power`/`is_prefix_op` know
    /// about, plus calls and parens. Every string this produces is
    /// well-formed by construction, so the round-trip property below
    /// additionally asserts zero parse errors (not just losslessness).
    fn arb_expr() -> impl Strategy<Value = String> {
        let leaf = prop_oneof![
            arb_integer(),
            Just("true".to_string()),
            Just("false".to_string()),
            arb_ident(),
        ];
        leaf.prop_recursive(3, 20, 3, |inner| {
            prop_oneof![
                inner.clone().prop_map(|e| format!("-{e}")),
                inner.clone().prop_map(|e| format!("!{e}")),
                inner.clone().prop_map(|e| format!("({e})")),
                (inner.clone(), arb_infix_op(), inner.clone())
                    .prop_map(|(l, op, r)| format!("{l} {op} {r}")),
                (arb_ident(), prop::collection::vec(inner, 0..=2))
                    .prop_map(|(name, args)| format!("{name}({})", args.join(", "))),
            ]
        })
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(256))]

        #[test]
        fn expr_round_trips_losslessly_and_parses_clean(body in arb_expr()) {
            let src = format!("var x = {body}\n");
            let p = parse(&src);
            prop_assert_eq!(&src, &p.syntax().text().to_string());
            prop_assert!(
                p.errors().is_empty(),
                "well-formed generated expr `{src}` produced errors: {:?}",
                p.errors()
            );
        }

        #[test]
        fn expr_as_call_argument_round_trips_losslessly(body in arb_expr()) {
            let src = format!("var x = wrap({body})\n");
            let p = parse(&src);
            prop_assert_eq!(&src, &p.syntax().text().to_string());
            prop_assert!(
                p.errors().is_empty(),
                "well-formed generated call-arg `{src}` produced errors: {:?}",
                p.errors()
            );
        }
    }
}