buildlang 1.15.0

BuildLang (buildc): an effects-oriented compiler with a verified C path, shader output, experimental backends, opt-in linear types, and re-checkable accountability + scientific-runtime receipts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
// ===============================================================================
// BUILDLANG CODE GENERATOR - AST TO MIR LOWERING
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================

//! Lowering from AST to MIR.
//!
//! This pass transforms the type-checked AST into MIR (Mid-level IR).
//!
//! The lowering is split across several submodules:
//! - `expr`: Block, statement, and expression lowering
//! - `types`: Type lowering, const evaluation, and generic monomorphization
//! - `macros`: Closure, effect, builtin macro, and iterator chain lowering

mod array_places;
mod asserts;
mod c_abi;
mod drops;
mod env_macro;
mod expr;
mod format;
mod global_init;
mod global_places;
mod limits;
mod lowlevel;
mod macros;
mod option_combinators;
pub(crate) mod parallel;
mod slice_escape;
mod string_parse;
mod tail_resume;
#[cfg(test)]
mod tests;
mod types;
mod unwrap_trap;
mod vec_range;

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crate::ast::{self, ItemKind};
use crate::types::TypeContext;

use super::backend::CodegenResult;
use super::builder::{values, MirBuilder, MirModuleBuilder};
use super::ir::*;

/// One parameter position of an overloaded definition, as seen by codegen's
/// dispatch resolver. Either a concrete lowered type or a generic type-parameter
/// slot (`T`), which matches any argument (least specific). Mirrors the checker's
/// distinction between a concrete `Ty` and a `TyKind::Param` in
/// `dispatch_position_match` (see `types::infer::dispatch_position_match`); the
/// two must stay in agreement so both sides pick the same winner.
#[derive(Debug, Clone)]
pub(crate) enum ParamSlot {
    /// A concrete parameter type (ranked by structural match / numeric coercion).
    Concrete(MirType),
    /// A generic type-parameter slot; matches any argument as `Generic`.
    Generic,
}

/// One candidate definition of an overloaded name in the codegen dispatch
/// registry. `is_generic` records whether the definition itself is generic (so a
/// selected generic winner is monomorphized via `lower_generic_call`, not emitted
/// as a mangled concrete function).
#[derive(Debug, Clone)]
pub(crate) struct MultiFnSig {
    /// Parameter slots in declaration order (concrete or generic).
    pub(crate) slots: Vec<ParamSlot>,
    /// Whether this definition has type generics (routes to monomorphization).
    pub(crate) is_generic: bool,
}

/// The definition a call site resolves to, once the shared resolver has picked
/// the unique most-specific candidate among an overloaded name's siblings.
pub(crate) enum OverloadTarget {
    /// A concrete definition, emitted under this mangled `name_<param-tuple>`.
    Concrete(Arc<str>),
    /// A generic definition; the call must be lowered through
    /// `lower_generic_call` (monomorphized on demand), not called directly.
    Generic,
}

/// A parameter that receives a capturing closure: its index, the closure's
/// function name, and the name and type of each captured value.
pub(crate) type ClosureParam = (usize, Arc<str>, Vec<(Arc<str>, MirType)>);

/// The struct that carries a closure's captured values: its name, and each
/// field's name and type.
pub(crate) type ClosureEnv = (Arc<str>, Vec<(Arc<str>, MirType)>);

/// AST to MIR lowerer.
pub struct MirLowerer<'ctx> {
    /// Type context.
    ctx: &'ctx TypeContext,
    /// Module builder.
    module: MirModuleBuilder,
    /// Variable to local mapping (per function).
    var_map: HashMap<Arc<str>, LocalId>,
    /// Loop context stack (continue_block, break_block, optional loop label).
    /// The label lets `break 'name` / `continue 'name` target an enclosing loop
    /// instead of the innermost one.
    loop_stack: Vec<(BlockId, BlockId, Option<String>)>,
    /// For each entry of `loop_stack`, how many drop scopes were open when the
    /// loop began, so `break` and `continue` drop the scopes inside it.
    pub(crate) loop_drop_depths: Vec<usize>,
    /// Result local of a `loop` that a `break value` assigned, keyed by the
    /// loop's exit block, so `let r = loop { ... break v; }` binds `v`.
    loop_break_values: HashMap<BlockId, LocalId>,
    /// Locals that hold a `char` (MIR stores a char as a u32 code point), so
    /// `{}` prints the character rather than its number.
    pub(crate) char_locals: std::collections::HashSet<LocalId>,
    /// Locals known to hold a reference (`&T`), from a `&` parameter, a `&`
    /// annotation on a `let`, a `&expr` initializer, or a copy of one. MIR
    /// lowers references and raw pointers to the same pointer type; this set
    /// lets `a == b` on two `&str` compare contents while two raw pointers
    /// still compare addresses.
    pub(crate) ref_locals: std::collections::HashSet<LocalId>,
    /// Locals (vectors, or pointers to vectors) whose elements are chars, from
    /// a `Vec<char>` annotation on a `let` or a parameter.
    pub(crate) char_vec_locals: std::collections::HashSet<LocalId>,
    /// Top-level user functions lowered under `user_fn_c_name` because their
    /// names collide with a C library or runtime name.
    pub(crate) shadow_fns: std::collections::HashSet<Arc<str>>,
    /// Constants and statics declared `char`. A char is an integer in MIR, so
    /// printing one as a character needs to know where it came from.
    pub(crate) char_globals: std::collections::HashSet<Arc<str>>,
    /// Constants and statics declared `&str` with a literal. The global holds
    /// the string; a use of the name is a reference to it.
    pub(crate) str_ref_globals: std::collections::HashSet<Arc<str>>,
    /// Locals declared `&str` or `&String`: a parameter, an annotated `let`, or
    /// a use of a `&str` constant. A string method on one reads through it.
    pub(crate) str_ref_locals: std::collections::HashSet<LocalId>,
    /// `type Name = T;` at the top level: the name stands for `T`.
    pub(crate) type_aliases: HashMap<Arc<str>, ast::Type>,
    /// Unannotated `vec_new()` bindings whose element type waits for the first
    /// push: binding local -> every local to retype (constructor temp, binding).
    pub(crate) pending_untyped_vecs: HashMap<LocalId, Vec<LocalId>>,
    /// Set while lowering the initializer of such a binding.
    pub(crate) untyped_vec_new_binding: bool,
    /// The constructor temp the initializer created, for the binding to claim.
    pub(crate) untyped_vec_new_dest: Option<LocalId>,
    /// Counter for the temporaries of a store into a vector element's field.
    pub(crate) vec_store_counter: u32,
    /// Pending vectors read before their first push (their type is then fixed).
    pub(crate) observed_pending_vecs: std::collections::HashSet<LocalId>,
    /// True while lowering a re-parsed macro argument, whose spans do not
    /// index into the file.
    pub(crate) in_macro_fragment: bool,
    /// Current function builder.
    current_fn: Option<MirBuilder>,
    /// Source code (for extracting token text in macro expansion).
    source: Option<Arc<str>>,
    /// Counter for generating unique closure function names.
    closure_count: u32,
    /// Impl method registry: maps (TypeName, MethodName) -> mangled function name.
    impl_methods: HashMap<(Arc<str>, Arc<str>), Arc<str>>,
    /// Generic function ASTs stored for monomorphization: name -> FnDef clone.
    generic_functions: HashMap<Arc<str>, ast::FnDef>,
    /// Generic enum ASTs stored for monomorphization: name -> EnumDef clone.
    generic_enums: HashMap<Arc<str>, ast::EnumDef>,
    /// Generic struct ASTs stored for monomorphization: name -> StructDef clone.
    generic_structs: HashMap<Arc<str>, ast::StructDef>,
    /// Set of already-generated monomorphized specializations (mangled names).
    monomorphized: HashSet<Arc<str>>,
    /// Trait definitions: maps trait name -> ordered list of method signatures.
    /// Used to generate vtable structs and dispatch.
    trait_methods: HashMap<Arc<str>, Vec<(Arc<str>, MirFnSig)>>,
    /// Trait implementations: maps (TraitName, TypeName) -> ordered method names.
    /// Used to populate vtable entries.
    trait_impls: HashMap<(Arc<str>, Arc<str>), Vec<Arc<str>>>,
    /// Effect definitions: maps effect name -> vec of (operation_name, param_types).
    effect_defs: HashMap<Arc<str>, Vec<(Arc<str>, Vec<MirType>)>>,
    effect_op_rets: HashMap<(Arc<str>, Arc<str>), MirType>,
    /// Closure capture registry: maps closure function name -> list of
    /// (captured_var_name, captured_var_local_id) pairs.  When a call is made
    /// through a local that was assigned from a capturing closure, the extra
    /// captured values are appended as arguments.
    closure_captures: HashMap<Arc<str>, Vec<(Arc<str>, LocalId)>>,
    /// Maps a *local variable* (by its LocalId) that holds a closure function
    /// pointer to the closure's internal function name, so that `lower_call`
    /// can look up captures.
    local_closure_name: HashMap<LocalId, Arc<str>>,
    /// Set by a generic call for the specialisation it is about to lower:
    /// for each parameter that receives a capturing closure, the parameter
    /// index, the closure's function name, and the name and type of every
    /// captured value. The specialisation takes those values as extra
    /// parameters after the declared ones.
    pub(crate) pending_closure_params: Vec<ClosureParam>,
    /// Parameter types for the next closure written in place, for its
    /// parameters that have no written type (`opt.map(|x| x * 2)`).
    pub(crate) closure_param_hint: Option<Vec<MirType>>,
    /// The Ok type of the `let` annotation being initialised, for a
    /// `s.parse()` written without a turbofish.
    pub(crate) parse_target_hint: Option<MirType>,
    /// Types with an `impl Drop`, by name, to their `T_drop` function.
    pub(crate) drop_fns: HashMap<Arc<str>, Arc<str>>,
    /// The owned values with a Drop impl in each open block of the function
    /// being lowered, outermost first (see `drops.rs`).
    pub(crate) drop_scopes: Vec<Vec<drops::DropSlot>>,
    /// Methods, as (type name, method name), whose `self` is taken by value.
    pub(crate) by_value_self: HashSet<(Arc<str>, Arc<str>)>,
    /// Functions declared to return `impl Trait`, by name, kept so one
    /// can be lowered the first time it is called: what it returns is
    /// known only from its body.
    pub(crate) impl_return_fns: HashMap<Arc<str>, ast::FnDef>,
    /// Functions from `impl_return_fns` already lowered.
    pub(crate) impl_return_done: HashSet<Arc<str>>,
    /// A function that returns a capturing closure -> that closure's name.
    pub(crate) fn_closure_env: HashMap<Arc<str>, Arc<str>>,
    /// Closure name -> the struct that carries its captured values out of
    /// the function that made it, and each field's name and type.
    pub(crate) closure_env_fields: HashMap<Arc<str>, ClosureEnv>,
    /// Locals that hold such a struct -> the closure they stand for.
    pub(crate) local_env_closure: HashMap<LocalId, Arc<str>>,
    /// Parameter and return types of every top-level function that is not
    /// generic, by name, so a function named as a value has a type before
    /// its body is lowered.
    pub(crate) fn_ast_sigs: HashMap<Arc<str>, (Vec<ast::Type>, Option<ast::Type>)>,
    /// Generic impl blocks stored for deferred monomorphization.
    /// Maps base type name (e.g., "Option") -> list of impl defs.
    generic_impls: HashMap<Arc<str>, Vec<ast::ImplDef>>,
    /// Visibility of the current item being lowered (set by lower_function_with_vis).
    current_item_vis: Option<bool>,
    /// The current impl block's type name (for resolving `Self` in MIR lowering).
    current_impl_type: Option<Arc<str>>,
    /// Module prefix stack for inline `pub mod` blocks.
    /// When inside `pub mod foo { pub mod bar { ... } }`, this contains ["foo", "bar"].
    /// Item names are prefixed with "foo_bar_" for name mangling.
    module_prefix: Vec<Arc<str>>,
    /// Maps module short names to their mangling prefix.
    /// For `pub module std::math`, maps "math" → "std" so that
    /// `math::add()` resolves to `std_add` (not `math_add`).
    module_aliases: HashMap<Arc<str>, Arc<str>>,
    /// Maps bare type names to their full module-prefixed names.
    /// E.g., "Operator" → "tonemap_Operator" when Operator is defined
    /// inside `mod tonemap`. Used for cross-module type references.
    type_module_map: HashMap<Arc<str>, Arc<str>>,
    /// Set of tuple type names already registered as MIR type defs.
    tuple_type_defs: HashSet<Arc<str>>,
    /// Expected return type for the current expression being lowered.
    /// Set from let binding type annotations before lowering init expressions.
    /// Used by resolve_call_return_type to override the i32 fallback.
    pub(crate) expected_type: Option<MirType>,
    /// Tracks the inner type T for locals holding runtime Option<T> values.
    /// Populated from let-binding type annotations (`let x: Option<HashMap<K,V>> = ...`)
    /// and from Some(value) construction. Used by lower_runtime_option_match
    /// to bind pattern variables with the correct type instead of i32.
    pub(crate) option_inner_types: HashMap<LocalId, MirType>,
    /// Tracks the Ok payload type T for locals holding runtime Result<T, E> values.
    /// Populated from let-binding type annotations (`let r: Result<i32, String> = ...`).
    /// Used by lower_runtime_result_match to read the Ok union slot with the
    /// correct type instead of defaulting to i32 (which would silently mis-read
    /// f64/pointer Ok payloads).
    pub(crate) result_ok_types: HashMap<LocalId, MirType>,
    /// Tracks the Err payload type E for locals holding runtime Result<T, E>.
    /// Populated from let-binding annotations. Used by lower_runtime_result_match
    /// to read the Err union slot with the correct type. Defaults to BuildString
    /// (the common String-error case) when absent.
    pub(crate) result_err_types: HashMap<LocalId, MirType>,
    /// Maps a function name to the Ok payload type of its `Result<Ok, Err>`
    /// return type, captured during the collection pass. Lets a `match call() {
    /// Ok(x) => ... }` on a direct call recover the Ok type even with no
    /// intervening let-binding annotation. Keyed by the declared (unmangled)
    /// function name.
    pub(crate) fn_result_ok_types: HashMap<Arc<str>, MirType>,
    /// Maps a function name to the Err payload type E of its `Result<Ok, Err>`
    /// return, captured during the collection pass. Lets a direct-call match
    /// bind the Err arm with the right type. Keyed by the declared name.
    pub(crate) fn_result_err_types: HashMap<Arc<str>, MirType>,
    /// Maps a function name to the inner payload type T of its `Option<T>`
    /// return type, captured during the collection pass. Lets a `match call() {
    /// Some(x) => ... }` on a direct call read the correct union slot even with
    /// no intervening let annotation (symmetric to fn_result_ok_types). Keyed by
    /// the declared (unmangled) function name.
    pub(crate) fn_option_inner_types: HashMap<Arc<str>, MirType>,
    /// Functions whose declared return type is `char` or `Vec<char>`, so a `let`
    /// bound to a direct call keeps printing characters.
    /// Type parameter -> concrete type while lowering a monomorphized body.
    pub(crate) type_param_subst: HashMap<Arc<str>, MirType>,
    pub(crate) fn_returns_char: std::collections::HashSet<Arc<str>>,
    pub(crate) fn_returns_char_vec: std::collections::HashSet<Arc<str>>,
    /// Const name -> evaluated literal value, collected in a pre-pass so
    /// that const identifiers used as array lengths (`[T; MAX_DIMS]`) resolve.
    pub(crate) const_values: HashMap<Arc<str>, MirConst>,
    /// MIR-level names (as they appear in `MirType::Struct`, i.e. already
    /// module-prefixed for items inside inline `mod` blocks) of every
    /// non-generic `#[linear]` struct/enum, populated during the collection
    /// pass (`collect_struct`/`collect_enum`). Passed to each function's
    /// `MirBuilder` so every local-creation site tags `"linear"` locals
    /// uniformly. Generic/monomorphized linear ADTs are intentionally out of
    /// scope here (deferred to the 2b checker, which sees monomorphized MIR).
    pub(crate) linear_type_names: HashSet<Arc<str>>,
    /// Structs marked `#[repr(C)]`, which `extern "C"` exports may use.
    pub(crate) repr_c_structs: HashSet<Arc<str>>,
    /// Multiple-dispatch registry (codegen mirror of the checker's
    /// `multi_methods`): resolved function name -> a candidate signature per
    /// definition sharing that name, in declaration order. GENERIC definitions
    /// are recorded here too (with generic parameter positions marked as
    /// `ParamSlot::Generic`) so a name that mixes generic and concrete defs is
    /// counted as overloaded and resolved through the SAME `resolve_overload` the
    /// checker uses; this is what keeps the checker and codegen in agreement on
    /// the winner. A name with a single entry keeps its PLAIN C name (backward
    /// compat + extern "C"/FFI untouched); a name with 2+ entries dispatches by
    /// the argument-type tuple (concrete winners are emitted under a mangled
    /// `name_<param-tuple>`, a generic winner is monomorphized).
    pub(crate) multi_fns: HashMap<Arc<str>, Vec<MultiFnSig>>,
}

// =============================================================================
// Iterator chain desugaring types
// =============================================================================

/// An intermediate transform operation in an iterator chain.
pub(crate) enum IterStep<'a> {
    /// `.map(|params| body)` - transform each element.
    Map { closure: &'a ast::Expr },
    /// `.filter(|x| pred)` - keep only elements for which the predicate holds.
    Filter { closure: &'a ast::Expr },
    /// `.enumerate()` - prepend an index to each element.
    Enumerate,
    /// `.cloned()` - identity (no-op for Copy types).
    Cloned,
    /// `.rev()` - iterate the source in reverse order.
    Rev,
    /// `.take(n)` - yield only the first `n` elements (by source position).
    Take { count: &'a ast::Expr },
    /// `.skip(n)` - skip the first `n` elements (by source position).
    Skip { count: &'a ast::Expr },
}

/// Terminal operation of an iterator chain.
pub(crate) enum IterTerminal<'a> {
    /// `.collect()` - gather results into a new Vec.
    Collect,
    /// `.fold(init, |acc, x| body)` - accumulate a single value.
    Fold {
        init: &'a ast::Expr,
        closure: &'a ast::Expr,
    }, // fields accessible via match pattern
    /// `.sum()` - add all elements, starting from a zero accumulator.
    Sum,
    /// `.count()` - count elements, starting from zero.
    Count,
    /// `.product()` - multiply all elements, starting from one.
    Product,
    /// `.any(|x| pred)` - true if the predicate holds for any element.
    Any { closure: &'a ast::Expr },
    /// `.all(|x| pred)` - true if the predicate holds for every element.
    All { closure: &'a ast::Expr },
}

/// A fully parsed iterator chain: `source.iter().<steps>.<terminal>`.
pub(crate) struct IterChain<'a> {
    /// The source expression (the thing `.iter()` is called on).
    pub(crate) source: &'a ast::Expr,
    /// Ordered list of intermediate transforms.
    pub(crate) steps: Vec<IterStep<'a>>,
    /// The terminal operation.
    pub(crate) terminal: IterTerminal<'a>,
}

impl<'ctx> MirLowerer<'ctx> {
    /// Create a new lowerer.
    pub fn new(ctx: &'ctx TypeContext) -> Self {
        Self {
            ctx,
            module: MirModuleBuilder::new("main"),
            var_map: HashMap::new(),
            loop_stack: Vec::new(),
            loop_drop_depths: Vec::new(),
            loop_break_values: HashMap::new(),
            char_locals: std::collections::HashSet::new(),
            ref_locals: std::collections::HashSet::new(),
            char_vec_locals: std::collections::HashSet::new(),
            shadow_fns: std::collections::HashSet::new(),
            char_globals: std::collections::HashSet::new(),
            str_ref_globals: std::collections::HashSet::new(),
            str_ref_locals: std::collections::HashSet::new(),
            type_aliases: HashMap::new(),
            pending_untyped_vecs: HashMap::new(),
            untyped_vec_new_binding: false,
            untyped_vec_new_dest: None,
            vec_store_counter: 0,
            observed_pending_vecs: std::collections::HashSet::new(),
            in_macro_fragment: false,
            current_fn: None,
            source: None,
            closure_count: 0,
            impl_methods: HashMap::new(),
            generic_functions: HashMap::new(),
            generic_enums: HashMap::new(),
            generic_structs: HashMap::new(),
            monomorphized: HashSet::new(),
            trait_methods: HashMap::new(),
            trait_impls: HashMap::new(),
            effect_defs: HashMap::new(),
            effect_op_rets: HashMap::new(),
            closure_captures: HashMap::new(),
            local_closure_name: HashMap::new(),
            pending_closure_params: Vec::new(),
            closure_param_hint: None,
            parse_target_hint: None,
            drop_fns: HashMap::new(),
            drop_scopes: Vec::new(),
            by_value_self: HashSet::new(),
            impl_return_fns: HashMap::new(),
            impl_return_done: HashSet::new(),
            fn_closure_env: HashMap::new(),
            closure_env_fields: HashMap::new(),
            local_env_closure: HashMap::new(),
            fn_ast_sigs: HashMap::new(),
            generic_impls: HashMap::new(),
            current_item_vis: None,
            current_impl_type: None,
            module_prefix: Vec::new(),
            module_aliases: HashMap::new(),
            type_module_map: HashMap::new(),
            tuple_type_defs: HashSet::new(),
            expected_type: None,
            option_inner_types: HashMap::new(),
            result_ok_types: HashMap::new(),
            result_err_types: HashMap::new(),
            fn_result_ok_types: HashMap::new(),
            fn_result_err_types: HashMap::new(),
            fn_option_inner_types: HashMap::new(),
            type_param_subst: HashMap::new(),
            fn_returns_char: std::collections::HashSet::new(),
            fn_returns_char_vec: std::collections::HashSet::new(),
            const_values: HashMap::new(),
            linear_type_names: HashSet::new(),
            repr_c_structs: HashSet::new(),
            multi_fns: HashMap::new(),
        }
    }

    /// Create a new lowerer with source code for macro expansion.
    pub fn with_source(ctx: &'ctx TypeContext, source: Arc<str>) -> Self {
        Self {
            ctx,
            module: MirModuleBuilder::new("main"),
            var_map: HashMap::new(),
            loop_stack: Vec::new(),
            loop_drop_depths: Vec::new(),
            loop_break_values: HashMap::new(),
            char_locals: std::collections::HashSet::new(),
            ref_locals: std::collections::HashSet::new(),
            char_vec_locals: std::collections::HashSet::new(),
            shadow_fns: std::collections::HashSet::new(),
            char_globals: std::collections::HashSet::new(),
            str_ref_globals: std::collections::HashSet::new(),
            str_ref_locals: std::collections::HashSet::new(),
            type_aliases: HashMap::new(),
            pending_untyped_vecs: HashMap::new(),
            untyped_vec_new_binding: false,
            untyped_vec_new_dest: None,
            vec_store_counter: 0,
            observed_pending_vecs: std::collections::HashSet::new(),
            in_macro_fragment: false,
            current_fn: None,
            source: Some(source),
            closure_count: 0,
            impl_methods: HashMap::new(),
            generic_functions: HashMap::new(),
            generic_enums: HashMap::new(),
            generic_structs: HashMap::new(),
            monomorphized: HashSet::new(),
            trait_methods: HashMap::new(),
            trait_impls: HashMap::new(),
            effect_defs: HashMap::new(),
            effect_op_rets: HashMap::new(),
            closure_captures: HashMap::new(),
            local_closure_name: HashMap::new(),
            pending_closure_params: Vec::new(),
            closure_param_hint: None,
            parse_target_hint: None,
            drop_fns: HashMap::new(),
            drop_scopes: Vec::new(),
            by_value_self: HashSet::new(),
            impl_return_fns: HashMap::new(),
            impl_return_done: HashSet::new(),
            fn_closure_env: HashMap::new(),
            closure_env_fields: HashMap::new(),
            local_env_closure: HashMap::new(),
            fn_ast_sigs: HashMap::new(),
            generic_impls: HashMap::new(),
            current_item_vis: None,
            current_impl_type: None,
            module_prefix: Vec::new(),
            module_aliases: HashMap::new(),
            type_module_map: HashMap::new(),
            tuple_type_defs: HashSet::new(),
            expected_type: None,
            option_inner_types: HashMap::new(),
            result_ok_types: HashMap::new(),
            result_err_types: HashMap::new(),
            fn_result_ok_types: HashMap::new(),
            fn_result_err_types: HashMap::new(),
            fn_option_inner_types: HashMap::new(),
            type_param_subst: HashMap::new(),
            fn_returns_char: std::collections::HashSet::new(),
            fn_returns_char_vec: std::collections::HashSet::new(),
            const_values: HashMap::new(),
            linear_type_names: HashSet::new(),
            repr_c_structs: HashSet::new(),
            multi_fns: HashMap::new(),
        }
    }

    /// Build a prefixed name for items inside inline modules.
    /// E.g., inside `mod foo { mod bar { fn baz() } }` the prefix
    /// stack is ["foo", "bar"], so `baz` becomes `foo_bar_baz`.
    fn prefixed_name(&self, name: &Arc<str>) -> Arc<str> {
        if self.module_prefix.is_empty() {
            name.clone()
        } else {
            let mut s = String::new();
            for seg in &self.module_prefix {
                s.push_str(seg);
                s.push('_');
            }
            s.push_str(name);
            Arc::from(s)
        }
    }

    /// Resolve a bare function name inside an inline module by trying the
    /// module-prefixed name first (local definition), then falling back to
    /// the unprefixed name (parent scope via `use super::*`).
    ///
    /// For example, inside `pub mod convert`, a call to `xyz_to_lab` will
    /// first check for `convert_xyz_to_lab` in the MIR module, and only
    /// fall back to `xyz_to_lab` if the prefixed version doesn't exist.
    fn resolve_fn_name(&self, bare_name: &str) -> Arc<str> {
        if !self.module_prefix.is_empty() {
            let prefixed = self.prefixed_name(&Arc::from(bare_name));
            if self.module.find_function(prefixed.as_ref()).is_some() {
                return prefixed;
            }
        }
        if self.shadow_fns.contains(bare_name) {
            return Self::user_fn_c_name(bare_name);
        }
        Arc::from(bare_name)
    }

    /// Register built-in vector math struct types so that field access
    /// (e.g. `v.x`, `v.y`, `v.z`) resolves correctly through
    /// `lookup_struct_field_type`.
    fn register_vector_types(&mut self) {
        let f64_ty = MirType::f64();

        // build_vec2 { x: f64, y: f64 }
        self.module.create_struct(
            Arc::from("build_vec2"),
            vec![
                (Some(Arc::from("x")), f64_ty.clone()),
                (Some(Arc::from("y")), f64_ty.clone()),
            ],
        );

        // build_vec3 { x: f64, y: f64, z: f64 }
        self.module.create_struct(
            Arc::from("build_vec3"),
            vec![
                (Some(Arc::from("x")), f64_ty.clone()),
                (Some(Arc::from("y")), f64_ty.clone()),
                (Some(Arc::from("z")), f64_ty.clone()),
            ],
        );

        // build_vec4 { x: f64, y: f64, z: f64, w: f64 }
        self.module.create_struct(
            Arc::from("build_vec4"),
            vec![
                (Some(Arc::from("x")), f64_ty.clone()),
                (Some(Arc::from("y")), f64_ty.clone()),
                (Some(Arc::from("z")), f64_ty.clone()),
                (Some(Arc::from("w")), f64_ty.clone()),
            ],
        );
    }

    /// Lower a module.
    /// True when a top-level user function of this name would collide with a
    /// name the lowerer or the C output already uses: a C library function, a
    /// runtime helper or a print builtin. Such a function is lowered under
    /// `user_fn_c_name`, so `fn log(...)`, `fn read(...)` or `fn printf(...)`
    /// in a program is the program's own function at every call.
    /// `min`, `max`, `abs` and the names in the C backend's stdlib-collision
    /// list are escaped there and are not repeated here.
    pub(crate) fn shadows_runtime_name(name: &str) -> bool {
        if name.starts_with("build_") || name.starts_with("__") {
            return true;
        }
        matches!(
            name,
            "print"
                | "println"
                | "eprint"
                | "eprintln"
                | "assert"
                | "printf"
                | "fprintf"
                | "sprintf"
                | "snprintf"
                | "vprintf"
                | "vfprintf"
                | "vsprintf"
                | "vsnprintf"
                | "scanf"
                | "fscanf"
                | "sscanf"
                | "puts"
                | "fputs"
                | "gets"
                | "fgets"
                | "putc"
                | "fputc"
                | "putchar"
                | "getc"
                | "fgetc"
                | "getchar"
                | "ungetc"
                | "perror"
                | "fopen"
                | "freopen"
                | "fclose"
                | "fflush"
                | "fread"
                | "fwrite"
                | "fseek"
                | "ftell"
                | "rewind"
                | "fgetpos"
                | "fsetpos"
                | "feof"
                | "ferror"
                | "clearerr"
                | "tmpfile"
                | "tmpnam"
                | "setbuf"
                | "setvbuf"
                | "malloc"
                | "calloc"
                | "realloc"
                | "free"
                | "_Exit"
                | "quick_exit"
                | "at_quick_exit"
                | "strtoul"
                | "strtoll"
                | "strtoull"
                | "strtof"
                | "strtold"
                | "atoll"
                | "mblen"
                | "mbtowc"
                | "wctomb"
                | "mbstowcs"
                | "wcstombs"
                | "memcpy"
                | "memmove"
                | "memset"
                | "memcmp"
                | "memchr"
                | "strlen"
                | "strcpy"
                | "strncpy"
                | "strcat"
                | "strncat"
                | "strcmp"
                | "strncmp"
                | "strcoll"
                | "strxfrm"
                | "strchr"
                | "strrchr"
                | "strstr"
                | "strspn"
                | "strcspn"
                | "strpbrk"
                | "strtok"
                | "strerror"
                | "strdup"
                | "strndup"
                | "sqrt"
                | "cbrt"
                | "sin"
                | "cos"
                | "tan"
                | "asin"
                | "acos"
                | "atan"
                | "atan2"
                | "sinh"
                | "cosh"
                | "tanh"
                | "asinh"
                | "acosh"
                | "atanh"
                | "exp"
                | "exp2"
                | "expm1"
                | "log"
                | "log2"
                | "log10"
                | "log1p"
                | "pow"
                | "fabs"
                | "floor"
                | "ceil"
                | "round"
                | "trunc"
                | "rint"
                | "nearbyint"
                | "lround"
                | "llround"
                | "lrint"
                | "llrint"
                | "fmod"
                | "remainder"
                | "remquo"
                | "fmax"
                | "fmin"
                | "fdim"
                | "fma"
                | "hypot"
                | "copysign"
                | "nan"
                | "nextafter"
                | "nexttoward"
                | "frexp"
                | "ldexp"
                | "modf"
                | "scalbn"
                | "scalbln"
                | "ilogb"
                | "logb"
                | "erf"
                | "erfc"
                | "tgamma"
                | "lgamma"
                | "j0"
                | "j1"
                | "jn"
                | "y0"
                | "y1"
                | "yn"
                | "gamma"
                | "signgam"
                | "sqrtf"
                | "sinf"
                | "cosf"
                | "tanf"
                | "powf"
                | "expf"
                | "logf"
                | "fabsf"
                | "floorf"
                | "ceilf"
                | "roundf"
                | "fmodf"
                | "time"
                | "clock"
                | "difftime"
                | "mktime"
                | "strftime"
                | "gmtime"
                | "localtime"
                | "asctime"
                | "ctime"
                | "timespec_get"
                | "isalnum"
                | "isalpha"
                | "isblank"
                | "iscntrl"
                | "isdigit"
                | "isgraph"
                | "islower"
                | "isprint"
                | "ispunct"
                | "isspace"
                | "isupper"
                | "isxdigit"
                | "signal"
                | "raise"
                | "setjmp"
                | "longjmp"
                | "errno"
                | "read"
                | "write"
                | "open"
                | "close"
                | "creat"
                | "lseek"
                | "pipe"
                | "dup"
                | "dup2"
                | "fork"
                | "execv"
                | "execve"
                | "execvp"
                | "wait"
                | "waitpid"
                | "kill"
                | "sleep"
                | "usleep"
                | "alarm"
                | "pause"
                | "access"
                | "chdir"
                | "getcwd"
                | "rmdir"
                | "mkdir"
                | "unlink"
                | "link"
                | "symlink"
                | "readlink"
                | "stat"
                | "fstat"
                | "lstat"
                | "chmod"
                | "chown"
                | "truncate"
                | "ftruncate"
                | "isatty"
                | "getpid"
                | "getppid"
                | "getuid"
                | "geteuid"
                | "getgid"
                | "socket"
                | "bind"
                | "listen"
                | "accept"
                | "connect"
                | "send"
                | "recv"
                | "sendto"
                | "recvfrom"
                | "shutdown"
                | "select"
                | "poll"
                | "ioctl"
                | "fcntl"
                | "index"
                | "rindex"
                | "bcopy"
                | "bzero"
                | "bcmp"
                | "ffs"
                | "random"
                | "srandom"
                | "drand48"
                | "lrand48"
                | "srand48"
                | "basename"
                | "dirname"
                | "mmap"
                | "munmap"
                | "mprotect"
                | "dlopen"
                | "dlsym"
                | "dlclose"
                | "environ"
                | "optarg"
                | "optind"
                | "getopt"
                | "stdin"
                | "stdout"
                | "stderr"
        )
    }

    /// The name a shadowing user function is lowered under.
    pub(crate) fn user_fn_c_name(name: &str) -> Arc<str> {
        Arc::from(format!("bld_u_{name}"))
    }

    /// Give every `impl Trait for T` the trait's methods that have a body and
    /// that the impl does not write itself. After this an inherited method is
    /// an ordinary method of `T`: `T_method` exists, and `Self` in its body is
    /// `T`. Only traits declared at the top level of the file are followed.
    fn add_trait_default_methods(items: Vec<ast::Item>) -> Vec<ast::Item> {
        let mut defaults: HashMap<Arc<str>, Vec<ast::FnDef>> = HashMap::new();
        for item in &items {
            if let ItemKind::Trait(t) = &item.kind {
                let with_body: Vec<ast::FnDef> = t
                    .items
                    .iter()
                    .filter_map(|ti| match &ti.kind {
                        ast::TraitItemKind::Function(f) if f.body.is_some() => Some((**f).clone()),
                        _ => None,
                    })
                    .collect();
                if !with_body.is_empty() {
                    defaults.insert(t.name.name.clone(), with_body);
                }
            }
        }
        if defaults.is_empty() {
            return items;
        }
        items
            .into_iter()
            .map(|mut item| {
                let ItemKind::Impl(impl_def) = &mut item.kind else {
                    return item;
                };
                let Some(inherited) = impl_def
                    .trait_ref
                    .as_ref()
                    .and_then(|tr| tr.path.last_ident())
                    .and_then(|name| defaults.get(&name.name))
                else {
                    return item;
                };
                for f in inherited {
                    let written = impl_def.items.iter().any(|ii| {
                        matches!(&ii.kind, ast::ImplItemKind::Function(g)
                            if g.name.name == f.name.name)
                    });
                    if !written {
                        impl_def.items.push(ast::ImplItem {
                            vis: ast::Visibility::Private,
                            attrs: Vec::new(),
                            is_default: false,
                            kind: ast::ImplItemKind::Function(Box::new(f.clone())),
                            span: f.name.span,
                            id: ast::NodeId::DUMMY,
                        });
                    }
                }
                item
            })
            .collect()
    }

    /// Top-level functions with a body whose names collide (see
    /// `shadows_runtime_name`), renamed for lowering. Declarations without a
    /// body and `extern` functions keep their names: those name C symbols.
    fn rename_shadowing_fns(&mut self, items: &[ast::Item]) -> Vec<ast::Item> {
        items
            .iter()
            .map(|item| {
                let ItemKind::Function(f) = &item.kind else {
                    return item.clone();
                };
                let name = f.name.name.as_ref();
                if f.body.is_none() || f.sig.abi.is_some() || !Self::shadows_runtime_name(name) {
                    return item.clone();
                }
                self.shadow_fns.insert(f.name.name.clone());
                let mut f2 = f.as_ref().clone();
                f2.name = ast::Ident {
                    name: Self::user_fn_c_name(name),
                    span: f.name.span,
                };
                let mut item2 = item.clone();
                item2.kind = ItemKind::Function(Box::new(f2));
                item2
            })
            .collect()
    }

    pub fn lower_module(mut self, module: &ast::Module) -> CodegenResult<MirModule> {
        // Register built-in vector math types before user code
        self.register_vector_types();

        // A user function named like a C library or runtime function is
        // lowered under its own name space.
        let items = self.rename_shadowing_fns(&module.items);
        let items = Self::add_trait_default_methods(items);
        for item in &items {
            if let ItemKind::Function(f) = &item.kind {
                if !self.fn_has_type_generics(f) {
                    let params = f.sig.params.iter().map(|p| (*p.ty).clone()).collect();
                    let ret = f.sig.return_ty.as_ref().map(|t| (**t).clone());
                    self.fn_ast_sigs.insert(f.name.name.clone(), (params, ret));
                    if f.sig
                        .return_ty
                        .as_ref()
                        .is_some_and(|t| matches!(t.kind, ast::TypeKind::ImplTrait { .. }))
                    {
                        self.impl_return_fns
                            .insert(f.name.name.clone(), (**f).clone());
                    }
                }
            }
        }
        for item in &items {
            if let ItemKind::TypeAlias(alias) = &item.kind {
                if let Some(ty) = alias.ty.as_ref() {
                    self.type_aliases
                        .insert(alias.name.name.clone(), (**ty).clone());
                }
            }
        }

        // Pre-pass: evaluate consts so const identifiers used as array
        // lengths (e.g. `[T; MAX_DIMS]`) resolve during type lowering below.
        for item in &items {
            self.collect_const_values(item);
        }

        // Pre-pass: build the multiple-dispatch registry so the collection and
        // lowering passes both know which names are overloaded (and mangle
        // their definitions) while leaving single-def names on their plain name.
        for item in &items {
            self.collect_multi_fn_signatures(item);
            self.collect_repr_c(item);
        }

        // First pass: collect type definitions and function signatures
        for item in &items {
            self.collect_item(item)?;
        }

        // Register every `const` and `static` before any body is lowered, so a
        // body that names a global declared later in the source still sees its
        // declared type (a later `const BASE: u64` was typed `i32`, G13).
        for item in &items {
            self.collect_globals(item)?;
        }

        // Generate vtables for all (Trait, Type) pairs
        self.generate_vtables();

        // Second pass: lower function bodies
        for item in &items {
            self.lower_top_level_item(item)?;
        }

        let mut repr_c: Vec<Arc<str>> = self.repr_c_structs.iter().cloned().collect();
        repr_c.sort();
        self.module.module_mut().repr_c = repr_c;
        Ok(self.module.build())
    }

    // =========================================================================
    // COLLECTION PASS
    // =========================================================================

    /// Evaluate top-level and inline-module const definitions into
    /// const_values so they can resolve as array lengths during lowering.
    fn collect_const_values(&mut self, item: &ast::Item) {
        match &item.kind {
            ItemKind::Const(c) => {
                if let Some(v) = c.value.as_ref().and_then(|e| self.try_const_eval(e)) {
                    self.const_values.insert(c.name.name.clone(), v);
                }
            }
            ItemKind::Mod(m) => {
                if let Some(content) = &m.content {
                    for it in &content.items {
                        self.collect_const_values(it);
                    }
                }
            }
            _ => {}
        }
    }

    fn collect_item(&mut self, item: &ast::Item) -> CodegenResult<()> {
        match &item.kind {
            ItemKind::Struct(s) => {
                self.collect_struct(s, Self::has_attribute(&item.attrs, "linear"))?;
                // Check for #[derive(...)] attributes and auto-generate impls
                self.process_derive_attrs(&item.attrs, &s.name, s);
                Ok(())
            }
            ItemKind::Enum(e) => self.collect_enum(e, Self::has_attribute(&item.attrs, "linear")),
            ItemKind::Function(f) => self.collect_function(f),
            ItemKind::Impl(impl_def) => self.collect_impl(impl_def),
            // Effect declarations: collect operation signatures so handler
            // lowering can look up parameter types.
            ItemKind::Trait(t) => self.collect_trait(t),
            ItemKind::Effect(e) => self.collect_effect(e),
            // Extern blocks: register foreign function declarations so that
            // calls can resolve return types and the C backend emits proper
            // forward declarations.
            ItemKind::ExternBlock(eb) => self.collect_extern_block(eb),
            // Inline module: push module name onto prefix stack and
            // recursively collect all contained items.
            ItemKind::Mod(m) => self.collect_inline_mod(m),
            // Use declarations (e.g. `use super::*`) are handled implicitly
            // by the flattened naming scheme - no collection needed.
            ItemKind::Use(_) => Ok(()),
            _ => Ok(()),
        }
    }

    /// Generate vtable definitions for all (Trait, Type) implementation pairs.
    fn generate_vtables(&mut self) {
        // Copy trait_methods to the MirModule for the C backend to access
        let trait_methods_clone = self.trait_methods.clone();
        for (trait_name, methods) in &trait_methods_clone {
            self.module
                .module_mut()
                .trait_methods
                .insert(trait_name.clone(), methods.clone());
        }

        // For each (Trait, Type) impl pair, create a vtable
        // Sorted: map order differs from one compiler run to the next, and the
        // emitted code must not.
        let mut impl_pairs: Vec<_> = self.trait_impls.keys().cloned().collect();
        impl_pairs.sort();
        for (trait_name, type_name) in impl_pairs {
            if let Some(trait_methods) = self.trait_methods.get(&trait_name) {
                let methods: Vec<_> = trait_methods
                    .iter()
                    .map(|(method_name, sig)| {
                        let mangled = self
                            .impl_methods
                            .get(&(type_name.clone(), method_name.clone()))
                            .cloned()
                            .unwrap_or_else(|| Arc::from(format!("{}_{}", type_name, method_name)));
                        (method_name.clone(), mangled, sig.clone())
                    })
                    .collect();

                self.module.module_mut().vtables.push(MirVtable {
                    trait_name: trait_name.clone(),
                    type_name: type_name.clone(),
                    methods,
                });
            }
        }
    }

    fn collect_trait(&mut self, t: &ast::TraitDef) -> CodegenResult<()> {
        let trait_name: Arc<str> = t.name.name.clone();
        let mut methods = Vec::new();

        for item in &t.items {
            if let ast::TraitItemKind::Function(fndef) = &item.kind {
                let params: Vec<MirType> = fndef
                    .sig
                    .params
                    .iter()
                    .map(|p| self.lower_type_from_ast(&p.ty))
                    .collect();
                let ret = fndef
                    .sig
                    .return_ty
                    .as_ref()
                    .map(|t| self.lower_type_from_ast(t))
                    .unwrap_or(MirType::Void);

                // A method that returns or takes `Self` by value is not object
                // safe: it cannot be called through `dyn Trait`, and C has no type
                // named `Self` for its vtable slot. Leave it out of the vtable;
                // static calls through `T: Trait` do not use the table.
                let mentions_self = |t: &MirType| {
                    fn walk(t: &MirType) -> bool {
                        match t {
                            MirType::Struct(n) => n.as_ref() == "Self",
                            MirType::Ptr(inner) => walk(inner),
                            _ => false,
                        }
                    }
                    walk(t)
                };
                if mentions_self(&ret) || params.iter().skip(1).any(mentions_self) {
                    continue;
                }

                // First param is self - replace with void* for vtable fn ptr
                let mut vtable_params = vec![MirType::Ptr(Box::new(MirType::Void))];
                vtable_params.extend(params.into_iter().skip(1));

                let fn_sig = MirFnSig::new(vtable_params, ret);
                methods.push((fndef.name.name.clone(), fn_sig));
            }
        }

        self.trait_methods.insert(trait_name, methods);
        Ok(())
    }

    fn collect_effect(&mut self, e: &ast::EffectDef) -> CodegenResult<()> {
        let effect_name: Arc<str> = Arc::from(e.name.name.as_ref());
        let ops: Vec<(Arc<str>, Vec<MirType>)> = e
            .operations
            .iter()
            .map(|op| {
                let param_types: Vec<MirType> = op
                    .params
                    .iter()
                    .map(|p| self.lower_type_from_ast(&p.ty))
                    .collect();
                (Arc::from(op.name.name.as_ref()), param_types)
            })
            .collect();
        for op in &e.operations {
            let r = op
                .return_ty
                .as_ref()
                .map(|t| self.lower_type_from_ast(t))
                .unwrap_or(MirType::Void);
            self.effect_op_rets
                .insert((effect_name.clone(), Arc::from(op.name.name.as_ref())), r);
        }
        self.effect_defs.insert(effect_name, ops);
        Ok(())
    }

    /// Collect extern block declarations.  Each foreign function is registered
    /// as a declaration-only `MirFunction` so that call-site return-type
    /// resolution works and the C backend emits proper forward declarations.
    fn collect_extern_block(&mut self, eb: &ast::ExternBlockDef) -> CodegenResult<()> {
        for foreign_item in &eb.items {
            if let ast::ForeignItemKind::Fn(f) = &foreign_item.kind {
                // Build parameter types.  For extern "C" functions, map `&str`
                // directly to `Ptr(i8)` (i.e. `const char*`) rather than
                // `Ptr(BuildString)`.
                let params: Vec<MirType> = f
                    .sig
                    .params
                    .iter()
                    .map(|p| self.lower_ffi_type(&p.ty))
                    .collect();

                let ret = f
                    .sig
                    .return_ty
                    .as_ref()
                    .map(|t| self.lower_ffi_type(t))
                    .unwrap_or(MirType::Void);

                let mut sig = MirFnSig::new(params, ret);
                sig.calling_conv = CallingConv::C;
                // Carry the parsed `...` variadic marker (e.g. `printf`) so the
                // C backend emits a trailing `, ...` in the declaration.
                sig.is_variadic = f.sig.is_variadic;

                let mut func = MirFunction::declaration(f.name.name.clone(), sig);
                func.is_public = true;
                // Carry the extern block's `header "..."` clause onto each
                // declaration so the C backend can emit the right `#include`
                // and skip synthesizing a prototype for it.
                func.link_header = eb.header.as_deref().map(Arc::from);
                // Carry the `link "..."` clause so the build driver can pass
                // the library to the C compiler.
                func.link_lib = eb.link.as_deref().map(Arc::from);
                // Carry the `source "..."` clause so the C backend can compile
                // the binding into the same translation unit.
                func.link_source = eb.source.as_deref().map(Arc::from);

                // Set parameter names on the declaration so the C backend can
                // emit readable prototypes.
                for (i, param) in f.sig.params.iter().enumerate() {
                    if let ast::PatternKind::Ident { name, .. } = &param.pattern.kind {
                        let local = MirLocal {
                            id: LocalId(i as u32),
                            name: Some(name.name.clone()),
                            ty: self.lower_ffi_type(&param.ty),
                            is_mut: false,
                            is_param: true,
                            annotations: Vec::new(),
                        };
                        func.locals.push(local);
                    }
                }

                self.module.add_function(func);
            } else if let ast::ForeignItemKind::Static {
                name,
                mutability,
                ty,
            } = &foreign_item.kind
            {
                // A foreign `static` lowers to an external-declaration global:
                // it is referenced, never defined. It carries the block's
                // header/link so the C backend includes the header (or emits a
                // bare `extern` declaration) and links the library.
                let mut global = MirGlobal::new(name.name.clone(), self.lower_ffi_type(ty));
                global.is_extern_decl = true;
                global.is_mut = matches!(mutability, ast::Mutability::Mutable);
                global.linkage = Linkage::External;
                global.link_header = eb.header.as_deref().map(Arc::from);
                global.link_lib = eb.link.as_deref().map(Arc::from);
                self.module.add_global(global);
            }
        }
        Ok(())
    }

    /// Collect items inside an inline `mod` block.
    ///
    /// Items are collected with their names prefixed by the module path so
    /// that `pub mod math { pub fn add(...) }` registers a function named
    /// `math_add`.  Path-based calls like `math::add(...)` are resolved to
    /// `math_add` by `lower_path`, which joins path segments with `_`.
    fn collect_inline_mod(&mut self, m: &ast::ModDef) -> CodegenResult<()> {
        if let Some(ref content) = m.content {
            self.module_prefix.push(m.name.name.clone());
            // Forward-declare every non-generic struct/enum name in this
            // module (bare -> module-prefixed) BEFORE lowering any item body.
            // Field types are lowered during collect_struct/collect_enum, so a
            // field whose type is declared LATER in the same module would
            // otherwise miss type_module_map and keep its bare name, emitting C
            // that names an undefined identifier (e.g. a bare ColorPrimaries
            // field where only hdr_ColorPrimaries is defined).
            for item in &content.items {
                let (name, generics) = match &item.kind {
                    ItemKind::Struct(s) => (&s.name.name, &s.generics),
                    ItemKind::Enum(e) => (&e.name.name, &e.generics),
                    _ => continue,
                };
                let has_generics = generics
                    .params
                    .iter()
                    .any(|p| matches!(p.kind, ast::GenericParamKind::Type { .. }));
                if !has_generics {
                    let prefixed = self.prefixed_name(name);
                    self.type_module_map.insert(name.clone(), prefixed);
                }
            }
            for item in &content.items {
                // Rewrite item names with the module prefix before collecting.
                let rewritten = self.rewrite_item_with_prefix(item);
                self.collect_item(&rewritten)?;
            }
            self.module_prefix.pop();
        }
        Ok(())
    }

    /// Rewrite an item's name by prepending the current module prefix.
    /// This is used to "flatten" items from inline modules into the
    /// top-level scope with mangled names (e.g. `mod_fn` for `mod::fn`).
    fn rewrite_item_with_prefix(&self, item: &ast::Item) -> ast::Item {
        if self.module_prefix.is_empty() {
            return item.clone();
        }
        let new_kind = match &item.kind {
            ItemKind::Function(f) => {
                let mut f2 = f.as_ref().clone();
                f2.name = ast::Ident {
                    name: self.prefixed_name(&f.name.name),
                    span: f.name.span,
                };
                ItemKind::Function(Box::new(f2))
            }
            ItemKind::Struct(s) => {
                let mut s2 = s.as_ref().clone();
                s2.name = ast::Ident {
                    name: self.prefixed_name(&s.name.name),
                    span: s.name.span,
                };
                ItemKind::Struct(Box::new(s2))
            }
            ItemKind::Enum(e) => {
                let mut e2 = e.as_ref().clone();
                e2.name = ast::Ident {
                    name: self.prefixed_name(&e.name.name),
                    span: e.name.span,
                };
                ItemKind::Enum(Box::new(e2))
            }
            ItemKind::Const(c) => {
                let mut c2 = c.as_ref().clone();
                c2.name = ast::Ident {
                    name: self.prefixed_name(&c.name.name),
                    span: c.name.span,
                };
                ItemKind::Const(Box::new(c2))
            }
            ItemKind::Static(s) => {
                let mut s2 = s.as_ref().clone();
                s2.name = ast::Ident {
                    name: self.prefixed_name(&s.name.name),
                    span: s.name.span,
                };
                ItemKind::Static(Box::new(s2))
            }
            ItemKind::Trait(t) => {
                let mut t2 = t.as_ref().clone();
                t2.name = ast::Ident {
                    name: self.prefixed_name(&t.name.name),
                    span: t.name.span,
                };
                ItemKind::Trait(Box::new(t2))
            }
            // Impl, Use, Mod, etc. - pass through unchanged
            _ => item.kind.clone(),
        };
        ast::Item {
            kind: new_kind,
            vis: item.vis.clone(),
            attrs: item.attrs.clone(),
            span: item.span,
            id: item.id,
        }
    }

    /// Lower an AST type for FFI usage.  This differs from `lower_type_from_ast`
    /// in that `&str` maps to `Ptr(i8)` (`const char*`) rather than
    /// `Ptr(BuildString)`, which is what C library functions expect.
    fn lower_ffi_type(&self, ty: &ast::Type) -> MirType {
        match &ty.kind {
            ast::TypeKind::Ref { ty: inner, .. } => {
                // &str -> const char* for FFI
                if let ast::TypeKind::Path(path) = &inner.kind {
                    if let Some(ident) = path.last_ident() {
                        if ident.name.as_ref() == "str" || ident.name.as_ref() == "String" {
                            return MirType::Ptr(Box::new(MirType::i8()));
                        }
                    }
                }
                MirType::Ptr(Box::new(self.lower_ffi_type(inner)))
            }
            _ => self.lower_type_from_ast(ty),
        }
    }

    fn collect_struct(&mut self, s: &ast::StructDef, is_linear: bool) -> CodegenResult<()> {
        // If the struct has generic type parameters, store for later monomorphization
        let has_generics = s
            .generics
            .params
            .iter()
            .any(|p| matches!(p.kind, ast::GenericParamKind::Type { .. }));

        if has_generics {
            // Generic linear ADTs are out of scope for the 2a groundwork:
            // the 2b checker consumes monomorphized MIR, where the concrete
            // instantiation's name would need to be tagged instead. Not
            // tagging here is conservative (an untagged local is simply
            // invisible to 2b), matching the spec's error-handling note.
            self.generic_structs.insert(s.name.name.clone(), s.clone());
            return Ok(());
        }

        let fields = match &s.fields {
            ast::StructFields::Named(fields) => fields
                .iter()
                .map(|f| {
                    let ty = self.lower_type_from_ast(&f.ty);
                    (Some(f.name.name.clone()), ty)
                })
                .collect(),
            ast::StructFields::Tuple(fields) => fields
                .iter()
                .map(|f| {
                    let ty = self.lower_type_from_ast(&f.ty);
                    (None, ty)
                })
                .collect(),
            ast::StructFields::Unit => Vec::new(),
        };

        let full_name = s.name.name.clone();
        if is_linear {
            self.linear_type_names.insert(full_name.clone());
        }
        self.module.create_struct(full_name.clone(), fields);

        // Register the bare→prefixed mapping so cross-module type
        // references can resolve (e.g., bare "Operator" → "tonemap_Operator").
        if !self.module_prefix.is_empty() {
            // Extract the bare name by stripping the prefix
            let prefix = self
                .module_prefix
                .iter()
                .map(|s| s.as_ref())
                .collect::<Vec<_>>()
                .join("_");
            let prefix_with_sep = format!("{}_", prefix);
            if let Some(bare) = full_name.strip_prefix(&prefix_with_sep) {
                self.type_module_map.insert(Arc::from(bare), full_name);
            }
        }

        Ok(())
    }

    /// Process #[derive(...)] attributes on a struct and register auto-generated methods.
    fn process_derive_attrs(
        &mut self,
        attrs: &[ast::Attribute],
        name: &ast::Ident,
        _s: &ast::StructDef,
    ) {
        for attr in attrs {
            if let Some(seg) = attr.path.segments.first() {
                if seg.ident.name.as_ref() == "derive" {
                    // Extract derive trait names from the attribute arguments
                    // For now we recognize Clone by checking the token stream
                    let has_clone = self.attr_has_derive_name(attr, "Clone");
                    if has_clone {
                        // Register a clone method: TypeName_clone(self) -> TypeName
                        // The actual body is trivial for value types - just return self.
                        let type_name = name.name.clone();
                        let method_name: Arc<str> = Arc::from(format!("{}_clone", type_name));
                        self.impl_methods
                            .insert((type_name.clone(), Arc::from("clone")), method_name.clone());
                        // The actual function will be generated in lower_item pass
                        // by checking for this registered method.
                    }
                }
            }
        }
    }

    /// Check if a derive attribute contains a specific trait name.
    fn attr_has_derive_name(&self, attr: &ast::Attribute, target: &str) -> bool {
        if let ast::AttrArgs::Delimited(tokens) = &attr.args {
            for tok in tokens {
                if let ast::TokenTree::Token(t) = tok {
                    if let crate::lexer::TokenKind::Ident = &t.kind {
                        // Check token text via source span
                        if let Some(ref src) = self.source {
                            let start = t.span.start.to_usize();
                            let end = t.span.end.to_usize();
                            if end <= src.len() && &src[start..end] == target {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        false
    }

    fn collect_enum(&mut self, e: &ast::EnumDef, is_linear: bool) -> CodegenResult<()> {
        // If the enum has generic type parameters, store for later monomorphization
        let has_generics = e
            .generics
            .params
            .iter()
            .any(|p| matches!(p.kind, ast::GenericParamKind::Type { .. }));

        if has_generics {
            // See the matching comment in collect_struct: generic linear
            // ADTs are deferred to the 2b checker via monomorphized MIR.
            self.generic_enums.insert(e.name.name.clone(), e.clone());
            return Ok(());
        }

        let variants: Vec<_> = e
            .variants
            .iter()
            .enumerate()
            .map(|(i, v)| {
                let fields = match &v.fields {
                    ast::StructFields::Named(fields) => fields
                        .iter()
                        .map(|f| (Some(f.name.name.clone()), self.lower_type_from_ast(&f.ty)))
                        .collect(),
                    ast::StructFields::Tuple(fields) => fields
                        .iter()
                        .map(|f| (None, self.lower_type_from_ast(&f.ty)))
                        .collect(),
                    ast::StructFields::Unit => Vec::new(),
                };

                MirEnumVariant {
                    name: v.name.name.clone(),
                    discriminant: i as i128,
                    fields,
                }
            })
            .collect();

        let full_name = e.name.name.clone();
        if is_linear {
            self.linear_type_names.insert(full_name.clone());
            // A struct-like variant (`Has { item: Coin }`) is lowered by
            // `lower_struct_expr` to an aggregate whose local is typed
            // `MirType::Struct(<variant name>)` (e.g. `Struct("Has")`), NOT
            // `Struct(<enum name>)`. Without tagging the variant's synthetic
            // struct name, that local is invisible to the MIR linear checker,
            // so `match &w { Wrap::Has { item } => .. }` extracting the linear
            // payload out of a shared borrow is not flagged and the enum can be
            // cloned. Tag every variant's name of a `#[linear]` enum so a local
            // typed with a variant struct name is recognized as linear. (A
            // payload-less variant name is harmless to include: no local is
            // typed `Struct(<that name>)` unless it is a variant construct,
            // which is exactly the linear case.)
            for v in &e.variants {
                self.linear_type_names.insert(v.name.name.clone());
            }
        }
        self.module
            .create_enum(full_name.clone(), MirType::i32(), variants);

        // Register bare→prefixed mapping for cross-module resolution
        if !self.module_prefix.is_empty() {
            let prefix = self
                .module_prefix
                .iter()
                .map(|s| s.as_ref())
                .collect::<Vec<_>>()
                .join("_");
            let prefix_with_sep = format!("{}_", prefix);
            if let Some(bare) = full_name.strip_prefix(&prefix_with_sep) {
                self.type_module_map.insert(Arc::from(bare), full_name);
            }
        }

        Ok(())
    }

    /// Monomorphize a generic enum for a specific concrete type (single-param shorthand).
    /// E.g., `Option<T>` + `i32` → `Option_i32` with `Some(i32)` variant.
    fn monomorphize_enum(
        &mut self,
        enum_name: &str,
        concrete_ty: &MirType,
    ) -> CodegenResult<Arc<str>> {
        // Build single-param substitution map and delegate to multi-param version
        let enum_def = self.generic_enums.get(enum_name).cloned();
        if let Some(ref e) = enum_def {
            let type_param = e
                .generics
                .params
                .iter()
                .find_map(|p| match &p.kind {
                    ast::GenericParamKind::Type { .. } => Some(p.ident.name.clone()),
                    _ => None,
                })
                .unwrap_or(Arc::from("T"));
            let mut subst = HashMap::new();
            subst.insert(type_param, concrete_ty.clone());
            return self.monomorphize_enum_multi(enum_name, &subst);
        }
        Ok(Arc::from(enum_name))
    }

    /// Monomorphize a generic enum with a multi-parameter substitution map.
    /// E.g., `Result<T, E>` + `{T: i32, E: BuildString}` → `Result_E_BuildString_T_i32`.
    fn monomorphize_enum_multi(
        &mut self,
        enum_name: &str,
        subst: &HashMap<Arc<str>, MirType>,
    ) -> CodegenResult<Arc<str>> {
        let mangled_name = Self::mangle_generic_name(enum_name, subst);

        if self.monomorphized.contains(&mangled_name) {
            return Ok(mangled_name);
        }
        self.monomorphized.insert(mangled_name.clone());

        let enum_def = self.generic_enums.get(enum_name).cloned();
        let enum_def = match enum_def {
            Some(e) => e,
            None => return Ok(Arc::from(enum_name)), // Not generic, use as-is
        };

        // Build monomorphized variants using the substitution map
        let variants: Vec<_> = enum_def
            .variants
            .iter()
            .enumerate()
            .map(|(i, v)| {
                let fields = match &v.fields {
                    ast::StructFields::Named(fields) => fields
                        .iter()
                        .map(|f| {
                            let ty = self.substitute_type_from_ast(&f.ty, subst);
                            (Some(f.name.name.clone()), ty)
                        })
                        .collect(),
                    ast::StructFields::Tuple(fields) => fields
                        .iter()
                        .map(|f| {
                            let ty = self.substitute_type_from_ast(&f.ty, subst);
                            (None, ty)
                        })
                        .collect(),
                    ast::StructFields::Unit => Vec::new(),
                };

                MirEnumVariant {
                    name: v.name.name.clone(),
                    discriminant: i as i128,
                    fields,
                }
            })
            .collect();

        self.module
            .create_enum(mangled_name.clone(), MirType::i32(), variants);

        // Also monomorphize any impl blocks for this generic enum
        self.monomorphize_impl_methods(enum_name, &mangled_name, subst)?;

        Ok(mangled_name)
    }

    /// Monomorphize a generic struct for specific concrete types.
    /// E.g., `Pair<T> { first: T, second: T }` + `{T: i32}` → `Pair_i32`.
    fn monomorphize_struct(
        &mut self,
        struct_name: &str,
        subst: &HashMap<Arc<str>, MirType>,
    ) -> CodegenResult<Arc<str>> {
        let mangled_name = Self::mangle_generic_name(struct_name, subst);

        if self.monomorphized.contains(&mangled_name) {
            return Ok(mangled_name);
        }
        self.monomorphized.insert(mangled_name.clone());

        let struct_def = self.generic_structs.get(struct_name).cloned();
        let struct_def = match struct_def {
            Some(s) => s,
            None => return Ok(Arc::from(struct_name)), // Not generic, use as-is
        };

        let fields = match &struct_def.fields {
            ast::StructFields::Named(fields) => fields
                .iter()
                .map(|f| {
                    let ty = self.substitute_type_from_ast(&f.ty, subst);
                    (Some(f.name.name.clone()), ty)
                })
                .collect(),
            ast::StructFields::Tuple(fields) => fields
                .iter()
                .map(|f| {
                    let ty = self.substitute_type_from_ast(&f.ty, subst);
                    (None, ty)
                })
                .collect(),
            ast::StructFields::Unit => Vec::new(),
        };

        self.module.create_struct(mangled_name.clone(), fields);

        // Also monomorphize any impl blocks for this generic struct
        self.monomorphize_impl_methods(struct_name, &mangled_name, subst)?;

        Ok(mangled_name)
    }

    /// Resolve an AST type using a substitution map for generic type parameters.
    /// Falls back to `lower_type_from_ast` for non-generic types.
    fn substitute_type_from_ast(
        &self,
        ty: &ast::Type,
        subst: &HashMap<Arc<str>, MirType>,
    ) -> MirType {
        match &ty.kind {
            ast::TypeKind::Path(path) => {
                if path.is_simple() {
                    if let Some(ident) = path.last_ident() {
                        // Check if this type name is a generic parameter to substitute
                        if let Some(concrete) = subst.get(&ident.name) {
                            return concrete.clone();
                        }
                    }
                }
                // Check for generic type references like Option<T> in field types
                if let Some(ident) = path.last_ident() {
                    if let Some(generic_args) = path.last_generics() {
                        if !generic_args.is_empty() {
                            let inner_subst = self.resolve_generic_args_with_subst(
                                ident.name.as_ref(),
                                generic_args,
                                subst,
                            );
                            if !inner_subst.is_empty() {
                                let mangled =
                                    Self::mangle_generic_name(ident.name.as_ref(), &inner_subst);
                                return MirType::Struct(mangled);
                            }
                        }
                    }
                }
                self.lower_type_from_ast(ty)
            }
            ast::TypeKind::Ref { ty: inner, .. } | ast::TypeKind::Ptr { ty: inner, .. } => {
                MirType::Ptr(Box::new(self.substitute_type_from_ast(inner, subst)))
            }
            ast::TypeKind::Array { elem, len } => {
                let elem_ty = self.substitute_type_from_ast(elem, subst);
                let length = self
                    .try_const_eval(len)
                    .and_then(|c| match c {
                        MirConst::Int(v, _) => Some(v as u64),
                        MirConst::Uint(v, _) => Some(v as u64),
                        _ => None,
                    })
                    .unwrap_or(0);
                MirType::Array(Box::new(elem_ty), length)
            }
            ast::TypeKind::Slice(inner) => {
                MirType::Slice(Box::new(self.substitute_type_from_ast(inner, subst)))
            }
            _ => self.lower_type_from_ast(ty),
        }
    }

    /// Resolve generic arguments from a path using an existing substitution map.
    /// E.g., given `Option<T>` and subst `{T: i32}`, returns `{T: i32}` for Option's params.
    fn resolve_generic_args_with_subst(
        &self,
        type_name: &str,
        generic_args: &[ast::GenericArg],
        outer_subst: &HashMap<Arc<str>, MirType>,
    ) -> HashMap<Arc<str>, MirType> {
        let mut result = HashMap::new();

        // Get the type parameter names from the generic definition
        let param_names: Vec<Arc<str>> = if let Some(enum_def) = self.generic_enums.get(type_name) {
            enum_def
                .generics
                .params
                .iter()
                .filter_map(|p| match &p.kind {
                    ast::GenericParamKind::Type { .. } => Some(p.ident.name.clone()),
                    _ => None,
                })
                .collect()
        } else if let Some(struct_def) = self.generic_structs.get(type_name) {
            struct_def
                .generics
                .params
                .iter()
                .filter_map(|p| match &p.kind {
                    ast::GenericParamKind::Type { .. } => Some(p.ident.name.clone()),
                    _ => None,
                })
                .collect()
        } else {
            return result;
        };

        // Positional type parameters are indexed among themselves: lifetime
        // and associated-type-binding arguments do not occupy a type-parameter
        // slot, so count only `Type` args. (This also corrects a latent offset
        // for `Foo<'a, T>`, where the lifetime previously shifted `T` off the
        // end of `param_names` and dropped its substitution.)
        let mut type_pos = 0;
        for arg in generic_args.iter() {
            if let ast::GenericArg::Type(arg_ty) = arg {
                if let Some(param_name) = param_names.get(type_pos) {
                    result.insert(
                        param_name.clone(),
                        self.substitute_type_from_ast(arg_ty, outer_subst),
                    );
                }
                type_pos += 1;
            }
        }

        result
    }

    /// Generate a mangled name from a base name and a substitution map.
    /// E.g., ("Result", {T: i32, E: BuildString}) → "Result_i32_BuildString"
    /// A short stable tag for a type that has no readable mangled name.
    pub(crate) fn type_tag(ty: &MirType) -> String {
        let mut h: u32 = 0x811c_9dc5;
        for b in format!("{ty:?}").bytes() {
            h = (h ^ u32::from(b)).wrapping_mul(0x0100_0193);
        }
        format!("{h:08x}")
    }

    fn mangle_generic_name(base: &str, subst: &HashMap<Arc<str>, MirType>) -> Arc<str> {
        let mut parts = vec![base.to_string()];
        // Sort by param name for deterministic mangling
        let mut entries: Vec<_> = subst.iter().collect();
        entries.sort_by_key(|(k, _)| (*k).clone());
        for (_, ty) in entries {
            parts.push(Self::mangle_type(ty));
        }
        Arc::from(parts.join("_"))
    }

    /// Monomorphize all impl blocks for a generic type using the given substitution map.
    /// For each method in the impl, generates a specialized version like `Option_T_i32_unwrap_or`.
    fn monomorphize_impl_methods(
        &mut self,
        base_type_name: &str,
        mangled_type_name: &Arc<str>,
        subst: &HashMap<Arc<str>, MirType>,
    ) -> CodegenResult<()> {
        let impl_defs = match self.generic_impls.get(base_type_name) {
            Some(impls) => impls.clone(),
            None => return Ok(()),
        };

        for impl_def in &impl_defs {
            for impl_item in &impl_def.items {
                if let ast::ImplItemKind::Function(f) = &impl_item.kind {
                    let method_name = f.name.name.clone();
                    let mangled_fn_name: Arc<str> =
                        Arc::from(format!("{}_{}", mangled_type_name, method_name));

                    // Register in impl_methods so method calls resolve
                    self.impl_methods.insert(
                        (mangled_type_name.clone(), method_name.clone()),
                        mangled_fn_name.clone(),
                    );

                    // Skip if already generated
                    if self.monomorphized.contains(&mangled_fn_name) {
                        continue;
                    }
                    self.monomorphized.insert(mangled_fn_name.clone());

                    // Build a specialized FnDef with type params replaced.
                    // We need to also replace `self` type references with the
                    // mangled type, and the function name is already mangled.
                    let mut specialized = Self::monomorphize_fndef_multi(
                        f,
                        subst,
                        f.name.name.clone(), // Keep original name; we rename below
                    );
                    // Override the name to our mangled fn name
                    specialized.name = ast::Ident {
                        name: mangled_fn_name.clone(),
                        span: f.name.span,
                    };

                    // Save context, lower as impl method, restore.
                    // lower_impl_method will NOT re-mangle; it uses the
                    // fn name from the def, but prepends type_name_.
                    // So we use lower_function directly and manually handle
                    // the self param type.
                    let saved_fn = self.current_fn.take();
                    let saved_vars = std::mem::take(&mut self.var_map);
                    let saved_chars = std::mem::take(&mut self.char_locals);
                    let saved_refs = std::mem::take(&mut self.ref_locals);
                    let saved_str_refs = std::mem::take(&mut self.str_ref_locals);
                    let saved_char_vecs = std::mem::take(&mut self.char_vec_locals);
                    let saved_pending_vecs = std::mem::take(&mut self.pending_untyped_vecs);

                    self.lower_generic_impl_method(mangled_type_name, &specialized)?;

                    self.current_fn = saved_fn;
                    self.var_map = saved_vars;
                    self.char_locals = saved_chars;
                    self.ref_locals = saved_refs;
                    self.str_ref_locals = saved_str_refs;
                    self.char_vec_locals = saved_char_vecs;
                    self.pending_untyped_vecs = saved_pending_vecs;
                }
            }
        }

        Ok(())
    }

    /// Pre-pass: build the multiple-dispatch registry (`multi_fns`) before any
    /// collection or lowering, so both passes agree on which names are
    /// overloaded and on the mangled name of each definition. Walks inline
    /// modules with the same prefix tracking used elsewhere, so the recorded
    /// names match the module-prefixed function names in the MIR module.
    fn collect_multi_fn_signatures(&mut self, item: &ast::Item) {
        match &item.kind {
            ItemKind::Function(f) => {
                // Record EVERY definition, generic or concrete. Generic defs are
                // still monomorphized per call site (they are never emitted as a
                // plain overloaded C symbol), but they must appear in the
                // registry so a name that mixes a generic and a concrete def is
                // counted as overloaded and routed through the shared resolver;
                // otherwise codegen would run the plain generic-call path while
                // the checker resolved a concrete def -> miscompile.
                let name = self.prefixed_name(&f.name.name);
                let sig = self.multi_fn_sig_of(f);
                self.multi_fns.entry(name).or_default().push(sig);
            }
            ItemKind::Mod(m) => {
                if let Some(ref content) = m.content {
                    self.module_prefix.push(m.name.name.clone());
                    for it in &content.items {
                        self.collect_multi_fn_signatures(it);
                    }
                    self.module_prefix.pop();
                }
            }
            _ => {}
        }
    }

    /// Build the dispatch signature for one definition: a `ParamSlot` per
    /// parameter (generic type-parameter positions become `ParamSlot::Generic`,
    /// everything else `Concrete(lowered_ty)`), plus whether the definition is
    /// generic overall. A parameter is generic when its type is a bare reference
    /// to one of the function's own declared type parameters (`fn h<T>(a: T)`);
    /// this is the codegen counterpart of the checker seeing a `TyKind::Param`.
    fn multi_fn_sig_of(&self, f: &ast::FnDef) -> MultiFnSig {
        let type_param_names: Vec<&str> = f
            .generics
            .params
            .iter()
            .filter_map(|p| match &p.kind {
                ast::GenericParamKind::Type { .. } => Some(p.ident.name.as_ref()),
                _ => None,
            })
            .collect();
        let is_type_param = |ty: &ast::Type| -> bool {
            if let ast::TypeKind::Path(path) = &ty.kind {
                if path.segments.len() == 1 {
                    let seg = path.segments[0].ident.name.as_ref();
                    return type_param_names.contains(&seg);
                }
            }
            false
        };
        let slots: Vec<ParamSlot> = f
            .sig
            .params
            .iter()
            .map(|p| {
                if is_type_param(&p.ty) {
                    ParamSlot::Generic
                } else {
                    ParamSlot::Concrete(self.lower_type_from_ast(&p.ty))
                }
            })
            .collect();
        MultiFnSig {
            slots,
            is_generic: !type_param_names.is_empty(),
        }
    }

    /// The C name a function definition is emitted under. For an overloaded
    /// name this is the mangled `name_<param-tuple>`; otherwise it is the
    /// function's own (already module-prefixed) name, unchanged. Called at both
    /// the forward-declaration and body-lowering sites so the two agree.
    ///
    /// Note: `f.name.name` is already the resolved (module-prefixed) name by the
    /// time collection/lowering runs (see `rewrite_item_with_prefix`), which is
    /// exactly the key used in `multi_fns`.
    pub(crate) fn emitted_fn_name(&self, f: &ast::FnDef) -> Arc<str> {
        if self.is_overloaded_fn(f.name.name.as_ref()) {
            let param_tys: Vec<MirType> = f
                .sig
                .params
                .iter()
                .map(|p| self.lower_type_from_ast(&p.ty))
                .collect();
            Self::mangle_multi_fn_name(f.name.name.as_ref(), &param_tys)
        } else {
            f.name.name.clone()
        }
    }

    /// Whether `resolved_name` has two or more definitions (is overloaded).
    pub(crate) fn is_overloaded_fn(&self, resolved_name: &str) -> bool {
        self.multi_fns
            .get(resolved_name)
            .map(|v| v.len() >= 2)
            .unwrap_or(false)
    }

    /// Mangled C name for the definition of `resolved_name` whose parameter
    /// tuple is `param_tys`. Only meaningful for overloaded names; single-def
    /// names keep their plain name. Deterministic: `name_<ty0>_<ty1>...`.
    pub(crate) fn mangle_multi_fn_name(resolved_name: &str, param_tys: &[MirType]) -> Arc<str> {
        let mut parts = vec![resolved_name.to_string()];
        for ty in param_tys {
            parts.push(Self::mangle_type(ty));
        }
        Arc::from(parts.join("_"))
    }

    /// If `resolved_name` is overloaded, resolve the call's selected definition
    /// from the lowered argument types (running the SAME `resolve_overload` the
    /// type checker used) and return the target to emit: a concrete mangled name
    /// or a signal to monomorphize the selected generic definition. Returns
    /// `None` for non-overloaded names (they keep their plain name) or when
    /// resolution fails (the checker already reported the error; fall back to the
    /// plain / generic path to avoid a second cascading failure).
    ///
    /// This resolver and the checker's `try_infer_multi_dispatch` both feed the
    /// SAME `resolve_overload` with a matching per-position specificity function
    /// (`mir_position_match` here, `dispatch_position_match` there). Keeping the
    /// two match functions in sync is what guarantees checker and codegen select
    /// the same winner for the generic+concrete case; see the note on
    /// `mir_position_match`.
    pub(crate) fn resolve_overloaded_call_name(
        &self,
        resolved_name: &str,
        arg_tys: &[MirType],
    ) -> Option<OverloadTarget> {
        let candidates = self.multi_fns.get(resolved_name)?;
        if candidates.len() < 2 {
            return None;
        }

        struct Cand<'a>(&'a [ParamSlot]);
        impl crate::types::DispatchCandidate for Cand<'_> {
            fn arity(&self) -> usize {
                self.0.len()
            }
        }
        let views: Vec<Cand<'_>> = candidates.iter().map(|c| Cand(&c.slots)).collect();

        let selected = crate::types::resolve_overload(&views, arg_tys.len(), |ci, pos| {
            Self::mir_position_match(&candidates[ci].slots[pos], &arg_tys[pos])
        })
        .ok()?;

        let winner = &candidates[selected];
        if winner.is_generic {
            // A generic winner is not a plain C symbol; the caller lowers it
            // through `lower_generic_call`, which monomorphizes on demand.
            return Some(OverloadTarget::Generic);
        }
        // A concrete winner is emitted under its mangled per-signature name. All
        // slots of a concrete def are `Concrete(..)`, so this is well-defined.
        let param_tys: Vec<MirType> = winner
            .slots
            .iter()
            .map(|s| match s {
                ParamSlot::Concrete(t) => t.clone(),
                // Unreachable for a non-generic def, but degrade safely.
                ParamSlot::Generic => MirType::i32(),
            })
            .collect();
        Some(OverloadTarget::Concrete(Self::mangle_multi_fn_name(
            resolved_name,
            &param_tys,
        )))
    }

    /// Codegen-side specificity match for one position. Mirrors the checker's
    /// `dispatch_position_match` (`types::infer`) so both sides pick the same
    /// method; the two are hand-maintained copies over different type
    /// representations (`ParamSlot`/`MirType` here vs `Ty` there) and MUST agree
    /// on the ordering, or checker and codegen diverge on the winner.
    ///
    /// - A generic slot matches any argument as `Generic` (least specific).
    /// - A concrete param equal to the arg is `Exact`.
    /// - Int/float args coerce to a matching numeric param (`Coercion`), matching
    ///   the checker's literal-defaulting rule (`add(3,5)` -> i32, `add(3.0)`
    ///   -> f64).
    /// - Otherwise `None` (the concrete parameter rules the candidate out).
    fn mir_position_match(param: &ParamSlot, arg: &MirType) -> Option<crate::types::PositionMatch> {
        use crate::types::PositionMatch;
        let param = match param {
            ParamSlot::Generic => return Some(PositionMatch::Generic),
            ParamSlot::Concrete(t) => t,
        };
        if param == arg {
            return Some(PositionMatch::Exact);
        }
        // Integer-literal args default to i32 in `infer_single_arg_type`; treat
        // any integer arg as coercible to any integer param, and likewise for
        // floats, so `add(3,5)` selects the i32 overload while `add(3.0,5.0)`
        // selects the f64 one (matching the checker's literal-defaulting rule).
        match (param, arg) {
            (MirType::Int(..), MirType::Int(..)) => Some(PositionMatch::Coercion),
            (MirType::Float(..), MirType::Float(..)) => Some(PositionMatch::Coercion),
            // `&mut T` passed where `&T` is expected: MIR does not distinguish
            // the two pointer kinds, so a pointer to the same pointee matches.
            (MirType::Ptr(p), MirType::Ptr(a)) if p == a => Some(PositionMatch::Coercion),
            _ => None,
        }
    }

    fn collect_function(&mut self, f: &ast::FnDef) -> CodegenResult<()> {
        // If the function has generic type parameters, store it for later
        // monomorphization instead of lowering it immediately.
        if self.fn_has_type_generics(f) {
            self.generic_functions
                .insert(f.name.name.clone(), f.clone());
            return Ok(());
        }

        // Register a forward declaration so that resolve_call_return_type
        // can find the function's return type even before its body is lowered.
        // Skip `main` since its return type is special-cased during lowering.
        if f.name.name.as_ref() != "main" {
            // Overloaded definitions are emitted under a mangled, per-signature
            // name; single-def names keep their plain name (backward compat).
            let emitted = self.emitted_fn_name(f);
            let params: Vec<MirType> = f
                .sig
                .params
                .iter()
                .map(|p| self.lower_type_from_ast(&p.ty))
                .collect();
            let ret = f
                .sig
                .return_ty
                .as_ref()
                .map(|t| self.lower_type_from_ast(t))
                .unwrap_or(MirType::Void);
            let sig = MirFnSig::new(params, ret);
            self.module.declare_function(emitted.clone(), sig);

            // Capture the Ok payload type for `-> Result<Ok, Err>` returns so a
            // `match call() { Ok(x) => ... }` on a direct call can read the
            // correct union slot without an intervening let annotation.
            if let Some(ref ret_ty) = f.sig.return_ty {
                if let Some(ok_ty) = self.result_ok_inner_from_ast(ret_ty) {
                    self.fn_result_ok_types.insert(emitted.clone(), ok_ty);
                }
                if let Some(err_ty) = self.result_err_inner_from_ast(ret_ty) {
                    self.fn_result_err_types.insert(emitted.clone(), err_ty);
                }
                // Same threading for `-> Option<T>` so a direct-call Some match
                // reads the correct slot (symmetric to the Result Ok case).
                if let Some(inner_ty) = self.option_inner_from_ast(ret_ty) {
                    self.fn_option_inner_types.insert(emitted.clone(), inner_ty);
                }
                if Self::ast_type_is_char(ret_ty) {
                    self.fn_returns_char.insert(emitted.clone());
                } else if Self::ast_type_is_char_vec(ret_ty) {
                    self.fn_returns_char_vec.insert(emitted.clone());
                }
            }
        }

        Ok(())
    }

    /// If the AST type is `Result<Ok, Err>`, lower and return the `Ok` payload
    /// type. Returns None for any non-Result type. Used to thread the Ok type
    /// from a function signature to its match sites.
    pub(crate) fn result_ok_inner_from_ast(&self, ty: &ast::Type) -> Option<MirType> {
        self.generic_first_arg_from_ast(ty, "Result")
    }

    /// If the AST type is `Result<Ok, Err>`, lower and return the `Err` payload
    /// type (the second generic argument). Returns None for any non-Result type.
    pub(crate) fn result_err_inner_from_ast(&self, ty: &ast::Type) -> Option<MirType> {
        if let ast::TypeKind::Path(ref path) = ty.kind {
            let is_result = path
                .last_ident()
                .map(|i| i.name.as_ref() == "Result")
                .unwrap_or(false);
            if is_result {
                if let Some(args) = path.last_generics() {
                    if let Some(ast::GenericArg::Type(ref err_ast_ty)) = args.get(1) {
                        return Some(self.lower_type_from_ast(err_ast_ty));
                    }
                }
            }
        }
        None
    }

    /// If the AST type is `Option<T>`, lower and return the `T` payload type.
    /// Returns None for any non-Option type.
    pub(crate) fn option_inner_from_ast(&self, ty: &ast::Type) -> Option<MirType> {
        self.generic_first_arg_from_ast(ty, "Option")
    }

    /// If the AST type is `Wrapper<First, ...>`, lower and return `First`.
    /// Returns None when the type head doesn't match `wrapper` or has no args.
    fn generic_first_arg_from_ast(&self, ty: &ast::Type, wrapper: &str) -> Option<MirType> {
        if let ast::TypeKind::Path(ref path) = ty.kind {
            let matches_head = path
                .last_ident()
                .map(|i| i.name.as_ref() == wrapper)
                .unwrap_or(false);
            if matches_head {
                if let Some(args) = path.last_generics() {
                    if let Some(ast::GenericArg::Type(ref inner_ast_ty)) = args.first() {
                        return Some(self.lower_type_from_ast(inner_ast_ty));
                    }
                }
            }
        }
        None
    }

    /// Collect impl block methods, registering them as `TypeName_methodName` functions.
    fn collect_impl(&mut self, impl_def: &ast::ImplDef) -> CodegenResult<()> {
        let type_name = self.resolve_type_name(&impl_def.self_ty);
        self.note_drop_impl(impl_def, &type_name);

        // Check if this is an impl on a generic type (e.g., impl<T> Option<T> { ... })
        // If so, store for deferred monomorphization.
        let has_impl_generics = impl_def
            .generics
            .params
            .iter()
            .any(|p| matches!(p.kind, ast::GenericParamKind::Type { .. }));
        let is_generic_type = self.generic_enums.contains_key(type_name.as_ref())
            || self.generic_structs.contains_key(type_name.as_ref());

        if has_impl_generics || is_generic_type {
            self.generic_impls
                .entry(type_name.clone())
                .or_insert_with(Vec::new)
                .push(impl_def.clone());
            return Ok(());
        }

        // Standard-library formatting traits need `std::fmt::Formatter`, which
        // the C backend does not provide; the impl used to emit an unknown C
        // type. Reject it with the supported alternative.
        if let Some(tr) = impl_def.trait_ref.as_ref() {
            let segs: Vec<&str> = tr
                .path
                .segments
                .iter()
                .map(|s| s.ident.name.as_ref())
                .collect();
            if let Some(last @ ("Display" | "Debug")) = segs.last().copied() {
                let span = tr.path.span;
                return Err(crate::codegen::CodegenError::Rejected {
                    message: format!(
                        "implementing `{last}` is not supported by the C backend: it has no `std::fmt::Formatter`"
                    ),
                    location: (span.end.0 > span.start.0).then_some((span.start.0, span.end.0)),
                    help: Some(format!(
                        "give `{type_name}` a method that builds the text, for example `fn to_string(&self) -> String {{ format!(\"...\", self.x) }}`, and print that"
                    )),
                });
            }
        }

        // Track trait implementations for vtable generation
        let trait_name = impl_def.trait_ref.as_ref().map(|tr| {
            tr.path
                .last_ident()
                .map(|i| i.name.clone())
                .unwrap_or(Arc::from("Unknown"))
        });

        let mut impl_method_names = Vec::new();

        for impl_item in &impl_def.items {
            if let ast::ImplItemKind::Function(f) = &impl_item.kind {
                let method_name = f.name.name.clone();
                let mangled: Arc<str> = Arc::from(format!("{}_{}", type_name, method_name));
                self.impl_methods
                    .insert((type_name.clone(), method_name.clone()), mangled.clone());
                impl_method_names.push(mangled.clone());

                // Forward-declare the method signature so resolve_call_return_type
                // can find the correct return type during lowering.
                let mut params = Vec::new();
                for param in &f.sig.params {
                    let is_self = matches!(
                        &param.pattern.kind,
                        ast::PatternKind::Ident { name, .. } if name.name.as_ref() == "self"
                    );
                    if is_self {
                        if matches!(param.ty.kind, ast::TypeKind::Ref { .. }) {
                            params.push(MirType::Ptr(Box::new(MirType::Struct(type_name.clone()))));
                        } else {
                            params.push(MirType::Struct(type_name.clone()));
                        }
                    } else {
                        params.push(self.lower_type_from_ast(&param.ty));
                    }
                }
                let ret = f
                    .sig
                    .return_ty
                    .as_ref()
                    .map(|t| self.lower_type_from_ast(t))
                    .unwrap_or(MirType::Void);
                // Resolve Self in the return type to the concrete impl type so
                // callers outside the impl see the real type (e.g. fn new() -> Self).
                let ret = match ret {
                    MirType::Struct(ref name) if name.as_ref() == "Self" => {
                        MirType::Struct(type_name.clone())
                    }
                    MirType::Ptr(ref inner) => {
                        if let MirType::Struct(ref name) = **inner {
                            if name.as_ref() == "Self" {
                                MirType::Ptr(Box::new(MirType::Struct(type_name.clone())))
                            } else {
                                ret
                            }
                        } else {
                            ret
                        }
                    }
                    _ => ret,
                };
                // Thread the method's Result/Option payload types, keyed by the
                // mangled name, so a `match recv.method() { ... }` reads the
                // correct union slot (mirrors collect_function for free fns).
                if let Some(ref ret_ty) = f.sig.return_ty {
                    if let Some(ok_ty) = self.result_ok_inner_from_ast(ret_ty) {
                        self.fn_result_ok_types.insert(mangled.clone(), ok_ty);
                    }
                    if let Some(err_ty) = self.result_err_inner_from_ast(ret_ty) {
                        self.fn_result_err_types.insert(mangled.clone(), err_ty);
                    }
                    if let Some(inner_ty) = self.option_inner_from_ast(ret_ty) {
                        self.fn_option_inner_types.insert(mangled.clone(), inner_ty);
                    }
                    if Self::ast_type_is_char(ret_ty) {
                        self.fn_returns_char.insert(mangled.clone());
                    } else if Self::ast_type_is_char_vec(ret_ty) {
                        self.fn_returns_char_vec.insert(mangled.clone());
                    }
                }

                self.module
                    .declare_function(mangled, MirFnSig::new(params, ret));
            }
        }

        // Register trait impl for vtable generation
        if let Some(ref tname) = trait_name {
            self.trait_impls
                .insert((tname.clone(), type_name.clone()), impl_method_names);
        }

        Ok(())
    }

    /// Extract a type name from an AST Type node (used for impl block self_ty).
    fn resolve_type_name(&self, ty: &ast::Type) -> Arc<str> {
        let bare_name = match &ty.kind {
            ast::TypeKind::Path(path) => path
                .last_ident()
                .map(|i| i.name.clone())
                .unwrap_or(Arc::from("Unknown")),
            _ => Arc::from("Unknown"),
        };
        // Inside a module, use the prefixed name for user-defined types
        // to match struct typedefs (e.g., `Vec3` -> `std_Vec3`).
        // Do NOT prefix builtins (Vec, HashMap, String, etc.).
        if !self.module_prefix.is_empty() {
            let name = bare_name.as_ref();
            let is_builtin = matches!(
                name,
                "Vec"
                    | "HashMap"
                    | "HashSet"
                    | "BTreeMap"
                    | "BTreeSet"
                    | "String"
                    | "Option"
                    | "Result"
                    | "Box"
            );
            if !is_builtin {
                let prefixed = self.prefixed_name(&bare_name);
                if self.module.find_type(prefixed.as_ref()).is_some() {
                    return prefixed;
                }
            }
        }
        bare_name
    }

    // =========================================================================
    // LOWERING PASS
    // =========================================================================

    fn lower_item(&mut self, item: &ast::Item) -> CodegenResult<()> {
        match &item.kind {
            ItemKind::Function(f) => self.lower_function_with_vis(f, &item.attrs, &item.vis),
            ItemKind::Struct(s) => {
                // Generate derive'd methods (e.g., clone)
                self.generate_derive_methods(&s.name, &item.attrs)
            }
            ItemKind::Static(s) => {
                // Check for #[uniform] attribute
                if Self::has_attribute(&item.attrs, "uniform") {
                    self.extract_uniform_from_static(s);
                }
                self.lower_static(s)
            }
            ItemKind::Const(c) => {
                // Check for #[uniform] attribute
                if Self::has_attribute(&item.attrs, "uniform") {
                    self.extract_uniform_from_const(c);
                }
                self.lower_const(c)
            }
            ItemKind::Impl(impl_def) => self.lower_impl(impl_def),
            // Effect declarations produce no code -- handled at type-check time
            // and dispatched via effect_id at runtime.
            ItemKind::Effect(_) => Ok(()),
            // Inline module: push module name onto prefix stack and
            // recursively lower all contained items.
            ItemKind::Mod(m) => self.lower_inline_mod(m, false),
            // Use declarations - no-op in lowering (name resolution is
            // handled by the prefix + join scheme).
            ItemKind::Use(_) => Ok(()),
            _ => Ok(()),
        }
    }

    /// Lower items inside an inline `mod` block.
    ///
    /// Similar to `collect_inline_mod`, this pushes the module name onto
    /// the prefix stack and rewrites item names before lowering. `top_level`
    /// is true for a module-level `mod`, whose globals `collect_globals`
    /// has already added.
    fn lower_inline_mod(&mut self, m: &ast::ModDef, top_level: bool) -> CodegenResult<()> {
        if let Some(ref content) = m.content {
            self.module_prefix.push(m.name.name.clone());
            for item in &content.items {
                let rewritten = self.rewrite_item_with_prefix(item);
                if top_level {
                    self.lower_top_level_item(&rewritten)?;
                } else {
                    self.lower_item(&rewritten)?;
                }
            }
            self.module_prefix.pop();
        }
        Ok(())
    }

    /// Add the module-level `const` and `static` globals, in source order,
    /// ahead of the body pass. Items inside an inline `mod` get the same
    /// prefixed names `lower_inline_mod` gives them.
    fn collect_globals(&mut self, item: &ast::Item) -> CodegenResult<()> {
        match &item.kind {
            ItemKind::Static(s) => self.lower_static(s),
            ItemKind::Const(c) => self.lower_const(c),
            ItemKind::Mod(m) => {
                if let Some(ref content) = m.content {
                    self.module_prefix.push(m.name.name.clone());
                    for it in &content.items {
                        let rewritten = self.rewrite_item_with_prefix(it);
                        self.collect_globals(&rewritten)?;
                    }
                    self.module_prefix.pop();
                }
                Ok(())
            }
            _ => Ok(()),
        }
    }

    /// Lower a module-level item in the body pass. Its `const` and `static`
    /// globals were added by `collect_globals`, so only the `#[uniform]`
    /// extraction is left for them here; a `const` inside a function body
    /// still goes through `lower_item`.
    fn lower_top_level_item(&mut self, item: &ast::Item) -> CodegenResult<()> {
        match &item.kind {
            ItemKind::Static(s) => {
                if Self::has_attribute(&item.attrs, "uniform") {
                    self.extract_uniform_from_static(s);
                }
                Ok(())
            }
            ItemKind::Const(c) => {
                if Self::has_attribute(&item.attrs, "uniform") {
                    self.extract_uniform_from_const(c);
                }
                Ok(())
            }
            ItemKind::Mod(m) => self.lower_inline_mod(m, true),
            _ => self.lower_item(item),
        }
    }

    /// Check if any attribute has the given name.
    fn has_attribute(attrs: &[ast::Attribute], name: &str) -> bool {
        attrs.iter().any(|attr| {
            attr.path
                .segments
                .first()
                .map_or(false, |seg| seg.ident.name.as_ref() == name)
        })
    }

    /// Extract a uniform declaration from a const item with #[uniform].
    fn extract_uniform_from_const(&mut self, c: &ast::ConstDef) {
        let ty = self.lower_type_from_ast(&c.ty);
        let default = c.value.as_ref().and_then(|e| self.try_const_eval(e));
        self.module.module_mut().uniforms.push(MirUniform {
            name: c.name.name.clone(),
            ty,
            default,
        });
    }

    /// Extract a uniform declaration from a static item with #[uniform].
    fn extract_uniform_from_static(&mut self, s: &ast::StaticDef) {
        let ty = self.lower_type_from_ast(&s.ty);
        let default = s.value.as_ref().and_then(|e| self.try_const_eval(e));
        self.module.module_mut().uniforms.push(MirUniform {
            name: s.name.name.clone(),
            ty,
            default,
        });
    }

    /// Extract shader stage from function attributes (#[vertex], #[fragment], #[compute]).
    fn extract_shader_stage(attrs: &[ast::Attribute]) -> Option<ShaderStage> {
        for attr in attrs {
            if let Some(seg) = attr.path.segments.first() {
                match seg.ident.name.as_ref() {
                    "vertex" => return Some(ShaderStage::Vertex),
                    "fragment" => return Some(ShaderStage::Fragment),
                    "compute" => return Some(ShaderStage::Compute),
                    _ => {}
                }
            }
        }
        None
    }

    /// Extract uniform binding info from attributes: #[uniform(binding = N, set = M)]
    fn extract_uniform_binding(&self, attrs: &[ast::Attribute]) -> Option<(u32, u32)> {
        for attr in attrs {
            if let Some(seg) = attr.path.segments.first() {
                if seg.ident.name.as_ref() == "uniform" {
                    let mut binding = 0u32;
                    let mut set = 0u32;
                    if let ast::AttrArgs::Delimited(tokens) = &attr.args {
                        // Parse binding = N, set = M from token stream
                        let mut i = 0;
                        while i < tokens.len() {
                            if let ast::TokenTree::Token(tok) = &tokens[i] {
                                if let crate::lexer::TokenKind::Ident = &tok.kind {
                                    // Extract identifier name from source via span
                                    let name_str = if let Some(ref src) = self.source {
                                        let start = tok.span.start.to_usize();
                                        let end = tok.span.end.to_usize();
                                        if end <= src.len() {
                                            Some(src[start..end].to_string())
                                        } else {
                                            None
                                        }
                                    } else {
                                        None
                                    };
                                    // Look for "= N" after the identifier
                                    if let Some(name_str) = name_str {
                                        if i + 2 < tokens.len() {
                                            if let ast::TokenTree::Token(ref num_tok) =
                                                tokens[i + 2]
                                            {
                                                if let crate::lexer::TokenKind::Literal { .. } =
                                                    &num_tok.kind
                                                {
                                                    // Extract numeric value from source via span
                                                    if let Some(ref src) = self.source {
                                                        let start = num_tok.span.start.to_usize();
                                                        let end = num_tok.span.end.to_usize();
                                                        if end <= src.len() {
                                                            if let Ok(n) =
                                                                src[start..end].parse::<u32>()
                                                            {
                                                                match name_str.as_str() {
                                                                    "binding" => binding = n,
                                                                    "set" => set = n,
                                                                    _ => {}
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            i += 1;
                        }
                    }
                    return Some((set, binding));
                }
            }
        }
        None
    }

    /// Lower a function with explicit visibility from the Item node.
    fn lower_function_with_vis(
        &mut self,
        f: &ast::FnDef,
        attrs: &[ast::Attribute],
        vis: &ast::Visibility,
    ) -> CodegenResult<()> {
        self.current_item_vis = Some(vis.is_public());
        let result = self.lower_function(f, attrs);
        self.current_item_vis = None;
        result
    }

    /// Lower one function with `self.source` set to the text of the file the
    /// function came from. Macro arguments (`println!`, `format!`, `vec!`) are
    /// re-read from source text by span; a function merged in from a `mod`
    /// file has spans into that file, and before M4 they were read against the
    /// main file, so `format!("hello {}", n)` in a module printed unrelated
    /// text from the main program.
    fn lower_function(&mut self, f: &ast::FnDef, attrs: &[ast::Attribute]) -> CodegenResult<()> {
        slice_escape::check_fn(f)?;
        let own = crate::lexer::source_text_for_id(f.name.span.source_id)
            .filter(|_| f.name.span.source_id != crate::lexer::SourceId::ANONYMOUS);
        let Some(text) = own else {
            return self.lower_function_body(f, attrs);
        };
        let saved = self.source.replace(text);
        let result = self.lower_function_body(f, attrs);
        self.source = saved;
        result
    }

    fn lower_function_body(
        &mut self,
        f: &ast::FnDef,
        attrs: &[ast::Attribute],
    ) -> CodegenResult<()> {
        // Skip generic functions - they are monomorphized on demand at call sites.
        if self.fn_has_type_generics(f) {
            return Ok(());
        }
        // A function that returns `impl Trait` is lowered once, at its first
        // call or here, whichever comes first.
        if self.impl_return_fns.contains_key(&f.name.name)
            && !self.impl_return_done.insert(f.name.name.clone())
        {
            return Ok(());
        }

        // Build function signature
        let mut params: Vec<_> = f
            .sig
            .params
            .iter()
            .map(|p| self.lower_type_from_ast(&p.ty))
            .collect();
        // A specialisation made for a capturing closure takes the captured
        // values after its declared parameters.
        let closure_params = std::mem::take(&mut self.pending_closure_params);
        let declared_params = params.len();
        for (_, _, captured) in &closure_params {
            params.extend(captured.iter().map(|(_, ty)| ty.clone()));
        }

        let is_main = f.name.name.as_ref() == "main";
        let has_shader_stage = Self::extract_shader_stage(attrs).is_some();
        // Overloaded definitions are emitted under a mangled per-signature name;
        // single-def names keep their plain name (backward compat / FFI).
        let emitted_name = self.emitted_fn_name(f);

        let ret = if is_main && f.sig.return_ty.is_none() && !has_shader_stage {
            // C requires main to return int (but not shader main)
            MirType::i32()
        } else {
            f.sig
                .return_ty
                .as_ref()
                .map(|t| self.lower_type_from_ast(t))
                .unwrap_or(MirType::Void)
        };

        // Register tuple type defs for any tuple types in the signature.
        if let MirType::Tuple(ref elems) = ret {
            self.ensure_tuple_type_def(elems);
        }

        let sig = MirFnSig::new(params, ret);
        let fn_ret_ty = sig.ret.clone();

        if let Some(body) = &f.body {
            // Save the current function context so that nested function
            // definitions (e.g. `fn helper()` inside another function body)
            // do not clobber the enclosing function's builder and var_map.
            let saved_fn = self.current_fn.take();
            let saved_vars = std::mem::take(&mut self.var_map);
            let saved_chars = std::mem::take(&mut self.char_locals);
            let saved_refs = std::mem::take(&mut self.ref_locals);
            let saved_str_refs = std::mem::take(&mut self.str_ref_locals);
            let saved_char_vecs = std::mem::take(&mut self.char_vec_locals);
            let saved_pending_vecs = std::mem::take(&mut self.pending_untyped_vecs);
            // Local ids restart in every function, so which locals hold a
            // closure is per function too.
            let saved_closure_locals = std::mem::take(&mut self.local_closure_name);
            let saved_env_locals = std::mem::take(&mut self.local_env_closure);

            // Create function builder
            let mut builder = MirBuilder::with_linear_type_names(
                emitted_name.clone(),
                sig,
                Arc::new(self.linear_type_names.clone()),
            );

            // Map parameters to locals and set their names + annotations
            for (i, param) in f.sig.params.iter().enumerate() {
                if let ast::PatternKind::Ident { name, .. } = &param.pattern.kind {
                    let local_id = builder.param_local(i);
                    builder.set_param_name(i, name.name.clone());
                    // Thread reference mutability (`&mut T` vs `&T`) into the
                    // param local so backends (notably SPIR-V compute) can tell a
                    // writable output buffer from a read-only input. A `&mut`
                    // reference or a `*mut` raw pointer is mutable; everything
                    // else stays read-only (the MirLocal default).
                    let is_mut = matches!(
                        &param.ty.kind,
                        ast::TypeKind::Ref {
                            mutability: ast::Mutability::Mutable,
                            ..
                        } | ast::TypeKind::Ptr {
                            mutability: ast::Mutability::Mutable,
                            ..
                        }
                    );
                    if is_mut {
                        builder.set_param_mut(i, true);
                    }
                    // Extract type annotations (e.g., `with ColorSpace<Linear>`)
                    let annotations = Self::extract_type_annotations(&param.ty);
                    if !annotations.is_empty() {
                        builder.set_param_annotations(i, annotations);
                    }
                    self.var_map.insert(name.name.clone(), local_id);
                    self.record_result_param(local_id, &param.ty);
                    if matches!(param.ty.kind, ast::TypeKind::Ref { .. }) {
                        self.ref_locals.insert(local_id);
                    }
                    if Self::ast_type_is_str_ref(&param.ty) {
                        self.str_ref_locals.insert(local_id);
                    }
                    if Self::ast_type_is_char(&param.ty) {
                        self.char_locals.insert(local_id);
                    } else if Self::ast_type_is_char_vec(&param.ty) {
                        self.char_vec_locals.insert(local_id);
                    }
                }
            }

            let mut next_param = declared_params;
            for (index, closure_name, captured) in &closure_params {
                self.local_closure_name
                    .insert(builder.param_local(*index), closure_name.clone());
                let mut here = Vec::with_capacity(captured.len());
                for (name, _) in captured {
                    let local_id = builder.param_local(next_param);
                    builder.set_param_name(
                        next_param,
                        Arc::from(format!("{}_{}", closure_name, name)),
                    );
                    here.push((name.clone(), local_id));
                    next_param += 1;
                }
                self.closure_captures.insert(closure_name.clone(), here);
            }

            self.current_fn = Some(builder);

            // Lower function body (tail expression sees the declared return type)
            let result = self.lower_fn_body(body)?;
            // A closure in the tail of a function that returns `impl Trait`
            // leaves as its function pointer, or as its captured values.
            let (result, closure_ret) = if self.impl_return_fns.contains_key(&f.name.name) {
                self.closure_return_value(&emitted_name, result)
            } else {
                (result, None)
            };

            // Add return if needed
            let mut builder = self.current_fn.take().unwrap();
            // Attribute the (possibly synthesized) implicit return to the
            // whole body's span; individual `return` expressions inside the
            // body already carry their own statement's span via lower_block.
            builder.set_current_span(body.span);
            if is_main && !has_shader_stage {
                // main returns 0 (success) in C - but not for shader entry points
                let zero = MirValue::Const(MirConst::Int(0, MirType::i32()));
                builder.ret(Some(zero));
            } else if f.sig.return_ty.is_some()
                && matches!(result, Some(MirValue::Const(MirConst::Unit)))
                && !matches!(fn_ret_ty, MirType::Void)
            {
                // The body ends in a statement with no value, such as a `loop`
                // that only leaves through `return`. A checked program never
                // gets here; returning the unit value was a C error. Stop the
                // program if it does.
                builder.abort();
            } else if f.sig.return_ty.is_some() {
                if let Some(val) = result {
                    // If the result is a local that might not be declared
                    // (created in a block unreachable from the while loop exit),
                    // ensure the local exists by re-creating it if needed.
                    if let MirValue::Local(id) = &val {
                        if builder.local_type(*id).is_none() {
                            let ret_ty = fn_ret_ty.clone();
                            let ret_local = builder.create_local(ret_ty.clone());
                            let default = match &ret_ty {
                                MirType::Int(_, _) => MirValue::Const(MirConst::Int(0, ret_ty)),
                                MirType::Float(_) => MirValue::Const(MirConst::Float(0.0, ret_ty)),
                                _ => MirValue::Const(MirConst::Int(0, MirType::i32())),
                            };
                            builder.assign(ret_local, MirRValue::Use(default));
                            builder.ret(Some(MirValue::Local(ret_local)));
                        } else {
                            builder.ret(Some(val));
                        }
                    } else {
                        builder.ret(Some(val));
                    }
                }
            } else {
                builder.ret_void();
            }

            let mut func = builder.build();
            if let Some(ty) = closure_ret {
                func.sig.ret = ty.clone();
                self.module.set_return_type(emitted_name.as_ref(), &ty);
            }
            if is_main {
                func.linkage = Linkage::External; // main must not be static
            }
            // An `extern "C" fn` definition is an explicit C-ABI export: give it
            // external linkage so the symbol is callable from C (not `static`),
            // and mark it for declaration in the generated C export header.
            if f.sig.abi.is_some() {
                func.linkage = Linkage::External;
                func.is_c_export = true;
                self.check_c_export_signature(f, &func)?;
            }
            func.is_public = is_main || self.current_item_vis.unwrap_or(true);

            // Set shader stage from attributes (#[vertex], #[fragment], #[compute])
            func.shader_stage = Self::extract_shader_stage(attrs);
            if func.shader_stage.is_some() {
                func.is_public = true; // shader entry points must be public
            }

            self.module.add_function(func);

            // Restore the enclosing function context (if any).
            self.current_fn = saved_fn;
            self.var_map = saved_vars;
            self.char_locals = saved_chars;
            self.ref_locals = saved_refs;
            self.str_ref_locals = saved_str_refs;
            self.char_vec_locals = saved_char_vecs;
            self.pending_untyped_vecs = saved_pending_vecs;
            self.local_closure_name = saved_closure_locals;
            self.local_env_closure = saved_env_locals;
        } else {
            // Declaration only
            self.module.declare_function(f.name.name.clone(), sig);
        }

        Ok(())
    }

    /// Lower all methods in an impl block as free functions with mangled names.
    fn lower_impl(&mut self, impl_def: &ast::ImplDef) -> CodegenResult<()> {
        let type_name = self.resolve_type_name(&impl_def.self_ty);

        // Skip generic impls - they are lowered when the type is monomorphized
        let has_impl_generics = impl_def
            .generics
            .params
            .iter()
            .any(|p| matches!(p.kind, ast::GenericParamKind::Type { .. }));
        let is_generic_type = self.generic_enums.contains_key(type_name.as_ref())
            || self.generic_structs.contains_key(type_name.as_ref());

        if has_impl_generics || is_generic_type {
            return Ok(());
        }

        // Set current impl type so Self resolves correctly in type lowering
        self.current_impl_type = Some(type_name.clone());

        // PASS 1: Forward-declare ALL method signatures before lowering bodies.
        // This fixes forward references: method A can call method B even if B
        // is defined after A in the source, because B's signature is already known.
        for impl_item in &impl_def.items {
            if let ast::ImplItemKind::Function(f) = &impl_item.kind {
                self.declare_impl_method(&type_name, f)?;
            }
            // An associated constant `Type::NAME` is the global `Type_NAME`,
            // the name a path to it lowers to.
            if let ast::ImplItemKind::Const { name, ty, value } = &impl_item.kind {
                let global_name: Arc<str> = Arc::from(format!("{}_{}", type_name, name.name));
                let mir_ty = self.lower_type_from_ast(ty);
                let init = self.global_initializer(&global_name, value, &mir_ty)?;
                let mut global = MirGlobal::new(global_name, mir_ty);
                global.init = init;
                global.is_mut = false;
                self.module.add_global(global);
            }
        }

        // PASS 2: Lower method bodies (signatures already declared).
        for impl_item in &impl_def.items {
            if let ast::ImplItemKind::Function(f) = &impl_item.kind {
                self.lower_impl_method(&type_name, f)?;
            }
        }

        self.current_impl_type = None;
        Ok(())
    }

    /// Forward-declare an impl method's signature without lowering the body.
    /// This enables forward references within the same impl block.
    fn declare_impl_method(&mut self, type_name: &Arc<str>, f: &ast::FnDef) -> CodegenResult<()> {
        let mangled_name: Arc<str> = Arc::from(format!("{}_{}", type_name, f.name.name));

        // Build parameter types
        let mut params = Vec::new();
        for param in &f.sig.params {
            let is_self = matches!(
                &param.pattern.kind,
                ast::PatternKind::Ident { name, .. } if name.name.as_ref() == "self"
            );
            if is_self {
                if matches!(param.ty.kind, ast::TypeKind::Ref { .. }) {
                    params.push(MirType::Ptr(Box::new(MirType::Struct(type_name.clone()))));
                } else {
                    params.push(MirType::Struct(type_name.clone()));
                }
            } else {
                params.push(self.lower_type_from_ast(&param.ty));
            }
        }

        let ret = f
            .sig
            .return_ty
            .as_ref()
            .map(|t| self.lower_type_from_ast(t))
            .unwrap_or(MirType::Void);

        // Resolve any remaining Self in return type to the concrete impl type.
        // This ensures callers outside the impl block see the real type.
        let ret = match ret {
            MirType::Struct(ref name) if name.as_ref() == "Self" => {
                MirType::Struct(type_name.clone())
            }
            MirType::Ptr(ref inner) => {
                if let MirType::Struct(ref name) = **inner {
                    if name.as_ref() == "Self" {
                        MirType::Ptr(Box::new(MirType::Struct(type_name.clone())))
                    } else {
                        ret
                    }
                } else {
                    ret
                }
            }
            _ => ret,
        };

        // Register tuple type defs for any tuple types in the signature
        // (mirrors lower_function; impl methods returning a tuple of named
        // structs otherwise never register the tuple's MirTypeDef).
        if let MirType::Tuple(ref elems) = ret {
            self.ensure_tuple_type_def(elems);
        }

        let sig = MirFnSig::new(params, ret);
        self.module.declare_function(mangled_name, sig);
        Ok(())
    }

    /// Lower a single impl method as a free function.
    /// The method `fn area(self) -> f64` on type `Rectangle` becomes
    /// `fn Rectangle_area(self: Rectangle) -> f64`.
    fn lower_impl_method(&mut self, type_name: &Arc<str>, f: &ast::FnDef) -> CodegenResult<()> {
        let mangled_name: Arc<str> = Arc::from(format!("{}_{}", type_name, f.name.name));

        // Build parameter types: `self` becomes the struct type, `&self`/`&mut self`
        // becomes a pointer to the struct type, others are lowered normally.
        let mut params = Vec::new();
        for param in &f.sig.params {
            let is_self = matches!(&param.pattern.kind,
                ast::PatternKind::Ident { name, .. } if name.name.as_ref() == "self"
            );
            if is_self {
                // Check if the type is a reference (&Self or &mut Self)
                if matches!(param.ty.kind, ast::TypeKind::Ref { .. }) {
                    params.push(MirType::Ptr(Box::new(MirType::Struct(type_name.clone()))));
                } else {
                    params.push(MirType::Struct(type_name.clone()));
                }
            } else {
                params.push(self.lower_type_from_ast(&param.ty));
            }
        }

        let ret = f
            .sig
            .return_ty
            .as_ref()
            .map(|t| self.lower_type_from_ast(t))
            .unwrap_or(MirType::Void);

        // Resolve Self in return type to concrete impl type
        let ret = match ret {
            MirType::Struct(ref name) if name.as_ref() == "Self" => {
                MirType::Struct(type_name.clone())
            }
            MirType::Ptr(ref inner) => {
                if let MirType::Struct(ref name) = **inner {
                    if name.as_ref() == "Self" {
                        MirType::Ptr(Box::new(MirType::Struct(type_name.clone())))
                    } else {
                        ret
                    }
                } else {
                    ret
                }
            }
            _ => ret,
        };

        // Register tuple type defs for any tuple types in the signature
        // (mirrors lower_function; impl methods returning a tuple of named
        // structs otherwise never register the tuple's MirTypeDef).
        if let MirType::Tuple(ref elems) = ret {
            self.ensure_tuple_type_def(elems);
        }

        let sig = MirFnSig::new(params, ret);

        if let Some(body) = &f.body {
            // Save enclosing function context for nested method definitions.
            let saved_fn = self.current_fn.take();
            let saved_vars = std::mem::take(&mut self.var_map);
            let saved_chars = std::mem::take(&mut self.char_locals);
            let saved_refs = std::mem::take(&mut self.ref_locals);
            let saved_str_refs = std::mem::take(&mut self.str_ref_locals);
            let saved_char_vecs = std::mem::take(&mut self.char_vec_locals);
            let saved_pending_vecs = std::mem::take(&mut self.pending_untyped_vecs);

            let mut builder = MirBuilder::with_linear_type_names(
                mangled_name.clone(),
                sig,
                Arc::new(self.linear_type_names.clone()),
            );

            // Map parameters (including self) to locals
            for (i, param) in f.sig.params.iter().enumerate() {
                if let ast::PatternKind::Ident { name, .. } = &param.pattern.kind {
                    let local_id = builder.param_local(i);
                    builder.set_param_name(i, name.name.clone());
                    self.var_map.insert(name.name.clone(), local_id);
                    self.record_result_param(local_id, &param.ty);
                    if matches!(param.ty.kind, ast::TypeKind::Ref { .. }) {
                        self.ref_locals.insert(local_id);
                    }
                    if Self::ast_type_is_str_ref(&param.ty) {
                        self.str_ref_locals.insert(local_id);
                    }
                    if Self::ast_type_is_char(&param.ty) {
                        self.char_locals.insert(local_id);
                    } else if Self::ast_type_is_char_vec(&param.ty) {
                        self.char_vec_locals.insert(local_id);
                    }
                }
            }

            self.current_fn = Some(builder);

            let result = self.lower_fn_body(body)?;

            let mut builder = self.current_fn.take().unwrap();
            let returns_value = f
                .sig
                .return_ty
                .as_ref()
                .is_some_and(|t| !matches!(self.lower_type_from_ast(t), MirType::Void));
            if returns_value && matches!(result, Some(MirValue::Const(MirConst::Unit))) {
                // The body ends in a statement with no value (see `lower_function`).
                builder.abort();
            } else if f.sig.return_ty.is_some() {
                if let Some(val) = result {
                    builder.ret(Some(val));
                }
            } else {
                builder.ret_void();
            }

            let mut func = builder.build();
            func.is_public = true;
            self.module.add_function(func);

            // Restore enclosing function context.
            self.current_fn = saved_fn;
            self.var_map = saved_vars;
            self.char_locals = saved_chars;
            self.ref_locals = saved_refs;
            self.str_ref_locals = saved_str_refs;
            self.char_vec_locals = saved_char_vecs;
            self.pending_untyped_vecs = saved_pending_vecs;
        }

        Ok(())
    }

    /// Lower a monomorphized generic impl method. Unlike lower_impl_method,
    /// this uses the function name directly (already mangled) and the self type
    /// is the already-mangled type name.
    fn lower_generic_impl_method(
        &mut self,
        type_name: &Arc<str>,
        f: &ast::FnDef,
    ) -> CodegenResult<()> {
        // The function name is already the final mangled name (e.g., Option_i32_unwrap_or)
        let fn_name = f.name.name.clone();

        let mut params = Vec::new();
        for param in &f.sig.params {
            let is_self = matches!(&param.pattern.kind,
                ast::PatternKind::Ident { name, .. } if name.name.as_ref() == "self"
            );
            if is_self {
                if matches!(param.ty.kind, ast::TypeKind::Ref { .. }) {
                    params.push(MirType::Ptr(Box::new(MirType::Struct(type_name.clone()))));
                } else {
                    params.push(MirType::Struct(type_name.clone()));
                }
            } else {
                params.push(self.lower_type_from_ast(&param.ty));
            }
        }

        let ret = f
            .sig
            .return_ty
            .as_ref()
            .map(|t| self.lower_type_from_ast(t))
            .unwrap_or(MirType::Void);

        let sig = MirFnSig::new(params, ret);

        if let Some(body) = &f.body {
            // Save enclosing function context for nested definitions.
            let saved_fn = self.current_fn.take();
            let saved_vars = std::mem::take(&mut self.var_map);
            let saved_chars = std::mem::take(&mut self.char_locals);
            let saved_refs = std::mem::take(&mut self.ref_locals);
            let saved_str_refs = std::mem::take(&mut self.str_ref_locals);
            let saved_char_vecs = std::mem::take(&mut self.char_vec_locals);
            let saved_pending_vecs = std::mem::take(&mut self.pending_untyped_vecs);

            let mut builder = MirBuilder::with_linear_type_names(
                fn_name.clone(),
                sig,
                Arc::new(self.linear_type_names.clone()),
            );

            for (i, param) in f.sig.params.iter().enumerate() {
                if let ast::PatternKind::Ident { name, .. } = &param.pattern.kind {
                    let local_id = builder.param_local(i);
                    builder.set_param_name(i, name.name.clone());
                    self.var_map.insert(name.name.clone(), local_id);
                    self.record_result_param(local_id, &param.ty);
                    if matches!(param.ty.kind, ast::TypeKind::Ref { .. }) {
                        self.ref_locals.insert(local_id);
                    }
                    if Self::ast_type_is_str_ref(&param.ty) {
                        self.str_ref_locals.insert(local_id);
                    }
                    if Self::ast_type_is_char(&param.ty) {
                        self.char_locals.insert(local_id);
                    } else if Self::ast_type_is_char_vec(&param.ty) {
                        self.char_vec_locals.insert(local_id);
                    }
                }
            }

            self.current_fn = Some(builder);
            let result = self.lower_fn_body(body)?;

            let mut builder = self.current_fn.take().unwrap();
            let returns_value = f
                .sig
                .return_ty
                .as_ref()
                .is_some_and(|t| !matches!(self.lower_type_from_ast(t), MirType::Void));
            if returns_value && matches!(result, Some(MirValue::Const(MirConst::Unit))) {
                // The body ends in a statement with no value (see `lower_function`).
                builder.abort();
            } else if f.sig.return_ty.is_some() {
                if let Some(val) = result {
                    builder.ret(Some(val));
                }
            } else {
                builder.ret_void();
            }

            let mut func = builder.build();
            func.is_public = true;
            self.module.add_function(func);

            // Restore enclosing function context.
            self.current_fn = saved_fn;
            self.var_map = saved_vars;
            self.char_locals = saved_chars;
            self.ref_locals = saved_refs;
            self.str_ref_locals = saved_str_refs;
            self.char_vec_locals = saved_char_vecs;
            self.pending_untyped_vecs = saved_pending_vecs;
        }

        Ok(())
    }

    /// Generate methods from #[derive(...)] attributes on a struct.
    fn generate_derive_methods(
        &mut self,
        name: &ast::Ident,
        _attrs: &[ast::Attribute],
    ) -> CodegenResult<()> {
        let type_name = name.name.clone();
        let clone_key = (type_name.clone(), Arc::from("clone"));

        // Only generate if the clone method was registered during collection
        if self.impl_methods.contains_key(&clone_key) {
            let fn_name = self.impl_methods.get(&clone_key).unwrap().clone();

            // Skip if already generated
            if self.monomorphized.contains(&fn_name) {
                return Ok(());
            }
            self.monomorphized.insert(fn_name.clone());

            // Generate: fn TypeName_clone(self: TypeName) -> TypeName { return self; }
            let struct_ty = MirType::Struct(type_name.clone());
            let sig = MirFnSig::new(vec![struct_ty.clone()], struct_ty.clone());
            let mut builder = MirBuilder::with_linear_type_names(
                fn_name,
                sig,
                Arc::new(self.linear_type_names.clone()),
            );

            let self_local = builder.param_local(0);
            builder.set_param_name(0, Arc::from("self"));
            builder.ret(Some(values::local(self_local)));

            let mut func = builder.build();
            func.is_public = true;
            self.module.add_function(func);
        }

        Ok(())
    }

    fn lower_static(&mut self, s: &ast::StaticDef) -> CodegenResult<()> {
        let ty = self.lower_type_from_ast(&s.ty);
        if Self::ast_type_is_char(&s.ty) {
            self.char_globals.insert(s.name.name.clone());
        }
        // `&str` with a literal: the global holds the string itself.
        let ty = match (
            &ty,
            s.value
                .as_ref()
                .and_then(|e| global_init::string_literal(e)),
        ) {
            (MirType::Ptr(inner), Some(_)) if matches!(inner.as_ref(), MirType::Struct(n) if n.as_ref() == "BuildString") =>
            {
                self.str_ref_globals.insert(s.name.name.clone());
                (**inner).clone()
            }
            _ => ty,
        };
        let init = match s.value.as_ref() {
            Some(e) => self.global_initializer(&s.name.name, e, &ty)?,
            None => None,
        };

        let mut global = MirGlobal::new(s.name.name.clone(), ty);
        global.init = init;
        global.is_mut = s.mutability.is_mut();

        self.module.add_global(global);
        Ok(())
    }

    fn lower_const(&mut self, c: &ast::ConstDef) -> CodegenResult<()> {
        let ty = self.lower_type_from_ast(&c.ty);
        if Self::ast_type_is_char(&c.ty) {
            self.char_globals.insert(c.name.name.clone());
        }
        // `&str` with a literal: the global holds the string itself.
        let ty = match (
            &ty,
            c.value
                .as_ref()
                .and_then(|e| global_init::string_literal(e)),
        ) {
            (MirType::Ptr(inner), Some(_)) if matches!(inner.as_ref(), MirType::Struct(n) if n.as_ref() == "BuildString") =>
            {
                self.str_ref_globals.insert(c.name.name.clone());
                (**inner).clone()
            }
            _ => ty,
        };
        let init = match c.value.as_ref() {
            Some(e) => self.global_initializer(&c.name.name, e, &ty)?,
            None => None,
        };

        let mut global = MirGlobal::new(c.name.name.clone(), ty);
        global.init = init;
        global.is_mut = false;

        self.module.add_global(global);
        Ok(())
    }

    // =========================================================================
    // TYPE INFERENCE HELPERS
    // =========================================================================

    /// Infer the MIR type of a value based on its representation.
    /// When the AST does not carry resolved type annotations into the lowering
    /// phase, we derive a best-effort type from the value itself.
    fn type_of_value(&self, val: &MirValue) -> MirType {
        match val {
            MirValue::Const(c) => match c {
                MirConst::Bool(_) => MirType::Bool,
                MirConst::Int(_, ty) => ty.clone(),
                MirConst::Uint(_, ty) => ty.clone(),
                MirConst::Float(_, ty) => ty.clone(),
                MirConst::Str(_) => MirType::Ptr(Box::new(MirType::i8())),
                MirConst::ByteStr(_) => MirType::Ptr(Box::new(MirType::u8())),
                MirConst::Null(ty) => MirType::Ptr(Box::new(ty.clone())),
                MirConst::Unit => MirType::Void,
                MirConst::Zeroed(ty) => ty.clone(),
                MirConst::Undef(ty) => ty.clone(),
                MirConst::Struct(name, _) => MirType::Struct(name.clone()),
                MirConst::Array(elem, vals) => {
                    MirType::Array(Box::new(elem.clone()), vals.len() as u64)
                }
            },
            MirValue::Local(id) => {
                // Look up the local's declared type in the current function builder
                if let Some(ref builder) = self.current_fn {
                    if let Some(local) = builder.local_type(*id) {
                        return local;
                    }
                }
                MirType::i32()
            }
            MirValue::Global(name) => {
                // Look up the global's type from the module
                if let Some(global) = self.module.find_global(name) {
                    global.ty.clone()
                } else if let Some(ty) = limits::c_limit_type(name) {
                    ty
                } else {
                    MirType::i32()
                }
            }
            MirValue::Function(_) => MirType::i32(),
        }
    }

    /// Determine the result type of a binary operation given its operator and
    /// left operand type.  Comparisons always produce Bool; arithmetic and
    /// bitwise ops propagate the operand type.
    fn binary_result_type(&self, op: BinOp, left_val: &MirValue, right_val: &MirValue) -> MirType {
        match op {
            BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => MirType::Bool,
            // A bare integer literal is lowered with a default signedness (signed
            // `i32`) that need not match a same-width variable operand. Take the
            // result-temp type from a NON-CONSTANT operand when the left side is
            // the constant, so `100 - z` (`z: u32`) produces a `u32` temp: were the
            // literal's `i32` used, storing that temp back into a `u32` destination
            // (`z = 100 - z`) would be a type mismatch the strict SPIR-V backend
            // rejects. This mirrors the SPIR-V backend's operand-type derivation so
            // the temp's declared type and the emitted op's result type agree.
            _ => {
                if matches!(left_val, MirValue::Const(_))
                    && !matches!(right_val, MirValue::Const(_))
                {
                    self.type_of_value(right_val)
                } else {
                    self.type_of_value(left_val)
                }
            }
        }
    }

    /// Look up a struct field type by struct name and field name.
    fn lookup_struct_field_type(&self, struct_name: &str, field_name: &str) -> Option<MirType> {
        if let Some(type_def) = self.module.find_type(struct_name) {
            if let TypeDefKind::Struct { fields, .. } = &type_def.kind {
                for (fname, fty) in fields {
                    if let Some(name) = fname {
                        if name.as_ref() == field_name {
                            return Some(fty.clone());
                        }
                    }
                }
            }
        }
        // A struct-like enum variant (`Has { item: Coin }`) is NOT registered as
        // a `Struct` type; its name is the synthetic variant struct name. Fall
        // back to searching every enum's variants for a variant whose name is
        // `struct_name`, returning its matching field type. This is what lets a
        // record-pattern bind through a `match` on a struct-like enum variant
        // recover the true (possibly `#[linear]`) field type instead of the
        // `i32` default — required for the MIR linear checker to see the field
        // extract as a move of a linear payload out of a shared borrow.
        self.module.find_variant_field_type(struct_name, field_name)
    }

    /// Look up a struct field's ordinal index (0-based declaration order) by
    /// name. Index-based backends (LLVM GEP, Rust positional) use this in a
    /// place projection; the C backend renders by name.
    fn lookup_struct_field_index(&self, struct_name: &str, field_name: &str) -> Option<u32> {
        if let Some(type_def) = self.module.find_type(struct_name) {
            if let TypeDefKind::Struct { fields, .. } = &type_def.kind {
                for (i, (fname, _)) in fields.iter().enumerate() {
                    if let Some(name) = fname {
                        if name.as_ref() == field_name {
                            return Some(i as u32);
                        }
                    }
                }
            }
        }
        None
    }

    /// Look up an enum variant by enum name and variant name.
    /// Returns (discriminant, variant_fields) if found.
    fn lookup_enum_variant(
        &self,
        enum_name: &str,
        variant_name: &str,
    ) -> Option<(i128, Vec<(Option<Arc<str>>, MirType)>)> {
        if let Some(type_def) = self.module.find_type(enum_name) {
            if let TypeDefKind::Enum { variants, .. } = &type_def.kind {
                for v in variants {
                    if v.name.as_ref() == variant_name {
                        return Some((v.discriminant, v.fields.clone()));
                    }
                }
            }
        }
        None
    }

    /// Check if a name refers to a known enum type.
    fn is_enum_type(&self, name: &str) -> bool {
        if let Some(type_def) = self.module.find_type(name) {
            matches!(type_def.kind, TypeDefKind::Enum { .. })
        } else {
            false
        }
    }

    /// Find the most recently monomorphized specialization of a generic enum.
    /// E.g., if "Option" has been monomorphized as "Option_T_i32", return that.
    fn find_monomorphized_enum(&self, base_name: &str) -> Option<Arc<str>> {
        let prefix = format!("{}_", base_name);
        // Search only registered enum types, not all monomorphized names
        // (which also includes functions like Option_i32_unwrap_or)
        self.monomorphized
            .iter()
            .find(|name| name.starts_with(&prefix) && self.is_enum_type(name))
            .cloned()
    }
}

/// Determine item visibility.  The AST currently does not carry a
/// visibility modifier on the Ident node, so all items are assumed
/// public.  When the parser / AST is extended with `pub` tracking,
/// this function should inspect the actual modifier.
fn item_visibility(_name: &ast::Ident) -> Option<bool> {
    Some(true)
}