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
// ===============================================================================
// BUILDLANG CODE GENERATOR - MACRO AND CLOSURE LOWERING
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================
//! Closure lowering, effect lowering, builtin macro expansion, and iterator
//! chain desugaring for MIR.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::ast::{self, ExprKind, StmtKind};
use crate::codegen::backend::{CodegenError, CodegenResult};
use crate::codegen::builder::{values, MirBuilder};
use crate::codegen::ir::*;
use super::{IterChain, IterStep, IterTerminal, MirLowerer};
impl<'ctx> MirLowerer<'ctx> {
// =========================================================================
// CLOSURE LOWERING
// =========================================================================
/// Collect free variables in an expression that are defined in the
/// enclosing scope (i.e., present in `env_vars`) but are NOT among
/// the closure's own `param_names`. Returns a de-duplicated list of
/// (variable_name, local_id_in_enclosing_scope).
pub(super) fn collect_free_vars(
expr: &ast::Expr,
param_names: &HashSet<Arc<str>>,
env_vars: &HashMap<Arc<str>, LocalId>,
source: Option<&str>,
) -> Vec<(Arc<str>, LocalId)> {
let mut found: Vec<(Arc<str>, LocalId)> = Vec::new();
let mut seen: HashSet<Arc<str>> = HashSet::new();
Self::collect_free_vars_inner(expr, param_names, env_vars, &mut found, &mut seen, source);
found
}
fn collect_free_vars_inner(
expr: &ast::Expr,
param_names: &HashSet<Arc<str>>,
env_vars: &HashMap<Arc<str>, LocalId>,
found: &mut Vec<(Arc<str>, LocalId)>,
seen: &mut HashSet<Arc<str>>,
source: Option<&str>,
) {
match &expr.kind {
ExprKind::Ident(ident) => {
if !param_names.contains(&ident.name) && !seen.contains(&ident.name) {
if let Some(&local_id) = env_vars.get(&ident.name) {
seen.insert(ident.name.clone());
found.push((ident.name.clone(), local_id));
}
}
}
ExprKind::Binary { left, right, .. } => {
Self::collect_free_vars_inner(left, param_names, env_vars, found, seen, source);
Self::collect_free_vars_inner(right, param_names, env_vars, found, seen, source);
}
ExprKind::Unary { expr: inner, .. }
| ExprKind::Paren(inner)
| ExprKind::Ref { expr: inner, .. }
| ExprKind::Deref(inner)
| ExprKind::Return(Some(inner))
| ExprKind::Resume(Some(inner))
| ExprKind::Try(inner)
| ExprKind::Await(inner)
| ExprKind::Cast { expr: inner, .. } => {
Self::collect_free_vars_inner(inner, param_names, env_vars, found, seen, source);
}
ExprKind::Call { func, args } => {
Self::collect_free_vars_inner(func, param_names, env_vars, found, seen, source);
for a in args {
Self::collect_free_vars_inner(a, param_names, env_vars, found, seen, source);
}
}
ExprKind::MethodCall { receiver, args, .. } => {
Self::collect_free_vars_inner(receiver, param_names, env_vars, found, seen, source);
for a in args {
Self::collect_free_vars_inner(a, param_names, env_vars, found, seen, source);
}
}
ExprKind::If {
condition,
then_branch,
else_branch,
} => {
Self::collect_free_vars_inner(
condition,
param_names,
env_vars,
found,
seen,
source,
);
for stmt in &then_branch.stmts {
if let StmtKind::Expr(e) | StmtKind::Semi(e) = &stmt.kind {
Self::collect_free_vars_inner(
e,
param_names,
env_vars,
found,
seen,
source,
);
}
}
if let Some(e) = else_branch {
Self::collect_free_vars_inner(e, param_names, env_vars, found, seen, source);
}
}
ExprKind::Block(block) | ExprKind::Unsafe(block) => {
for stmt in &block.stmts {
if let StmtKind::Expr(e) | StmtKind::Semi(e) = &stmt.kind {
Self::collect_free_vars_inner(
e,
param_names,
env_vars,
found,
seen,
source,
);
}
}
}
ExprKind::Tuple(elems) | ExprKind::Array(elems) => {
for e in elems {
Self::collect_free_vars_inner(e, param_names, env_vars, found, seen, source);
}
}
ExprKind::Index { expr: arr, index } => {
Self::collect_free_vars_inner(arr, param_names, env_vars, found, seen, source);
Self::collect_free_vars_inner(index, param_names, env_vars, found, seen, source);
}
ExprKind::Field { expr: obj, .. } => {
Self::collect_free_vars_inner(obj, param_names, env_vars, found, seen, source);
}
ExprKind::Assign { target, value, .. } => {
Self::collect_free_vars_inner(target, param_names, env_vars, found, seen, source);
Self::collect_free_vars_inner(value, param_names, env_vars, found, seen, source);
}
ExprKind::Match { scrutinee, arms } => {
Self::collect_free_vars_inner(
scrutinee,
param_names,
env_vars,
found,
seen,
source,
);
for arm in arms {
Self::collect_free_vars_inner(
&arm.body,
param_names,
env_vars,
found,
seen,
source,
);
if let Some(guard) = &arm.guard {
Self::collect_free_vars_inner(
guard,
param_names,
env_vars,
found,
seen,
source,
);
}
}
}
ExprKind::Macro { tokens, .. } => {
// Scan token trees for identifiers
for tt in tokens {
Self::collect_free_vars_in_token_tree(
tt,
param_names,
env_vars,
found,
seen,
source,
);
}
}
_ => {}
}
}
fn collect_free_vars_in_token_tree(
tt: &ast::TokenTree,
param_names: &HashSet<Arc<str>>,
env_vars: &HashMap<Arc<str>, LocalId>,
found: &mut Vec<(Arc<str>, LocalId)>,
seen: &mut HashSet<Arc<str>>,
source: Option<&str>,
) {
match tt {
ast::TokenTree::Token(token) => {
// Check if this token is an identifier that references an
// enclosing variable. We need the source text to recover the
// identifier string because Token stores only a span.
if let crate::lexer::TokenKind::Ident = &token.kind {
if let Some(src) = source {
let start = token.span.start.to_usize();
let end = token.span.end.to_usize();
if end <= src.len() {
let name: Arc<str> = Arc::from(&src[start..end]);
if !param_names.contains(&name) && !seen.contains(&name) {
if let Some(&local_id) = env_vars.get(&name) {
seen.insert(name.clone());
found.push((name, local_id));
}
}
}
}
}
}
ast::TokenTree::Delimited { tokens, .. } => {
for inner in tokens {
Self::collect_free_vars_in_token_tree(
inner,
param_names,
env_vars,
found,
seen,
source,
);
}
}
}
}
/// Lower a closure expression into a static function + function pointer.
///
/// **Capturing closures (lambda lifting)**: if the closure body references
/// variables from the enclosing scope, those variables are added as extra
/// trailing parameters to the generated `__closure_N` function. At the
/// call site the captured values are automatically appended.
///
/// NOTE: this approach works for closures that are called locally or passed
/// to functions that invoke them in the same compilation unit. Returning a
/// capturing closure from a function is not yet supported because the
/// function-pointer signature would differ from the declared type.
pub(crate) fn lower_closure(
&mut self,
params: &[ast::ClosureParam],
return_type: Option<&ast::Type>,
body: &ast::Expr,
) -> CodegenResult<MirValue> {
let closure_id = self.closure_count;
self.closure_count += 1;
let closure_name: Arc<str> = Arc::from(format!("__closure_{}", closure_id));
// ---- Detect captured variables (lambda lifting) ----
let param_names: HashSet<Arc<str>> = params
.iter()
.filter_map(|p| {
if let ast::PatternKind::Ident { name, .. } = &p.pattern.kind {
Some(name.name.clone())
} else {
None
}
})
.collect();
let captures =
Self::collect_free_vars(body, ¶m_names, &self.var_map, self.source.as_deref());
// ---- Build the MIR signature ----
// Declared params first, then captured-variable params appended. A
// parameter written without a type takes the caller's hint
// (`opt.map(|x| ..)` gives `x` the payload type), else i32.
let hint = self.closure_param_hint.take().unwrap_or_default();
let mut mir_params: Vec<MirType> = params
.iter()
.enumerate()
.map(|(i, p)| {
p.ty.as_ref()
.map(|t| self.lower_type_from_ast(t))
.or_else(|| hint.get(i).cloned())
.unwrap_or(MirType::i32())
})
.collect();
// Resolve captured variable types from the enclosing builder.
let capture_types: Vec<MirType> = captures
.iter()
.map(|(_name, local_id)| {
if let Some(ref builder) = self.current_fn {
builder.local_type(*local_id).unwrap_or(MirType::i32())
} else {
MirType::i32()
}
})
.collect();
mir_params.extend(capture_types.iter().cloned());
let mir_ret = return_type
.map(|t| self.lower_type_from_ast(t))
.unwrap_or(MirType::i32());
let sig = MirFnSig::new(mir_params.clone(), mir_ret.clone());
// The fn-ptr type must use the *full* parameter list (visible +
// captured) so that the C declaration matches the call sites, which
// append captured values as extra arguments.
let mut fn_ptr_ty =
MirType::FnPtr(Box::new(MirFnSig::new(mir_params.clone(), mir_ret.clone())));
// Save current function state
let saved_fn = self.current_fn.take();
let saved_vars = std::mem::take(&mut self.var_map);
let mut closure_builder = MirBuilder::with_linear_type_names(
closure_name.clone(),
sig,
Arc::new(self.linear_type_names.clone()),
);
// Map declared params
for (i, param) in params.iter().enumerate() {
if let ast::PatternKind::Ident { name, .. } = ¶m.pattern.kind {
let local_id = closure_builder.param_local(i);
closure_builder.set_param_name(i, name.name.clone());
self.var_map.insert(name.name.clone(), local_id);
}
}
// Map captured-variable params (appended after declared params)
for (ci, (cap_name, _)) in captures.iter().enumerate() {
let param_idx = params.len() + ci;
let local_id = closure_builder.param_local(param_idx);
closure_builder.set_param_name(param_idx, cap_name.clone());
self.var_map.insert(cap_name.clone(), local_id);
}
self.current_fn = Some(closure_builder);
// The closure's drop scopes are its own; a `return` in it must not
// drop the enclosing function's values.
let saved_drops = std::mem::take(&mut self.drop_scopes);
let body_val = self.lower_expr(body);
self.drop_scopes = saved_drops;
let body_val = body_val?;
// A closure written without a return type returns its body's type
// (`|x| x > 2` gives a bool, `|x| Some(x)` an Option). Before, it
// always returned i32.
let inferred_ret = if return_type.is_none() {
self.closure_body_type(&body_val)
} else {
None
};
let mut closure_builder = self.current_fn.take().unwrap();
if let Some(ret) = inferred_ret {
if let Some(ret_local) = closure_builder.return_local() {
closure_builder.retype_local(ret_local, ret.clone());
}
closure_builder.set_return_type(ret.clone());
fn_ptr_ty = MirType::FnPtr(Box::new(MirFnSig::new(mir_params.clone(), ret)));
}
if mir_ret != MirType::Void {
closure_builder.ret(Some(body_val));
} else {
closure_builder.ret_void();
}
let mut closure_func = closure_builder.build();
closure_func.linkage = Linkage::Internal;
closure_func.is_public = false;
self.module.add_function(closure_func);
// Restore the enclosing function state
self.current_fn = saved_fn;
self.var_map = saved_vars;
// Register captures so that lower_call can append extra args.
if !captures.is_empty() {
self.closure_captures.insert(closure_name.clone(), captures);
}
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function for closure".to_string()))?;
let result = builder.create_local(fn_ptr_ty);
builder.assign(
result,
MirRValue::Use(MirValue::Function(closure_name.clone())),
);
// Track that this local holds the given closure so we can find
// its captures later when calling through this local.
self.local_closure_name.insert(result, closure_name);
Ok(values::local(result))
}
pub(crate) fn lower_struct_expr(
&mut self,
path: &ast::Path,
fields: &[ast::FieldExpr],
rest: Option<&ast::Expr>,
) -> CodegenResult<MirValue> {
let mut raw_name = path
.last_ident()
.map(|i| i.name.clone())
.unwrap_or(Arc::from(""));
// Resolve Self to concrete type name
if raw_name.as_ref() == "Self" {
if let Some(ref impl_ty) = self.current_impl_type {
raw_name = impl_ty.clone();
}
}
// Inside inline modules, try the prefixed struct name first so that
// types defined in the current module are resolved correctly.
if !self.module_prefix.is_empty() {
let prefixed = self.prefixed_name(&raw_name);
if self.module.find_type(prefixed.as_ref()).is_some() {
raw_name = prefixed;
}
}
// Lower the field values in the order written (their side effects run
// in that order), each against its declared type, so `tags: Vec::new()`
// builds the field's vector type and not a `Vec<i32>` (M4 pilot).
let declared = self.struct_field_types(raw_name.as_ref());
let mut field_vals: Vec<MirValue> = Vec::with_capacity(fields.len());
for f in fields {
let expected = declared.as_ref().and_then(|d| {
d.iter()
.find(|(n, _)| n.as_deref() == Some(f.name.name.as_ref()))
.map(|(_, t)| t.clone())
});
let prev_expected = match expected {
Some(t) => self.expected_type.replace(t),
None => self.expected_type.take(),
};
let val = if let Some(val) = &f.value {
self.lower_expr(val)
} else {
// Field shorthand: `name` means `name: name`
self.lower_ident(&f.name)
};
self.expected_type = prev_expected;
field_vals.push(val?);
}
// Check if this is a generic struct that needs monomorphization
let struct_name = if self.generic_structs.contains_key(raw_name.as_ref()) {
// Try to resolve from explicit generic args on the path
let generic_args = path.last_generics().unwrap_or(&[]);
if !generic_args.is_empty() {
let empty_subst = HashMap::new();
let subst = self.resolve_generic_args_with_subst(
raw_name.as_ref(),
generic_args,
&empty_subst,
);
self.monomorphize_struct(raw_name.as_ref(), &subst)?
} else {
// Infer generic params from field values
let subst =
self.infer_struct_generics_from_fields(raw_name.as_ref(), &field_vals, fields);
self.monomorphize_struct(raw_name.as_ref(), &subst)?
}
} else {
raw_name
};
// With `..base` the values are matched to fields by name further down;
// keep them in the order written for that.
let written_vals = rest.map(|_| field_vals.clone());
// The aggregate is positional: put the values in declaration order.
// Written out of order, `Q { c: "hi", a: 3, b: 2.5 }` assigned `a`
// the string, and with two fields of one type it swapped them silently.
let field_vals = match self.struct_field_types(struct_name.as_ref()) {
Some(decl) if decl.len() == fields.len() => {
let mut ordered = Vec::with_capacity(decl.len());
for (name, _) in &decl {
let pos = fields
.iter()
.position(|f| Some(f.name.name.as_ref()) == name.as_deref());
match pos {
Some(i) => ordered.push(field_vals[i].clone()),
None => {
ordered.clear();
break;
}
}
}
if ordered.len() == decl.len() {
ordered
} else {
field_vals
}
}
_ => field_vals,
};
// `S { a: 1, ..base }`: the fields not written come from `base`.
let field_vals = match (rest, written_vals) {
(Some(rest), Some(written)) => {
self.struct_update_operands(&struct_name, fields, written, rest)?
}
_ => field_vals,
};
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
let result = builder.create_local(MirType::Struct(struct_name.clone()));
builder.aggregate(result, AggregateKind::Struct(struct_name), field_vals);
Ok(values::local(result))
}
/// The operands of `S { written.., ..rest }` in declaration order: a
/// written field keeps its value and every other field is read from
/// `rest`. Before this the `..rest` part was ignored, the aggregate held
/// only the written fields, and the others read as zero. `written` is in
/// the order the fields were written, which is the order they were
/// evaluated in; `rest` is evaluated after them.
fn struct_update_operands(
&mut self,
struct_name: &Arc<str>,
fields: &[ast::FieldExpr],
written: Vec<MirValue>,
rest: &ast::Expr,
) -> CodegenResult<Vec<MirValue>> {
let unsupported = || CodegenError::Rejected {
message: format!("`..` in a `{struct_name}` literal needs a struct with named fields"),
location: (rest.span.end.0 > rest.span.start.0)
.then_some((rest.span.start.0, rest.span.end.0)),
help: Some("write every field of the literal".to_string()),
};
let decl = self
.struct_field_types(struct_name.as_ref())
.ok_or_else(unsupported)?;
let base = self.lower_expr(rest)?;
let mut operands = Vec::with_capacity(decl.len());
for (name, ty) in decl {
let name = name.ok_or_else(unsupported)?;
let given = fields
.iter()
.position(|f| f.name.name.as_ref() == name.as_ref());
if let Some(value) = given.and_then(|i| written.get(i)) {
operands.push(value.clone());
continue;
}
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
let field = builder.create_local(ty.clone());
builder.assign(
field,
MirRValue::FieldAccess {
base: base.clone(),
field_name: name,
field_ty: ty,
},
);
operands.push(values::local(field));
}
Ok(operands)
}
/// The named fields of a struct type in declaration order, if it is one.
fn struct_field_types(&self, name: &str) -> Option<Vec<(Option<Arc<str>>, MirType)>> {
match &self.module.find_type(name)?.kind {
TypeDefKind::Struct { fields, .. } => Some(fields.clone()),
_ => None,
}
}
/// Infer generic type parameters for a struct from the types of field values
/// at the construction site.
fn infer_struct_generics_from_fields(
&self,
struct_name: &str,
field_vals: &[MirValue],
field_exprs: &[ast::FieldExpr],
) -> HashMap<Arc<str>, MirType> {
let mut subst = HashMap::new();
let struct_def = match self.generic_structs.get(struct_name) {
Some(s) => s.clone(),
None => return subst,
};
// Get type parameter names
let type_param_names: Vec<Arc<str>> = struct_def
.generics
.params
.iter()
.filter_map(|p| match &p.kind {
ast::GenericParamKind::Type { .. } => Some(p.ident.name.clone()),
_ => None,
})
.collect();
// Match field types against field values
if let ast::StructFields::Named(def_fields) = &struct_def.fields {
for (i, def_field) in def_fields.iter().enumerate() {
if let Some(val) = field_vals.get(i) {
let val_ty = self.type_of_value(val);
// Check if this field's type is a generic parameter
if let ast::TypeKind::Path(path) = &def_field.ty.kind {
if path.is_simple() {
if let Some(ident) = path.last_ident() {
for tp_name in &type_param_names {
if ident.name.as_ref() == tp_name.as_ref() {
subst.entry(tp_name.clone()).or_insert(val_ty.clone());
}
}
}
}
}
}
}
}
// Also try matching by field name from field_exprs
if let ast::StructFields::Named(def_fields) = &struct_def.fields {
for field_expr in field_exprs {
let field_name = &field_expr.name.name;
if let Some(def_field) = def_fields.iter().find(|f| &f.name.name == field_name) {
if let ast::TypeKind::Path(path) = &def_field.ty.kind {
if path.is_simple() {
if let Some(ident) = path.last_ident() {
for tp_name in &type_param_names {
if ident.name.as_ref() == tp_name.as_ref() {
// Already handled above via positional matching
}
}
}
}
}
}
}
}
// Fill in any unbound params with i32 default
for tp_name in &type_param_names {
subst.entry(tp_name.clone()).or_insert(MirType::i32());
}
subst
}
// =========================================================================
// EFFECT LOWERING
// =========================================================================
/// Compute a deterministic integer ID for a named effect.
///
/// Built-in effects get fixed IDs; user-defined effects are hashed into a
/// range starting at 100 so they never collide with the built-in set.
fn effect_id(effect_name: &str) -> i32 {
match effect_name {
"IO" => 1,
"Error" => 2,
"Async" => 3,
"State" => 4,
"NonDet" => 5,
_ => {
// Hash the name for user-defined effects
let mut hash: i32 = 0;
for b in effect_name.bytes() {
hash = hash.wrapping_mul(31).wrapping_add(b as i32);
}
hash.abs() + 100 // offset to avoid collision with built-ins
}
}
}
/// Look up the type of a parameter in an effect operation definition.
///
/// `effect_name` - the resolved effect name (e.g. "Console")
/// `op_name` - the operation name (e.g. "log")
/// `param_idx` - zero-based parameter index
///
/// Returns `None` if the effect or operation is not found, or if the index
/// is out of range.
pub(super) fn lookup_effect_param_type(
&self,
effect_name: &str,
op_name: &str,
param_idx: usize,
) -> Option<MirType> {
let ops = self.effect_defs.get(effect_name)?;
for (name, param_types) in ops {
if name.as_ref() == op_name {
return param_types.get(param_idx).cloned();
}
}
None
}
/// Lower an `ExprKind::Handle` expression.
///
/// ```text
/// handle { body } with { Effect.op(params) => handler_body, ... }
/// ```
///
/// Generates MIR that:
/// 1. Allocates a `BuildHandler` on the stack (as a struct local).
/// 2. Calls `build_push_handler(&handler, effect_id)`.
/// 3. Calls `setjmp(handler.env)`:
/// - If the result is 0 -> execute the body normally, then pop the handler.
/// - If the result is N -> dispatch to handler clause N-1.
/// 4. Pops the handler on every exit path.
pub(crate) fn lower_handle(
&mut self,
effect: &ast::Path,
handlers: &[ast::EffectHandler],
body: &ast::Block,
) -> CodegenResult<MirValue> {
// Resolve the effect name and its integer ID.
let effect_name = effect
.segments
.iter()
.map(|s| s.ident.name.as_ref())
.collect::<Vec<_>>()
.join("::");
let eid = Self::effect_id(&effect_name);
// --- Allocate locals ---------------------------------------------------
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
// The handler struct is opaque at the MIR level; the C backend will emit
// a `BuildHandler` declaration for it. We represent it as an i8 array
// large enough to hold the C struct (the runtime defines the real type).
let handler_local = builder.create_named_local(
format!("__handler_{}", effect_name),
MirType::Struct(Arc::from("BuildHandler")),
);
// The local that receives the setjmp return value (0 = normal, N = op N-1).
let setjmp_result = builder.create_local(MirType::i32());
// The final result of the handle expression.
let handle_result = builder.create_local(MirType::i32());
// --- Create blocks ------------------------------------------------------
let push_block = builder.create_labeled_block(format!("effect_push_{}", setjmp_result.0));
let body_block = builder.create_labeled_block(format!("effect_body_{}", setjmp_result.0));
let merge_block = builder.create_labeled_block(format!("effect_merge_{}", setjmp_result.0));
// Create a block for each handler clause.
let handler_blocks: Vec<BlockId> = handlers
.iter()
.enumerate()
.map(|(i, _)| {
let builder = self.current_fn.as_mut().unwrap();
builder.create_labeled_block(format!("effect_handler_{}_{}", setjmp_result.0, i))
})
.collect();
let mut is_tail: Vec<bool> = Vec::with_capacity(handlers.len());
// --- Emit: push handler -------------------------------------------------
{
let builder = self.current_fn.as_mut().unwrap();
builder.goto(push_block);
builder.switch_to_block(push_block);
// build_push_handler(&handler, effect_id)
let push_fn = MirValue::Function(Arc::from("build_push_handler"));
// Take address of the handler struct so the C call gets a pointer.
let handler_ptr_local = builder.create_local(MirType::Ptr(Box::new(MirType::Struct(
Arc::from("BuildHandler"),
))));
builder.assign(
handler_ptr_local,
MirRValue::AddressOf {
is_mut: true,
place: MirPlace::local(handler_local),
},
);
let eid_val = MirValue::Const(MirConst::Int(eid as i128, MirType::i32()));
let cont = builder.create_block();
builder.call(
push_fn,
vec![MirValue::Local(handler_ptr_local), eid_val],
None,
cont,
);
builder.switch_to_block(cont);
for h in handlers {
is_tail.push(self.lower_tail_clause(h, &effect_name, handler_local)?);
}
let builder = self.current_fn.as_mut().unwrap();
// setjmp(handler.env) - pass the handler local directly;
// the C backend will emit `.env` when it sees a setjmp call
// with a BuildHandler-typed argument.
let setjmp_fn = MirValue::Function(Arc::from("setjmp"));
let cont2 = builder.create_block();
builder.call(
setjmp_fn,
vec![MirValue::Local(handler_local)],
Some(setjmp_result),
cont2,
);
builder.switch_to_block(cont2);
// Branch: if setjmp_result == 0 -> body, else dispatch
let zero = MirValue::Const(MirConst::Int(0, MirType::i32()));
let is_normal = builder.create_local(MirType::Bool);
builder.binary_op(is_normal, BinOp::Eq, MirValue::Local(setjmp_result), zero);
// Build switch targets for handler dispatch.
// setjmp returns op_id + 1, so handler clause i fires when result == i+1.
let default_block = if handler_blocks.is_empty() {
merge_block
} else {
handler_blocks[0]
};
if handler_blocks.len() <= 1 {
// Simple: either body or first (only) handler
builder.branch(MirValue::Local(is_normal), body_block, default_block);
} else {
// Multi-handler: first check if normal, then switch on op_id.
let dispatch_block = builder.create_labeled_block("effect_dispatch");
builder.branch(MirValue::Local(is_normal), body_block, dispatch_block);
builder.switch_to_block(dispatch_block);
let targets: Vec<(MirConst, BlockId)> = handler_blocks
.iter()
.enumerate()
.map(|(i, &blk)| {
(
MirConst::Int(
super::tail_resume::op_hash(&handlers[i].operation.name) as i128
+ 1,
MirType::i32(),
),
blk,
)
})
.collect();
builder.switch(MirValue::Local(setjmp_result), targets, merge_block);
}
}
// --- Emit: body (normal path, setjmp returned 0) ------------------------
{
let builder = self.current_fn.as_mut().unwrap();
builder.switch_to_block(body_block);
}
let body_val = self.lower_block(body)?;
{
let builder = self.current_fn.as_mut().unwrap();
if let Some(ref v) = body_val {
// Don't assign void/unit values to the handle result.
if !matches!(v, MirValue::Const(MirConst::Unit)) {
builder.assign(handle_result, MirRValue::Use(v.clone()));
}
}
// Pop the handler after the body completes normally.
let pop_fn = MirValue::Function(Arc::from("build_pop_handler"));
let cont = builder.create_block();
builder.call(pop_fn, vec![], None, cont);
builder.switch_to_block(cont);
builder.goto(merge_block);
}
// --- Emit: handler clauses ----------------------------------------------
for (i, handler) in handlers.iter().enumerate() {
{
let builder = self.current_fn.as_mut().unwrap();
builder.switch_to_block(handler_blocks[i]);
}
if is_tail[i] {
let builder = self.current_fn.as_mut().unwrap();
let cont = builder.create_block();
builder.call(
MirValue::Function(Arc::from("build_pop_handler")),
vec![],
None,
cont,
);
builder.switch_to_block(cont);
builder.goto(merge_block);
continue;
}
// Map handler parameters to locals so the handler body can reference
// them. For the setjmp model the parameter data is available via
// `handler.handler_data`; at the MIR level we just create named
// locals that the C backend will initialise from `handler_data`.
for (param_idx, param) in handler.params.iter().enumerate() {
if let ast::PatternKind::Ident { name, .. } = ¶m.pattern.kind {
// Determine parameter type: use explicit annotation if present,
// otherwise look up the effect operation's parameter types
// from the collected effect definitions.
let op_name = handler.operation.name.as_ref();
let ty = param
.ty
.as_ref()
.map(|t| self.lower_type_from_ast(t))
.unwrap_or_else(|| {
self.lookup_effect_param_type(&effect_name, op_name, param_idx)
.unwrap_or(MirType::i32())
});
let builder = self.current_fn.as_mut().unwrap();
let local = builder.create_named_local(name.name.clone(), ty.clone());
self.var_map.insert(name.name.clone(), local);
// Load argument `param_idx` from handler_data.
// The perform site stores a `void*[N]` argv array in
// handler_data, where argv[i] points to argument i. The
// `handler_data#<i>` field marker tells the C backend which
// argument to read; it renders as:
// msg = *(ParamType*)((void**)__handler_EffectName.handler_data)[i]
let handler_data_field = MirRValue::FieldAccess {
base: MirValue::Local(handler_local),
field_name: Arc::from(format!("handler_data#{}", param_idx)),
field_ty: MirType::Ptr(Box::new(MirType::Void)),
};
builder.assign(local, handler_data_field);
}
}
// Lower the handler body expression.
let handler_val = self.lower_expr(&handler.body)?;
{
let builder = self.current_fn.as_mut().unwrap();
// Don't assign void/unit values to the handle result.
// Also skip if the handler_val is a local that isn't declared in
// the current function (can happen with resume return values).
let should_assign = !matches!(handler_val, MirValue::Const(MirConst::Unit))
&& !matches!(handler_val, MirValue::Const(MirConst::Bool(_)))
&& match &handler_val {
MirValue::Local(lid) => builder.local_exists(*lid),
_ => true,
};
if should_assign {
builder.assign(handle_result, MirRValue::Use(handler_val));
}
// Pop handler after handling.
let pop_fn = MirValue::Function(Arc::from("build_pop_handler"));
let cont = builder.create_block();
builder.call(pop_fn, vec![], None, cont);
builder.switch_to_block(cont);
builder.goto(merge_block);
}
}
// --- Merge block --------------------------------------------------------
{
let builder = self.current_fn.as_mut().unwrap();
builder.switch_to_block(merge_block);
}
Ok(values::local(handle_result))
}
/// Lower an `ExprKind::Resume` expression.
///
/// In the setjmp/longjmp one-shot model, `resume(value)` stores the resume
/// value into the handler result local and returns from the handler clause.
/// Because the handler clause already ends with an assignment to the
/// handle-expression result followed by a goto to the merge block, the
/// simplest lowering is to evaluate the resume value and return it as the
/// handler clause's value.
pub(crate) fn lower_resume(&mut self, value: Option<&ast::Expr>) -> CodegenResult<MirValue> {
if let Some(expr) = value {
self.lower_expr(expr)
} else {
Ok(values::unit())
}
}
/// Lower an `ExprKind::Perform` expression.
///
/// ```text
/// perform Effect.op(arg1, arg2, ...)
/// ```
///
/// Generates a call to `build_perform(effect_id, op_id, arg_ptr, result_ptr)`
/// which longjmps to the nearest matching handler. The first argument is
/// passed via the `arg` pointer; the result pointer is set up so the handler
/// can write a return value back to the perform-site (for the one-shot model
/// this is not used, but the slot is allocated for future coroutine support).
pub(crate) fn lower_perform(
&mut self,
effect: &ast::Ident,
operation: &ast::Ident,
args: &[ast::Expr],
) -> CodegenResult<MirValue> {
let eid = Self::effect_id(effect.name.as_ref());
// Compute a simple operation index from the operation name.
// In a full implementation this would look up the effect declaration to
// find the canonical index; here we use a hash so that different op
// names within the same effect get distinct IDs.
let op_id: i32 = super::tail_resume::op_hash(&operation.name);
let ret_ty = self
.effect_op_rets
.get(&(effect.name.clone(), operation.name.clone()))
.cloned()
.filter(|t| *t != MirType::Void)
.unwrap_or(MirType::i32());
// Lower every argument. Each is marshalled into a `void*[N]` argv
// array whose i-th slot holds the address of argument i; the handler
// reads argument i back via `((void**)handler_data)[i]`. Passing the
// whole argv (not just the first arg) is what lets a multi-parameter
// operation see all of its arguments. A zero-argument operation passes
// a null `arg` pointer, which its handler never dereferences.
let arg_vals: Vec<MirValue> = args
.iter()
.map(|a| self.lower_expr(a))
.collect::<CodegenResult<Vec<_>>>()?;
// Compute each argument's type before borrowing current_fn mutably.
let arg_tys: Vec<MirType> = arg_vals.iter().map(|v| self.type_of_value(v)).collect();
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
// Allocate a result slot on the stack. Use an unnamed local to
// avoid duplicate C declarations when perform is called multiple
// times with the same effect/operation.
let result_local = builder.create_local(ret_ty.clone());
// Build the argv array of pointers-to-arguments. Each argument value is
// stored into its own local so its address is stable, then written into
// `argv[i]`; a `T*` slot value decays to the `void*` element type in C.
let n = arg_vals.len();
let arg_ptr_value: MirValue = if n == 0 {
MirValue::Const(MirConst::Null(MirType::Void))
} else {
let argv = builder.create_local(MirType::Array(
Box::new(MirType::Ptr(Box::new(MirType::Void))),
n as u64,
));
for (i, (val, ty)) in arg_vals.into_iter().zip(arg_tys.into_iter()).enumerate() {
let arg_local = builder.create_local(ty);
builder.assign(arg_local, MirRValue::Use(val));
builder.push_index_store(
MirValue::Local(argv),
MirValue::Const(MirConst::Int(i as i128, MirType::i32())),
MirType::Ptr(Box::new(MirType::Void)),
MirRValue::AddressOf {
is_mut: false,
place: MirPlace::local(arg_local),
},
);
}
MirValue::Local(argv)
};
// Take the address of the result slot for the void* result parameter.
let result_ptr = builder.create_local(MirType::Ptr(Box::new(ret_ty)));
builder.assign(
result_ptr,
MirRValue::AddressOf {
is_mut: true,
place: MirPlace::local(result_local),
},
);
// build_perform(effect_id, op_id, argv, &result)
let perform_fn = MirValue::Function(Arc::from("build_perform"));
let eid_val = MirValue::Const(MirConst::Int(eid as i128, MirType::i32()));
let op_val = MirValue::Const(MirConst::Int(op_id as i128, MirType::i32()));
let cont = builder.create_block();
builder.call(
perform_fn,
vec![eid_val, op_val, arg_ptr_value, MirValue::Local(result_ptr)],
None,
cont,
);
builder.switch_to_block(cont);
// In practice build_perform never returns (it longjmps), but at the MIR
// level we model the continuation so the CFG remains well-formed. The
// result local is available if a future coroutine-based implementation
// stores a return value there.
Ok(values::local(result_local))
}
// =========================================================================
// BUILTIN MACRO LOWERING
// =========================================================================
/// Lower `vec![a, b, c]` (literal) and `vec![val; count]` (repeat) macros.
///
/// Expansion:
/// vec![a, b, c] => let v = vec_new_T(); vec_push_T(v, a); vec_push_T(v, b); vec_push_T(v, c); v
/// vec![val; count] => let v = vec_new_T(); for i in 0..count { vec_push_T(v, val); } v
///
/// The element type is inferred from the first argument expression.
pub(crate) fn lower_vec_macro(&mut self, tokens: &[ast::TokenTree]) -> CodegenResult<MirValue> {
// When a `Vec<T>` type is expected (from a let annotation or another
// bidirectional hint), lower each element with `T` as its expected type
// and build the vec at `T`. Without this an annotated
// `let v: Vec<i64> = vec![1, 2, 3]` infers `i32` from the bare literals,
// stores 4-byte-strided elements through the i32 push helper, and every
// `v[i]` reads at the i64 width the annotation requires -> the read
// spans two elements: a silent wrong answer with no diagnostic.
let expected_elem: Option<MirType> = match &self.expected_type {
Some(MirType::Vec(elem)) => Some((**elem).clone()),
_ => None,
};
// Check if tokens have valid spans matching our source file.
// When the macro expander expands nested vec! calls, the inner
// tokens get synthetic spans that don't match self.source.
// In that case, fall back to creating an empty vec (the macro
// expander already handled the expansion at a higher level).
if let Some(ref source) = self.source {
let has_valid_spans = tokens.iter().any(|t| {
if let ast::TokenTree::Token(tok) = t {
let s = tok.span.start.to_usize();
let e = tok.span.end.to_usize();
e > s
&& e <= source.len()
&& source.is_char_boundary(s)
&& source.is_char_boundary(e)
&& {
// Verify the span actually points to code, not a comment
let text = &source[s..e];
// For an Ident token, the text should be alphanumeric
match &tok.kind {
crate::lexer::TokenKind::Ident => {
text.chars().all(|c| c.is_alphanumeric() || c == '_')
}
_ => true,
}
}
} else {
true // Delimited groups are fine
}
});
if !has_valid_spans && !tokens.is_empty() {
// Tokens have synthetic spans - this vec! was already expanded
// by the macro expander. Create an empty vec as placeholder,
// at the expected element type when one is known (else the f64
// default this path has always used).
let placeholder_elem = expected_elem.clone().unwrap_or_else(MirType::f64);
let (new_fn_name, _) = Self::vec_fn_names_for_type(&placeholder_elem)?;
let new_fn = MirValue::Function(Arc::from(new_fn_name));
let vec_ty = MirType::Vec(Box::new(placeholder_elem));
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
let vec_local = builder.create_local(vec_ty);
let cont = builder.create_block();
builder.call(new_fn, vec![], Some(vec_local), cont);
builder.switch_to_block(cont);
return Ok(MirValue::Local(vec_local));
}
}
// Split macro tokens into argument groups at top-level commas/semicolons.
let all_groups = self.split_vec_macro_token_groups(tokens);
if all_groups.is_empty() {
// vec![] with no args -- empty vec at the expected element type,
// else i32.
let empty_elem = expected_elem.clone().unwrap_or_else(MirType::i32);
let (new_fn_name, _) = Self::vec_fn_names_for_type(&empty_elem)?;
let new_fn = MirValue::Function(Arc::from(new_fn_name));
let vec_ty = MirType::Vec(Box::new(empty_elem));
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
let vec_local = builder.create_local(vec_ty);
let cont = builder.create_block();
builder.call(new_fn, vec![], Some(vec_local), cont);
builder.switch_to_block(cont);
return Ok(MirValue::Local(vec_local));
}
// Check for repeat syntax: vec![val; count]
let is_repeat = self.detect_vec_repeat_syntax(tokens);
if is_repeat && all_groups.len() == 2 {
// vec![val; count] -- repeat form
let val_tokens = all_groups[0].clone();
let count_tokens = all_groups[1].clone();
// Lower the value at the expected element type so a bare literal
// adopts the annotated width; fall back to the inferred type.
let prev_expected = self.expected_type.take();
self.expected_type = expected_elem.clone();
let val = self.parse_and_lower_token_group(val_tokens);
self.expected_type = prev_expected;
let val = val?;
let elem_ty = expected_elem
.clone()
.unwrap_or_else(|| self.type_of_value(&val));
let (new_fn_name, push_fn_name) = Self::vec_fn_names_for_type(&elem_ty)?;
let vec_ty = MirType::Vec(Box::new(elem_ty));
// Create the vec
let new_fn = MirValue::Function(Arc::from(new_fn_name));
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
let vec_local = builder.create_local(vec_ty);
let cont = builder.create_block();
builder.call(new_fn, vec![], Some(vec_local), cont);
builder.switch_to_block(cont);
// Parse and lower the count expression
let count_val = self.parse_and_lower_token_group(count_tokens)?;
// Emit a counted loop: for i in 0..count { vec_push(v, val) }
// We implement this as a simple while loop in MIR:
// let i = 0; while (i < count) { vec_push(v, val); i = i + 1; }
let i_local = {
let builder = self.current_fn.as_mut().unwrap();
let i = builder.create_local(MirType::i64());
builder.assign(
i,
MirRValue::Use(MirValue::Const(MirConst::Int(0, MirType::i64()))),
);
i
};
// Create loop blocks
let (loop_header, loop_body, loop_exit) = {
let builder = self.current_fn.as_mut().unwrap();
let header = builder.create_block();
let body = builder.create_block();
let exit = builder.create_block();
(header, body, exit)
};
// Jump to loop header
{
let builder = self.current_fn.as_mut().unwrap();
builder.goto(loop_header);
builder.switch_to_block(loop_header);
}
// Condition: i < count
let cond = {
let builder = self.current_fn.as_mut().unwrap();
let cond = builder.create_local(MirType::Bool);
builder.assign(
cond,
MirRValue::BinaryOp {
op: BinOp::Lt,
left: MirValue::Local(i_local),
right: count_val.clone(),
},
);
cond
};
// Branch on condition
{
let builder = self.current_fn.as_mut().unwrap();
builder.branch(MirValue::Local(cond), loop_body, loop_exit);
builder.switch_to_block(loop_body);
}
// Push the value
let push_fn = MirValue::Function(Arc::from(push_fn_name));
{
let builder = self.current_fn.as_mut().unwrap();
let cont2 = builder.create_block();
builder.call(push_fn, vec![MirValue::Local(vec_local), val], None, cont2);
builder.switch_to_block(cont2);
}
// Increment i
{
let builder = self.current_fn.as_mut().unwrap();
let incremented = builder.create_local(MirType::i64());
builder.assign(
incremented,
MirRValue::BinaryOp {
op: BinOp::Add,
left: MirValue::Local(i_local),
right: MirValue::Const(MirConst::Int(1, MirType::i64())),
},
);
builder.assign(i_local, MirRValue::Use(MirValue::Local(incremented)));
builder.goto(loop_header);
}
// Switch to exit block
{
let builder = self.current_fn.as_mut().unwrap();
builder.switch_to_block(loop_exit);
}
Ok(MirValue::Local(vec_local))
} else {
// vec![a, b, c] -- literal form
// Lower the first argument at the expected element type (so a bare
// literal adopts the annotated width), else infer from its value.
let first_tokens = all_groups[0].clone();
let prev_expected = self.expected_type.take();
self.expected_type = expected_elem.clone();
let first_val = self.parse_and_lower_token_group(first_tokens);
self.expected_type = prev_expected;
let first_val = first_val?;
let elem_ty = expected_elem
.clone()
.unwrap_or_else(|| self.type_of_value(&first_val));
let (new_fn_name, push_fn_name) = Self::vec_fn_names_for_type(&elem_ty)?;
let vec_ty = MirType::Vec(Box::new(elem_ty));
// Create the vec
let new_fn = MirValue::Function(Arc::from(new_fn_name));
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
let vec_local = builder.create_local(vec_ty);
let cont = builder.create_block();
builder.call(new_fn, vec![], Some(vec_local), cont);
builder.switch_to_block(cont);
// Push the first element
let push_fn_val = MirValue::Function(Arc::from(push_fn_name.as_str()));
{
let builder = self.current_fn.as_mut().unwrap();
let cont2 = builder.create_block();
builder.call(
push_fn_val,
vec![MirValue::Local(vec_local), first_val],
None,
cont2,
);
builder.switch_to_block(cont2);
}
// Push remaining elements, each lowered at the expected element type.
for group in &all_groups[1..] {
let prev_expected = self.expected_type.take();
self.expected_type = expected_elem.clone();
let val = self.parse_and_lower_token_group(group.clone());
self.expected_type = prev_expected;
let val = val?;
let push_fn_val = MirValue::Function(Arc::from(push_fn_name.as_str()));
let builder = self.current_fn.as_mut().unwrap();
let cont2 = builder.create_block();
builder.call(
push_fn_val,
vec![MirValue::Local(vec_local), val],
None,
cont2,
);
builder.switch_to_block(cont2);
}
Ok(MirValue::Local(vec_local))
}
}
/// Map a vec element type to its runtime build/push helper pair, or reject
/// the element type when the HVec runtime cannot store it.
///
/// Two storage strategies back a `Vec<T>`. Scalars and strings ride a
/// built-in `build_hvec_*_<suffix>` family: f64 (also f32), i64 (also
/// isize), i32 (the narrow integer widths, u32, char, and bool), and str.
/// A user struct, a nested vector, or a map rides a monomorphized,
/// element-sized wrapper the C backend emits per element type
/// (`vec_elem_needs_sized_wrapper` in codegen/backend/c.rs), keyed by the
/// struct name or the nested handle's C type. Selecting the wrapper suffix
/// here keeps `vec![Point { .. }]` in step with `v.push(Point { .. })`,
/// which the vec method accessors already lower through the same wrapper.
///
/// A tuple or an array element has no representation in either strategy: no
/// scalar family fits it and the backend emits no wrapper for it. Reject it
/// rather than fall through to the i32 family, which for an array element
/// silently miscompiled (the array decayed to a pointer truncated to
/// `int32_t` under `-Wint-conversion`, warn-only) and for a tuple leaked a
/// raw C type error. A vector of a tuple or array element is an honest gap;
/// it needs a wrapper that stores and projects the aggregate, the same path
/// structs and nested vectors already take.
///
/// Keep the supported suffixes in sync with `hvec_elem_suffix` and
/// `vec_elem_needs_sized_wrapper` in codegen/backend/c.rs and with the vec
/// method and free-function accessor tables in codegen/lower/expr.rs, so a
/// `vec![...]` builds the same typed handle those accessors later read.
fn vec_fn_names_for_type(elem_ty: &MirType) -> CodegenResult<(String, String)> {
let suffix: String = match elem_ty {
MirType::Float(FloatSize::F64) | MirType::Float(FloatSize::F32) => "f64".to_string(),
MirType::Int(IntSize::I8, true) => "i8".to_string(),
MirType::Int(IntSize::I16, true) => "i16".to_string(),
MirType::Int(IntSize::I32, true) => "i32".to_string(),
MirType::Int(IntSize::I64, true) => "i64".to_string(),
MirType::Int(IntSize::I128, true) => "i128".to_string(),
MirType::Int(IntSize::ISize, true) => "isize".to_string(),
MirType::Int(IntSize::I8, false) => "u8".to_string(),
MirType::Int(IntSize::I16, false) => "u16".to_string(),
MirType::Int(IntSize::I32, false) => "u32".to_string(),
MirType::Int(IntSize::I64, false) => "u64".to_string(),
MirType::Int(IntSize::I128, false) => "u128".to_string(),
MirType::Int(IntSize::ISize, false) => "usize".to_string(),
MirType::Struct(n) if n.as_ref() == "BuildString" => "str".to_string(),
MirType::Bool => "i32".to_string(),
// A user struct, a nested vector, or a map rides the element-sized
// wrapper the C backend generates; the suffix is the struct name or
// the nested handle's C type, matching hvec_elem_suffix.
MirType::Struct(n) => n.to_string(),
MirType::Vec(_) => "BuildVecHandle".to_string(),
MirType::Map(_, _) => "BuildMapHandle".to_string(),
// A view element: keyed by its slice struct name, as in
// hvec_elem_suffix.
MirType::Ptr(inner) if matches!(inner.as_ref(), MirType::Slice(_)) => {
match inner.as_ref() {
MirType::Slice(e) => MirType::slice_type_name(e).to_string(),
_ => unreachable!(),
}
}
_ => {
return Err(CodegenError::Unsupported(format!(
"a vector of `{elem_ty}` elements is not supported yet: the Vec \
runtime stores scalar (integer, float, bool, char), string, \
struct, nested-vector, and map elements, not a tuple or array \
element"
)))
}
};
Ok((
format!("build_hvec_new_{suffix}"),
format!("build_hvec_push_{suffix}"),
))
}
/// Extract all argument source texts from vec! macro tokens.
/// Unlike print macros, vec! has no format string to skip.
/// Split vec! macro tokens into argument token groups at top-level
/// commas or semicolons. Returns flattened token lists suitable for
/// passing directly to the parser, avoiding span-based source text
/// extraction which breaks when tokens have cross-source spans.
fn split_vec_macro_token_groups(
&self,
tokens: &[ast::TokenTree],
) -> Vec<Vec<crate::lexer::Token>> {
use crate::lexer::TokenKind;
// Unwrap outermost Delimited group if present
let inner: &[ast::TokenTree] = if tokens.len() == 1 {
if let ast::TokenTree::Delimited {
tokens: ref inner, ..
} = tokens[0]
{
inner
} else {
tokens
}
} else {
tokens
};
let mut groups: Vec<Vec<crate::lexer::Token>> = Vec::new();
let mut current: Vec<crate::lexer::Token> = Vec::new();
let mut depth: i32 = 0;
// Recursively flatten a TokenTree into a Vec<Token>
fn flatten_tree(tree: &ast::TokenTree, out: &mut Vec<crate::lexer::Token>) {
match tree {
ast::TokenTree::Token(tok) => out.push(tok.clone()),
ast::TokenTree::Delimited {
delimiter,
tokens: inner,
span,
} => {
out.push(crate::lexer::Token::new(
TokenKind::OpenDelim(*delimiter),
*span,
));
for t in inner {
flatten_tree(t, out);
}
out.push(crate::lexer::Token::new(
TokenKind::CloseDelim(*delimiter),
*span,
));
}
}
}
for token in inner {
match token {
ast::TokenTree::Token(tok) => match &tok.kind {
TokenKind::OpenDelim(_) => {
depth += 1;
current.push(tok.clone());
}
TokenKind::CloseDelim(_) => {
depth -= 1;
current.push(tok.clone());
}
TokenKind::Comma | TokenKind::Semi if depth == 0 => {
if !current.is_empty() {
groups.push(std::mem::take(&mut current));
}
}
_ => {
current.push(tok.clone());
}
},
ast::TokenTree::Delimited { .. } => {
// Flatten the delimited group into individual tokens
// so the parser can handle it
flatten_tree(token, &mut current);
}
}
}
if !current.is_empty() {
groups.push(current);
}
groups
}
/// Parse a token group as an expression and lower it.
fn parse_and_lower_token_group(
&mut self,
tokens: Vec<crate::lexer::Token>,
) -> CodegenResult<MirValue> {
use crate::lexer::SourceFile;
use crate::parser::Parser;
// Build source text. First try span-based extraction from source,
// then validate it by re-tokenizing. If validation fails, use
// reconstructed text from token kinds.
let source_text = self.extract_source_for_tokens(&tokens);
let sf = SourceFile::anonymous(source_text.as_str());
match crate::lexer::tokenize(source_text.as_str()) {
Ok(new_tokens) => {
let mut parser = Parser::new(&sf, new_tokens);
match parser.parse_expr() {
Ok(expr) => {
// The parsed expression's token spans are relative to
// `source_text` (the anonymous re-tokenized string), not
// the original file. Point self.source at it while we
// lower, so a nested macro that re-extracts source by
// span reads the right text. Without this, an inner
// vec! inside a Vec<Vec<_>> literal sliced the original
// file at a stale offset and pushed a garbage element
// (an unrelated identifier, then the 0 parse-failure
// default). Restore the previous source afterward.
let prev_source = self.source.replace(Arc::from(source_text.as_str()));
let result = self.lower_expr(&expr);
self.source = prev_source;
result
}
Err(_) => {
// Parsing failed - tokens likely have synthetic spans.
// Return a sensible default (0 for numerics).
Ok(MirValue::Const(MirConst::Int(0, MirType::i64())))
}
}
}
Err(_) => {
// Tokenization failed - return default
Ok(MirValue::Const(MirConst::Int(0, MirType::i64())))
}
}
}
/// Extract source text for a token group. Tries span-based extraction first,
/// validates by checking token count matches, falls back to reconstruction.
fn extract_source_for_tokens(&self, tokens: &[crate::lexer::Token]) -> String {
if let Some(ref src) = self.source {
let first_start = tokens.first().map(|t| t.span.start.to_usize()).unwrap_or(0);
let last_end = tokens.last().map(|t| t.span.end.to_usize()).unwrap_or(0);
if last_end > first_start
&& last_end <= src.len()
&& src.is_char_boundary(first_start)
&& src.is_char_boundary(last_end)
{
// With the module merge's renames applied (a module call in a
// `vec![...]` element).
let candidate = renamed_slice(
src,
first_start,
last_end,
tokens.first().map(|t| t.span.source_id),
);
// Validate: re-tokenize and check it produces a similar token count
if let Ok(re_tokens) = crate::lexer::tokenize(candidate.as_str()) {
// If re-tokenization gives roughly the same number of tokens, use it
if re_tokens.len() >= tokens.len().saturating_sub(2)
&& re_tokens.len() <= tokens.len() + 2
{
return candidate;
}
}
}
}
// Fallback: reconstruct from token kinds
self.reconstruct_source_from_tokens(tokens)
}
/// Reconstruct source text from token kinds when spans are unreliable.
fn reconstruct_source_from_tokens(&self, tokens: &[crate::lexer::Token]) -> String {
use crate::lexer::{Delimiter, LiteralKind, TokenKind};
let mut parts = Vec::new();
for tok in tokens {
let text = match &tok.kind {
TokenKind::Ident | TokenKind::RawIdent | TokenKind::Lifetime => {
// Try to extract from source
if let Some(ref src) = self.source {
let s = tok.span.start.to_usize();
let e = tok.span.end.to_usize();
if e > s
&& e <= src.len()
&& src.is_char_boundary(s)
&& src.is_char_boundary(e)
{
src[s..e].to_string()
} else {
"_".to_string()
}
} else {
"_".to_string()
}
}
TokenKind::Literal { kind, suffix: _ } => {
if let Some(ref src) = self.source {
let s = tok.span.start.to_usize();
let e = tok.span.end.to_usize();
if e > s && e <= src.len() {
src[s..e].to_string()
} else {
match kind {
LiteralKind::Int { .. } => "0".to_string(),
LiteralKind::Float { .. } => "0.0".to_string(),
LiteralKind::Str { .. } => "\"\"".to_string(),
LiteralKind::Char { .. } => "'\\0'".to_string(),
_ => "0".to_string(),
}
}
} else {
"0".to_string()
}
}
TokenKind::Keyword(kw) => format!("{:?}", kw).to_lowercase(),
TokenKind::Plus => "+".to_string(),
TokenKind::Minus => "-".to_string(),
TokenKind::Star => "*".to_string(),
TokenKind::Slash => "/".to_string(),
TokenKind::Percent => "%".to_string(),
TokenKind::And => "&".to_string(),
TokenKind::Or => "|".to_string(),
TokenKind::Caret => "^".to_string(),
TokenKind::Not => "!".to_string(),
TokenKind::Dot => ".".to_string(),
TokenKind::DotDot => "..".to_string(),
TokenKind::DotDotEq => "..=".to_string(),
TokenKind::Comma => ",".to_string(),
TokenKind::Semi => ";".to_string(),
TokenKind::Colon => ":".to_string(),
TokenKind::ColonColon => "::".to_string(),
TokenKind::Eq => "=".to_string(),
TokenKind::EqEq => "==".to_string(),
TokenKind::Ne => "!=".to_string(),
TokenKind::Lt => "<".to_string(),
TokenKind::Gt => ">".to_string(),
TokenKind::Le => "<=".to_string(),
TokenKind::Ge => ">=".to_string(),
TokenKind::OpenDelim(Delimiter::Paren) => "(".to_string(),
TokenKind::OpenDelim(Delimiter::Bracket) => "[".to_string(),
TokenKind::OpenDelim(Delimiter::Brace) => "{".to_string(),
TokenKind::CloseDelim(Delimiter::Paren) => ")".to_string(),
TokenKind::CloseDelim(Delimiter::Bracket) => "]".to_string(),
TokenKind::CloseDelim(Delimiter::Brace) => "}".to_string(),
TokenKind::Arrow => "->".to_string(),
TokenKind::FatArrow => "=>".to_string(),
TokenKind::Underscore => "_".to_string(),
TokenKind::Tilde => "~".to_string(),
TokenKind::At => "@".to_string(),
TokenKind::Pound => "#".to_string(),
TokenKind::Question => "?".to_string(),
TokenKind::Shl => "<<".to_string(),
TokenKind::Shr => ">>".to_string(),
_ => {
// Fallback: try span extraction
if let Some(ref src) = self.source {
let s = tok.span.start.to_usize();
let e = tok.span.end.to_usize();
if e > s
&& e <= src.len()
&& src.is_char_boundary(s)
&& src.is_char_boundary(e)
{
src[s..e].to_string()
} else {
" ".to_string()
}
} else {
" ".to_string()
}
}
};
parts.push(text);
}
parts.join(" ")
}
/// Detect whether the token stream contains a semicolon at the top level,
/// indicating the `vec![val; count]` repeat syntax.
fn detect_vec_repeat_syntax(&self, tokens: &[ast::TokenTree]) -> bool {
use crate::lexer::{Delimiter, TokenKind};
// Unwrap outermost Delimited if present, don't flatten
let inner: &[ast::TokenTree] = if tokens.len() == 1 {
if let ast::TokenTree::Delimited {
tokens: ref inner, ..
} = tokens[0]
{
inner
} else {
tokens
}
} else {
tokens
};
let mut depth: i32 = 0;
for token in inner {
match token {
ast::TokenTree::Delimited { .. } => {
// Nested delimited group - skip it entirely (don't
// look inside for semicolons).
}
ast::TokenTree::Token(tok) => match &tok.kind {
TokenKind::OpenDelim(Delimiter::Paren)
| TokenKind::OpenDelim(Delimiter::Bracket)
| TokenKind::OpenDelim(Delimiter::Brace) => depth += 1,
TokenKind::CloseDelim(Delimiter::Paren)
| TokenKind::CloseDelim(Delimiter::Bracket)
| TokenKind::CloseDelim(Delimiter::Brace) => depth -= 1,
TokenKind::Semi if depth == 0 => return true,
_ => {}
},
}
}
false
}
/// Shared format-macro processing for `print!`/`println!`/`format!`: parse
/// the format string and arguments, convert `{}`/`{:?}`/`{:.N}` placeholders
/// to C printf specifiers, intern the C format string, and return its string
/// index plus the lowered argument values (BuildString args reduced to their
/// `.ptr`, trimmed to the placeholder count).
fn prepare_format_call(
&mut self,
tokens: &[ast::TokenTree],
newline: bool,
) -> CodegenResult<(u32, Vec<MirValue>)> {
use super::format::{parse_format, ArgRef, Piece};
let format_str = self.extract_string_from_tokens(tokens);
let pieces = parse_format(&format_str).map_err(|message| CodegenError::Rejected {
message,
location: None,
help: Some(
"supported: `{}`, `{:?}`, `{name}`, `{0}`, width, `<` `>` alignment, `+`, `#`, `0`, \
precision, and `x` `X` `o`"
.to_string(),
),
})?;
// Lower the explicit arguments in order. A failure is an error, not a
// silently missing value.
let arg_source_texts = self.extract_arg_source_texts(tokens);
let mut explicit: Vec<(MirValue, String)> = Vec::new();
for src in &arg_source_texts {
let val = self.parse_and_lower_macro_arg(src)?;
explicit.push((val, src.trim().to_string()));
}
let mut c_fmt = String::new();
let mut values = Vec::new();
let mut next = 0usize;
for piece in &pieces {
match piece {
Piece::Text(t) => c_fmt.push_str(&t.replace('%', "%%")),
Piece::Arg(arg_ref, spec) => {
let (val, what) = match arg_ref {
ArgRef::Next => {
let i = next;
next += 1;
explicit.get(i).cloned().ok_or_else(|| CodegenError::Rejected {
message: format!(
"format string `{format_str}` has more `{{}}` placeholders than arguments"
),
location: None,
help: Some("pass one argument per `{}`".to_string()),
})?
}
ArgRef::Index(i) => {
explicit.get(*i).cloned().ok_or_else(|| CodegenError::Rejected {
message: format!(
"format string `{format_str}` refers to argument {i}, which was not passed"
),
location: None,
help: Some("positional arguments count from 0".to_string()),
})?
}
ArgRef::Name(name) => {
(self.parse_and_lower_macro_arg(name)?, name.clone())
}
};
let (conv, arg) = self.fmt_placeholder(val, spec, &what)?;
c_fmt.push_str(&conv);
if let Some(a) = arg {
values.push(a);
}
}
}
}
if newline {
c_fmt.push('\n');
}
let str_idx = self.module.intern_string(c_fmt);
Ok((str_idx, values))
}
/// `print!`/`println!`/`eprint!`/`eprintln!`/`dbg!`: format the arguments
/// and lower to a backend-neutral stdout or stderr printf-style output call.
pub(crate) fn lower_print_macro(
&mut self,
tokens: &[ast::TokenTree],
newline: bool,
stderr: bool,
) -> CodegenResult<()> {
let (str_idx, arg_values) = self.prepare_format_call(tokens, newline)?;
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function for macro".into()))?;
let fmt_local = builder.create_local(MirType::Ptr(Box::new(MirType::i8())));
builder.assign(
fmt_local,
MirRValue::Use(MirValue::Const(MirConst::Str(str_idx))),
);
let continue_block = builder.create_block();
let print_fn = if stderr { "eprintf" } else { "printf" };
let mut call_args = vec![MirValue::Local(fmt_local)];
call_args.extend(arg_values);
builder.call(
MirValue::Function(Arc::from(print_fn)),
call_args,
None,
continue_block,
);
builder.switch_to_block(continue_block);
Ok(())
}
/// `format!`: build an owned `BuildString` from the format string and
/// arguments via the variadic `build_sprintf` runtime function (no trailing
/// newline; returns the string instead of printing it).
pub(crate) fn lower_format_macro(
&mut self,
tokens: &[ast::TokenTree],
) -> CodegenResult<MirValue> {
let (str_idx, arg_values) = self.prepare_format_call(tokens, false)?;
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function for macro".into()))?;
let fmt_local = builder.create_local(MirType::Ptr(Box::new(MirType::i8())));
builder.assign(
fmt_local,
MirRValue::Use(MirValue::Const(MirConst::Str(str_idx))),
);
let result = builder.create_local(MirType::Struct(Arc::from("BuildString")));
let continue_block = builder.create_block();
let sprintf_fn = MirValue::Function(Arc::from("build_sprintf"));
let mut call_args = vec![MirValue::Local(fmt_local)];
call_args.extend(arg_values);
builder.call(sprintf_fn, call_args, Some(result), continue_block);
builder.switch_to_block(continue_block);
Ok(values::local(result))
}
/// Extract the source text of each argument expression in a macro call,
/// after the format string. Returns a Vec of source-text strings, one
/// per argument. Uses token spans to find comma-separated argument
/// boundaries in the original source.
fn extract_arg_source_texts(&self, tokens: &[ast::TokenTree]) -> Vec<String> {
use crate::lexer::{Delimiter, TokenKind};
let source = match self.source {
Some(ref s) => s,
None => return Vec::new(),
};
// Unwrap the outermost Delimited group if present, but do NOT flatten
// nested groups - their spans must stay intact for correct source extraction.
let inner: &[ast::TokenTree] = if tokens.len() == 1 {
if let ast::TokenTree::Delimited {
tokens: ref inner, ..
} = tokens[0]
{
inner
} else {
tokens
}
} else {
tokens
};
// Walk the token list, tracking delimiter depth to distinguish
// top-level argument-separating commas from commas inside nested expressions.
let source_id = inner.iter().find_map(|tree| match tree {
ast::TokenTree::Token(tok) => Some(tok.span.source_id),
ast::TokenTree::Delimited { span, .. } => Some(span.source_id),
});
let mut args = Vec::new();
let mut past_format_string = false;
let mut depth: i32 = 0;
let mut current_arg_start: Option<usize> = None; // byte offset in source
let mut current_arg_end: usize = 0;
for token in inner {
match token {
ast::TokenTree::Delimited { span, .. } => {
if !past_format_string {
continue;
}
// Use the full span of the delimited group to extend
// the current argument range without flattening.
let s = span.start.to_usize();
let e = span.end.to_usize();
if current_arg_start.is_none() {
current_arg_start = Some(s);
}
if e > current_arg_end {
current_arg_end = e;
}
}
ast::TokenTree::Token(tok) => {
if !past_format_string {
if let TokenKind::Literal { kind, .. } = &tok.kind {
if matches!(kind, crate::lexer::LiteralKind::Str { .. }) {
past_format_string = true;
}
}
continue;
}
// Track parenthesis/bracket/brace depth
match &tok.kind {
TokenKind::OpenDelim(Delimiter::Paren)
| TokenKind::OpenDelim(Delimiter::Bracket)
| TokenKind::OpenDelim(Delimiter::Brace) => {
depth += 1;
let s = tok.span.start.to_usize();
let e = tok.span.end.to_usize();
if current_arg_start.is_none() {
current_arg_start = Some(s);
}
if e > current_arg_end {
current_arg_end = e;
}
}
TokenKind::CloseDelim(Delimiter::Paren)
| TokenKind::CloseDelim(Delimiter::Bracket)
| TokenKind::CloseDelim(Delimiter::Brace) => {
depth -= 1;
let s = tok.span.start.to_usize();
let e = tok.span.end.to_usize();
if current_arg_start.is_none() {
current_arg_start = Some(s);
}
if e > current_arg_end {
current_arg_end = e;
}
}
TokenKind::Comma if depth == 0 => {
// Top-level comma: flush current argument
if let Some(start) = current_arg_start {
if current_arg_end > start && current_arg_end <= source.len() {
let text =
renamed_slice(source, start, current_arg_end, source_id);
if !text.is_empty() {
args.push(text);
}
}
current_arg_start = None;
current_arg_end = 0;
}
}
_ => {
// Extend current argument span
let s = tok.span.start.to_usize();
let e = tok.span.end.to_usize();
if current_arg_start.is_none() {
current_arg_start = Some(s);
}
if e > current_arg_end {
current_arg_end = e;
}
}
}
}
}
}
// Flush any remaining argument
if let Some(start) = current_arg_start {
if current_arg_end > start && current_arg_end <= source.len() {
let text = renamed_slice(source, start, current_arg_end, source_id);
if !text.is_empty() {
args.push(text);
}
}
}
args
}
/// Parse a source text fragment as an expression, then lower it through
/// the normal expression-lowering pipeline.
fn parse_and_lower_macro_arg(&mut self, src: &str) -> CodegenResult<MirValue> {
use crate::lexer::SourceFile;
use crate::parser::Parser;
// Create a mini source file for the expression fragment
let sf = SourceFile::anonymous(src);
let tokens = crate::lexer::tokenize(src).map_err(|e| {
CodegenError::Internal(format!("Failed to tokenize macro arg '{}': {:?}", src, e))
})?;
let mut parser = Parser::new(&sf, tokens);
let expr = parser.parse_expr().map_err(|e| {
CodegenError::Internal(format!("Failed to parse macro arg '{}': {:?}", src, e))
})?;
// The fragment's spans index into `src`, not the file. A nested macro
// (`println!("{:?}", vec![1, 2])`) reads its arguments through
// `self.source` and used to read the file's text at those offsets
// (`vec![1, 2]` became `vec![i, 0]`). Point `self.source` at the
// fragment while lowering it, and drop locations meant for the file.
let saved_source = self.source.replace(Arc::from(src));
let saved_fragment = std::mem::replace(&mut self.in_macro_fragment, true);
let result = self.lower_expr(&expr);
self.source = saved_source;
self.in_macro_fragment = saved_fragment;
let val = result?;
// A global read inline has no local to carry its type: a `bool` was
// passed to `%s` as it was (a crash) and a `char` printed as its code.
// Copy it into a typed local, as a `let` would.
if let MirValue::Global(name) = &val {
let is_char = self.char_globals.contains(name);
let ty = self.module.find_global(name).map(|g| g.ty.clone());
if let Some(ty) = ty.filter(|t| is_char || matches!(t, MirType::Bool)) {
let builder = self.current_fn.as_mut().ok_or_else(|| {
CodegenError::Internal("No current function for macro".into())
})?;
let local = builder.create_local(ty);
builder.assign(local, MirRValue::Use(val.clone()));
if is_char {
self.char_locals.insert(local);
}
return Ok(MirValue::Local(local));
}
}
// `x as char` or a call to a `-> char` function prints as a character.
// A `let` marks its local as a char; an argument written inline has no
// `let`, so mark its value here (`format!("{}", 65u32 as char)` gave
// `65` before).
let call_is_char = match &expr.kind {
ExprKind::Call { func, .. } => match &func.kind {
ExprKind::Ident(id) => self.fn_returns_char.contains(&id.name),
_ => false,
},
_ => false,
};
if Self::expr_is_char_literal_or_cast(&expr) || call_is_char {
let ty = self.type_of_value(&val);
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function for macro".into()))?;
let local = builder.create_local(ty);
builder.assign(local, MirRValue::Use(val));
self.char_locals.insert(local);
return Ok(MirValue::Local(local));
}
Ok(val)
}
/// Walk a Rust-style format string and report, for each placeholder in
/// order, whether it is a plain `{}` (default Display). Escaped braces
/// (`{{`, `}}`) are skipped and every `{:...}` form reports `false`. The
/// brace bookkeeping mirrors the placeholder loop in `prepare_format_call`,
/// so index `i` here lines up with placeholder `i` there.
fn placeholder_is_plain(format_str: &str) -> Vec<bool> {
let mut kinds = Vec::new();
let mut chars = format_str.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '{' {
match chars.peek() {
Some('{') => {
chars.next();
}
Some('}') => {
chars.next();
kinds.push(true);
}
Some(':') => {
chars.next();
while let Some(&c) = chars.peek() {
chars.next();
if c == '}' {
break;
}
}
kinds.push(false);
}
_ => {}
}
} else if ch == '}' && chars.peek() == Some(&'}') {
chars.next();
}
}
kinds
}
/// Pick the correct printf format specifier based on the MIR type.
fn format_specifier_for_type(&self, ty: Option<&MirType>, precision: Option<&str>) -> String {
match ty {
Some(MirType::Int(IntSize::I128, _)) => "%s".to_string(),
Some(MirType::Int(IntSize::I64 | IntSize::ISize, true)) => "%lld".to_string(),
Some(MirType::Int(IntSize::I64 | IntSize::ISize, false)) => "%llu".to_string(),
Some(MirType::Int(_, true)) => "%d".to_string(),
Some(MirType::Int(_, false)) => "%u".to_string(),
Some(MirType::Float(FloatSize::F32)) | Some(MirType::Float(FloatSize::F64)) => {
if let Some(prec) = precision {
format!("%.{}f", prec)
} else {
"%g".to_string()
}
}
Some(MirType::Bool) => "%s".to_string(), // printed via ternary in C
Some(MirType::Ptr(_)) => "%s".to_string(), // assume string pointer
Some(MirType::Struct(name)) if name.as_ref() == "BuildString" => "%s".to_string(),
_ => "%d".to_string(), // default for integers (most common)
}
}
/// Return a short debug type name for {:?} format.
fn type_debug_name(&self, ty: Option<&MirType>) -> String {
match ty {
Some(MirType::Int(IntSize::I8, true)) => "i8",
Some(MirType::Int(IntSize::I16, true)) => "i16",
Some(MirType::Int(IntSize::I32, true)) => "i32",
Some(MirType::Int(IntSize::I64, true)) => "i64",
Some(MirType::Int(IntSize::I8, false)) => "u8",
Some(MirType::Int(IntSize::I16, false)) => "u16",
Some(MirType::Int(IntSize::I32, false)) => "u32",
Some(MirType::Int(IntSize::I64, false)) => "u64",
Some(MirType::Float(FloatSize::F32)) => "f32",
Some(MirType::Float(FloatSize::F64)) => "f64",
Some(MirType::Bool) => "bool",
Some(MirType::Ptr(_)) => "str",
Some(MirType::Struct(name)) => return name.to_string(),
_ => "i32",
}
.to_string()
}
pub(crate) fn lower_panic_macro(&mut self, tokens: &[ast::TokenTree]) -> CodegenResult<()> {
// Print the panic message first
self.lower_print_macro(tokens, true, false)?;
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function for macro".into()))?;
// Call abort() after printing
builder.abort();
// Create an unreachable continuation block for any code after panic
let unreachable_block = builder.create_block();
builder.switch_to_block(unreachable_block);
Ok(())
}
pub(crate) fn extract_string_from_tokens(&self, tokens: &[ast::TokenTree]) -> String {
use crate::lexer::TokenKind;
for token in tokens {
match token {
ast::TokenTree::Token(tok) => {
if let TokenKind::Literal { kind, .. } = &tok.kind {
if matches!(kind, crate::lexer::LiteralKind::Str { .. }) {
// Try to extract the string content from source via span
if let Some(ref source) = self.source {
let start = tok.span.start.to_usize();
let end = tok.span.end.to_usize();
if start < source.len() && end <= source.len() && start < end {
if let Some(raw) = source.get(start..end) {
// Strip surrounding quotes
// Strip exactly one quote at each end:
// `trim_end_matches` would also eat an
// escaped quote before the closing one.
let content = raw.strip_prefix('"').unwrap_or(raw);
let content = content.strip_suffix('"').unwrap_or(content);
// The span holds the source spelling;
// the format string is its value, so
// `\n` must become a newline here (the
// C backend escapes it again).
return crate::lexer::unescape_str(content);
}
}
}
// Fallback: return empty string if source not available
return String::new();
}
}
}
ast::TokenTree::Delimited { tokens: inner, .. } => {
let result = self.extract_string_from_tokens(inner);
if !result.is_empty() {
return result;
}
}
}
}
String::new()
}
fn extract_arg_idents_from_tokens(&self, tokens: &[ast::TokenTree]) -> Vec<String> {
use crate::lexer::TokenKind;
let mut args = Vec::new();
let mut past_first_comma = false;
let mut current_arg = String::new();
// Flatten delimited groups
let flat: Vec<&ast::TokenTree> = tokens
.iter()
.flat_map(|t| match t {
ast::TokenTree::Delimited { tokens: inner, .. } => inner.iter().collect::<Vec<_>>(),
other => vec![other],
})
.collect();
for token in &flat {
if let ast::TokenTree::Token(tok) = token {
match &tok.kind {
TokenKind::Comma => {
if past_first_comma && !current_arg.is_empty() {
args.push(std::mem::take(&mut current_arg));
}
past_first_comma = true;
}
TokenKind::Ident if past_first_comma => {
// Extract identifier name from source via span
if let Some(ref source) = self.source {
let start = tok.span.start.to_usize();
let end = tok.span.end.to_usize();
if start < source.len() && end <= source.len() {
let name = source.get(start..end).unwrap_or("");
if current_arg.is_empty() {
current_arg = name.to_string();
} else {
// Appending after a dot
current_arg.push_str(name);
}
}
}
}
TokenKind::Dot if past_first_comma && !current_arg.is_empty() => {
// Part of a field access expression: ident.field
current_arg.push('.');
}
_ => {}
}
}
}
// Flush any remaining argument
if past_first_comma && !current_arg.is_empty() {
args.push(current_arg);
}
args
}
// =================================================================
// Iterator chain lowering: .iter().map(|x| ...).collect() → loop
// =================================================================
/// Try to parse a method call chain as an iterator pipeline.
/// Returns `None` if the chain doesn't start with `.iter()`.
///
/// Walks backwards from the terminal (`collect` or `fold`) through
/// nested `MethodCall` receivers until it finds `.iter()`.
pub(crate) fn try_parse_iter_chain<'a>(
terminal_receiver: &'a ast::Expr,
terminal_name: &str,
terminal_args: &'a [ast::Expr],
) -> Option<IterChain<'a>> {
let terminal = match terminal_name {
"collect" => IterTerminal::Collect,
"fold" if terminal_args.len() == 2 => IterTerminal::Fold {
init: &terminal_args[0],
closure: &terminal_args[1],
},
"sum" if terminal_args.is_empty() => IterTerminal::Sum,
"count" if terminal_args.is_empty() => IterTerminal::Count,
"product" if terminal_args.is_empty() => IterTerminal::Product,
"any" if terminal_args.len() == 1 => IterTerminal::Any {
closure: &terminal_args[0],
},
"all" if terminal_args.len() == 1 => IterTerminal::All {
closure: &terminal_args[0],
},
_ => return None,
};
// Walk backwards through the MethodCall chain.
let mut steps: Vec<IterStep<'a>> = Vec::new();
let mut current = terminal_receiver;
loop {
match ¤t.kind {
ExprKind::MethodCall {
receiver,
method,
args,
..
} => {
let name = method.name.as_ref();
match name {
"iter" => {
// Found the base - `receiver` is the source vec.
steps.reverse();
return Some(IterChain {
source: receiver,
steps,
terminal,
});
}
"map" if args.len() == 1 => {
steps.push(IterStep::Map { closure: &args[0] });
current = receiver;
}
"filter" if args.len() == 1 => {
steps.push(IterStep::Filter { closure: &args[0] });
current = receiver;
}
"enumerate" if args.is_empty() => {
steps.push(IterStep::Enumerate);
current = receiver;
}
"cloned" if args.is_empty() => {
steps.push(IterStep::Cloned);
current = receiver;
}
"rev" if args.is_empty() => {
steps.push(IterStep::Rev);
current = receiver;
}
"take" if args.len() == 1 => {
steps.push(IterStep::Take { count: &args[0] });
current = receiver;
}
"skip" if args.len() == 1 => {
steps.push(IterStep::Skip { count: &args[0] });
current = receiver;
}
_ => return None, // Unknown intermediate method
}
}
_ => return None, // Chain doesn't lead to a MethodCall
}
}
}
/// Lower a fully parsed iterator chain into an imperative loop.
///
/// For `.collect()` terminals, produces:
/// ```text
/// let result = vec_new_T();
/// for i in 0..vec_len(source) {
/// let elem = vec_get_T(source, i);
/// // apply each step transform
/// vec_push_T(result, final_elem);
/// }
/// result
/// ```
///
/// For `.fold(init, |acc, x| body)` terminals, produces:
/// ```text
/// let acc = init;
/// for i in 0..vec_len(source) {
/// let elem = vec_get_T(source, i);
/// // apply each step transform
/// acc = body(acc, elem);
/// }
/// acc
/// ```
pub(crate) fn lower_iter_chain(&mut self, chain: &IterChain<'_>) -> CodegenResult<MirValue> {
// 1. Lower the source vec expression.
let source_val = self.lower_expr(chain.source)?;
let source_ty = self.type_of_value(&source_val);
// Determine the element type from the Vec type.
let elem_ty = match &source_ty {
MirType::Vec(inner) => inner.as_ref().clone(),
_ => MirType::f64(), // Fallback; most spectrum usage is f64
};
// Select the correct runtime function names for the element type.
let (get_fn_name, len_fn_name) = Self::vec_get_len_fn_names(&elem_ty)?;
// Store source in a local so we can reference it in the loop.
let source_local = {
let builder = self
.current_fn
.as_mut()
.ok_or_else(|| CodegenError::Internal("No current function".to_string()))?;
let loc = builder.create_local(source_ty.clone());
builder.assign(loc, MirRValue::Use(source_val));
loc
};
// 2. Get the length: len = vec_len(source)
let len_local = {
let builder = self.current_fn.as_mut().unwrap();
let len = builder.create_local(MirType::i64());
let cont = builder.create_block();
builder.call(
MirValue::Function(Arc::from(len_fn_name)),
vec![values::local(source_local)],
Some(len),
cont,
);
builder.switch_to_block(cont);
len
};
// 3. Check for enumerate step - affects how many closure params we
// bind (index + element vs just element).
let has_enumerate = chain.steps.iter().any(|s| matches!(s, IterStep::Enumerate));
// `.rev()` iterates the source in reverse: start at len-1, step down,
// exit when the (signed) index drops below 0.
let reversed = chain.steps.iter().any(|s| matches!(s, IterStep::Rev));
// 4. Determine result element type by walking the steps.
// After map closures, the type may change based on the closure's
// return type annotation. For now we infer from the closure.
let output_elem_ty = self.infer_chain_output_type(&elem_ty, &chain.steps);
let (new_fn_name, push_fn_name) = Self::vec_fn_names_for_type(&output_elem_ty)?;
// 5. Set up the result value depending on terminal type.
let (result_local, _is_collect) = match &chain.terminal {
IterTerminal::Collect => {
// Create the output vec.
let builder = self.current_fn.as_mut().unwrap();
let vec_ty = MirType::Vec(Box::new(output_elem_ty.clone()));
let result = builder.create_local(vec_ty);
let cont = builder.create_block();
builder.call(
MirValue::Function(Arc::from(new_fn_name)),
vec![],
Some(result),
cont,
);
builder.switch_to_block(cont);
(result, true)
}
IterTerminal::Fold { init, .. } => {
// Lower the initial accumulator value.
let init_val = self.lower_expr(init)?;
let init_ty = self.type_of_value(&init_val);
let builder = self.current_fn.as_mut().unwrap();
let acc = builder.create_local(init_ty);
builder.assign(acc, MirRValue::Use(init_val));
(acc, false)
}
IterTerminal::Sum => {
// `sum` adds numbers. Summing strings or structs has no meaning
// here (Rust has no `Sum` for them either) and used to emit an
// integer accumulator assigned to a string.
if !matches!(output_elem_ty, MirType::Int(..) | MirType::Float(..)) {
return Err(CodegenError::Rejected {
message: format!(
"`sum` needs numeric elements, found `{}`",
output_elem_ty.to_string().replace("BuildString", "str")
),
location: self
.source
.as_deref()
.and_then(|src| crate::codegen::c_verify::locate_call(src, "sum")),
help: Some(
"to join strings, loop over them and append each with `s = s + &x;`"
.to_string(),
),
});
}
// Accumulator of the output element type, initialized to zero.
let zero = match &output_elem_ty {
MirType::Float(_) => MirConst::Float(0.0, output_elem_ty.clone()),
_ => MirConst::Int(0, output_elem_ty.clone()),
};
let builder = self.current_fn.as_mut().unwrap();
let acc = builder.create_local(output_elem_ty.clone());
builder.assign(acc, MirRValue::Use(MirValue::Const(zero)));
(acc, false)
}
IterTerminal::Count => {
// i64 counter initialized to zero; the element value is ignored.
let builder = self.current_fn.as_mut().unwrap();
let acc = builder.create_local(MirType::i64());
builder.assign(
acc,
MirRValue::Use(MirValue::Const(MirConst::Int(0, MirType::i64()))),
);
(acc, false)
}
IterTerminal::Product => {
// Accumulator of the output element type, initialized to one.
let one = match &output_elem_ty {
MirType::Float(_) => MirConst::Float(1.0, output_elem_ty.clone()),
_ => MirConst::Int(1, output_elem_ty.clone()),
};
let builder = self.current_fn.as_mut().unwrap();
let acc = builder.create_local(output_elem_ty.clone());
builder.assign(acc, MirRValue::Use(MirValue::Const(one)));
(acc, false)
}
IterTerminal::Any { .. } => {
// bool accumulator, false until a matching element is seen.
let builder = self.current_fn.as_mut().unwrap();
let acc = builder.create_local(MirType::Bool);
builder.assign(acc, MirRValue::Use(MirValue::Const(MirConst::Bool(false))));
(acc, false)
}
IterTerminal::All { .. } => {
// bool accumulator, true until a non-matching element is seen.
let builder = self.current_fn.as_mut().unwrap();
let acc = builder.create_local(MirType::Bool);
builder.assign(acc, MirRValue::Use(MirValue::Const(MirConst::Bool(true))));
(acc, false)
}
};
// Per-step counters for take/skip, created before the loop so they
// persist across iterations. Indexed by step position; None for steps
// that don't need a counter. Counting yielded/skipped elements (rather
// than checking the source index) makes take/skip compose correctly with
// each other and with filter.
let step_counters: Vec<Option<LocalId>> = {
let builder = self.current_fn.as_mut().unwrap();
chain
.steps
.iter()
.map(|s| match s {
IterStep::Take { .. } | IterStep::Skip { .. } => {
let c = builder.create_local(MirType::i64());
builder.assign(
c,
MirRValue::Use(MirValue::Const(MirConst::Int(0, MirType::i64()))),
);
Some(c)
}
_ => None,
})
.collect()
};
// 6. Create the loop: for i in 0..len { ... }
let idx_local = {
let builder = self.current_fn.as_mut().unwrap();
let idx = builder.create_local(MirType::i64());
if reversed {
// idx = len - 1
builder.binary_op(
idx,
BinOp::Sub,
values::local(len_local),
MirValue::Const(MirConst::Int(1, MirType::i64())),
);
} else {
builder.assign(
idx,
MirRValue::Use(MirValue::Const(MirConst::Int(0, MirType::i64()))),
);
}
idx
};
let (cond_block, body_block, incr_block, exit_block) = {
let builder = self.current_fn.as_mut().unwrap();
let cond = builder.create_block();
let body = builder.create_block();
let incr = builder.create_block();
let exit = builder.create_block();
builder.goto(cond);
builder.switch_to_block(cond);
(cond, body, incr, exit)
};
// Condition: forward `idx < len`, reversed `idx >= 0`.
{
let builder = self.current_fn.as_mut().unwrap();
let cmp = builder.create_local(MirType::Bool);
if reversed {
builder.binary_op(
cmp,
BinOp::Ge,
values::local(idx_local),
MirValue::Const(MirConst::Int(0, MirType::i64())),
);
} else {
builder.binary_op(
cmp,
BinOp::Lt,
values::local(idx_local),
values::local(len_local),
);
}
builder.branch(values::local(cmp), body_block, exit_block);
builder.switch_to_block(body_block);
}
// 7. Loop body: get element, apply transforms.
let elem_local = {
let builder = self.current_fn.as_mut().unwrap();
let elem = builder.create_local(elem_ty.clone());
let cont = builder.create_block();
builder.call(
MirValue::Function(Arc::from(get_fn_name)),
vec![values::local(source_local), values::local(idx_local)],
Some(elem),
cont,
);
builder.switch_to_block(cont);
elem
};
// Apply each step transform to produce the final value.
let mut current_val = values::local(elem_local);
for (step_idx, step) in chain.steps.iter().enumerate() {
match step {
IterStep::Map { closure } => {
current_val = self.lower_iter_map_inline(
closure,
current_val,
if has_enumerate {
Some(values::local(idx_local))
} else {
None
},
)?;
}
IterStep::Filter { closure } => {
// Evaluate the predicate on the current element; if it does
// not hold, skip straight to the increment block (drop this
// element from the rest of the pipeline and the terminal).
let keep = self.lower_iter_map_inline(
closure,
current_val.clone(),
if has_enumerate {
Some(values::local(idx_local))
} else {
None
},
)?;
let builder = self.current_fn.as_mut().unwrap();
let keep_block = builder.create_block();
builder.branch(keep, keep_block, incr_block);
builder.switch_to_block(keep_block);
}
IterStep::Enumerate => {
// enumerate doesn't change the value; it just means
// subsequent map closures get (index, elem). The index
// is passed via the idx_local when lowering map closures.
}
IterStep::Cloned => {
// No-op for Copy types.
}
IterStep::Rev => {
// Direction is handled by the loop bounds; per-element no-op.
}
IterStep::Skip { count } => {
// skip(n): while the skip counter < n, increment it and drop
// the element (goto increment); afterwards pass through. The
// counter (not the source index) makes this compose with
// filter and other skips.
let n_val = self.lower_expr(count)?;
let ctr = step_counters[step_idx].expect("skip counter");
let builder = self.current_fn.as_mut().unwrap();
let skipping = builder.create_local(MirType::Bool);
builder.binary_op(skipping, BinOp::Lt, values::local(ctr), n_val);
let skip_block = builder.create_block();
let pass_block = builder.create_block();
builder.branch(values::local(skipping), skip_block, pass_block);
// Skip: counter += 1, drop this element.
builder.switch_to_block(skip_block);
let nc = builder.create_local(MirType::i64());
builder.binary_op(
nc,
BinOp::Add,
values::local(ctr),
MirValue::Const(MirConst::Int(1, MirType::i64())),
);
builder.assign(ctr, MirRValue::Use(values::local(nc)));
builder.goto(incr_block);
builder.switch_to_block(pass_block);
}
IterStep::Take { count } => {
// take(n): once the take counter reaches n, exit the loop;
// otherwise increment it and pass the element through. The
// counter (not the source index) makes this compose.
let n_val = self.lower_expr(count)?;
let ctr = step_counters[step_idx].expect("take counter");
let builder = self.current_fn.as_mut().unwrap();
let done = builder.create_local(MirType::Bool);
builder.binary_op(done, BinOp::Ge, values::local(ctr), n_val);
let take_block = builder.create_block();
builder.branch(values::local(done), exit_block, take_block);
// Within the limit: counter += 1, pass through.
builder.switch_to_block(take_block);
let nc = builder.create_local(MirType::i64());
builder.binary_op(
nc,
BinOp::Add,
values::local(ctr),
MirValue::Const(MirConst::Int(1, MirType::i64())),
);
builder.assign(ctr, MirRValue::Use(values::local(nc)));
}
}
}
// 8. Terminal: push to result vec OR update accumulator.
match &chain.terminal {
IterTerminal::Collect => {
let builder = self.current_fn.as_mut().unwrap();
let cont = builder.create_block();
builder.call(
MirValue::Function(Arc::from(push_fn_name)),
vec![values::local(result_local), current_val],
None,
cont,
);
builder.switch_to_block(cont);
}
IterTerminal::Fold { closure, .. } => {
// Inline the fold closure: acc = closure(acc, current_val)
let new_acc =
self.lower_iter_fold_inline(closure, values::local(result_local), current_val)?;
let builder = self.current_fn.as_mut().unwrap();
builder.assign(result_local, MirRValue::Use(new_acc));
}
IterTerminal::Sum => {
// acc = acc + current_val
let val_ty = self.type_of_value(¤t_val);
let builder = self.current_fn.as_mut().unwrap();
let next = builder.create_local(val_ty);
builder.binary_op(next, BinOp::Add, values::local(result_local), current_val);
builder.assign(result_local, MirRValue::Use(values::local(next)));
}
IterTerminal::Count => {
// acc = acc + 1 (the element value is unused)
let builder = self.current_fn.as_mut().unwrap();
let next = builder.create_local(MirType::i64());
builder.binary_op(
next,
BinOp::Add,
values::local(result_local),
MirValue::Const(MirConst::Int(1, MirType::i64())),
);
builder.assign(result_local, MirRValue::Use(values::local(next)));
}
IterTerminal::Product => {
// acc = acc * current_val
let val_ty = self.type_of_value(¤t_val);
let builder = self.current_fn.as_mut().unwrap();
let next = builder.create_local(val_ty);
builder.binary_op(next, BinOp::Mul, values::local(result_local), current_val);
builder.assign(result_local, MirRValue::Use(values::local(next)));
}
IterTerminal::Any { closure } => {
// acc = acc || pred(elem) (bitwise-or on bool is correct here)
let pred = self.lower_iter_map_inline(
closure,
current_val,
if has_enumerate {
Some(values::local(idx_local))
} else {
None
},
)?;
let builder = self.current_fn.as_mut().unwrap();
let next = builder.create_local(MirType::Bool);
builder.binary_op(next, BinOp::BitOr, values::local(result_local), pred);
builder.assign(result_local, MirRValue::Use(values::local(next)));
}
IterTerminal::All { closure } => {
// acc = acc && pred(elem) (bitwise-and on bool is correct here)
let pred = self.lower_iter_map_inline(
closure,
current_val,
if has_enumerate {
Some(values::local(idx_local))
} else {
None
},
)?;
let builder = self.current_fn.as_mut().unwrap();
let next = builder.create_local(MirType::Bool);
builder.binary_op(next, BinOp::BitAnd, values::local(result_local), pred);
builder.assign(result_local, MirRValue::Use(values::local(next)));
}
}
// 9. Increment and loop back.
{
let builder = self.current_fn.as_mut().unwrap();
builder.goto(incr_block);
builder.switch_to_block(incr_block);
let next_idx = builder.create_local(MirType::i64());
builder.binary_op(
next_idx,
if reversed { BinOp::Sub } else { BinOp::Add },
values::local(idx_local),
MirValue::Const(MirConst::Int(1, MirType::i64())),
);
builder.assign(idx_local, MirRValue::Use(values::local(next_idx)));
builder.goto(cond_block);
}
// 10. Switch to exit block and return the result.
{
let builder = self.current_fn.as_mut().unwrap();
builder.switch_to_block(exit_block);
}
Ok(values::local(result_local))
}
/// Inline-lower a `.map()` closure call: evaluate the closure body
/// with the closure's parameter bound to `elem_val`.
///
/// Instead of emitting a real closure function + call, we directly
/// lower the closure body expression in the current function scope
/// with the parameter variable mapped to `elem_val`.
fn lower_iter_map_inline(
&mut self,
closure_expr: &ast::Expr,
elem_val: MirValue,
index_val: Option<MirValue>,
) -> CodegenResult<MirValue> {
// An unannotated element parameter takes the element's own type. It
// used to default to f64, so `|x| *x != ""` over strings compared a
// double with a string.
let elem_ty_default = self.type_of_value(&elem_val);
if let ExprKind::Closure { params, body, .. } = &closure_expr.kind {
// Save the current var_map entries that will be shadowed.
let mut saved: Vec<(Arc<str>, Option<LocalId>)> = Vec::new();
if params.len() == 2 && index_val.is_some() {
// enumerate-style: |i, x| body
// First param = index, second param = element
if let ast::PatternKind::Ident { name, .. } = ¶ms[0].pattern.kind {
let old = self.var_map.get(&name.name).copied();
saved.push((name.name.clone(), old));
let idx_val = index_val.unwrap();
let param_ty = params[0]
.ty
.as_ref()
.map(|t| self.lower_type_from_ast(t))
.unwrap_or(MirType::i64());
let builder = self.current_fn.as_mut().unwrap();
let local = builder.create_local(param_ty);
builder.assign(local, MirRValue::Use(idx_val));
self.var_map.insert(name.name.clone(), local);
}
if let ast::PatternKind::Ident { name, .. } = ¶ms[1].pattern.kind {
let old = self.var_map.get(&name.name).copied();
saved.push((name.name.clone(), old));
let param_ty = params[1]
.ty
.as_ref()
.map(|t| self.lower_type_from_ast(t))
.unwrap_or_else(|| elem_ty_default.clone());
let builder = self.current_fn.as_mut().unwrap();
let local = builder.create_local(param_ty);
builder.assign(local, MirRValue::Use(elem_val));
self.var_map.insert(name.name.clone(), local);
}
} else if params.len() == 1
&& index_val.is_some()
&& matches!(¶ms[0].pattern.kind, ast::PatternKind::Tuple(t) if t.len() == 2)
{
// enumerate-style with a tuple param: |(i, x)| body.
// First tuple element = index, second = element.
if let ast::PatternKind::Tuple(elems) = ¶ms[0].pattern.kind {
if let ast::PatternKind::Ident { name, .. } = &elems[0].kind {
let old = self.var_map.get(&name.name).copied();
saved.push((name.name.clone(), old));
let builder = self.current_fn.as_mut().unwrap();
let local = builder.create_local(MirType::i64());
builder.assign(local, MirRValue::Use(index_val.clone().unwrap()));
self.var_map.insert(name.name.clone(), local);
}
if let ast::PatternKind::Ident { name, .. } = &elems[1].kind {
let old = self.var_map.get(&name.name).copied();
saved.push((name.name.clone(), old));
let elem_ty = self.type_of_value(&elem_val);
let builder = self.current_fn.as_mut().unwrap();
let local = builder.create_local(elem_ty);
builder.assign(local, MirRValue::Use(elem_val));
self.var_map.insert(name.name.clone(), local);
}
}
} else if let Some(first_param) = params.first() {
// Single-param: |x| body
if let ast::PatternKind::Ident { name, .. } = &first_param.pattern.kind {
let old = self.var_map.get(&name.name).copied();
saved.push((name.name.clone(), old));
let param_ty = first_param
.ty
.as_ref()
.map(|t| self.lower_type_from_ast(t))
.unwrap_or_else(|| elem_ty_default.clone());
let builder = self.current_fn.as_mut().unwrap();
let local = builder.create_local(param_ty);
builder.assign(local, MirRValue::Use(elem_val));
self.var_map.insert(name.name.clone(), local);
}
}
// Lower the closure body inline.
let result = self.lower_expr(body)?;
// Restore shadowed var_map entries.
for (name, old) in saved {
if let Some(id) = old {
self.var_map.insert(name, id);
} else {
self.var_map.remove(&name);
}
}
Ok(result)
} else {
// Not a closure - shouldn't happen, but fall back to lowering as-is.
self.lower_expr(closure_expr)
}
}
/// Inline-lower a `.fold()` closure: `|acc, x| body`.
fn lower_iter_fold_inline(
&mut self,
closure_expr: &ast::Expr,
acc_val: MirValue,
elem_val: MirValue,
) -> CodegenResult<MirValue> {
if let ExprKind::Closure { params, body, .. } = &closure_expr.kind {
let mut saved: Vec<(Arc<str>, Option<LocalId>)> = Vec::new();
// Bind acc parameter.
if let Some(acc_param) = params.first() {
if let ast::PatternKind::Ident { name, .. } = &acc_param.pattern.kind {
let old = self.var_map.get(&name.name).copied();
saved.push((name.name.clone(), old));
let param_ty = acc_param
.ty
.as_ref()
.map(|t| self.lower_type_from_ast(t))
.unwrap_or(MirType::f64());
let builder = self.current_fn.as_mut().unwrap();
let local = builder.create_local(param_ty);
builder.assign(local, MirRValue::Use(acc_val));
self.var_map.insert(name.name.clone(), local);
}
}
// Bind element parameter.
if params.len() >= 2 {
if let ast::PatternKind::Ident { name, .. } = ¶ms[1].pattern.kind {
let old = self.var_map.get(&name.name).copied();
saved.push((name.name.clone(), old));
let param_ty = params[1]
.ty
.as_ref()
.map(|t| self.lower_type_from_ast(t))
.unwrap_or(MirType::f64());
let builder = self.current_fn.as_mut().unwrap();
let local = builder.create_local(param_ty);
builder.assign(local, MirRValue::Use(elem_val));
self.var_map.insert(name.name.clone(), local);
}
}
let result = self.lower_expr(body)?;
for (name, old) in saved {
if let Some(id) = old {
self.var_map.insert(name, id);
} else {
self.var_map.remove(&name);
}
}
Ok(result)
} else {
self.lower_expr(closure_expr)
}
}
/// Infer the output element type of an iterator chain by examining
/// the steps. For `.map()` closures with a return type annotation,
/// use that. For closures whose body is a simple identifier matching
/// a parameter, use that parameter's annotated type. Otherwise,
/// propagate the input element type.
fn infer_chain_output_type(&self, input_ty: &MirType, steps: &[IterStep<'_>]) -> MirType {
let mut ty = input_ty.clone();
for step in steps {
match step {
IterStep::Map { closure } => {
if let ExprKind::Closure {
return_type,
params,
body,
..
} = &closure.kind
{
if let Some(ret_ty) = return_type {
ty = self.lower_type_from_ast(ret_ty);
} else {
// Try to infer from the closure body: if the body
// is a simple identifier matching a parameter, use
// that parameter's type annotation.
if let ExprKind::Ident(body_ident) = &body.kind {
for param in params {
if let ast::PatternKind::Ident { name, .. } =
¶m.pattern.kind
{
if name.name.as_ref() == body_ident.name.as_ref() {
if let Some(pt) = ¶m.ty {
ty = self.lower_type_from_ast(pt);
}
break;
}
}
}
}
// For binary expressions (e.g., |x| x * 2.0),
// the type is preserved from the single param.
else if params.len() == 1 {
if let Some(p) = params.first() {
if let Some(pt) = &p.ty {
ty = self.lower_type_from_ast(pt);
}
}
}
}
}
}
IterStep::Filter { .. }
| IterStep::Enumerate
| IterStep::Cloned
| IterStep::Rev
| IterStep::Take { .. }
| IterStep::Skip { .. } => {
// These don't change the element type.
}
}
}
ty
}
/// Select the C runtime accessor for the element type, with the same
/// element-to-suffix table every other Vec path uses. It used to know only
/// f64 and i64 and read every other element (strings included) through the
/// i32 accessor, which did not compile.
fn vec_get_len_fn_names(elem_ty: &MirType) -> CodegenResult<(String, &'static str)> {
let suffix = match elem_ty {
MirType::Float(_) => "f64".to_string(),
MirType::Int(IntSize::I64, _) | MirType::Int(IntSize::ISize, _) => "i64".to_string(),
MirType::Int(_, _) | MirType::Bool => "i32".to_string(),
other => Self::hvec_elem_suffix(other)?,
};
Ok((format!("build_hvec_get_{suffix}"), "build_hvec_len"))
}
}
/// The source text of one macro argument, with the module merge's renames
/// applied (see `register_macro_ident_rename`), trimmed.
pub(super) fn renamed_slice(
source: &str,
start: usize,
end: usize,
source_id: Option<crate::lexer::SourceId>,
) -> String {
let Some(text) = source.get(start..end) else {
return String::new();
};
let renames = match source_id {
Some(id) => crate::lexer::macro_ident_renames_in(id, start as u32, end as u32),
None => Vec::new(),
};
if renames.is_empty() {
return text.trim().to_string();
}
let mut out = String::with_capacity(text.len() + 16);
let mut at = start;
for (s, e, name) in renames {
let (s, e) = (s as usize, e as usize);
if s < at {
continue;
}
out.push_str(&source[at..s]);
out.push_str(&name);
at = e;
}
out.push_str(&source[at..end]);
out.trim().to_string()
}