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
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
use crate::ast::*;
use crate::builtins::Builtin;
use crate::lexer::Token;
use std::collections::HashMap;
pub struct Parser {
tokens: Vec<(Token, Span)>,
pos: usize,
/// Parallel to `tokens` with length `tokens.len() + 1`. Entry `i` is
/// `Some(span)` iff at least one unindented `Token::Newline` (a top-level
/// declaration boundary, as produced by `lexer::normalize_newlines`) sat
/// immediately before token `i` in the pre-filter stream. The trailing
/// entry covers any newlines after the last surviving token. Populated in
/// `Parser::new` before newlines are filtered out, then consulted by
/// `parse_fn_decl`/`parse_params`/`parse_type` to keep header parsing from
/// walking off the end of one function and into the next. Without this,
/// a malformed header on line N reports its error span on line N+1 or
/// later, sending personas to bisect the wrong function.
decl_boundary: Vec<Option<Span>>,
/// Known function arities, populated with builtins at construction
/// and extended with user-function headers as they're parsed.
fn_arity: HashMap<String, usize>,
/// For each known function, which parameter positions take a function
/// reference (HOF positions).
fn_param_is_fn: HashMap<String, Vec<bool>>,
/// When true, an Ident followed by another whitespace-separated atom is
/// parsed as a bare Ref (list element) rather than a function call.
/// Set only inside list-literal element parsing.
no_whitespace_call: bool,
/// Synthetic top-level decls emitted by inline-lambda lifting. Appended to
/// `Program.declarations` after the main parse. Each inline lambda
/// `(p:t>r;body)` becomes a `Decl::Function { name: "__lit_N", ... }` here
/// and the call site is replaced by `Expr::Ref("__lit_N")` so HOFs see a
/// fn-ref just like a named helper.
lifted_decls: Vec<Decl>,
/// Monotonic counter for synthetic lambda names.
lambda_counter: usize,
}
#[derive(Debug, thiserror::Error)]
#[error("Parse error at token {position}: {message}")]
pub struct ParseError {
pub code: &'static str,
pub position: usize,
pub span: Span,
pub message: String,
pub hint: Option<String>,
}
type Result<T> = std::result::Result<T, ParseError>;
impl Parser {
pub fn new(tokens: Vec<(Token, Span)>) -> Self {
// Filter out newlines — idea9 uses ; as separator. Each surviving
// `Token::Newline` came out of `lexer::normalize_newlines`, which
// converts indented continuations into `;` and only keeps a literal
// newline at column 0 (an unambiguous top-level decl boundary). We
// throw the tokens away to keep the rest of the parser simple, but
// remember WHERE they sat in `decl_boundary` so header parsing in
// `parse_fn_decl` can detect when it would walk past one and into
// the next function. Without that signal, error spans land on the
// wrong function in multi-function files.
let mut filtered: Vec<(Token, Span)> = Vec::with_capacity(tokens.len());
let mut decl_boundary: Vec<Option<Span>> = Vec::with_capacity(tokens.len() + 1);
let mut pending: Option<Span> = None;
for (tok, span) in tokens.into_iter() {
if tok == Token::Newline {
// Coalesce a run of consecutive newlines into the first one's
// span; either way the meaning ("a decl boundary sat here") is
// identical and one span is enough for diagnostics.
if pending.is_none() {
pending = Some(span);
}
continue;
}
decl_boundary.push(pending.take());
filtered.push((tok, span));
}
// Trailing entry covers any newlines after the final surviving token.
decl_boundary.push(pending.take());
debug_assert_eq!(decl_boundary.len(), filtered.len() + 1);
let (fn_arity, fn_param_is_fn) = builtin_arity_tables();
Parser {
tokens: filtered,
pos: 0,
decl_boundary,
fn_arity,
fn_param_is_fn,
no_whitespace_call: false,
lifted_decls: Vec::new(),
lambda_counter: 0,
}
}
/// Returns `Some(span)` if an unindented newline (top-level declaration
/// boundary) sits immediately before the current token. The span points
/// at the newline byte itself, but for diagnostic anchoring callers
/// typically prefer `prev_span()` (the last token of the offending
/// function's line). Returns `None` if no boundary precedes `self.pos`
/// or the parser is at EOF beyond the recorded range.
fn boundary_at_cursor(&self) -> Option<Span> {
self.decl_boundary.get(self.pos).copied().flatten()
}
/// Emit ILO-P020 if we've crossed a top-level declaration boundary OR hit
/// EOF while still parsing the header of `fn_name`. The error span is
/// anchored at the offending function (preferring `header_start` if it
/// points at a real token; falling back to `prev_span()` otherwise) so
/// the diagnostic lands on the right line in multi-function files.
///
/// `header_start` is the span of the function name token captured at the
/// start of `parse_fn_decl`. Passing it through keeps the error pinned to
/// the function name itself rather than whatever was last consumed
/// (which can be a `>` on the same line — fine — but is cleaner this way).
///
/// EOF is treated as a "soft boundary" here: a file that simply ends
/// inside a function header is the same class of bug as one that
/// continues into another decl, and the persona needs the same hint.
/// Without this branch, EOF mid-header falls through to the default
/// `peek_span()` error path which returns `Span::UNKNOWN` and renders
/// as line 1 col 1 — pre-existing infra-wide limitation we route around
/// here for the fn-header case specifically.
fn check_fn_header_boundary(&self, fn_name: &str, header_start: Span) -> Result<()> {
if self.boundary_at_cursor().is_none() && !self.at_end() {
return Ok(());
}
let mut anchor = header_start;
if anchor.start == anchor.end {
anchor = self.prev_span();
}
let trailing = if self.at_end() {
"header runs off the end of the file"
} else {
"header runs off the end of the line"
};
Err(ParseError {
code: "ILO-P020",
position: self.pos,
span: anchor,
message: format!("incomplete function header for `{fn_name}`: {trailing}"),
hint: Some(
"a function header is `name params>type;body` — finish it on the same line, or indent the continuation so the parser keeps it inside this function".to_string(),
),
})
}
fn peek(&self) -> Option<&Token> {
self.tokens.get(self.pos).map(|(t, _)| t)
}
fn peek_span(&self) -> Span {
self.tokens
.get(self.pos)
.map(|(_, s)| *s)
.unwrap_or(Span::UNKNOWN)
}
fn advance(&mut self) -> Option<&Token> {
let tok = self.tokens.get(self.pos).map(|(t, _)| t);
if tok.is_some() {
self.pos += 1;
}
tok
}
fn expect(&mut self, expected: &Token) -> Result<Span> {
match self.peek() {
Some(tok) if tok == expected => {
let span = self.peek_span();
self.advance();
Ok(span)
}
Some(tok) => {
let hint = if *expected == Token::Greater
&& *tok == Token::Minus
&& self.token_at(self.pos + 1) == Some(&Token::Greater)
{
Some("ilo uses '>' not '->' for the return type separator".to_string())
} else if *expected == Token::LBrace && *tok == Token::Semi {
// Multi-line function-body / loop-body / guard-body from
// other-language indentation (qa-tester, devops-sre,
// pdf-analyst, html-scraper rerun3). Newlines between
// body statements are collapsed to `;` by the lexer,
// so `@k kws\n body` becomes `@k kws;body` and the
// foreach's required `{` lands on a `;` instead.
Some(
"ilo bodies are single-line, `;`-separated. If you broke the body across lines, collapse it onto one line or wrap with `{ ... }`. For example `@k kws{body};...` not `@k kws;body`.".to_string()
)
} else {
None
};
let mut err = self.error(
"ILO-P003",
format!("expected {:?}, got {:?}", expected, tok),
);
err.hint = hint;
Err(err)
}
None => Err(self.error("ILO-P004", format!("expected {:?}, got EOF", expected))),
}
}
fn expect_ident(&mut self) -> Result<String> {
match self.peek().cloned() {
Some(Token::Ident(name)) => {
self.advance();
Ok(name)
}
Some(tok) => {
if let Some((msg, hint)) = reserved_keyword_message(&tok) {
Err(self.error_hint("ILO-P011", msg, hint))
} else {
Err(self.error("ILO-P005", format!("expected identifier, got {:?}", tok)))
}
}
None => Err(self.error("ILO-P006", "expected identifier, got EOF".into())),
}
}
fn error(&self, code: &'static str, message: String) -> ParseError {
ParseError {
code,
position: self.pos,
span: self.peek_span(),
message,
hint: None,
}
}
fn error_hint(&self, code: &'static str, message: String, hint: String) -> ParseError {
ParseError {
code,
position: self.pos,
span: self.peek_span(),
message,
hint: Some(hint),
}
}
fn at_end(&self) -> bool {
self.pos >= self.tokens.len()
}
/// Check if we're at a body terminator (end of input, `}`, or end of declaration)
fn at_body_end(&self) -> bool {
matches!(self.peek(), None | Some(Token::RBrace))
}
/// Access raw token (for lookahead). Returns just the Token reference.
fn token_at(&self, idx: usize) -> Option<&Token> {
self.tokens.get(idx).map(|(t, _)| t)
}
// ---- Top-level parsing ----
pub fn parse_program(&mut self) -> (Program, Vec<ParseError>) {
let mut declarations = Vec::new();
let mut errors: Vec<ParseError> = Vec::new();
const MAX_ERRORS: usize = 20;
// Cascade suppression: once we've reported a P001 at the top level, drop
// further P001 errors until the parser successfully consumes another
// declaration. The first P001 nearly always has the actionable hint;
// subsequent ones are noise produced while resyncing through stray
// tokens (e.g. a leftover `}` after a body-level parse failure).
let mut suppress_p001 = false;
while !self.at_end() {
if errors.len() >= MAX_ERRORS {
break;
}
let before_pos = self.pos;
match self.parse_decl() {
Ok(decl) => {
declarations.push(decl);
suppress_p001 = false;
}
Err(e) => {
let err_span = e.span;
let is_cascade_class = matches!(e.code, "ILO-P001" | "ILO-P002");
if !(is_cascade_class && suppress_p001) {
errors.push(e);
}
if is_cascade_class {
suppress_p001 = true;
}
let end_span = self.sync_to_decl_boundary();
declarations.push(Decl::Error {
span: err_span.merge(end_span),
});
// Guarantee forward progress so we cannot loop emitting the
// same error against the same token (e.g. a stray `}`).
if self.pos == before_pos {
self.advance();
}
}
}
}
// Append synthetic decls emitted by inline-lambda lifting. Their names
// start with `__lit_`, which is not a legal user ident (starts with
// `_`), so there is no collision risk.
declarations.append(&mut self.lifted_decls);
(
Program {
declarations,
source: None,
},
errors,
)
}
/// Return true if the tokens at `pos` look like the start of a function declaration:
/// `Ident` followed by `>` (no-param function) OR `Ident Ident :` (has params).
///
/// Reserved statement-keyword identifiers (`wh`/`ret`/`brk`/`cnt`) are never
/// valid function names — `parse_stmt` intercepts them as control-flow forms.
/// Short-circuiting here closes the `wh >cond{...}` mid-body re-parse trap,
/// where the body-boundary heuristic in `parse_body_with` would otherwise
/// treat `wh >v 0{...}` as a fresh fn decl named `wh` returning `v`.
fn is_fn_decl_start(&self, pos: usize) -> bool {
let name = match self.token_at(pos) {
Some(Token::Ident(n)) => n,
_ => return false,
};
if is_reserved_stmt_keyword(name) {
return false;
}
match self.token_at(pos + 1) {
// name>return — zero-param function
Some(Token::Greater) => true,
// name param:type ... — has params
Some(Token::Ident(_)) => matches!(self.token_at(pos + 2), Some(Token::Colon)),
_ => false,
}
}
/// Stricter variant of `is_fn_decl_start` used at top-level body boundaries
/// to disambiguate fn declarations from record construction. A real fn decl
/// always has `>` followed by a return type before the body's first `;`,
/// while a record `Outer a:1 b:2` never has a `>` before its terminator.
/// Returns true only when a `>` is visible before the next `;`/`}`/`{`/EOF
/// at the same bracket depth.
fn is_fn_decl_start_strict(&self, pos: usize) -> bool {
if !self.is_fn_decl_start(pos) {
return false;
}
// Fast path: `Ident >` is unambiguous in body position because a leading
// `name>` statement is not legal here (no expression starts with a bare
// identifier followed by `>` in a way that doesn't look like a fn decl
// header). Even `a > b` would only appear after a `;`, but it has no
// following `;type;` shape — but we still want to confirm by scanning.
let mut i = pos + 1;
let mut depth: i32 = 0;
while let Some(tok) = self.token_at(i) {
match tok {
Token::LParen | Token::LBracket | Token::LBrace => depth += 1,
Token::RParen | Token::RBracket => depth -= 1,
_ if depth > 0 => {}
Token::Greater if depth == 0 => return true,
Token::Semi | Token::RBrace => return false,
_ => {}
}
i += 1;
}
false
}
/// Advance past tokens until we reach what looks like the start of the next
/// declaration (or EOF). Returns the span of the last token consumed.
/// Tracks brace depth so nested `{…}` blocks are skipped atomically.
fn sync_to_decl_boundary(&mut self) -> Span {
let mut depth: usize = 0;
let mut last_span = self.peek_span();
loop {
match self.peek() {
None => break,
Some(Token::LBrace) => {
depth += 1;
last_span = self.peek_span();
self.advance();
}
Some(Token::RBrace) => {
if depth == 0 {
// Stray top-level `}` — consume it so the outer loop
// makes progress rather than re-reporting the same
// token as a "missing declaration".
last_span = self.peek_span();
self.advance();
break;
}
depth -= 1;
last_span = self.peek_span();
self.advance();
}
// Unambiguous declaration starters
Some(Token::Type) | Some(Token::Tool) if depth == 0 => break,
// An identifier that looks like a function header
_ if depth == 0 && self.is_fn_decl_start(self.pos) => break,
_ => {
last_span = self.peek_span();
self.advance();
}
}
}
last_span
}
fn parse_decl(&mut self) -> Result<Decl> {
// Reserved-keyword binding attempts: `var=5`, `let=5`, `if=5`, ...
// Surface the friendly ILO-P011 message before any expression-level
// cascade fires.
if self.token_at(self.pos + 1) == Some(&Token::Eq)
&& let Some(tok) = self.peek()
&& let Some((msg, _)) = reserved_keyword_message(tok)
{
return Err(self.error_hint(
"ILO-P011",
msg,
"use `name=expr` for bindings (e.g. `count=5`)".to_string(),
));
}
// Loop-control words `cnt`/`brk` used as binding names: `cnt=5`.
if let Some(Token::Ident(name)) = self.peek()
&& (name == "cnt" || name == "brk")
&& self.token_at(self.pos + 1) == Some(&Token::Eq)
{
let (word, role, alt) = if name == "cnt" {
("cnt", "continue", "count")
} else {
("brk", "break", "brake")
};
return Err(self.error_hint(
"ILO-P011",
format!("`{word}` is reserved for {role} (loop control) and cannot be used as an identifier"),
format!("pick a different name like `{alt}` or `{}`", &word[..1]),
));
}
// Builtin `fld` (fold) used as binding name: `fld=5`. Personas reach
// for `fld` as a natural variable (field/fold/folder); the builtin
// collision otherwise surfaces as a misleading ILO-T006 arity error.
if let Some(Token::Ident(name)) = self.peek()
&& name == "fld"
&& self.token_at(self.pos + 1) == Some(&Token::Eq)
{
return Err(self.error_hint(
"ILO-P011",
"`fld` is reserved for the fold builtin and cannot be used as an identifier".into(),
"pick a different name like `field` or `folder`".into(),
));
}
// Any other builtin name used as binding LHS: `flat=...`, `frq=...`,
// `map=...`, etc. Personas hit this constantly (pdf-analyst rerun3 #6:
// `flat=cat ls " "` then `spl flat ". "` mis-dispatched to the builtin
// and surfaced as `arity mismatch: 'flat' expects 1 args, got 0`).
// Mirrors `parse_fn_decl`'s existing `Builtin::is_builtin` rejection.
if let Some(Token::Ident(name)) = self.peek()
&& self.token_at(self.pos + 1) == Some(&Token::Eq)
&& Builtin::is_builtin(name)
{
let name = name.clone();
return Err(self.error_hint(
"ILO-P011",
format!("`{name}` is a builtin and cannot be used as a binding name"),
format!("rename to something like `my{name}` or `{name}v`. Builtins shadow local bindings in call position, so reusing the name silently mis-dispatches."),
));
}
match self.peek() {
Some(Token::Type) => self.parse_type_decl(),
Some(Token::Tool) => self.parse_tool_decl(),
Some(Token::Use) => self.parse_use_decl(),
Some(Token::Ident(_)) => {
// Check for keywords from other languages before attempting fn parse
let ident_str = match self.peek() {
Some(Token::Ident(s)) => s.as_str(),
_ => unreachable!(),
};
if ident_str == "alias" {
return self.parse_alias_decl();
}
let hint = match ident_str {
"function" | "def" | "fn" =>
Some("ilo function syntax: name param:type > return-type; body".to_string()),
"let" | "var" | "const" =>
Some("ilo uses assignment syntax: name = expr".to_string()),
"return" =>
Some("the last expression in a function body is the return value — no 'return' keyword".to_string()),
"if" =>
Some("ilo uses match for conditionals: ?expr{true:... false:...}".to_string()),
_ => None,
};
if let Some(hint_msg) = hint {
let mut err = self.error(
"ILO-P001",
format!("expected declaration, got Ident({ident_str:?})"),
);
err.hint = Some(hint_msg);
return Err(err);
}
self.parse_fn_decl()
}
Some(tok) => {
let msg = format!("expected declaration, got {:?}", tok);
let hint = match tok {
Token::Plus | Token::Minus | Token::Star | Token::Slash
| Token::Greater | Token::Less | Token::GreaterEq | Token::LessEq
| Token::Eq | Token::NotEq | Token::Amp | Token::Pipe
| Token::Bang | Token::Tilde | Token::Caret =>
Some("prefix operators can't start a declaration. Bind call results to variables: r=fac -n 1;*n r".to_string()),
Token::KwFn | Token::KwDef =>
Some("ilo function syntax: name param:type > return-type; body".to_string()),
Token::KwLet | Token::KwVar | Token::KwConst =>
Some("ilo uses assignment syntax: name = expr".to_string()),
Token::KwReturn =>
Some("the last expression in a function body is the return value — no 'return' keyword".to_string()),
Token::KwIf =>
Some("ilo uses match for conditionals: ?expr{true:... false:...}".to_string()),
_ => None,
};
let mut err = self.error("ILO-P001", msg);
err.hint = hint;
Err(err)
}
None => Err(self.error("ILO-P002", "expected declaration, got EOF".into())),
}
}
/// `use "path/to/file.ilo"` or `use "path/to/file.ilo" [name1 name2]`
fn parse_use_decl(&mut self) -> Result<Decl> {
let start = self.peek_span();
self.expect(&Token::Use)?;
let path = match self.peek().cloned() {
Some(Token::Text(p)) => {
self.advance();
p
}
Some(tok) => {
return Err(self.error(
"ILO-P016",
format!("expected a string path after `use`, got {:?}", tok),
));
}
None => {
return Err(self.error(
"ILO-P016",
"expected a string path after `use`, got EOF".into(),
));
}
};
// Optional `[name1 name2 ...]` scoped import list
let only = if self.peek() == Some(&Token::LBracket) {
self.advance(); // consume `[`
let mut names = Vec::new();
while self.peek() != Some(&Token::RBracket) {
match self.peek() {
None => {
return Err(self.error("ILO-P016", "unclosed `[` in use statement".into()));
}
_ => names.push(self.expect_ident()?),
}
}
self.expect(&Token::RBracket)?;
if names.is_empty() {
return Err(self.error(
"ILO-P016",
"use `[...]` list must not be empty — omit brackets to import all".into(),
));
}
Some(names)
} else {
None
};
let end = self.peek_span();
Ok(Decl::Use {
path,
only,
span: start.merge(end),
})
}
/// `type name{field:type;...}`
fn parse_type_decl(&mut self) -> Result<Decl> {
let start = self.peek_span();
self.expect(&Token::Type)?;
let name = self.expect_ident()?;
self.expect(&Token::LBrace)?;
let mut fields = Vec::new();
while self.peek() != Some(&Token::RBrace) {
if !fields.is_empty() {
self.expect(&Token::Semi)?;
}
let fname = self.expect_ident()?;
self.expect(&Token::Colon)?;
let ty = self.parse_type()?;
fields.push(Param { name: fname, ty });
}
let end = self.peek_span();
self.expect(&Token::RBrace)?;
Ok(Decl::TypeDef {
name,
fields,
span: start.merge(end),
})
}
/// `tool name"desc" params>return timeout:n,retry:n`
fn parse_tool_decl(&mut self) -> Result<Decl> {
let start = self.peek_span();
self.expect(&Token::Tool)?;
let name = self.expect_ident()?;
let description = match self.peek().cloned() {
Some(Token::Text(s)) => {
self.advance();
s
}
_ => return Err(self.error("ILO-P015", "expected tool description string".into())),
};
let params = self.parse_params()?;
self.expect(&Token::Greater)?;
let return_type = self.parse_type()?;
let mut timeout = None;
let mut retry = None;
// Parse optional tool options: timeout:n,retry:n
while matches!(self.peek(), Some(Token::Timeout) | Some(Token::Retry)) {
match self.peek() {
Some(Token::Timeout) => {
self.advance();
self.expect(&Token::Colon)?;
timeout = Some(self.parse_number()?);
}
Some(Token::Retry) => {
self.advance();
self.expect(&Token::Colon)?;
retry = Some(self.parse_number()?);
}
_ => break,
}
if self.peek() == Some(&Token::Comma) {
self.advance();
}
}
// End span: last consumed token
let end_span = self.prev_span();
Ok(Decl::Tool {
name,
description,
params,
return_type,
timeout,
retry,
span: start.merge(end_span),
})
}
/// `alias name type`
fn parse_alias_decl(&mut self) -> Result<Decl> {
let start = self.peek_span();
// consume the `alias` identifier
self.advance();
let name = self.expect_ident()?;
let target = self.parse_type()?;
let end = self.prev_span();
Ok(Decl::Alias {
name,
target,
span: start.merge(end),
})
}
/// `name params>return;body`
fn parse_fn_decl(&mut self) -> Result<Decl> {
let start = self.peek_span();
let name = self.expect_ident()?;
// Reject user functions whose name collides with a builtin. Without this
// the verifier's call-dispatch (which checks `is_builtin` before user
// `self.functions`) would silently shadow the user function and report
// a misleading arity error from the builtin's signature (e.g. a
// persona writes `lst>n;42` + `lst()` and gets
// `ILO-T006 'lst' expects 3 args, got 0` from the 3-arg list-ctor
// builtin). Same precedent applies in `parse_stmt` for `fld=`/`cnt=`/
// `brk=` bindings — keep the diagnostic shape consistent.
if Builtin::is_builtin(&name) {
return Err(self.error_hint(
"ILO-P011",
format!(
"`{name}` is a builtin and cannot be used as a function name"
),
format!(
"rename to something like `my{name}` or `{name}of` — builtins shadow user functions in calls, so reusing the name silently breaks dispatch"
),
));
}
let params = self.parse_params()?;
// After params, before we touch `>` and the return type, make sure we
// haven't crossed a top-level decl boundary. If we have, the header
// is incomplete — surface ILO-P020 anchored at this function's name
// rather than letting `expect(Greater)`/`parse_type` walk into the
// next function and report the error on the wrong line.
self.check_fn_header_boundary(&name, start)?;
// Register arity + per-param fn-ref flags BEFORE parsing the body so
// recursive self-references inside the body benefit from eager
// call-arg expansion (e.g. `fac n:n>n;?=n 0{1}{*n fac -n 1}` —
// `fac -n 1` is parsed as a single nested call).
self.register_user_fn(&name, ¶ms);
// Friendly hint for `name:>R` from other-language signature shapes
// (qa-tester rerun3, `main:>n`). ilo's no-param signature is
// `name>return;body` — no `:` between the name and `>`. The default
// `expect(Greater)` would surface a bare `ILO-P003: expected Greater,
// got Colon` which doesn't mention the actual fix.
if params.is_empty()
&& self.peek() == Some(&Token::Colon)
&& self.token_at(self.pos + 1) == Some(&Token::Greater)
{
return Err(self.error_hint(
"ILO-P003",
format!(
"unexpected `:>` after `{name}` — ilo signatures don't put a colon before the return-type separator"
),
format!(
"write `{name}>return;body` for a no-param function, or `{name} p:t>return;body` if params were intended"
),
));
}
self.expect(&Token::Greater)?;
// Same check between `>` and the return type: `f2 a:n>\n` must report
// against `f2`, not against whatever ident starts the next line.
self.check_fn_header_boundary(&name, start)?;
let return_type = self.parse_type()?;
// The header/body boundary is normally a `;`, but a newline (filtered
// out before parsing) leaves no separator. Accept either: consume a
// `;` if present, otherwise fall straight into the body.
if self.peek() == Some(&Token::Semi) {
self.advance();
}
let body = self.parse_body_with(true)?;
let end = self.prev_span();
Ok(Decl::Function {
name,
params,
return_type,
body,
span: start.merge(end),
})
}
/// Span of the previously consumed token.
fn prev_span(&self) -> Span {
if self.pos > 0 {
self.tokens[self.pos - 1].1
} else {
Span::UNKNOWN
}
}
/// If the next token is `!` or `!!` immediately adjacent (no whitespace)
/// to the previously-consumed token, consume it and return the matching
/// `UnwrapMode`. Otherwise return `UnwrapMode::None` and consume nothing.
///
/// Adjacency is what distinguishes `func!` (postfix unwrap) from
/// `func !x` (call with a `!x` argument), and likewise for `!!`.
fn maybe_postfix_unwrap(&mut self) -> UnwrapMode {
let prev = self.prev_span();
let next_span = self.peek_span();
let adjacent = prev.end > 0 && next_span.start == prev.end;
if !adjacent {
return UnwrapMode::None;
}
match self.peek() {
Some(Token::BangBang) => {
self.advance();
UnwrapMode::Panic
}
Some(Token::Bang) => {
self.advance();
UnwrapMode::Propagate
}
_ => UnwrapMode::None,
}
}
// ---- Types ----
fn parse_type(&mut self) -> Result<Type> {
// Safety net: if we're about to read a type from across a top-level
// declaration boundary or from past EOF, the source is malformed (a
// nested type slot ran off the end of its line — e.g.
// `f2 a:n>R\nmain>...` where `R` expects an err-type that never
// arrives, or `main a:n>R` where the file ends). Anchor the
// diagnostic at the previous token so it lands on the offending
// function's line rather than wherever the next declaration starts
// (or line 1 col 1 when EOF falls back to `Span::UNKNOWN`).
// Header-level callers (`parse_fn_decl`) catch this first and emit
// the friendlier ILO-P020; this guard only fires for nested type
// slots inside `R`/`M`/`F`/`L`/`O`/`S` where the header-level check
// can't see in.
if self.boundary_at_cursor().is_some() || self.at_end() {
let (code, msg): (&'static str, &str) = if self.at_end() {
("ILO-P008", "expected type, got end of file")
} else {
("ILO-P007", "expected type, got end of line")
};
return Err(ParseError {
code,
position: self.pos,
span: self.prev_span(),
message: msg.to_string(),
hint: None,
});
}
match self.peek().cloned() {
Some(Token::LParen) => {
self.advance();
let inner = self.parse_type()?;
self.expect(&Token::RParen)?;
Ok(inner)
}
Some(Token::Ident(ref s)) if s == "n" => {
self.advance();
Ok(Type::Number)
}
Some(Token::Ident(ref s)) if s == "t" => {
self.advance();
Ok(Type::Text)
}
Some(Token::Ident(ref s)) if s == "b" => {
self.advance();
Ok(Type::Bool)
}
Some(Token::Underscore) => {
self.advance();
Ok(Type::Any)
}
Some(Token::OptType) => {
self.advance();
let inner = self.parse_type()?;
Ok(Type::Optional(Box::new(inner)))
}
Some(Token::ListType) => {
self.advance();
let inner = self.parse_type()?;
Ok(Type::List(Box::new(inner)))
}
Some(Token::MapType) => {
self.advance();
let key_type = self.parse_type()?;
let val_type = self.parse_type()?;
Ok(Type::Map(Box::new(key_type), Box::new(val_type)))
}
Some(Token::ResultType) => {
self.advance();
let ok_type = self.parse_type()?;
let err_type = self.parse_type()?;
Ok(Type::Result(Box::new(ok_type), Box::new(err_type)))
}
Some(Token::SumType) => {
self.advance();
// Collect variant names: lowercase idents not followed by colon.
let mut variants = Vec::new();
while let Some(Token::Ident(_)) = self.peek() {
// Ident followed by colon = param name, stop.
if self.token_at(self.pos + 1) == Some(&Token::Colon) {
break;
}
if let Some(Token::Ident(name)) = self.peek().cloned() {
variants.push(name);
self.advance();
}
}
if variants.is_empty() {
return Err(
self.error("ILO-P010", "S type requires at least one variant".into())
);
}
Ok(Type::Sum(variants))
}
Some(Token::FnType) => {
self.advance();
// Collect all following types; last is return type, preceding are params.
// Stop when the next token cannot start a type, is >, ;, }, or is an Ident
// followed by : (which would be a new parameter name, not a type).
let mut types = Vec::new();
loop {
if !self.can_start_type() {
break;
}
// An Ident followed by Colon is a param name, not a type.
if matches!(self.peek(), Some(Token::Ident(_)))
&& self.token_at(self.pos + 1) == Some(&Token::Colon)
{
break;
}
types.push(self.parse_type()?);
}
if types.is_empty() {
return Err(
self.error("ILO-P009", "F type requires at least a return type".into())
);
}
let return_type = types.pop().expect("F type requires at least a return type");
Ok(Type::Fn(types, Box::new(return_type)))
}
Some(Token::Ident(name)) => {
self.advance();
Ok(Type::Named(name))
}
Some(tok) => Err(self.error("ILO-P007", format!("expected type, got {:?}", tok))),
None => Err(self.error("ILO-P008", "expected type, got EOF".into())),
}
}
/// Returns true if the current token can begin a type expression.
fn can_start_type(&self) -> bool {
match self.peek() {
Some(Token::Ident(s)) => {
matches!(s.as_str(), "n" | "t" | "b")
|| self.token_at(self.pos + 1) != Some(&Token::Colon)
}
Some(Token::Underscore) => true,
Some(Token::OptType) => true,
Some(Token::ListType) => true,
Some(Token::MapType) => true,
Some(Token::ResultType) => true,
Some(Token::SumType) => true,
Some(Token::FnType) => true,
Some(Token::LParen) => true,
_ => false,
}
}
/// Parse parameter list: `name:type name:type ...`
///
/// Stops at the first non-`Ident:type` shape, and also stops at a top-level
/// declaration boundary (an unindented newline in the source) so a
/// malformed header like `f2 a:n` missing its `>type` does not slurp the
/// next function's name (`main`) as another parameter.
fn parse_params(&mut self) -> Result<Vec<Param>> {
let mut params = Vec::new();
while let Some(Token::Ident(_)) = self.peek() {
// A top-level newline before the next ident means the previous
// function's header ended without a `>type;body` — stop here and
// let `parse_fn_decl` surface a precise ILO-P020 against the
// offending function's line, instead of letting this loop drag
// tokens across the boundary.
if self.boundary_at_cursor().is_some() {
break;
}
// Look ahead for colon to distinguish params from other constructs
if self.pos + 1 < self.tokens.len()
&& self.token_at(self.pos + 1) == Some(&Token::Colon)
{
let name = self.expect_ident()?;
self.expect(&Token::Colon)?;
let ty = self.parse_type()?;
params.push(Param { name, ty });
} else {
break;
}
}
Ok(params)
}
// ---- Body & Statements ----
/// Parse a semicolon-separated body, wrapping each statement with its source span.
fn parse_body(&mut self) -> Result<Vec<Spanned<Stmt>>> {
self.parse_body_with(false)
}
/// Parse a semicolon-separated body. When `top_level` is true, the body
/// also terminates if the tokens after a `;` look like the start of the
/// next top-level function declaration. This closes the "sibling helper
/// slurp" trap where a body's final bare call would otherwise consume the
/// next function's name as an argument (and the trailing `>type;` would
/// then be parsed as a comparison, hiding the boundary).
fn parse_body_with(&mut self, top_level: bool) -> Result<Vec<Spanned<Stmt>>> {
let mut stmts = Vec::new();
if !self.at_body_end() {
let span_start = self.peek_span();
let stmt = self.parse_stmt()?;
stmts.push(Spanned {
node: stmt,
span: span_start.merge(self.prev_span()),
});
while self.peek() == Some(&Token::Semi) {
self.advance();
if self.at_body_end() {
break;
}
if top_level && self.is_fn_decl_start_strict(self.pos) {
break;
}
let span_start = self.peek_span();
let stmt = self.parse_stmt()?;
stmts.push(Spanned {
node: stmt,
span: span_start.merge(self.prev_span()),
});
}
}
Ok(stmts)
}
fn parse_stmt(&mut self) -> Result<Stmt> {
// Reserved-keyword binding attempts inside a function body: `var=5`,
// `let=5`, `if=5`, ... Surface the friendly ILO-P011 message before
// `parse_atom` cascades into a cryptic ILO-P009.
if self.token_at(self.pos + 1) == Some(&Token::Eq)
&& let Some(tok) = self.peek()
&& let Some((msg, _)) = reserved_keyword_message(tok)
{
return Err(self.error_hint(
"ILO-P011",
msg,
"use `name=expr` for bindings (e.g. `count=5`)".to_string(),
));
}
match self.peek() {
Some(Token::Question) => {
if self.is_prefix_ternary() {
let expr = self.parse_prefix_ternary()?;
Ok(Stmt::Expr(expr))
} else {
self.parse_match_stmt()
}
}
Some(Token::At) => self.parse_foreach(),
Some(Token::Ident(name)) if name == "ret" => {
self.advance(); // consume "ret"
let value = self.parse_expr()?;
Ok(Stmt::Return(value))
}
Some(Token::Ident(name)) if name == "brk" => {
if self.token_at(self.pos + 1) == Some(&Token::Eq) {
return Err(self.error_hint(
"ILO-P011",
"`brk` is reserved for break (loop control) and cannot be used as an identifier".into(),
"pick a different name like `brake` or `b`".into(),
));
}
self.advance(); // consume "brk"
// brk with optional value expression
let value = if self.at_body_end() {
None
} else {
Some(self.parse_expr()?)
};
Ok(Stmt::Break(value))
}
Some(Token::Ident(name)) if name == "cnt" => {
if self.token_at(self.pos + 1) == Some(&Token::Eq) {
return Err(self.error_hint(
"ILO-P011",
"`cnt` is reserved for continue (loop control) and cannot be used as an identifier".into(),
"pick a different name like `count` or `c`".into(),
));
}
self.advance(); // consume "cnt"
Ok(Stmt::Continue)
}
Some(Token::Ident(name))
if name == "fld" && self.token_at(self.pos + 1) == Some(&Token::Eq) =>
{
Err(self.error_hint(
"ILO-P011",
"`fld` is reserved for the fold builtin and cannot be used as an identifier"
.into(),
"pick a different name like `field` or `folder`".into(),
))
}
Some(Token::Ident(name)) if name == "wh" => {
self.advance(); // consume "wh"
let condition = self.parse_expr()?;
self.expect(&Token::LBrace)?;
let body = self.parse_body()?;
self.expect(&Token::RBrace)?;
Ok(Stmt::While { condition, body })
}
Some(Token::LBrace) if self.is_destructure_pattern() => self.parse_destructure(),
Some(Token::Ident(_)) => {
// Check for let binding: ident '='
if self.pos + 1 < self.tokens.len()
&& self.token_at(self.pos + 1) == Some(&Token::Eq)
{
// Reject builtin-named binding LHS: `flat=...`, `frq=...`,
// `map=...`, etc. Without this, the local binding is
// silently accepted but any later use in operand position
// resolves to the builtin (the verifier checks
// `is_builtin` before locals), surfacing as a misleading
// `ILO-T006 arity mismatch` (pdf-analyst rerun3 #6).
// Mirrors `parse_fn_decl`'s precedent (PR #245).
if let Some(Token::Ident(name)) = self.peek()
&& Builtin::is_builtin(name)
{
let name = name.clone();
return Err(self.error_hint(
"ILO-P011",
format!("`{name}` is a builtin and cannot be used as a binding name"),
format!("rename to something like `my{name}` or `{name}v`. Builtins shadow local bindings in call position, so reusing the name silently mis-dispatches."),
));
}
self.parse_let()
} else {
// Could be a guard or an expression statement
self.parse_expr_or_guard()
}
}
Some(Token::Bang) => {
// !cond{body} — negated guard
self.parse_bang_stmt()
}
Some(Token::Caret) => {
// ^expr — Err constructor as statement
self.parse_caret_stmt()
}
_ => {
let expr = self.parse_expr()?;
// Check if this is a guard: expr followed by {
if self.peek() == Some(&Token::LBrace) {
let body = self.parse_brace_body()?;
let else_body = if self.peek() == Some(&Token::LBrace) {
Some(self.parse_brace_body()?)
} else {
None
};
Ok(Stmt::Guard {
condition: expr,
negated: false,
body,
else_body,
braceless: false,
})
} else if is_guard_eligible_condition(&expr) && self.can_start_operand() {
Ok(self.parse_braceless_guard_body(expr, false)?)
} else {
Ok(Stmt::Expr(expr))
}
}
}
}
fn parse_let(&mut self) -> Result<Stmt> {
let name = self.expect_ident()?;
self.expect(&Token::Eq)?;
// Friendly hint: `name={...}` is a common reach for a map-literal from
// other languages. ilo builds maps with `mmap` + `mset`. Catch it
// before parse_expr emits the bare ILO-P009 "expected expression,
// got LBrace".
if self.peek() == Some(&Token::LBrace) && self.brace_looks_like_map_literal() {
return Err(self.error_hint(
"ILO-P009",
format!(
"`{name}={{...}}` — ilo has no `{{key value}}` map literal syntax"
),
format!(
"build maps with `mmap` (empty) and `mset`, e.g. `{name}=mset mmap \"k\" v` (chain `mset` for multiple entries)"
),
));
}
let value = self.parse_expr()?;
// Check if this is a ternary assignment: v=cond{then}{else}
// or a conditional assignment: v=cond{body}
if self.peek() == Some(&Token::LBrace) && is_guard_eligible_condition(&value) {
let then_body = self.parse_brace_body()?;
if self.peek() == Some(&Token::LBrace) {
// Two brace blocks: v=cond{then}{else}
// Desugar to: Let { name, value: Ternary { condition, then_expr, else_expr } }
let else_body = self.parse_brace_body()?;
let then_expr = body_to_expr(then_body);
let else_expr = body_to_expr(else_body);
Ok(Stmt::Let {
name,
value: Expr::Ternary {
condition: Box::new(value),
then_expr: Box::new(then_expr),
else_expr: Box::new(else_expr),
},
})
} else {
// Single brace block: v=cond{body} (conditional assignment)
// Desugar to: Guard { condition, body: [Let { name, value: last_expr }] }
let body_with_let = wrap_body_as_let(&name, then_body);
Ok(Stmt::Guard {
condition: value,
negated: false,
body: body_with_let,
else_body: None,
braceless: false,
})
}
} else {
Ok(Stmt::Let { name, value })
}
}
/// Lookahead: does the `{` at current position look like a map-literal
/// attempt from another language? We fire only on shapes that are
/// unambiguously not a destructure or some other valid form:
/// `{"text" ...}`, `{<number> ...}`, or `{}` (empty braces).
/// Idents inside braces could be destructure shapes, so we skip them.
fn brace_looks_like_map_literal(&self) -> bool {
if self.peek() != Some(&Token::LBrace) {
return false;
}
matches!(
self.token_at(self.pos + 1),
Some(Token::Text(_) | Token::Number(_) | Token::RBrace)
)
}
/// Lookahead: `{ident;ident...}=` — destructure pattern
fn is_destructure_pattern(&self) -> bool {
let mut pos = self.pos + 1; // skip `{`
loop {
match self.token_at(pos) {
Some(Token::Ident(_)) => pos += 1,
Some(Token::Semi) => pos += 1,
Some(Token::RBrace) => {
return self.token_at(pos + 1) == Some(&Token::Eq);
}
_ => return false,
}
}
}
/// `{a;b;c}=expr` — destructure record fields into bindings
fn parse_destructure(&mut self) -> Result<Stmt> {
self.expect(&Token::LBrace)?;
let mut bindings = Vec::new();
loop {
let name = self.expect_ident()?;
bindings.push(name);
if self.peek() == Some(&Token::Semi) {
self.advance(); // consume `;`
} else {
break;
}
}
self.expect(&Token::RBrace)?;
self.expect(&Token::Eq)?;
let value = self.parse_expr()?;
Ok(Stmt::Destructure { bindings, value })
}
/// `?{arms}` or `?expr{arms}`
fn parse_match_stmt(&mut self) -> Result<Stmt> {
self.expect(&Token::Question)?;
let subject = if self.peek() == Some(&Token::LBrace) {
None
} else {
Some(self.parse_atom()?)
};
self.expect(&Token::LBrace)?;
// Friendly hint: `?cond{body}` on a bare bool is a common slip — the
// user reaches for braced-conditional execution but gets match syntax
// and the body is parsed as a pattern. If the body shape is clearly
// statement-like (not pattern-like) and a subject is present, suggest
// the `=cond true{body}` braced-conditional form.
if let Some(subj) = &subject {
if self.body_looks_like_statement_not_pattern() {
if let Some(subj_src) = subject_source(subj) {
return Err(self.error_hint(
"ILO-P011",
format!(
"`?{subj_src}{{...}}` is match syntax — the body is parsed as pattern arms, not statements"
),
format!(
"for braced-conditional execution on a bool, use `={subj_src} true{{body}}` (or `!{subj_src}{{body}}` for the negated case)"
),
));
}
}
}
let arms = self.parse_match_arms()?;
self.expect(&Token::RBrace)?;
Ok(Stmt::Match { subject, arms })
}
/// After consuming `{` in a `?subject{...}` match, peek to see whether the
/// first arm body looks like a statement rather than a pattern. Patterns
/// have a `:` within the first 1-3 tokens; statement-shape bodies do not.
fn body_looks_like_statement_not_pattern(&self) -> bool {
// Empty body / immediate `}` — not a statement; let the normal parser
// surface its own error.
if matches!(self.peek(), Some(Token::RBrace) | None) {
return false;
}
// Look at the first identifier-led shape only. Patterns that start
// with `^`, `~`, `_`, literal, or type-letter (`n`, `t`, `b`, `l`)
// followed by ident — those we leave to parse_pattern. Statement-like:
// `Ident =` (let), `Ident <op-not-colon>` (call/expr).
match self.peek() {
Some(Token::Ident(name)) => {
// Type-letter pattern: `n x:` / `t x:` / `b x:` / `l x:` —
// an ident followed by another ident (or `_`) followed by `:`.
if matches!(name.as_str(), "n" | "t" | "b" | "l")
&& matches!(
self.token_at(self.pos + 1),
Some(Token::Ident(_) | Token::Underscore)
)
&& self.token_at(self.pos + 2) == Some(&Token::Colon)
{
return false;
}
// Plain `Ident :` is also a pattern shape (less common).
if self.token_at(self.pos + 1) == Some(&Token::Colon) {
return false;
}
// Otherwise an ident followed by `=` or any operator is a
// statement.
true
}
// `+`, `-`, `*`, `/`, `=`, `>=`, `<=`, `<`, `>`, `!=`, `==` etc.
// at body head are clearly statement-shape expressions.
Some(t) if is_statement_head_operator(t) => true,
_ => false,
}
}
fn parse_match_arms(&mut self) -> Result<Vec<MatchArm>> {
let mut arms = Vec::new();
while self.peek() != Some(&Token::RBrace) {
if !arms.is_empty() {
self.expect(&Token::Semi)?;
if self.peek() == Some(&Token::RBrace) {
break;
}
}
arms.push(self.parse_match_arm()?);
}
Ok(arms)
}
fn parse_match_arm(&mut self) -> Result<MatchArm> {
let pattern = self.parse_pattern()?;
self.expect(&Token::Colon)?;
let body = self.parse_arm_body()?;
Ok(MatchArm { pattern, body })
}
/// Parse body of a match arm — multiple statements until next arm pattern or `}`.
///
/// Two body shapes are accepted:
/// - Brace block: `~v:{stmt1;stmt2;final-expr}` — mirrors `=cond{block}` grammar,
/// makes the arm boundary unambiguous when the body contains call-shapes that
/// could look like patterns. Final stmt is the arm value.
/// - Inline `;`-separated: `~v:stmt1;stmt2;final-expr` — existing form. `;` followed
/// by a pattern-shaped token sequence starts a new arm (see `semi_starts_new_arm`).
fn parse_arm_body(&mut self) -> Result<Vec<Spanned<Stmt>>> {
// Brace-block form: only when the `{...}` is not a destructure pattern start
// (e.g. `{a, b}=v` is a destructure assignment, kept on the inline path).
if self.peek() == Some(&Token::LBrace) && !self.is_destructure_pattern() {
return self.parse_brace_body();
}
let mut stmts = Vec::new();
if !self.at_arm_end() {
let span_start = self.peek_span();
let stmt = self.parse_stmt()?;
stmts.push(Spanned {
node: stmt,
span: span_start.merge(self.prev_span()),
});
// Continue consuming statements if `;` is followed by non-pattern content
while self.peek() == Some(&Token::Semi) && !self.semi_starts_new_arm() {
self.advance(); // consume ;
if self.at_arm_end() {
break;
}
let span_start = self.peek_span();
let stmt = self.parse_stmt()?;
stmts.push(Spanned {
node: stmt,
span: span_start.merge(self.prev_span()),
});
}
}
Ok(stmts)
}
/// Check if the `;` at current position starts a new match arm.
/// A new arm starts with a pattern followed by `:`.
fn semi_starts_new_arm(&self) -> bool {
if self.peek() != Some(&Token::Semi) {
return false;
}
// Look past the `;`
let after_semi = self.pos + 1;
if after_semi >= self.tokens.len() {
return false;
}
match self.token_at(after_semi) {
// ^ident: or ^_: → err pattern
Some(Token::Caret) => matches!(
(self.token_at(after_semi + 1), self.token_at(after_semi + 2)),
(
Some(Token::Ident(_) | Token::Underscore),
Some(Token::Colon)
)
),
// ~ident: or ~_: → ok pattern
Some(Token::Tilde) => matches!(
(self.token_at(after_semi + 1), self.token_at(after_semi + 2)),
(
Some(Token::Ident(_) | Token::Underscore),
Some(Token::Colon)
)
),
// _: → wildcard
Some(Token::Underscore) => {
after_semi + 1 < self.tokens.len()
&& self.token_at(after_semi + 1) == Some(&Token::Colon)
}
// literal: → literal pattern (number, string, bool)
Some(Token::Number(_) | Token::Text(_) | Token::True | Token::False | Token::Nil) => {
after_semi + 1 < self.tokens.len()
&& self.token_at(after_semi + 1) == Some(&Token::Colon)
}
// n/t/b/l ident: or n/t/b/l _: → TypeIs pattern
Some(Token::Ident(ty_name)) if matches!(ty_name.as_str(), "n" | "t" | "b" | "l") => {
matches!(
(self.token_at(after_semi + 1), self.token_at(after_semi + 2)),
(
Some(Token::Ident(_) | Token::Underscore),
Some(Token::Colon)
)
)
}
_ => false,
}
}
fn at_arm_end(&self) -> bool {
matches!(self.peek(), None | Some(Token::RBrace) | Some(Token::Semi))
}
fn parse_pattern(&mut self) -> Result<Pattern> {
match self.peek() {
Some(Token::Caret) => {
self.advance();
let name = match self.peek() {
Some(Token::Underscore) => {
self.advance();
"_".to_string()
}
_ => self.expect_ident()?,
};
Ok(Pattern::Err(name))
}
Some(Token::Tilde) => {
self.advance();
let name = match self.peek() {
Some(Token::Underscore) => {
self.advance();
"_".to_string()
}
_ => self.expect_ident()?,
};
Ok(Pattern::Ok(name))
}
Some(Token::Underscore) => {
self.advance();
Ok(Pattern::Wildcard)
}
Some(Token::Number(_)) => {
if let Some(Token::Number(n)) = self.advance().cloned() {
Ok(Pattern::Literal(Literal::Number(n)))
} else {
unreachable!()
}
}
Some(Token::Text(_)) => {
if let Some(Token::Text(s)) = self.advance().cloned() {
Ok(Pattern::Literal(Literal::Text(s)))
} else {
unreachable!()
}
}
Some(Token::True) => {
self.advance();
Ok(Pattern::Literal(Literal::Bool(true)))
}
Some(Token::False) => {
self.advance();
Ok(Pattern::Literal(Literal::Bool(false)))
}
Some(Token::Nil) => {
self.advance();
Ok(Pattern::Literal(Literal::Nil))
}
Some(Token::Ident(name)) if matches!(name.as_str(), "n" | "t" | "b" | "l") => {
let ty = match name.as_str() {
"n" => Type::Number,
"t" => Type::Text,
"b" => Type::Bool,
"l" => Type::List(Box::new(Type::Text)),
_ => unreachable!(),
};
self.advance();
let binding = match self.peek() {
Some(Token::Underscore) => {
self.advance();
"_".to_string()
}
_ => self.expect_ident()?,
};
Ok(Pattern::TypeIs { ty, binding })
}
Some(tok) => Err(self.error("ILO-P011", format!("expected pattern, got {:?}", tok))),
None => Err(self.error("ILO-P012", "expected pattern, got EOF".into())),
}
}
/// `@binding collection{body}` or `@binding start..end{body}`
fn parse_foreach(&mut self) -> Result<Stmt> {
self.expect(&Token::At)?;
let binding = self.expect_ident()?;
// Range bounds accept any expression form: literals, idents, prefix
// binops (`+i 2`), unary minus (`-n 1`), and call forms (`len xs`,
// `at ys 0`). Call args greedily stop at `..` and `{` because neither
// token starts an operand, so `@j 0..len xs{...}` parses cleanly as
// `0..Call(len,[xs])`. See tests/regression_range_expr.rs for the
// cross-engine matrix.
let start_expr = self.parse_expr_inner()?;
// Check for range syntax: start..end
if self.peek() == Some(&Token::DotDot) {
self.advance(); // consume ..
let end_expr = self.parse_expr_inner()?;
let body = self.parse_brace_body()?;
return Ok(Stmt::ForRange {
binding,
start: start_expr,
end: end_expr,
body,
});
}
let body = self.parse_brace_body()?;
Ok(Stmt::ForEach {
binding,
collection: start_expr,
body,
})
}
/// Parse `!` at statement position — negated guard `!cond{body}` or logical NOT `!expr`.
/// Also supports braceless negated guards: `!>=x 10 "fallback"`.
fn parse_bang_stmt(&mut self) -> Result<Stmt> {
self.expect(&Token::Bang)?;
let inner = self.parse_expr_inner()?;
if self.peek() == Some(&Token::LBrace) {
// Negated guard: !cond{body} or !cond{then}{else}
let body = self.parse_brace_body()?;
let else_body = if self.peek() == Some(&Token::LBrace) {
Some(self.parse_brace_body()?)
} else {
None
};
Ok(Stmt::Guard {
condition: inner,
negated: true,
body,
else_body,
braceless: false,
})
} else if is_guard_eligible_condition(&inner) && self.can_start_operand() {
Ok(self.parse_braceless_guard_body(inner, true)?)
} else {
// Logical NOT as expression statement: !expr
Ok(Stmt::Expr(Expr::UnaryOp {
op: UnaryOp::Not,
operand: Box::new(inner),
}))
}
}
/// Parse `^` at statement position — Err constructor: `^expr`
fn parse_caret_stmt(&mut self) -> Result<Stmt> {
self.expect(&Token::Caret)?;
let inner = self.parse_expr_inner()?;
Ok(Stmt::Expr(Expr::Err(Box::new(inner))))
}
/// Parse ident-starting statement — could be guard (expr{body}) or expr statement.
/// Also supports braceless guards: `>=sp 1000 "gold"` (no braces needed when
/// the condition is a comparison/logical operator and the body is a single expression).
fn parse_expr_or_guard(&mut self) -> Result<Stmt> {
let expr = self.parse_expr()?;
if self.peek() == Some(&Token::LBrace) {
let body = self.parse_brace_body()?;
let else_body = if self.peek() == Some(&Token::LBrace) {
Some(self.parse_brace_body()?)
} else {
None
};
Ok(Stmt::Guard {
condition: expr,
negated: false,
body,
else_body,
braceless: false,
})
} else if is_guard_eligible_condition(&expr) && self.can_start_operand() {
Ok(self.parse_braceless_guard_body(expr, false)?)
} else {
Ok(Stmt::Expr(expr))
}
}
/// Parse the body of a braceless guard after eligibility has been confirmed.
/// Uses `parse_operand` (not `parse_expr`) so function calls are NOT consumed —
/// call bodies require braces: `>=sp 1000{classify sp}`.
fn parse_braceless_guard_body(&mut self, condition: Expr, negated: bool) -> Result<Stmt> {
let body_start = self.peek_span();
let body_expr = self.parse_operand()?;
let body_span = body_start.merge(self.prev_span());
// Dangling token detection: after a braceless guard body, the next token
// must be `;`, `}`, `)` (lambda-body terminator), or EOF. If something
// else follows, the user likely wrote a function call without braces:
// `>=sp 1000 classify sp`
if !matches!(
self.peek(),
None | Some(Token::Semi) | Some(Token::RBrace) | Some(Token::RParen)
) {
return Err(self.error_hint(
"ILO-P016",
"unexpected token after braceless guard body".to_string(),
"function calls in braceless guards need braces: >=cond val{func args}".to_string(),
));
}
Ok(Stmt::Guard {
condition,
negated,
body: vec![Spanned::new(Stmt::Expr(body_expr), body_span)],
else_body: None,
braceless: true,
})
}
fn parse_brace_body(&mut self) -> Result<Vec<Spanned<Stmt>>> {
self.expect(&Token::LBrace)?;
let body = self.parse_body()?;
self.expect(&Token::RBrace)?;
Ok(body)
}
// ---- Expressions ----
fn parse_expr(&mut self) -> Result<Expr> {
let expr = match self.peek() {
Some(Token::Tilde) => {
self.advance();
let inner = self.parse_expr_inner()?;
Expr::Ok(Box::new(inner))
}
Some(Token::Caret) => {
self.advance();
let inner = self.parse_expr_inner()?;
Expr::Err(Box::new(inner))
}
_ => self.parse_expr_inner()?,
};
let expr = self.maybe_with(expr)?;
let expr = self.maybe_nil_coalesce(expr)?;
self.maybe_pipe(expr)
}
/// Parse expression, possibly followed by `with`
fn maybe_with(&mut self, expr: Expr) -> Result<Expr> {
if matches!(self.peek(), Some(Token::With)) {
self.advance();
let mut updates = Vec::new();
while let Some(Token::Ident(_)) = self.peek() {
if self.pos + 1 < self.tokens.len()
&& self.token_at(self.pos + 1) == Some(&Token::Colon)
{
let name = self.expect_ident()?;
self.expect(&Token::Colon)?;
let value = self.parse_atom()?;
updates.push((name, value));
} else {
break;
}
}
Ok(Expr::With {
object: Box::new(expr),
updates,
})
} else {
Ok(expr)
}
}
/// Parse nil-coalesce: `a ?? b` — if a is nil, use b
fn maybe_nil_coalesce(&mut self, mut expr: Expr) -> Result<Expr> {
while matches!(self.peek(), Some(Token::NilCoalesce)) {
self.advance(); // consume ??
let default = self.parse_expr_inner()?;
expr = Expr::NilCoalesce {
value: Box::new(expr),
default: Box::new(default),
};
}
Ok(expr)
}
/// Parse pipe chains: `expr >> func` desugars to `func(expr)`.
/// `expr >> func a b` desugars to `func(a, b, expr)` — piped value becomes last arg.
fn maybe_pipe(&mut self, mut expr: Expr) -> Result<Expr> {
while matches!(self.peek(), Some(Token::PipeOp)) {
self.advance(); // consume >>
let func_name = self.expect_ident()?;
let unwrap = self.maybe_postfix_unwrap();
// Parse additional args (operands until we hit >>, ;, }, etc.)
// Use call-arg parsing so nested calls inside a pipe target
// expand naturally (e.g. `xs >> map str` keeps `str` as a bare
// fn-ref since `map`'s first arg is a fn-ref position).
let mut args = Vec::new();
// Piped value will occupy the final slot, so explicit args here
// fill slots 0..arity-1. Subtract 1 from the outer-arity advertised
// to `parse_call_arg` so `fmt` correctly sees these as middle
// slots (and so a misplaced `fmt` in a pipe target gets the
// precise ILO-P018 rather than silently mis-parsing).
let pipe_outer_arity = self.fn_arity.get(&func_name).copied();
while self.can_start_operand() {
let arg_idx = args.len();
let in_fn_pos = self.is_fn_ref_position(&func_name, arg_idx);
let outer_ctx = pipe_outer_arity
.filter(|&k| k > 0)
.map(|k| (func_name.as_str(), k - 1, arg_idx));
args.push(self.parse_call_arg(in_fn_pos, outer_ctx)?);
}
// Piped value becomes last arg
args.push(expr);
expr = Expr::Call {
function: func_name,
args,
unwrap,
};
}
Ok(expr)
}
/// Return the infix binding power (left, right) for a token, or None if not infix.
/// Higher numbers bind tighter. Right bp > left bp for left-associativity.
/// Operators that, in the middle of a call-arg sequence, may end the call
/// by binding the preceding expression as their left operand. Covers
/// Pratt-table infix ops plus `??` (handled by `maybe_nil_coalesce`).
fn is_infix_or_suffix_op(token: &Token) -> bool {
matches!(token, Token::NilCoalesce) || Self::infix_binding_power(token).is_some()
}
fn infix_binding_power(token: &Token) -> Option<(u8, u8, BinOp)> {
match token {
Token::Pipe => Some((1, 2, BinOp::Or)),
Token::Amp => Some((3, 4, BinOp::And)),
Token::Eq => Some((5, 6, BinOp::Equals)),
Token::NotEq => Some((5, 6, BinOp::NotEquals)),
Token::Less => Some((7, 8, BinOp::LessThan)),
Token::Greater => Some((7, 8, BinOp::GreaterThan)),
Token::LessEq => Some((7, 8, BinOp::LessOrEqual)),
Token::GreaterEq => Some((7, 8, BinOp::GreaterOrEqual)),
Token::PlusEq => Some((9, 10, BinOp::Append)),
Token::Plus => Some((9, 10, BinOp::Add)),
Token::Minus => Some((9, 10, BinOp::Subtract)),
Token::Star => Some((11, 12, BinOp::Multiply)),
Token::Slash => Some((11, 12, BinOp::Divide)),
_ => None,
}
}
/// Pratt parser: given a left-hand expression, consume infix operators
/// with binding power >= min_bp and build the tree.
fn parse_infix(&mut self, mut left: Expr, min_bp: u8) -> Result<Expr> {
while let Some(token) = self.peek() {
let Some((l_bp, r_bp, op)) = Self::infix_binding_power(token) else {
break;
};
if l_bp < min_bp {
break;
}
self.advance(); // consume operator
// Parse right-hand side: an operand (atom or prefix op), then recurse for infix
let right = self.parse_operand()?;
let right = self.parse_infix(right, r_bp)?;
left = Expr::BinOp {
op,
left: Box::new(left),
right: Box::new(right),
};
}
Ok(left)
}
/// Parse a single list element — like `parse_expr_inner` but also handles
/// `~expr` (Ok) and `^expr` (Err) wrapping that `parse_expr` normally handles.
/// Scan ahead from the current position (just past the opening `[`)
/// to determine whether this list literal contains a top-level comma.
/// Used to choose between comma-separated mode (calls allowed in
/// elements) and whitespace mode (bare refs are elements).
fn list_has_top_level_comma(&self) -> bool {
let mut depth_paren = 0;
let mut depth_bracket = 0;
let mut depth_brace = 0;
let mut i = self.pos;
while i < self.tokens.len() {
match &self.tokens[i].0 {
Token::LParen => depth_paren += 1,
Token::RParen => depth_paren -= 1,
Token::LBracket => depth_bracket += 1,
Token::RBracket => {
if depth_bracket == 0 && depth_paren == 0 && depth_brace == 0 {
return false;
}
depth_bracket -= 1;
}
Token::LBrace => depth_brace += 1,
Token::RBrace => depth_brace -= 1,
Token::Comma if depth_paren == 0 && depth_bracket == 0 && depth_brace == 0 => {
return true;
}
_ => {}
}
i += 1;
}
false
}
/// Whitespace-mode list element: bare refs become elements, not calls.
/// Without this guard, `[a b c]` would parse as `[Call(a, [b, c])]` and
/// confuse agents who reasonably expect it to mirror `[1 2 3]`. Calls
/// inside whitespace-list elements still work via parens (`[(f x) y]`
/// or `[f(x) y]`) — the flag is cleared on paren entry.
fn parse_list_element(&mut self) -> Result<Expr> {
let prev = self.no_whitespace_call;
self.no_whitespace_call = true;
let result = self.parse_list_element_call_ok();
self.no_whitespace_call = prev;
result
}
/// Comma-mode list element: full expression including whitespace-calls.
/// Used when the list literal contains a top-level comma, so
/// `[floor x, ceil x]` parses each side as its own call expression.
fn parse_list_element_call_ok(&mut self) -> Result<Expr> {
match self.peek() {
Some(Token::Tilde) => {
self.advance();
let inner = self.parse_expr_inner()?;
Ok(Expr::Ok(Box::new(inner)))
}
Some(Token::Caret) => {
self.advance();
let inner = self.parse_expr_inner()?;
Ok(Expr::Err(Box::new(inner)))
}
_ => self.parse_expr_inner(),
}
}
/// Core expression parsing — handles prefix ops, match expr, calls, atoms.
/// Infix operators are only applied after atoms/calls, not after prefix operators
/// (prefix forms like `+a b` are self-contained).
fn parse_expr_inner(&mut self) -> Result<Expr> {
match self.peek() {
// Minus is special: could be unary negation (-x) or binary subtract (-a b)
Some(Token::Minus) => self.parse_minus(),
// Logical NOT: !x
Some(Token::Bang) => {
self.advance();
let operand = self.parse_operand()?;
Ok(Expr::UnaryOp {
op: UnaryOp::Not,
operand: Box::new(operand),
})
}
// Dollar prefix: $expr → get expr
Some(Token::Dollar) => self.parse_dollar(),
// Prefix binary operators: +a b, *a b, etc. — self-contained, no infix after
Some(Token::Plus)
| Some(Token::Star)
| Some(Token::Slash)
| Some(Token::Greater)
| Some(Token::Less)
| Some(Token::GreaterEq)
| Some(Token::LessEq)
| Some(Token::Eq)
| Some(Token::NotEq)
| Some(Token::Amp)
| Some(Token::Pipe)
| Some(Token::PlusEq) => self.parse_prefix_binop(),
// Prefix nil-coalesce: ??a b — mirror of infix `a ?? b`
Some(Token::NilCoalesce) => {
self.advance();
let value = self.parse_operand()?;
let default = self.parse_expr_inner()?;
Ok(Expr::NilCoalesce {
value: Box::new(value),
default: Box::new(default),
})
}
// Match expression: ?expr{...} or ?{...}, or prefix ternary: ?=x 0 10 20
Some(Token::Question) => self.parse_question_expr(),
// Atoms and calls — infix operators can follow these
_ => {
let primary = self.parse_call_or_atom()?;
self.parse_infix(primary, 0)
}
}
}
/// `$expr` → `get expr`, `$!expr` → `get! expr`, `$!!expr` → `get!! expr`
fn parse_dollar(&mut self) -> Result<Expr> {
self.advance(); // consume $
let unwrap = self.maybe_postfix_unwrap();
let arg = self.parse_operand()?;
Ok(Expr::Call {
function: "get".to_string(),
args: vec![arg],
unwrap,
})
}
/// Check if `?` at current position is followed by a comparison op (prefix ternary).
fn is_prefix_ternary(&self) -> bool {
matches!(
self.token_at(self.pos + 1),
Some(
Token::Eq
| Token::Greater
| Token::Less
| Token::GreaterEq
| Token::LessEq
| Token::NotEq
)
)
}
/// Parse `?` as either match (`?expr{...}`) or prefix ternary (`?=x 0 10 20`).
fn parse_question_expr(&mut self) -> Result<Expr> {
if self.is_prefix_ternary() {
return self.parse_prefix_ternary();
}
self.parse_match_expr()
}
/// Parse prefix ternary: `?=x 0 10 20` → Ternary { condition: BinOp(=, x, 0), then: 10, else: 20 }
fn parse_prefix_ternary(&mut self) -> Result<Expr> {
self.advance(); // consume ?
// Parse the condition as a prefix binop (=x 0, >x 5, etc.)
let condition = self.parse_prefix_binop()?;
// Parse then and else expressions
let then_expr = self.parse_operand()?;
let else_expr = self.parse_operand()?;
Ok(Expr::Ternary {
condition: Box::new(condition),
then_expr: Box::new(then_expr),
else_expr: Box::new(else_expr),
})
}
/// Parse match as expression: `?expr{arms}` or `?{arms}`
fn parse_match_expr(&mut self) -> Result<Expr> {
self.expect(&Token::Question)?;
let subject = if self.peek() == Some(&Token::LBrace) {
None
} else {
Some(Box::new(self.parse_atom()?))
};
self.expect(&Token::LBrace)?;
let arms = self.parse_match_arms()?;
self.expect(&Token::RBrace)?;
Ok(Expr::Match { subject, arms })
}
/// Parse `-`: unary negation (`-x`) when one atom follows,
/// binary subtract (`-a b`) when two atoms follow.
fn parse_minus(&mut self) -> Result<Expr> {
self.advance(); // consume `-`
let first = self.parse_operand()?;
if self.can_start_operand() {
let second = self.parse_operand()?;
Ok(Expr::BinOp {
op: BinOp::Subtract,
left: Box::new(first),
right: Box::new(second),
})
} else {
Ok(Expr::UnaryOp {
op: UnaryOp::Negate,
operand: Box::new(first),
})
}
}
fn parse_prefix_binop(&mut self) -> Result<Expr> {
// Reject compound-comparison prefix from other languages: `=<a b`
// (intended as ≤), `=>a b` (intended as ≥). ilo already has the
// single-token forms `<=` / `>=`; the multi-token compound is a
// common slip from agents that learnt operator precedence
// elsewhere (qa-tester rerun3, `=<d 0{...}`). Surface a friendly
// hint before consuming the leading op.
if let Some(tok) = self.peek().cloned()
&& matches!(tok, Token::Eq)
&& let Some(next) = self.token_at(self.pos + 1).cloned()
&& let Some((compound, replacement)) = compound_comparison_replacement(&tok, &next)
{
return Err(self.error_hint(
"ILO-P003",
format!(
"`{compound}` is not an ilo operator; compound prefix forms don't compose"
),
format!(
"use `{replacement}` (single token) instead, e.g. `{replacement}a b` for the comparison"
),
));
}
let op = match self.advance() {
Some(Token::Plus) => BinOp::Add,
Some(Token::Star) => BinOp::Multiply,
Some(Token::Slash) => BinOp::Divide,
Some(Token::Greater) => BinOp::GreaterThan,
Some(Token::Less) => BinOp::LessThan,
Some(Token::GreaterEq) => BinOp::GreaterOrEqual,
Some(Token::LessEq) => BinOp::LessOrEqual,
Some(Token::Eq) => BinOp::Equals,
Some(Token::NotEq) => BinOp::NotEquals,
Some(Token::Amp) => {
if self.peek() == Some(&Token::Amp) {
return Err(self.error_hint(
"ILO-P003",
"unexpected '&&': ilo uses single '&' for AND".to_string(),
"ilo uses single '&' for AND, '|' for OR".to_string(),
));
}
BinOp::And
}
Some(Token::Pipe) => {
if self.peek() == Some(&Token::Pipe) {
return Err(self.error_hint(
"ILO-P003",
"unexpected '||': ilo uses single '|' for OR".to_string(),
"ilo uses single '&' for AND, '|' for OR".to_string(),
));
}
BinOp::Or
}
Some(Token::PlusEq) => BinOp::Append,
_ => unreachable!(),
};
let left = self.parse_operand()?;
let right = self.parse_operand()?;
Ok(Expr::BinOp {
op,
left: Box::new(left),
right: Box::new(right),
})
}
/// Register a user function's arity and per-param fn-ref flags so that
/// call-arg parsing can eagerly consume nested calls when this function
/// is used as the outer callee.
fn register_user_fn(&mut self, name: &str, params: &[Param]) {
self.fn_arity.insert(name.to_string(), params.len());
let flags: Vec<bool> = params
.iter()
.map(|p| matches!(p.ty, Type::Fn(_, _)))
.collect();
self.fn_param_is_fn.insert(name.to_string(), flags);
}
/// Is arg position `arg_idx` of function `outer_name` a fn-ref position
/// (i.e. expects a function reference, not a regular value)? When true,
/// we must NOT eagerly expand an Ident in that position as a nested call.
fn is_fn_ref_position(&self, outer_name: &str, arg_idx: usize) -> bool {
self.fn_param_is_fn
.get(outer_name)
.and_then(|v| v.get(arg_idx).copied())
.unwrap_or(false)
}
/// Is `name` a variadic-trailing builtin — one that, when used as a nested
/// call argument, must occupy the LAST arg slot of the outer call and
/// then consumes every remaining operand as its own trailing args?
///
/// Currently only `fmt`. The rule is intentionally narrow:
/// * trailing slot of a known-arity outer → eagerly parse template + tail.
/// * middle slot → emit ILO-P018 (must be last, or wrap in parens).
/// * outside known-arity context → fall through to existing behaviour
/// (top-level call, list element with comma boundary, etc.).
fn is_variadic_trailing_builtin(name: &str) -> bool {
name == "fmt" || name == "format"
}
/// Parse a single call argument. If `in_fn_ref_pos` is true, falls back
/// to plain `parse_operand` so an Ident stays as a bare ref (HOF use).
/// Otherwise, when the next token is an Ident naming a known function
/// with arity N, eagerly consume that Ident plus its N args as a nested
/// call — this lets agents write `prnt str nc` and `hd tl xs` naturally.
///
/// `outer_ctx` carries the surrounding call's name, total arity, and the
/// current slot index (the slot this arg fills). It lets us decide
/// whether a variadic-trailing builtin like `fmt` is at the trailing slot
/// (eagerly consume its template + remaining operands) or a middle slot
/// (emit ILO-P018). `None` means we're not parsing inside a known-arity
/// outer, so the variadic-trailing rule doesn't apply.
fn parse_call_arg(
&mut self,
in_fn_ref_pos: bool,
outer_ctx: Option<(&str, usize, usize)>,
) -> Result<Expr> {
// Variadic-trailing handling for `fmt` (and its `format` alias) when
// used as a nested arg of a known-arity outer.
if !in_fn_ref_pos
&& let Some(Token::Ident(name)) = self.peek()
&& Self::is_variadic_trailing_builtin(name)
&& let Some((outer_name, outer_arity, arg_idx)) = outer_ctx
{
// Don't fire on shapes that wouldn't be a plain call anyway —
// record fields, field/index access, bang-unwrap, zero-arg paren.
let next = self.token_at(self.pos + 1);
let is_record = matches!(next, Some(Token::Ident(_)))
&& self.token_at(self.pos + 2) == Some(&Token::Colon);
let is_field = matches!(next, Some(Token::Dot) | Some(Token::DotQuestion));
let is_zero_arg_call =
next == Some(&Token::LParen) && self.token_at(self.pos + 2) == Some(&Token::RParen);
let is_unwrap = matches!(next, Some(&Token::Bang) | Some(&Token::BangBang)) && {
let ident_span = self.peek_span();
let bang_span = self
.tokens
.get(self.pos + 1)
.map(|(_, s)| *s)
.unwrap_or(Span::UNKNOWN);
ident_span.end > 0 && bang_span.start == ident_span.end
};
if !(is_record || is_field || is_zero_arg_call || is_unwrap) {
let fmt_name = name.clone();
let is_trailing = arg_idx + 1 == outer_arity;
if !is_trailing {
return Err(self.error_hint(
"ILO-P018",
format!(
"`{fmt_name}` must be the last argument to `{outer_name}`; \
wrap in parens to use it earlier"
),
format!(
"`{outer_name}` expects {outer_arity} args and `{fmt_name}` is at \
slot {arg_idx} of {outer_arity}. Either move `{fmt_name}` to the last position, \
or write `({fmt_name} \"...\" ...)` so its args are grouped."
),
));
}
// Trailing slot — eagerly consume `fmt` + template + all
// remaining operands as fmt's args.
self.advance(); // consume `fmt`
let mut fmt_args = Vec::new();
// fmt requires a template (its declared arity 1); if no
// operand follows, leave the underfilled call for the
// verifier to flag with its usual ILO-T013 error.
while self.can_start_operand() {
// fmt's own slots are all value positions (no fn-refs),
// and nested fmt-in-fmt is the same trailing slot of its
// recursive context — pass through.
fmt_args.push(self.parse_call_arg(false, None)?);
// Stop on infix operators so `prnt fmt "x" 1 + 2` keeps
// `+ 2` for the outer expression parser to handle (as it
// would for any nested call's last arg).
if let Some(tok) = self.peek()
&& Self::is_infix_or_suffix_op(tok)
&& (matches!(tok, Token::NilCoalesce)
|| !self.looks_like_prefix_binary(self.pos))
{
break;
}
}
return Ok(Expr::Call {
function: fmt_name,
args: fmt_args,
unwrap: UnwrapMode::None,
});
}
}
if !in_fn_ref_pos
&& let Some(Token::Ident(name)) = self.peek()
&& let Some(&arity) = self.fn_arity.get(name)
&& arity > 0
{
// Don't eagerly expand if the Ident is followed by tokens that
// turn it into something other than a plain call (record fields,
// field/index access, postfix-bang, zero-arg paren form).
let next = self.token_at(self.pos + 1);
let is_record = matches!(next, Some(Token::Ident(_)))
&& self.token_at(self.pos + 2) == Some(&Token::Colon);
let is_field = matches!(next, Some(Token::Dot) | Some(Token::DotQuestion));
let is_zero_arg_call =
next == Some(&Token::LParen) && self.token_at(self.pos + 2) == Some(&Token::RParen);
let is_unwrap = matches!(next, Some(&Token::Bang) | Some(&Token::BangBang)) && {
let ident_span = self.peek_span();
let bang_span = self
.tokens
.get(self.pos + 1)
.map(|(_, s)| *s)
.unwrap_or(Span::UNKNOWN);
ident_span.end > 0 && bang_span.start == ident_span.end
};
if !(is_record || is_field || is_zero_arg_call || is_unwrap) {
let inner_name = name.clone();
self.advance(); // consume the inner function ident
let mut inner_args = Vec::with_capacity(arity);
for i in 0..arity {
if !self.can_start_operand() {
// Underfilled — let the verifier report arity mismatch.
break;
}
let inner_fn_pos = self.is_fn_ref_position(&inner_name, i);
inner_args
.push(self.parse_call_arg(inner_fn_pos, Some((&inner_name, arity, i)))?);
}
return Ok(Expr::Call {
function: inner_name,
args: inner_args,
unwrap: UnwrapMode::None,
});
}
}
self.parse_operand()
}
/// Parse function call or plain atom
/// call = IDENT atom+ (greedy, when not a record)
/// Also handles zero-arg calls: `func()`
fn parse_call_or_atom(&mut self) -> Result<Expr> {
let atom = self.parse_atom()?;
// If atom is a Ref, check if it's a call or record construction
if let Expr::Ref(ref name) = atom {
let name = name.clone();
// Check for auto-unwrap: `name!` (Propagate) or `name!!` (Panic).
// Both must be ADJACENT to `name` (no space) to distinguish from
// `func !x` (call with a `!x` argument). `maybe_postfix_unwrap`
// encodes the adjacency rule.
let unwrap = self.maybe_postfix_unwrap();
// Check for zero-arg call: name() / name!() / name!!()
if self.peek() == Some(&Token::LParen)
&& self.pos + 1 < self.tokens.len()
&& self.token_at(self.pos + 1) == Some(&Token::RParen)
{
self.advance(); // (
self.advance(); // )
return Ok(Expr::Call {
function: name,
args: vec![],
unwrap,
});
}
// If we consumed `!` / `!!`, this must be a call (even with zero
// args if nothing follows).
if unwrap.is_any() {
let mut args = Vec::new();
let outer_arity_known = self.fn_arity.get(&name).copied();
while self.can_start_operand() {
let arg_idx = args.len();
let in_fn_pos = self.is_fn_ref_position(&name, arg_idx);
let outer_ctx = outer_arity_known
.filter(|&k| k > 0)
.map(|k| (name.as_str(), k, arg_idx));
args.push(self.parse_call_arg(in_fn_pos, outer_ctx)?);
}
return Ok(Expr::Call {
function: name,
args,
unwrap,
});
}
// Check for record construction: name field:value
if self.is_named_field_ahead() {
return self.parse_record(name);
}
// Zero-arg builtins: `rnd`/`now`/`mmap` with no args → Call with empty args
if (name == "rnd" || name == "now" || name == "mmap") && !self.can_start_operand() {
return Ok(Expr::Call {
function: name,
args: vec![],
unwrap: UnwrapMode::None,
});
}
// Inside a list literal, `[a b c]` must yield three list
// elements rather than `[Call(a, [b, c])]`. Bare refs to locals
// stay as elements. But a known function (in `fn_arity` with
// arity > 0) followed by operands parses as a call with EXACTLY
// arity operands consumed - same arity-capped rule that the
// nested-call path in `parse_call_arg` uses (line 1916). This
// lets `[str n]`, `[at xs 0]`, `[map dbl xs]`, and side-by-side
// `[str a str b str c]` Just Work without forcing agents to
// bind every formatted value first or reach for parens.
//
// The arity cap is critical: without it, `[at xs 0 at xs 2]`
// would parse as `at(xs, 0, at, xs, 2)` (5 args) instead of two
// calls. Mirroring `parse_call_arg`'s `for i in 0..arity` keeps
// each list element to a single capped call.
if self.no_whitespace_call {
let arity = self.fn_arity.get(&name).copied().unwrap_or(0);
if arity == 0 || !self.can_start_operand() {
return Ok(atom);
}
let mut args = Vec::with_capacity(arity);
for i in 0..arity {
if !self.can_start_operand() {
// Underfilled - let the verifier report arity
// mismatch with its usual ILO-T006 error.
break;
}
let inner_fn_pos = self.is_fn_ref_position(&name, i);
args.push(self.parse_call_arg(inner_fn_pos, Some((&name, arity, i)))?);
}
return Ok(Expr::Call {
function: name,
args,
unwrap: UnwrapMode::None,
});
}
// Check for function call: name followed by args
//
// Infix interaction: when the first token after the name is an
// operator, use lookahead to decide prefix-as-call-arg vs infix:
// `fac -n 1` → fac(-(n,1)) (operator + 2 atoms = prefix binary)
// `x - 3` → x - 3 (operator + 1 atom = infix)
// `f a + b` → f(a) + b (atom then operator = infix on call)
if self.can_start_operand() {
// If the first token is an infix-eligible operator, check if it
// looks like a prefix binary op (followed by 2+ atoms) or infix
if let Some(tok) = self.peek()
&& Self::is_infix_or_suffix_op(tok)
&& !self.looks_like_prefix_binary(self.pos)
{
return Ok(atom);
}
let mut args = Vec::new();
let outer_arity_known = self.fn_arity.get(&name).copied();
while self.can_start_operand() {
let arg_idx = args.len();
let in_fn_pos = self.is_fn_ref_position(&name, arg_idx);
let outer_ctx = outer_arity_known
.filter(|&k| k > 0)
.map(|k| (name.as_str(), k, arg_idx));
args.push(self.parse_call_arg(in_fn_pos, outer_ctx)?);
// After each arg, if next is infix, stop. `??` is always
// infix once we've already collected at least one arg —
// `f a ?? b` means `(f a) ?? b`, never `f a (??b ...)`.
// Without this, chained `f a ?? g b ?? d` mis-parses as
// `f a (?? g b) (?? d)` because the prefix-binary scanner
// sees `?? g b` as a valid prefix nil-coalesce form.
if let Some(tok) = self.peek()
&& Self::is_infix_or_suffix_op(tok)
&& (matches!(tok, Token::NilCoalesce)
|| !self.looks_like_prefix_binary(self.pos))
{
break;
}
}
return Ok(Expr::Call {
function: name,
args,
unwrap: UnwrapMode::None,
});
}
}
Ok(atom)
}
/// Check if next tokens look like `ident:expr` (named field)
fn is_named_field_ahead(&self) -> bool {
if let Some(Token::Ident(_)) = self.peek()
&& self.pos + 1 < self.tokens.len()
&& self.token_at(self.pos + 1) == Some(&Token::Colon)
{
// Make sure it's not a param pattern (type follows colon)
return true;
}
false
}
/// Parse record: `typename field:val field:val`
fn parse_record(&mut self, type_name: String) -> Result<Expr> {
let mut fields = Vec::new();
while self.is_named_field_ahead() {
let fname = self.expect_ident()?;
self.expect(&Token::Colon)?;
let value = self.parse_atom()?;
fields.push((fname, value));
}
Ok(Expr::Record { type_name, fields })
}
/// Lookahead: does the token at `pos` start a prefix binary operator
/// (operator followed by 2+ simple atoms before the next operator/terminator)?
///
/// Used to disambiguate: `fac -n 1` (prefix: `-` + 2 atoms) vs `x - 3` (infix: `-` + 1 atom).
/// Counts consecutive simple atoms; an operator-headed sub-expression that itself
/// looks_like_prefix_binary also counts as one atom (so `h +a +b c` parses with
/// `+a` and `+b c` as two args).
fn looks_like_prefix_binary(&self, pos: usize) -> bool {
self.scan_prefix_binary_end(pos).is_some()
}
/// If the token at `pos` heads a prefix-binary expression (operator + 2 atoms,
/// where each atom may itself be a nested prefix-binary), return the position
/// just after the last consumed token. Otherwise return None.
fn scan_prefix_binary_end(&self, pos: usize) -> Option<usize> {
if pos >= self.tokens.len() {
return None;
}
let mut count = 0;
let mut look = pos + 1;
while look < self.tokens.len() && count < 2 {
// Stop at function declaration boundaries
if self.is_fn_decl_start(look) {
break;
}
let t = &self.tokens[look].0;
match t {
Token::Ident(_)
| Token::Number(_)
| Token::Text(_)
| Token::True
| Token::False
| Token::Nil
| Token::Underscore => {
count += 1;
look += 1;
}
Token::LParen | Token::LBracket => {
// Paren/bracket group counts as one atom
count += 1;
let close = if *t == Token::LParen {
Token::RParen
} else {
Token::RBracket
};
let mut depth = 1;
look += 1;
while look < self.tokens.len() && depth > 0 {
let inner = &self.tokens[look].0;
if *inner == *t {
depth += 1;
}
if *inner == close {
depth -= 1;
}
look += 1;
}
}
// A nested prefix-binary operator counts as one atom if it itself
// heads a prefix-binary sub-expression. Only the binary-only
// operators listed in parse_prefix_binop qualify (plus Minus,
// which is handled by parse_minus and is also binary-capable).
// Unary-only operators (Bang/Tilde/Caret) are intentionally
// excluded — they aren't prefix-binary.
Token::Plus
| Token::Minus
| Token::Star
| Token::Slash
| Token::Greater
| Token::Less
| Token::GreaterEq
| Token::LessEq
| Token::Eq
| Token::NotEq
| Token::Amp
| Token::Pipe
| Token::PlusEq
| Token::NilCoalesce => {
if let Some(end) = self.scan_prefix_binary_end(look) {
count += 1;
look = end;
} else {
break;
}
}
// Stop at other operators, terminators, etc.
_ => break,
}
}
if count >= 2 { Some(look) } else { None }
}
/// Can the current token start an atom?
fn can_start_atom(&self) -> bool {
matches!(
self.peek(),
Some(Token::Ident(_))
| Some(Token::Number(_))
| Some(Token::Text(_))
| Some(Token::True)
| Some(Token::False)
| Some(Token::Nil)
| Some(Token::Underscore)
| Some(Token::LParen)
| Some(Token::LBracket)
)
}
/// Can the next token start an operand? (atom or prefix operator)
/// Returns false if the current position looks like the start of a new function
/// declaration — `Ident >` (zero-param) or `Ident Ident :` (parameterised) — so
/// that a non-last function ending with a call doesn't greedily consume the next
/// function's name as an argument.
fn can_start_operand(&self) -> bool {
// If the upcoming token is an Ident that begins a new declaration, stop here.
if self.is_fn_decl_start(self.pos) {
return false;
}
self.can_start_atom()
|| matches!(
self.peek(),
Some(Token::Plus)
| Some(Token::Minus)
| Some(Token::Star)
| Some(Token::Slash)
| Some(Token::Greater)
| Some(Token::Less)
| Some(Token::GreaterEq)
| Some(Token::LessEq)
| Some(Token::Eq)
| Some(Token::NotEq)
| Some(Token::Amp)
| Some(Token::Pipe)
| Some(Token::PlusEq)
| Some(Token::NilCoalesce)
| Some(Token::Bang)
| Some(Token::Tilde)
| Some(Token::Caret)
| Some(Token::Dollar)
)
}
/// Parse an operand — an atom or a nested prefix operator.
/// This sits between `parse_atom` (terminals only) and `parse_expr_inner`
/// (which includes function calls). Prefix operators use this so that
/// `+*a b c` works without greedy call parsing.
fn parse_operand(&mut self) -> Result<Expr> {
match self.peek() {
Some(Token::Plus)
| Some(Token::Star)
| Some(Token::Slash)
| Some(Token::Greater)
| Some(Token::Less)
| Some(Token::GreaterEq)
| Some(Token::LessEq)
| Some(Token::Eq)
| Some(Token::NotEq)
| Some(Token::Amp)
| Some(Token::Pipe)
| Some(Token::PlusEq) => self.parse_prefix_binop(),
Some(Token::NilCoalesce) => {
self.advance();
let value = self.parse_operand()?;
let default = self.parse_expr_inner()?;
Ok(Expr::NilCoalesce {
value: Box::new(value),
default: Box::new(default),
})
}
Some(Token::Minus) => self.parse_minus(),
Some(Token::Bang) => {
self.advance();
let operand = self.parse_operand()?;
Ok(Expr::UnaryOp {
op: UnaryOp::Not,
operand: Box::new(operand),
})
}
Some(Token::Tilde) => {
self.advance();
let inner = self.parse_operand()?;
Ok(Expr::Ok(Box::new(inner)))
}
Some(Token::Caret) => {
self.advance();
let inner = self.parse_operand()?;
Ok(Expr::Err(Box::new(inner)))
}
Some(Token::Dollar) => self.parse_dollar(),
_ => self.parse_atom(),
}
}
/// Parse an atom — the smallest expression unit
fn parse_atom(&mut self) -> Result<Expr> {
match self.peek().cloned() {
Some(Token::Number(n)) => {
self.advance();
Ok(Expr::Literal(Literal::Number(n)))
}
Some(Token::Text(s)) => {
self.advance();
Ok(Expr::Literal(Literal::Text(s)))
}
Some(Token::True) => {
self.advance();
Ok(Expr::Literal(Literal::Bool(true)))
}
Some(Token::False) => {
self.advance();
Ok(Expr::Literal(Literal::Bool(false)))
}
Some(Token::Nil) => {
self.advance();
Ok(Expr::Literal(Literal::Nil))
}
Some(Token::Underscore) => {
self.advance();
Ok(Expr::Ref("_".to_string()))
}
Some(Token::LParen) => {
// Inline-lambda disambiguation. A parenthesised inline fn
// literal looks like `(p1:t1 p2:t2 >ret;body)` or `(>ret;body)`
// for a zero-param body. The trigger is unambiguous: only a
// lambda has an `ident:` pair (or a leading `>`) immediately
// inside the paren before the matching `)`, without an
// intervening top-level `;` — a grouped expression never does.
if self.looks_like_inline_lambda() {
return self.parse_inline_lambda();
}
self.advance();
// Parenthesised expressions are self-contained — restore
// normal whitespace-call behaviour inside.
let prev = self.no_whitespace_call;
self.no_whitespace_call = false;
let expr = self.parse_expr();
self.no_whitespace_call = prev;
let expr = expr?;
self.expect(&Token::RParen)?;
Ok(expr)
}
Some(Token::LBracket) => {
self.advance();
// Disambiguation: if this list literal contains any comma
// (at depth 0), it uses comma-separated mode where each
// element is a full expression — calls like
// `[floor x, ceil x]` work as expected. Otherwise the list
// is whitespace-separated and bare refs become elements:
// `[a b c]` → `[a, b, c]`, mirroring `[1 2 3]`. Calls
// inside a whitespace-list must use parens: `[(f x) y]`.
let has_comma = self.list_has_top_level_comma();
let mut items = Vec::new();
while self.peek() != Some(&Token::RBracket) {
if has_comma {
items.push(self.parse_list_element_call_ok()?);
} else {
items.push(self.parse_list_element()?);
}
// Skip optional comma separator
if self.peek() == Some(&Token::Comma) {
self.advance();
}
}
self.expect(&Token::RBracket)?;
Ok(Expr::List(items))
}
Some(Token::Ident(name)) => {
self.advance();
// Zero-arg builtins used as operands (arguments to other calls)
if name == "mmap" {
return Ok(Expr::Call {
function: name,
args: vec![],
unwrap: UnwrapMode::None,
});
}
// Zero-arg call in operand position: `name()` and `name!()`.
// Mirrors the statement-head handling in `parse_call_or_atom`
// so `len xs()`, `@v xs(){...}`, `map dbl xs()`, `hd xs()`,
// `at xs() 0` all parse as `Call { args: [] }` instead of
// leaving the bare Ref behind and then choking on the LParen.
// SPEC.md:16 and :843 already document `make-id()` / `fetch!()`.
// `name!()` (Propagate) or `name!!()` (Panic) — postfix unwrap
// adjacent to the name, then a zero-arg paren-call.
let bang_mode = match self.peek() {
Some(Token::Bang) => Some(UnwrapMode::Propagate),
Some(Token::BangBang) => Some(UnwrapMode::Panic),
_ => None,
};
let bang_adjacent = bang_mode.is_some() && {
let prev = self.prev_span();
let bang = self.peek_span();
// Adjacent if spans are real (non-zero) and contiguous —
// distinguish `name!()` (unwrap zero-arg call) from
// `name !x` (call with NOT arg).
prev.end > 0 && bang.start == prev.end
};
if bang_adjacent
&& self.token_at(self.pos + 1) == Some(&Token::LParen)
&& self.token_at(self.pos + 2) == Some(&Token::RParen)
{
let mode = bang_mode.expect("guarded by bang_adjacent above");
self.advance(); // ! or !!
self.advance(); // (
self.advance(); // )
return Ok(Expr::Call {
function: name,
args: vec![],
unwrap: mode,
});
}
if self.peek() == Some(&Token::LParen)
&& self.token_at(self.pos + 1) == Some(&Token::RParen)
{
self.advance(); // (
self.advance(); // )
return Ok(Expr::Call {
function: name,
args: vec![],
unwrap: UnwrapMode::None,
});
}
// Check for field access chain: ident.field.field...
let mut expr = Expr::Ref(name);
while matches!(self.peek(), Some(Token::Dot) | Some(Token::DotQuestion)) {
let safe = self.peek() == Some(&Token::DotQuestion);
self.advance();
match self.peek().cloned() {
Some(Token::Number(n)) if n.fract() == 0.0 && n >= 0.0 => {
self.advance();
expr = Expr::Index {
object: Box::new(expr),
index: n as usize,
safe,
};
}
_ => {
let field = self.expect_ident()?;
expr = Expr::Field {
object: Box::new(expr),
field,
safe,
};
}
}
}
Ok(expr)
}
Some(tok) => {
// Friendly hint for `fn`/`def`/`lambda`-style lambda attempts
// from other languages at expression position. ilo's inline
// lambda syntax is parenthesised: `(p:t>r;body)`. (qa-tester
// and scientific-researcher rerun3 both reached for `fn`.)
if let Some((msg, hint)) = lambda_keyword_message(&tok) {
return Err(self.error_hint("ILO-P009", msg, hint));
}
Err(self.error("ILO-P009", format!("expected expression, got {:?}", tok)))
}
None => Err(self.error("ILO-P010", "expected expression, got EOF".into())),
}
}
/// Lookahead: does the token at `self.pos` (`(`) open an inline lambda?
///
/// Triggers (all unambiguous — grouped expressions never start this way):
/// - `( ident : ...` — at least one typed param
/// - `( > ...` — zero-param lambda
///
/// We also require a `>` to appear at paren-depth 0 before the matching
/// `)` — this rejects e.g. `(a:1 b:2)` (record-style key:val, which is
/// not currently a valid grouped expression but guards against future
/// syntax overlap).
fn looks_like_inline_lambda(&self) -> bool {
debug_assert_eq!(self.peek(), Some(&Token::LParen));
let first = self.token_at(self.pos + 1);
let second = self.token_at(self.pos + 2);
let starts_like_lambda = matches!(
(first, second),
(Some(Token::Ident(_)), Some(Token::Colon)) | (Some(Token::Greater), _)
);
if !starts_like_lambda {
return false;
}
// Confirm a `>` exists at paren-depth 0 inside the parens.
let mut depth = 1usize;
let mut i = self.pos + 1;
while let Some(tok) = self.token_at(i) {
match tok {
Token::LParen | Token::LBracket | Token::LBrace => depth += 1,
Token::RParen | Token::RBracket | Token::RBrace => {
depth -= 1;
if depth == 0 {
return false;
}
}
Token::Greater if depth == 1 => return true,
_ => {}
}
i += 1;
}
false
}
/// Parse `(params>return;body)` as an inline lambda. Lifts the body into
/// a synthetic top-level `Decl::Function { name: "__lit_N", .. }` and
/// returns `Expr::Ref("__lit_N")` so HOFs see a fn-ref identical to a
/// named helper.
///
/// Phase 1: closures are rejected. Any reference to a name that isn't a
/// param, isn't a local binding, and isn't a known function/builtin
/// raises ILO-P017 pointing at the Phase 2 follow-up.
fn parse_inline_lambda(&mut self) -> Result<Expr> {
let start = self.peek_span();
self.expect(&Token::LParen)?;
// Parens are self-contained; reset whitespace-call mode inside.
let prev_no_ws = self.no_whitespace_call;
self.no_whitespace_call = false;
let params = self.parse_params()?;
self.expect(&Token::Greater)?;
let return_type = self.parse_type()?;
if self.peek() == Some(&Token::Semi) {
self.advance();
}
// The body parses until `)` at the current paren depth. We mark the
// RParen as a body terminator by parsing statements one-by-one and
// stopping when we see `)`. Reusing `parse_body` would consume the
// `)` as part of normal at-body-end logic — instead, parse a
// semicolon-separated sequence that terminates on RParen.
let body = self.parse_lambda_body()?;
self.no_whitespace_call = prev_no_ws;
let end = self.peek_span();
self.expect(&Token::RParen)?;
// Free-variable analysis. Phase 1 rejected any free var with ILO-P017;
// Phase 2 captures them: the lifted decl gets capture params appended
// after the originals, and the call site emits `Expr::MakeClosure`
// with `Expr::Ref(c)` per capture so they're snapshot by value at
// closure-construction time.
let bound: std::collections::HashSet<String> =
params.iter().map(|p| p.name.clone()).collect();
let mut free = Vec::new();
// `local` is shared across the body's statement sequence so that a
// `let` in stmt N makes its name visible to stmt N+1.
let mut local: Vec<String> = Vec::new();
for stmt in &body {
self.collect_free_in_stmt(&stmt.node, &bound, &mut local, &mut free);
}
// Lift to a synthetic top-level decl. If there are free variables,
// append them as capture params (`_:any` typed) after the originals.
let name = format!("__lit_{}", self.lambda_counter);
self.lambda_counter += 1;
let mut lifted_params = params;
for cap in &free {
lifted_params.push(Param {
name: cap.clone(),
ty: Type::Any,
});
}
self.register_user_fn(&name, &lifted_params);
let span = start.merge(end);
self.lifted_decls.push(Decl::Function {
name: name.clone(),
params: lifted_params,
return_type,
body,
span,
});
if free.is_empty() {
Ok(Expr::Ref(name))
} else {
let captures: Vec<Expr> = free.into_iter().map(Expr::Ref).collect();
Ok(Expr::MakeClosure {
fn_name: name,
captures,
})
}
}
/// Parse a `;`-separated sequence of statements terminated by `)`.
fn parse_lambda_body(&mut self) -> Result<Vec<Spanned<Stmt>>> {
let mut stmts = Vec::new();
if self.peek() != Some(&Token::RParen) {
let span_start = self.peek_span();
let stmt = self.parse_stmt()?;
stmts.push(Spanned {
node: stmt,
span: span_start.merge(self.prev_span()),
});
while self.peek() == Some(&Token::Semi) {
self.advance();
if self.peek() == Some(&Token::RParen) {
break;
}
let span_start = self.peek_span();
let stmt = self.parse_stmt()?;
stmts.push(Spanned {
node: stmt,
span: span_start.merge(self.prev_span()),
});
}
}
Ok(stmts)
}
/// Walk a statement and record any `Expr::Ref` that isn't bound by the
/// lambda's params, by an enclosing `let`/destructure/foreach inside the
/// body, or by a known function/builtin name. `local` carries
/// body-introduced bindings as we descend.
fn collect_free_in_stmt(
&self,
stmt: &Stmt,
params: &std::collections::HashSet<String>,
local: &mut Vec<String>,
free: &mut Vec<String>,
) {
match stmt {
Stmt::Let { name, value } => {
self.collect_free_in_expr(value, params, local, free);
local.push(name.clone());
}
Stmt::Guard {
condition,
body,
else_body,
..
} => {
self.collect_free_in_expr(condition, params, local, free);
let depth = local.len();
for s in body {
self.collect_free_in_stmt(&s.node, params, local, free);
}
local.truncate(depth);
if let Some(eb) = else_body {
let depth = local.len();
for s in eb {
self.collect_free_in_stmt(&s.node, params, local, free);
}
local.truncate(depth);
}
}
Stmt::Match { subject, arms } => {
if let Some(s) = subject {
self.collect_free_in_expr(s, params, local, free);
}
for arm in arms {
let depth = local.len();
match &arm.pattern {
Pattern::Err(b) | Pattern::Ok(b) => local.push(b.clone()),
Pattern::TypeIs { binding, .. } => local.push(binding.clone()),
_ => {}
}
for s in &arm.body {
self.collect_free_in_stmt(&s.node, params, local, free);
}
local.truncate(depth);
}
}
Stmt::ForEach {
binding,
collection,
body,
} => {
self.collect_free_in_expr(collection, params, local, free);
let depth = local.len();
local.push(binding.clone());
for s in body {
self.collect_free_in_stmt(&s.node, params, local, free);
}
local.truncate(depth);
}
Stmt::ForRange {
binding,
start,
end,
body,
} => {
self.collect_free_in_expr(start, params, local, free);
self.collect_free_in_expr(end, params, local, free);
let depth = local.len();
local.push(binding.clone());
for s in body {
self.collect_free_in_stmt(&s.node, params, local, free);
}
local.truncate(depth);
}
Stmt::While { condition, body } => {
self.collect_free_in_expr(condition, params, local, free);
let depth = local.len();
for s in body {
self.collect_free_in_stmt(&s.node, params, local, free);
}
local.truncate(depth);
}
Stmt::Return(e) | Stmt::Expr(e) => self.collect_free_in_expr(e, params, local, free),
Stmt::Break(opt) => {
if let Some(e) = opt {
self.collect_free_in_expr(e, params, local, free);
}
}
Stmt::Continue => {}
Stmt::Destructure { bindings, value } => {
self.collect_free_in_expr(value, params, local, free);
for b in bindings {
local.push(b.clone());
}
}
}
}
fn collect_free_in_expr(
&self,
expr: &Expr,
params: &std::collections::HashSet<String>,
local: &mut Vec<String>,
free: &mut Vec<String>,
) {
match expr {
Expr::Literal(_) => {}
Expr::Ref(name) => {
if name == "_" {
return;
}
if params.contains(name) || local.iter().any(|n| n == name) {
return;
}
// Known top-level fn (incl. builtins and lifted lambdas) — fine
// as a fn-ref. The verifier will reject unknown refs anyway,
// but we need to whitelist these so legitimate HOF use inside
// a lambda body (`srt slen xs` for a top-level `slen`) doesn't
// trip the closure check.
if self.fn_arity.contains_key(name) {
return;
}
if !free.iter().any(|n| n == name) {
free.push(name.clone());
}
}
Expr::Field { object, .. } => self.collect_free_in_expr(object, params, local, free),
Expr::Index { object, .. } => self.collect_free_in_expr(object, params, local, free),
Expr::Call { function, args, .. } => {
// Function name is resolved against the known-fn table; if it
// isn't known, the verifier will flag it. We do NOT treat the
// callee name as a free var (calls aren't captures).
let _ = function;
for a in args {
self.collect_free_in_expr(a, params, local, free);
}
}
Expr::BinOp { left, right, .. } => {
self.collect_free_in_expr(left, params, local, free);
self.collect_free_in_expr(right, params, local, free);
}
Expr::UnaryOp { operand, .. } => {
self.collect_free_in_expr(operand, params, local, free)
}
Expr::Ok(e) | Expr::Err(e) => self.collect_free_in_expr(e, params, local, free),
Expr::List(items) => {
for i in items {
self.collect_free_in_expr(i, params, local, free);
}
}
Expr::Record { fields, .. } => {
for (_, v) in fields {
self.collect_free_in_expr(v, params, local, free);
}
}
Expr::Match { subject, arms } => {
if let Some(s) = subject {
self.collect_free_in_expr(s, params, local, free);
}
for arm in arms {
let depth = local.len();
match &arm.pattern {
Pattern::Err(b) | Pattern::Ok(b) => local.push(b.clone()),
Pattern::TypeIs { binding, .. } => local.push(binding.clone()),
_ => {}
}
for s in &arm.body {
self.collect_free_in_stmt(&s.node, params, local, free);
}
local.truncate(depth);
}
}
Expr::NilCoalesce { value, default } => {
self.collect_free_in_expr(value, params, local, free);
self.collect_free_in_expr(default, params, local, free);
}
Expr::With { object, updates } => {
self.collect_free_in_expr(object, params, local, free);
for (_, v) in updates {
self.collect_free_in_expr(v, params, local, free);
}
}
Expr::Ternary {
condition,
then_expr,
else_expr,
} => {
self.collect_free_in_expr(condition, params, local, free);
self.collect_free_in_expr(then_expr, params, local, free);
self.collect_free_in_expr(else_expr, params, local, free);
}
Expr::MakeClosure { captures, .. } => {
// Already-lifted nested closure (only emitted by the parser
// itself). Its captures are expressions in the enclosing scope
// — walk them as free-var candidates so a nested lambda's
// capture transitively bubbles up through the outer lambda.
for cap in captures {
self.collect_free_in_expr(cap, params, local, free);
}
}
}
}
fn parse_number(&mut self) -> Result<f64> {
match self.peek().cloned() {
Some(Token::Number(n)) => {
self.advance();
Ok(n)
}
Some(tok) => Err(self.error("ILO-P013", format!("expected number, got {:?}", tok))),
None => Err(self.error("ILO-P014", "expected number, got EOF".into())),
}
}
}
/// Build the parser's static arity/HOF tables for builtins. These are used
/// during call-arg parsing to eagerly consume nested calls in arg position
/// (so `prnt str nc` parses as `prnt(str(nc))` instead of `prnt(str, nc)`).
///
/// Builtins with overloaded arities (`rnd`/`now` — 0 args, but also seen
/// with args in `rnd`, plus `get`/`post`/`rd`/`rdb` 1-or-2-arg variants and
/// `srt` 1-or-2-arg variants) get the BASE/canonical arity entered here.
/// `srt`'s entry uses arity 2 with a fn-ref first position, which lets
/// `srt cmp xs` expand and degrades gracefully for `srt xs` (the loop
/// simply stops when no more operands are available).
///
/// Mutating-only HOFs (`map`/`flt`/`fld`/`grp`) get fn-ref flag on slot 0.
fn builtin_arity_tables() -> (HashMap<String, usize>, HashMap<String, Vec<bool>>) {
// (name, arity, fn_ref_positions)
let entries: &[(&str, usize, &[usize])] = &[
// Conversion
("str", 1, &[]),
("num", 1, &[]),
// Math (unary)
("abs", 1, &[]),
("flr", 1, &[]),
("cel", 1, &[]),
("rou", 1, &[]),
("sqrt", 1, &[]),
("log", 1, &[]),
("exp", 1, &[]),
("sin", 1, &[]),
("cos", 1, &[]),
// Math (binary)
("min", 2, &[]),
("max", 2, &[]),
("mod", 2, &[]),
("pow", 2, &[]),
// Aggregates
("sum", 1, &[]),
("avg", 1, &[]),
// Collections (unary)
("len", 1, &[]),
("hd", 1, &[]),
("tl", 1, &[]),
("rev", 1, &[]),
("unq", 1, &[]),
("flat", 1, &[]),
("frq", 1, &[]),
// Collections (binary)
("at", 2, &[]),
("has", 2, &[]),
("spl", 2, &[]),
("cat", 2, &[]),
// Collections (ternary)
("slc", 3, &[]),
// Sort: 2-arg form (cmp, list) with fn-ref slot 0; 1-arg form
// (list) still parses because the loop stops when no operand
// follows. The 0th slot is a fn-ref position so `srt xs` keeps
// `xs` as a bare ref and doesn't try to expand it.
("srt", 2, &[0]),
// Higher-order
("map", 2, &[0]),
("flt", 2, &[0]),
("fld", 3, &[0]),
("grp", 2, &[0]),
("uniqby", 2, &[0]),
("partition", 2, &[0]),
("flatmap", 2, &[0]),
("mapr", 2, &[0]),
// I/O
("prnt", 1, &[]),
("wr", 2, &[]),
("wrl", 2, &[]),
("trm", 1, &[]),
("upr", 1, &[]),
("lwr", 1, &[]),
("cap", 1, &[]),
("ord", 1, &[]),
("chr", 1, &[]),
("chars", 1, &[]),
// fmt is variadic (template + N args) — leave to greedy parsing
// JSON
("jdmp", 1, &[]),
("jpar", 1, &[]),
("jpth", 2, &[]),
// Regex
("rgx", 2, &[]),
("rgxall", 2, &[]),
("rgxsub", 3, &[]),
// Map (associative)
("mget", 2, &[]),
("mset", 3, &[]),
("mhas", 2, &[]),
("mkeys", 1, &[]),
("mvals", 1, &[]),
("mdel", 2, &[]),
// Note: omitted by design — these have overloads or zero-arg forms
// best left to the existing greedy/zero-arg paths:
// rnd, now, mmap (0-arg, special-cased above)
// get, post, rd, rdb, rdl, env (variable arity / IO)
// $ / get (path access via dollar prefix)
];
let mut arity = HashMap::new();
let mut fn_flags = HashMap::new();
for (name, n, hof_slots) in entries {
arity.insert((*name).to_string(), *n);
let mut flags = vec![false; *n];
for &slot in *hof_slots {
if slot < flags.len() {
flags[slot] = true;
}
}
fn_flags.insert((*name).to_string(), flags);
}
// Mirror entries under their long-form aliases (e.g. `filter` → `flt`)
// so agents writing `filter pos xs` still get the HOF first-arg
// protection and arity-aware expansion.
for (long, short) in crate::ast::all_builtin_aliases() {
if let Some(n) = arity.get(short).copied() {
arity.insert(long.to_string(), n);
}
if let Some(flags) = fn_flags.get(short).cloned() {
fn_flags.insert(long.to_string(), flags);
}
}
(arity, fn_flags)
}
/// Extract the last expression from a body, falling back to Nil.
fn body_to_expr(body: Vec<Spanned<Stmt>>) -> Expr {
if body.is_empty() {
return Expr::Literal(Literal::Nil);
}
match body.into_iter().last().unwrap().node {
Stmt::Expr(e) => e,
// If the last statement is not an expression, fall back to Nil.
_ => Expr::Literal(Literal::Nil),
}
}
/// Wrap the last expression in a body as a `Let` binding.
/// For example, if the body is `[Expr(- 0 x)]`, it becomes
/// `[Let { name: "v", value: Subtract(0, x) }]`.
fn wrap_body_as_let(name: &str, mut body: Vec<Spanned<Stmt>>) -> Vec<Spanned<Stmt>> {
if body.is_empty() {
return vec![Spanned::unknown(Stmt::Let {
name: name.to_string(),
value: Expr::Literal(Literal::Nil),
})];
}
let last_idx = body.len() - 1;
let last = &mut body[last_idx];
let span = last.span;
match &last.node {
Stmt::Expr(expr) => {
body[last_idx] = Spanned::new(
Stmt::Let {
name: name.to_string(),
value: expr.clone(),
},
span,
);
}
_ => {
// If the last statement is not an expression (e.g. another Let),
// we can't transform it — leave it as-is. This shouldn't normally
// happen in well-formed ternary assignments.
}
}
body
}
/// Map a lambda-introducer keyword from another language to a friendly
/// ilo-equivalent hint. Returns `(message, hint)`. Used at expression
/// position when `fn`/`def` appears where an operand is expected.
fn lambda_keyword_message(tok: &Token) -> Option<(String, String)> {
let kw = match tok {
Token::KwFn => "fn",
Token::KwDef => "def",
_ => return None,
};
Some((
format!(
"`{kw}` is a reserved word and cannot start an expression"
),
"ilo's inline lambda syntax is `(p:t>r;body)`, e.g. `map (x:n>n;+x 1) xs`. For a named function use `name params>return;body` at the top level.".to_string(),
))
}
/// Map a compound-comparison prefix attempt (`=<`, `=>`) to its single-token
/// ilo equivalent. Returns `(rendered, replacement)`. Used by
/// `parse_prefix_binop` to surface ILO-P003 with a friendly hint before the
/// `Eq` is consumed as its own prefix op (which would then fail on the
/// second operand and surface a misleading "expected expression, got
/// LBrace" deep into the expression).
///
/// `!<` / `!>` are deliberately NOT covered here: `!` at statement position
/// is the negated-guard form (`!cond{body}`), so `!<d 0` parses as
/// "negated guard whose condition is `<d 0`", which is valid ilo and would
/// be incorrectly rejected by the hint.
fn compound_comparison_replacement(
first: &Token,
second: &Token,
) -> Option<(&'static str, &'static str)> {
match (first, second) {
(Token::Eq, Token::Less) => Some(("=<", "<=")),
(Token::Eq, Token::Greater) => Some(("=>", ">=")),
_ => None,
}
}
/// Identifier-keywords intercepted by `parse_stmt` as control-flow forms.
/// These names can never legitimately start a function declaration, so the
/// `is_fn_decl_start` heuristic must reject them — otherwise `wh >v 0{...}`
/// gets mis-parsed as a fn decl named `wh` returning `v` (see the gis-analyst
/// and routing-tsp persona reports).
fn is_reserved_stmt_keyword(name: &str) -> bool {
matches!(name, "wh" | "ret" | "brk" | "cnt")
}
/// Map a reserved-keyword token to its `(message, hint)` pair for ILO-P011.
fn reserved_keyword_message(tok: &Token) -> Option<(String, String)> {
let (name, hint) = match tok {
Token::KwIf => ("if", "ilo uses `cond{body}` for conditional branches"),
Token::KwReturn => ("return", "ilo uses `ret expr` for early returns"),
Token::KwLet => ("let", "ilo uses `name=expr` for bindings"),
Token::KwFn => ("fn", "ilo defines functions as `name params>return;body`"),
Token::KwDef => ("def", "ilo defines functions as `name params>return;body`"),
Token::KwVar => ("var", "ilo uses `name=expr` for bindings"),
Token::KwConst => ("const", "ilo uses `name=expr` for bindings"),
_ => return None,
};
Some((
format!("`{name}` is a reserved word and cannot be used as an identifier"),
hint.to_string(),
))
}
/// Check if an expression is a comparison or logical operator — eligible
/// as a braceless guard condition. Prefix operators have fixed arity, so
/// the parser knows exactly where the condition ends and the body begins.
/// Operators that, when sitting as the first token inside a match-arm `{...}`,
/// indicate the user wrote a statement (call / expr) rather than a pattern.
/// Patterns lead with `^`, `~`, `_`, a literal, or a type-letter; an arithmetic
/// or comparison operator at body head is therefore unambiguous statement-shape.
fn is_statement_head_operator(t: &Token) -> bool {
matches!(
t,
Token::Plus
| Token::Minus
| Token::Star
| Token::Slash
| Token::Eq
| Token::Greater
| Token::GreaterEq
| Token::Less
| Token::LessEq
| Token::NotEq
| Token::Bang
)
}
/// Render a simple Expr subject as source-ish text for diagnostics —
/// only the common case `Ref("name")` needs an exact echo; everything
/// else falls back to a placeholder so the hint stays readable.
fn subject_source(expr: &Expr) -> Option<String> {
match expr {
Expr::Ref(name) => Some(name.clone()),
_ => None,
}
}
fn is_guard_eligible_condition(expr: &Expr) -> bool {
matches!(
expr,
Expr::BinOp { op, .. } if matches!(
op,
BinOp::Equals | BinOp::NotEquals
| BinOp::GreaterThan | BinOp::LessThan
| BinOp::GreaterOrEqual | BinOp::LessOrEqual
| BinOp::And | BinOp::Or
)
)
}
/// Parse from token+span pairs.
/// Returns `(program, errors)`. The program may contain `Decl::Error` poison nodes
/// for declarations that failed to parse. Check `errors.is_empty()` before using
/// the program for execution — error nodes are skipped by the verifier but not
/// by the backends.
pub fn parse(tokens: Vec<(Token, Span)>) -> (Program, Vec<ParseError>) {
let mut parser = Parser::new(tokens);
parser.parse_program()
}
/// Parse from bare tokens (no span information, UNKNOWN spans).
/// Returns `Err` if any parse errors are present (first error).
/// Used by test helpers in interpreter, vm, and codegen modules.
#[cfg(test)]
pub fn parse_tokens(tokens: Vec<Token>) -> std::result::Result<Program, Vec<ParseError>> {
let pairs: Vec<(Token, Span)> = tokens.into_iter().map(|t| (t, Span::UNKNOWN)).collect();
let (prog, errors) = parse(pairs);
if errors.is_empty() {
Ok(prog)
} else {
Err(errors)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lexer;
fn parse_str(source: &str) -> Program {
let tokens = lexer::lex(source).unwrap();
let token_spans: Vec<(Token, Span)> = tokens
.into_iter()
.map(|(t, r)| {
(
t,
Span {
start: r.start,
end: r.end,
},
)
})
.collect();
let (prog, errors) = parse(token_spans);
assert!(errors.is_empty(), "parse errors: {:?}", errors);
prog
}
fn parse_str_errors(source: &str) -> (Program, Vec<ParseError>) {
let tokens = lexer::lex(source).unwrap();
let token_spans: Vec<(Token, Span)> = tokens
.into_iter()
.map(|(t, r)| {
(
t,
Span {
start: r.start,
end: r.end,
},
)
})
.collect();
parse(token_spans)
}
fn parse_file(path: &str) -> Program {
let source =
std::fs::read_to_string(path).unwrap_or_else(|e| panic!("cannot read {}: {}", path, e));
parse_str(&source)
}
#[test]
fn parse_simple_function() {
// tot p:n q:n r:n>n;s=*p q;t=*s r;+s t
let prog = parse_str("tot p:n q:n r:n>n;s=*p q;t=*s r;+s t");
assert_eq!(prog.declarations.len(), 1);
let Decl::Function {
name, params, body, ..
} = &prog.declarations[0]
else {
panic!("expected function")
};
assert_eq!(name, "tot");
assert_eq!(params.len(), 3);
assert_eq!(body.len(), 3); // s=..., t=..., +s t
}
#[test]
fn parse_let_binding() {
let prog = parse_str("f x:n>n;y=+x 1;y");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 2);
let Stmt::Let { name, .. } = &body[0].node else {
panic!("expected let")
};
assert_eq!(name, "y");
}
#[test]
fn parse_type_def() {
let prog = parse_str("type point{x:n;y:n}");
let Decl::TypeDef { name, fields, .. } = &prog.declarations[0] else {
panic!("expected type def")
};
assert_eq!(name, "point");
assert_eq!(fields.len(), 2);
}
#[test]
fn parse_guard() {
let prog = parse_str(r#"cls sp:n>t;>=sp 1000{"gold"};"bronze""#);
let Decl::Function { name, body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(name, "cls");
assert!(body.len() >= 2);
let Stmt::Guard { negated, .. } = &body[0].node else {
panic!("expected guard")
};
assert!(!negated);
}
#[test]
fn parse_match_stmt() {
let prog = parse_str(r#"f x:n>t;?{^e:^"error";~v:v;_:"default"}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { subject, arms } = &body[0].node else {
panic!("expected match")
};
assert!(subject.is_none());
assert_eq!(arms.len(), 3);
}
#[test]
fn parse_prefix_ternary() {
let prog = parse_str("f x:n>n;?=x 0 10 20");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Ternary {
condition,
then_expr,
else_expr,
}) = &body[0].node
else {
panic!("expected ternary, got {:?}", body[0])
};
assert!(matches!(
condition.as_ref(),
Expr::BinOp {
op: BinOp::Equals,
..
}
));
assert!(matches!(then_expr.as_ref(), Expr::Literal(Literal::Number(n)) if *n == 10.0));
assert!(matches!(else_expr.as_ref(), Expr::Literal(Literal::Number(n)) if *n == 20.0));
}
#[test]
fn parse_prefix_ternary_gt() {
let prog = parse_str("f x:n>n;?>x 3 1 0");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Ternary { condition, .. }) = &body[0].node else {
panic!("expected ternary, got {:?}", body[0])
};
assert!(matches!(
condition.as_ref(),
Expr::BinOp {
op: BinOp::GreaterThan,
..
}
));
}
#[test]
fn parse_prefix_ternary_assignment() {
let prog = parse_str("f x:n>n;v=?=x 0 10 20;v");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Let { name, value, .. } = &body[0].node else {
panic!("expected let, got {:?}", body[0])
};
assert_eq!(name, "v");
assert!(matches!(value, Expr::Ternary { .. }));
}
#[test]
fn parse_ok_err_exprs() {
let prog = parse_str("f x:n>R n t;~x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(
matches!(&body[0].node, Stmt::Expr(Expr::Ok(_))),
"expected Ok expr, got {:?}",
body[0]
);
}
#[test]
fn parse_foreach() {
let prog = parse_str("f xs:L n>n;s=0;@x xs{s=+s x};s");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(body.len() >= 3);
let Stmt::ForEach { binding, .. } = &body[1].node else {
panic!("expected foreach")
};
assert_eq!(binding, "x");
}
#[test]
fn parse_for_range() {
let prog = parse_str("f>n;@i 0..3{i}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::ForRange {
binding,
start,
end,
..
} = &body[0].node
else {
panic!("expected ForRange")
};
assert_eq!(binding, "i");
assert_eq!(*start, Expr::Literal(Literal::Number(0.0)));
assert_eq!(*end, Expr::Literal(Literal::Number(3.0)));
}
#[test]
fn parse_for_range_with_expr_end() {
// Dynamic end: @i 0..n{body}
let prog = parse_str("f n:n>n;@i 0..n{i}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::ForRange { binding, end, .. } = &body[0].node else {
panic!("expected ForRange")
};
assert_eq!(binding, "i");
assert_eq!(*end, Expr::Ref("n".to_string()));
}
#[test]
fn parse_multi_decl() {
let prog = parse_str("f x:n>n;*x 2 g x:n>n;+x 1");
assert_eq!(prog.declarations.len(), 2);
}
#[test]
fn parse_nested_prefix() {
let prog = parse_str("f a:n b:n c:n>n;+*a b c");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Add,
left,
..
}) = &body[0].node
else {
panic!("expected binop")
};
assert!(matches!(
**left,
Expr::BinOp {
op: BinOp::Multiply,
..
}
));
}
#[test]
fn parse_list_literal() {
let prog = parse_str("f x:n>L n;[x, *x 2, *x 3]");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::List(items)) = &body[0].node else {
panic!("expected list")
};
assert_eq!(items.len(), 3);
}
#[test]
fn parse_field_access() {
let prog = parse_str("f p:point>n;p.x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Field { field, .. }) = &body[0].node else {
panic!("expected field access")
};
assert_eq!(field, "x");
}
#[test]
fn parse_index_access() {
let prog = parse_str("f xs:L n>n;xs.0");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Index { index, .. }) = &body[0].node else {
panic!("expected index access")
};
assert_eq!(*index, 0);
}
#[test]
fn parse_safe_field_access() {
let prog = parse_str("f p:point>n;p.?x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Field { field, safe, .. }) = &body[0].node else {
panic!("expected safe field access")
};
assert_eq!(field, "x");
assert!(*safe);
}
#[test]
fn parse_negated_guard() {
let prog = parse_str(r#"f x:b>t;!x{"yes"};"no""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Guard { negated, .. } = &body[0].node else {
panic!("expected guard")
};
assert!(negated);
}
#[test]
fn parse_record_construction() {
let prog = parse_str("type point{x:n;y:n} f a:n b:n>point;point x:a y:b");
let Decl::Function { body, .. } = &prog.declarations[1] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Record { type_name, fields }) = &body[0].node else {
panic!("expected record")
};
assert_eq!(type_name, "point");
assert_eq!(fields.len(), 2);
}
#[test]
fn parse_with_expr() {
let prog = parse_str("type point{x:n;y:n} f p:point>point;p with x:1 y:2");
let Decl::Function { body, .. } = &prog.declarations[1] else {
panic!("expected function")
};
let Stmt::Expr(Expr::With { updates, .. }) = &body[0].node else {
panic!("expected with expr")
};
assert_eq!(updates.len(), 2);
}
#[test]
fn parse_tool_decl() {
let prog = parse_str(r#"tool fetch"http get" url:t>t timeout:30,retry:3"#);
let Decl::Tool {
name,
description,
timeout,
retry,
..
} = &prog.declarations[0]
else {
panic!("expected tool")
};
assert_eq!(name, "fetch");
assert_eq!(description, "http get");
assert_eq!(*timeout, Some(30.0));
assert_eq!(*retry, Some(3.0));
}
#[test]
fn parse_match_with_subject() {
let prog = parse_str("f x:R n t>n;?x{~v:v;^e:0}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { subject, arms } = &body[0].node else {
panic!("expected match stmt")
};
assert!(subject.is_some());
assert_eq!(arms.len(), 2);
}
#[test]
fn parse_match_expr_in_let() {
let prog = parse_str(r#"f x:R n t>n;r=?x{~v:v;^e:0};r"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 2);
assert!(
matches!(
&body[0].node,
Stmt::Let {
value: Expr::Match { .. },
..
}
),
"expected let with match expr, got {:?}",
body[0]
);
}
#[test]
fn parse_call_with_prefix_arg() {
// fac -n 1 should parse as Call(fac, [Subtract(n, 1)])
let prog = parse_str("fac n:n>n;r=fac -n 1;*n r");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Let {
value: Expr::Call { function, args, .. },
..
} = &body[0].node
else {
panic!("expected call with prefix arg")
};
assert_eq!(function, "fac");
assert_eq!(args.len(), 1);
assert!(matches!(
&args[0],
Expr::BinOp {
op: BinOp::Subtract,
..
}
));
}
// ── Infix operator tests ────────────────────────────────────────────────
#[test]
fn infix_add() {
let prog = parse_str("f x:n>n;x + 1");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp { op: BinOp::Add, .. }) = &body[0].node else {
panic!("expected infix add")
};
}
#[test]
fn infix_subtract() {
let prog = parse_str("f x:n>n;x - 3");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Subtract,
..
}) = &body[0].node
else {
panic!("expected infix subtract")
};
}
#[test]
fn infix_multiply() {
let prog = parse_str("f x:n>n;x * 2");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Multiply,
..
}) = &body[0].node
else {
panic!("expected infix multiply")
};
}
#[test]
fn infix_divide() {
let prog = parse_str("f x:n>n;x / 2");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Divide, ..
}) = &body[0].node
else {
panic!("expected infix divide")
};
}
#[test]
fn infix_precedence_mul_over_add() {
// x + y * 2 → +(x, *(y, 2))
let prog = parse_str("f x:n y:n>n;x + y * 2");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Add,
left,
right,
}) = &body[0].node
else {
panic!("expected add")
};
assert!(matches!(left.as_ref(), Expr::Ref(_)));
assert!(matches!(
right.as_ref(),
Expr::BinOp {
op: BinOp::Multiply,
..
}
));
}
#[test]
fn infix_parens_override_precedence() {
// (x + y) * 2 → *( +(x,y), 2 )
let prog = parse_str("f x:n y:n>n;(x + y) * 2");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Multiply,
left,
..
}) = &body[0].node
else {
panic!("expected multiply")
};
assert!(matches!(left.as_ref(), Expr::BinOp { op: BinOp::Add, .. }));
}
#[test]
fn infix_call_binds_tighter() {
// f a + b → (f a) + b
let prog = parse_str("f x:n>n;x g x:n>n;f x + 1");
let Decl::Function { body, .. } = &prog.declarations[1] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Add,
left,
..
}) = &body[0].node
else {
panic!("expected infix add")
};
assert!(matches!(left.as_ref(), Expr::Call { .. }));
}
#[test]
fn infix_comparison() {
let prog = parse_str("f x:n y:n>b;x > y");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::GreaterThan,
..
}) = &body[0].node
else {
panic!("expected gt")
};
}
#[test]
fn infix_and_or() {
let prog = parse_str("f a:b b:b>b;a & b");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp { op: BinOp::And, .. }) = &body[0].node else {
panic!("expected and")
};
}
#[test]
fn infix_left_associative() {
// a - b - c → (a - b) - c
let prog = parse_str("f a:n b:n c:n>n;a - b - c");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Subtract,
left,
..
}) = &body[0].node
else {
panic!("expected sub")
};
assert!(matches!(
left.as_ref(),
Expr::BinOp {
op: BinOp::Subtract,
..
}
));
}
#[test]
fn prefix_still_works_alongside_infix() {
// +x 1 should still work as prefix
let prog = parse_str("f x:n>n;+x 1");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp { op: BinOp::Add, .. }) = &body[0].node else {
panic!("expected prefix add")
};
}
#[test]
fn prefix_call_arg_still_works() {
// fac -n 1 should still parse as Call(fac, [-(n,1)])
let prog = parse_str("fac n:n>n;r=fac -n 1;*n r");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Let {
value: Expr::Call { function, args, .. },
..
} = &body[0].node
else {
panic!("expected call")
};
assert_eq!(function, "fac");
assert_eq!(args.len(), 1);
assert!(matches!(
&args[0],
Expr::BinOp {
op: BinOp::Subtract,
..
}
));
}
// ── End infix tests ───────────────────────────────────────────────────────
#[test]
fn parse_zero_arg_call() {
let prog = parse_str("f>n;g() g>n;42");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call { function, args, .. }) = &body[0].node else {
panic!("expected zero-arg call")
};
assert_eq!(function, "g");
assert!(args.is_empty());
}
#[test]
fn parse_paren_expr() {
let prog = parse_str("f x:n>n;*(+x 1) 2");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Multiply,
left,
..
}) = &body[0].node
else {
panic!("expected binop")
};
assert!(matches!(**left, Expr::BinOp { op: BinOp::Add, .. }));
}
#[test]
fn parse_list_append() {
let prog = parse_str("f xs:L n x:n>L n;+=xs x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(
matches!(
&body[0].node,
Stmt::Expr(Expr::BinOp {
op: BinOp::Append,
..
})
),
"expected append, got {:?}",
body[0]
);
}
#[test]
fn parse_trailing_comma_in_list() {
let prog = parse_str("f>L n;[1, 2, 3,]");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::List(items)) = &body[0].node else {
panic!("expected list")
};
assert_eq!(items.len(), 3);
}
#[test]
fn parse_empty_list() {
let prog = parse_str("f>L n;[]");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::List(items)) = &body[0].node else {
panic!("expected list")
};
assert!(items.is_empty());
}
#[test]
fn parse_list_space_separated() {
let prog = parse_str("f>L n;[1 2 3]");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::List(items)) = &body[0].node else {
panic!("expected list")
};
assert_eq!(items.len(), 3);
}
#[test]
fn parse_list_with_variables() {
let prog = parse_str(r#"f w:t>L t;["hi" w]"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::List(items)) = &body[0].node else {
panic!("expected list")
};
assert_eq!(items.len(), 2);
}
#[test]
fn parse_list_mixed_types() {
let prog = parse_str(r#"f>L a;["search" 10 true]"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::List(items)) = &body[0].node else {
panic!("expected list")
};
assert_eq!(items.len(), 3);
}
#[test]
fn parse_list_ok_err_elements() {
let prog = parse_str("f>L R n t;[~1 ~2 ~3]");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::List(items)) = &body[0].node else {
panic!("expected list")
};
assert_eq!(items.len(), 3);
}
#[test]
fn parse_caret_stmt_in_match() {
let prog = parse_str(r#"f x:R n t>n;?x{^e:^"error";~v:v;_:0}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert!(
matches!(&arms[0].body[0].node, Stmt::Expr(Expr::Err(_))),
"expected Err expr in first arm"
);
}
#[test]
fn parse_chained_field_access() {
let prog = parse_str("type inner{v:n} type outer{i:inner} f o:outer>n;o.i.v");
// Should parse as o.i.v (chained field access)
let Decl::Function { body, .. } = &prog.declarations[2] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Field { object, field, .. }) = &body[0].node else {
panic!("expected chained field")
};
assert_eq!(field, "v");
assert!(matches!(**object, Expr::Field { .. }));
}
#[test]
fn parse_multi_stmt_match_arm() {
let prog = parse_str("f x:R n t>n;?x{~v:y=+v 1;*y 2;^e:0}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert_eq!(arms[0].body.len(), 2); // y=+v 1, *y 2
}
#[test]
fn parse_negated_guard_vs_not_expr() {
// !x{body} is negated guard; !x as last stmt is logical NOT
let prog = parse_str("f x:b>b;!x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(
matches!(
&body[0].node,
Stmt::Expr(Expr::UnaryOp {
op: UnaryOp::Not,
..
})
),
"expected NOT expr, got {:?}",
body[0]
);
}
#[test]
fn parse_match_bool_literals() {
let prog = parse_str("f x:b>n;?x{true:1;false:0}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert!(matches!(
arms[0].pattern,
Pattern::Literal(Literal::Bool(true))
));
assert!(matches!(
arms[1].pattern,
Pattern::Literal(Literal::Bool(false))
));
}
#[test]
fn parse_match_number_with_wildcard() {
let prog = parse_str(r#"f x:n>t;?x{1:"one";2:"two";_:"other"}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert_eq!(arms.len(), 3);
assert!(matches!(arms[2].pattern, Pattern::Wildcard));
}
#[test]
fn parse_match_string_patterns() {
let prog = parse_str(r#"f x:t>n;?x{"a":1;"b":2;_:0}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert_eq!(arms.len(), 3);
assert!(matches!(&arms[0].pattern, Pattern::Literal(Literal::Text(s)) if s == "a"));
}
#[test]
fn parse_all_comparison_ops() {
// Each op produces a different BinOp
let tests = vec![
(">=a b", BinOp::GreaterOrEqual),
("<=a b", BinOp::LessOrEqual),
("!=a b", BinOp::NotEquals),
("=a b", BinOp::Equals),
(">a b", BinOp::GreaterThan),
("<a b", BinOp::LessThan),
("&a b", BinOp::And),
("|a b", BinOp::Or),
];
for (expr_str, expected_op) in tests {
let code = format!("f a:b b:b>b;{}", expr_str);
let prog = parse_str(&code);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::BinOp { op, .. }) = &body[0].node else {
panic!("expected binop for {}", expr_str)
};
assert_eq!(*op, expected_op, "failed for expr: {}", expr_str);
}
}
#[test]
fn parse_error_has_span() {
// "f x:n>n;+" — the + at byte 8 triggers an error because no operands follow
let source = "f x:n>n;+";
let tokens = lexer::lex(source).unwrap();
let token_spans: Vec<(Token, Span)> = tokens
.into_iter()
.map(|(t, r)| {
(
t,
Span {
start: r.start,
end: r.end,
},
)
})
.collect();
let (_prog, errors) = parse(token_spans);
let err = errors.into_iter().next().expect("expected parse error");
// Error message should mention the problem
assert!(!err.message.is_empty());
// Position should be non-zero (error is after the initial tokens)
assert!(err.position > 0, "error position should be > 0");
}
// ---- Span-specific tests ----
#[test]
fn fn_decl_span_covers_full_declaration() {
let prog = parse_str("f x:n>n;*x 2");
let Decl::Function { span, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(span.start, 0);
assert!(span.end > 0, "function span end should be > 0");
}
#[test]
fn type_decl_span_covers_full_declaration() {
let prog = parse_str("type point{x:n;y:n}");
let Decl::TypeDef { span, .. } = &prog.declarations[0] else {
panic!("expected type def")
};
assert_eq!(span.start, 0);
// Should extend to cover the closing }
assert!(
span.end >= 18,
"type span end should cover closing brace, got {}",
span.end
);
}
#[test]
fn multi_decl_spans_are_distinct() {
let prog = parse_str("f x:n>n;*x 2 g y:n>n;+y 1");
assert_eq!(prog.declarations.len(), 2);
let Decl::Function { span: span_f, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let span_f = *span_f;
let Decl::Function { span: span_g, .. } = &prog.declarations[1] else {
panic!("expected function")
};
let span_g = *span_g;
// f starts at 0, g starts after f
assert_eq!(span_f.start, 0);
assert!(span_g.start > span_f.start, "g should start after f");
assert!(
span_g.start >= span_f.end,
"g span should not overlap f span"
);
}
#[test]
fn tool_decl_has_span() {
let prog = parse_str(r#"tool fetch"http get" url:t>t"#);
let Decl::Tool { span, .. } = &prog.declarations[0] else {
panic!("expected tool")
};
assert_eq!(span.start, 0);
assert!(span.end > 0);
}
// ---- File-based tests ----
#[test]
fn parse_example_01_simple_function() {
let prog = parse_file("examples/01-simple-function.ilo");
assert_eq!(prog.declarations.len(), 1);
let Decl::Function {
name,
params,
return_type,
body,
..
} = &prog.declarations[0]
else {
panic!("expected function")
};
assert_eq!(name, "tot");
assert_eq!(params.len(), 3);
assert_eq!(*return_type, Type::Number);
assert_eq!(body.len(), 3);
}
#[test]
fn parse_example_02_with_dependencies() {
let prog = parse_file("examples/02-with-dependencies.ilo");
assert_eq!(prog.declarations.len(), 1);
let Decl::Function {
name, return_type, ..
} = &prog.declarations[0]
else {
panic!("expected function")
};
assert_eq!(name, "prc");
assert!(matches!(return_type, Type::Result(_, _)));
}
#[test]
fn parse_error_messages() {
let bad = "42 x:n>n;x";
let tokens = lexer::lex(bad).unwrap();
let token_spans: Vec<(Token, Span)> = tokens
.into_iter()
.map(|(t, r)| {
(
t,
Span {
start: r.start,
end: r.end,
},
)
})
.collect();
let (_prog, errors) = parse(token_spans);
let err = errors.into_iter().next().expect("expected parse error");
assert!(
err.message.contains("expected declaration"),
"got: {}",
err.message
);
}
#[test]
fn parse_complex_match_patterns() {
let prog = parse_str(r#"f x:R n t>n;?x{^e:0;~v:?v{1:100;2:200;_:v}}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 1);
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert_eq!(arms.len(), 2);
// Second arm body should be a nested match statement
assert!(matches!(&arms[1].body[0].node, Stmt::Match { .. }));
}
#[test]
fn parse_deeply_nested_prefix() {
let prog = parse_str("f x:n>n;+*+x 1 2 3");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
// Should be: +(*(+(x,1), 2), 3)
let Stmt::Expr(Expr::BinOp {
op: BinOp::Add,
left,
..
}) = &body[0].node
else {
panic!("expected add")
};
let Expr::BinOp {
op: BinOp::Multiply,
left: inner,
..
} = &**left
else {
panic!("expected nested multiply")
};
assert!(matches!(&**inner, Expr::BinOp { op: BinOp::Add, .. }));
}
#[test]
fn parse_tokens_legacy_api() {
// Test the legacy parse_tokens API
let source = "f x:n>n;*x 2";
let tokens: Vec<Token> = lexer::lex(source)
.unwrap()
.into_iter()
.map(|(t, _)| t)
.collect();
let prog = parse_tokens(tokens).unwrap();
assert_eq!(prog.declarations.len(), 1);
}
// ---- Error recovery tests ----
#[test]
fn recovery_second_function_parsed_after_first_error() {
// First function has missing `>` (no params, hits `;` instead of `>`)
// Second function should still parse correctly.
let (prog, errors) = parse_str_errors("f x:n n;bad g y:n>n;y");
// One error from `f`, one valid `g`
assert!(!errors.is_empty(), "expected parse error from f");
let valid: Vec<_> = prog
.declarations
.iter()
.filter(|d| !matches!(d, Decl::Error { .. }))
.collect();
assert_eq!(valid.len(), 1, "g should parse successfully");
let Decl::Function { name, .. } = valid[0] else {
panic!("expected function g")
};
assert_eq!(name, "g");
}
#[test]
fn recovery_error_node_in_declarations() {
let (prog, errors) = parse_str_errors("f x:n n;bad g y:n>n;y");
assert!(!errors.is_empty());
// Program.declarations has two entries: an Error and a Function
assert_eq!(prog.declarations.len(), 2);
assert!(matches!(prog.declarations[0], Decl::Error { .. }));
assert!(matches!(prog.declarations[1], Decl::Function { .. }));
}
#[test]
fn recovery_two_errors_both_reported() {
// Both functions have bad signatures
let (prog, errors) = parse_str_errors("f x:n n;bad g y:n n;bad");
assert_eq!(errors.len(), 2, "expected two errors");
assert_eq!(prog.declarations.len(), 2);
assert!(
prog.declarations
.iter()
.all(|d| matches!(d, Decl::Error { .. }))
);
}
#[test]
fn recovery_error_node_not_in_json() {
// Decl::Error nodes must be filtered from JSON AST output
let (prog, _errors) = parse_str_errors("f x:n n;bad g y:n>n;y");
let json = serde_json::to_string(&prog).unwrap();
// Only g should appear; the error node is suppressed
let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
let decls = parsed["declarations"].as_array().unwrap();
assert_eq!(
decls.len(),
1,
"only valid declarations should appear in JSON"
);
}
#[test]
fn recovery_stops_at_20_errors() {
// Build a string with 25 bad single-token "functions" followed by a valid one
let bad: String = (0..25).map(|i| format!("f{i} x:n n;bad ")).collect();
let good = "g y:n>n;y";
let source = format!("{bad}{good}");
let (_prog, errors) = parse_str_errors(&source);
assert!(
errors.len() <= 20,
"should cap at 20 errors, got {}",
errors.len()
);
}
#[test]
fn recovery_type_decl_after_error() {
// A type declaration after a broken function should be recovered
let (prog, errors) = parse_str_errors("f x:n n;bad type point{x:n;y:n}");
assert!(!errors.is_empty());
let valid: Vec<_> = prog
.declarations
.iter()
.filter(|d| !matches!(d, Decl::Error { .. }))
.collect();
assert_eq!(valid.len(), 1);
assert!(matches!(valid[0], Decl::TypeDef { .. }));
}
// ---- EOF error paths ----
#[test]
fn eof_while_expecting_type() {
// `f x:` — hits EOF while expecting a type
let (_, errors) = parse_str_errors("f x:");
assert!(!errors.is_empty(), "expected parse error");
assert!(
errors
.iter()
.any(|e| e.message.contains("EOF") || e.message.contains("expected")),
"unexpected error messages: {:?}",
errors
);
}
#[test]
fn eof_while_expecting_identifier() {
// `f` alone hits EOF inside the function header (no params, no `>`,
// no return type). After the ILO-P020 boundary-anchor work, this
// surfaces as "incomplete function header" anchored at `f` rather
// than a generic EOF message with `Span::UNKNOWN`. Either shape is
// fine for the persona — the assertion just needs to confirm a
// real parse error fired, not pin the exact wording.
let (_, errors) = parse_str_errors("f");
assert!(!errors.is_empty(), "expected parse error");
assert!(
errors.iter().any(|e| e.message.contains("EOF")
|| e.message.contains("expected")
|| e.message.contains("incomplete function header")),
"unexpected error messages: {:?}",
errors
);
}
#[test]
fn eof_while_expecting_expression() {
// `f x:n>n;+x` — incomplete binary op, hits EOF for right operand
let (_, errors) = parse_str_errors("f x:n>n;+x");
assert!(
!errors.is_empty(),
"expected parse error for EOF expression"
);
}
#[test]
fn eof_expecting_gt_in_signature() {
// `f x:n` — no `>` and no body
let (_, errors) = parse_str_errors("f x:n");
assert!(!errors.is_empty(), "expected parse error");
}
// ---- Tool description string missing (ILO-P015) ----
#[test]
fn tool_missing_description() {
let (_, errors) = parse_str_errors("tool my-tool x:n>n");
assert!(
!errors.is_empty(),
"expected parse error for missing description"
);
assert!(
errors.iter().any(|e| e.code == "ILO-P015"),
"expected ILO-P015 error, got: {:?}",
errors
);
}
// ---- Unexpected token in various positions ----
#[test]
fn unexpected_token_as_expression() {
// `}` is not a valid expression start
let (_, errors) = parse_str_errors("f x:n>n;>x 0{}};x");
assert!(!errors.is_empty(), "expected parse error");
}
#[test]
fn unexpected_token_as_pattern() {
// Invalid pattern in match arm
let (_, errors) = parse_str_errors("f x:n>n;?x{+:1;_:0}");
assert!(!errors.is_empty(), "expected parse error for bad pattern");
}
#[test]
fn eof_while_expecting_declaration() {
// Empty input — no declarations, should get EOF error
let (prog, errors) = parse_str_errors("");
// Empty programs may or may not produce errors; at minimum they produce no decls
let _ = (prog, errors);
}
#[test]
fn expect_ident_got_non_ident() {
// `type 123{...}` — expect_ident() gets a Number token → ILO-P005
let (_, errors) = parse_str_errors("type 123{x:n}");
assert!(!errors.is_empty(), "expected parse error");
assert!(
errors
.iter()
.any(|e| e.code == "ILO-P005" || e.message.contains("expected identifier")),
"unexpected errors: {:?}",
errors
);
}
#[test]
fn expect_ident_got_eof() {
// `type` — EOF where an identifier is expected → ILO-P006
let (_, errors) = parse_str_errors("type");
assert!(!errors.is_empty(), "expected parse error");
assert!(
errors
.iter()
.any(|e| e.code == "ILO-P006" || e.message.contains("EOF")),
"unexpected errors: {:?}",
errors
);
}
#[test]
fn parse_ok_expr_as_operand() {
// `~x` as the argument to a function call — exercises Tilde in parse_operand
let prog = parse_str("f x:n>R n t;g ~x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call { function, args, .. }) = &body[0].node else {
panic!("expected call")
};
assert_eq!(function, "g");
assert!(matches!(&args[0], Expr::Ok(_)));
}
#[test]
fn parse_err_expr_as_operand() {
// `^x` as the argument to a function call — exercises Caret in parse_operand
let prog = parse_str("f x:n>R n t;g ^x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call { function, args, .. }) = &body[0].node else {
panic!("expected call")
};
assert_eq!(function, "g");
assert!(matches!(&args[0], Expr::Err(_)));
}
#[test]
fn declaration_starts_with_prefix_op_gets_hint() {
// A declaration starting with `+` — triggers hint about prefix operators
let (_, errors) = parse_str_errors("+x 1");
assert!(!errors.is_empty(), "expected parse error");
}
#[test]
fn nested_brace_body_recovery() {
// A function body with nested braces that fail to parse properly
// This exercises the brace-depth tracking in error recovery
let (prog, errors) = parse_str_errors("f x:n>n;>x 0{{inner}};x g y:n>n;y");
// The recovery should still find `g`
assert!(!errors.is_empty(), "should have errors from nested braces");
let valid: Vec<_> = prog
.declarations
.iter()
.filter(|d| matches!(d, Decl::Function { name, .. } if name == "g"))
.collect();
assert!(
!valid.is_empty() || !prog.declarations.is_empty(),
"should recover at least something"
);
}
#[test]
fn parse_ident_guard_expr_or_guard() {
// Ident-starting guard: `x{42}` exercises parse_expr_or_guard returning a Guard (L621-625)
let prog = parse_str("f x:b>n;x{42}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(
matches!(&body[0].node, Stmt::Guard { negated: false, .. }),
"expected non-negated guard, got {:?}",
body[0]
);
}
#[test]
fn parse_eof_in_pattern() {
// EOF while parsing pattern → ILO-P012 error (L571)
// Construct tokens manually: f > n ; ? x { (no closing brace, no pattern)
let tokens: Vec<(Token, Span)> = vec![
(Token::Ident("f".to_string()), Span::UNKNOWN),
(Token::Greater, Span::UNKNOWN),
(Token::Ident("n".to_string()), Span::UNKNOWN),
(Token::Semi, Span::UNKNOWN),
(Token::Question, Span::UNKNOWN),
(Token::Number(1.0), Span::UNKNOWN),
(Token::LBrace, Span::UNKNOWN),
// EOF here — no pattern token
];
let (_, errors) = parse(tokens);
assert!(
!errors.is_empty(),
"expected parse error for EOF in pattern"
);
let found = errors
.iter()
.any(|e| e.code == "ILO-P012" || e.message.contains("EOF"));
assert!(found, "expected ILO-P012 error, got: {:?}", errors);
}
// ---- Coverage: trailing semicolons and edge cases ----
// L363: parse_body trailing `;` — consumed `;` but at_body_end → break
#[test]
fn parse_body_trailing_semicolon() {
// `f>n;42;` — `;` after `42` is consumed, then at_body_end (EOF) → break (L363)
let prog = parse_str("f>n;42;");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 1);
}
// L436: parse_match_arms trailing `;` before `}` — arm with empty body (L436)
// at_arm_end() is true at `;`, so parse_arm_body returns Ok([]).
// Then parse_match_arms sees `;`, consumes it, and peek is `}` → break (L436)
#[test]
fn parse_match_arms_trailing_semi() {
// `?{1:;}` — arm `1:` has empty body, `;` then `}` → break at L436
let prog = parse_str("f>n;?{1:;}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert_eq!(arms.len(), 1);
assert_eq!(arms[0].body.len(), 0); // empty body
}
// L460: parse_arm_body trailing `;` before `}` — consumed `;`, at_arm_end → break (L460)
#[test]
fn parse_arm_body_trailing_semi() {
// `?0{_:1;}` — in arm body, `;` consumed, peek is `}` → at_arm_end → break (L460)
let prog = parse_str("f>n;?0{_:1;}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert_eq!(arms.len(), 1);
assert_eq!(arms[0].body.len(), 1);
}
// L477: semi_starts_new_arm — after_semi >= tokens.len() (EOF after `;`) → return false (L477)
#[test]
fn parse_incomplete_match_arm_eof_after_semi() {
// `?x{1:42;` — `;` is the last token → semi_starts_new_arm hits L477
let (_, errors) = parse_str_errors("f x:n>n;?x{1:42;");
assert!(
!errors.is_empty(),
"expected parse error for unclosed match"
);
}
// L670: parse_expr_or_with — ident after `with` not followed by `:` → break (L670)
#[test]
fn parse_with_ident_no_colon() {
// `x with a` — `a` not followed by `:` (EOF) → break at L670, `a` stays unconsumed
let (_, errors) = parse_str_errors("f x:n>n;x with a");
// Errors may occur from leftover tokens, but L670 is exercised
let _ = errors;
}
// L991: parse_number in tool timeout — non-number token → ILO-P013 error (L991)
#[test]
fn parse_tool_timeout_non_numeric() {
// `timeout:foo` — `foo` is Ident, not Number → parse_number ILO-P013 at L991
let (_, errors) = parse_str_errors(r#"tool f "desc" x:n>n timeout:foo"#);
assert!(
!errors.is_empty(),
"expected parse error for non-numeric timeout"
);
let found = errors
.iter()
.any(|e| e.code == "ILO-P013" || e.message.contains("expected number"));
assert!(found, "expected ILO-P013, got: {:?}", errors);
}
// L992: parse_number in tool timeout — EOF after `:` → ILO-P014 error (L992)
#[test]
fn parse_tool_timeout_eof() {
// `timeout:` followed by EOF → parse_number ILO-P014 at L992
let (_, errors) = parse_str_errors(r#"tool f "desc" x:n>n timeout:"#);
assert!(!errors.is_empty(), "expected parse error for EOF timeout");
let found = errors
.iter()
.any(|e| e.code == "ILO-P014" || e.message.contains("EOF"));
assert!(found, "expected ILO-P014, got: {:?}", errors);
}
#[test]
fn parse_semi_starts_new_arm_caret_eof() {
// L488: `false` branch in semi_starts_new_arm() for Caret pattern when
// after_semi + 2 >= tokens.len() (only `^ident` after `;`, no `:`)
// Input: `?x{1:2;^v` — after arm `1:2`, we're at `;`, next is `^v` then EOF
let (_, errors) = parse_str_errors("f x:n>n;?x{1:2;^v");
// Parse error expected (incomplete arm), but the false-branch in semi_starts_new_arm fires
let _ = errors; // errors are expected (incomplete parse)
}
#[test]
fn parse_semi_starts_new_arm_tilde_eof() {
// L499: `false` branch in semi_starts_new_arm() for Tilde pattern when
// after_semi + 2 >= tokens.len() (only `~ident` after `;`, no `:`)
let (_, errors) = parse_str_errors("f x:n>n;?x{1:2;~v");
let _ = errors;
}
#[test]
fn parse_decl_eof() {
// L190: `None => Err(...)` in parse_decl() when peek() is None at declaration start
// A trailing `;` after a valid declaration causes the parser to try to parse another decl
let (prog, _) = parse_str_errors("f>n;42;");
// Either parsed successfully (trailing semi in body) or parser got EOF
let _ = prog;
}
#[test]
fn parse_prev_span_at_zero() {
// L292: `Span::UNKNOWN` in prev_span() when pos == 0
// Trigger by having a tool decl with no tokens consumed yet at a parse_body call
// Actually, just parsing something that calls prev_span at position 0
let (_, errors) = parse_str_errors("");
let _ = errors;
}
// L190: parse_decl() with empty token stream → None => Err("expected declaration, got EOF")
#[test]
fn parse_decl_with_empty_tokens() {
let mut parser = Parser::new(vec![]);
let result = parser.parse_decl();
assert!(result.is_err());
assert_eq!(result.unwrap_err().code, "ILO-P002");
}
// L292: prev_span() when pos == 0 (no tokens consumed) → Span::UNKNOWN
#[test]
fn prev_span_at_position_zero() {
let parser = Parser::new(vec![(Token::Ident("x".into()), Span { start: 1, end: 2 })]);
// pos == 0, nothing consumed → should return Span::UNKNOWN
assert_eq!(parser.prev_span(), Span::UNKNOWN);
}
// L472: semi_starts_new_arm() when peek() != Semi → return false at L472
#[test]
fn semi_starts_new_arm_non_semi_token() {
let parser = Parser::new(vec![(Token::Ident("x".into()), Span::UNKNOWN)]);
// peek() is Ident, not Semi → L472 returns false
assert!(!parser.semi_starts_new_arm());
}
// ---- C3: parser hint/suggestion tests ----
#[test]
fn hint_p001_function_keyword() {
let (_, errors) = parse_str_errors("function foo() {}");
assert!(!errors.is_empty());
let e = errors.iter().find(|e| e.code == "ILO-P001").unwrap();
let hint = e.hint.as_ref().unwrap();
assert!(hint.contains("ilo function syntax"));
}
#[test]
fn hint_p001_let_keyword() {
let (_, errors) = parse_str_errors("let x = 5");
assert!(!errors.is_empty());
let e = errors.iter().find(|e| e.code == "ILO-P001").unwrap();
let hint = e.hint.as_ref().unwrap();
assert!(hint.contains("assignment syntax"));
}
#[test]
fn hint_p001_return_keyword() {
let (_, errors) = parse_str_errors("return x");
assert!(!errors.is_empty());
let e = errors.iter().find(|e| e.code == "ILO-P001").unwrap();
let hint = e.hint.as_ref().unwrap();
assert!(hint.contains("return value"));
}
#[test]
fn hint_p001_if_keyword() {
let (_, errors) = parse_str_errors("if x > 0 { true }");
assert!(!errors.is_empty());
let e = errors.iter().find(|e| e.code == "ILO-P001").unwrap();
let hint = e.hint.as_ref().unwrap();
assert!(hint.contains("match"));
}
#[test]
fn hint_p001_operator_at_decl_level() {
// '+' at declaration level — operator hint
let tokens = vec![
(Token::Plus, Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty());
let e = errors.iter().find(|e| e.code == "ILO-P001").unwrap();
let hint = e.hint.as_ref().unwrap();
assert!(hint.contains("prefix operators"));
}
#[test]
fn hint_p003_arrow_instead_of_greater() {
// f x:n->n;x uses -> instead of >
let (_, errors) = parse_str_errors("f x:n->n;x");
// Should find an error about -> vs >
assert!(!errors.is_empty());
let e = errors.iter().find(|e| e.code == "ILO-P003").unwrap();
let hint = e.hint.as_ref().unwrap();
assert!(hint.contains("->"));
assert!(hint.contains(">"));
}
#[test]
fn hint_p003_double_amp() {
// && at expression level
let (_, errors) = parse_str_errors("f x:b y:b>b;&&x y");
let e = errors.iter().find(|e| e.code == "ILO-P003").unwrap();
let hint = e.hint.as_ref().unwrap();
assert!(hint.contains("'&'"));
assert!(hint.contains("'|'"));
}
#[test]
fn hint_p003_double_pipe() {
// || at expression level
let (_, errors) = parse_str_errors("f x:b y:b>b;||x y");
let e = errors.iter().find(|e| e.code == "ILO-P003").unwrap();
let hint = e.hint.as_ref().unwrap();
assert!(hint.contains("'|'"));
}
#[test]
fn no_hint_p001_unrecognized_token() {
// A token that has no specific hint
let tokens = vec![(Token::Number(42.0), Span::UNKNOWN)];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty());
// Should get ILO-P001 but no hint for a bare number
let e = errors.iter().find(|e| e.code == "ILO-P001").unwrap();
assert!(e.hint.is_none());
}
#[test]
fn parse_unwrap_call() {
// Single function with unwrap call as let-bind (no multi-func boundary issue)
let prog = parse_str("f x:n>R n t;d=g! x;~d");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Let {
value:
Expr::Call {
function,
args,
unwrap,
},
..
} = &body[0].node
else {
panic!("expected unwrap call")
};
assert_eq!(function, "g");
assert!(unwrap.is_propagate());
assert_eq!(args.len(), 1);
assert!(matches!(&args[0], Expr::Ref(n) if n == "x"));
}
#[test]
fn parse_unwrap_zero_arg() {
// fetch!() → Call { function: "fetch", unwrap: UnwrapMode::Propagate, args: [] }
let prog = parse_str("f>R t t;d=g!();~d");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Let {
value:
Expr::Call {
function,
args,
unwrap,
},
..
} = &body[0].node
else {
panic!("expected unwrap zero-arg call")
};
assert_eq!(function, "g");
assert!(unwrap.is_propagate());
assert!(args.is_empty());
}
#[test]
fn parse_bang_not_is_not_unwrap() {
// g !x → Call(g, [Not(Ref(x))]), NOT an unwrap call
// Single-function to avoid boundary issues
let prog = parse_str("f x:b>b;g !x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call {
function,
args,
unwrap,
..
}) = &body[0].node
else {
panic!("expected call with NOT arg")
};
assert_eq!(function, "g");
assert!(!unwrap.is_any());
assert_eq!(args.len(), 1);
assert!(matches!(
&args[0],
Expr::UnaryOp {
op: UnaryOp::Not,
..
}
));
}
#[test]
fn parse_unwrap_multi_arg() {
// f! a b → Call { function: "f", unwrap: UnwrapMode::Propagate, args: [Ref("a"), Ref("b")] }
// Use let-bind to avoid greedy arg consumption at decl boundary
let prog = parse_str("f a:n b:n>R n t;d=g! a b;~d");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Let {
value:
Expr::Call {
function,
args,
unwrap,
},
..
} = &body[0].node
else {
panic!("expected unwrap multi-arg call")
};
assert_eq!(function, "g");
assert!(unwrap.is_propagate());
assert_eq!(args.len(), 2);
}
#[test]
fn parse_unwrap_as_last_expr() {
// Unwrap as the last expression in the body (tail position)
let prog = parse_str("f x:n>R n t;g! x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call {
function, unwrap, ..
}) = &body[0].node
else {
panic!("expected unwrap call expr")
};
assert_eq!(function, "g");
assert!(unwrap.is_propagate());
}
// ---- Braceless guards ----
#[test]
fn braceless_guard_comparison_literal() {
// >=sp 1000 "gold" → Guard with comparison condition and literal body
let prog = parse_str(r#"cls sp:n>t;>=sp 1000 "gold";"bronze""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(
body.len(),
2,
"expected 2 stmts (guard + expr), got {:?}",
body
);
let Stmt::Guard {
condition,
negated,
body: guard_body,
..
} = &body[0].node
else {
panic!("expected guard")
};
assert!(!negated);
assert!(matches!(
condition,
Expr::BinOp {
op: BinOp::GreaterOrEqual,
..
}
));
assert_eq!(guard_body.len(), 1);
let Stmt::Expr(Expr::Literal(Literal::Text(s))) = &guard_body[0].node else {
panic!("expected text literal body")
};
assert_eq!(s, "gold");
}
#[test]
fn braceless_guard_variable_body() {
// <=n 1 n → Guard returning variable
let prog = parse_str("fib n:n>n;<=n 1 n;+n 1");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 2);
let Stmt::Guard {
condition,
negated,
body: guard_body,
..
} = &body[0].node
else {
panic!("expected guard")
};
assert!(!negated);
assert!(matches!(
condition,
Expr::BinOp {
op: BinOp::LessOrEqual,
..
}
));
assert_eq!(guard_body.len(), 1);
assert!(matches!(&guard_body[0].node, Stmt::Expr(Expr::Ref(n)) if n == "n"));
}
#[test]
fn braceless_guard_ok_body() {
// >=x 0 ~x → Guard returning Ok(x)
let prog = parse_str("f x:n>R n t;>=x 0 ~x;^\"negative\"");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Guard {
body: guard_body, ..
} = &body[0].node
else {
panic!("expected guard")
};
assert_eq!(guard_body.len(), 1);
assert!(matches!(&guard_body[0].node, Stmt::Expr(Expr::Ok(_))));
}
#[test]
fn braceless_guard_err_body() {
// <x 0 ^"negative" → Guard returning Err
let prog = parse_str(r#"f x:n>R n t;<x 0 ^"negative";~x"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Guard {
body: guard_body, ..
} = &body[0].node
else {
panic!("expected guard")
};
assert_eq!(guard_body.len(), 1);
assert!(matches!(&guard_body[0].node, Stmt::Expr(Expr::Err(_))));
}
#[test]
fn braceless_guard_operator_body() {
// >=x 10 +x 1 → Guard returning x+1
let prog = parse_str("f x:n>n;>=x 10 +x 1;*x 2");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 2);
let Stmt::Guard {
body: guard_body, ..
} = &body[0].node
else {
panic!("expected guard")
};
assert_eq!(guard_body.len(), 1);
assert!(matches!(
&guard_body[0].node,
Stmt::Expr(Expr::BinOp { op: BinOp::Add, .. })
));
}
#[test]
fn braceless_guard_multi_guard_program() {
// Full classify program with braceless guards
let prog = parse_str(r#"cls sp:n>t;>=sp 1000 "gold";>=sp 500 "silver";"bronze""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 3, "expected 3 stmts, got {:?}", body);
assert!(matches!(&body[0].node, Stmt::Guard { .. }));
assert!(matches!(&body[1].node, Stmt::Guard { .. }));
assert!(matches!(
&body[2].node,
Stmt::Expr(Expr::Literal(Literal::Text(_)))
));
}
#[test]
fn braceless_guard_negated() {
// !>=x 10 "small" → negated braceless guard
let prog = parse_str(r#"f x:n>t;!>=x 10 "small";"big""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 2);
let Stmt::Guard {
condition,
negated,
body: guard_body,
..
} = &body[0].node
else {
panic!("expected negated guard")
};
assert!(negated);
assert!(matches!(
condition,
Expr::BinOp {
op: BinOp::GreaterOrEqual,
..
}
));
assert_eq!(guard_body.len(), 1);
let Stmt::Expr(Expr::Literal(Literal::Text(s))) = &guard_body[0].node else {
panic!("expected text body")
};
assert_eq!(s, "small");
}
#[test]
fn braceless_guard_non_comparison_not_triggered() {
// +x y "result" — Add is NOT a comparison, so no braceless guard
// +x y is an expr, "result" is a separate expr
let prog = parse_str(r#"f x:n y:n>t;+x y;"result""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
// First stmt should be an Expr (BinOp Add), not a Guard
assert!(
matches!(
&body[0].node,
Stmt::Expr(Expr::BinOp { op: BinOp::Add, .. })
),
"non-comparison should not trigger braceless guard, got {:?}",
body[0]
);
}
#[test]
fn braceless_guard_braced_still_works() {
// Braced guards should still work exactly as before
let prog = parse_str(r#"cls sp:n>t;>=sp 1000{"gold"};"bronze""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 2);
let Stmt::Guard { negated, .. } = &body[0].node else {
panic!("expected guard")
};
assert!(!negated);
}
#[test]
fn braceless_guard_equality() {
// =x "admin" ~x → equality check braceless guard
let prog = parse_str(r#"f x:t>R t t;=x "admin" ~x;^"denied""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Guard { condition, .. } = &body[0].node else {
panic!("expected guard")
};
assert!(matches!(
condition,
Expr::BinOp {
op: BinOp::Equals,
..
}
));
}
#[test]
fn braceless_guard_logical_and() {
// &a b "both" → logical AND braceless guard
let prog = parse_str(r#"f a:b b:b>t;&a b "both";"nope""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Guard { condition, .. } = &body[0].node else {
panic!("expected guard")
};
assert!(matches!(condition, Expr::BinOp { op: BinOp::And, .. }));
}
#[test]
fn braceless_guard_at_end_no_body() {
// >=x 10 at end with semicolon but no body token → not a braceless guard
let prog = parse_str("f x:n>b;>=x 10");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 1);
// Should be a plain expression, not a guard (nothing follows)
assert!(matches!(
&body[0].node,
Stmt::Expr(Expr::BinOp {
op: BinOp::GreaterOrEqual,
..
})
));
}
#[test]
fn braceless_guard_factorial() {
// fac n:n>n;<=n 1 1;r=fac -n 1;*n r
let prog = parse_str("fac n:n>n;<=n 1 1;r=fac -n 1;*n r");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(
body.len(),
3,
"expected 3 stmts (guard + let + expr), got {:?}",
body
);
let Stmt::Guard {
condition,
body: guard_body,
..
} = &body[0].node
else {
panic!("expected guard")
};
assert!(matches!(
condition,
Expr::BinOp {
op: BinOp::LessOrEqual,
..
}
));
assert_eq!(guard_body.len(), 1);
assert!(
matches!(&guard_body[0].node, Stmt::Expr(Expr::Literal(Literal::Number(n))) if *n == 1.0)
);
}
// ---- Braceless guard ambiguity detection (ILO-P016) ----
#[test]
fn braceless_guard_dangling_token_error() {
// >=sp 1000 classify sp — `classify` is body, `sp` dangles → ILO-P016
let (_, errors) = parse_str_errors("cls sp:n>t;>=sp 1000 classify sp");
assert!(
errors.iter().any(|e| e.code == "ILO-P016"),
"expected ILO-P016 error, got: {:?}",
errors
);
assert!(
errors
.iter()
.any(|e| e.hint.as_ref().is_some_and(|h| h.contains("braces"))),
"expected hint about braces, got: {:?}",
errors
);
}
#[test]
fn braceless_guard_valid_semicolon_terminates() {
// >=sp 1000 classify; — `classify` as variable ref, semicolon terminates → valid
let prog = parse_str("cls sp:n>t;>=sp 1000 classify;\"fallback\"");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(matches!(&body[0].node, Stmt::Guard { .. }));
}
// ---- Dollar / HTTP get tests ----
#[test]
fn parse_dollar_desugars_to_get() {
let prog = parse_str(r#"f url:t>R t t;$url"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call {
function,
args,
unwrap,
}) = &body[0].node
else {
panic!("expected get call")
};
assert_eq!(function, "get");
assert_eq!(args.len(), 1);
assert!(!unwrap.is_any());
}
#[test]
fn parse_dollar_bang_desugars_to_get_unwrap() {
let prog = parse_str(r#"f url:t>t;$!url"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call {
function,
args,
unwrap,
}) = &body[0].node
else {
panic!("expected get! call")
};
assert_eq!(function, "get");
assert_eq!(args.len(), 1);
assert!(unwrap.is_propagate());
}
#[test]
fn parse_dollar_with_string_literal() {
let prog = parse_str(r#"f>R t t;$"http://example.com""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call { function, args, .. }) = &body[0].node else {
panic!("expected get call")
};
assert_eq!(function, "get");
assert!(matches!(&args[0], Expr::Literal(Literal::Text(_))));
}
#[test]
fn parse_ternary_guard_else() {
let source = r#"f x:n>t;=x 1{"yes"}{"no"}"#;
let (program, errors) = parse_str_errors(source);
assert!(errors.is_empty(), "parse errors: {:?}", errors);
let Decl::Function { body, .. } = &program.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 1, "expected 1 stmt (ternary), got {:?}", body);
let Stmt::Guard { else_body, .. } = &body[0].node else {
panic!("expected guard with else")
};
assert!(else_body.is_some(), "expected else_body in ternary");
let eb = else_body.as_ref().unwrap();
assert_eq!(eb.len(), 1);
}
#[test]
fn parse_while_loop() {
let prog = parse_str("f>n;wh true{42}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::While { condition, body } = &body[0].node else {
panic!("expected While")
};
assert!(matches!(condition, Expr::Literal(Literal::Bool(true))));
assert_eq!(body.len(), 1);
}
#[test]
fn parse_ret_statement() {
let prog = parse_str("f x:n>n;ret +x 1");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 1);
assert!(
matches!(
&body[0].node,
Stmt::Return(Expr::BinOp { op: BinOp::Add, .. })
),
"expected Return(BinOp::Add), got {:?}",
body[0]
);
}
#[test]
fn parse_pipe_simple() {
// f x>>g desugars to g(f(x))
let prog = parse_str("add a:n b:n>n;+a b\nf x:n>n;add x 1>>add 2");
let Decl::Function { body, .. } = &prog.declarations[1] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call { function, args, .. }) = &body[0].node else {
panic!("expected Call")
};
assert_eq!(function, "add");
assert_eq!(args.len(), 2); // 2 and add(x, 1)
}
#[test]
fn parse_pipe_chain() {
// str x>>len desugars to len(str(x))
let prog = parse_str("f x:n>n;str x>>len");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call { function, args, .. }) = &body[0].node else {
panic!("expected Call")
};
assert_eq!(function, "len");
assert_eq!(args.len(), 1);
let Expr::Call { function, .. } = &args[0] else {
panic!("expected Call(str)")
};
assert_eq!(function, "str");
}
#[test]
fn parse_ret_in_guard() {
let prog = parse_str(r#"f x:n>t;>x 0{ret "pos"};"neg""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(body.len(), 2);
let Stmt::Guard {
body: guard_body, ..
} = &body[0].node
else {
panic!("expected guard")
};
let Stmt::Return(Expr::Literal(Literal::Text(s))) = &guard_body[0].node else {
panic!("expected Return")
};
assert_eq!(s, "pos");
}
#[test]
fn parse_brk_no_value() {
let prog = parse_str("f>n;wh true{brk}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::While { body, .. } = &body[0].node else {
panic!("expected While")
};
assert!(matches!(&body[0].node, Stmt::Break(None)));
}
#[test]
fn parse_brk_with_value() {
let prog = parse_str("f>n;wh true{brk 42}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::While { body, .. } = &body[0].node else {
panic!("expected While")
};
assert!(
matches!(&body[0].node, Stmt::Break(Some(Expr::Literal(Literal::Number(n)))) if *n == 42.0)
);
}
#[test]
fn parse_cnt() {
let prog = parse_str("f>n;wh true{cnt}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::While { body, .. } = &body[0].node else {
panic!("expected While")
};
assert!(matches!(&body[0].node, Stmt::Continue));
}
#[test]
fn parse_dollar_in_operand() {
// $ in operand position (inside a binary op)
let prog = parse_str(r#"f url:t>R t t;cat [$url] ",""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call { function, .. }) = &body[0].node else {
panic!("expected Call")
};
assert_eq!(function, "cat");
}
// ---- Destructuring bind tests ----
#[test]
fn parse_destructure_two_fields() {
let prog = parse_str("type pt{x:n;y:n} f p:pt>n;{x;y}=p;+x y");
let Decl::Function { body: func, .. } = &prog.declarations[1] else {
panic!("expected function")
};
let Stmt::Destructure { bindings, value } = &func[0].node else {
panic!("expected Destructure")
};
assert_eq!(bindings, &["x", "y"]);
assert!(matches!(value, Expr::Ref(name) if name == "p"));
}
#[test]
fn parse_destructure_single_field() {
let prog = parse_str("type pt{x:n} f p:pt>n;{x}=p;x");
let Decl::Function { body: func, .. } = &prog.declarations[1] else {
panic!("expected function")
};
let Stmt::Destructure { bindings, .. } = &func[0].node else {
panic!("expected Destructure")
};
assert_eq!(bindings, &["x"]);
}
#[test]
fn parse_destructure_three_fields() {
let prog = parse_str("type pt{a:n;b:t;c:b} f p:pt>n;{a;b;c}=p;a");
let Decl::Function { body: func, .. } = &prog.declarations[1] else {
panic!("expected function")
};
let Stmt::Destructure { bindings, .. } = &func[0].node else {
panic!("expected Destructure")
};
assert_eq!(bindings, &["a", "b", "c"]);
}
// ---- Greedy argument parsing regression tests ----
/// A non-last function ending with a call must not consume the next function's
/// name as an argument. `len xs` should parse as Call(len, [xs]), and `g` must
/// become its own zero-param declaration.
#[test]
fn greedy_arg_stops_at_zero_param_decl() {
// `len xs` ends the first function; `g` starts a zero-param function (g>n)
let prog = parse_str("f xs:n>n;len xs g>n;2");
assert_eq!(
prog.declarations.len(),
2,
"expected exactly 2 declarations"
);
let Decl::Function { name, body, .. } = &prog.declarations[0] else {
panic!("expected function f")
};
assert_eq!(name, "f");
// Body has one statement: Call(len, [xs])
let Stmt::Expr(Expr::Call { function, args, .. }) = &body[0].node else {
panic!("expected Call(len, [xs])")
};
assert_eq!(function, "len");
assert_eq!(
args.len(),
1,
"len should have exactly 1 arg, not consume `g`"
);
assert!(matches!(&args[0], Expr::Ref(n) if n == "xs"));
let Decl::Function { name, .. } = &prog.declarations[1] else {
panic!("expected function g")
};
assert_eq!(name, "g");
}
/// A non-last function ending with a call must not consume the next function's
/// name (parameterised form) as an argument.
#[test]
fn greedy_arg_stops_at_parameterised_decl() {
// `len xs` ends the first function; `g y:n>n` is a parameterised function
let prog = parse_str("f xs:n>n;len xs g y:n>n;*y 2");
assert_eq!(
prog.declarations.len(),
2,
"expected exactly 2 declarations"
);
let Decl::Function { name, body, .. } = &prog.declarations[0] else {
panic!("expected function f")
};
assert_eq!(name, "f");
let Stmt::Expr(Expr::Call { function, args, .. }) = &body[0].node else {
panic!("expected Call(len, [xs])")
};
assert_eq!(function, "len");
assert_eq!(
args.len(),
1,
"len should have exactly 1 arg, not consume `g`"
);
let Decl::Function { name, params, .. } = &prog.declarations[1] else {
panic!("expected function g")
};
assert_eq!(name, "g");
assert_eq!(params.len(), 1);
assert_eq!(params[0].name, "y");
}
/// Three functions in sequence — the middle one ends with a call.
#[test]
fn greedy_arg_three_functions_middle_ends_with_call() {
let prog = parse_str("f xs:n>n;len xs g y:n>n;*y 2 h z:n>n;+z 1");
assert_eq!(prog.declarations.len(), 3, "expected 3 declarations");
let Decl::Function { name, .. } = &prog.declarations[0] else {
panic!("expected function f")
};
assert_eq!(name, "f");
let Decl::Function { name, .. } = &prog.declarations[1] else {
panic!("expected function g")
};
assert_eq!(name, "g");
let Decl::Function { name, .. } = &prog.declarations[2] else {
panic!("expected function h")
};
assert_eq!(name, "h");
}
/// A function call with multiple valid args must still get all of them when the
/// tokens after the args are NOT a declaration boundary.
#[test]
fn greedy_arg_still_collects_multiple_args_within_single_function() {
// `tot p q r` with three numeric args should still parse as Call(tot, [1, 2, 3])
let prog = parse_str("f>n;tot 1 2 3");
assert_eq!(prog.declarations.len(), 1);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::Call { function, args, .. }) = &body[0].node else {
panic!("expected Call(tot, [1,2,3])")
};
assert_eq!(function, "tot");
assert_eq!(args.len(), 3);
}
#[test]
fn parse_type_is_pattern_in_match() {
let prog = parse_str(r#"f x:t>t;?x{n v:"num";t v:v;_:"other"}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert_eq!(arms.len(), 3);
assert!(
matches!(&arms[0].pattern, Pattern::TypeIs { ty: Type::Number, binding } if binding == "v"),
"arm0: {:?}",
arms[0].pattern
);
assert!(
matches!(&arms[1].pattern, Pattern::TypeIs { ty: Type::Text, binding } if binding == "v"),
"arm1: {:?}",
arms[1].pattern
);
assert!(
matches!(&arms[2].pattern, Pattern::Wildcard),
"arm2: {:?}",
arms[2].pattern
);
}
// --- use declaration ---
#[test]
fn parse_use_basic() {
let prog = parse_str(r#"use "lib.ilo""#);
let Decl::Use { path, only, .. } = &prog.declarations[0] else {
panic!("expected Use")
};
assert_eq!(path, "lib.ilo");
assert!(only.is_none());
}
#[test]
fn parse_use_with_scoped_imports() {
let prog = parse_str(r#"use "lib.ilo" [foo bar]"#);
let Decl::Use { path, only, .. } = &prog.declarations[0] else {
panic!("expected Use")
};
assert_eq!(path, "lib.ilo");
let names = only.as_ref().unwrap();
assert_eq!(names, &["foo", "bar"]);
}
#[test]
fn parse_use_missing_path_error() {
let (_, errors) = parse_str_errors("use 42");
assert!(!errors.is_empty());
assert!(
errors.iter().any(|e| e.code == "ILO-P016"),
"got: {:?}",
errors
);
}
#[test]
fn parse_use_empty_bracket_list_error() {
let (_, errors) = parse_str_errors(r#"use "lib.ilo" []"#);
assert!(!errors.is_empty());
assert!(
errors
.iter()
.any(|e| e.code == "ILO-P016" && e.message.contains("must not be empty")),
"got: {:?}",
errors
);
}
// --- alias declaration ---
#[test]
fn parse_alias_basic() {
let prog = parse_str("alias mynum n");
let Decl::Alias { name, target, .. } = &prog.declarations[0] else {
panic!("expected Alias")
};
assert_eq!(name, "mynum");
assert!(matches!(target, Type::Number));
}
#[test]
fn parse_alias_complex_type() {
let prog = parse_str("alias res R n t");
let Decl::Alias { name, target, .. } = &prog.declarations[0] else {
panic!("expected Alias")
};
assert_eq!(name, "res");
assert!(matches!(target, Type::Result(_, _)));
}
// --- tool retry option ---
#[test]
fn parse_tool_retry_option() {
let prog = parse_str(r#"tool fetch"Get a URL" url:t>R t t retry:3"#);
let Decl::Tool {
name,
retry,
timeout,
..
} = &prog.declarations[0]
else {
panic!("expected Tool")
};
assert_eq!(name, "fetch");
assert_eq!(*retry, Some(3.0));
assert!(timeout.is_none());
}
#[test]
fn parse_tool_timeout_and_retry() {
let prog = parse_str(r#"tool fetch"Get a URL" url:t>R t t timeout:5,retry:3"#);
let Decl::Tool { timeout, retry, .. } = &prog.declarations[0] else {
panic!("expected Tool")
};
assert_eq!(*timeout, Some(5.0));
assert_eq!(*retry, Some(3.0));
}
// --- nil coalesce ---
#[test]
fn parse_nil_coalesce_basic() {
let prog = parse_str("f x:n>n;x??99");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::NilCoalesce { default, .. }) = &body[0].node else {
panic!("expected NilCoalesce")
};
let Expr::Literal(Literal::Number(n)) = default.as_ref() else {
panic!("expected 99")
};
assert_eq!(*n, 99.0);
}
// ---- Reserved words as identifiers (expect_ident error paths, lines 80-114) ----
#[test]
fn reserved_word_if_as_identifier_errors_with_hint() {
// `if` appearing where an identifier is expected (e.g. as a function name
// via the Token::KwIf path in expect_ident) — exercise ILO-P011 with hint.
// We use raw tokens so the keyword token actually reaches expect_ident inside
// parse_type_decl (which calls expect_ident for the type name).
let tokens = vec![
(Token::Type, Span::UNKNOWN),
(Token::KwIf, Span::UNKNOWN),
(Token::LBrace, Span::UNKNOWN),
(Token::RBrace, Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P011")
.expect("expected ILO-P011");
assert!(
e.message.contains("`if` is a reserved word"),
"message: {}",
e.message
);
let hint = e.hint.as_ref().expect("expected hint");
assert!(
hint.contains("cond"),
"hint should mention cond syntax, got: {}",
hint
);
}
#[test]
fn reserved_word_return_as_identifier_errors_with_hint() {
let tokens = vec![
(Token::Type, Span::UNKNOWN),
(Token::KwReturn, Span::UNKNOWN),
(Token::LBrace, Span::UNKNOWN),
(Token::RBrace, Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P011")
.expect("expected ILO-P011");
assert!(
e.message.contains("`return` is a reserved word"),
"message: {}",
e.message
);
let hint = e.hint.as_ref().expect("expected hint");
assert!(
hint.contains("ret"),
"hint should mention `ret`, got: {}",
hint
);
}
#[test]
fn reserved_word_let_as_identifier_errors_with_hint() {
let tokens = vec![
(Token::Type, Span::UNKNOWN),
(Token::KwLet, Span::UNKNOWN),
(Token::LBrace, Span::UNKNOWN),
(Token::RBrace, Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P011")
.expect("expected ILO-P011");
assert!(
e.message.contains("`let` is a reserved word"),
"message: {}",
e.message
);
let hint = e.hint.as_ref().expect("expected hint");
assert!(
hint.contains("name=expr") || hint.contains("bindings"),
"hint: {}",
hint
);
}
#[test]
fn reserved_word_fn_as_identifier_errors_with_hint() {
let tokens = vec![
(Token::Type, Span::UNKNOWN),
(Token::KwFn, Span::UNKNOWN),
(Token::LBrace, Span::UNKNOWN),
(Token::RBrace, Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P011")
.expect("expected ILO-P011");
assert!(
e.message.contains("`fn` is a reserved word"),
"message: {}",
e.message
);
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("name params>return"), "hint: {}", hint);
}
#[test]
fn reserved_word_def_as_identifier_errors_with_hint() {
let tokens = vec![
(Token::Type, Span::UNKNOWN),
(Token::KwDef, Span::UNKNOWN),
(Token::LBrace, Span::UNKNOWN),
(Token::RBrace, Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P011")
.expect("expected ILO-P011");
assert!(
e.message.contains("`def` is a reserved word"),
"message: {}",
e.message
);
}
#[test]
fn reserved_word_var_as_identifier_errors_with_hint() {
let tokens = vec![
(Token::Type, Span::UNKNOWN),
(Token::KwVar, Span::UNKNOWN),
(Token::LBrace, Span::UNKNOWN),
(Token::RBrace, Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P011")
.expect("expected ILO-P011");
assert!(
e.message.contains("`var` is a reserved word"),
"message: {}",
e.message
);
let hint = e.hint.as_ref().expect("expected hint");
assert!(
hint.contains("name=expr") || hint.contains("bindings"),
"hint: {}",
hint
);
}
#[test]
fn reserved_word_const_as_identifier_errors_with_hint() {
let tokens = vec![
(Token::Type, Span::UNKNOWN),
(Token::KwConst, Span::UNKNOWN),
(Token::LBrace, Span::UNKNOWN),
(Token::RBrace, Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P011")
.expect("expected ILO-P011");
assert!(
e.message.contains("`const` is a reserved word"),
"message: {}",
e.message
);
let hint = e.hint.as_ref().expect("expected hint");
assert!(
hint.contains("name=expr") || hint.contains("bindings"),
"hint: {}",
hint
);
}
// ---- Foreign syntax hints in parse_decl (lines 246-269) ----
#[test]
fn foreign_syntax_fn_keyword_at_decl_level_gets_hint() {
// `fn` token at declaration level triggers the Token::KwFn arm in parse_decl
let tokens = vec![
(Token::KwFn, Span::UNKNOWN),
(Token::Ident("foo".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint on fn at decl level");
assert!(hint.contains("ilo function syntax"), "hint: {}", hint);
}
#[test]
fn foreign_syntax_def_keyword_at_decl_level_gets_hint() {
let tokens = vec![
(Token::KwDef, Span::UNKNOWN),
(Token::Ident("foo".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("ilo function syntax"), "hint: {}", hint);
}
#[test]
fn foreign_syntax_let_keyword_at_decl_level_gets_hint() {
let tokens = vec![
(Token::KwLet, Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("assignment syntax"), "hint: {}", hint);
}
#[test]
fn foreign_syntax_var_keyword_at_decl_level_gets_hint() {
let tokens = vec![
(Token::KwVar, Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("assignment syntax"), "hint: {}", hint);
}
#[test]
fn foreign_syntax_const_keyword_at_decl_level_gets_hint() {
let tokens = vec![
(Token::KwConst, Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("assignment syntax"), "hint: {}", hint);
}
#[test]
fn foreign_syntax_return_keyword_at_decl_level_gets_hint() {
let tokens = vec![
(Token::KwReturn, Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("return value"), "hint: {}", hint);
}
#[test]
fn foreign_syntax_if_keyword_at_decl_level_gets_hint() {
let tokens = vec![
(Token::KwIf, Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint");
assert!(
hint.contains("match") || hint.contains("conditionals"),
"hint: {}",
hint
);
}
// ---- Foreign syntax hints from Ident("let" etc.) in parse_decl (lines 242-257) ----
#[test]
fn foreign_ident_let_at_decl_level_gets_hint() {
// "let" as an Ident token (not a keyword) triggers the hint branch in parse_decl
let (_, errors) = parse_str_errors("let x = 5");
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("assignment syntax"), "hint: {}", hint);
}
#[test]
fn foreign_ident_return_at_decl_level_gets_hint() {
let (_, errors) = parse_str_errors("return x");
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("return value"), "hint: {}", hint);
}
#[test]
fn foreign_ident_if_at_decl_level_gets_hint() {
let (_, errors) = parse_str_errors("if x > 0 {}");
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("match"), "hint: {}", hint);
}
#[test]
fn foreign_ident_fn_at_decl_level_gets_hint() {
let (_, errors) = parse_str_errors("fn foo() {}");
assert!(!errors.is_empty(), "expected parse error");
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("ilo function syntax"), "hint: {}", hint);
}
// ---- Type parsing edge cases (lines 484-515) ----
#[test]
fn sum_type_requires_at_least_one_variant() {
// `S` with no variants before `>` should produce ILO-P010
// f x:S>n;x — `S` type has no variants (next token is `>` which stops variant collection)
let (_, errors) = parse_str_errors("f x:S>n;x");
assert!(!errors.is_empty(), "expected parse error for empty S type");
assert!(
errors
.iter()
.any(|e| e.code == "ILO-P010" || e.message.contains("S type requires")),
"expected ILO-P010, got: {:?}",
errors
);
}
#[test]
fn fn_type_requires_at_least_return_type() {
// `F` with no types at all should produce ILO-P009
// f x:F>n;x — `F` type immediately followed by `>` (not a valid type start)
let (_, errors) = parse_str_errors("f x:F>n;x");
assert!(!errors.is_empty(), "expected parse error for empty F type");
assert!(
errors
.iter()
.any(|e| e.code == "ILO-P009" || e.message.contains("F type requires")),
"expected ILO-P009, got: {:?}",
errors
);
}
// ---- can_start_type() coverage — type prefixes in param lists (lines 534-541) ----
#[test]
fn nil_type_underscore_in_param() {
// `_` starts a Nil type
let prog = parse_str("f x:_>_;x");
let Decl::Function {
params,
return_type,
..
} = &prog.declarations[0]
else {
panic!("expected function")
};
assert_eq!(params[0].ty, Type::Any);
assert_eq!(*return_type, Type::Any);
}
#[test]
fn optional_type_in_param() {
// `O t` — OptType token `O` starts an optional type
let prog = parse_str("f x:O t>O t;x");
let Decl::Function {
params,
return_type,
..
} = &prog.declarations[0]
else {
panic!("expected function")
};
assert!(matches!(params[0].ty, Type::Optional(_)));
assert!(matches!(*return_type, Type::Optional(_)));
}
#[test]
fn list_type_in_param() {
// `L n` — ListType starts a list type
let prog = parse_str("f x:L n>L n;x");
let Decl::Function {
params,
return_type,
..
} = &prog.declarations[0]
else {
panic!("expected function")
};
assert!(matches!(¶ms[0].ty, Type::List(inner) if **inner == Type::Number));
assert!(matches!(return_type, Type::List(inner) if **inner == Type::Number));
}
#[test]
fn map_type_in_param() {
// `M t n` — MapType starts a map type
let prog = parse_str("f x:M t n>M t n;x");
let Decl::Function {
params,
return_type,
..
} = &prog.declarations[0]
else {
panic!("expected function")
};
assert!(matches!(¶ms[0].ty, Type::Map(_, _)));
assert!(matches!(return_type, Type::Map(_, _)));
}
#[test]
fn result_type_in_param() {
// `R t t` — ResultType starts a result type
let prog = parse_str("f x:R t t>R t t;x");
let Decl::Function {
params,
return_type,
..
} = &prog.declarations[0]
else {
panic!("expected function")
};
assert!(matches!(¶ms[0].ty, Type::Result(_, _)));
assert!(matches!(return_type, Type::Result(_, _)));
}
#[test]
fn sum_type_in_param() {
// `S ok err` — SumType starts a sum type with variants
let prog = parse_str("f x:S ok err>S ok err;x");
let Decl::Function {
params,
return_type,
..
} = &prog.declarations[0]
else {
panic!("expected function")
};
assert!(matches!(¶ms[0].ty, Type::Sum(variants) if variants.len() == 2));
assert!(matches!(return_type, Type::Sum(variants) if variants.len() == 2));
}
#[test]
fn fn_type_in_param() {
// `F n n` — FnType starts a function type (param: n, return: n)
let prog = parse_str("f x:F n n>F n n;x");
let Decl::Function {
params,
return_type,
..
} = &prog.declarations[0]
else {
panic!("expected function")
};
// F n n → Fn([Number], Number)
assert!(matches!(¶ms[0].ty, Type::Fn(param_types, _) if param_types.len() == 1));
assert!(matches!(return_type, Type::Fn(param_types, _) if param_types.len() == 1));
}
// ---- Match arm with type-annotated (TypeIs) patterns ----
#[test]
fn match_arm_multiple_type_is_patterns() {
// ?x{n v:v;t v:v;b v:v} — three TypeIs arms each binding a different type
let prog = parse_str(r#"f x:t>t;?x{n v:"num";t v:v;b v:"bool"}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert_eq!(arms.len(), 3, "expected 3 arms");
assert!(
matches!(&arms[0].pattern, Pattern::TypeIs { ty: Type::Number, binding } if binding == "v")
);
assert!(
matches!(&arms[1].pattern, Pattern::TypeIs { ty: Type::Text, binding } if binding == "v")
);
assert!(
matches!(&arms[2].pattern, Pattern::TypeIs { ty: Type::Bool, binding } if binding == "v")
);
}
#[test]
fn match_arm_type_is_with_wildcard_binding() {
// n _: pattern with wildcard binding
let prog = parse_str(r#"f x:t>t;?x{n _:"num";_:"other"}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert_eq!(arms.len(), 2);
assert!(
matches!(&arms[0].pattern, Pattern::TypeIs { ty: Type::Number, binding } if binding == "_")
);
assert!(matches!(&arms[1].pattern, Pattern::Wildcard));
}
// ---- use statement error paths ----
#[test]
fn use_missing_path_eof_error() {
// `use` followed by EOF — expects a string path
let (_, errors) = parse_str_errors("use");
assert!(!errors.is_empty(), "expected parse error");
assert!(
errors
.iter()
.any(|e| e.code == "ILO-P016" || e.message.contains("expected a string path")),
"expected ILO-P016, got: {:?}",
errors
);
}
#[test]
fn use_unclosed_bracket_list_error() {
// `use "file.ilo" [foo` — unclosed `[` without closing `]`
let (_, errors) = parse_str_errors(r#"use "file.ilo" [foo"#);
assert!(!errors.is_empty(), "expected parse error for unclosed [");
assert!(
errors
.iter()
.any(|e| e.code == "ILO-P016" || e.message.contains("unclosed")),
"expected ILO-P016 for unclosed bracket, got: {:?}",
errors
);
}
#[test]
fn use_bracket_list_with_reserved_word_errors() {
// `use "file.ilo" [if]` — `if` inside `[...]` triggers expect_ident → ILO-P011
let tokens = vec![
(Token::Use, Span::UNKNOWN),
(Token::Text("file.ilo".into()), Span::UNKNOWN),
(Token::LBracket, Span::UNKNOWN),
(Token::KwIf, Span::UNKNOWN),
(Token::RBracket, Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty(), "expected parse error");
assert!(
errors.iter().any(|e| e.code == "ILO-P011"),
"expected ILO-P011 for reserved word in use list, got: {:?}",
errors
);
}
// ── Coverage: L246/L248/L250 — "return"/"if" hints at decl level ──────────
#[test]
fn parse_return_at_decl_level_gives_hint() {
let (_, errors) = parse_str_errors("return x");
assert!(!errors.is_empty(), "expected parse error");
let hint_found = errors
.iter()
.any(|e| e.hint.as_deref().unwrap_or("").contains("return value"));
assert!(
hint_found,
"expected 'return value' hint, got: {:?}",
errors
);
}
#[test]
fn parse_if_at_decl_level_gives_hint() {
let (_, errors) = parse_str_errors("if x > 0");
assert!(!errors.is_empty(), "expected parse error");
let hint_found = errors
.iter()
.any(|e| e.hint.as_deref().unwrap_or("").contains("match"));
assert!(
hint_found,
"expected 'match' hint for 'if', got: {:?}",
errors
);
}
// ── Coverage: L375 — tool decl `_ => break` after non-timeout/retry tok ──
#[test]
fn parse_tool_decl_stops_at_non_option_token() {
// tool with no timeout/retry: the loop hits `_ => break` immediately
let prog = parse_str(r#"tool ping "ping server" url:t>t"#);
let Decl::Tool { name, .. } = &prog.declarations[0] else {
panic!("expected tool decl")
};
assert_eq!(name, "ping");
}
// ── Coverage: L484 — sum type variant loop breaks on `ident:` ─────────────
#[test]
fn parse_sum_type_with_trailing_param_breaks_correctly() {
// `S foo bar` where variants are foo, bar — but we need a function that
// uses an S type as param and has `ident:` after the variants.
// `f x:S foo bar>t;"ok"` → type `S foo bar` parsed, loop breaks at `>`
let prog = parse_str(r#"f x:S foo bar>t;"ok""#);
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 1);
let Type::Sum(variants) = ¶ms[0].ty else {
panic!("expected Sum type")
};
assert_eq!(variants, &["foo".to_string(), "bar".to_string()]);
}
// ── Coverage: L510 — F type break when `ident:` follows ──────────────────
#[test]
fn parse_fn_type_in_param_breaks_at_colon() {
// `f cb:F n t x:n>n;x` — cb has type F n t (fn n>t), loop breaks at `x:`
let prog = parse_str(r#"f cb:F n t x:n>n;x"#);
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 2);
let Type::Fn(arg_types, ret) = ¶ms[0].ty else {
panic!("expected Fn type")
};
assert_eq!(arg_types.len(), 1);
assert!(matches!(**ret, Type::Text));
}
// ── Coverage: L534-540 — can_start_type() for special type tokens ─────────
#[test]
fn parse_underscore_type_in_param() {
// `_` as a type token — parse_type returns Type::Any (underscore = any/unknown type)
// Trigger via `f x:_>n;0`
let (_, errors) = parse_str_errors("f x:_>n;0");
// Whether it succeeds or errors, the Underscore branch of can_start_type was hit
// Just ensure no panic
let _ = errors;
}
#[test]
fn parse_opt_type_in_param() {
// `O t` = optional text type
let prog = parse_str("f x:O t>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 1);
assert!(matches!(¶ms[0].ty, Type::Optional(_)));
}
#[test]
fn parse_list_type_in_param() {
let prog = parse_str("f xs:L n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(matches!(¶ms[0].ty, Type::List(_)));
}
#[test]
fn parse_map_type_in_param() {
let prog = parse_str("f m:M t n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(matches!(¶ms[0].ty, Type::Map(_, _)));
}
#[test]
fn parse_result_type_in_param() {
let prog = parse_str("f r:R n t>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(matches!(¶ms[0].ty, Type::Result(_, _)));
}
// ── Coverage: L677 — is_guard_eligible_condition `_ => return false` ─────
#[test]
fn guard_with_non_eligible_condition_parses_as_stmt() {
// A literal in condition position: `42{body}` — not guard-eligible by ident
// The condition is a number literal → `_ => return false` in is_guard_eligible_condition
let prog = parse_str(r#"f x:n>n;x{x}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(!body.is_empty());
// x is an ident which IS eligible — need a pure literal
// Instead test `1{x}` which would parse as guard with Literal condition
let _ = body;
}
#[test]
fn guard_with_literal_condition_hits_non_eligible_branch() {
// `f x:n>n; 1{x}` — literal `1` is not guard-eligible → parsed as expr stmt
// then `{x}` fails or is next decl — tests the `_ => return false` path
let (prog, _errors) = parse_str_errors(r#"f x:n>n; 1{x}"#);
// Just ensure no panic — the literal number triggers the wildcard arm
let _ = prog;
}
// ── Coverage: L806/L811 — pattern lookahead short-circuit ────────────────
#[test]
fn match_with_type_pattern_at_end_of_tokens() {
// A match where the type pattern lookahead (after_semi + 2) might exceed
// token length — create a minimal match that exercises the bounds check
let prog = parse_str(r#"f x:n>t;?x{~v:"ok";^_:"err"}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(!body.is_empty());
}
// ── Coverage: L928 — negated guard with else body ─────────────────────────
#[test]
fn parse_negated_guard_with_else_body() {
// `!cond{then}{else}` — negated guard with an else branch
let prog = parse_str(r#"f x:n>n;!>x 0{-1}{1}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(!body.is_empty());
let Stmt::Guard {
negated, else_body, ..
} = &body[0].node
else {
panic!("expected Guard")
};
assert!(negated, "expected negated guard");
assert!(else_body.is_some(), "expected else body");
}
// ── Coverage: L964 — regular guard with else body ─────────────────────────
#[test]
fn parse_guard_with_else_body() {
// `cond{then}{else}` — guard with an else branch
let prog = parse_str(r#"f x:n>n;>x 0{1}{-1}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(!body.is_empty());
let Stmt::Guard {
negated, else_body, ..
} = &body[0].node
else {
panic!("expected Guard")
};
assert!(!negated, "expected non-negated guard");
assert!(else_body.is_some(), "expected else body");
}
// ── Coverage: L975 — braceless negated guard ──────────────────────────────
#[test]
fn parse_braceless_negated_guard() {
// `!>x 0 99` — negated braceless guard: if NOT (x > 0), return 99
let prog = parse_str(r#"f x:n>n;!>x 0 99;x"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(body.len() >= 2);
let Stmt::Guard { negated, .. } = &body[0].node else {
panic!("expected Guard")
};
assert!(negated);
}
// ── Coverage: L1080-1085 — pipe with `!` unwrap ───────────────────────────
#[test]
fn parse_pipe_with_bang_unwrap() {
// `expr >> func!` — pipe with adjacent `!` triggers unwrap path
let prog = parse_str(r#"dbl x:n>n;*x 2 f s:t>n;s>>num!"#);
let Some(Decl::Function { body, .. }) = prog.declarations.last() else {
panic!("expected function")
};
assert!(!body.is_empty());
let Stmt::Expr(Expr::Call { unwrap, .. }) = &body[0].node else {
panic!("expected Call expr")
};
assert!(unwrap.is_propagate(), "expected unwrap=true on piped call");
}
// ── Coverage: L1413 — Token::Dollar in parse_operand ─────────────────────
#[test]
fn parse_dollar_as_operand_in_let() {
// `r = $url` where `$url` appears in operand position inside a let binding
let prog = parse_str(r#"f url:t>R t t;r=$url;r"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(!body.is_empty());
let Stmt::Let { value, .. } = &body[0].node else {
panic!("expected let")
};
let Expr::Call {
function, unwrap, ..
} = value
else {
panic!("expected get call")
};
assert_eq!(function, "get");
assert!(!unwrap.is_any());
}
// ── Coverage: L484 — SumType loop break on param name ────────────────────
#[test]
fn parse_sum_type_stops_at_named_param() {
// `S a` collects "a" as variant; `n:n` triggers break at line 484 (ident+colon).
let prog = parse_str("f x:S a n:n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 2);
let Type::Sum(variants) = ¶ms[0].ty else {
panic!("expected Sum type")
};
assert_eq!(variants, &["a"]);
assert_eq!(params[1].name, "n");
}
// ── Coverage: L510 — FnType loop break on param name ─────────────────────
#[test]
fn parse_fn_type_stops_at_named_param() {
// Inside `F n`, after consuming the first `n`, the second `n:` is a named
// param (primitive ident + colon) → can_start_type returns true but
// the ident+colon guard at line 507-510 breaks the loop.
let prog = parse_str("f x:F n n:n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 2);
let Type::Fn(param_types, ret) = ¶ms[0].ty else {
panic!("expected Fn type")
};
assert!(param_types.is_empty(), "F n should have no param types");
assert!(matches!(ret.as_ref(), Type::Number));
}
// ── Coverage: L534-L540 — can_start_type branches inside FnType ──────────
#[test]
fn parse_fn_type_with_underscore_param() {
// `F _ n` — Underscore arg type → can_start_type line 534
let prog = parse_str("f cb:F _ n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 1);
assert!(matches!(¶ms[0].ty, Type::Fn(..)));
}
#[test]
fn parse_fn_type_with_opt_param() {
// `F O n n` — OptType arg → can_start_type line 535
let prog = parse_str("f cb:F O n n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 1);
assert!(matches!(¶ms[0].ty, Type::Fn(..)));
}
#[test]
fn parse_fn_type_with_list_param() {
// `F L n n` — ListType arg → can_start_type line 536
let prog = parse_str("f cb:F L n n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 1);
assert!(matches!(¶ms[0].ty, Type::Fn(..)));
}
#[test]
fn parse_fn_type_with_map_param() {
// `F M t n n` — MapType arg → can_start_type line 537
let prog = parse_str("f cb:F M t n n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 1);
assert!(matches!(¶ms[0].ty, Type::Fn(..)));
}
#[test]
fn parse_fn_type_with_result_param() {
// `F R n t n` — ResultType arg → can_start_type line 538
let prog = parse_str("f cb:F R n t n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 1);
assert!(matches!(¶ms[0].ty, Type::Fn(..)));
}
#[test]
fn parse_fn_type_with_sum_param() {
// `F S a n` — SumType arg → can_start_type line 539
// Sum consumes all idents not followed by colon; "a" and "n" are both variants.
let prog = parse_str("f cb:F S a n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 1);
assert!(matches!(¶ms[0].ty, Type::Fn(..)));
}
#[test]
fn parse_fn_type_with_nested_fn_param() {
// `F F n n` — nested FnType arg → can_start_type line 540
let prog = parse_str("f cb:F F n n>n;0");
let Decl::Function { params, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert_eq!(params.len(), 1);
assert!(matches!(¶ms[0].ty, Type::Fn(..)));
}
// ── Coverage: L677 — is_destructure_pattern returns false ────────────────
#[test]
fn parse_non_ident_inside_brace_is_not_destructure() {
// `{42}` at statement start: is_destructure_pattern hits `_ => return false`
// at line 677 (Number is not Ident/Semi/RBrace). Falls to expr parse → error.
let (_prog, errs) = parse_str_errors("f x:n>n;{42}=x");
assert!(
!errs.is_empty(),
"expected parse error for non-destructure brace"
);
}
// ── Coverage: L806 — TypeIs lookahead in semi_starts_new_arm (true path) ──
#[test]
fn parse_match_type_is_two_arms() {
// After parsing first arm body, `;n z:` triggers semi_starts_new_arm TypeIs
// lookahead (after_semi+2 < len, and tokens match ident+colon → line 806 true).
let prog = parse_str(r#"f x:n>n;?x{n y: +y 1; n z: *z 2}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(!body.is_empty());
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected Match")
};
assert_eq!(arms.len(), 2);
}
// ── Coverage: L811 — TypeIs lookahead in semi_starts_new_arm (false path) ─
#[test]
fn parse_match_type_is_incomplete_at_eof() {
// `;n` at end of token stream — TypeIs arm: after_semi+2 >= len → line 811 false.
let (_prog, errs) = parse_str_errors("f x:n>n;?x{n y:1;n");
assert!(
!errs.is_empty(),
"expected parse error for incomplete TypeIs arm"
);
}
// ── Coverage: L1413 — Token::Dollar in parse_operand (as call argument) ───
#[test]
fn parse_dollar_as_function_argument() {
// `foo $url` — Dollar appears as an argument in parse_operand (line 1413),
// distinct from `$url` at statement level which uses parse_expr_inner (line 1118).
let prog = parse_str(r#"f url:t>t;fetch $url"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(!body.is_empty());
let Stmt::Expr(Expr::Call { function, args, .. }) = &body[0].node else {
panic!("expected Call stmt")
};
assert_eq!(function, "fetch");
assert_eq!(args.len(), 1);
let Expr::Call {
function: inner_fn, ..
} = &args[0]
else {
panic!("expected get call as arg")
};
assert_eq!(inner_fn, "get");
}
// ── Coverage: L798 — literal pattern lookahead when literal is last token ──
#[test]
fn match_literal_pattern_at_end_of_tokens() {
// Incomplete match where literal pattern appears as the last token after `;`.
// Exercises the Number/Text/True/False arm of is_match_arm_pattern_lookahead
// when `after_semi + 1 >= self.tokens.len()` → condition at L798 is false.
// parse_str_errors is used since the input is intentionally incomplete.
let (prog, _errors) = parse_str_errors(r#"f x:n>t;?x{1:"one";2"#);
let _ = prog; // just ensure no panic; parser recovers from incomplete input
}
// ── Coverage: L246/L248/L250 — Ident("let")/Ident("return")/Ident("if") at decl level ──
// The lexer normally produces keyword tokens for these, so we must use raw tokens
// to exercise the Ident string-matching hints in parse_decl.
#[test]
fn foreign_ident_let_raw_token_hint() {
// Token::Ident("let") triggers the "let"|"var"|"const" arm at L245-246
let tokens = vec![
(Token::Ident("let".into()), Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty());
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
assert!(e.hint.as_ref().unwrap().contains("assignment syntax"));
}
#[test]
fn foreign_ident_var_raw_token_hint() {
let tokens = vec![
(Token::Ident("var".into()), Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty());
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
assert!(e.hint.as_ref().unwrap().contains("assignment syntax"));
}
#[test]
fn foreign_ident_const_raw_token_hint() {
let tokens = vec![
(Token::Ident("const".into()), Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty());
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
assert!(e.hint.as_ref().unwrap().contains("assignment syntax"));
}
#[test]
fn foreign_ident_return_raw_token_hint() {
// Token::Ident("return") triggers the "return" arm at L247-248
let tokens = vec![
(Token::Ident("return".into()), Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty());
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
assert!(e.hint.as_ref().unwrap().contains("return value"));
}
#[test]
fn foreign_ident_if_raw_token_hint() {
// Token::Ident("if") triggers the "if" arm at L249-250
let tokens = vec![
(Token::Ident("if".into()), Span::UNKNOWN),
(Token::Ident("x".into()), Span::UNKNOWN),
];
let (_, errors) = parse(tokens);
assert!(!errors.is_empty());
let e = errors
.iter()
.find(|e| e.code == "ILO-P001")
.expect("expected ILO-P001");
assert!(e.hint.as_ref().unwrap().contains("match"));
}
// ── Coverage: L880-881 — nil literal pattern in match arm ──────────────────
#[test]
fn parse_match_nil_literal_pattern() {
// `?x{nil:0;_:1}` — nil token as a match pattern (Pattern::Literal(Literal::Nil))
let prog = parse_str("f x:n>n;?x{nil:0;_:1}");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert!(matches!(&arms[0].pattern, Pattern::Literal(Literal::Nil)));
}
// ── Coverage: L975 — parse_expr_or_guard: guard with else body ─────────────
#[test]
fn parse_expr_or_guard_with_else_body() {
// Expression followed by {then}{else} triggers L974-975 in parse_expr_or_guard
let source = r#"f x:n>n;=x 1{10}{20}"#;
let prog = parse_str(source);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Guard { else_body, .. } = &body[0].node else {
panic!("expected guard")
};
assert!(else_body.is_some(), "expected else body");
}
// ── Coverage: L986 — braceless guard from parse_expr_or_guard ──────────────
#[test]
fn parse_expr_or_guard_braceless() {
// A comparison expr followed by an operand that can start (not brace) exercises L985-986
// `=x 0 99;x` — equals is guard-eligible, 99 is the braceless body
let prog = parse_str("f x:n>n;=x 0 99;x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(body.len() >= 2);
assert!(
matches!(&body[0].node, Stmt::Guard { .. }),
"expected braceless guard, got {:?}",
body[0]
);
}
// ── Coverage: L1118-L1126 — infix operator binding powers ──────────────────
#[test]
fn infix_or_operator() {
let prog = parse_str("f a:b b:b>b;a | b");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp { op: BinOp::Or, .. }) = &body[0].node else {
panic!("expected infix or")
};
}
#[test]
fn infix_equals_operator() {
// `=` at statement level is a let-binding, so wrap in parens to force infix parsing
let prog = parse_str("f a:n b:n>b;(a == b)");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Equals, ..
}) = &body[0].node
else {
panic!("expected infix equals, got {:?}", body[0])
};
}
#[test]
fn infix_not_equals_operator() {
let prog = parse_str("f a:n b:n>b;a != b");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::NotEquals,
..
}) = &body[0].node
else {
panic!("expected infix not-equals")
};
}
#[test]
fn infix_less_than_operator() {
let prog = parse_str("f a:n b:n>b;a < b");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::LessThan,
..
}) = &body[0].node
else {
panic!("expected infix less-than")
};
}
#[test]
fn infix_less_or_equal_operator() {
let prog = parse_str("f a:n b:n>b;a <= b");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::LessOrEqual,
..
}) = &body[0].node
else {
panic!("expected infix <=")
};
}
#[test]
fn infix_greater_or_equal_operator() {
let prog = parse_str("f a:n b:n>b;a >= b");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::GreaterOrEqual,
..
}) = &body[0].node
else {
panic!("expected infix >=")
};
}
#[test]
fn infix_append_operator() {
let prog = parse_str("f xs:L n x:n>L n;xs += x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!()
};
let Stmt::Expr(Expr::BinOp {
op: BinOp::Append, ..
}) = &body[0].node
else {
panic!("expected infix +=")
};
}
// ── Coverage: L1469-1477 — looks_like_prefix_binary with paren/bracket groups ──
#[test]
fn looks_like_prefix_with_paren_group() {
// `fac -(n) 1` — the `(n)` counts as one atom via the paren-group branch at L1467-1478
let prog = parse_str("fac n:n>n;r=fac -(n) 1;*n r");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Let {
value: Expr::Call { function, args, .. },
..
} = &body[0].node
else {
panic!("expected call")
};
assert_eq!(function, "fac");
assert_eq!(args.len(), 1);
}
#[test]
fn looks_like_prefix_with_bracket_group() {
// `foo -[1,2] 3` — the `[1,2]` counts as one atom via the bracket-group branch
let prog = parse_str("foo a:L n b:n>n;0 f x:n>n;r=foo -[1, 2] x;r");
let Decl::Function { body, .. } = &prog.declarations[1] else {
panic!("expected function")
};
let Stmt::Let {
value: Expr::Call { function, args, .. },
..
} = &body[0].node
else {
panic!("expected call")
};
assert_eq!(function, "foo");
assert_eq!(args.len(), 1);
}
// ── Coverage: L1591-1592 — nil literal in parse_operand ────────────────────
#[test]
fn parse_nil_literal_operand() {
// `nil` as an expression operand — exercises Token::Nil in parse_operand
let prog = parse_str("f>_;nil");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(matches!(
&body[0].node,
Stmt::Expr(Expr::Literal(Literal::Nil))
));
}
// ── Equality vs assignment disambiguation ──────────────────────────────────
#[test]
fn eq_prefix_is_equality_check() {
// `=x y` in expression context is prefix equality: BinOp(Equals, x, y)
let prog = parse_str("f x:n y:n>b;=x y");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected fn")
};
let Stmt::Expr(Expr::BinOp { op, .. }) = &body[0].node else {
panic!("expected equality binop, got {:?}", body[0].node)
};
assert_eq!(*op, BinOp::Equals);
}
#[test]
fn eq_after_ident_is_let_binding() {
// `x=1` inside a function body is a let binding
let prog = parse_str("f>n;x=1;x");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected fn")
};
let Stmt::Let { name, .. } = &body[0].node else {
panic!("expected let binding, got {:?}", body[0].node)
};
assert_eq!(name, "x");
}
#[test]
fn eq_double_equals_is_equality() {
// `==` lexes the same as `=` (both Token::Eq) — used in prefix as equality
let prog = parse_str("f x:n>b;==x 1");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected fn")
};
let Stmt::Expr(Expr::BinOp { op, .. }) = &body[0].node else {
panic!("expected equality binop, got {:?}", body[0].node)
};
assert_eq!(*op, BinOp::Equals);
}
#[test]
fn eq_infix_is_equality() {
// Infix `=` after a non-ident expression is equality, not assignment.
// `(+1 0)=0` — the parenthesised expr followed by `=` can't be let-binding.
let prog = parse_str("f x:n>b;r=+x 0;=r 0");
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected fn")
};
// Second statement: `=r 0` is prefix equality
let Stmt::Expr(Expr::BinOp {
op: BinOp::Equals, ..
}) = &body[1].node
else {
panic!("expected equality, got {:?}", body[1].node)
};
}
#[test]
fn eq_prefix_ternary_uses_equality() {
// `?=x 0 "zero" "nonzero"` — the `=` after `?` is prefix equality in a ternary
let prog = parse_str(r#"f x:n>t;?=x 0 "zero" "nonzero""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected fn")
};
let Stmt::Expr(Expr::Ternary { condition, .. }) = &body[0].node else {
panic!("expected ternary, got {:?}", body[0].node)
};
let Expr::BinOp { op, .. } = condition.as_ref() else {
panic!("expected equality condition, got {:?}", condition)
};
assert_eq!(*op, BinOp::Equals);
}
#[test]
fn eq_guard_with_equality_condition() {
// `=x 1{...}` — equality check as guard condition, not assignment
let prog = parse_str(r#"f x:n>t;=x 1{"one"};"other""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected fn")
};
let Stmt::Guard { condition, .. } = &body[0].node else {
panic!("expected guard, got {:?}", body[0].node)
};
let Expr::BinOp { op, .. } = condition else {
panic!("expected equality condition, got {:?}", condition)
};
assert_eq!(*op, BinOp::Equals);
}
// ── Coverage: L813 — TypeIs pattern lookahead bounds check ─────────────────
#[test]
fn type_is_pattern_bounds_check_in_semi_starts_new_arm() {
// Multi-arm match with TypeIs pattern: `;n v:` — after_semi+2 < tokens.len() is true
// and the matches! returns true because the tokens are (Ident("n"), Ident("v"), Colon)
let prog = parse_str(r#"f x:n>n;?x{n v:v;_:0}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert_eq!(arms.len(), 2);
assert!(matches!(
&arms[0].pattern,
Pattern::TypeIs {
ty: Type::Number,
..
}
));
}
// ── Coverage gap tests ──────────────────────────────────────────────
// L1048: Guard with else-body braces: `>=x 0{x}{0}` (two brace blocks)
#[test]
fn cov_guard_with_else_braces() {
let prog = parse_str(r#"f x:n>n;>=x 0{x}{0}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
match &body[0].node {
Stmt::Guard { else_body, .. } => {
assert!(else_body.is_some(), "should have else body");
}
other => panic!("expected Guard, got {:?}", other),
}
}
// L1059: Braceless guard — `>=x 0 x` (comparison as condition, single expression body)
#[test]
fn cov_braceless_guard() {
let prog = parse_str(r#"f x:n>n;>=x 0 x"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(matches!(&body[0].node, Stmt::Guard { .. }));
}
// L1243-1245: Err expression via Caret in list element context
#[test]
fn cov_err_expression() {
let prog = parse_str(r#"f>R n t;^"oops""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
match &body[0].node {
Stmt::Expr(Expr::Err(_)) => {}
other => panic!("expected Err expression, got {:?}", other),
}
}
// L1835: parse_tokens returning Err (parse errors)
#[test]
fn cov_parse_tokens_error() {
use crate::lexer::Token;
// An incomplete program that should produce parse errors
let tokens = vec![Token::Greater]; // just ">" — not a valid program
let result = super::parse_tokens(tokens);
assert!(
result.is_err(),
"incomplete tokens should produce parse error"
);
}
// L881: TypeIs pattern lookahead with 'b' type
#[test]
fn cov_type_is_bool_pattern() {
let prog = parse_str(r#"f x:n>n;?x{b v:1;_:0}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert!(matches!(
&arms[0].pattern,
Pattern::TypeIs { ty: Type::Bool, .. }
));
}
// L881: TypeIs pattern with 'l' (list) type
#[test]
fn cov_type_is_list_pattern() {
let prog = parse_str(r#"f x:n>n;?x{l v:1;_:0}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert!(matches!(
&arms[0].pattern,
Pattern::TypeIs {
ty: Type::List(_),
..
}
));
}
// Multiple braceless guards (cascading)
#[test]
fn cov_cascading_braceless_guards() {
let prog = parse_str(r#"cls sp:n>t;>=sp 1000 "gold";>=sp 500 "silver";"bronze""#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
assert!(body.len() >= 2, "should have multiple statements");
}
// Nil literal in match pattern
#[test]
fn cov_nil_literal_pattern() {
let prog = parse_str(r#"f x:n>n;?x{nil:0;_:1}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
assert!(matches!(&arms[0].pattern, Pattern::Literal(Literal::Nil)));
}
// parse_let single-brace desugar: v=cond{body} → Guard { condition, body: [Let{name,...}] }
// Covers lines 752-759 (the else branch after single brace block) and wrap_body_as_let (1851-1878)
#[test]
fn cov_parse_let_single_brace_guard() {
let prog = parse_str(r#"f x:n>n;v=>=x 0{42};v"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
// First stmt should be a Guard (desugared from v=cond{body})
assert!(
matches!(
&body[0].node,
Stmt::Guard {
negated: false,
else_body: None,
braceless: false,
..
}
),
"expected Guard from single-brace let desugar, got {:?}",
body[0].node
);
}
// wrap_body_as_let with empty body: v=cond{} → Guard { body: [Let{name, Nil}] }
// Covers wrap_body_as_let empty-body branch (line 1852-1856)
#[test]
fn cov_wrap_body_as_let_empty_body() {
let prog = parse_str(r#"f x:n>n;v=>=x 0{};v"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Guard {
body: guard_body, ..
} = &body[0].node
else {
panic!("expected Guard, got {:?}", body[0].node)
};
// The desugared body should be a single Let with Nil value
assert_eq!(guard_body.len(), 1);
assert!(
matches!(
&guard_body[0].node,
Stmt::Let {
value: Expr::Literal(Literal::Nil),
..
}
),
"expected Let{{Nil}} in guard body, got {:?}",
guard_body[0].node
);
}
// wrap_body_as_let where last stmt is NOT an Expr (it's a Let) — the non-Expr fallthrough
// Covers the `_ => { /* no-op */ }` arm in wrap_body_as_let (line 1871-1875)
#[test]
fn cov_wrap_body_as_let_non_expr_last() {
// body contains only a let stmt (w=1), so wrap_body_as_let's last stmt is Stmt::Let
let prog = parse_str(r#"f x:n>n;v=>=x 0{w=1};v"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Guard {
body: guard_body, ..
} = &body[0].node
else {
panic!("expected Guard, got {:?}", body[0].node)
};
// The inner let (w=1) should remain — non-Expr last stmt is left as-is
assert!(!guard_body.is_empty());
assert!(
matches!(&guard_body[0].node, Stmt::Let { name, .. } if name == "w"),
"expected inner Let{{w}} untouched, got {:?}",
guard_body[0].node
);
}
// parse_list_element with Caret/Err constructor inside list literal: [^"msg"]
// Covers lines 1279-1282 (Some(Token::Caret) branch in parse_list_element)
#[test]
fn cov_list_element_caret_err() {
let prog = parse_str(r#"f x:n>R n t;[^"bad"]"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::List(elems)) = &body[0].node else {
panic!("expected List expr, got {:?}", body[0].node)
};
assert_eq!(elems.len(), 1);
assert!(
matches!(&elems[0], Expr::Err(_)),
"expected Err element, got {:?}",
elems[0]
);
}
// body_to_expr with empty body → Expr::Literal(Nil)
// Covered via ternary desugar v=cond{}{} where both branches are empty
// Covers line 1839 (body.is_empty() early return in body_to_expr)
#[test]
fn cov_body_to_expr_empty() {
let prog = parse_str(r#"f x:n>n;v=>=x 0{}{};v"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
// v=cond{}{} desugars to Let { value: Ternary { then: Nil, else: Nil } }
let Stmt::Let { value, .. } = &body[0].node else {
panic!("expected Let, got {:?}", body[0].node)
};
assert!(
matches!(value, Expr::Ternary { then_expr, else_expr, .. }
if matches!(then_expr.as_ref(), Expr::Literal(Literal::Nil))
&& matches!(else_expr.as_ref(), Expr::Literal(Literal::Nil))
),
"expected Ternary{{Nil, Nil}}, got {:?}",
value
);
}
// body_to_expr where last stmt is NOT an Expr → falls back to Nil
// Covers line 1844 (_ => Expr::Literal(Literal::Nil) in body_to_expr)
#[test]
fn cov_body_to_expr_non_expr_last() {
// v=cond{w=1}{w=2} — each branch body's last stmt is a Let, not an Expr
let prog = parse_str(r#"f x:n>n;v=>=x 0{w=1}{w=2};v"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Let { value, .. } = &body[0].node else {
panic!("expected Let, got {:?}", body[0].node)
};
// Both branches have non-Expr last stmts → both arms become Nil
assert!(
matches!(value, Expr::Ternary { then_expr, else_expr, .. }
if matches!(then_expr.as_ref(), Expr::Literal(Literal::Nil))
&& matches!(else_expr.as_ref(), Expr::Literal(Literal::Nil))
),
"expected Ternary fallback to Nil for non-Expr branches, got {:?}",
value
);
}
// semi_starts_new_arm TypeIs branch: `;n v:` after an arm body → true (covers line 916 path)
// Also the false path: `;n 5` — TypeIs ident found but token after is not Ident/Underscore
#[test]
fn cov_semi_starts_new_arm_type_is() {
// Match with numeric arm, then a TypeIs arm — `;n v:v` should be seen as new arm start
let prog = parse_str(r#"f x:n>n;?x{1:x;n v:v;_:0}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
// Three arms: literal 1, TypeIs n, wildcard
assert_eq!(arms.len(), 3, "expected 3 match arms");
assert!(
matches!(
&arms[1].pattern,
Pattern::TypeIs {
ty: Type::Number,
..
}
),
"expected TypeIs Number arm, got {:?}",
arms[1].pattern
);
}
// semi_starts_new_arm TypeIs false path: `;n 5` — type ident followed by a number (not Ident/Underscore)
// Covers line 915 matches! returning false (the else branch in the `^0` annotation)
#[test]
fn cov_semi_starts_new_arm_type_is_false() {
// In this match, arm body has `x` then `;n` where `n` is used as a *variable ref*, not a type pattern.
// `?x{1:x;n;_:0}` — `;n` is followed by `;` (not Ident:Colon), so semi_starts_new_arm returns false
// for the TypeIs check, and `n` becomes a statement in the arm body.
let prog = parse_str(r#"f x:n>n;?x{1:x;n;_:0}"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Match { arms, .. } = &body[0].node else {
panic!("expected match")
};
// `;n;` — `n` is checked: token after_semi is `n` (TypeIs candidate), but token after that
// is `;` which is NOT Ident or Underscore → matches! returns false → `n` is a body stmt.
// So arm 0 (`1:`) gets body [x, n], arm 1 (`_:`) gets body [0].
assert!(arms.len() >= 2, "expected at least 2 arms");
}
// looks_like_prefix_binary with a simple paren group: e.g. `+ (x) 1`
// The `(x)` paren group is counted as one atom — covers line 1618-1637
#[test]
fn cov_looks_like_prefix_binary_paren_group() {
// `+ (x) 1` — paren group as first arg, then second arg → binary prefix op
let prog = parse_str(r#"f x:n>n;+(x) 1"#);
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
// Should parse as BinOp::Add with a paren-grouped first arg
assert!(
matches!(
&body[0].node,
Stmt::Expr(Expr::BinOp { op: BinOp::Add, .. })
),
"expected Add BinOp, got {:?}",
body[0].node
);
}
// looks_like_prefix_binary with NESTED parens: calling `dbl -((x)) 1`
// When parsing `dbl`'s args, the first token is `-` (infix-eligible), so
// looks_like_prefix_binary scans forward: `((x))` = one atom (with inner depth++ at line 1631)
// then `1` = second atom → returns true (is prefix binary, not infix).
#[test]
fn cov_looks_like_prefix_binary_nested_parens() {
// `dbl -((x)) 1` — `dbl` is called with `-((x))` and `1` as args
// The `((x))` paren group causes depth += 1 inside looks_like_prefix_binary
let prog = parse_str(r#"dbl x:n>n;*x 2 f y:n>n;dbl -((y)) 1"#);
let Decl::Function { body, .. } = &prog.declarations[1] else {
panic!("expected second function")
};
// Should parse as a call to dbl with args [-((y)), 1]... actually as Call{dbl, [BinOp{Sub,Ref(y),Lit(1)}]}
assert!(
matches!(&body[0].node, Stmt::Expr(Expr::Call { function, .. }) if function == "dbl"),
"expected Call to dbl, got {:?}",
body[0].node
);
}
// ── Coverage: parse_type LParen branch (nested generic types) ──────────
fn first_fn_return_debug(src: &str) -> String {
let prog = parse_str(src);
match &prog.declarations[0] {
Decl::Function { return_type, .. } => format!("{:?}", return_type),
_ => String::from("not-a-fn"),
}
}
fn first_fn_param_debug(src: &str) -> String {
let prog = parse_str(src);
match &prog.declarations[0] {
Decl::Function { params, .. } => format!("{:?}", params),
_ => String::from("not-a-fn"),
}
}
#[test]
fn parse_type_result_of_list() {
// `R (L n) t` — exercises LParen arm of parse_type around `L n`.
let s = first_fn_return_debug("f>R (L n) t;~[1,2,3]");
assert!(s.contains("Result"), "no Result: {s}");
assert!(s.contains("List"), "no List: {s}");
}
#[test]
fn parse_type_parens_around_atom_transparent() {
// `R (n) t` — single-token in parens unwraps to plain `n`.
let s = first_fn_return_debug("f>R (n) t;~1");
assert!(s.contains("Result"), "no Result: {s}");
assert!(s.contains("Number"), "no Number: {s}");
}
#[test]
fn parse_type_param_with_paren_type() {
// LParen in a param type position exercises can_start_type's LParen branch.
let s = first_fn_param_debug("f x:(L n)>n;0");
assert!(s.contains("List"), "no List: {s}");
assert!(s.contains("Number"), "no Number: {s}");
}
#[test]
fn parse_type_nested_paren_around_atom_does_not_break_flat() {
// Sanity: existing flat `R n t` still parses.
let s = first_fn_return_debug("f>R n t;~1");
assert!(s.contains("Result"), "no Result: {s}");
}
#[test]
fn parse_type_triple_nested_paren() {
// `R (L (R n t)) t` — recursive parse_type calls through LParen arm twice.
let s = first_fn_return_debug("f>R (L (R n t)) t;~[~1,~2]");
assert!(s.contains("Result"), "no Result: {s}");
assert!(s.contains("List"), "no List: {s}");
}
// ---- list-literal-refs parser coverage ----
fn first_list_items(prog: &Program) -> Vec<Expr> {
let Decl::Function { body, .. } = &prog.declarations[0] else {
panic!("expected function")
};
let Stmt::Expr(Expr::List(items)) = &body[0].node else {
panic!("expected list, got {:?}", body[0].node)
};
items.clone()
}
#[test]
fn parse_list_whitespace_refs_are_bare_refs() {
// `[a b c]` must be a 3-element list of bare refs, not Call(a, [b, c]).
let prog = parse_str("f a:n b:n c:n>L n;[a b c]");
let items = first_list_items(&prog);
assert_eq!(items.len(), 3);
for (i, name) in ["a", "b", "c"].iter().enumerate() {
assert!(
matches!(&items[i], Expr::Ref(n) if n == name),
"items[{i}] not Ref({name}), got {:?}",
items[i]
);
}
}
#[test]
fn parse_list_comma_mode_keeps_calls() {
// With a top-level comma, calls inside elements remain calls.
let prog = parse_str("f x:n>L n;[flr x, cel x]");
let items = first_list_items(&prog);
assert_eq!(items.len(), 2);
assert!(matches!(&items[0], Expr::Call { function, .. } if function == "flr"));
assert!(matches!(&items[1], Expr::Call { function, .. } if function == "cel"));
}
#[test]
fn parse_list_whitespace_parens_force_call() {
// `[(flr x) y]` — parens reset no_whitespace_call so flr x is a call.
let prog = parse_str("f x:n y:n>L n;[(flr x) y]");
let items = first_list_items(&prog);
assert_eq!(items.len(), 2);
assert!(matches!(&items[0], Expr::Call { function, .. } if function == "flr"));
assert!(matches!(&items[1], Expr::Ref(n) if n == "y"));
}
#[test]
fn parse_list_has_top_level_comma_ignores_nested() {
// Nested brackets contain a comma but outer is whitespace-mode.
// Outer must still be whitespace-mode (no top-level comma).
let prog = parse_str("f>L L n;[[1,2] [3,4]]");
let items = first_list_items(&prog);
assert_eq!(items.len(), 2);
for inner in &items {
let Expr::List(sub) = inner else {
panic!("expected nested list, got {:?}", inner)
};
assert_eq!(sub.len(), 2);
}
}
#[test]
fn parse_list_empty_whitespace_mode() {
// Empty list — list_has_top_level_comma must hit the RBracket-at-depth-0
// early-return without errors.
let prog = parse_str("f>L n;[]");
let items = first_list_items(&prog);
assert!(items.is_empty());
}
#[test]
fn parse_list_single_ref_whitespace_mode() {
let prog = parse_str("f a:n>L n;[a]");
let items = first_list_items(&prog);
assert_eq!(items.len(), 1);
assert!(matches!(&items[0], Expr::Ref(n) if n == "a"));
}
#[test]
fn parse_list_whitespace_with_literals_and_refs() {
let prog = parse_str("f a:n>L n;[1 a 2]");
let items = first_list_items(&prog);
assert_eq!(items.len(), 3);
assert!(matches!(&items[1], Expr::Ref(n) if n == "a"));
}
#[test]
fn parse_list_comma_mode_with_parens_inside() {
// Top-level comma + nested paren — exercises the LParen reset path
// inside comma-mode element parsing.
let prog = parse_str("f x:n>L n;[(flr x), x]");
let items = first_list_items(&prog);
assert_eq!(items.len(), 2);
assert!(matches!(&items[0], Expr::Call { function, .. } if function == "flr"));
}
#[test]
fn parse_list_whitespace_with_ok_err_wrappers() {
// `[~1 ^2 ~3]` — call_ok path through Tilde/Caret arms in whitespace mode.
let prog = parse_str("f>L R n t;[~1 ^\"e\" ~3]");
let items = first_list_items(&prog);
assert_eq!(items.len(), 3);
assert!(matches!(&items[0], Expr::Ok(_)));
assert!(matches!(&items[1], Expr::Err(_)));
assert!(matches!(&items[2], Expr::Ok(_)));
}
// Zero-arg call `name()` and `name!()` must parse in every operand
// position, not just at statement head. See `parse_atom` Ident arm and
// SPEC.md:16 / SPEC.md:843. Regression for routing-tsp friction #3.
fn last_fn_body(prog: &Program) -> &[Spanned<Stmt>] {
let decl = prog
.declarations
.iter()
.rev()
.find(|d| matches!(d, Decl::Function { .. }))
.expect("expected at least one function decl");
let Decl::Function { body, .. } = decl else {
unreachable!()
};
body
}
/// Extract the args of the outermost Call on the first statement of the
/// last function in `prog`. Statement can be Expr or Let — either works.
fn first_stmt_outer_call_args(prog: &Program) -> Vec<Expr> {
let body = last_fn_body(prog);
let expr = match &body[0].node {
Stmt::Expr(e) => e,
Stmt::Let { value, .. } => value,
Stmt::Return(e) => e,
other => panic!("unexpected first stmt: {:?}", other),
};
match expr {
Expr::Call { args, .. } => args.clone(),
other => panic!("expected Call expr, got {:?}", other),
}
}
#[test]
fn zero_arg_call_as_builtin_arg() {
// `len xs()` must parse as `len(xs())`, not as `len xs` + dangling `()`.
let prog = parse_str("xs>L n;[1 2 3]\nf>n;len xs()");
let args = first_stmt_outer_call_args(&prog);
assert_eq!(args.len(), 1);
match &args[0] {
Expr::Call {
function,
args,
unwrap,
} => {
assert_eq!(function, "xs");
assert!(args.is_empty());
assert!(!unwrap.is_any());
}
other => panic!("expected zero-arg Call for xs(), got {:?}", other),
}
}
#[test]
fn zero_arg_call_as_hof_collection_arg() {
// `map dbl xs()` — last arg of a HOF is the operand path.
let prog = parse_str("xs>L n;[1 2 3]\ndbl x:n>n;* x 2\nf>L n;map dbl xs()");
let args = first_stmt_outer_call_args(&prog);
assert_eq!(args.len(), 2);
assert!(matches!(&args[0], Expr::Ref(n) if n == "dbl"));
match &args[1] {
Expr::Call { function, args, .. } => {
assert_eq!(function, "xs");
assert!(args.is_empty());
}
other => panic!("expected xs() Call, got {:?}", other),
}
}
#[test]
fn zero_arg_call_as_loop_subject() {
// `@v xs(){...}` — loop subject goes through parse_expr_inner → parse_call_or_atom.
let prog = parse_str("xs>L n;[1 2 3]\nf>n;t=0;@v xs(){t=+t v};t");
let body = last_fn_body(&prog);
let foreach = body
.iter()
.find_map(|s| match &s.node {
Stmt::ForEach { collection, .. } => Some(collection),
_ => None,
})
.expect("expected ForEach stmt");
match foreach {
Expr::Call { function, args, .. } => {
assert_eq!(function, "xs");
assert!(args.is_empty());
}
other => panic!("expected xs() Call in loop subject, got {:?}", other),
}
}
#[test]
fn zero_arg_unwrap_call_in_operand_position() {
// `len fetch!()` — `name!()` must work in operand position too.
// SPEC.md:843 documents `fetch!()` for the auto-unwrap form.
let prog = parse_str("fetch>R t t;~\"hi\"\nf>R n t;~len fetch!()");
let body = last_fn_body(&prog);
// Body is `Expr(Ok(Call(len, [Call(fetch, [], unwrap=true)])))`.
let expr = match &body[0].node {
Stmt::Expr(e) => e,
Stmt::Return(e) => e,
other => panic!("expected Expr/Return stmt, got {:?}", other),
};
let ok_inner = match expr {
Expr::Ok(inner) => inner.as_ref(),
other => panic!("expected Ok wrapper, got {:?}", other),
};
let len_args = match ok_inner {
Expr::Call { function, args, .. } if function == "len" => args,
other => panic!("expected len Call, got {:?}", other),
};
assert_eq!(len_args.len(), 1);
match &len_args[0] {
Expr::Call {
function,
args,
unwrap,
} => {
assert_eq!(function, "fetch");
assert!(args.is_empty());
assert!(unwrap.is_propagate(), "expected unwrap=true for fetch!()");
}
other => panic!("expected fetch!() Call, got {:?}", other),
}
}
#[test]
fn bare_ident_still_parses_as_ref_for_hof_arg() {
// Make sure the fix doesn't regress the HOF fn-ref path:
// `map dbl xs` keeps `dbl` as Ref so the verifier can resolve it to
// a function reference. Only the trailing `()` triggers a Call.
let prog = parse_str("dbl x:n>n;* x 2\nf xs:L n>L n;map dbl xs");
let args = first_stmt_outer_call_args(&prog);
assert_eq!(args.len(), 2);
assert!(matches!(&args[0], Expr::Ref(n) if n == "dbl"));
assert!(matches!(&args[1], Expr::Ref(n) if n == "xs"));
}
// ── persona-diagnostic batch 2 ────────────────────────────────────────
#[test]
fn compound_prefix_eq_less_emits_hint() {
// `f d:n>n;=<d 0{ret 0};d` — the compound `=<` is a slip for `<=`.
let source = "f d:n>n;=<d 0{ret 0};d";
let (_, errors) = parse_str_errors(source);
let e = errors
.iter()
.find(|e| e.code == "ILO-P003")
.expect("expected ILO-P003 for compound prefix");
assert!(
e.message.contains("`=<` is not an ilo operator"),
"message: {}",
e.message
);
let hint = e.hint.as_ref().expect("expected hint");
assert!(
hint.contains("<=") && hint.contains("single token"),
"hint: {}",
hint
);
}
#[test]
fn compound_prefix_eq_greater_emits_hint() {
let source = "f d:n>n;=>d 0{ret 0};d";
let (_, errors) = parse_str_errors(source);
let e = errors
.iter()
.find(|e| e.code == "ILO-P003")
.expect("expected ILO-P003");
assert!(e.message.contains("`=>`"), "message: {}", e.message);
assert!(
e.hint.as_ref().unwrap().contains(">="),
"hint: {:?}",
e.hint
);
}
#[test]
fn compound_prefix_bang_less_is_negated_guard_not_compound() {
// `!<d 0{ret 0}` is a VALID negated guard: `!` + condition `<d 0`
// + body `{ret 0}`. The compound-prefix hint must not fire here
// because `!<` is not a compound-comparison ambiguity in ilo.
let source = "f d:n>n;!<d 0{ret 0};d";
let (_, errors) = parse_str_errors(source);
assert!(
!errors
.iter()
.any(|e| e.message.contains("`!<` is not an ilo operator")),
"should not fire compound-prefix hint for `!<`; errors: {:?}",
errors
);
}
#[test]
fn fn_at_expression_position_emits_lambda_hint() {
let source = "main>n;f=fn x:n>n;+x 1;f 5";
let (_, errors) = parse_str_errors(source);
// First error should be the lambda hint, not a downstream cascade.
let e = errors
.iter()
.find(|e| e.code == "ILO-P009" && e.message.contains("`fn` is a reserved word"))
.expect("expected ILO-P009 with `fn` lambda message");
let hint = e.hint.as_ref().expect("expected hint");
assert!(
hint.contains("(p:t>r;body)") && hint.contains("inline lambda"),
"hint: {}",
hint
);
}
#[test]
fn def_at_expression_position_emits_lambda_hint() {
let source = "main>n;f=def x:n>n;+x 1;f 5";
let (_, errors) = parse_str_errors(source);
let e = errors
.iter()
.find(|e| e.code == "ILO-P009" && e.message.contains("`def` is a reserved word"))
.expect("expected ILO-P009 with `def` lambda message");
assert!(e.hint.as_ref().unwrap().contains("(p:t>r;body)"));
}
#[test]
fn fn_decl_colon_before_greater_emits_signature_hint() {
// `main:>n;42` — the `:` before `>` is a slip from other-language
// type-annotation shapes. Surface the canonical signature form.
let source = "main:>n;42";
let (_, errors) = parse_str_errors(source);
let e = errors
.iter()
.find(|e| e.code == "ILO-P003")
.expect("expected ILO-P003");
assert!(
e.message.contains(":>") && e.message.contains("main"),
"message: {}",
e.message
);
let hint = e.hint.as_ref().expect("expected hint");
assert!(hint.contains("main>return;body"), "hint: {}", hint);
}
#[test]
fn fn_decl_with_params_still_errors_normally_on_stray_colon() {
// With actual params (`f x:n:>n`), the new hint must NOT fire; the
// generic `expected Greater, got Colon` path is correct because
// params are non-empty and the colon position is post-params.
let source = "f x:n:>n;42";
let (_, errors) = parse_str_errors(source);
let e = errors
.iter()
.find(|e| e.code == "ILO-P003")
.expect("expected ILO-P003");
// Must not contain the new `:>` signature-shape hint.
assert!(
!e.message.contains(":>"),
"should not fire signature hint with non-empty params; got: {}",
e.message
);
}
#[test]
fn lbrace_expected_got_semi_emits_multiline_body_hint() {
// Foreach body without explicit `{`: `@k xs;+k 1` triggers
// `expected LBrace, got Semi`.
let source = "main>n;xs=[1 2 3];@k xs;+k 1";
let (_, errors) = parse_str_errors(source);
let e = errors
.iter()
.find(|e| e.code == "ILO-P003" && e.message.contains("expected LBrace"))
.expect("expected ILO-P003 LBrace error");
let hint = e.hint.as_ref().expect("expected hint");
assert!(
hint.contains("single-line") && hint.contains("`{ ... }`"),
"hint: {}",
hint
);
}
#[test]
fn lbrace_expected_got_other_token_no_multiline_hint() {
// `type foo bar` — expected LBrace got Ident("bar"). The new hint
// should NOT fire here; it's specific to the `;` after-statement
// shape, not arbitrary non-`{` tokens.
let source = "type foo bar";
let (_, errors) = parse_str_errors(source);
let e = errors
.iter()
.find(|e| e.code == "ILO-P003")
.expect("expected ILO-P003");
let hint_contains_multiline = e
.hint
.as_ref()
.map(|h| h.contains("single-line"))
.unwrap_or(false);
assert!(
!hint_contains_multiline,
"should not fire multi-line hint here; hint: {:?}",
e.hint
);
}
}