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
//! Parser for Metal DOL.
//!
//! This module provides a recursive descent parser that transforms a stream
//! of tokens into an Abstract Syntax Tree (AST).
//!
//! # Example
//!
//! ```rust
//! use metadol::parser::Parser;
//! use metadol::ast::Declaration;
//!
//! let input = r#"
//! gene container.exists {
//! container has identity
//! }
//!
//! exegesis {
//! A container is the fundamental unit.
//! }
//! "#;
//!
//! let mut parser = Parser::new(input);
//! let result = parser.parse();
//! assert!(result.is_ok());
//! ```
use crate::ast::*;
use crate::error::ParseError;
use crate::lexer::{Lexer, Token, TokenKind};
use crate::macros::{AttributeArg, MacroAttribute, MacroInvocation};
use crate::pratt::{infix_binding_power, prefix_binding_power};
/// The parser for Metal DOL source text.
///
/// The parser uses recursive descent to transform tokens into an AST.
/// It provides helpful error messages with source locations.
pub struct Parser<'a> {
/// The underlying lexer
lexer: Lexer<'a>,
/// The source text (for exegesis parsing)
source: &'a str,
/// Current token
current: Token,
/// Previous token (for span tracking)
previous: Token,
/// Peeked token for lookahead (if any)
peeked: Option<Token>,
/// Second peeked token for two-token lookahead (if any)
peeked2: Option<Token>,
/// Third peeked token for three-token lookahead (if any)
peeked3: Option<Token>,
}
impl<'a> Parser<'a> {
/// Creates a new parser for the given source text.
pub fn new(source: &'a str) -> Self {
let mut lexer = Lexer::new(source);
let current = lexer.next_token();
let previous = Token::new(TokenKind::Eof, "", Span::default());
Parser {
lexer,
source,
current,
previous,
peeked: None,
peeked2: None,
peeked3: None,
}
}
/// Parses the source into a declaration.
///
/// # Returns
///
/// The parsed `Declaration` on success, or a `ParseError` on failure.
pub fn parse(&mut self) -> Result<Declaration, ParseError> {
// Skip module declaration if present
self.skip_module_and_uses()?;
let decl = self.parse_declaration()?;
// Allow trailing content (other declarations in the file)
// For now, we just return the first declaration
Ok(decl)
}
/// Parses all declarations from the input.
///
/// Skips module declarations and use statements, then parses all
/// top-level declarations until EOF.
///
/// # Returns
///
/// A vector of all parsed declarations, or a `ParseError` on failure.
pub fn parse_all(&mut self) -> Result<Vec<Declaration>, ParseError> {
// Skip module declaration if present
self.skip_module_and_uses()?;
let mut declarations = Vec::new();
while self.current.kind != TokenKind::Eof {
let decl = self.parse_declaration()?;
declarations.push(decl);
}
Ok(declarations)
}
/// Parses a complete DOL file including module and use declarations.
///
/// Returns a `DolFile` containing the module declaration (if any),
/// use declarations, and all top-level declarations.
pub fn parse_file(&mut self) -> Result<DolFile, ParseError> {
// Parse optional module declaration
let module = if self.current.kind == TokenKind::Module {
Some(self.parse_module_decl()?)
} else {
None
};
// Parse use declarations
let mut uses = Vec::new();
loop {
// Handle pub use (re-exports)
if self.current.kind == TokenKind::Pub && self.peek().kind == TokenKind::Use {
self.advance(); // consume pub
let use_decl = self.parse_use_decl(Visibility::Public)?;
uses.push(use_decl);
} else if self.current.kind == TokenKind::Use {
uses.push(self.parse_use_decl(Visibility::Private)?);
} else {
break;
}
}
// Parse all declarations
let mut declarations = Vec::new();
while self.current.kind != TokenKind::Eof {
let decl = self.parse_declaration()?;
declarations.push(decl);
}
Ok(DolFile {
module,
uses,
declarations,
})
}
/// Skips module declaration and use statements at the start of a file.
fn skip_module_and_uses(&mut self) -> Result<(), ParseError> {
// Skip module declaration
if self.current.kind == TokenKind::Module {
self.advance(); // module
// Skip path
while self.current.kind == TokenKind::Identifier || self.current.kind == TokenKind::Dot
{
self.advance();
}
// Skip version
if self.current.kind == TokenKind::At {
self.advance();
if self.current.kind == TokenKind::Version {
self.advance();
}
}
}
// Skip use declarations (including pub use)
loop {
// Skip optional pub modifier
if self.current.kind == TokenKind::Pub {
if self.peek().kind == TokenKind::Use {
self.advance(); // pub
} else {
// pub followed by something else (like pub gene) - stop skipping
break;
}
}
if self.current.kind != TokenKind::Use {
break;
}
self.advance(); // use
// Skip path (identifiers, ::, ., *, etc.)
while self.current.kind != TokenKind::Eof
&& self.current.kind != TokenKind::Gen
&& self.current.kind != TokenKind::Gene
&& self.current.kind != TokenKind::Type
&& self.current.kind != TokenKind::Trait
&& self.current.kind != TokenKind::Constraint
&& self.current.kind != TokenKind::Rule
&& self.current.kind != TokenKind::System
&& self.current.kind != TokenKind::Evolves
&& self.current.kind != TokenKind::Pub
&& self.current.kind != TokenKind::Use
&& self.current.kind != TokenKind::Module
&& self.current.kind != TokenKind::Exegesis
&& self.current.kind != TokenKind::Docs
&& self.current.kind != TokenKind::Macro // Stop before attributes
&& self.current.kind != TokenKind::Sex // Stop before sex declarations
&& self.current.kind != TokenKind::Function // Stop before functions
&& self.current.kind != TokenKind::Const
// Stop before constants
{
self.advance();
}
}
Ok(())
}
/// Skips generic type parameters: <T, U: Bound, V = Default>
fn skip_type_params(&mut self) -> Result<(), ParseError> {
if self.current.kind != TokenKind::Lt {
return Ok(());
}
self.advance(); // consume <
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
match self.current.kind {
TokenKind::Lt => depth += 1,
TokenKind::Greater => depth -= 1,
_ => {}
}
self.advance();
}
Ok(())
}
/// Skips a type expression (handles simple types and complex ones like `enum { ... }`).
#[allow(dead_code)]
fn skip_type_expr(&mut self) -> Result<(), ParseError> {
// Handle enum keyword with brace block
if self.current.kind == TokenKind::Identifier && self.current.lexeme == "enum" {
self.advance(); // consume 'enum'
if self.current.kind == TokenKind::LeftBrace {
self.advance(); // consume '{'
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
match self.current.kind {
TokenKind::LeftBrace => depth += 1,
TokenKind::RightBrace => depth -= 1,
_ => {}
}
self.advance();
}
}
return Ok(());
}
// Regular type expression: consume identifier/type keyword and optional generics
// Handle built-in type keywords (String, Int8, Int16, etc.)
if self.current.kind == TokenKind::Identifier
|| self.current.kind == TokenKind::StringType
|| self.current.kind == TokenKind::Int8
|| self.current.kind == TokenKind::Int16
|| self.current.kind == TokenKind::Int32
|| self.current.kind == TokenKind::Int64
|| self.current.kind == TokenKind::UInt8
|| self.current.kind == TokenKind::UInt16
|| self.current.kind == TokenKind::UInt32
|| self.current.kind == TokenKind::UInt64
|| self.current.kind == TokenKind::Float32
|| self.current.kind == TokenKind::Float64
|| self.current.kind == TokenKind::BoolType
{
self.advance();
} else if self.current.kind == TokenKind::LeftBracket {
// Array type: [Type] or [Type; size]
self.advance();
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
match self.current.kind {
TokenKind::LeftBracket => depth += 1,
TokenKind::RightBracket => depth -= 1,
_ => {}
}
self.advance();
}
return Ok(());
}
// Skip generic parameters: <T, U>
self.skip_type_params()?;
Ok(())
}
/// Parses a declaration.
fn parse_declaration(&mut self) -> Result<Declaration, ParseError> {
// Collect attribute annotations like #[wasm_export] or #[test]
let mut collected_attributes: Vec<String> = Vec::new();
while self.current.kind == TokenKind::Macro {
self.advance(); // consume #
if self.current.kind == TokenKind::LeftBracket {
self.advance(); // consume [
// Get the attribute name
let attr_name = if self.current.kind == TokenKind::Identifier {
self.current.lexeme.clone()
} else {
String::new()
};
// Skip to closing ]
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
match self.current.kind {
TokenKind::LeftBracket => depth += 1,
TokenKind::RightBracket => depth -= 1,
_ => {}
}
self.advance();
}
// If it's a #[test] attribute, skip the following function entirely
if attr_name == "test" {
if self.current.kind == TokenKind::Function {
self.advance(); // consume 'fun'
// Skip function name and body
while self.current.kind != TokenKind::Eof {
if self.current.kind == TokenKind::LeftBrace {
// Skip function body
self.advance();
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
match self.current.kind {
TokenKind::LeftBrace => depth += 1,
TokenKind::RightBrace => depth -= 1,
_ => {}
}
self.advance();
}
break;
}
self.advance();
}
}
// Check if we've reached end of file after skipping tests
if self.current.kind == TokenKind::Eof {
return Ok(Declaration::Gene(Gen {
visibility: Visibility::default(),
name: "_test_skipped".to_string(),
extends: None,
statements: vec![],
exegesis: "Tests skipped".to_string(),
span: self.current.span,
}));
}
// Clear collected attributes since we skipped a test
collected_attributes.clear();
} else if !attr_name.is_empty() {
// Store non-test attributes to attach to the next declaration
collected_attributes.push(attr_name);
}
}
}
// Skip visibility modifier
if self.current.kind == TokenKind::Pub {
self.advance();
// Skip optional (spirit) or (parent)
if self.current.kind == TokenKind::LeftParen {
self.advance(); // (
self.advance(); // spirit/parent
if self.current.kind == TokenKind::RightParen {
self.advance(); // )
}
}
}
match self.current.kind {
TokenKind::Gene | TokenKind::Gen => self.parse_gene(),
// type is an alias for gene (v0.3.0)
TokenKind::Type => self.parse_type_declaration(),
TokenKind::Trait => self.parse_trait(),
TokenKind::Constraint | TokenKind::Rule => self.parse_constraint(),
TokenKind::System => self.parse_system(),
TokenKind::Evolves | TokenKind::Evo => self.parse_evolution(),
TokenKind::Sex => self.parse_sex_top_level_with_attrs(collected_attributes),
TokenKind::Function => {
// Top-level pure function
let mut func = self.parse_function_decl()?;
func.attributes = collected_attributes;
Ok(Declaration::Function(Box::new(func)))
}
TokenKind::Const => {
// Top-level constant declaration
self.parse_const_decl()
}
TokenKind::Exegesis | TokenKind::Docs => {
// Skip file-level exegesis/docs block
self.advance(); // consume 'exegesis'/'docs'
self.expect(TokenKind::LeftBrace)?;
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
if self.current.kind == TokenKind::LeftBrace {
depth += 1;
}
if self.current.kind == TokenKind::RightBrace {
depth -= 1;
}
self.advance();
}
// Try to parse next declaration, or return placeholder if EOF
if self.current.kind == TokenKind::Eof {
Ok(Declaration::Gene(Gen {
visibility: Visibility::default(),
name: "_module_doc".to_string(),
extends: None,
statements: vec![],
exegesis: "Module-level documentation".to_string(),
span: self.current.span,
}))
} else {
self.parse_declaration()
}
}
TokenKind::Use => {
// Skip use statement and parse next declaration
self.advance(); // consume 'use'
// Skip path (identifiers, ::, ., *, { }, etc.)
while self.current.kind != TokenKind::Eof
&& self.current.kind != TokenKind::Gen
&& self.current.kind != TokenKind::Gene
&& self.current.kind != TokenKind::Type
&& self.current.kind != TokenKind::Trait
&& self.current.kind != TokenKind::Constraint
&& self.current.kind != TokenKind::Rule
&& self.current.kind != TokenKind::System
&& self.current.kind != TokenKind::Evolves
&& self.current.kind != TokenKind::Pub
&& self.current.kind != TokenKind::Use
&& self.current.kind != TokenKind::Exegesis
&& self.current.kind != TokenKind::Docs
&& self.current.kind != TokenKind::Sex
&& self.current.kind != TokenKind::Function
&& self.current.kind != TokenKind::Module
&& self.current.kind != TokenKind::Macro
// Stop before attributes
{
self.advance();
}
// Parse next declaration
if self.current.kind == TokenKind::Eof {
Ok(Declaration::Gene(Gen {
visibility: Visibility::default(),
name: "_use_only".to_string(),
extends: None,
statements: vec![],
exegesis: "Use-only file".to_string(),
span: self.current.span,
}))
} else {
self.parse_declaration()
}
}
TokenKind::Module => {
// Skip mod/module submodule declaration and parse next declaration
self.advance(); // consume 'mod' or 'module'
// Skip module name
if self.current.kind == TokenKind::Identifier {
self.advance();
}
// Skip block content if present
if self.current.kind == TokenKind::LeftBrace {
self.advance();
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
if self.current.kind == TokenKind::LeftBrace {
depth += 1;
}
if self.current.kind == TokenKind::RightBrace {
depth -= 1;
}
self.advance();
}
}
// Parse next declaration
if self.current.kind == TokenKind::Eof {
Ok(Declaration::Gene(Gen {
visibility: Visibility::default(),
name: "_module_decl".to_string(),
extends: None,
statements: vec![],
exegesis: "Module-only file".to_string(),
span: self.current.span,
}))
} else {
self.parse_declaration()
}
}
_ => Err(ParseError::InvalidDeclaration {
found: self.current.lexeme.clone(),
span: self.current.span,
}),
}
}
/// Parses an optional visibility modifier.
/// Returns Visibility::Private if no modifier is present.
#[allow(dead_code)]
fn parse_visibility(&mut self) -> Result<Visibility, ParseError> {
match self.current.kind {
TokenKind::Pub => {
self.advance();
// Check for pub(spirit) or pub(parent)
if self.current.kind == TokenKind::LeftParen {
self.advance();
if self.current.kind == TokenKind::Spirit {
self.advance();
self.expect(TokenKind::RightParen)?;
Ok(Visibility::PubSpirit)
} else if self.current.lexeme == "parent" {
self.advance();
self.expect(TokenKind::RightParen)?;
Ok(Visibility::PubParent)
} else {
Err(ParseError::UnexpectedToken {
expected: "spirit or parent".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
})
}
} else {
Ok(Visibility::Public)
}
}
_ => Ok(Visibility::Private),
}
}
/// Parses a module declaration: module path.to.module @ version
fn parse_module_decl(&mut self) -> Result<ModuleDecl, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Module)?;
// Parse module path (e.g., "univrs.container.lifecycle")
// The lexer may produce a single qualified identifier "dol.ast" or separate tokens
let mut path = Vec::new();
let ident = self.expect_identifier()?;
// Split qualified identifiers into path components
path.extend(ident.split('.').map(|s| s.to_string()));
while self.current.kind == TokenKind::Dot {
self.advance();
let ident = self.expect_identifier()?;
path.extend(ident.split('.').map(|s| s.to_string()));
}
// Parse optional version
let version = if self.current.kind == TokenKind::At {
self.advance();
Some(self.parse_version()?)
} else {
None
};
let span = start_span.merge(&self.previous.span);
Ok(ModuleDecl {
path,
version,
span,
})
}
/// Parses a version: 1.2.3 or 1.2.3-alpha
fn parse_version(&mut self) -> Result<Version, ParseError> {
let version_str = self.expect_version()?;
// Parse the version string into components
let mut parts = version_str.splitn(2, '-');
let numbers_part = parts.next().unwrap();
let suffix = parts.next().map(|s| s.to_string());
let numbers: Vec<&str> = numbers_part.split('.').collect();
if numbers.len() != 3 {
return Err(ParseError::InvalidStatement {
message: "version must have three parts".to_string(),
span: self.previous.span,
});
}
Ok(Version {
major: numbers[0].parse().unwrap_or(0),
minor: numbers[1].parse().unwrap_or(0),
patch: numbers[2].parse().unwrap_or(0),
suffix,
})
}
/// Parses a use declaration: use path::to::module::{items}
///
/// Supports import sources:
/// - Local: `use container`
/// - Registry: `use @univrs/std`
/// - Git: `use @git:github.com/org/repo`
/// - HTTPS: `use @https://example.com/file.dol`
fn parse_use_decl(&mut self, visibility: Visibility) -> Result<UseDecl, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Use)?;
// Parse import source prefix
let (source, mut path) = self.parse_import_source()?;
// Continue parsing path with :: or . separators
// Use expect_identifier_or_keyword to allow keywords like "state" in paths
while self.current.kind == TokenKind::PathSep || self.current.kind == TokenKind::Dot {
self.advance();
if self.current.kind == TokenKind::LeftBrace {
break; // Items list
}
if self.current.kind == TokenKind::Star {
break; // Glob import
}
let ident = self.expect_identifier_or_keyword()?;
path.extend(ident.split('.').map(|s| s.to_string()));
}
// Parse items
let items = if self.current.kind == TokenKind::Star {
self.advance();
UseItems::All
} else if self.current.kind == TokenKind::LeftBrace {
self.advance();
let mut items = Vec::new();
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof
{
let name = self.expect_identifier()?;
let alias = if self.current.kind == TokenKind::As {
self.advance();
Some(self.expect_identifier()?)
} else {
None
};
items.push(UseItem { name, alias });
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightBrace)?;
UseItems::Named(items)
} else {
UseItems::Single
};
// Parse optional alias
let alias = if self.current.kind == TokenKind::As {
self.advance();
Some(self.expect_identifier()?)
} else {
None
};
let span = start_span.merge(&self.previous.span);
Ok(UseDecl {
visibility,
source,
path,
items,
alias,
span,
})
}
/// Parses the import source prefix and initial path.
///
/// Returns (ImportSource, initial_path_components)
fn parse_import_source(&mut self) -> Result<(ImportSource, Vec<String>), ParseError> {
// Check for @ prefix indicating external source
if self.current.kind == TokenKind::At {
self.advance(); // consume @
let prefix = self.expect_identifier()?;
// Check for special prefixes
if prefix == "git" && self.current.kind == TokenKind::Colon {
// @git:github.com/org/repo
self.advance(); // consume :
let url = self.parse_url_path()?;
let reference = if self.current.kind == TokenKind::Colon {
self.advance();
Some(self.expect_identifier()?)
} else {
None
};
return Ok((ImportSource::Git { url, reference }, Vec::new()));
} else if prefix == "https" && self.current.kind == TokenKind::Colon {
// @https://example.com/file.dol
self.advance(); // consume :
// Expect // after https:
if self.current.lexeme == "/" {
self.advance();
self.advance(); // consume //
}
let url = format!("https://{}", self.parse_url_path()?);
return Ok((ImportSource::Https { url, sha256: None }, Vec::new()));
} else {
// @org/package format - this is a registry import
// prefix is the org name
let org = prefix;
self.expect(TokenKind::Slash)?;
let full_ident = self.expect_identifier()?;
// Split the identifier - first segment is package, rest goes to path
// e.g., "std.io.println" -> package="std", path=["io", "println"]
let segments: Vec<&str> = full_ident.split('.').collect();
let package = segments[0].to_string();
let path: Vec<String> = segments[1..].iter().map(|s| s.to_string()).collect();
// Optional version constraint after colon
let version = if self.current.kind == TokenKind::Colon {
self.advance();
// Version could be a string like "^1.0" or just identifier
if self.current.kind == TokenKind::String {
let v = self.current.lexeme.trim_matches('"').to_string();
self.advance();
Some(v)
} else {
Some(self.expect_identifier()?)
}
} else {
None
};
// Return the path segments that come after the package name
return Ok((
ImportSource::Registry {
org,
package,
version,
},
path,
));
}
}
// Local import - parse initial path segment only
// The main loop in parse_use_decl will handle additional segments
// Use expect_identifier_or_keyword to allow keywords like "state" as module names
let mut path = Vec::new();
let ident = self.expect_identifier_or_keyword()?;
path.extend(ident.split('.').map(|s| s.to_string()));
Ok((ImportSource::Local, path))
}
/// Parses a URL-like path (for git: and https: sources).
fn parse_url_path(&mut self) -> Result<String, ParseError> {
let mut parts = Vec::new();
// Collect path segments separated by / and .
loop {
if self.current.kind == TokenKind::Identifier {
parts.push(self.current.lexeme.to_string());
self.advance();
} else {
break;
}
if self.current.kind == TokenKind::Slash {
parts.push("/".to_string());
self.advance();
} else if self.current.kind == TokenKind::Dot {
parts.push(".".to_string());
self.advance();
} else {
break;
}
}
if parts.is_empty() {
return Err(ParseError::UnexpectedToken {
expected: "URL path".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
}
Ok(parts.join(""))
}
/// Parses a gene declaration.
fn parse_gene(&mut self) -> Result<Declaration, ParseError> {
let start_span = self.current.span;
// v0.8.0: Accept both "gen" (new) and "gene" (deprecated)
if self.current.kind == TokenKind::Gen {
self.advance();
} else if self.current.kind == TokenKind::Gene {
eprintln!("warning: 'gene' keyword is deprecated in v0.8.0, use 'gen' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
} else {
return Err(ParseError::UnexpectedToken {
expected: "'gen' or 'gene'".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
}
let name = self.expect_identifier()?;
// Skip generic type parameters if present: <T, U: Bound>
self.skip_type_params()?;
// Parse optional extends clause (v0.3.0): gene Foo extends Bar { ... }
let extends = if self.current.kind == TokenKind::Extends {
self.advance();
Some(self.expect_identifier()?)
} else {
None
};
self.expect(TokenKind::LeftBrace)?;
let statements = self.parse_statements()?;
// DOL 2.0: exegesis can be inside braces
let inline_exegesis = self.parse_inline_exegesis()?;
self.expect(TokenKind::RightBrace)?;
// DOL 1.0: exegesis can be after braces
// DOL 2.0: use inline or default to empty
let exegesis = if let Some(ex) = inline_exegesis {
ex
} else if self.current.kind == TokenKind::Exegesis || self.current.kind == TokenKind::Docs {
self.parse_exegesis()?
} else {
String::new() // DOL 2.0 tolerant: empty exegesis if none
};
let span = start_span.merge(&self.previous.span);
Ok(Declaration::Gene(Gen {
visibility: Visibility::default(),
name,
extends,
statements,
exegesis,
span,
}))
}
/// Parses a type declaration (v0.3.0 - alias for gene).
///
/// Type declarations work exactly like gene declarations but use the `type` keyword.
/// This provides an alternative syntax that may be more familiar to developers
/// coming from other languages.
fn parse_type_declaration(&mut self) -> Result<Declaration, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Type)?;
let name = self.expect_identifier()?;
// Skip generic type parameters if present: <T, U: Bound>
self.skip_type_params()?;
// Parse optional extends clause: type Foo extends Bar { ... }
let extends = if self.current.kind == TokenKind::Extends {
self.advance();
Some(self.expect_identifier()?)
} else {
None
};
self.expect(TokenKind::LeftBrace)?;
let statements = self.parse_statements()?;
// DOL 2.0: exegesis can be inside braces
let inline_exegesis = self.parse_inline_exegesis()?;
self.expect(TokenKind::RightBrace)?;
// DOL 1.0: exegesis can be after braces
// DOL 2.0: use inline or default to empty
let exegesis = if let Some(ex) = inline_exegesis {
ex
} else if self.current.kind == TokenKind::Exegesis || self.current.kind == TokenKind::Docs {
self.parse_exegesis()?
} else {
String::new() // DOL 2.0 tolerant: empty exegesis if none
};
let span = start_span.merge(&self.previous.span);
// Type declarations are represented as Gene in the AST
Ok(Declaration::Gene(Gen {
visibility: Visibility::default(),
name,
extends,
statements,
exegesis,
span,
}))
}
/// Parses a trait declaration.
fn parse_trait(&mut self) -> Result<Declaration, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Trait)?;
let name = self.expect_identifier()?;
// Skip generic type parameters if present
self.skip_type_params()?;
self.expect(TokenKind::LeftBrace)?;
let mut statements = Vec::new();
let mut _laws: Vec<LawDecl> = Vec::new();
while self.current.kind != TokenKind::RightBrace
&& self.current.kind != TokenKind::Eof
&& self.current.kind != TokenKind::Exegesis
&& self.current.kind != TokenKind::Docs
{
// Check for law declarations
if self.current.kind == TokenKind::Law {
let law = self.parse_law_decl()?;
_laws.push(law);
} else {
statements.push(self.parse_statement()?);
}
}
// DOL 2.0: exegesis can be inside braces
let inline_exegesis = self.parse_inline_exegesis()?;
self.expect(TokenKind::RightBrace)?;
// DOL 1.0: exegesis can be after braces
let exegesis = if let Some(ex) = inline_exegesis {
ex
} else if self.current.kind == TokenKind::Exegesis || self.current.kind == TokenKind::Docs {
self.parse_exegesis()?
} else {
String::new()
};
let span = start_span.merge(&self.previous.span);
Ok(Declaration::Trait(Trait {
visibility: Visibility::default(),
name,
statements,
exegesis,
span,
}))
}
/// Parses a constraint declaration.
fn parse_constraint(&mut self) -> Result<Declaration, ParseError> {
let start_span = self.current.span;
// v0.8.0: Accept both "rule" (new) and "constraint" (deprecated)
if self.current.kind == TokenKind::Rule {
self.advance();
} else if self.current.kind == TokenKind::Constraint {
eprintln!("warning: 'constraint' keyword is deprecated in v0.8.0, use 'rule' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
} else {
return Err(ParseError::UnexpectedToken {
expected: "'rule' or 'constraint'".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
}
let name = self.expect_identifier()?;
// Skip generic type parameters if present
self.skip_type_params()?;
self.expect(TokenKind::LeftBrace)?;
let statements = self.parse_statements()?;
// DOL 2.0: exegesis can be inside braces
let inline_exegesis = self.parse_inline_exegesis()?;
self.expect(TokenKind::RightBrace)?;
// DOL 1.0: exegesis can be after braces
let exegesis = if let Some(ex) = inline_exegesis {
ex
} else if self.current.kind == TokenKind::Exegesis || self.current.kind == TokenKind::Docs {
self.parse_exegesis()?
} else {
String::new()
};
let span = start_span.merge(&self.previous.span);
Ok(Declaration::Constraint(Rule {
visibility: Visibility::default(),
name,
statements,
exegesis,
span,
}))
}
/// Parses a system declaration.
fn parse_system(&mut self) -> Result<Declaration, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::System)?;
let name = self.expect_identifier()?;
// Skip generic type parameters if present
self.skip_type_params()?;
// DOL 2.0: version is optional
let version = if self.current.kind == TokenKind::At {
self.advance();
self.expect_version()?
} else {
"0.0.0".to_string()
};
self.expect(TokenKind::LeftBrace)?;
let mut requirements = Vec::new();
let mut statements = Vec::new();
let mut _states: Vec<StateDecl> = Vec::new(); // States for future use
while self.current.kind != TokenKind::RightBrace
&& self.current.kind != TokenKind::Eof
&& self.current.kind != TokenKind::Exegesis
&& self.current.kind != TokenKind::Docs
{
if self.current.kind == TokenKind::Requires
&& self.peek_is_identifier()
&& self.peek_is_version_constraint()
{
requirements.push(self.parse_requirement()?);
} else if self.current.kind == TokenKind::State {
// Parse state declaration
let state = self.parse_state_decl()?;
_states.push(state); // Store in local vector for future use
} else {
statements.push(self.parse_statement()?);
}
}
// DOL 2.0: exegesis can be inside braces
let inline_exegesis = self.parse_inline_exegesis()?;
self.expect(TokenKind::RightBrace)?;
// DOL 1.0: exegesis can be after braces
let exegesis = if let Some(ex) = inline_exegesis {
ex
} else if self.current.kind == TokenKind::Exegesis || self.current.kind == TokenKind::Docs {
self.parse_exegesis()?
} else {
String::new()
};
let span = start_span.merge(&self.previous.span);
Ok(Declaration::System(System {
visibility: Visibility::default(),
name,
version,
requirements,
statements,
exegesis,
span,
}))
}
/// Parses an evolution declaration.
fn parse_evolution(&mut self) -> Result<Declaration, ParseError> {
let start_span = self.current.span;
// v0.8.0: Accept both "evo" (new) and "evolves" (deprecated)
if self.current.kind == TokenKind::Evo {
self.advance();
} else if self.current.kind == TokenKind::Evolves {
eprintln!("warning: 'evolves' keyword is deprecated in v0.8.0, use 'evo' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
} else {
return Err(ParseError::UnexpectedToken {
expected: "'evo' or 'evolves'".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
}
let name = self.expect_identifier()?;
self.expect(TokenKind::At)?;
let version = self.expect_version()?;
self.expect(TokenKind::Greater)?;
let parent_version = self.expect_version()?;
self.expect(TokenKind::LeftBrace)?;
let mut additions = Vec::new();
let mut deprecations = Vec::new();
let mut removals = Vec::new();
let mut rationale = None;
let mut _migrate: Option<Vec<Stmt>> = None;
while self.current.kind != TokenKind::RightBrace
&& self.current.kind != TokenKind::Eof
&& self.current.kind != TokenKind::Exegesis
&& self.current.kind != TokenKind::Docs
{
match self.current.kind {
TokenKind::Adds => {
self.advance();
additions.push(self.parse_statement()?);
}
TokenKind::Deprecates => {
self.advance();
deprecations.push(self.parse_statement()?);
}
TokenKind::Removes => {
self.advance();
let name = self.expect_identifier()?;
removals.push(name);
}
TokenKind::Because => {
self.advance();
let text = self.expect_string()?;
rationale = Some(text);
}
TokenKind::Migrate => {
_migrate = Some(self.parse_migrate_block()?);
}
_ => {
return Err(ParseError::UnexpectedToken {
expected: "adds, deprecates, removes, migrate, or because".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
}
}
}
// DOL 2.0: exegesis can be inside braces
let inline_exegesis = self.parse_inline_exegesis()?;
self.expect(TokenKind::RightBrace)?;
// DOL 1.0: exegesis can be after braces
let exegesis = if let Some(ex) = inline_exegesis {
ex
} else if self.current.kind == TokenKind::Exegesis || self.current.kind == TokenKind::Docs {
self.parse_exegesis()?
} else {
String::new()
};
let span = start_span.merge(&self.previous.span);
Ok(Declaration::Evolution(Evo {
name,
version,
parent_version,
additions,
deprecations,
removals,
rationale,
exegesis,
span,
}))
}
/// Parses multiple statements until a closing brace.
fn parse_statements(&mut self) -> Result<Vec<Statement>, ParseError> {
let mut statements = Vec::new();
// Stop at RightBrace or Eof
// DOL 2.0/v0.4.0: exegesis blocks can appear throughout gene body, handled in parse_statement
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof {
statements.push(self.parse_statement()?);
}
Ok(statements)
}
/// Parses a single statement.
fn parse_statement(&mut self) -> Result<Statement, ParseError> {
let start_span = self.current.span;
// Handle DOL 2.0/v0.4.0 inline exegesis blocks - skip them
while self.current.kind == TokenKind::Exegesis || self.current.kind == TokenKind::Docs {
self.advance(); // consume 'exegesis' or 'docs'
if self.current.kind == TokenKind::LeftBrace {
self.advance();
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
match self.current.kind {
TokenKind::LeftBrace => depth += 1,
TokenKind::RightBrace => depth -= 1,
_ => {}
}
self.advance();
}
}
// If we're at the end of the block, return a no-op marker
if self.current.kind == TokenKind::RightBrace || self.current.kind == TokenKind::Eof {
return Ok(Statement::Is {
subject: "_skip".to_string(),
state: "_noop".to_string(),
span: start_span.merge(&self.previous.span),
});
}
}
// Handle 'uses' statements
if self.current.kind == TokenKind::Uses {
self.advance();
let reference = self.expect_identifier()?;
return Ok(Statement::Uses {
reference,
span: start_span.merge(&self.previous.span),
});
}
// Handle quantified statements
if matches!(self.current.kind, TokenKind::Each | TokenKind::All) {
let quantifier = match self.current.kind {
TokenKind::Each => Quantifier::Each,
TokenKind::All => Quantifier::All,
_ => unreachable!(),
};
self.advance();
// For quantified statements, parse the complete phrase including predicates
let phrase = self.parse_quantified_phrase()?;
return Ok(Statement::Quantified {
quantifier,
phrase,
span: start_span.merge(&self.previous.span),
});
}
// Handle DOL 2.0 'has' field declarations: has name: Type [= default]
if self.current.kind == TokenKind::Has {
self.advance();
let name = self.expect_identifier_or_keyword()?;
// Check for typed field: has name: Type
if self.current.kind == TokenKind::Colon {
self.advance();
let type_ = self.parse_type()?;
// Parse optional default value: = expr
let default = if self.current.kind == TokenKind::Equal {
self.advance();
Some(self.parse_expr(0)?)
} else {
None
};
return Ok(Statement::HasField(Box::new(HasField {
name,
type_,
default,
constraint: None,
span: start_span.merge(&self.previous.span),
})));
} else {
// Skip untyped default value: = expr
if self.current.kind == TokenKind::Equal {
self.advance();
self.parse_expr(0)?;
}
return Ok(Statement::Has {
subject: "self".to_string(),
property: name,
span: start_span.merge(&self.previous.span),
});
}
}
// Handle DOL 2.0 inline 'constraint'/'rule' blocks inside declarations
if self.current.kind == TokenKind::Constraint || self.current.kind == TokenKind::Rule {
// Emit deprecation warning for old 'constraint' keyword
if self.current.kind == TokenKind::Constraint {
eprintln!("warning: 'constraint' keyword is deprecated in v0.8.0, use 'rule' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
}
self.advance();
let name = self.expect_identifier()?;
// Skip constraint body: { ... }
if self.current.kind == TokenKind::LeftBrace {
self.advance();
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
match self.current.kind {
TokenKind::LeftBrace => depth += 1,
TokenKind::RightBrace => depth -= 1,
_ => {}
}
self.advance();
}
}
return Ok(Statement::Requires {
subject: "self".to_string(),
requirement: name,
span: start_span.merge(&self.previous.span),
});
}
// Handle DOL 2.0 function declarations inside genes: [pub] [sex] fun name(...) -> Type { ... }
// Check for optional visibility modifier
let mut visibility = Visibility::Private;
let mut purity = Purity::Pure;
if self.current.kind == TokenKind::Pub {
visibility = Visibility::Public;
self.advance();
}
// Check for optional purity modifier (sex = side-effecting)
if self.current.kind == TokenKind::Sex {
purity = Purity::Sex;
self.advance();
}
if self.current.kind == TokenKind::Function {
let mut func = self.parse_function_decl()?;
func.visibility = visibility;
func.purity = purity;
return Ok(Statement::Function(Box::new(func)));
}
// If we consumed pub/sex but didn't find 'fun', this is an error
if visibility != Visibility::Private || purity != Purity::Pure {
return Err(ParseError::UnexpectedToken {
expected: "'fun' after visibility/purity modifier".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
}
// Handle DOL 2.0 'law' declarations
if self.current.kind == TokenKind::Law {
self.advance();
let name = self.expect_identifier()?;
// Skip law params
if self.current.kind == TokenKind::LeftParen {
self.advance();
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
match self.current.kind {
TokenKind::LeftParen => depth += 1,
TokenKind::RightParen => depth -= 1,
_ => {}
}
self.advance();
}
}
// Skip law body
if self.current.kind == TokenKind::LeftBrace {
self.advance();
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
match self.current.kind {
TokenKind::LeftBrace => depth += 1,
TokenKind::RightBrace => depth -= 1,
_ => {}
}
self.advance();
}
}
return Ok(Statement::Requires {
subject: "self".to_string(),
requirement: name,
span: start_span.merge(&self.previous.span),
});
}
// Handle visibility modifiers (pub, pub(spirit), etc.)
if self.current.kind == TokenKind::Pub {
self.advance();
// Skip pub(...) if present
if self.current.kind == TokenKind::LeftParen {
self.advance();
let mut depth = 1;
while depth > 0 && self.current.kind != TokenKind::Eof {
match self.current.kind {
TokenKind::LeftParen => depth += 1,
TokenKind::RightParen => depth -= 1,
_ => {}
}
self.advance();
}
}
// Continue to parse the actual statement
return self.parse_statement();
}
// Parse subject - allow keywords as field names (e.g., `type: Int64`)
let subject = self.expect_identifier_or_keyword()?;
// Determine statement type based on predicate
match self.current.kind {
TokenKind::Has => {
self.advance();
let property = self.expect_identifier_or_keyword()?;
// Check for typed field: has name: Type
if self.current.kind == TokenKind::Colon {
self.advance(); // consume ':'
let type_ = self.parse_type()?;
// Parse optional default value: = expr
let default = if self.current.kind == TokenKind::Equal {
self.advance();
Some(self.parse_expr(0)?)
} else {
None
};
Ok(Statement::HasField(Box::new(HasField {
name: property,
type_,
default,
constraint: None,
span: start_span.merge(&self.previous.span),
})))
} else {
Ok(Statement::Has {
subject,
property,
span: start_span.merge(&self.previous.span),
})
}
}
TokenKind::Is => {
self.advance();
let state = self.expect_identifier()?;
Ok(Statement::Is {
subject,
state,
span: start_span.merge(&self.previous.span),
})
}
TokenKind::Derives => {
self.advance();
self.expect(TokenKind::From)?;
let origin = self.parse_phrase()?;
Ok(Statement::DerivesFrom {
subject,
origin,
span: start_span.merge(&self.previous.span),
})
}
TokenKind::Requires => {
self.advance();
let requirement = self.parse_phrase()?;
Ok(Statement::Requires {
subject,
requirement,
span: start_span.merge(&self.previous.span),
})
}
TokenKind::Emits => {
self.advance();
let event = self.expect_identifier()?;
Ok(Statement::Emits {
action: subject,
event,
span: start_span.merge(&self.previous.span),
})
}
TokenKind::Matches => {
self.advance();
let target = self.parse_phrase()?;
Ok(Statement::Matches {
subject,
target,
span: start_span.merge(&self.previous.span),
})
}
TokenKind::Never => {
self.advance();
let action = self.expect_identifier()?;
Ok(Statement::Never {
subject,
action,
span: start_span.merge(&self.previous.span),
})
}
// DOL 2.0: name: Type field syntax (without 'has' keyword)
TokenKind::Colon => {
self.advance(); // consume ':'
// Parse the type expression
let type_ = self.parse_type()?;
// Parse optional default value
let default = if self.current.kind == TokenKind::Equal {
self.advance();
Some(self.parse_expr(0)?)
} else {
None
};
Ok(Statement::HasField(Box::new(HasField {
name: subject,
type_,
default,
constraint: None,
span: start_span.merge(&self.previous.span),
})))
}
// Handle phrases that continue with more identifiers
TokenKind::Identifier => {
// This might be part of a longer phrase
let mut phrase = subject;
while self.current.kind == TokenKind::Identifier {
phrase.push(' ');
phrase.push_str(&self.current.lexeme);
self.advance();
// Check if we've hit a predicate
if self.current.kind.is_predicate() {
break;
}
}
// Now check what predicate follows
match self.current.kind {
TokenKind::Emits => {
self.advance();
let event = self.expect_identifier()?;
Ok(Statement::Emits {
action: phrase,
event,
span: start_span.merge(&self.previous.span),
})
}
TokenKind::Never => {
self.advance();
let action = self.expect_identifier()?;
Ok(Statement::Never {
subject: phrase,
action,
span: start_span.merge(&self.previous.span),
})
}
TokenKind::Matches => {
self.advance();
let target = self.parse_phrase()?;
Ok(Statement::Matches {
subject: phrase,
target,
span: start_span.merge(&self.previous.span),
})
}
TokenKind::Is => {
self.advance();
let state = self.expect_identifier()?;
Ok(Statement::Is {
subject: phrase,
state,
span: start_span.merge(&self.previous.span),
})
}
TokenKind::Has => {
self.advance();
let property = self.expect_identifier_or_keyword()?;
Ok(Statement::Has {
subject: phrase,
property,
span: start_span.merge(&self.previous.span),
})
}
TokenKind::Requires => {
self.advance();
let requirement = self.parse_phrase()?;
Ok(Statement::Requires {
subject: phrase,
requirement,
span: start_span.merge(&self.previous.span),
})
}
_ => Err(ParseError::InvalidStatement {
message: format!("expected predicate after '{}'", phrase),
span: self.current.span,
}),
}
}
_ => Err(ParseError::UnexpectedToken {
expected: "predicate (has, is, derives, requires, etc.)".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
}),
}
}
/// Parses a phrase (one or more identifiers).
///
/// Uses lookahead to avoid consuming identifiers that start new statements.
/// If the token after an identifier is a predicate, that identifier starts
/// a new statement and should not be included in this phrase.
///
/// Note: The `no` keyword is allowed in phrases since it's not used as a
/// quantifier (only `each` and `all` are used).
fn parse_phrase(&mut self) -> Result<String, ParseError> {
let mut phrase = String::new();
// First token must be identifier or 'no' (which can appear in phrases)
if self.current.kind != TokenKind::Identifier && self.current.kind != TokenKind::No {
return Err(ParseError::UnexpectedToken {
expected: "identifier".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
}
phrase.push_str(&self.current.lexeme);
self.advance();
// Continue while we see identifiers or 'no', but use lookahead to stop
// at statement boundaries
while self.current.kind == TokenKind::Identifier || self.current.kind == TokenKind::No {
// Peek at what comes after this token
let next_kind = self.peek().kind;
// If the next token is a predicate, this identifier starts
// a new statement - don't include it in this phrase
if next_kind.is_predicate() {
break;
}
phrase.push(' ');
phrase.push_str(&self.current.lexeme);
self.advance();
}
Ok(phrase)
}
/// Parses a quantified phrase (for 'each'/'all' statements).
///
/// This continues parsing until end of statement, including predicates like 'emits'.
/// For example: "each transition emits event" captures "transition emits event".
fn parse_quantified_phrase(&mut self) -> Result<String, ParseError> {
let mut phrase = String::new();
// First token (identifier) is required
if self.current.kind != TokenKind::Identifier {
return Err(ParseError::UnexpectedToken {
expected: "identifier".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
}
phrase.push_str(&self.current.lexeme);
self.advance();
// Continue until we hit a statement boundary (RightBrace, EOF, or start of new statement)
loop {
match self.current.kind {
// End of statement boundaries
TokenKind::RightBrace | TokenKind::Eof => break,
// New statement starters (not predicates)
TokenKind::Uses | TokenKind::Each | TokenKind::All => break,
// Identifiers continue the phrase
TokenKind::Identifier => {
phrase.push(' ');
phrase.push_str(&self.current.lexeme);
self.advance();
}
// Predicates that can appear in quantified phrases
TokenKind::Has
| TokenKind::Is
| TokenKind::Emits
| TokenKind::Matches
| TokenKind::Never
| TokenKind::Requires
| TokenKind::Derives
| TokenKind::From => {
phrase.push(' ');
phrase.push_str(&self.current.lexeme);
self.advance();
}
// Any other token ends the phrase
_ => break,
}
}
Ok(phrase)
}
/// Parses a version requirement.
fn parse_requirement(&mut self) -> Result<Requirement, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Requires)?;
let name = self.expect_identifier()?;
let constraint = match self.current.kind {
TokenKind::GreaterEqual => {
self.advance();
">=".to_string()
}
TokenKind::Greater => {
self.advance();
">".to_string()
}
TokenKind::Equal => {
self.advance();
"=".to_string()
}
_ => {
return Err(ParseError::UnexpectedToken {
expected: "version constraint (>=, >, =)".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
}
};
let version = self.expect_version()?;
Ok(Requirement {
name,
constraint,
version,
span: start_span.merge(&self.previous.span),
})
}
/// Parses a has statement with optional default value and constraint.
/// Syntax: subject has property [: Type] [= default] [where constraint]
/// Returns a Statement::Has with extended information
pub fn parse_has_statement(
&mut self,
subject: String,
start_span: Span,
) -> Result<Statement, ParseError> {
self.expect(TokenKind::Has)?;
let property = self.expect_identifier_or_keyword()?;
// Check for HasField with type, default, and constraint
// This is for DOL 2.0 extended has syntax
// For now, just return the simple Has statement
// Extended parsing can be added when needed
Ok(Statement::Has {
subject,
property,
span: start_span.merge(&self.previous.span),
})
}
/// Parses a has field declaration in a gene body.
/// Syntax: subject has property: Type [= default] [where constraint]
pub fn parse_has_field(&mut self) -> Result<HasField, ParseError> {
let start_span = self.current.span;
let name = self.expect_identifier_or_keyword()?;
self.expect(TokenKind::Has)?;
let _property = self.expect_identifier_or_keyword()?; // "property" part becomes part of name
// Parse optional type
let type_ = if self.current.kind == TokenKind::Colon {
self.advance();
self.parse_type()?
} else {
TypeExpr::Named("Any".to_string())
};
// Parse optional default
let default = if self.current.kind == TokenKind::Equal {
self.advance();
Some(self.parse_expr(0)?)
} else {
None
};
// Parse optional constraint
let constraint = if self.current.kind == TokenKind::Where {
self.advance();
Some(self.parse_expr(0)?)
} else {
None
};
Ok(HasField {
name,
type_,
default,
constraint,
span: start_span.merge(&self.previous.span),
})
}
/// Parses a state declaration in a system.
/// Syntax: state name: Type [= default]
pub fn parse_state_decl(&mut self) -> Result<StateDecl, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::State)?;
let name = self.expect_identifier()?;
// Type is required for state
self.expect(TokenKind::Colon)?;
let type_ = self.parse_type()?;
// Parse optional default
let default = if self.current.kind == TokenKind::Equal {
self.advance();
Some(self.parse_expr(0)?)
} else {
None
};
Ok(StateDecl {
name,
type_,
default,
span: start_span.merge(&self.previous.span),
})
}
/// Parses a variable declaration: var/const name: Type [= value]
/// Used for sex var and const declarations.
pub fn parse_var_decl(&mut self, mutability: Mutability) -> Result<VarDecl, ParseError> {
let start_span = self.current.span;
let name = self.expect_identifier()?;
// Parse optional type annotation
let type_ann = if self.current.kind == TokenKind::Colon {
self.advance();
Some(self.parse_type()?)
} else {
None
};
// Parse optional value
let value = if self.current.kind == TokenKind::Equal {
self.advance();
Some(self.parse_expr(0)?)
} else {
None
};
Ok(VarDecl {
mutability,
name,
type_ann,
value,
span: start_span.merge(&self.previous.span),
})
}
/// Parses a sex var declaration: sex var name: Type [= value]
pub fn parse_sex_var(&mut self) -> Result<VarDecl, ParseError> {
self.expect(TokenKind::Sex)?;
self.expect(TokenKind::Var)?;
self.parse_var_decl(Mutability::Mutable)
}
/// Parses a const declaration: const name: Type = value
pub fn parse_const(&mut self) -> Result<VarDecl, ParseError> {
self.expect(TokenKind::Const)?;
self.parse_var_decl(Mutability::Immutable)
}
/// Parses a top-level const declaration: const NAME: Type = value
///
/// Returns a Declaration::Const for use in module-level declarations.
pub fn parse_const_decl(&mut self) -> Result<Declaration, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Const)?;
let name = self.expect_identifier()?;
// Parse optional type annotation
let type_ann = if self.current.kind == TokenKind::Colon {
self.advance();
Some(self.parse_type()?)
} else {
None
};
// Const requires a value
self.expect(TokenKind::Equal)?;
let value = self.parse_expr(0)?;
// Consume optional semicolon
self.consume_optional_semicolon();
Ok(Declaration::Const(ConstDecl {
visibility: Visibility::default(),
name,
type_ann,
value,
span: start_span.merge(&self.previous.span),
}))
}
/// Parses an extern function declaration: sex extern [abi] fun name(...) -> Type
pub fn parse_sex_extern(&mut self) -> Result<ExternDecl, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Sex)?;
self.expect(TokenKind::Extern)?;
// Parse optional ABI
let abi = if self.current.kind == TokenKind::String {
Some(self.expect_string()?)
} else {
None
};
self.expect(TokenKind::Function)?;
let name = self.expect_identifier()?;
// Parse parameters
self.expect(TokenKind::LeftParen)?;
let mut params = Vec::new();
while self.current.kind != TokenKind::RightParen && self.current.kind != TokenKind::Eof {
// Allow DOL keywords as parameter names (e.g., `gene: GeneDecl`)
let param_name = self.expect_identifier_or_keyword()?;
self.expect(TokenKind::Colon)?;
let type_ann = self.parse_type()?;
params.push(FunctionParam {
name: param_name,
type_ann,
});
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
// Parse optional return type
let return_type = if self.current.kind == TokenKind::Arrow {
self.advance();
Some(self.parse_type()?)
} else {
None
};
Ok(ExternDecl {
abi,
name,
params,
return_type,
span: start_span.merge(&self.previous.span),
})
}
/// Parse top-level sex declaration with attributes (sex var, sex fun, sex extern)
fn parse_sex_top_level_with_attrs(
&mut self,
attributes: Vec<String>,
) -> Result<Declaration, ParseError> {
let start = self.current.span;
// Don't consume 'sex' - let child functions do it
// Peek at what comes after 'sex'
let next = self.peek();
match next.kind {
TokenKind::Var => {
let var_decl = self.parse_sex_var()?;
Ok(Declaration::SexVar(var_decl))
}
TokenKind::Function => {
self.advance(); // consume 'sex'
let mut func = self.parse_function_decl()?;
func.purity = crate::ast::Purity::Sex;
func.attributes = attributes;
Ok(Declaration::Function(Box::new(func)))
}
TokenKind::Extern => {
let extern_decl = self.parse_sex_extern()?;
// Keep extern functions as Gene placeholder (FFI stubs need special handling)
Ok(Declaration::Gene(Gen {
visibility: Visibility::default(),
name: extern_decl.name.clone(),
extends: None,
statements: vec![],
exegesis: format!("sex extern {}", extern_decl.name),
span: extern_decl.span,
}))
}
_ => Err(ParseError::InvalidDeclaration {
found: format!("sex {}", next.lexeme),
span: start,
}),
}
}
/// Parses the exegesis block.
fn parse_exegesis(&mut self) -> Result<String, ParseError> {
// v0.8.0: Accept both "docs" (new) and "exegesis" (deprecated)
if self.current.kind == TokenKind::Docs {
self.advance(); // consume 'docs'
} else if self.current.kind == TokenKind::Exegesis {
eprintln!("warning: 'exegesis' keyword is deprecated in v0.8.0, use 'docs' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance(); // consume 'exegesis'
} else {
return Err(ParseError::MissingExegesis {
span: self.current.span,
});
}
self.expect(TokenKind::LeftBrace)?;
// Collect all text until closing brace
// We need to handle nested braces
let mut content = String::new();
let mut brace_depth = 1;
// Get position after opening brace
let start_pos = self.current.span.start;
// Re-lex from the source to get raw text
let source_after_brace = &self.lexer_source()[start_pos..];
for ch in source_after_brace.chars() {
if ch == '{' {
brace_depth += 1;
content.push(ch);
} else if ch == '}' {
brace_depth -= 1;
if brace_depth == 0 {
break;
}
content.push(ch);
} else {
content.push(ch);
}
}
// Skip past the exegesis content in the lexer
// We need to advance until we find the matching closing brace
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof {
self.advance();
}
if self.current.kind == TokenKind::RightBrace {
self.advance();
}
Ok(content.trim().to_string())
}
/// Parses an optional inline exegesis block (DOL 2.0 style).
/// Returns None if no exegesis is present.
fn parse_inline_exegesis(&mut self) -> Result<Option<String>, ParseError> {
if self.current.kind != TokenKind::Exegesis && self.current.kind != TokenKind::Docs {
return Ok(None);
}
self.advance(); // consume 'exegesis' or 'docs'
self.expect(TokenKind::LeftBrace)?;
// Collect all text until closing brace
let mut content = String::new();
let mut brace_depth = 1;
let start_pos = self.current.span.start;
let source_after_brace = &self.lexer_source()[start_pos..];
for ch in source_after_brace.chars() {
if ch == '{' {
brace_depth += 1;
content.push(ch);
} else if ch == '}' {
brace_depth -= 1;
if brace_depth == 0 {
break;
}
content.push(ch);
} else {
content.push(ch);
}
}
// Skip past the exegesis content in the lexer
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof {
self.advance();
}
if self.current.kind == TokenKind::RightBrace {
self.advance();
}
Ok(Some(content.trim().to_string()))
}
// === DOL 2.0 Expression Parsing ===
/// Parses an expression using Pratt parsing for operator precedence.
///
/// # Arguments
///
/// * `min_bp` - Minimum binding power for this expression context
///
/// # Returns
///
/// The parsed expression on success, or a ParseError on failure.
pub fn parse_expr(&mut self, min_bp: u8) -> Result<Expr, ParseError> {
// Parse prefix or atom
let mut lhs = self.parse_prefix_or_atom()?;
// Parse infix operators with binding power
loop {
// Special case: member access (.) should only consume an identifier
if self.current.kind == TokenKind::Dot {
self.advance();
let field = self.expect_identifier()?;
// Check if this is a struct literal: Type.Variant { ... }
// Only treat as struct literal if:
// 1. The field starts with uppercase (type name convention)
// 2. The content looks like struct fields (identifier: value or empty)
let is_type_name = field.chars().next().is_some_and(|c| c.is_uppercase());
// Check if this is a struct literal: Type.Variant { ... }
// A struct literal has fields in the form `identifier: value`
// Use two-token lookahead to check for `{ identifier :` pattern
let is_struct_literal = self.current.kind == TokenKind::LeftBrace
&& is_type_name
&& (self.peek().kind == TokenKind::RightBrace
|| (Self::is_identifier_like(self.peek().kind)
&& self.peek2().kind == TokenKind::Colon));
if is_struct_literal {
// This is a struct literal like Type.Variant { field: value }
// Combine the lhs and field into a path name
let path_name = match &lhs {
Expr::Identifier(name) => format!("{}.{}", name, field),
Expr::Member { object, field: f } => {
if let Expr::Identifier(name) = object.as_ref() {
format!("{}.{}.{}", name, f, field)
} else {
field.clone()
}
}
_ => field.clone(),
};
self.advance(); // consume '{'
let mut fields = Vec::new();
while self.current.kind != TokenKind::RightBrace
&& self.current.kind != TokenKind::Eof
{
// Allow keywords as struct field names (e.g., uses, module, etc.)
let field_name = self.expect_identifier_or_keyword()?;
self.expect(TokenKind::Colon)?;
let value = self.parse_expr(0)?;
fields.push((field_name, value));
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightBrace)?;
// Create struct literal expression
lhs = Expr::StructLiteral {
type_name: path_name,
fields,
};
} else {
lhs = Expr::Member {
object: Box::new(lhs),
field,
};
}
continue;
}
// Check for infix operators (excluding Dot which is handled above)
if let Some((left_bp, _right_bp)) = infix_binding_power(&self.current.kind) {
if self.current.kind == TokenKind::Dot {
// Already handled above
break;
}
if left_bp < min_bp {
break;
}
let op = self.current.kind;
self.advance();
// Special handling for `as` - it takes a type, not an expression
if op == TokenKind::As {
let target_type = self.parse_type()?;
lhs = Expr::Cast {
expr: Box::new(lhs),
target_type,
};
} else {
let rhs = self.parse_expr(_right_bp)?;
lhs = self.make_binary_expr(lhs, op, rhs)?;
}
} else if self.current.kind == TokenKind::LeftParen {
// Function call
self.advance();
let mut args = Vec::new();
while self.current.kind != TokenKind::RightParen
&& self.current.kind != TokenKind::Eof
{
args.push(self.parse_expr(0)?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
lhs = Expr::Call {
callee: Box::new(lhs),
args,
};
} else if self.current.kind == TokenKind::LeftBracket {
// Array indexing (parsed as function call for now)
self.advance();
let index = self.parse_expr(0)?;
self.expect(TokenKind::RightBracket)?;
lhs = Expr::Call {
callee: Box::new(lhs),
args: vec![index],
};
} else if self.current.kind == TokenKind::Reflect {
// Postfix `?` - try operator for error propagation
self.advance();
lhs = Expr::Try(Box::new(lhs));
} else if self.current.kind == TokenKind::LeftBrace {
// Struct literal without path: Identifier { field: value }
// Only treat as struct literal if:
// 1. The name starts with uppercase (type name convention)
// 2. The content looks like struct fields (identifier: value or empty)
if let Expr::Identifier(name) = &lhs {
let is_type_name = name.chars().next().is_some_and(|c| c.is_uppercase());
if !is_type_name {
break;
}
// Use two-token lookahead to check for struct literal pattern
// - Empty: `Foo {}` - next token is `}`
// - With fields: `Foo { x: y }` - next is identifier or keyword, then `:`
let is_struct_literal = self.peek().kind == TokenKind::RightBrace
|| (Self::is_identifier_like(self.peek().kind)
&& self.peek2().kind == TokenKind::Colon);
if !is_struct_literal {
// Not a struct literal, likely a block like `if x != None { ... }`
break;
}
let struct_name = name.clone();
self.advance(); // consume '{'
let mut fields = Vec::new();
while self.current.kind != TokenKind::RightBrace
&& self.current.kind != TokenKind::Eof
{
// Allow keywords as struct field names (e.g., uses, module, etc.)
let field_name = self.expect_identifier_or_keyword()?;
self.expect(TokenKind::Colon)?;
let value = self.parse_expr(0)?;
fields.push((field_name, value));
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightBrace)?;
// Create struct literal expression
lhs = Expr::StructLiteral {
type_name: struct_name,
fields,
};
} else {
break;
}
} else {
break;
}
}
Ok(lhs)
}
/// Parses prefix operators and atomic expressions.
fn parse_prefix_or_atom(&mut self) -> Result<Expr, ParseError> {
// Special case for Bang: check if it's eval (!{...}) or logical not (!expr)
if self.current.kind == TokenKind::Bang {
self.advance();
if self.current.kind == TokenKind::LeftBrace {
// Eval: !{ expr }
self.advance();
let expr = self.parse_expr(0)?;
self.expect(TokenKind::RightBrace)?;
return Ok(Expr::Eval(Box::new(expr)));
} else {
// Logical not: !expr
let bp = prefix_binding_power(&TokenKind::Bang).unwrap();
let operand = self.parse_expr(bp)?;
return Ok(Expr::Unary {
op: UnaryOp::Not,
operand: Box::new(operand),
});
}
}
// Check for QuasiQuote (double quote: ''expr)
if self.current.kind == TokenKind::Quote {
self.advance();
// Check if the next token is also a quote
if self.current.kind == TokenKind::Quote {
self.advance();
// This is a quasi-quote
let bp = prefix_binding_power(&TokenKind::Quote).unwrap();
let operand = self.parse_expr(bp)?;
return Ok(Expr::QuasiQuote(Box::new(operand)));
} else {
// Single quote - regular quote
let bp = prefix_binding_power(&TokenKind::Quote).unwrap();
let operand = self.parse_expr(bp)?;
return Ok(Expr::Quote(Box::new(operand)));
}
}
// Check for other prefix operators
if let Some(bp) = prefix_binding_power(&self.current.kind) {
let op = self.current.kind;
self.advance();
let operand = self.parse_expr(bp)?;
return self.make_unary_expr(op, operand);
}
// Parse atoms
match self.current.kind {
// Self-reference: this
TokenKind::This => {
self.advance();
Ok(Expr::This)
}
// Literals
TokenKind::String => {
let value = self.current.lexeme.clone();
self.advance();
Ok(Expr::Literal(Literal::String(value)))
}
TokenKind::Char => {
let value = self.current.lexeme.chars().next().unwrap_or('\0');
self.advance();
Ok(Expr::Literal(Literal::Char(value)))
}
TokenKind::Identifier => {
let mut name = self.current.lexeme.clone();
self.advance();
// Check for special boolean literals
if name == "true" {
return Ok(Expr::Literal(Literal::Bool(true)));
} else if name == "false" {
return Ok(Expr::Literal(Literal::Bool(false)));
}
// Check for numeric literals (lexer sends them as identifiers)
if let Ok(int_val) = name.parse::<i64>() {
return Ok(Expr::Literal(Literal::Int(int_val)));
}
if let Ok(float_val) = name.parse::<f64>() {
return Ok(Expr::Literal(Literal::Float(float_val)));
}
// Handle path expressions like Map::new, Type::Variant
while self.current.kind == TokenKind::PathSep {
self.advance(); // consume ::
if self.current.kind == TokenKind::Identifier {
name.push_str("::");
name.push_str(&self.current.lexeme);
self.advance();
} else {
break;
}
}
Ok(Expr::Identifier(name))
}
// Allow DOL keywords to be used as identifiers in expression context
TokenKind::Gene
| TokenKind::Trait
| TokenKind::System
| TokenKind::Constraint
| TokenKind::Rule
| TokenKind::Evolves
| TokenKind::Exegesis
| TokenKind::Test
| TokenKind::Law
| TokenKind::State
| TokenKind::Module
| TokenKind::Use
// v0.3.0 keywords that may appear as identifiers
| TokenKind::Type
| TokenKind::Val
| TokenKind::Extends
// Type keywords for referencing type enum variants
| TokenKind::Int8
| TokenKind::Int16
| TokenKind::Int32
| TokenKind::Int64
| TokenKind::UInt8
| TokenKind::UInt16
| TokenKind::UInt32
| TokenKind::UInt64
| TokenKind::Float32
| TokenKind::Float64
| TokenKind::BoolType
| TokenKind::StringType
| TokenKind::VoidType => {
let mut name = self.current.lexeme.clone();
self.advance();
// Handle path expressions like Type::Variant
while self.current.kind == TokenKind::PathSep {
self.advance(); // consume ::
if self.current.kind == TokenKind::Identifier {
name.push_str("::");
name.push_str(&self.current.lexeme);
self.advance();
} else {
break;
}
}
Ok(Expr::Identifier(name))
}
// Parenthesized expression or tuple
TokenKind::LeftParen => {
self.advance();
// Empty tuple: ()
if self.current.kind == TokenKind::RightParen {
self.advance();
return Ok(Expr::Tuple(vec![]));
}
let first = self.parse_expr(0)?;
// Check for tuple (comma separated)
if self.current.kind == TokenKind::Comma {
let mut elements = vec![first];
while self.current.kind == TokenKind::Comma {
self.advance();
if self.current.kind == TokenKind::RightParen {
break; // Trailing comma
}
elements.push(self.parse_expr(0)?);
}
self.expect(TokenKind::RightParen)?;
Ok(Expr::Tuple(elements))
} else {
// Simple parenthesized expression
self.expect(TokenKind::RightParen)?;
Ok(first)
}
}
// Lambda expression: |params| body
TokenKind::Bar => self.parse_lambda(),
// If expression
TokenKind::If => self.parse_if_expr(),
// Match expression
TokenKind::Match => self.parse_match_expr(),
// Forall quantifier expression (v0.3.0)
// Syntax 1: forall x: T. expr (first-order logic style)
// Syntax 2: forall x in iter { body } (iterator style)
TokenKind::Forall => self.parse_forall_expr(),
// Block expression
TokenKind::LeftBrace => self.parse_block_expr(),
// Sex block expression
TokenKind::Sex => self.parse_sex_block(),
// Eval or logical not: handled by prefix operators
// Type reflection: ?TypeName
TokenKind::Reflect => {
self.advance();
let type_expr = self.parse_type()?;
Ok(Expr::Reflect(Box::new(type_expr)))
}
// Macro invocation: #macro_name(args)
TokenKind::Macro => self.parse_macro_invocation_expr(),
// Idiom brackets: [| f a b |]
TokenKind::IdiomOpen => self.parse_idiom_bracket(),
// Boolean literals
TokenKind::True => {
self.advance();
Ok(Expr::Literal(Literal::Bool(true)))
}
TokenKind::False => {
self.advance();
Ok(Expr::Literal(Literal::Bool(false)))
}
// Null literal
TokenKind::Null => {
self.advance();
Ok(Expr::Literal(Literal::Null))
}
// List literal: [] or [expr, expr, ...]
TokenKind::LeftBracket => {
self.advance();
let mut elements = Vec::new();
while self.current.kind != TokenKind::RightBracket
&& self.current.kind != TokenKind::Eof
{
elements.push(self.parse_expr(0)?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightBracket)?;
Ok(Expr::List(elements))
}
// Control flow as expressions (for use in match arms)
TokenKind::Break => {
self.advance();
Ok(Expr::Block(Block {
statements: vec![Stmt::Break],
final_expr: None,
span: self.previous.span,
}))
}
TokenKind::Continue => {
self.advance();
Ok(Expr::Block(Block {
statements: vec![Stmt::Continue],
final_expr: None,
span: self.previous.span,
}))
}
TokenKind::Return => {
self.advance();
let start_span = self.previous.span;
// Check if there's a return value
let value = if self.current.kind != TokenKind::RightBrace
&& self.current.kind != TokenKind::Comma
&& self.current.kind != TokenKind::Eof
&& !matches!(
self.current.kind,
TokenKind::RightParen | TokenKind::RightBracket
)
{
Some(self.parse_expr(0)?)
} else {
None
};
Ok(Expr::Block(Block {
statements: vec![Stmt::Return(value)],
final_expr: None,
span: start_span,
}))
}
_ => Err(ParseError::UnexpectedToken {
expected: "expression".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
}),
}
}
/// Creates a binary expression from operator token.
fn make_binary_expr(
&self,
left: Expr,
op_token: TokenKind,
right: Expr,
) -> Result<Expr, ParseError> {
let op = match op_token {
TokenKind::Plus => BinaryOp::Add,
TokenKind::Minus => BinaryOp::Sub,
TokenKind::Star => BinaryOp::Mul,
TokenKind::Slash => BinaryOp::Div,
TokenKind::Percent => BinaryOp::Mod,
TokenKind::Caret => BinaryOp::Pow,
TokenKind::Eq => BinaryOp::Eq,
TokenKind::Ne => BinaryOp::Ne,
TokenKind::Lt => BinaryOp::Lt,
TokenKind::Le => BinaryOp::Le,
TokenKind::Greater => BinaryOp::Gt,
TokenKind::GreaterEqual => BinaryOp::Ge,
TokenKind::And => BinaryOp::And,
TokenKind::Or => BinaryOp::Or,
TokenKind::Pipe => BinaryOp::Pipe,
TokenKind::Compose => BinaryOp::Compose,
TokenKind::At => BinaryOp::Apply,
TokenKind::Bind => BinaryOp::Bind,
TokenKind::Dot => BinaryOp::Member,
TokenKind::DotDot => BinaryOp::Range,
_ => {
return Err(ParseError::InvalidStatement {
message: format!("invalid binary operator: {:?}", op_token),
span: self.current.span,
})
}
};
Ok(Expr::Binary {
left: Box::new(left),
op,
right: Box::new(right),
})
}
/// Creates a unary expression from operator token.
fn make_unary_expr(&self, op_token: TokenKind, operand: Expr) -> Result<Expr, ParseError> {
match op_token {
TokenKind::Minus => Ok(Expr::Unary {
op: UnaryOp::Neg,
operand: Box::new(operand),
}),
TokenKind::Bang => Ok(Expr::Unary {
op: UnaryOp::Not,
operand: Box::new(operand),
}),
TokenKind::Quote => Ok(Expr::Quote(Box::new(operand))),
TokenKind::Reflect => Ok(Expr::Unary {
op: UnaryOp::Reflect,
operand: Box::new(operand),
}),
TokenKind::Comma => {
// Comma as unquote operator (,expr)
Ok(Expr::Unquote(Box::new(operand)))
}
TokenKind::Star => Ok(Expr::Unary {
op: UnaryOp::Deref,
operand: Box::new(operand),
}),
_ => Err(ParseError::InvalidStatement {
message: format!("invalid unary operator: {:?}", op_token),
span: self.current.span,
}),
}
}
/// Parses a lambda expression: |params| body
fn parse_lambda(&mut self) -> Result<Expr, ParseError> {
self.expect(TokenKind::Bar)?;
let mut params = Vec::new();
while self.current.kind != TokenKind::Bar && self.current.kind != TokenKind::Eof {
let name = self.expect_identifier()?;
let type_ann = if self.current.kind == TokenKind::Colon {
self.advance();
Some(self.parse_type()?)
} else {
None
};
params.push((name, type_ann));
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::Bar)?;
let return_type = if self.current.kind == TokenKind::Arrow {
self.advance();
Some(self.parse_type()?)
} else {
None
};
let body = Box::new(self.parse_expr(0)?);
Ok(Expr::Lambda {
params,
return_type,
body,
})
}
/// Parses an if expression: if condition { then } else { else }
fn parse_if_expr(&mut self) -> Result<Expr, ParseError> {
self.expect(TokenKind::If)?;
let condition = Box::new(self.parse_expr(0)?);
self.expect(TokenKind::LeftBrace)?;
let then_branch = Box::new(self.parse_block_expr_inner()?);
self.expect(TokenKind::RightBrace)?;
let else_branch = if self.current.kind == TokenKind::Else {
self.advance();
if self.current.kind == TokenKind::If {
// else if
Some(Box::new(self.parse_if_expr()?))
} else {
self.expect(TokenKind::LeftBrace)?;
let else_expr = Box::new(self.parse_block_expr_inner()?);
self.expect(TokenKind::RightBrace)?;
Some(else_expr)
}
} else {
None
};
Ok(Expr::If {
condition,
then_branch,
else_branch,
})
}
/// Parses a match expression.
fn parse_match_expr(&mut self) -> Result<Expr, ParseError> {
self.expect(TokenKind::Match)?;
let scrutinee = Box::new(self.parse_expr(0)?);
self.expect(TokenKind::LeftBrace)?;
let mut arms = Vec::new();
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof {
// Parse first pattern
let first_pattern = self.parse_pattern()?;
// Check for or-patterns (pattern | pattern | ...)
let pattern = if self.current.kind == TokenKind::Bar {
let mut patterns = vec![first_pattern];
while self.current.kind == TokenKind::Bar {
self.advance();
patterns.push(self.parse_pattern()?);
}
Pattern::Or(patterns)
} else {
first_pattern
};
let guard = if self.current.kind == TokenKind::If {
self.advance();
Some(Box::new(self.parse_expr(0)?))
} else {
None
};
// Support both `pattern => body` and `pattern { body }` syntax
let body = if self.current.kind == TokenKind::FatArrow {
self.advance();
Box::new(self.parse_expr(0)?)
} else if self.current.kind == TokenKind::LeftBrace {
// Parse block expression for brace syntax
Box::new(self.parse_block_expr()?)
} else {
return Err(ParseError::UnexpectedToken {
expected: "'=>' or '{'".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
};
arms.push(MatchArm {
pattern,
guard,
body,
});
if self.current.kind == TokenKind::Comma {
self.advance();
}
}
self.expect(TokenKind::RightBrace)?;
Ok(Expr::Match { scrutinee, arms })
}
/// Parses a forall quantifier expression (v0.3.0).
///
/// Supports two syntaxes:
/// - `forall x: T. expr` - First-order logic style with type annotation
/// - `forall x in iter { body }` - Iterator style for collections
fn parse_forall_expr(&mut self) -> Result<Expr, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Forall)?;
let var = self.expect_identifier()?;
// Check for type-annotated syntax: forall x: T. expr
if self.current.kind == TokenKind::Colon {
self.advance();
let type_ = self.parse_type()?;
// Expect dot separator for the body
self.expect(TokenKind::Dot)?;
let body = self.parse_expr(0)?;
let span = start_span.merge(&self.previous.span);
Ok(Expr::Forall(ForallExpr {
var,
type_,
body: Box::new(body),
span,
}))
} else if self.current.kind == TokenKind::In {
// Iterator syntax: forall x in iter { body }
self.advance();
let iter = self.parse_expr(0)?;
self.expect(TokenKind::LeftBrace)?;
let mut statements = Vec::new();
let mut final_expr = None;
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof
{
if self.is_statement_keyword() {
statements.push(self.parse_stmt()?);
} else {
let expr = self.parse_expr(0)?;
// Check if this is the final expression or needs to be a statement
if self.current.kind == TokenKind::Semicolon {
self.advance();
statements.push(Stmt::Expr(expr));
} else if self.current.kind == TokenKind::RightBrace {
final_expr = Some(expr);
} else {
statements.push(Stmt::Expr(expr));
}
}
}
self.expect(TokenKind::RightBrace)?;
let span = start_span.merge(&self.previous.span);
// For iterator-style forall, wrap in a Block that represents the comprehension
// Use a synthetic Inferred type since we don't know the element type statically
let body = Expr::Block(Block {
statements,
final_expr: final_expr.map(Box::new),
span: Span::default(),
});
// Create a ForallExpr using a placeholder type to indicate iterator-style
// The underscore "_" indicates the type should be inferred from the iterator
Ok(Expr::Forall(ForallExpr {
var,
type_: TypeExpr::Named("_".to_string()),
body: Box::new(Expr::Binary {
left: Box::new(iter),
op: BinaryOp::Member,
right: Box::new(body),
}),
span,
}))
} else {
Err(ParseError::UnexpectedToken {
expected: ": or in".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
})
}
}
/// Parses a pattern for match expressions.
pub fn parse_pattern(&mut self) -> Result<Pattern, ParseError> {
match self.current.kind {
TokenKind::Underscore => {
self.advance();
Ok(Pattern::Wildcard)
}
TokenKind::String => {
let value = self.current.lexeme.clone();
self.advance();
Ok(Pattern::Literal(Literal::String(value)))
}
TokenKind::Char => {
let value = self.current.lexeme.chars().next().unwrap_or('\0');
self.advance();
Ok(Pattern::Literal(Literal::Char(value)))
}
// Allow DOL keywords to be used as pattern identifiers
TokenKind::Gene
| TokenKind::Trait
| TokenKind::System
| TokenKind::Constraint
| TokenKind::Rule
| TokenKind::Evolves
| TokenKind::Exegesis
| TokenKind::Test
| TokenKind::Law
| TokenKind::State
| TokenKind::Module
| TokenKind::Use
// Type keywords for matching type enum variants
| TokenKind::Int8
| TokenKind::Int16
| TokenKind::Int32
| TokenKind::Int64
| TokenKind::UInt8
| TokenKind::UInt16
| TokenKind::UInt32
| TokenKind::UInt64
| TokenKind::Float32
| TokenKind::Float64
| TokenKind::BoolType
| TokenKind::StringType
| TokenKind::VoidType
// v0.3.0 keywords that may appear as identifiers in patterns
| TokenKind::Type
| TokenKind::Val
| TokenKind::Extends
| TokenKind::Forall => {
let name = self.current.lexeme.clone();
self.advance();
Ok(Pattern::Identifier(name))
}
TokenKind::Identifier => {
let mut name = self.current.lexeme.clone();
self.advance();
// Handle path patterns like `Statement.Matches`
while self.current.kind == TokenKind::Dot {
self.advance();
let part = self.expect_identifier()?;
name = format!("{}.{}", name, part);
}
// Check for constructor pattern with tuple args: `Some(x)`
if self.current.kind == TokenKind::LeftParen {
self.advance();
let mut fields = Vec::new();
while self.current.kind != TokenKind::RightParen
&& self.current.kind != TokenKind::Eof
{
fields.push(self.parse_pattern()?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
Ok(Pattern::Constructor { name, fields })
}
// Check for struct destructuring pattern: `Foo { field: binding, field2 }`
// Must distinguish from match arm body `Foo { stmt; }`.
// Struct patterns have: `{ ident: binding }`, `{ ident, ident2 }`, etc.
// Match arm bodies have: `{ expr.method() }`, `{ func() }`, `{ 0 }`, `{ None }`, etc.
//
// The heuristic for single-field patterns like `Foo { bar }`:
// - If followed by another `{` (like `Foo { bar } { body }`), it's a struct pattern
// - If followed by `:` or `,` in the braces, it's definitely a struct pattern
// - Otherwise, it's ambiguous and we treat it as NOT a struct pattern
// (to avoid misinterpreting `None { x }` as struct pattern when it's a match arm)
else if self.current.kind == TokenKind::LeftBrace
&& self.peek().kind == TokenKind::Identifier
&& !self.peek().lexeme.contains('.')
&& !self.peek().lexeme.chars().next().is_some_and(|c| c.is_ascii_digit())
&& (matches!(self.peek2().kind, TokenKind::Colon | TokenKind::Comma)
|| (self.peek2().kind == TokenKind::RightBrace
&& self.peek3().kind == TokenKind::LeftBrace))
{
self.advance();
let mut fields = Vec::new();
while self.current.kind != TokenKind::RightBrace
&& self.current.kind != TokenKind::Eof
{
// Parse field name
let field_name = self.expect_identifier()?;
// Check for field rename pattern: `field: pattern`
if self.current.kind == TokenKind::Colon {
self.advance();
let pattern = self.parse_pattern()?;
// Store as a nested pattern with the field name
fields.push(Pattern::Constructor {
name: field_name,
fields: vec![pattern],
});
} else {
// Simple field binding: `field` (shorthand for `field: field`)
fields.push(Pattern::Identifier(field_name));
}
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightBrace)?;
// Use Constructor pattern with the struct name and field patterns
Ok(Pattern::Constructor { name, fields })
} else if name == "true" {
Ok(Pattern::Literal(Literal::Bool(true)))
} else if name == "false" {
Ok(Pattern::Literal(Literal::Bool(false)))
} else if let Ok(int_val) = name.parse::<i64>() {
// Numeric pattern (lexer sends numbers as identifiers)
Ok(Pattern::Literal(Literal::Int(int_val)))
} else if let Ok(float_val) = name.parse::<f64>() {
Ok(Pattern::Literal(Literal::Float(float_val)))
} else {
Ok(Pattern::Identifier(name))
}
}
TokenKind::LeftParen => {
self.advance();
let mut patterns = Vec::new();
while self.current.kind != TokenKind::RightParen
&& self.current.kind != TokenKind::Eof
{
patterns.push(self.parse_pattern()?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
Ok(Pattern::Tuple(patterns))
}
_ => Err(ParseError::UnexpectedToken {
expected: "pattern".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
}),
}
}
/// Parses a block expression: { statements; final_expr }
fn parse_block_expr(&mut self) -> Result<Expr, ParseError> {
self.expect(TokenKind::LeftBrace)?;
let expr = self.parse_block_expr_inner()?;
self.expect(TokenKind::RightBrace)?;
Ok(expr)
}
/// Parses a sex block expression: sex { statements }
fn parse_sex_block(&mut self) -> Result<Expr, ParseError> {
self.expect(TokenKind::Sex)?;
self.expect(TokenKind::LeftBrace)?;
let mut statements = Vec::new();
let mut final_expr = None;
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof {
// Check if this is a statement or final expression
if self.is_statement_keyword() {
statements.push(self.parse_stmt()?);
} else {
// Try to parse as expression
let expr = self.parse_expr(0)?;
// If followed by semicolon, it's a statement
if self.current.kind == TokenKind::Semicolon {
self.advance();
statements.push(Stmt::Expr(expr));
} else {
// It's the final expression
final_expr = Some(Box::new(expr));
break;
}
}
}
self.expect(TokenKind::RightBrace)?;
Ok(Expr::SexBlock(Block {
statements,
final_expr,
span: Span::default(),
}))
}
/// Parses the interior of a block expression (without braces).
fn parse_block_expr_inner(&mut self) -> Result<Expr, ParseError> {
let mut statements = Vec::new();
let mut final_expr = None;
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof {
// Check if this is a statement or final expression
if self.is_statement_keyword() {
statements.push(self.parse_stmt()?);
} else {
// Try to parse as expression, then check if it's an assignment
let expr = self.parse_expr(0)?;
// Check for assignment (e.g., a.b = expr)
if self.current.kind == TokenKind::Equal {
self.advance(); // consume '='
let value = self.parse_expr(0)?;
self.consume_optional_semicolon();
statements.push(Stmt::Assign {
target: expr,
value,
});
} else if self.current.kind == TokenKind::Semicolon {
// It's an expression statement
self.advance();
statements.push(Stmt::Expr(expr));
} else if self.current.kind == TokenKind::RightBrace
|| self.current.kind == TokenKind::Eof
{
// It's the final expression (no semicolon needed before })
final_expr = Some(Box::new(expr));
break;
} else {
// Assume it's a statement without semicolon (DOL style)
statements.push(Stmt::Expr(expr));
}
}
}
Ok(Expr::Block(Block {
statements,
final_expr,
span: Span::default(),
}))
}
/// Checks if a token kind can be used as an identifier (for struct field names, etc.)
fn is_identifier_like(kind: TokenKind) -> bool {
matches!(
kind,
TokenKind::Identifier
| TokenKind::Gene
| TokenKind::Trait
| TokenKind::System
| TokenKind::Constraint
| TokenKind::Rule
| TokenKind::Evolves
| TokenKind::Exegesis
| TokenKind::Test
| TokenKind::Law
| TokenKind::State
| TokenKind::Module
| TokenKind::Use
| TokenKind::Uses
| TokenKind::Migrate
| TokenKind::Pub
| TokenKind::Has
| TokenKind::Is
| TokenKind::Requires
| TokenKind::Var
| TokenKind::Let
| TokenKind::Function
| TokenKind::Return
| TokenKind::If
| TokenKind::Else
| TokenKind::Match
| TokenKind::For
| TokenKind::While
| TokenKind::Loop
| TokenKind::In
| TokenKind::Break
| TokenKind::Continue
| TokenKind::Where
| TokenKind::True
| TokenKind::False
| TokenKind::From
| TokenKind::Int8
| TokenKind::Int16
| TokenKind::Int32
| TokenKind::Int64
| TokenKind::UInt8
| TokenKind::UInt16
| TokenKind::UInt32
| TokenKind::UInt64
| TokenKind::Float32
| TokenKind::Float64
| TokenKind::BoolType
| TokenKind::StringType
| TokenKind::VoidType
| TokenKind::Type
| TokenKind::Val
| TokenKind::Extends
| TokenKind::Forall
)
}
/// Checks if the current token is a statement keyword.
fn is_statement_keyword(&self) -> bool {
matches!(
self.current.kind,
TokenKind::Let
| TokenKind::Val
| TokenKind::Var
| TokenKind::Const
| TokenKind::For
| TokenKind::While
| TokenKind::Loop
| TokenKind::Break
| TokenKind::Continue
| TokenKind::Return
| TokenKind::Sex
)
}
/// Parses a statement.
/// Consume a semicolon if present (DOL makes semicolons optional)
fn consume_optional_semicolon(&mut self) {
if self.current.kind == TokenKind::Semicolon {
self.advance();
}
}
/// Parses a single statement.
pub fn parse_stmt(&mut self) -> Result<Stmt, ParseError> {
match self.current.kind {
TokenKind::Let => {
self.advance();
// Support `let _ = ...` discard pattern
let name = if self.current.kind == TokenKind::Underscore {
self.advance();
"_".to_string()
} else {
// Allow keywords as variable names (e.g., let exegesis = ...)
self.expect_identifier_or_keyword()?
};
let type_ann = if self.current.kind == TokenKind::Colon {
self.advance();
Some(self.parse_type()?)
} else {
None
};
// Value is optional if type annotation is provided (uninitialized declaration)
let value = if self.current.kind == TokenKind::Equal {
self.advance();
self.parse_expr(0)?
} else if type_ann.is_some() {
// Use a placeholder for uninitialized declarations with type annotations
// This will be generated as `let name: Type;` in Rust
Expr::Identifier("__uninitialized__".to_string())
} else {
return Err(ParseError::UnexpectedToken {
expected: "= or type annotation".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
};
self.consume_optional_semicolon();
Ok(Stmt::Let {
name,
type_ann,
value,
})
}
// val x: Type = expr (immutable binding, v0.3.0)
TokenKind::Val => {
self.advance();
// Support `val _ = ...` discard pattern
let name = if self.current.kind == TokenKind::Underscore {
self.advance();
"_".to_string()
} else {
self.expect_identifier_or_keyword()?
};
let type_ann = if self.current.kind == TokenKind::Colon {
self.advance();
Some(self.parse_type()?)
} else {
None
};
// Value is optional if type annotation is provided
let value = if self.current.kind == TokenKind::Equal {
self.advance();
self.parse_expr(0)?
} else if type_ann.is_some() {
Expr::Identifier("__uninitialized__".to_string())
} else {
return Err(ParseError::UnexpectedToken {
expected: "= or type annotation".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
});
};
self.consume_optional_semicolon();
// val is semantically equivalent to let (immutable)
Ok(Stmt::Let {
name,
type_ann,
value,
})
}
TokenKind::Var => {
self.advance();
let name = self.expect_identifier()?;
let type_ann = if self.current.kind == TokenKind::Colon {
self.advance();
Some(self.parse_type()?)
} else {
None
};
self.expect(TokenKind::Equal)?;
let value = self.parse_expr(0)?;
self.consume_optional_semicolon();
Ok(Stmt::Let {
name,
type_ann,
value,
})
}
TokenKind::Const => {
self.advance();
let name = self.expect_identifier()?;
let type_ann = if self.current.kind == TokenKind::Colon {
self.advance();
Some(self.parse_type()?)
} else {
None
};
self.expect(TokenKind::Equal)?;
let value = self.parse_expr(0)?;
self.consume_optional_semicolon();
Ok(Stmt::Let {
name,
type_ann,
value,
})
}
TokenKind::Sex => {
// Parse as expression (sex block)
let expr = self.parse_expr(0)?;
self.consume_optional_semicolon();
Ok(Stmt::Expr(expr))
}
TokenKind::For => self.parse_for_stmt(),
TokenKind::While => self.parse_while_stmt(),
TokenKind::Loop => self.parse_loop_stmt(),
TokenKind::Break => {
self.advance();
self.consume_optional_semicolon();
Ok(Stmt::Break)
}
TokenKind::Continue => {
self.advance();
self.consume_optional_semicolon();
Ok(Stmt::Continue)
}
TokenKind::Return => {
self.advance();
let value = if self.current.kind != TokenKind::Semicolon
&& self.current.kind != TokenKind::RightBrace
&& self.current.kind != TokenKind::Eof
{
Some(self.parse_expr(0)?)
} else {
None
};
self.consume_optional_semicolon();
Ok(Stmt::Return(value))
}
_ => {
// Try to parse as simple assignment (identifier = expr) first
// This handles DOL's simple assignment syntax without 'let'
// Use peek() to avoid consuming tokens we can't restore
if self.current.kind == TokenKind::Identifier
&& self.peek().kind == TokenKind::Equal
{
let name = self.expect_identifier()?;
self.advance(); // consume '='
let value = self.parse_expr(0)?;
self.consume_optional_semicolon();
return Ok(Stmt::Assign {
target: Expr::Identifier(name),
value,
});
}
let expr = self.parse_expr(0)?;
// Check for assignment after expression (e.g., a.b = expr or a[i] = expr)
if self.current.kind == TokenKind::Equal {
self.advance(); // consume '='
let value = self.parse_expr(0)?;
self.consume_optional_semicolon();
return Ok(Stmt::Assign {
target: expr,
value,
});
}
self.consume_optional_semicolon();
Ok(Stmt::Expr(expr))
}
}
}
/// Parses a for loop statement.
fn parse_for_stmt(&mut self) -> Result<Stmt, ParseError> {
self.expect(TokenKind::For)?;
// Allow DOL keywords as loop variable names (e.g., `for law in laws`)
let binding = self.expect_identifier_or_keyword()?;
self.expect(TokenKind::In)?;
let iterable = self.parse_expr(0)?;
self.expect(TokenKind::LeftBrace)?;
let mut body = Vec::new();
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof {
body.push(self.parse_stmt()?);
}
self.expect(TokenKind::RightBrace)?;
Ok(Stmt::For {
binding,
iterable,
body,
})
}
/// Parses a while loop statement.
fn parse_while_stmt(&mut self) -> Result<Stmt, ParseError> {
self.expect(TokenKind::While)?;
let condition = self.parse_expr(0)?;
self.expect(TokenKind::LeftBrace)?;
let mut body = Vec::new();
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof {
body.push(self.parse_stmt()?);
}
self.expect(TokenKind::RightBrace)?;
Ok(Stmt::While { condition, body })
}
/// Parses a loop statement.
fn parse_loop_stmt(&mut self) -> Result<Stmt, ParseError> {
self.expect(TokenKind::Loop)?;
self.expect(TokenKind::LeftBrace)?;
let mut body = Vec::new();
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof {
body.push(self.parse_stmt()?);
}
self.expect(TokenKind::RightBrace)?;
Ok(Stmt::Loop { body })
}
/// Parses a type expression.
pub fn parse_type(&mut self) -> Result<TypeExpr, ParseError> {
// Handle built-in type keywords
let base_type = match self.current.kind {
// v0.8.0 NEW type keywords (lowercase)
TokenKind::I8 => {
self.advance();
TypeExpr::Named("i8".to_string())
}
TokenKind::I16 => {
self.advance();
TypeExpr::Named("i16".to_string())
}
TokenKind::I32 => {
self.advance();
TypeExpr::Named("i32".to_string())
}
TokenKind::I64 => {
self.advance();
TypeExpr::Named("i64".to_string())
}
TokenKind::I128 => {
self.advance();
TypeExpr::Named("i128".to_string())
}
TokenKind::U8 => {
self.advance();
TypeExpr::Named("u8".to_string())
}
TokenKind::U16 => {
self.advance();
TypeExpr::Named("u16".to_string())
}
TokenKind::U32 => {
self.advance();
TypeExpr::Named("u32".to_string())
}
TokenKind::U64 => {
self.advance();
TypeExpr::Named("u64".to_string())
}
TokenKind::U128 => {
self.advance();
TypeExpr::Named("u128".to_string())
}
TokenKind::F32 => {
self.advance();
TypeExpr::Named("f32".to_string())
}
TokenKind::F64 => {
self.advance();
TypeExpr::Named("f64".to_string())
}
TokenKind::Bool => {
self.advance();
TypeExpr::Named("bool".to_string())
}
TokenKind::Str => {
self.advance();
TypeExpr::Named("string".to_string())
}
// DEPRECATED type keywords (uppercase) - emit warnings
TokenKind::Int8 => {
eprintln!("warning: 'Int8' type is deprecated in v0.8.0, use 'i8' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("i8".to_string())
}
TokenKind::Int16 => {
eprintln!("warning: 'Int16' type is deprecated in v0.8.0, use 'i16' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("i16".to_string())
}
TokenKind::Int32 => {
eprintln!("warning: 'Int32' type is deprecated in v0.8.0, use 'i32' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("i32".to_string())
}
TokenKind::Int64 => {
eprintln!("warning: 'Int64' type is deprecated in v0.8.0, use 'i64' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("i64".to_string())
}
TokenKind::UInt8 => {
eprintln!("warning: 'UInt8' type is deprecated in v0.8.0, use 'u8' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("u8".to_string())
}
TokenKind::UInt16 => {
eprintln!("warning: 'UInt16' type is deprecated in v0.8.0, use 'u16' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("u16".to_string())
}
TokenKind::UInt32 => {
eprintln!("warning: 'UInt32' type is deprecated in v0.8.0, use 'u32' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("u32".to_string())
}
TokenKind::UInt64 => {
eprintln!("warning: 'UInt64' type is deprecated in v0.8.0, use 'u64' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("u64".to_string())
}
TokenKind::Float32 => {
eprintln!("warning: 'Float32' type is deprecated in v0.8.0, use 'f32' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("f32".to_string())
}
TokenKind::Float64 => {
eprintln!("warning: 'Float64' type is deprecated in v0.8.0, use 'f64' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("f64".to_string())
}
TokenKind::BoolType => {
eprintln!("warning: 'Bool' type is deprecated in v0.8.0, use 'bool' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("bool".to_string())
}
TokenKind::StringType => {
eprintln!("warning: 'String' type is deprecated in v0.8.0, use 'string' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Named("string".to_string())
}
TokenKind::VoidType => {
eprintln!("warning: 'Void' type is deprecated in v0.8.0, use unit type '()' instead at line {}, column {}",
self.current.span.line, self.current.span.column);
self.advance();
TypeExpr::Tuple(Vec::new()) // Void maps to unit type
}
TokenKind::Bang => {
self.advance();
TypeExpr::Never
}
TokenKind::Identifier => {
let name = self.expect_identifier()?;
// Check for inline enum type: enum { A, B, C } or enum { A { x: Int }, B }
if name == "enum" && self.current.kind == TokenKind::LeftBrace {
self.advance(); // consume '{'
let mut variants = Vec::new();
while self.current.kind != TokenKind::RightBrace
&& self.current.kind != TokenKind::Eof
{
if self.current.kind == TokenKind::RightBrace {
break;
}
// Parse variant name (allow keywords as variant names)
let variant_name = self.expect_identifier_or_keyword()?;
let mut fields = Vec::new();
let mut tuple_types = Vec::new();
let mut discriminant = None;
// Check for tuple variant: Variant(T, U)
if self.current.kind == TokenKind::LeftParen {
self.advance(); // consume '('
while self.current.kind != TokenKind::RightParen
&& self.current.kind != TokenKind::Eof
{
tuple_types.push(self.parse_type()?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
}
// Check for struct fields: Variant { field: Type, ... }
else if self.current.kind == TokenKind::LeftBrace {
self.advance(); // consume '{'
while self.current.kind != TokenKind::RightBrace
&& self.current.kind != TokenKind::Eof
{
let field_name = self.expect_identifier_or_keyword()?;
self.expect(TokenKind::Colon)?;
let field_type = self.parse_type()?;
fields.push((field_name, field_type));
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightBrace)?;
}
// Check for discriminant value: Variant = 0
if self.current.kind == TokenKind::Equal {
self.advance(); // consume '='
// Numeric values are tokenized as Identifier
if let Ok(val) = self.current.lexeme.parse::<i64>() {
discriminant = Some(val);
}
self.advance();
}
variants.push(EnumVariant {
name: variant_name,
fields,
tuple_types,
discriminant,
});
// Skip comma if present
if self.current.kind == TokenKind::Comma {
self.advance();
}
}
self.expect(TokenKind::RightBrace)?;
TypeExpr::Enum { variants }
// Check for generic type
} else if self.current.kind == TokenKind::Lt {
// v0.8.0: Emit deprecation warnings for List and Optional
if name == "List" {
eprintln!("warning: 'List<T>' is deprecated in v0.8.0, use 'Vec<T>' instead at line {}, column {}",
self.previous.span.line, self.previous.span.column);
} else if name == "Optional" {
eprintln!("warning: 'Optional<T>' is deprecated in v0.8.0, use 'Option<T>' instead at line {}, column {}",
self.previous.span.line, self.previous.span.column);
}
self.advance();
let mut args = Vec::new();
// Also check for Compose (>>) which can occur in nested generics
while self.current.kind != TokenKind::Greater
&& self.current.kind != TokenKind::Compose
&& self.current.kind != TokenKind::Eof
{
args.push(self.parse_type()?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
// Use special method that handles >> splitting
self.expect_greater_in_type()?;
// Normalize deprecated type names in the AST
let normalized_name = if name == "List" {
"Vec"
} else if name == "Optional" {
"Option"
} else {
&name
};
TypeExpr::Generic {
name: normalized_name.to_string(),
args,
}
} else {
TypeExpr::Named(name)
}
}
TokenKind::LeftParen => {
self.advance();
let mut types = Vec::new();
while self.current.kind != TokenKind::RightParen
&& self.current.kind != TokenKind::Eof
{
types.push(self.parse_type()?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
// Check if it's a function type
if self.current.kind == TokenKind::Arrow {
self.advance();
let return_type = Box::new(self.parse_type()?);
TypeExpr::Function {
params: types,
return_type,
}
} else {
TypeExpr::Tuple(types)
}
}
_ => {
return Err(ParseError::UnexpectedToken {
expected: "type".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
})
}
};
Ok(base_type)
}
/// Parses a fun declaration (for DOL 2.0 gene/trait bodies).
fn parse_function_decl(&mut self) -> Result<FunctionDecl, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Function)?;
// Allow DOL keywords as function names (e.g., `fun test()`)
let name = self.expect_identifier_or_keyword()?;
self.expect(TokenKind::LeftParen)?;
let mut params = Vec::new();
while self.current.kind != TokenKind::RightParen && self.current.kind != TokenKind::Eof {
// Allow DOL keywords as parameter names (e.g., `gene: GeneDecl`)
let param_name = self.expect_identifier_or_keyword()?;
self.expect(TokenKind::Colon)?;
let type_ann = self.parse_type()?;
params.push(FunctionParam {
name: param_name,
type_ann,
});
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
let return_type = if self.current.kind == TokenKind::Arrow {
self.advance();
Some(self.parse_type()?)
} else {
None
};
// Body is optional for sex fun (import declaration if no body)
let body = if self.current.kind == TokenKind::LeftBrace {
self.advance(); // consume '{'
let mut stmts = Vec::new();
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof
{
stmts.push(self.parse_stmt()?);
}
self.expect(TokenKind::RightBrace)?;
stmts
} else {
// No body - this is an import declaration (only valid for sex fun)
Vec::new()
};
let span = start_span.merge(&self.previous.span);
Ok(FunctionDecl {
visibility: Visibility::default(),
purity: Purity::default(),
name,
type_params: None,
params,
return_type,
body,
exegesis: String::new(),
span,
attributes: Vec::new(),
})
}
/// Parses a law declaration in a trait.
///
/// Syntax: `law name(params) { body } [exegesis { ... }]`
///
/// Laws are declarative constraints/properties that must hold for a trait.
/// Unlike `fun` which contains implementation code, `law` bodies are
/// logical expressions (predicates).
pub fn parse_law_decl(&mut self) -> Result<LawDecl, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Law)?;
let name = self.expect_identifier()?;
// Parse parameters
self.expect(TokenKind::LeftParen)?;
let mut params = Vec::new();
while self.current.kind != TokenKind::RightParen && self.current.kind != TokenKind::Eof {
// Allow DOL keywords as parameter names (e.g., `gene: GeneDecl`)
let param_name = self.expect_identifier_or_keyword()?;
self.expect(TokenKind::Colon)?;
let type_ann = self.parse_type()?;
params.push(FunctionParam {
name: param_name,
type_ann,
});
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
// Parse body expression (a predicate/constraint)
self.expect(TokenKind::LeftBrace)?;
let body = self.parse_expr(0)?;
self.expect(TokenKind::RightBrace)?;
// Parse optional exegesis
let exegesis = if self.current.kind == TokenKind::Exegesis {
Some(self.parse_exegesis()?)
} else {
None
};
Ok(LawDecl {
name,
params,
body,
exegesis,
span: start_span.merge(&self.previous.span),
})
}
/// Parses a migrate block for evolution.
///
/// Syntax: `migrate { statements }`
///
/// Migrate blocks contain imperative migration code that transforms
/// data or state from the old version to the new version.
pub fn parse_migrate_block(&mut self) -> Result<Vec<Stmt>, ParseError> {
self.expect(TokenKind::Migrate)?;
self.expect(TokenKind::LeftBrace)?;
let mut statements = Vec::new();
while self.current.kind != TokenKind::RightBrace && self.current.kind != TokenKind::Eof {
statements.push(self.parse_stmt()?);
}
self.expect(TokenKind::RightBrace)?;
Ok(statements)
}
// === Macro Parsing ===
/// Parses a macro invocation expression: #macro_name(args)
fn parse_macro_invocation_expr(&mut self) -> Result<Expr, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Macro)?; // consume #
// Get macro name
let name = self.expect_identifier()?;
// Parse optional arguments
let args = if self.current.kind == TokenKind::LeftParen {
self.advance();
let mut args = Vec::new();
while self.current.kind != TokenKind::RightParen && self.current.kind != TokenKind::Eof
{
args.push(self.parse_expr(0)?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
args
} else {
Vec::new()
};
let _span = start_span.merge(&self.previous.span);
// Return as a special MacroCall expression
// We encode this as a Call with a special identifier prefix
Ok(Expr::Call {
callee: Box::new(Expr::Identifier(format!("#{}", name))),
args,
})
}
/// Parses idiom brackets: [| f a b |]
/// Desugars to f <$> a <*> b for applicative functor style.
fn parse_idiom_bracket(&mut self) -> Result<Expr, ParseError> {
self.expect(TokenKind::IdiomOpen)?; // consume [|
// Parse the function (first expression)
let func = self.parse_expr(0)?;
// Parse arguments until we hit |]
let mut args = Vec::new();
while self.current.kind != TokenKind::IdiomClose && self.current.kind != TokenKind::Eof {
args.push(self.parse_expr(0)?);
}
self.expect(TokenKind::IdiomClose)?; // consume |]
Ok(Expr::IdiomBracket {
func: Box::new(func),
args,
})
}
/// Parses a macro invocation and returns the MacroInvocation AST node.
pub fn parse_macro_invocation(&mut self) -> Result<MacroInvocation, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Macro)?; // consume #
// Get macro name
let name = self.expect_identifier()?;
// Parse optional arguments
let args = if self.current.kind == TokenKind::LeftParen {
self.advance();
let mut args = Vec::new();
while self.current.kind != TokenKind::RightParen && self.current.kind != TokenKind::Eof
{
args.push(self.parse_expr(0)?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
args
} else {
Vec::new()
};
let span = start_span.merge(&self.previous.span);
Ok(MacroInvocation::new(name, args, span))
}
/// Parses an attribute macro: #[macro_name(args)]
pub fn parse_macro_attribute(&mut self) -> Result<MacroAttribute, ParseError> {
let start_span = self.current.span;
self.expect(TokenKind::Macro)?; // consume #
self.expect(TokenKind::LeftBracket)?; // consume [
// Get macro name
let name = self.expect_identifier()?;
// Parse optional arguments
let args = if self.current.kind == TokenKind::LeftParen {
self.advance();
let mut args = Vec::new();
while self.current.kind != TokenKind::RightParen && self.current.kind != TokenKind::Eof
{
args.push(self.parse_attribute_arg()?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
args
} else {
Vec::new()
};
self.expect(TokenKind::RightBracket)?; // consume ]
let span = start_span.merge(&self.previous.span);
Ok(MacroAttribute::new(name, args, span))
}
/// Parses an attribute argument.
fn parse_attribute_arg(&mut self) -> Result<AttributeArg, ParseError> {
let name = self.expect_identifier()?;
// Check for key = value or nested attribute
if self.current.kind == TokenKind::Equal {
self.advance();
let value = self.parse_expr(0)?;
Ok(AttributeArg::KeyValue { key: name, value })
} else if self.current.kind == TokenKind::LeftParen {
// Nested attribute
self.advance();
let mut args = Vec::new();
while self.current.kind != TokenKind::RightParen && self.current.kind != TokenKind::Eof
{
args.push(self.parse_attribute_arg()?);
if self.current.kind == TokenKind::Comma {
self.advance();
} else {
break;
}
}
self.expect(TokenKind::RightParen)?;
Ok(AttributeArg::Nested { name, args })
} else {
// Simple identifier
Ok(AttributeArg::Ident(name))
}
}
/// Checks if we're at the start of an attribute macro.
pub fn is_at_attribute(&self) -> bool {
// Check for #[ pattern
if self.current.kind != TokenKind::Macro {
return false;
}
// Would need lookahead to check for [
true // Simplified check
}
// === Helper Methods ===
/// Returns the source text (for exegesis parsing).
fn lexer_source(&self) -> &'a str {
self.source
}
/// Advances to the next token.
fn advance(&mut self) {
self.previous = std::mem::replace(
&mut self.current,
self.peeked
.take()
.or_else(|| self.peeked2.take())
.or_else(|| self.peeked3.take())
.unwrap_or_else(|| self.lexer.next_token()),
);
// Shift peeked tokens down the chain
if self.peeked.is_none() && self.peeked2.is_some() {
self.peeked = self.peeked2.take();
}
if self.peeked2.is_none() && self.peeked3.is_some() {
self.peeked2 = self.peeked3.take();
}
}
/// Peeks at the next token without consuming it.
fn peek(&mut self) -> &Token {
if self.peeked.is_none() {
self.peeked = Some(self.lexer.next_token());
}
self.peeked.as_ref().unwrap()
}
/// Peeks at the token after the next token (two-token lookahead).
fn peek2(&mut self) -> &Token {
// Ensure peeked is populated
if self.peeked.is_none() {
self.peeked = Some(self.lexer.next_token());
}
// Ensure peeked2 is populated
if self.peeked2.is_none() {
self.peeked2 = Some(self.lexer.next_token());
}
self.peeked2.as_ref().unwrap()
}
/// Peeks at the third token ahead (three-token lookahead).
fn peek3(&mut self) -> &Token {
// Ensure all prior tokens are populated
if self.peeked.is_none() {
self.peeked = Some(self.lexer.next_token());
}
if self.peeked2.is_none() {
self.peeked2 = Some(self.lexer.next_token());
}
// Ensure peeked3 is populated
if self.peeked3.is_none() {
self.peeked3 = Some(self.lexer.next_token());
}
self.peeked3.as_ref().unwrap()
}
/// Expects the current token to be of a specific kind.
fn expect(&mut self, kind: TokenKind) -> Result<(), ParseError> {
if self.current.kind == kind {
self.advance();
Ok(())
} else {
Err(ParseError::UnexpectedToken {
expected: kind.to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
})
}
}
/// Expects a `>` token in type context, also accepting `>>` and splitting it.
/// This handles nested generics like `Option<Box<T>>` where `>>` is tokenized as one token.
fn expect_greater_in_type(&mut self) -> Result<(), ParseError> {
if self.current.kind == TokenKind::Greater {
self.advance();
Ok(())
} else if self.current.kind == TokenKind::Compose {
// >> becomes > after consuming one >
// Create a new > token with updated span
self.current = Token {
kind: TokenKind::Greater,
lexeme: ">".to_string(),
span: Span {
start: self.current.span.start + 1,
end: self.current.span.end,
line: self.current.span.line,
column: self.current.span.column + 1,
},
};
Ok(())
} else {
Err(ParseError::UnexpectedToken {
expected: ">".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
})
}
}
/// Expects an identifier and returns it.
fn expect_identifier(&mut self) -> Result<String, ParseError> {
if self.current.kind == TokenKind::Identifier {
let lexeme = self.current.lexeme.clone();
self.advance();
Ok(lexeme)
} else {
Err(ParseError::UnexpectedToken {
expected: "identifier".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
})
}
}
/// Expects an identifier or a DOL keyword that can be used as a variable/function name.
/// This allows keywords like `gene`, `trait`, `test`, etc. to be used as names.
fn expect_identifier_or_keyword(&mut self) -> Result<String, ParseError> {
match self.current.kind {
TokenKind::Identifier
| TokenKind::Gene
| TokenKind::Trait
| TokenKind::System
| TokenKind::Constraint
| TokenKind::Rule
| TokenKind::Evolves
| TokenKind::Exegesis
| TokenKind::Test
| TokenKind::Law
| TokenKind::State
| TokenKind::Module
| TokenKind::Use
| TokenKind::Uses
// Additional keywords that can be used as identifiers
| TokenKind::Migrate
| TokenKind::Pub
| TokenKind::Has
| TokenKind::Is
| TokenKind::Requires
| TokenKind::Var
| TokenKind::Let
| TokenKind::Function
| TokenKind::Return
| TokenKind::If
| TokenKind::Else
| TokenKind::Match
| TokenKind::For
| TokenKind::While
| TokenKind::Loop
| TokenKind::In
| TokenKind::Break
| TokenKind::Continue
| TokenKind::Where
| TokenKind::True
| TokenKind::False
// Evolution/migration keywords that can be field names
| TokenKind::From
// Type keywords
| TokenKind::Int8
| TokenKind::Int16
| TokenKind::Int32
| TokenKind::Int64
| TokenKind::UInt8
| TokenKind::UInt16
| TokenKind::UInt32
| TokenKind::UInt64
| TokenKind::Float32
| TokenKind::Float64
| TokenKind::BoolType
| TokenKind::StringType
| TokenKind::VoidType
// v0.3.0 keywords that can be used as identifiers
| TokenKind::Type
| TokenKind::Val
| TokenKind::Extends
| TokenKind::Forall
// v0.9.0 Spirit keywords that can be used as identifiers
| TokenKind::Spirit
| TokenKind::Config => {
let lexeme = self.current.lexeme.clone();
self.advance();
Ok(lexeme)
}
_ => Err(ParseError::UnexpectedToken {
expected: "identifier".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
}),
}
}
/// Expects a version and returns it.
fn expect_version(&mut self) -> Result<String, ParseError> {
if self.current.kind == TokenKind::Version {
let lexeme = self.current.lexeme.clone();
self.advance();
Ok(lexeme)
} else {
Err(ParseError::UnexpectedToken {
expected: "version number".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
})
}
}
/// Expects a string and returns it.
fn expect_string(&mut self) -> Result<String, ParseError> {
if self.current.kind == TokenKind::String {
let lexeme = self.current.lexeme.clone();
self.advance();
Ok(lexeme)
} else {
Err(ParseError::UnexpectedToken {
expected: "string".to_string(),
found: format!("'{}'", self.current.lexeme),
span: self.current.span,
})
}
}
/// Checks if the next token is an identifier.
fn peek_is_identifier(&self) -> bool {
// Simple lookahead - would need proper implementation
true
}
/// Checks if a version constraint follows.
fn peek_is_version_constraint(&self) -> bool {
// Simple lookahead - would need proper implementation
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_gene() {
let input = r#"
gene container.exists {
container has identity
container has status
}
exegesis {
A container is fundamental.
}
"#;
let mut parser = Parser::new(input);
let result = parser.parse();
assert!(result.is_ok(), "Parse error: {:?}", result.err());
if let Declaration::Gene(gene) = result.unwrap() {
assert_eq!(gene.name, "container.exists");
assert_eq!(gene.statements.len(), 2);
} else {
panic!("Expected Gene");
}
}
#[test]
fn test_parse_trait() {
let input = r#"
trait container.lifecycle {
uses container.exists
container is created
}
exegesis {
Lifecycle management.
}
"#;
let mut parser = Parser::new(input);
let result = parser.parse();
assert!(result.is_ok());
}
#[test]
fn test_missing_exegesis() {
// DOL 2.0 tolerant: missing exegesis defaults to empty string
let input = r#"
gene container.exists {
container has identity
}
"#;
let mut parser = Parser::new(input);
let result = parser.parse();
assert!(result.is_ok());
// Verify that exegesis is empty when not provided
let decl = result.unwrap();
if let Declaration::Gene(gene) = decl {
assert!(gene.exegesis.is_empty());
} else {
panic!("Expected Gene declaration");
}
}
}