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
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
//! Concrete syntax tree (CST) builder over the lossless [`lex`]
//! output. P2 of the rowan rewrite — translates the existing winnow
//! grammar into rowan `GreenNode`s while preserving every source byte
//! (including whitespace and comments) as first-class tokens.
//!
//! Architecture
//! ============
//!
//! - `Parser` wraps the flat `(SyntaxKind, &str)` token stream from
//! [`lex::lex`] plus a `rowan::GreenNodeBuilder` writing the tree.
//! - "Skip-trivia" helpers (`current`, `at`, `nth`) ignore whitespace
//! and comments, so productions can pattern-match on meaningful
//! structure without ever forgetting to write a trivia token to the
//! tree.
//! - Trivia is flushed to the builder lazily — emitted as siblings
//! *just before* the next meaningful token. The "right" home for a
//! trailing comment (does it belong to the closing brace, or to the
//! next pair?) is decided by `bump`'s flush order.
//! - Each grammar production is a function on `&mut Parser`. They
//! call `open(kind)` / `close()` to mark composite nodes. Failures
//! recover via `error_recover(sync_set)` which emits an ERROR node
//! and synchronises to the nearest token in `sync_set`.
//!
//! Scope
//! =====
//!
//! P2 (now complete) covers the full surface grammar:
//!
//! * Literals, identifiers, dotted paths, references.
//! * Lists, dicts (with pair attributes + method-shorthand closures
//! + typed keys), list comprehensions.
//! * Unary, binary (Pratt-precedence), call, postfix `.field` /
//! `[index]`, parenthesised closure (`(p) [-> R] => body`).
//! * `expr match { ... }` and `expr where { ... }` postfix forms.
//! * F-string decomposition into `F_STRING` + `F_STRING_LITERAL`
//! chunks + nested `F_STRING_INTERPOLATION` sub-nodes (whose
//! children are ordinary Relon expressions).
//! * `TYPE_NODE` — dotted paths, generics, optional `?`.
//! * Directive bodies dispatched by name: `#schema`/`#extend`
//! (name + generics + body + optional `with`), `#import`
//! (`<spec> from "path"`), `#main(typed-params) [-> Ret]`.
//!
//! P3 lives in `crate::ast` — typed-AST wrappers on top of this
//! CST. P4 will migrate downstream crates (analyzer, evaluator,
//! fmt, wasm, lsp) onto the new wrappers.
use crate::lex;
use crate::lex::utf8_codepoint_len_for_cst as utf8_codepoint_len;
use crate::syntax::{RelonLanguage, SyntaxKind, SyntaxNode};
use rowan::{Checkpoint, GreenNodeBuilder};
/// One parse failure with an attached byte position. Always reachable
/// from the resulting CST through the spanning `ERROR` node, but
/// surfacing them separately gives callers (LSP diagnostics, CLI
/// pretty-printer) a flat list without re-walking the tree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
pub message: String,
/// Byte offset into the original source where recovery began.
pub offset: usize,
}
/// Successful parse result. `green` is the lossless tree; `errors`
/// is the (possibly empty) list of parse errors emitted along the
/// way. The parser NEVER returns `Err` — every input shape produces
/// a tree, with `ERROR` nodes covering unparseable spans.
#[derive(Debug, Clone)]
pub struct Parse {
green: rowan::GreenNode,
pub errors: Vec<ParseError>,
}
impl Parse {
/// Wrap the green tree as a typed [`SyntaxNode`] for traversal.
pub fn syntax(&self) -> SyntaxNode {
SyntaxNode::new_root(self.green.clone())
}
/// Returns `true` when at least one parse error was emitted.
pub fn has_errors(&self) -> bool {
!self.errors.is_empty()
}
}
/// Top-level entry. Always produces a `Parse` — never panics, never
/// returns `Err`. Bytes that don't fit any production are absorbed
/// into `ERROR` nodes; the round-trip invariant holds regardless.
pub fn parse_cst(source: &str) -> Parse {
let tokens = lex::lex(source);
let mut parser = Parser::new(tokens);
parser.parse_document();
parser.finish()
}
// =====================================================================
// Parser state.
// =====================================================================
struct Parser<'a> {
/// The flat token stream the parser is currently consuming. We
/// own the vec so f-string interpolation sub-parses can swap in
/// a transient inner-token list without lifetime gymnastics —
/// the inner `&str` slices still point into the original source.
tokens: Vec<(SyntaxKind, &'a str)>,
pos: usize,
builder: GreenNodeBuilder<'static>,
errors: Vec<ParseError>,
/// Running byte offset — kept in sync with `pos` so we can record
/// error positions without re-walking.
cursor_byte: usize,
}
impl<'a> Parser<'a> {
fn new(tokens: Vec<(SyntaxKind, &'a str)>) -> Self {
Self {
tokens,
pos: 0,
builder: GreenNodeBuilder::new(),
errors: Vec::new(),
cursor_byte: 0,
}
}
fn finish(self) -> Parse {
// `parse_document` is responsible for emitting every token
// INSIDE the root DOCUMENT node — rowan requires it. The
// `finish()` call here just hands ownership of the green
// tree back.
debug_assert!(
self.pos >= self.tokens.len(),
"{} tokens unflushed at parse end",
self.tokens.len() - self.pos
);
Parse {
green: self.builder.finish(),
errors: self.errors,
}
}
// ----- token-stream introspection ----------------------------------
/// Kind of the next *non-trivia* token, or `None` if EOI.
fn current(&self) -> Option<SyntaxKind> {
self.nth(0)
}
/// Kind of the `n`-th non-trivia token ahead (0 = current), or
/// `None` if there aren't that many. Useful for productions that
/// need 1-token lookahead.
fn nth(&self, n: usize) -> Option<SyntaxKind> {
let mut idx = self.pos;
let mut left = n;
while idx < self.tokens.len() {
let kind = self.tokens[idx].0;
if kind.is_trivia() {
idx += 1;
continue;
}
if left == 0 {
return Some(kind);
}
left -= 1;
idx += 1;
}
None
}
fn at(&self, kind: SyntaxKind) -> bool {
self.current() == Some(kind)
}
fn at_set(&self, set: &[SyntaxKind]) -> bool {
self.current().is_some_and(|k| set.contains(&k))
}
fn at_end(&self) -> bool {
self.current().is_none()
}
// ----- consumption --------------------------------------------------
/// Emit any pending trivia tokens to the builder. Trivia tokens
/// (whitespace, comments) are skipped by `current` / `at` but
/// still need to land in the tree — this writes them flush
/// against whatever production opened most recently.
fn flush_trivia(&mut self) {
while self.pos < self.tokens.len() {
let (kind, text) = self.tokens[self.pos];
if !kind.is_trivia() {
return;
}
self.builder
.token(RelonLanguage::kind_to_raw_static(kind), text);
self.cursor_byte += text.len();
self.pos += 1;
}
}
/// Consume the next non-trivia token and emit it to the builder,
/// preceded by any pending trivia. Panics in tests if called at
/// EOI — productions should guard with `current()` first.
fn bump(&mut self) {
self.flush_trivia();
if self.pos >= self.tokens.len() {
debug_assert!(false, "bump() past end of input");
return;
}
let (kind, text) = self.tokens[self.pos];
self.builder
.token(RelonLanguage::kind_to_raw_static(kind), text);
self.cursor_byte += text.len();
self.pos += 1;
}
/// Consume the next non-trivia token if it matches `kind`.
/// Returns `true` on consume.
fn eat(&mut self, kind: SyntaxKind) -> bool {
if self.at(kind) {
self.bump();
true
} else {
false
}
}
/// Consume `kind` or emit a parse error. Returns `true` on
/// success; on failure leaves the cursor where it was and pushes
/// to `errors`. Productions that need to keep going should follow
/// `expect` with `error_recover` for proper sync behaviour.
fn expect(&mut self, kind: SyntaxKind) -> bool {
if self.eat(kind) {
true
} else {
self.error(format!("expected {kind:?}, found {:?}", self.current()));
false
}
}
fn error(&mut self, message: impl Into<String>) {
self.errors.push(ParseError {
message: message.into(),
offset: self.cursor_byte,
});
}
/// Wrap the next token (or a synthetic empty span) in an `ERROR`
/// node and push an error. Used as a one-shot way to mark an
/// unexpected leaf without entering recovery.
fn error_at_current(&mut self, message: impl Into<String>) {
self.error(message);
self.open(SyntaxKind::ERROR);
if !self.at_end() {
self.bump();
}
self.close();
}
/// Emit an `ERROR` node spanning every token until one of
/// `sync_set` is reached (or EOI). The error message is recorded
/// at the offset where recovery started.
fn error_recover(&mut self, message: impl Into<String>, sync_set: &[SyntaxKind]) {
self.error(message);
self.open(SyntaxKind::ERROR);
while !self.at_end() && !self.at_set(sync_set) {
self.bump();
}
self.close();
}
/// Canonical "back to a sane structural boundary" sync set: the
/// closing punctuators a dict / list / call would resume at, plus
/// the directive `#` head. Productions that recover with this set
/// re-enter their parent's punctuation-aware loop on the next
/// iteration. Used by the few productions that don't know which
/// container they're inside; container-specific recovery sites
/// keep narrower sets (`COMMA` + their own closing bracket).
const STRUCTURAL_SYNC: &'static [SyntaxKind] = &[
SyntaxKind::COMMA,
SyntaxKind::R_BRACE,
SyntaxKind::R_BRACK,
SyntaxKind::R_PAREN,
SyntaxKind::HASH,
];
// ----- node bracketing ---------------------------------------------
fn open(&mut self, kind: SyntaxKind) {
// Order matters: `start_node` MUST come before `flush_trivia`
// so any pending whitespace / comments land INSIDE the new
// node (as leading trivia of its first child) rather than as
// siblings of the node at the parent level. Flushing first
// would also break the very-first `open(DOCUMENT)` call —
// leading file trivia would end up at rowan's root level,
// violating the "exactly one root" invariant.
self.builder
.start_node(RelonLanguage::kind_to_raw_static(kind));
self.flush_trivia();
}
fn checkpoint(&mut self) -> Checkpoint {
// Checkpoint snaps to "right after any pending trivia" —
// `open_at(ck, ..)` wraps the construct that follows, NOT
// the trivia in front of it. Otherwise a comment before a
// binary expression would get pulled inside the
// `BINARY_EXPR` node, which is the wrong attachment.
self.flush_trivia();
self.builder.checkpoint()
}
fn open_at(&mut self, ck: Checkpoint, kind: SyntaxKind) {
self.builder
.start_node_at(ck, RelonLanguage::kind_to_raw_static(kind));
}
fn close(&mut self) {
self.builder.finish_node();
}
// =================================================================
// Productions.
// =================================================================
/// Top-level: zero-or-more attributes, then one document value.
/// The whole thing is wrapped in a `DOCUMENT` node so the round
/// trip walks from a single root.
fn parse_document(&mut self) {
self.open(SyntaxKind::DOCUMENT);
// Leading directives / decorators stacked above the root
// value. The grammar permits them at file scope (e.g.
// `#schema X { ... }` files with no separate value body).
while self.at(SyntaxKind::HASH) || self.at(SyntaxKind::AT) {
self.parse_attribute();
}
// The root value. EOI is fine — files like
// `#schema X { ... }` end after the directive's body.
if !self.at_end() {
self.parse_expr();
}
// Anything left over is unexpected trailing input — wrap as
// ERROR so the round-trip stays whole.
if !self.at_end() {
self.error_recover("trailing input after root value", &[]);
}
// Trailing trivia (final newline, footer comments) MUST land
// inside DOCUMENT — rowan only accepts one root node, and
// tokens emitted after `close()` would have nowhere to live.
self.flush_trivia();
self.close();
}
/// `@name(...)` or `#name <body>`. Decorator bodies are always
/// `(args)` (or absent) and decorator names may be dotted
/// (`@ensure.int`, `@module.fn`); directive bodies branch on the
/// name: `schema` / `extend` capture `name <T, U>? body? (with {})?`,
/// `import` captures `<spec> from "path"`, `main` captures
/// `( typed-params ) [-> Ret]`, the remaining names dispatch via
/// [`directive_shape`] — bare directives consume no body so they
/// can sit cleanly above the field they decorate, value directives
/// take exactly one trailing expression.
fn parse_attribute(&mut self) {
let is_directive = self.at(SyntaxKind::HASH);
let kind = if is_directive {
SyntaxKind::DIRECTIVE
} else {
SyntaxKind::DECORATOR
};
self.open(kind);
self.bump(); // # or @
let name_text = if self.at(SyntaxKind::IDENT) {
let text = self.current_text();
self.bump();
text
} else {
self.error_at_current("expected attribute name");
None
};
if !is_directive {
// Decorator — name may be dotted (`@ensure.at_least`).
// Body is always `(args)` or empty.
while self.at(SyntaxKind::DOT) {
self.bump();
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected identifier after `.` in decorator name");
break;
}
}
if self.at(SyntaxKind::L_PAREN) {
self.parse_call_args();
}
self.close();
return;
}
// Directive — dispatch on name. Unknown directive names take a
// single optional expression body to match the legacy parser's
// permissive fallback.
let shape = name_text
.and_then(crate::directive::directive_shape)
.unwrap_or(crate::DirectiveShape::Value);
match shape {
crate::DirectiveShape::Bare => {
// No body. `#internal`, `#relaxed`, `#unstrict`, `#native`.
}
crate::DirectiveShape::Value => {
if self.is_attribute_body_start() {
self.parse_expr();
}
}
crate::DirectiveShape::NameBody => self.parse_directive_name_body(),
crate::DirectiveShape::Enum => self.parse_directive_enum(),
crate::DirectiveShape::Import => self.parse_directive_import(),
crate::DirectiveShape::Main => self.parse_directive_main(),
}
self.close();
}
/// `#enum Name<T, U>? { Variant, Variant { field: Type }, Variant(Type) }`.
/// The lowerer turns this into the internal tagged-enum schema form.
fn parse_directive_enum(&mut self) {
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
return;
}
if self.at(SyntaxKind::LT) {
self.bump();
while !self.at(SyntaxKind::GT) && !self.at_end() {
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected generic param");
break;
}
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::GT);
}
if !self.eat(SyntaxKind::L_BRACE) {
return;
}
while !self.at(SyntaxKind::R_BRACE) && !self.at_end() {
if self.at(SyntaxKind::COMMA) {
self.bump();
continue;
}
self.open(SyntaxKind::ENUM_VARIANT);
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected enum variant name");
self.close();
break;
}
if self.at(SyntaxKind::L_BRACE) {
self.bump();
while !self.at(SyntaxKind::R_BRACE) && !self.at_end() {
if self.at(SyntaxKind::COMMA) {
self.bump();
continue;
}
self.open(SyntaxKind::ENUM_VARIANT_FIELD);
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected enum variant field name");
}
self.expect(SyntaxKind::COLON);
self.parse_type();
self.close();
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::R_BRACE);
} else if self.at(SyntaxKind::L_PAREN) {
self.parse_tuple_type();
}
self.close();
if !self.eat(SyntaxKind::COMMA) && !self.at(SyntaxKind::R_BRACE) {
self.error_at_current("expected `,` or `}` after enum variant");
break;
}
}
self.expect(SyntaxKind::R_BRACE);
}
/// `#schema Name <T, U>? body? (with { methods... })?`. The body
/// is whatever expression follows the name + generics (typically
/// a dict but the parser accepts any expression — the analyzer
/// emits a diagnostic when it isn't a dict). The trailing `with`
/// block is optional and may also follow a body-less `#schema X`
/// declaration.
fn parse_directive_name_body(&mut self) {
// Optional declared name.
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
return;
}
// Optional generic param list `<T, U>` — bare identifiers.
if self.at(SyntaxKind::LT) {
self.bump();
while !self.at(SyntaxKind::GT) && !self.at_end() {
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected generic param");
break;
}
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::GT);
}
// The body is everything up to (a) the next attribute, (b)
// the `with` keyword, or (c) the dict-field separator (`:`
// / `,` / `}` / EOI). Special-case the `with`-only shape
// (`#schema X with { ... }`) by skipping the body when we
// see `with` immediately.
let saw_with = self.at(SyntaxKind::IDENT) && self.current_text() == Some("with");
// v1 accepts an optional `:` separator between schema name and
// body: `#schema Image: { name: String }` is equivalent to
// `#schema Image { name: String }`. The legacy combinator chain
// consumed the `:` as part of the directive; the CST does the
// same so the `is_attribute_body_start` check below sees the
// body proper. Without this, the dict-field grammar would
// (correctly!) parse `Image:` as a malformed dict field after
// mistaking the directive for body-less.
if !saw_with && self.at(SyntaxKind::COLON) {
self.bump();
}
if !saw_with && self.is_attribute_body_start() {
// Guard: when the next chars are `Ident:` / `Ident,` we
// must not consume them — they belong to a dict field
// following `#schema X` in a `: ...` context.
if !self.peek_attribute_terminator() {
// Schema bodies are typically dicts (`#schema U { ... }`)
// but the grammar also accepts a type-alias body. When the body
// looks like a bare type expression — IDENT immediately
// followed by `<...>` — parse it as a type so the
// string-literal generic args don't surprise the Pratt
// expression grammar (which would treat `<` as a
// binary comparison).
if self.peek_is_bare_type_body() {
self.parse_type();
} else {
self.parse_expr();
}
}
}
// Optional `with { ... }` block — a structured method list.
// The legacy `opt_parse_with_block` (`directive.rs`) drives the
// shape: leading pragma stack (`#derive` / `#native` /
// `#internal` / `#no_auto_derive`), then a `name<T>?(p: T,
// ...) -> Ret (: body)?` declaration. We emit each method as
// a SCHEMA_METHOD node so the typed-AST layer can read the
// structure cheaply.
if self.at(SyntaxKind::IDENT) && self.current_text() == Some("with") {
self.bump();
if self.at(SyntaxKind::L_BRACE) {
self.parse_schema_with();
}
}
}
/// True when the upcoming token stream is an IDENT followed
/// immediately (no intervening whitespace) by `<` — a type-alias
/// body shape such as `Int` / `List<T>`. Used by
/// `parse_directive_name_body` to disambiguate the type-body shape
/// from a regular expression body. The IDENT-and-no-`<` case
/// (bare-type body like `#schema MyAlias String`) is also
/// classified as "type body" — the body is a single primitive
/// type identifier without generics.
fn peek_is_bare_type_body(&self) -> bool {
if !self.at(SyntaxKind::IDENT) {
return false;
}
// Only commit to the type body if the IDENT is one of the
// known type heads (`Int`, `String`, `Bool`, `List`, `Dict`,
// `Any`, `Float`) — otherwise a regular
// expression with a leading IDENT is the safer fallback.
let head = self.current_text().unwrap_or("");
if !matches!(
head,
"Int" | "String" | "Bool" | "Float" | "Any" | "List" | "Dict"
) {
return false;
}
// Allow both primitive aliases (`Int`) and generic containers
// (`List<T>`) as type-body starts.
let head_idx = self.pos_skip_trivia();
let mut idx = head_idx + 1;
let mut had_ws = false;
while idx < self.tokens.len() && self.tokens[idx].0.is_trivia() {
had_ws = true;
idx += 1;
}
if self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::LT) && !had_ws {
return true;
}
// Bare type identifier (`#schema MyAlias String`) — only
// accept when nothing else follows on the line. We approximate
// "nothing else" by checking the next non-trivia token isn't
// a typical expression-continuation symbol.
matches!(
self.tokens.get(idx).map(|(k, _)| *k),
Some(SyntaxKind::HASH) | Some(SyntaxKind::L_BRACE) | None
)
}
/// `with { (pragma | method)* }` — body of a `#schema` / `#extend`
/// directive. Lossless: every byte (whitespace, comments, leading
/// pragmas) sits inside the [`SCHEMA_WITH`] node, with each method
/// declaration wrapped in its own [`SCHEMA_METHOD`] child.
fn parse_schema_with(&mut self) {
self.open(SyntaxKind::SCHEMA_WITH);
self.bump(); // {
while !self.at(SyntaxKind::R_BRACE) && !self.at_end() {
// Method declarations are introduced by either a pragma
// (`#derive` / `#native` / `#internal` / `#no_auto_derive`)
// or directly by a method name. We greedily group leading
// pragmas with the next method into one SCHEMA_METHOD node
// — if no method follows (e.g. trailing schema-level
// `#no_auto_derive`), the directives sit at the
// SCHEMA_WITH level as siblings.
if self.at(SyntaxKind::HASH) {
let ck = self.checkpoint();
let mut had_method_pragma = false;
while self.at(SyntaxKind::HASH) {
let name = self.directive_name_after_hash();
if matches!(
name.as_deref(),
Some("derive") | Some("native") | Some("internal")
) {
had_method_pragma = true;
}
self.parse_attribute();
}
if self.at(SyntaxKind::IDENT) && !self.at_method_terminator() {
self.open_at(ck, SyntaxKind::SCHEMA_METHOD);
self.parse_schema_method_after_pragmas();
self.close();
} else if had_method_pragma {
// Pragma stack without a method — surface a recovery
// error to mirror the legacy "stray method pragma"
// diagnostic but keep parsing.
self.error(
"expected method declaration after `#derive` / `#native` / `#internal`",
);
}
continue;
}
if self.at(SyntaxKind::IDENT) {
self.open(SyntaxKind::SCHEMA_METHOD);
self.parse_schema_method_after_pragmas();
self.close();
continue;
}
// Unexpected token inside the with-block — recover to the
// next likely start of a method (HASH / IDENT / R_BRACE).
self.error_recover(
"expected method or pragma inside `with { ... }`",
&[SyntaxKind::HASH, SyntaxKind::IDENT, SyntaxKind::R_BRACE],
);
}
self.expect(SyntaxKind::R_BRACE);
self.close();
}
/// True when the upcoming non-trivia token is the with-block
/// terminator (`}`) — used to spot a pragma stack with no method
/// trailing it without confusing it for a normal method header.
fn at_method_terminator(&self) -> bool {
matches!(self.current(), Some(SyntaxKind::R_BRACE)) || self.at_end()
}
/// Peek the IDENT immediately after a HASH at the current position
/// (skipping trivia). Returns `None` if `#` isn't followed by an
/// identifier.
fn directive_name_after_hash(&self) -> Option<String> {
let mut idx = self.pos_skip_trivia();
if self.tokens.get(idx).map(|(k, _)| *k) != Some(SyntaxKind::HASH) {
return None;
}
idx += 1;
while idx < self.tokens.len() && self.tokens[idx].0.is_trivia() {
idx += 1;
}
match self.tokens.get(idx) {
Some((SyntaxKind::IDENT, text)) => Some((*text).to_string()),
_ => None,
}
}
/// Parse a single method declaration inside a `with { ... }` block.
/// Caller has already opened a SCHEMA_METHOD node and emitted any
/// leading pragma directives. Shape:
///
/// IDENT GenericParams? '(' (Param (',' Param)*)? ')' '->' Type (':' Expr)?
///
/// Each parameter takes the named form `name: Type` (opposite of
/// `#main`'s `Type name`), reusing the existing CLOSURE_PARAM
/// wrapper to keep the typed-AST layer simple. The body is omitted
/// for `#native` methods.
fn parse_schema_method_after_pragmas(&mut self) {
// Method name.
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected method name");
return;
}
// Optional method-level generics `<U, V>`.
if self.at(SyntaxKind::LT) {
self.bump();
while !self.at(SyntaxKind::GT) && !self.at_end() {
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected method generic parameter");
break;
}
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::GT);
}
// Parameter list `(name: Type, ...)`.
if !self.expect(SyntaxKind::L_PAREN) {
return;
}
while !self.at(SyntaxKind::R_PAREN) && !self.at_end() {
self.parse_schema_method_param();
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::R_PAREN);
// `-> ReturnType` — required by the analyzer-level grammar
// (every with-block method declares its return), but the CST
// accepts the missing-arrow shape so older test fixtures
// that elided the return type still round-trip cleanly.
if self.eat(SyntaxKind::THIN_ARROW) {
self.parse_type();
}
// Optional `: body`. Methods marked `#native` omit it; for
// others the analyzer enforces presence.
if self.eat(SyntaxKind::COLON) {
self.parse_expr();
}
}
/// One schema-method parameter: `name: Type`. Lossless — emitted
/// inside a CLOSURE_PARAM node so the typed-AST layer can reuse
/// the existing wrapper.
fn parse_schema_method_param(&mut self) {
self.open(SyntaxKind::CLOSURE_PARAM);
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected parameter name");
self.close();
return;
}
if self.eat(SyntaxKind::COLON) {
self.parse_type();
} else {
self.error("expected `:` in schema method parameter");
}
self.close();
}
/// `#import <spec> from "path"`. `<spec>` is one of
/// `*`, `{ a, b as c }`, or a single identifier.
fn parse_directive_import(&mut self) {
if self.at(SyntaxKind::STAR) {
self.bump();
} else if self.at(SyntaxKind::L_BRACE) {
// Destructure list `{ a, b as c }` — each entry is an
// IDENT optionally followed by `as IDENT`. This is NOT a
// dict, so we don't reuse `parse_dict`. The legacy
// `parse_import_spec` accepts this shape; the typed-AST
// layer carries the entries on `DirectiveImportSpec`.
self.parse_import_destructure();
} else if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected import spec");
return;
}
if self.at(SyntaxKind::IDENT) && self.current_text() == Some("from") {
self.bump();
} else {
self.error("expected `from` in #import");
return;
}
if self.at(SyntaxKind::STRING) {
self.bump();
} else {
self.error_at_current("expected path string in #import");
return;
}
// Optional integrity pin `<algo>:"<hex>"`. Accept anything of
// the shape `IDENT COLON STRING`; the algorithm name and hex
// are validated by the analyzer so the diagnostic span lands
// on the real source position rather than on the parser's
// current cursor.
if self.at(SyntaxKind::IDENT) {
self.bump();
if self.at(SyntaxKind::COLON) {
self.bump();
} else {
self.error_at_current("expected `:` in #import integrity pin");
return;
}
if self.at(SyntaxKind::STRING) {
self.bump();
} else {
self.error_at_current("expected hex string in #import integrity pin");
}
}
}
fn parse_import_destructure(&mut self) {
debug_assert!(self.at(SyntaxKind::L_BRACE));
self.bump(); // {
loop {
if self.at(SyntaxKind::R_BRACE) || self.at_end() {
break;
}
if self.at(SyntaxKind::IDENT) {
self.bump();
// Optional `as IDENT` alias.
if self.at(SyntaxKind::IDENT) && self.current_text() == Some("as") {
self.bump();
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected identifier after `as` in #import");
}
}
} else {
self.error_recover(
"expected identifier in #import destructure",
&[SyntaxKind::COMMA, SyntaxKind::R_BRACE],
);
}
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::R_BRACE);
}
/// `#main ( type ident, ... ) [-> Type]`. Captures the typed
/// param list directly so the directive node carries the same
/// structure the analyzer needs.
fn parse_directive_main(&mut self) {
if !self.eat(SyntaxKind::L_PAREN) {
self.error("expected `(` after `#main`");
return;
}
while !self.at(SyntaxKind::R_PAREN) && !self.at_end() {
// Each param: `Type ident` (closure-param shape).
self.parse_closure_param();
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::R_PAREN);
// Optional `-> ReturnType`.
if self.eat(SyntaxKind::THIN_ARROW) {
self.parse_type();
}
}
/// True when the next non-trivia token signals "no directive body
/// here, leave the ident for the surrounding grammar" — used by
/// `#schema X: value` (inside a dict) where `X` is the dict key,
/// not the schema-name body.
fn peek_attribute_terminator(&self) -> bool {
let mut idx = self.pos_skip_trivia();
// Skip an IDENT (and an optional generic angle-list).
if self.tokens.get(idx).map(|(k, _)| *k) != Some(SyntaxKind::IDENT) {
return false;
}
idx += 1;
while idx < self.tokens.len() && self.tokens[idx].0.is_trivia() {
idx += 1;
}
matches!(
self.tokens.get(idx).map(|(k, _)| *k),
Some(SyntaxKind::COLON) | Some(SyntaxKind::COMMA) | Some(SyntaxKind::R_BRACE)
)
}
fn is_attribute_body_start(&self) -> bool {
self.current().is_some_and(|k| {
matches!(
k,
SyntaxKind::IDENT
| SyntaxKind::NUMBER
| SyntaxKind::STRING
| SyntaxKind::L_BRACE
| SyntaxKind::L_BRACK
// `L_PAREN` covers the parenthesised closure form
// `(p) => body` and parenthesised expressions
// `(a + b)`. Without this, value-shape directives
// like `#default (self) => ...` and
// `#expect (n) => n > 0` would be parsed as
// body-less, leaving the closure for the
// surrounding dict to choke on.
| SyntaxKind::L_PAREN
| SyntaxKind::AMP
| SyntaxKind::MINUS
| SyntaxKind::BANG
| SyntaxKind::STAR
// F-strings start a fresh atom too.
| SyntaxKind::F_STRING_OPEN
)
})
}
// ----- expression entry -------------------------------------------
/// Parse a full expression. Operator precedence is climbed with a
/// Pratt-style loop. Lowest precedence first; primary handles
/// atoms and prefix unaries. `match { ... }` and `where { ... }`
/// trail the binary chain as the outermost postfix forms — they
/// take precedence above ternary etc., matching the winnow
/// grammar in `expr.rs`.
fn parse_expr(&mut self) {
let ck = self.checkpoint();
self.parse_expr_bp(0);
// Ternary: `cond ? then : else`. Bound at expression-tail
// precedence — lower than every binary operator (so the binary
// chain absorbs into `cond`) but higher than the trailing
// `match` / `where` postfix forms (which wrap whatever ternary
// produces). The legacy `parse_ternary` (`expr.rs`) sits at the
// same level — see the precedence chain notes there.
//
// Disambiguation: `?` may also be a path-access prefix
// (`a?.b`, `a?[0]`) or a type-optional marker (`Foo?` inside a
// typed context). Path access is consumed earlier — the CST's
// current postfix loop doesn't fold `?.` / `?[`, but the legacy
// pre-P4 path always took those bytes itself, so no fixture
// reaches this branch with them in postfix position. Type
// optionals only appear inside committed `parse_type` calls
// (match arms, closure params, directive bodies), never at the
// outermost expression level — so seeing `?` here is
// unambiguously a ternary head.
if self.at(SyntaxKind::QUESTION) {
// Guard: don't claim a ternary on `?.` / `?[`. Those forms
// belong to path access and are handled (or rejected) by the
// atom layer; consuming `?` here would steal the prefix.
let next = self.nth(1);
if !matches!(next, Some(SyntaxKind::DOT) | Some(SyntaxKind::L_BRACK)) {
self.open_at(ck, SyntaxKind::TERNARY_EXPR);
self.bump(); // ?
self.parse_expr();
if !self.expect(SyntaxKind::COLON) {
self.close();
return;
}
self.parse_expr();
self.close();
}
}
loop {
if self.at(SyntaxKind::IDENT) && self.current_text() == Some("match") {
// Only commit to MATCH_EXPR when `match` is followed
// by `{` — otherwise it's a bareword called `match`
// somewhere unrelated.
if self.nth(1) == Some(SyntaxKind::L_BRACE) {
self.open_at(ck, SyntaxKind::MATCH_EXPR);
self.bump(); // `match`
self.bump(); // {
while !self.at(SyntaxKind::R_BRACE) && !self.at_end() {
self.parse_match_arm();
if !self.eat(SyntaxKind::COMMA) && !self.at(SyntaxKind::R_BRACE) {
self.error_recover(
"expected `,` or `}` in match",
&[SyntaxKind::COMMA, SyntaxKind::R_BRACE],
);
self.eat(SyntaxKind::COMMA);
}
}
self.expect(SyntaxKind::R_BRACE);
self.close();
continue;
}
}
if self.at(SyntaxKind::IDENT)
&& self.current_text() == Some("where")
&& self.nth(1) == Some(SyntaxKind::L_BRACE)
{
self.open_at(ck, SyntaxKind::WHERE_EXPR);
self.bump(); // `where`
self.parse_dict();
self.close();
continue;
}
break;
}
}
/// One match arm: `pattern: body`. Pattern is one of:
///
/// * a TYPE_NODE (`Up`, `Int`) for existing unit/schema patterns;
/// * `*` for wildcard;
/// * a Rust-like enum payload pattern (`Pair(a, b)`,
/// `Email { address, subject: s }`).
fn parse_match_arm(&mut self) {
self.open(SyntaxKind::MATCH_ARM);
if self.at(SyntaxKind::UNDERSCORE) {
self.open(SyntaxKind::WILDCARD);
self.bump();
self.close();
} else if self.at(SyntaxKind::STAR) {
// `*` is no longer the pattern wildcard — the catch-all arm
// is now written `_`. Keep the `*` lexeme inside a WILDCARD
// node (so recovery stays structured) but flag the precise
// migration so the diagnostic points at the new spelling.
self.open(SyntaxKind::WILDCARD);
self.error_at_current(
"`*` is no longer a match wildcard — use `_` for the catch-all arm",
);
self.bump();
self.close();
} else if self.looks_like_match_payload_pattern() {
self.parse_match_pattern();
} else if self.at(SyntaxKind::IDENT) {
self.parse_type();
} else {
self.error_at_current("expected match-arm pattern");
}
if self.eat(SyntaxKind::COLON) {
self.parse_expr();
} else {
self.error("expected `:` in match arm");
}
self.close();
}
fn looks_like_match_payload_pattern(&self) -> bool {
if !self.at(SyntaxKind::IDENT) {
return false;
}
let mut idx = self.pos_skip_trivia() + 1;
while idx < self.tokens.len() && self.tokens[idx].0.is_trivia() {
idx += 1;
}
while self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::DOT) {
idx += 1;
while idx < self.tokens.len() && self.tokens[idx].0.is_trivia() {
idx += 1;
}
if self.tokens.get(idx).map(|(k, _)| *k) != Some(SyntaxKind::IDENT) {
return false;
}
idx += 1;
while idx < self.tokens.len() && self.tokens[idx].0.is_trivia() {
idx += 1;
}
}
matches!(
self.tokens.get(idx).map(|(k, _)| *k),
Some(SyntaxKind::L_PAREN | SyntaxKind::L_BRACE)
)
}
fn parse_match_pattern(&mut self) {
self.open(SyntaxKind::MATCH_PATTERN);
self.expect(SyntaxKind::IDENT);
while self.at(SyntaxKind::DOT) {
self.bump();
self.expect(SyntaxKind::IDENT);
}
if self.at(SyntaxKind::L_PAREN) {
self.bump();
while !self.at(SyntaxKind::R_PAREN) && !self.at_end() {
if self.at(SyntaxKind::UNDERSCORE) || self.at(SyntaxKind::IDENT) {
self.bump();
} else if self.at(SyntaxKind::STAR) {
self.error_at_current(
"`*` is no longer a pattern wildcard — use `_` to ignore a payload slot",
);
self.bump();
} else {
self.error_at_current("expected tuple pattern binding");
break;
}
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::R_PAREN);
} else if self.at(SyntaxKind::L_BRACE) {
self.bump();
while !self.at(SyntaxKind::R_BRACE) && !self.at_end() {
if self.at(SyntaxKind::IDENT) {
self.bump();
if self.eat(SyntaxKind::COLON) {
if self.at(SyntaxKind::UNDERSCORE) || self.at(SyntaxKind::IDENT) {
self.bump();
} else if self.at(SyntaxKind::STAR) {
self.error_at_current(
"`*` is no longer a pattern wildcard — use `_` to ignore a payload slot",
);
self.bump();
} else {
self.error_at_current("expected struct pattern binding");
break;
}
}
} else {
self.error_at_current("expected struct pattern field");
break;
}
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::R_BRACE);
}
self.close();
}
fn parse_expr_bp(&mut self, min_bp: u8) {
let lhs_ck = self.checkpoint();
self.parse_unary();
while let Some(op) = self.current() {
let Some((lbp, rbp)) = infix_bp(op) else {
break;
};
if lbp < min_bp {
break;
}
self.open_at(lhs_ck, SyntaxKind::BINARY_EXPR);
if op == SyntaxKind::PLUS_PLUS {
// `++` was parseable but never executable (the
// evaluator always trapped UnsupportedOperator).
// String concatenation is spelled `+`; keep consuming
// the token inside the BINARY_EXPR node (so recovery
// stays structured and the round-trip stays lossless)
// but flag the precise migration. Plain `error` — not
// `error_at_current`, which would wrap the token in an
// extra ERROR node and skip the normal bump below.
self.error("`++` is not an operator — use `+` to concatenate strings");
}
self.bump();
self.parse_expr_bp(rbp);
self.close();
}
}
/// Prefix-unary or atom. Postfix call / index / dot are wrapped
/// here via checkpoint.
fn parse_unary(&mut self) {
if self.at_set(&[SyntaxKind::MINUS, SyntaxKind::BANG, SyntaxKind::PLUS]) {
self.open(SyntaxKind::UNARY_EXPR);
self.bump();
self.parse_unary();
self.close();
return;
}
self.parse_postfix();
}
/// Atom with postfix suffixes (`.field`, `[i]`, `(args)`,
/// plus optional-chain `?.field` / `?[i]`).
fn parse_postfix(&mut self) {
let ck = self.checkpoint();
self.parse_atom();
loop {
if self.at(SyntaxKind::L_PAREN) {
self.open_at(ck, SyntaxKind::CALL_EXPR);
self.parse_call_args();
self.close();
} else if self.at(SyntaxKind::DOT)
|| self.at(SyntaxKind::L_BRACK)
|| (self.at(SyntaxKind::QUESTION)
&& matches!(
self.nth(1),
Some(SyntaxKind::DOT) | Some(SyntaxKind::L_BRACK)
))
{
// Path access — fold into VARIABLE_EXPR so dotted
// paths like `a.b.c` end up as a single node. v1.8
// positional access `xs.0` (number after `.`) is the
// tuple/list index form — accepted alongside `.field`.
// Optional chaining (`a?.b`, `a?[0]`) consumes the `?`
// as a prefix on the next segment; the typed-AST
// marks the segment as optional.
self.open_at(ck, SyntaxKind::VARIABLE_EXPR);
loop {
let is_optional_prefix = self.at(SyntaxKind::QUESTION)
&& matches!(
self.nth(1),
Some(SyntaxKind::DOT) | Some(SyntaxKind::L_BRACK)
);
if is_optional_prefix {
self.bump(); // ?
} else if !self.at(SyntaxKind::DOT) && !self.at(SyntaxKind::L_BRACK) {
break;
}
if self.at(SyntaxKind::DOT) {
self.bump();
if self.at(SyntaxKind::IDENT) || self.at(SyntaxKind::NUMBER) {
self.bump();
} else {
self.error_at_current("expected identifier or index after `.`");
}
} else if self.at(SyntaxKind::L_BRACK) {
// `[ index ]`
self.bump();
self.parse_expr();
self.expect(SyntaxKind::R_BRACK);
} else {
break;
}
}
self.close();
} else {
break;
}
}
}
fn parse_atom(&mut self) {
// Leading attributes (`#brand T {...}` / `@decorator(x) expr`)
// stack above the atom they decorate. The CST keeps them as
// siblings of the atom inside whatever node the caller opened
// (typically a DICT_FIELD value, a LIST element, or a function
// argument). The legacy parser handled this case the same way
// — the attribute decorates whatever expression follows.
while self.at(SyntaxKind::HASH) || self.at(SyntaxKind::AT) {
// Guard: when `#` heads a directive whose body is bare
// (e.g. `#relaxed` standing alone at file scope), there's
// no following expression — `parse_attribute` consumes
// nothing extra, and the loop would spin. Break out the
// moment we see no progress.
let before = self.pos;
self.parse_attribute();
if self.pos == before {
break;
}
}
match self.current() {
Some(SyntaxKind::NUMBER) => {
self.open(SyntaxKind::LITERAL);
self.bump();
self.close();
}
Some(SyntaxKind::STRING) => {
let text = self.tokens[self.pos_skip_trivia()].1;
if text.starts_with('f') {
self.parse_f_string();
} else {
self.open(SyntaxKind::LITERAL);
self.bump();
self.close();
}
}
Some(SyntaxKind::IDENT) => {
// `true` / `false` / `Infinity` / `NaN` and the removed `null` spelling are
// keyword-shaped literals but lex as IDENT — promote
// here so the lowering can decode them via the LITERAL
// walker (which dispatches on the inner token text).
let text = self.tokens[self.pos_skip_trivia()].1;
if matches!(text, "null" | "true" | "false" | "Infinity" | "NaN") {
self.open(SyntaxKind::LITERAL);
self.bump();
self.close();
} else if self.looks_like_variant_ctor() {
// `Enum.Variant { ... }` — at least two dotted
// segments followed by a brace body. Legacy
// `parse_variant_ctor` requires `path.len() >= 2`
// before committing; we match that here so plain
// `foo.bar` member access still falls through to
// the postfix loop as VARIABLE_EXPR.
self.parse_variant_ctor();
} else if self.looks_like_type_atom() {
// Bareword type expressions (`Dict<String, Int>`,
// `List<Int>`, `Foo?`). Legacy `parse_type_expr`
// lowers these into `Expr::Type`; we follow suit so
// forms like `#brand Dict<String, Int> { ... }`
// and `#schema Id Type<Arg>` parse
// cleanly without the Pratt grammar misreading
// `<` as a comparison.
self.parse_type();
} else {
self.open(SyntaxKind::VARIABLE_EXPR);
self.bump();
self.close();
}
}
Some(SyntaxKind::AMP) => self.parse_reference(),
Some(SyntaxKind::L_BRACE) => self.parse_dict(),
Some(SyntaxKind::L_BRACK) => self.parse_list(),
Some(SyntaxKind::L_PAREN) => {
// Three shapes share the leading `(`:
// 1. `(p1, p2) [-> RetType] => body` — a closure.
// 2. `(expr)` — a parenthesised
// group (precedence override, NOT a tuple).
// 3. `()` / `(e,)` / `(e1, e2, ...)` — a tuple value.
// The unit `()` and the trailing-comma 1-tuple
// `(e,)` are the disambiguators that keep `(e)`
// pure grouping.
// Closure lookahead runs first (it can see the trailing
// `=>`); the tuple-vs-group decision is made by scanning
// the parenthesised body for a top-level comma.
if self.try_parse_paren_closure() {
return;
}
self.parse_paren_or_tuple();
}
Some(SyntaxKind::STAR) => {
self.open(SyntaxKind::WILDCARD);
self.bump();
self.close();
}
Some(SyntaxKind::ELLIPSIS) => {
self.open(SyntaxKind::SPREAD_EXPR);
self.bump();
// v1.3 typed spread: `...<Type> expr`. The type hint
// sits between the ellipsis and the source expression
// and disambiguates strict-mode derivation. The inner
// expression follows the type with no separator.
if self.at(SyntaxKind::LT) {
self.bump();
self.parse_type();
self.expect(SyntaxKind::GT);
}
self.parse_unary();
self.close();
}
_ => {
// `parse_atom` is reached from inside dict / list /
// call / argument productions. When no atom shape
// matches the current token, recover to the nearest
// structural boundary so the surrounding loop can
// resume without spinning. We emit a single ERROR
// covering the bad span; the diagnostic message is
// the standard "expected expression."
self.error_recover("expected expression", Self::STRUCTURAL_SYNC);
}
}
}
/// Look ahead past the current IDENT for an `IDENT (DOT IDENT)+ {`
/// sequence — the variant-constructor shape `Enum.Variant { ... }`
/// the legacy `parse_variant_ctor` (`expr.rs`) detects. Returns
/// true only when at least two dotted segments precede the `{`,
/// matching the legacy `path.len() < 2` guard. Anything else
/// (single-segment IDENT, dotted-path member access without a
/// trailing brace) falls through to the regular VARIABLE_EXPR path.
fn looks_like_variant_ctor(&self) -> bool {
if !self.at(SyntaxKind::IDENT) {
return false;
}
let mut idx = self.pos_skip_trivia() + 1;
let advance_trivia = |i: &mut usize, toks: &[(SyntaxKind, &str)]| {
while *i < toks.len() && toks[*i].0.is_trivia() {
*i += 1;
}
};
advance_trivia(&mut idx, &self.tokens);
let mut segs: usize = 1;
while self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::DOT) {
idx += 1;
advance_trivia(&mut idx, &self.tokens);
if self.tokens.get(idx).map(|(k, _)| *k) != Some(SyntaxKind::IDENT) {
return false;
}
idx += 1;
segs += 1;
advance_trivia(&mut idx, &self.tokens);
}
if segs < 2 {
return false;
}
self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::L_BRACE)
}
/// Decide whether the current IDENT atom heads a *type* expression
/// (`Dict<String, Int>`, `List<Int>`, `Foo?`). Legacy
/// `parse_type_expr` (`expr.rs`) lowers such atoms into
/// `Expr::Type`; downstream forms like `#brand Dict<K, V> { ... }`
/// rely on this so the value body isn't misread as `Dict < K`
/// (binary comparison).
///
/// Conservative: only fires when the type-ness signal is
/// unambiguous — the IDENT is a known type head, OR is
/// immediately followed by `<...>` generics (no whitespace
/// before `<`), with the angle balance closing cleanly. A
/// trailing `?` (optional marker) also qualifies.
fn looks_like_type_atom(&self) -> bool {
if !self.at(SyntaxKind::IDENT) {
return false;
}
let head_text = self.current_text().unwrap_or("");
let head_idx = self.pos_skip_trivia();
let mut idx = head_idx + 1;
let mut had_ws = false;
while idx < self.tokens.len() && self.tokens[idx].0.is_trivia() {
had_ws = true;
idx += 1;
}
let known_head = matches!(
head_text,
"Int" | "String" | "Bool" | "Float" | "Any" | "List" | "Dict"
);
// `IDENT < ...>` — type with generics. Requires `<`
// immediately adjacent (no whitespace).
if self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::LT) && !had_ws {
// Scan for the matching `>` while tracking parens.
let mut depth: i32 = 1;
let mut paren_depth: i32 = 0;
let mut j = idx + 1;
while j < self.tokens.len() && depth > 0 {
match self.tokens[j].0 {
SyntaxKind::LT => depth += 1,
SyntaxKind::GT => depth -= 1,
SyntaxKind::L_PAREN => paren_depth += 1,
SyntaxKind::R_PAREN if paren_depth > 0 => paren_depth -= 1,
SyntaxKind::L_BRACE
| SyntaxKind::R_BRACE
| SyntaxKind::R_PAREN
| SyntaxKind::FAT_ARROW
if depth == 1 && paren_depth == 0 =>
{
return false
}
_ => {}
}
j += 1;
}
return depth == 0;
}
// Bare type head with no generics — only fires when the IDENT
// is recognised as a primitive type name. Guarded by what
// follows so plain VARIABLE_EXPR usage doesn't accidentally
// become a TYPE_NODE: must be followed by `{` (type-tagged
// dict body, `#brand T { ... }`) or a stray type-suffix `?`.
// The `?` no longer denotes optionality (that's `Option<T>`),
// but routing it here lets `parse_type` emit a precise "use
// Option<T>" error instead of a confusing ternary misparse.
if known_head {
let next = self.tokens.get(idx).map(|(k, _)| *k);
if matches!(next, Some(SyntaxKind::QUESTION) | Some(SyntaxKind::L_BRACE)) {
return true;
}
}
// `IDENT ? {` — a legacy `Weather? { ... }` shape. The `?` is no
// longer a valid optional marker, but the trailing brace makes
// this unambiguously a (now-erroring) type-tagged value rather
// than a ternary head, so route it into `parse_type` for the
// helpful diagnostic.
if self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::QUESTION) {
let mut j = idx + 1;
while j < self.tokens.len() && self.tokens[j].0.is_trivia() {
j += 1;
}
if self.tokens.get(j).map(|(k, _)| *k) == Some(SyntaxKind::L_BRACE) {
return true;
}
}
false
}
/// `Enum (.Variant)+ { body }` — emit a VARIANT_CTOR node wrapping
/// the dotted path (as plain IDENT + DOT tokens) and the brace
/// body (a regular DICT). Caller has already determined via
/// [`Self::looks_like_variant_ctor`] that we're at the head IDENT
/// of such a construct.
fn parse_variant_ctor(&mut self) {
self.open(SyntaxKind::VARIANT_CTOR);
// Head IDENT.
self.bump();
// Drain `.IDENT*` — guaranteed at least one by the peek.
while self.at(SyntaxKind::DOT) {
self.bump();
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected identifier after `.` in variant constructor");
break;
}
}
// Body is a regular dict literal.
if self.at(SyntaxKind::L_BRACE) {
self.parse_dict();
} else {
self.error("expected `{` in variant constructor");
}
self.close();
}
/// Index into `tokens` of the next non-trivia token. Caller must
/// guarantee `current().is_some()`.
fn pos_skip_trivia(&self) -> usize {
let mut idx = self.pos;
while idx < self.tokens.len() && self.tokens[idx].0.is_trivia() {
idx += 1;
}
idx
}
/// Decompose a leading `f"..."` / `f#"..."#` STRING token into a
/// proper [`F_STRING`] subtree. The original token is consumed
/// as a SINGLE leaf at the lex level, but for the CST we walk
/// its bytes and emit:
///
/// * `F_STRING_OPEN` — `f"` / `f#"` / `f##"` …
/// * `F_STRING_LITERAL` — verbatim text between zones.
/// * `F_STRING_INTERPOLATION` (a sub-node) — wraps a
/// `F_STRING_INTERP_START`, a recursively-parsed expression
/// (using the same flat lex on the interpolation bytes), and a
/// `F_STRING_INTERP_END`.
/// * `F_STRING_CLOSE` — matching `"` / `"#` / `"##` …
///
/// Reuses [`lex::lex`] for the interpolation bytes so any future
/// lexer change is picked up automatically. The whole emission is
/// driven directly by the original byte span — so the round-trip
/// invariant holds without help from the caller.
fn parse_f_string(&mut self) {
// Flush trivia FIRST so the F_STRING node nests under whatever
// production opened most recently. We then refuse to advance
// `self.pos` until we've emitted every sub-piece, so the
// overall byte count matches the original STRING token.
self.flush_trivia();
let tok_idx = self.pos;
let (_kind, full_text): (SyntaxKind, &'a str) = self.tokens[tok_idx];
let start_byte = self.cursor_byte;
// Parse the opening sequence: `f` + zero-or-more `#` + `"`.
let bytes = full_text.as_bytes();
// The lexer already guarantees this token starts with `f`,
// and that `next_is_hash_quote(bytes, 1)` was true, but be
// defensive — bail to plain LITERAL if anything else.
if bytes.first() != Some(&b'f') {
// Should be unreachable given the caller's guard.
self.open(SyntaxKind::LITERAL);
self.bump();
self.close();
return;
}
let mut idx: usize = 1;
while bytes.get(idx) == Some(&b'#') {
idx += 1;
}
if bytes.get(idx) != Some(&b'"') {
// Malformed open — emit the whole thing as a single
// LITERAL so byte-round-trip is preserved.
self.open(SyntaxKind::LITERAL);
self.bump();
self.close();
return;
}
let hash_count = idx - 1;
let open_end = idx + 1;
let mut closing = String::from("\"");
for _ in 0..hash_count {
closing.push('#');
}
// Locate the close. The body starts at `open_end`; we have to
// track interpolation depth so a literal `}` inside an
// interpolation can't be mistaken for the close.
let body_start = open_end;
let close_pos = self.find_fstring_close(bytes, body_start, &closing, hash_count);
let close_pos = match close_pos {
Some(p) => p,
None => {
// Unterminated — fall back to LITERAL.
self.open(SyntaxKind::LITERAL);
self.bump();
self.close();
return;
}
};
// Open the composite node.
self.open(SyntaxKind::F_STRING);
// Emit OPEN.
self.emit_raw_token(SyntaxKind::F_STRING_OPEN, &full_text[..open_end]);
// Walk body, splitting LITERAL chunks vs interpolation zones.
let mut i = body_start;
let mut literal_start = i;
let raw_string = hash_count > 0;
while i < close_pos {
if Self::starts_with_at(bytes, i, b"${") {
if i > literal_start {
self.emit_raw_token(SyntaxKind::F_STRING_LITERAL, &full_text[literal_start..i]);
}
// Find matching `}`.
let interp_start = i;
let interp_body_start = i + 2;
let mut depth: usize = 1;
let mut j = interp_body_start;
while j < close_pos && depth > 0 {
match bytes[j] {
b'{' => {
depth += 1;
j += 1;
}
b'}' => {
depth -= 1;
if depth == 0 {
break;
}
j += 1;
}
b'"' => {
// Skip nested "..." (the lexer always
// pairs them up safely on round-trip).
j = crate::lex::scan_normal_string_for_cst(bytes, j);
}
b => {
// Skip a full codepoint to make progress
// on invalid UTF-8 boundaries.
j += utf8_codepoint_len(b);
}
}
}
if depth != 0 {
// Unterminated interpolation — emit the rest as
// one literal so bytes survive, then stop.
self.emit_raw_token(SyntaxKind::F_STRING_LITERAL, &full_text[i..close_pos]);
literal_start = close_pos;
break;
}
let interp_body_end = j;
let interp_close = j + 1;
// Emit the interpolation sub-node.
self.open(SyntaxKind::F_STRING_INTERPOLATION);
self.emit_raw_token(
SyntaxKind::F_STRING_INTERP_START,
&full_text[interp_start..interp_body_start],
);
// Sub-parse the inner expression. The inner text is a
// self-contained slice; we hand it to a fresh `lex` +
// mini-parser. This is recursive (an interpolation can
// contain another f-string), but the byte-accounting
// works because we splice sub-tokens directly into the
// builder.
self.parse_fstring_interp_inner(&full_text[interp_body_start..interp_body_end]);
self.emit_raw_token(
SyntaxKind::F_STRING_INTERP_END,
&full_text[interp_body_end..interp_close],
);
self.close();
literal_start = interp_close;
i = interp_close;
continue;
}
// Escape handling — only relevant in non-raw f-strings.
if !raw_string && bytes[i] == b'\\' && i + 1 < close_pos {
i += 1 + utf8_codepoint_len(bytes[i + 1]);
continue;
}
i += utf8_codepoint_len(bytes[i]);
}
if literal_start < close_pos {
self.emit_raw_token(
SyntaxKind::F_STRING_LITERAL,
&full_text[literal_start..close_pos],
);
}
// Emit CLOSE.
self.emit_raw_token(SyntaxKind::F_STRING_CLOSE, &full_text[close_pos..]);
self.close();
// Advance the parser past the original STRING token now that
// we've emitted every sub-piece directly.
self.cursor_byte = start_byte + full_text.len();
self.pos = tok_idx + 1;
}
/// Emit a single leaf token directly to the builder (bypassing
/// the lex-token cursor). Used by f-string decomposition; never
/// advances `pos` / `cursor_byte`.
fn emit_raw_token(&mut self, kind: SyntaxKind, text: &str) {
self.builder
.token(RelonLanguage::kind_to_raw_static(kind), text);
}
/// Sub-parser for the inside of `${ ... }` in an f-string. We
/// temporarily swap `self.tokens` with the inner-text lex (the
/// `&str` slices inside still borrow from the original source,
/// so the swapped `Vec` is fully compatible lifetime-wise),
/// run the same Pratt expression grammar, then restore.
fn parse_fstring_interp_inner(&mut self, text: &'a str) {
let inner_tokens: Vec<(SyntaxKind, &'a str)> = crate::lex::lex(text);
// Stash outer state and install the inner stream.
let outer_tokens = std::mem::replace(&mut self.tokens, inner_tokens);
let outer_pos = std::mem::replace(&mut self.pos, 0);
let outer_cursor = self.cursor_byte;
self.cursor_byte = 0;
if !self.at_end() {
self.parse_expr();
}
// Absorb any remaining bytes so the F_STRING_INTERPOLATION
// body has full byte coverage. Trailing whitespace becomes
// trivia naturally; anything else lands in an ERROR node.
if !self.at_end() {
self.error_recover("trailing input in interpolation", &[]);
}
self.flush_trivia();
// Restore outer state.
self.tokens = outer_tokens;
self.pos = outer_pos;
self.cursor_byte = outer_cursor + text.len();
}
fn find_fstring_close(
&self,
bytes: &[u8],
body_start: usize,
closing: &str,
hashes: usize,
) -> Option<usize> {
let raw = hashes > 0;
let mut idx = body_start;
while idx + closing.len() <= bytes.len() {
// Skip past balanced `${...}` interpolations.
if Self::starts_with_at(bytes, idx, b"${") {
let mut depth: usize = 1;
let mut j = idx + 2;
while j < bytes.len() && depth > 0 {
match bytes[j] {
b'{' => depth += 1,
b'}' => depth -= 1,
b'"' => {
j = crate::lex::scan_normal_string_for_cst(bytes, j);
continue;
}
_ => {}
}
if depth == 0 {
j += 1;
break;
}
j += 1;
}
if depth != 0 {
return None;
}
idx = j;
continue;
}
if !raw && bytes[idx] == b'\\' {
if idx + 1 >= bytes.len() {
return None;
}
idx += 1 + utf8_codepoint_len(bytes[idx + 1]);
continue;
}
if Self::starts_with_at(bytes, idx, closing.as_bytes()) {
return Some(idx);
}
idx += utf8_codepoint_len(bytes[idx]);
}
None
}
fn starts_with_at(bytes: &[u8], idx: usize, needle: &[u8]) -> bool {
bytes
.get(idx..idx + needle.len())
.is_some_and(|s| s == needle)
}
/// Scan forward (without committing) starting from `start_idx`,
/// past a balanced `(...)`, returning the index of the first
/// non-trivia token AFTER the closing `)`. `start_idx` must point
/// at the opening `L_PAREN` token. Returns `None` if the parens
/// are unbalanced (we ran past EOI before matching).
fn scan_after_matching_paren(&self, start_idx: usize) -> Option<usize> {
debug_assert!(self.tokens.get(start_idx).map(|(k, _)| *k) == Some(SyntaxKind::L_PAREN));
let mut depth: i32 = 0;
let mut idx = start_idx;
while idx < self.tokens.len() {
let kind = self.tokens[idx].0;
match kind {
SyntaxKind::L_PAREN => depth += 1,
SyntaxKind::R_PAREN => {
depth -= 1;
if depth == 0 {
let mut next = idx + 1;
while next < self.tokens.len() && self.tokens[next].0.is_trivia() {
next += 1;
}
return Some(next);
}
}
_ => {}
}
idx += 1;
}
None
}
/// Without consuming anything, decide whether the `(...)` at the
/// current position is followed (modulo an optional `-> Type`) by
/// a `=>` arrow — i.e. the parens are a closure parameter list,
/// not a parenthesised expression. We're already at the
/// `L_PAREN`.
fn looks_like_closure_after_paren(&self) -> bool {
let lparen_idx = self.pos_skip_trivia();
let Some(after_paren) = self.scan_after_matching_paren(lparen_idx) else {
return false;
};
// `=> ...`?
if matches!(
self.tokens.get(after_paren).map(|(k, _)| *k),
Some(SyntaxKind::FAT_ARROW)
) {
return true;
}
// `-> RetType => ...`? Skip past the return-type tokens. We
// can't fully parse a type without committing, so scan ahead
// conservatively until we hit `=>` (closure) or anything that
// disqualifies (newline-like break is fine — trivia is skipped
// by definition, but we treat `,`/`}`/`]`/`)`/`:` as a
// disqualifier so we never confuse `-> Type:` patterns).
if matches!(
self.tokens.get(after_paren).map(|(k, _)| *k),
Some(SyntaxKind::THIN_ARROW)
) {
let mut idx = after_paren + 1;
let mut bracket_depth: i32 = 0;
while idx < self.tokens.len() {
let kind = self.tokens[idx].0;
if kind.is_trivia() {
idx += 1;
continue;
}
match kind {
SyntaxKind::FAT_ARROW if bracket_depth == 0 => return true,
SyntaxKind::COMMA
| SyntaxKind::R_BRACE
| SyntaxKind::R_BRACK
| SyntaxKind::R_PAREN
| SyntaxKind::COLON
if bracket_depth == 0 =>
{
return false
}
SyntaxKind::L_BRACE
| SyntaxKind::L_BRACK
| SyntaxKind::L_PAREN
| SyntaxKind::LT => {
bracket_depth += 1;
}
SyntaxKind::R_BRACE | SyntaxKind::R_BRACK | SyntaxKind::GT
if bracket_depth > 0 =>
{
bracket_depth -= 1;
}
_ => {}
}
idx += 1;
}
}
false
}
/// When `current()` is `L_PAREN` and `looks_like_closure_after_paren`
/// is true, consume the entire `(params) [-> RetType] => body`
/// construct and emit a CLOSURE node. Returns true on success.
/// Leaves the parser untouched and returns false otherwise.
fn try_parse_paren_closure(&mut self) -> bool {
if !self.at(SyntaxKind::L_PAREN) {
return false;
}
if !self.looks_like_closure_after_paren() {
return false;
}
self.open(SyntaxKind::CLOSURE);
self.bump(); // (
// Comma-separated CLOSURE_PARAMs.
while !self.at(SyntaxKind::R_PAREN) && !self.at_end() {
self.parse_closure_param();
if !self.eat(SyntaxKind::COMMA) && !self.at(SyntaxKind::R_PAREN) {
self.error_recover(
"expected `,` or `)` in closure parameter list",
&[SyntaxKind::COMMA, SyntaxKind::R_PAREN],
);
self.eat(SyntaxKind::COMMA);
}
}
self.expect(SyntaxKind::R_PAREN);
// Optional `-> RetType`.
if self.eat(SyntaxKind::THIN_ARROW) {
self.parse_type();
}
if self.expect(SyntaxKind::FAT_ARROW) {
self.parse_expr();
}
self.close();
true
}
/// Parse a `(`-led atom that is NOT a closure: either a
/// parenthesised group `(expr)` or a tuple value literal.
///
/// Disambiguation (locked design):
/// * `()` → unit / zero-tuple (TUPLE node, no children).
/// * `(e)` → grouping (the inner expression, no wrapper).
/// * `(e,)` → 1-tuple (trailing comma forces it).
/// * `(e1, e2, ...)` → n-tuple.
///
/// The opening `(` and closing `)` land inside the TUPLE node for the
/// tuple shapes so the round-trip-by-bytes invariant holds; for the
/// grouping shape the parens are bumped as bare leaves around the
/// inner expression (matching the pre-tuple behaviour).
fn parse_paren_or_tuple(&mut self) {
debug_assert!(self.at(SyntaxKind::L_PAREN));
let ck = self.checkpoint();
self.bump(); // (
// Empty parens — the unit tuple `()`.
if self.at(SyntaxKind::R_PAREN) {
self.open_at(ck, SyntaxKind::TUPLE);
self.bump(); // )
self.close();
return;
}
// Parse the first element / grouped expression.
self.parse_expr();
if self.at(SyntaxKind::COMMA) {
// At least one comma → a tuple. Wrap everything (including
// the already-parsed first element) in a TUPLE node.
self.open_at(ck, SyntaxKind::TUPLE);
while self.eat(SyntaxKind::COMMA) {
// Trailing comma before `)` is allowed (and is what
// makes `(e,)` a 1-tuple).
if self.at(SyntaxKind::R_PAREN) || self.at_end() {
break;
}
self.parse_expr();
}
self.expect(SyntaxKind::R_PAREN);
self.close();
return;
}
// No comma — plain grouping `(expr)`. No TUPLE wrapper; the
// inner expression stands on its own (precedence override only).
self.expect(SyntaxKind::R_PAREN);
}
/// One closure parameter — either `name` or `Type name`. P2
/// records the type, when present, as a TYPE_NODE child preceding
/// the IDENT.
fn parse_closure_param(&mut self) {
self.open(SyntaxKind::CLOSURE_PARAM);
// Heuristic: if the next two non-trivia tokens are IDENT IDENT
// (or a more elaborate type followed by an ident), treat the
// leading run as a TypeNode. We delegate to `parse_type` which
// commits conservatively (it stops at the first non-type-y
// token, so a bare `IDENT` doesn't get swallowed as a type).
// The simplest signal of "this is a typed param" is that
// there are at least two adjacent IDENTs, possibly with `<...>`
// / `?` in the type slot.
if self.peek_is_typed_param() {
self.parse_type();
}
// A bare `_` is a legal parameter name (the Rust-style
// ignore binding `(acc, _) => ...`). Since the lexer now emits
// `_` as `UNDERSCORE` rather than `IDENT`, accept it here too so
// a `_` parameter keeps parsing exactly as it did before the
// wildcard split.
if self.at(SyntaxKind::IDENT) || self.at(SyntaxKind::UNDERSCORE) {
self.bump();
} else {
self.error_at_current("expected closure parameter name");
}
self.close();
}
/// Cheap lookahead: does the upcoming token stream look like
/// `Type ident` (a typed closure parameter) or just `ident`
/// (untyped)? We say "typed" if the current token is IDENT and
/// the next non-trivia token after a `Type`-shaped run is another
/// IDENT — meaning the first one is the type and the second is
/// the param name. We allow `<...>` and `?` between them.
///
/// Crucial heuristic: when a `<` appears, it must be immediately
/// adjacent (no whitespace) to the preceding IDENT for it to
/// count as opening a generic argument list. Without this
/// guard, `a < b: c` (a closure param of type `a` named `< b`
/// — but `<` isn't a valid name leader, so it bails)
/// would still be misinterpreted in pathological cases. Rust /
/// TypeScript both use the same lex-time adjacency check.
fn peek_is_typed_param(&self) -> bool {
if !self.at(SyntaxKind::IDENT) {
return false;
}
// Walk past IDENT, optional `.IDENT*`, optional `<...>`,
// optional `?`, then check for IDENT.
let head_idx = self.pos_skip_trivia();
let mut idx = head_idx + 1;
let advance_trivia = |i: &mut usize| {
while *i < self.tokens.len() && self.tokens[*i].0.is_trivia() {
*i += 1;
}
};
// For the adjacency check we want to know whether ANY trivia
// intervenes between the IDENT and the next non-trivia token.
let mut had_trivia_after_head = false;
if idx < self.tokens.len() && self.tokens[idx].0.is_trivia() {
had_trivia_after_head = true;
advance_trivia(&mut idx);
}
// `.IDENT*`
while idx < self.tokens.len() && self.tokens[idx].0 == SyntaxKind::DOT {
idx += 1;
advance_trivia(&mut idx);
if self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::IDENT) {
idx += 1;
advance_trivia(&mut idx);
} else {
return false;
}
had_trivia_after_head = false;
}
// `<...>` — balanced angle scan. Refuse when whitespace
// separates the IDENT and the `<` — that's the disambiguation
// hook between `Foo<Bar>` (type) and `a < b` (comparison).
if self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::LT) {
if had_trivia_after_head {
return false;
}
let mut depth: i32 = 1;
// Track nested `(...)` so tuple-type arguments like
// `List<(Int, String)>` don't trip the comma rejection.
let mut paren_depth: i32 = 0;
idx += 1;
while idx < self.tokens.len() && depth > 0 {
match self.tokens[idx].0 {
SyntaxKind::LT => depth += 1,
SyntaxKind::GT => depth -= 1,
SyntaxKind::L_PAREN => paren_depth += 1,
SyntaxKind::R_PAREN if paren_depth > 0 => paren_depth -= 1,
// Anything that strongly disqualifies a type
// expression — bail. Commas at depth==1 are
// fine (`Dict<String, Int>`) — only structural
// tokens that can never appear inside a type
// disqualify the scan.
SyntaxKind::L_BRACE
| SyntaxKind::R_BRACE
| SyntaxKind::R_PAREN
| SyntaxKind::FAT_ARROW
if depth == 1 && paren_depth == 0 =>
{
return false
}
_ => {}
}
idx += 1;
}
if depth != 0 {
return false;
}
advance_trivia(&mut idx);
}
// Optional `?`.
if self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::QUESTION) {
idx += 1;
advance_trivia(&mut idx);
}
self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::IDENT)
}
/// Parse a type-expression-shaped run of tokens into a TYPE_NODE.
/// The grammar:
///
/// TypeNode := TupleType | (PathSeg ('.' PathSeg)* GenericArgs?)
/// TupleType := '(' ')' | '(' TypeNode ',' ')' | '(' TypeNode (',' TypeNode)+ ','? ')'
/// PathSeg := IDENT | STRING
/// GenericArgs := '<' (TypeNode (',' TypeNode)*)? ','? '>'
///
/// Handles string-keyed segments (`"namespaced".Foo`), nested
/// generics (`Map<String, Int>`), and v1.7 tuple types in both
/// type-hint position (`(Int, String) pair: ...`) and as generic
/// arguments (`List<(Int, String)>`). A trailing type-suffix `?`
/// (`T?`) is no longer valid — optionality is written `Option<T>` —
/// so we still consume any stray `?` token but flag it as an error.
fn parse_type(&mut self) {
// Tuple type — committed only when the caller picked
// `parse_type` (typed-key / generic-arg / closure-param /
// return-type position). The expression grammar uses its own
// `(...)` handler so a parens group never reaches this branch.
if self.at(SyntaxKind::L_PAREN) {
self.parse_tuple_type();
return;
}
self.open(SyntaxKind::TYPE_NODE);
// First segment: IDENT or STRING (allowed in the v1 grammar
// for dotted-string paths like `"foo".Bar`).
if self.at(SyntaxKind::IDENT) || self.at(SyntaxKind::STRING) {
self.bump();
} else {
self.error_at_current("expected type name");
self.close();
return;
}
// Dotted continuation.
while self.at(SyntaxKind::DOT) {
self.bump();
if self.at(SyntaxKind::IDENT) || self.at(SyntaxKind::STRING) {
self.bump();
} else {
self.error_at_current("expected identifier after `.` in type");
}
}
// Generic argument list. We're in a committed type context
// here (the caller already decided "this is a type"), so any
// `<` opens generics — no adjacency check needed.
if self.at(SyntaxKind::LT) {
self.bump();
loop {
if self.at(SyntaxKind::GT) || self.at_end() {
break;
}
self.parse_type();
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::GT);
}
// Type-suffix `?` is no longer valid syntax — optional types
// are written `Option<T>`. We still consume the token (keeping
// the tree lossless and avoiding recovery spin) but flag it as
// an error pointing the user to the named-type form.
if self.at(SyntaxKind::QUESTION) {
self.error("optional types are written `Option<T>`, not `T?`");
self.bump();
}
self.close();
}
/// `(T1, T2, ...)` tuple type. Three shapes:
///
/// * `()` — zero-tuple.
/// * `(T,)` — one-tuple (trailing comma is mandatory; without
/// it the form is a parenthesised type, not used
/// in the current grammar but still consumed as
/// a single-element TUPLE_TYPE for forward-compat).
/// * `(T1, T2)` — 2+ tuple, optional trailing comma.
///
/// Caller has already committed to type-position via `parse_type`,
/// so we don't have to worry about confusing this with a closure
/// param list — the closure detection happens at the expression
/// layer (`try_parse_paren_closure`) and never reaches here.
fn parse_tuple_type(&mut self) {
self.open(SyntaxKind::TUPLE_TYPE);
self.bump(); // (
while !self.at(SyntaxKind::R_PAREN) && !self.at_end() {
self.parse_type();
if !self.eat(SyntaxKind::COMMA) {
break;
}
}
self.expect(SyntaxKind::R_PAREN);
// Type-suffix `?` is no longer valid syntax — optional tuple
// types are written `Option<(...)>`. Consume the token but flag
// it as an error.
if self.at(SyntaxKind::QUESTION) {
self.error("optional types are written `Option<T>`, not `T?`");
self.bump();
}
self.close();
}
fn parse_reference(&mut self) {
// `&base.tail.tail...` with optional-chain `?.` / `?[` access
// forms (`&a.b?.c`, `&a?.[0]`). The legacy `reference_var`
// grammar accepts both `.` / `[` and the `?`-prefixed variant
// — the typed-AST tags the optional-ness on each `TokenKey`.
self.open(SyntaxKind::REFERENCE_EXPR);
self.bump(); // &
if self.at(SyntaxKind::IDENT) {
self.bump(); // base name
} else {
self.error_at_current("expected reference base after `&`");
}
loop {
// `?.` and `?[` — eat the `?` prefix first, then fall
// through to the regular dot / bracket handling.
if self.at(SyntaxKind::QUESTION)
&& matches!(
self.nth(1),
Some(SyntaxKind::DOT) | Some(SyntaxKind::L_BRACK)
)
{
self.bump(); // ?
} else if !self.at(SyntaxKind::DOT) && !self.at(SyntaxKind::L_BRACK) {
break;
}
if self.at(SyntaxKind::DOT) {
self.bump();
if self.at(SyntaxKind::IDENT) || self.at(SyntaxKind::NUMBER) {
self.bump();
} else {
self.error_at_current("expected identifier or index after `.`");
}
} else if self.at(SyntaxKind::L_BRACK) {
self.bump(); // [
self.parse_expr();
self.expect(SyntaxKind::R_BRACK);
} else {
break;
}
}
self.close();
}
fn parse_list(&mut self) {
// We don't know up-front whether this `[` opens a list or a
// comprehension — comprehensions look like `[ expr for id in
// iterable (if cond)? ]`. Use a checkpoint so we can wrap the
// first expression into either LIST or COMPREHENSION based on
// what we find next.
let outer_ck = self.checkpoint();
self.bump(); // [
// Empty list — handle explicitly so we don't try to parse an
// expression after `[`.
if self.at(SyntaxKind::R_BRACK) {
self.open_at(outer_ck, SyntaxKind::LIST);
self.bump();
self.close();
return;
}
// Parse the first element (or `for` head). If it's a spread,
// it can't be a comprehension head — emit LIST directly.
if self.at(SyntaxKind::ELLIPSIS) {
self.open_at(outer_ck, SyntaxKind::LIST);
self.parse_list_body_tail();
return;
}
self.parse_expr();
// After the first expression: if `for IDENT in ...`, this is
// a comprehension. Otherwise it's a regular list — wrap as
// LIST and continue collecting the rest.
if self.at(SyntaxKind::IDENT) && self.current_text() == Some("for") {
self.open_at(outer_ck, SyntaxKind::COMPREHENSION);
self.bump(); // `for`
if self.at(SyntaxKind::IDENT) {
self.bump();
} else {
self.error_at_current("expected identifier after `for`");
}
if self.at(SyntaxKind::IDENT) && self.current_text() == Some("in") {
self.bump();
} else {
self.error("expected `in` in comprehension");
}
self.parse_expr();
if self.at(SyntaxKind::IDENT) && self.current_text() == Some("if") {
self.bump();
self.parse_expr();
}
self.expect(SyntaxKind::R_BRACK);
self.close();
return;
}
// Regular list — wrap the existing first element into a LIST
// node and continue.
self.open_at(outer_ck, SyntaxKind::LIST);
if !self.eat(SyntaxKind::COMMA) && !self.at(SyntaxKind::R_BRACK) {
self.error_recover(
"expected `,` or `]` in list",
&[SyntaxKind::COMMA, SyntaxKind::R_BRACK],
);
self.eat(SyntaxKind::COMMA);
}
self.parse_list_body_tail();
}
/// Consume the remainder of a LIST body (after the optional leading
/// element + comma have already been emitted) up to and including
/// the closing `]`, then close the LIST node.
fn parse_list_body_tail(&mut self) {
while !self.at(SyntaxKind::R_BRACK) && !self.at_end() {
self.parse_expr();
if !self.eat(SyntaxKind::COMMA) && !self.at(SyntaxKind::R_BRACK) {
self.error_recover(
"expected `,` or `]` in list",
&[SyntaxKind::COMMA, SyntaxKind::R_BRACK],
);
self.eat(SyntaxKind::COMMA);
}
}
self.expect(SyntaxKind::R_BRACK);
self.close();
}
/// Text of the current (non-trivia) token, or None at EOI. Used by
/// keyword-tail productions (`for`, `in`, `if`, `match`, `where`,
/// `with`) that the lexer doesn't split out.
fn current_text(&self) -> Option<&'a str> {
let idx = self.pos_skip_trivia();
self.tokens.get(idx).map(|(_, t)| *t)
}
fn parse_dict(&mut self) {
self.open(SyntaxKind::DICT);
self.bump(); // {
while !self.at(SyntaxKind::R_BRACE) && !self.at_end() {
self.parse_dict_field();
if !self.eat(SyntaxKind::COMMA) && !self.at(SyntaxKind::R_BRACE) {
self.error_recover(
"expected `,` or `}` in dict",
&[SyntaxKind::COMMA, SyntaxKind::R_BRACE],
);
self.eat(SyntaxKind::COMMA);
}
}
self.expect(SyntaxKind::R_BRACE);
self.close();
}
fn parse_dict_field(&mut self) {
self.open(SyntaxKind::DICT_FIELD);
// Leading attributes (e.g. `#internal` / `#expect "msg"` /
// `@currency("USD")`) stack above the pair's key. Same
// shape the file root permits.
while self.at(SyntaxKind::HASH) || self.at(SyntaxKind::AT) {
self.parse_attribute();
}
if self.at_end() {
self.close();
return;
}
// Attribute-only field: `#import x from "p", "next": 1` — the
// `#import` directive already consumed its full body, leaving
// the field separator next. Same for a sequence of bare
// directives whose payload is the field itself (e.g.
// `#schema X { ... },`). Close the field here so the surrounding
// dict resumes at the separator.
if matches!(
self.current(),
Some(SyntaxKind::COMMA) | Some(SyntaxKind::R_BRACE)
) {
self.close();
return;
}
// The key: an ident, a string, or `...` (spread).
if self.at(SyntaxKind::ELLIPSIS) {
self.open(SyntaxKind::SPREAD_EXPR);
self.bump();
// v1.3 typed spread `...<Type> source` — same shape as the
// atom-level spread, but here we sit inside a dict field
// so the source expression can be a richer form.
if self.at(SyntaxKind::LT) {
self.bump();
self.parse_type();
self.expect(SyntaxKind::GT);
}
self.parse_expr();
self.close();
self.close();
return;
}
// Optional leading type hint: `Type key: value` /
// `Type key(params): body`. We commit only when peeking
// suggests a typed-key shape — otherwise the leading run is
// the key itself (e.g. a single identifier). v1.7 tuple types
// (`(Int, String) pair: ...`) take the same slot and are
// detected by a separate `(...)`-leading peek.
if self.peek_is_tuple_typed_dict_key() {
self.parse_tuple_type();
} else if self.peek_is_typed_dict_key() {
self.parse_type();
}
if self.at(SyntaxKind::IDENT) || self.at(SyntaxKind::STRING) {
self.bump();
} else if self.at(SyntaxKind::L_BRACK) {
// Dynamic key `[expr]: value`.
self.bump();
// Optional `<T>` type-hint between `[` and the expression.
if self.at(SyntaxKind::LT) {
self.bump();
self.parse_type();
self.expect(SyntaxKind::GT);
}
self.parse_expr();
self.expect(SyntaxKind::R_BRACK);
} else {
self.error_recover(
"expected dict key",
&[SyntaxKind::COLON, SyntaxKind::COMMA, SyntaxKind::R_BRACE],
);
}
// Method-shorthand closure: `key(params) [-> Ret]: body`.
// Detect via a `(` immediately after the key. We commit to the
// closure interpretation whenever a `(` follows the key, since
// the v1 grammar already reserves that position exclusively
// for the method shorthand.
if self.at(SyntaxKind::L_PAREN) {
// Emit `(params) [-> Ret]` as a CLOSURE_PARAM list now;
// the body that follows the `:` will be wrapped together
// with the params into a CLOSURE node via a checkpoint.
let closure_ck = self.checkpoint();
self.bump(); // (
while !self.at(SyntaxKind::R_PAREN) && !self.at_end() {
self.parse_closure_param();
if !self.eat(SyntaxKind::COMMA) && !self.at(SyntaxKind::R_PAREN) {
self.error_recover(
"expected `,` or `)` in closure parameter list",
&[SyntaxKind::COMMA, SyntaxKind::R_PAREN],
);
self.eat(SyntaxKind::COMMA);
}
}
self.expect(SyntaxKind::R_PAREN);
// Optional `-> RetType`.
if self.eat(SyntaxKind::THIN_ARROW) {
self.parse_type();
}
if self.eat(SyntaxKind::COLON) {
self.open_at(closure_ck, SyntaxKind::CLOSURE);
self.parse_expr();
self.close();
} else {
self.error("expected `:` in dict field");
}
} else if self.eat(SyntaxKind::COLON) {
self.parse_expr();
} else {
self.error("expected `:` in dict field");
}
self.close();
}
/// Does the upcoming token stream start with a Type-shaped run
/// followed by an IDENT (or STRING) and then `:` / `(` (i.e. a
/// typed-dict-key, NOT a dotted-path or a bare key)? Conservative
/// — false negatives are fine (the field still parses untyped),
/// but a false positive would consume the key as a type.
fn peek_is_typed_dict_key(&self) -> bool {
// Same logic as peek_is_typed_param, but we also accept STRING
// as the trailing key segment, and we require a following
// `:` or `(` so a dotted-path-as-value doesn't trip us up.
if !self.at(SyntaxKind::IDENT) {
return false;
}
let mut idx = self.pos_skip_trivia() + 1;
let advance_trivia = |i: &mut usize, toks: &[(SyntaxKind, &str)]| {
while *i < toks.len() && toks[*i].0.is_trivia() {
*i += 1;
}
};
advance_trivia(&mut idx, &self.tokens);
while idx < self.tokens.len() && self.tokens[idx].0 == SyntaxKind::DOT {
idx += 1;
advance_trivia(&mut idx, &self.tokens);
if self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::IDENT) {
idx += 1;
advance_trivia(&mut idx, &self.tokens);
} else {
return false;
}
}
let saw_generics = self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::LT);
if saw_generics {
let mut depth: i32 = 1;
// Track nested `(` / `)` so a tuple-type argument like
// `List<(Int, String)>` doesn't make the rejection bail
// out the moment it hits a comma or `)`.
let mut paren_depth: i32 = 0;
idx += 1;
while idx < self.tokens.len() && depth > 0 {
match self.tokens[idx].0 {
SyntaxKind::LT => depth += 1,
SyntaxKind::GT => depth -= 1,
SyntaxKind::L_PAREN => paren_depth += 1,
SyntaxKind::R_PAREN if paren_depth > 0 => paren_depth -= 1,
SyntaxKind::L_BRACE
| SyntaxKind::R_BRACE
| SyntaxKind::R_PAREN
| SyntaxKind::FAT_ARROW
| SyntaxKind::THIN_ARROW
| SyntaxKind::COLON
if depth == 1 && paren_depth == 0 =>
{
return false
}
_ => {}
}
idx += 1;
}
if depth != 0 {
return false;
}
advance_trivia(&mut idx, &self.tokens);
}
let saw_question = self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::QUESTION);
if saw_question {
idx += 1;
advance_trivia(&mut idx, &self.tokens);
}
// Now we must see IDENT or STRING (the key) followed by `:`
// or `(`. If neither, the leading run wasn't a type — bail
// and let the surrounding parser treat it as the key itself.
if !matches!(
self.tokens.get(idx).map(|(k, _)| *k),
Some(SyntaxKind::IDENT) | Some(SyntaxKind::STRING)
) {
return false;
}
let mut after_key = idx + 1;
advance_trivia(&mut after_key, &self.tokens);
let next = self.tokens.get(after_key).map(|(k, _)| *k);
matches!(next, Some(SyntaxKind::COLON) | Some(SyntaxKind::L_PAREN))
}
/// Does the upcoming token stream start with a balanced `(...)`
/// tuple-type prefix followed by an IDENT (or STRING) and then
/// `:` / `(` (i.e. `(Int, String) pair: ...`)? Used by
/// [`parse_dict_field`] to commit to the tuple-type lead, which
/// has to win over the "parens group" interpretation of the same
/// bytes when they appear at the head of a dict field. The
/// balanced paren scan walks past nested generics / nested parens
/// so `List<(Int, String)>` doesn't fool the outer detector.
fn peek_is_tuple_typed_dict_key(&self) -> bool {
if !self.at(SyntaxKind::L_PAREN) {
return false;
}
let lparen_idx = self.pos_skip_trivia();
let Some(after_paren) = self.scan_after_matching_paren(lparen_idx) else {
return false;
};
// Optional trailing `?` after the tuple type.
let mut idx = after_paren;
if self.tokens.get(idx).map(|(k, _)| *k) == Some(SyntaxKind::QUESTION) {
idx += 1;
while idx < self.tokens.len() && self.tokens[idx].0.is_trivia() {
idx += 1;
}
}
// Must see IDENT or STRING (the key), followed by `:` or `(`.
if !matches!(
self.tokens.get(idx).map(|(k, _)| *k),
Some(SyntaxKind::IDENT) | Some(SyntaxKind::STRING)
) {
return false;
}
let mut after_key = idx + 1;
while after_key < self.tokens.len() && self.tokens[after_key].0.is_trivia() {
after_key += 1;
}
matches!(
self.tokens.get(after_key).map(|(k, _)| *k),
Some(SyntaxKind::COLON) | Some(SyntaxKind::L_PAREN)
)
}
fn parse_call_args(&mut self) {
self.open(SyntaxKind::CALL_ARG);
self.bump(); // (
while !self.at(SyntaxKind::R_PAREN) && !self.at_end() {
self.parse_call_arg();
if !self.eat(SyntaxKind::COMMA) && !self.at(SyntaxKind::R_PAREN) {
self.error_recover(
"expected `,` or `)` in argument list",
&[SyntaxKind::COMMA, SyntaxKind::R_PAREN],
);
self.eat(SyntaxKind::COMMA);
}
}
self.expect(SyntaxKind::R_PAREN);
self.close();
}
/// One argument inside a call's parens. Either positional (a
/// bare expression) or named (`IDENT = expression`). The latter
/// is detected by peeking IDENT-followed-by-EQ — the legacy
/// `parse_call_arg` (`fn_call.rs`) uses the same lookahead. We
/// emit the IDENT + EQ + value expression as siblings of each
/// other under the parent CALL_ARG node so the lowering pass can
/// pick the name back out without re-running token logic.
fn parse_call_arg(&mut self) {
if self.at(SyntaxKind::IDENT) && self.nth(1) == Some(SyntaxKind::EQ) {
// Named: IDENT EQ <expr>.
self.bump(); // name
self.bump(); // =
self.parse_expr();
} else {
self.parse_expr();
}
}
}
// =====================================================================
// Operator precedence (Pratt binding-power table).
//
// Mirrors the existing precedence chain in `expr.rs`:
// 1. or ||
// 2. and &&
// 3. equality == !=
// 4. comparison < > <= >=
// 5. (retired) concat ++ — still consumed here for structured
// recovery, but `parse_expr_bp` flags it with a migration
// diagnostic pointing at `+` (string concatenation operator)
// 6. additive + -
// 7. multiplicative * / %
// 8. pipe |
// All operators are left-associative (right_bp = left_bp + 1).
// =====================================================================
fn infix_bp(kind: SyntaxKind) -> Option<(u8, u8)> {
Some(match kind {
SyntaxKind::PIPE_PIPE => (10, 11),
SyntaxKind::AMP_AMP => (20, 21),
SyntaxKind::EQ_EQ | SyntaxKind::BANG_EQ => (30, 31),
SyntaxKind::LT | SyntaxKind::GT | SyntaxKind::LT_EQ | SyntaxKind::GT_EQ => (40, 41),
SyntaxKind::PLUS_PLUS => (50, 51),
SyntaxKind::PLUS | SyntaxKind::MINUS => (60, 61),
SyntaxKind::STAR | SyntaxKind::SLASH | SyntaxKind::PERCENT => (70, 71),
SyntaxKind::PIPE => (80, 81),
_ => return None,
})
}
// =====================================================================
// rowan `Language::kind_to_raw` is an instance method on a unit type;
// our hot inner loops want a `'static`-friendly free function. Wrap it.
// =====================================================================
trait RawKind {
fn kind_to_raw_static(kind: SyntaxKind) -> rowan::SyntaxKind;
}
impl RawKind for RelonLanguage {
fn kind_to_raw_static(kind: SyntaxKind) -> rowan::SyntaxKind {
kind.into()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_round_trip(source: &str) -> Parse {
let parsed = parse_cst(source);
let reconstructed = parsed.syntax().text().to_string();
assert_eq!(reconstructed, source, "round-trip mismatch");
parsed
}
#[test]
fn empty_dict() {
let parsed = parse_round_trip("{}");
assert!(!parsed.has_errors());
}
#[test]
fn simple_dict() {
parse_round_trip("{ foo: 1, bar: 2 }");
}
#[test]
fn nested_dict_and_list() {
parse_round_trip("{\n foo: [1, 2, 3],\n bar: { baz: \"hi\" }\n}\n");
}
#[test]
fn reference_path() {
parse_round_trip("{ x: &root.foo.bar[0] }");
}
#[test]
fn binary_expression() {
let parsed = parse_round_trip("{ x: 1 + 2 * 3 }");
assert!(!parsed.has_errors());
// Multiplicative inside additive — verify the BINARY_EXPR
// nesting by looking at the syntax tree.
let syntax = parsed.syntax();
let dict = syntax
.descendants()
.find(|n| n.kind() == SyntaxKind::DICT)
.expect("dict");
let outer_binary = dict
.descendants()
.find(|n| n.kind() == SyntaxKind::BINARY_EXPR)
.expect("outer binary");
// The outer binary is `1 + (2 * 3)`. The right child is
// another BINARY_EXPR.
let inner_binaries: Vec<_> = outer_binary
.descendants()
.filter(|n| n.kind() == SyntaxKind::BINARY_EXPR && *n != outer_binary)
.collect();
assert!(!inner_binaries.is_empty(), "expected nested BINARY_EXPR");
}
#[test]
fn method_shorthand_emits_closure() {
let parsed = parse_round_trip("{ add(a, b): a + b }");
assert!(!parsed.has_errors());
let closures: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::CLOSURE)
.collect();
assert_eq!(closures.len(), 1, "expected exactly one CLOSURE node");
let params: Vec<_> = closures[0]
.descendants()
.filter(|n| n.kind() == SyntaxKind::CLOSURE_PARAM)
.collect();
assert_eq!(params.len(), 2, "expected two CLOSURE_PARAMs");
}
#[test]
fn standalone_paren_closure() {
let parsed = parse_round_trip("{ f: (a, b) => a + b }");
assert!(!parsed.has_errors());
let closures: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::CLOSURE)
.collect();
assert_eq!(closures.len(), 1);
}
#[test]
fn list_comprehension_emits_comprehension_node() {
let parsed = parse_round_trip("{ xs: [x * 2 for x in src if x > 0] }");
assert!(!parsed.has_errors());
let comps: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::COMPREHENSION)
.collect();
assert_eq!(comps.len(), 1);
// The COMPREHENSION should NOT also be a LIST.
let lists: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::LIST)
.collect();
// The dict body is not a list, so the only [...] in source
// becomes a COMPREHENSION — no LIST nodes at top level.
assert!(
lists.is_empty(),
"comprehension `[...]` should not also produce a LIST"
);
}
#[test]
fn match_expression_emits_match_node() {
let parsed = parse_round_trip(
"{ render(item): item match { Image: \"i\", Text: \"t\", _ : \"u\" } }",
);
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let matches: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::MATCH_EXPR)
.collect();
assert_eq!(matches.len(), 1);
let arms: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::MATCH_ARM)
.collect();
assert_eq!(arms.len(), 3);
}
#[test]
fn underscore_match_catch_all_parses_clean() {
// The Rust-style `_` catch-all parses without errors and yields a
// WILDCARD pattern node (the same node `*` used to produce).
let parsed = parse_round_trip("{ render(item): item match { Image: \"i\", _: \"u\" } }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let wildcards: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::WILDCARD)
.collect();
assert_eq!(wildcards.len(), 1);
}
#[test]
fn star_in_match_arm_now_errors() {
// `*` is no longer the pattern wildcard — a match catch-all
// spelled `*` is a parse error pointing at the new `_` spelling.
let parsed = parse_round_trip("{ render(item): item match { Image: \"i\", *: \"u\" } }");
assert!(
parsed.has_errors(),
"`*` in a match arm must error (use `_`): {:?}",
parsed.errors
);
assert!(
parsed.errors.iter().any(|e| e.message.contains("`_`")),
"diagnostic should point at `_`: {:?}",
parsed.errors
);
}
#[test]
fn plus_plus_concat_now_errors() {
// `++` was parseable but never executable — string
// concatenation is spelled `+`. The token is still consumed
// (round-trip stays lossless, recovery stays structured) but
// the parse carries a migration diagnostic pointing at `+`.
let parsed = parse_round_trip("{ msg: \"a\" ++ \"b\" }");
assert!(
parsed.has_errors(),
"`++` must error (use `+`): {:?}",
parsed.errors
);
assert!(
parsed
.errors
.iter()
.any(|e| e.message.contains("use `+` to concatenate strings")),
"diagnostic should point at `+`: {:?}",
parsed.errors
);
}
#[test]
fn plus_plus_in_main_body_errors() {
// Same diagnostic through the `#main` body expression path.
let parsed = parse_round_trip("#main(String s) -> String\ns ++ \"!\"\n");
assert!(
parsed.has_errors(),
"`++` in a #main body must error: {:?}",
parsed.errors
);
assert!(
parsed
.errors
.iter()
.any(|e| e.message.contains("use `+` to concatenate strings")),
"diagnostic should point at `+`: {:?}",
parsed.errors
);
}
#[test]
fn underscore_closure_param_parses_clean() {
// A bare `_` is a legal closure parameter name (the Rust-style
// ignore binding). The wildcard lexer split must NOT break it:
// `(acc, _) => acc` parses without errors.
let parsed = parse_round_trip("{ f(n): range(n).reduce(0, (acc, _) => acc) }");
assert!(
!parsed.has_errors(),
"`_` closure param must parse clean: {:?}",
parsed.errors
);
}
#[test]
fn schema_directive_with_body() {
let parsed = parse_round_trip("#schema User { String name: *, Int age: * }\n{ a: 1 }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let dirs: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::DIRECTIVE)
.collect();
assert_eq!(dirs.len(), 1);
}
#[test]
fn schema_with_generic_params_and_with_block() {
let parsed = parse_round_trip(
"#schema Result<T, E> { T value: *, E error: * } with { unwrap(): value }\n{ x: 1 }",
);
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn import_directive_round_trip() {
let parsed = parse_round_trip("#import string from \"std/string\"\n{ x: 1 }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn import_with_sha256_integrity_round_trip() {
let parsed =
parse_round_trip("#import lib from \"./lib.relon\" sha256:\"deadbeef\"\n{ x: 1 }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn import_with_missing_hex_string_reports_error() {
// `sha256:` followed by something that is not a STRING should
// raise a parse error (rather than silently consume tokens).
let parsed = parse_round_trip("#import lib from \"./lib.relon\" sha256: bad\n{ x: 1 }");
assert!(
parsed.has_errors(),
"expected parse error for malformed integrity pin"
);
}
#[test]
fn main_directive_round_trip() {
let parsed = parse_round_trip("#main(User u, Cart cart) -> Result<Order>\n{ x: 1 }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn f_string_emits_f_string_node() {
let parsed = parse_round_trip(r#"{ msg: f"hello ${name}!" }"#);
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let fs: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::F_STRING)
.collect();
assert_eq!(fs.len(), 1);
let interps: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::F_STRING_INTERPOLATION)
.collect();
assert_eq!(interps.len(), 1);
// Interpolation body should contain a VARIABLE_EXPR for `name`.
let interp = &interps[0];
let vars: Vec<_> = interp
.descendants()
.filter(|n| n.kind() == SyntaxKind::VARIABLE_EXPR)
.collect();
assert!(!vars.is_empty(), "expected VARIABLE_EXPR inside interp");
}
#[test]
fn raw_f_string_round_trip() {
parse_round_trip("{ msg: f#\"raw ${x} text\"# }");
}
#[test]
fn plain_string_still_literal() {
let parsed = parse_round_trip(r#"{ x: "hi" }"#);
let fs: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::F_STRING)
.collect();
assert!(fs.is_empty(), "plain string should not be F_STRING");
}
#[test]
fn where_expression_emits_where_node() {
let parsed = parse_round_trip("{ x: a + b where { a: 1, b: 2 } }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let wheres: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::WHERE_EXPR)
.collect();
assert_eq!(wheres.len(), 1);
}
#[test]
fn list_without_for_stays_list() {
let parsed = parse_round_trip("{ xs: [1, 2, 3] }");
assert!(!parsed.has_errors());
let lists: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::LIST)
.collect();
assert_eq!(lists.len(), 1);
}
#[test]
fn generic_type_in_closure_param() {
let parsed = parse_round_trip("{ extract(List<Int> xs, Option<String> sep): xs }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let types: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::TYPE_NODE)
.collect();
// `List<Int>` outer + `Int` nested + `Option<String>` outer +
// `String` nested = 4 TYPE_NODEs.
assert!(
types.len() >= 3,
"expected at least 3 TYPE_NODE, got {}",
types.len()
);
}
#[test]
fn type_suffix_question_is_rejected() {
// Wave A: the type-suffix `?` (`Int?`, `Weather?`, `List<T>?`)
// is no longer valid — optionality is written `Option<T>`. Each
// of these must surface a parse error pointing at `Option<T>`.
for source in [
"#main(Int? x) -> Int\n0\n",
"{ extract(String? sep): sep }",
"{ Weather? w: { a: 1 } }",
"{ x: #brand Weather? { a: 1 } }",
"{ extract(List<Int>? xs): xs }",
] {
let parsed = parse_cst(source);
assert!(
parsed.has_errors(),
"expected a parse error for type-suffix `?` in {source:?}"
);
assert!(
parsed
.errors
.iter()
.any(|e| e.message.contains("Option<T>")),
"expected an `Option<T>` hint in errors for {source:?}, got {:?}",
parsed.errors
);
}
}
#[test]
fn option_type_in_main_signature_parses_clean() {
// The migration target `Option<T>` parses without errors where
// the old `T?` used to.
let parsed = parse_cst("#main(Option<Int> x) -> Int\n0\n");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn optional_chaining_and_ternary_still_parse() {
// The call-chain `?` (optional chaining) and the ternary `?:`
// must keep parsing cleanly — only the type-suffix `?` is gone.
for source in [
"{ f(a): a?.b }",
"{ f(a): a?[0] }",
"{ f(a): a?.b?.c }",
"{ g(x): x < 0 ? -x : x }",
] {
let parsed = parse_round_trip(source);
assert!(
!parsed.has_errors(),
"unexpected errors for {source:?}: {:?}",
parsed.errors
);
}
}
#[test]
fn comparison_lt_not_treated_as_generics() {
// The closure-param peek must NOT decide `a < b` is a typed
// param — there's whitespace between `a` and `<`. The dict
// body should be a single binary expression.
let parsed = parse_round_trip("{ f: a < b }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let binaries: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::BINARY_EXPR)
.collect();
assert_eq!(binaries.len(), 1, "expected one BINARY_EXPR");
}
#[test]
fn typed_closure_param_records_type_node() {
let parsed = parse_round_trip("{ add(Int a, Int b): a + b }");
assert!(!parsed.has_errors());
let type_nodes: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::TYPE_NODE)
.collect();
assert!(
type_nodes.len() >= 2,
"expected TYPE_NODEs for typed params"
);
}
#[test]
fn comments_round_trip() {
parse_round_trip("// header\n{\n // inner\n x: 1, /* trail */ y: 2\n}\n");
}
#[test]
fn error_recovery_preserves_bytes() {
// Deliberate parse failure: missing colon. The recovery
// wraps `42` in an ERROR node and resyncs to `,`. Source
// bytes are intact end-to-end.
let parsed = parse_round_trip("{ foo 42, bar: 1 }");
assert!(parsed.has_errors(), "expected an error report");
}
#[test]
fn unknown_byte_does_not_crash() {
parse_round_trip("{ x: \u{0000} 1 }");
}
#[test]
fn variant_ctor_emits_variant_node() {
let parsed = parse_round_trip("{ x: Result.Ok { value: 1 } }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let vc: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::VARIANT_CTOR)
.collect();
assert_eq!(vc.len(), 1);
}
#[test]
fn variant_ctor_three_segment_path() {
let parsed = parse_round_trip("{ x: Foo.Bar.Baz { field: 1 } }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let vc: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::VARIANT_CTOR)
.collect();
assert_eq!(vc.len(), 1);
}
#[test]
fn dotted_access_without_brace_stays_variable() {
// `foo.bar` alone is member access — must NOT become a
// VARIANT_CTOR. Walks the post-fix path the same as before.
let parsed = parse_round_trip("{ x: foo.bar }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let vc: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::VARIANT_CTOR)
.collect();
assert!(vc.is_empty(), "single dotted access should not be a ctor");
}
#[test]
fn named_call_args_parse_without_errors() {
let parsed = parse_round_trip("{ y: map(f = g) }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
// The CALL_ARG node contains the IDENT, EQ, and value side by
// side; the lowering pass groups them back into a `CallArg`.
let call_args: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::CALL_ARG)
.collect();
assert_eq!(call_args.len(), 1);
let has_eq = call_args[0]
.children_with_tokens()
.filter_map(|el| el.into_token())
.any(|t| t.kind() == SyntaxKind::EQ);
assert!(has_eq, "named arg should carry an EQ token");
}
#[test]
fn mixed_positional_and_named_args() {
let parsed = parse_round_trip("{ z: f(1, name = expr, more = 2) }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn ternary_expression_emits_ternary_node() {
let parsed = parse_round_trip("{ x: a ? 1 : 2 }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let ts: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::TERNARY_EXPR)
.collect();
assert_eq!(ts.len(), 1, "expected one TERNARY_EXPR");
}
#[test]
fn ternary_root_no_whitespace() {
// Legacy accepts `true? 1:2` — every `?` / `:` boundary is
// surrounded by `soc0` so adjacent forms parse without spaces.
let parsed = parse_round_trip("true? 1:2");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn ternary_nested_in_else() {
// Right-recursive parse: `a ? 1 : b ? 2 : 3` should produce a
// ternary whose `els` is another ternary.
let parsed = parse_round_trip("{ x: a ? 1 : b ? 2 : 3 }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let ts: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::TERNARY_EXPR)
.collect();
assert_eq!(ts.len(), 2);
}
#[test]
fn bare_directive_does_not_consume_next_field() {
// `#internal` is a bare directive; the IDENT after it must
// belong to the next dict field, not to the directive body.
let src = "{ #internal\n field(s): s, next: 1 }";
let parsed = parse_round_trip(src);
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn dict_field_can_be_attribute_only() {
// `#import x from "p"` consumes its whole body; the field is
// attribute-only and the `,` belongs to the surrounding dict.
let src = "{ #import x from \"p\", next: 1 }";
let parsed = parse_round_trip(src);
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn schema_with_block_emits_method_nodes() {
// Slice-opener for the schema with-block grammar. Two methods
// back-to-back, one carrying a `#derive` pragma and a `Self`
// parameter type.
let src = "#schema Money { Int cents: * } with {\n #derive Equatable\n eq(other: Self) -> Bool: self.cents == other.cents\n}\n{ Money p: { cents: 100 } }\n";
let parsed = parse_round_trip(src);
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let with_blocks: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::SCHEMA_WITH)
.collect();
assert_eq!(with_blocks.len(), 1);
let methods: Vec<_> = with_blocks[0]
.descendants()
.filter(|n| n.kind() == SyntaxKind::SCHEMA_METHOD)
.collect();
assert_eq!(methods.len(), 1);
// The method should contain the `#derive` directive and a
// CLOSURE_PARAM for `other`.
let dirs: Vec<_> = methods[0]
.descendants()
.filter(|n| n.kind() == SyntaxKind::DIRECTIVE)
.collect();
assert_eq!(dirs.len(), 1);
let params: Vec<_> = methods[0]
.descendants()
.filter(|n| n.kind() == SyntaxKind::CLOSURE_PARAM)
.collect();
assert_eq!(params.len(), 1);
}
#[test]
fn schema_with_block_native_method_skips_body() {
// `#native` method has no `: body` — just the signature.
let src =
"#schema Doc { String text: * } with {\n #native\n render() -> String\n}\n{}\n";
let parsed = parse_round_trip(src);
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn tuple_index_access_round_trips() {
// v1.8 positional access `xs.0` — number after the dot is a
// valid path tail, alongside identifier-style `xs.field`.
let parsed = parse_round_trip("{ Int head: xs.0 }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn type_atom_for_brand_directive_body() {
// `#brand Dict<String, Int> { ... }` — the brand directive's
// body is a type-tagged dict. The leading IDENT `Dict` (a
// known type head) must lower into a TYPE_NODE so the
// generics aren't mistaken for binary `<` / `>` operators.
let src = "{ counters: #brand Dict<String, Int> { hits: 1 } }";
let parsed = parse_round_trip(src);
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let types: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::TYPE_NODE)
.collect();
assert!(!types.is_empty(), "expected a TYPE_NODE for Dict<...>");
}
#[test]
fn typed_spread_round_trips() {
// v1.3 typed spread `...<Type> expr`. The `<Type>` annotation
// lands inside the SPREAD_EXPR; the source expression follows.
let parsed = parse_round_trip("{ val: { ...<Extra> base } }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let spreads: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::SPREAD_EXPR)
.collect();
assert_eq!(spreads.len(), 1, "expected one SPREAD_EXPR");
let types: Vec<_> = spreads[0]
.descendants()
.filter(|n| n.kind() == SyntaxKind::TYPE_NODE)
.collect();
assert!(!types.is_empty(), "typed spread should carry a TYPE_NODE");
}
#[test]
fn tuple_type_in_dict_field_round_trips() {
// v1.7 tuple types in the type-hint slot of a dict field.
let parsed = parse_round_trip("{ (Int, String) pair: (42, \"hello\") }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let tts: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::TUPLE_TYPE)
.collect();
assert_eq!(tts.len(), 1, "expected one TUPLE_TYPE");
}
#[test]
fn tuple_type_inside_generic() {
let parsed = parse_round_trip("{ List<(Int, String)> rows: [(1, \"a\")] }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
let tts: Vec<_> = parsed
.syntax()
.descendants()
.filter(|n| n.kind() == SyntaxKind::TUPLE_TYPE)
.collect();
assert_eq!(tts.len(), 1);
}
#[test]
fn tuple_type_zero_and_one() {
// Zero-tuple `()` and one-tuple `(T,)` both round-trip
// cleanly. The trailing comma in the one-tuple matters for the
// typed-AST layer (it disambiguates from `(T)` parens), but the
// CST keeps the bytes verbatim.
let parsed = parse_round_trip("{ () unit: [], (Int,) one: [1] }");
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
#[test]
fn decorator_dotted_name_round_trips() {
// `@ensure.int` / `@ensure.at_least(1024)` — dotted decorator
// names appear in the corpus alongside plain `@name(...)`.
let src = "{ @ensure.int\n @ensure.at_least(1024)\n \"port\": 80 }";
let parsed = parse_round_trip(src);
assert!(!parsed.has_errors(), "errors: {:?}", parsed.errors);
}
/// Monotonic floor on how many checked-in `.relon` fixtures parse
/// without ANY ERROR nodes. Each P2 slice MUST raise this number;
/// regressions need a deliberate, recorded reason.
///
/// The floor starts at 30 (closures slice). Bump it as more P2
/// grammar lands.
#[test]
fn fixtures_clean_parse_floor() {
// Each P2 slice bumps the floor. At slice 1 (closures) we hit
// ~60 of ~210 — the directive / match / where / type slices
// pushed this to 135. After the P4-prep grammar gaps
// (ternary / named call args / variant ctor) we reach 148.
// Directive-shape dispatch + attribute-only dict fields pushed
// it to 157 (the next P2 slices target tuple types, typed
// spreads, and the schema with-block named-param method
// grammar). Tuple types `(T1, T2)` brought the floor to 165.
// Typed spreads `...<Type> expr` brought it to 170.
// Schema with-block structured method nodes brought it to 198.
// Tuple-index `.N` access, type-atom recognition for
// `#brand Dict<K, V> { ... }` / `Weather? { ... }`,
// Enum-with-struct-variant inside generic args, and
// expression-level leading attributes brought it to 208.
// The remaining two `.relon` files
// (`with_block_invalid/*.relon`) are intentional parse-error
// fixtures used by the legacy parser's negative test suite.
const FLOOR: usize = 208;
let clean = fixture_clean_parse_count();
eprintln!("[parser] fixtures clean-parse count: {clean}");
assert!(
clean >= FLOOR,
"regressed clean-parse count: floor={FLOOR}, actual={clean}",
);
}
fn fixture_clean_parse_count() -> usize {
use std::fs;
use std::path::PathBuf;
let crate_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let workspace_root = crate_dir
.parent()
.and_then(|p| p.parent())
.expect("workspace root")
.to_path_buf();
let mut files = Vec::new();
walk(&workspace_root, &mut files);
files.retain(|p| !p.to_string_lossy().contains("/target/"));
let mut clean = 0usize;
for path in files {
let source = fs::read_to_string(&path).unwrap_or_default();
if source.is_empty() {
continue;
}
let parsed = parse_cst(&source);
if !parsed.has_errors() {
clean += 1;
}
}
clean
}
/// The strongest invariant: every checked-in `.relon` file
/// round-trips through the CST byte-exact. Some may still have
/// parse errors (the v2 grammar doesn't cover every construct
/// yet) — that's expected and tolerated. What MUST hold is the
/// lossless tree property.
#[test]
fn every_fixture_round_trips_through_cst() {
use std::fs;
use std::path::PathBuf;
let crate_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let workspace_root = crate_dir
.parent()
.and_then(|p| p.parent())
.expect("workspace root")
.to_path_buf();
let mut files = Vec::new();
walk(&workspace_root, &mut files);
files.retain(|p| !p.to_string_lossy().contains("/target/"));
assert!(!files.is_empty());
for path in files {
let source = fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path:?}: {e}"));
let parsed = parse_cst(&source);
let reconstructed = parsed.syntax().text().to_string();
assert_eq!(reconstructed, source, "round-trip mismatch on {path:?}");
}
}
fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
let Ok(read) = std::fs::read_dir(dir) else {
return;
};
for entry in read.flatten() {
let p = entry.path();
if p.is_dir() {
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
if matches!(name, "target" | "node_modules" | ".git") {
continue;
}
walk(&p, out);
} else if p.extension().and_then(|e| e.to_str()) == Some("relon") {
out.push(p);
}
}
}
}