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
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
// ===============================================================================
// BUILDLANG TYPE SYSTEM - TYPE CHECKER
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================

//! Type checker for items (functions, structs, enums, traits, impls).
//!
//! This module handles type checking at the item level, while `infer.rs`
//! handles expression-level type inference.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;

use crate::ast::{self, ImplItemKind, ItemKind, StructFields, TraitItemKind};
use crate::lexer::{SourceId, Span};

/// How the checker finds the standard library directory (set once by
/// `buildc`, which can write the embedded copy to disk).
static STDLIB_DIR_FINDER: std::sync::OnceLock<fn() -> Option<PathBuf>> = std::sync::OnceLock::new();

/// Tell the checker where `mod NAME;` finds a standard library module.
pub fn set_stdlib_dir_finder(finder: fn() -> Option<PathBuf>) {
    let _ = STDLIB_DIR_FINDER.set(finder);
}

use super::context::*;
use super::error::*;
use super::infer::{TypeInfer, WellKnownTypes};
use super::ty::*;

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FunctionEffectSummary {
    pub function: String,
    pub declared_effects: Vec<String>,
    pub observed_capabilities: BTreeMap<String, BTreeSet<String>>,
    pub propagated_effects: BTreeMap<String, BTreeSet<String>>,
}

/// The type checker for items and declarations.
pub struct TypeChecker<'ctx> {
    /// The type context.
    ctx: &'ctx mut TypeContext,
    /// Collected errors.
    errors: Vec<TypeErrorWithSpan>,
    /// Effect context for tracking registered effects.
    effect_ctx: super::effects::EffectContext,
    /// Source directory for resolving external module files.
    source_dir: Option<std::path::PathBuf>,
    /// Canonicalized paths of `mod foo;` files currently on the load stack.
    /// A file that is already being loaded must not be loaded again, or a
    /// `mod NAME;` chain that comes back to itself would recurse until the
    /// stack overflows. Fail closed: a repeated path is a cycle diagnostic,
    /// not a crash. Paths are removed after their subtree finishes so a
    /// diamond (two siblings importing the same leaf) is not a false cycle.
    loading_modules: HashSet<PathBuf>,
    /// Cache of `use` module path (`a::b::c`) -> the set of top-level item
    /// names that module file exports (`None` when no backing file was found or
    /// it failed to parse). Reading a module's export names is read-only: it
    /// never mutates the type context, so binding an imported leaf as an opaque
    /// value can never perturb the consumer's own types the way collecting the
    /// module's items would. The cache keeps each module parsed at most once.
    use_module_exports: HashMap<Arc<str>, Option<HashSet<Arc<str>>>>,
    /// Source text for span-backed token evidence during inference.
    source_text: Option<Arc<str>>,
    /// Source ID associated with `source_text`.
    source_id: Option<SourceId>,
    /// Per-function declared/observed effect evidence for receipts.
    function_effect_summaries: Vec<FunctionEffectSummary>,
}

impl<'ctx> TypeChecker<'ctx> {
    /// Create a new type checker.
    pub fn new(ctx: &'ctx mut TypeContext) -> Self {
        Self {
            ctx,
            errors: Vec::new(),
            effect_ctx: super::effects::EffectContext::new(),
            source_dir: None,
            loading_modules: HashSet::new(),
            use_module_exports: HashMap::new(),
            source_text: None,
            source_id: None,
            function_effect_summaries: Vec::new(),
        }
    }

    /// Set the source directory for resolving `mod foo;` declarations.
    pub fn set_source_dir(&mut self, dir: std::path::PathBuf) {
        self.source_dir = Some(dir);
    }

    /// Set source text for span-backed token evidence.
    pub fn set_source_text(&mut self, source_text: impl Into<Arc<str>>) {
        self.source_text = Some(source_text.into());
        self.source_id = None;
    }

    /// Set source file data for span-backed token evidence.
    pub fn set_source_file(&mut self, source_file: &crate::lexer::SourceFile) {
        self.source_text = Some(source_file.source.clone());
        self.source_id = Some(source_file.id);
    }

    /// Get a reference to the effect context.
    pub fn effect_ctx(&self) -> &super::effects::EffectContext {
        &self.effect_ctx
    }

    /// Get collected errors.
    pub fn errors(&self) -> &[TypeErrorWithSpan] {
        &self.errors
    }

    /// Get per-function effect summaries collected during the latest module check.
    pub fn function_effect_summaries(&self) -> &[FunctionEffectSummary] {
        &self.function_effect_summaries
    }

    /// Take collected errors.
    pub fn take_errors(&mut self) -> Vec<TypeErrorWithSpan> {
        std::mem::take(&mut self.errors)
    }

    /// Check if there are any errors.
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Report an error.
    fn error(&mut self, error: TypeError, span: Span) {
        self.errors.push(TypeErrorWithSpan::new(error, span));
    }

    // =========================================================================
    // MODULE CHECKING
    // =========================================================================

    /// Check a module.
    pub fn check_module(&mut self, module: &ast::Module) {
        self.function_effect_summaries.clear();

        // `#[measured(source = "...")]` constants must name their source.
        if let Some(source) = self.source_text.clone() {
            for err in super::measured::collect(module, &source).1 {
                self.errors.push(TypeErrorWithSpan::new(
                    TypeError::MeasuredConstantInvalid {
                        name: err.name,
                        reason: err.reason,
                    },
                    err.span,
                ));
            }
        }

        // Register built-in vector/matrix struct types so that type annotations
        // like `vec3` resolve to known struct types with accessible fields.
        self.register_builtin_vec_types();

        // Register generic Option<T> before function signatures are collected,
        // so checked integer methods and explicit `-> Option<T>` annotations
        // share a real well-known ADT instead of a fresh inference variable.
        self.register_builtin_option_type();

        // Register prelude constructors (Ok, Err, Some, None) as variables
        // with fresh type variables so they pass type checking.
        self.ctx.define_var(Arc::from("Ok"), Ty::fresh_var());
        self.ctx.define_var(Arc::from("Err"), Ty::fresh_var());
        self.ctx.define_var(Arc::from("Some"), Ty::fresh_var());
        self.ctx.define_var(Arc::from("None"), Ty::fresh_var());

        // Register shader built-in functions as variables
        self.ctx.define_var(Arc::from("saturate"), Ty::fresh_var());
        self.ctx.define_var(Arc::from("discard"), Ty::fresh_var());

        // Register runtime built-in functions
        self.ctx.define_var(
            Arc::from("assert"),
            Ty::function(vec![Ty::bool()], Ty::unit()),
        );
        self.ctx.define_var(Arc::from("assert_eq"), Ty::fresh_var());
        self.ctx.define_var(Arc::from("println"), Ty::fresh_var());

        // First pass: collect all type definitions
        for item in &module.items {
            self.collect_item(item);
        }

        // Linear containment: a non-`#[linear]` aggregate may not hold a linear
        // field (it would launder the resource past no-cloning). Runs after all
        // types are collected so every field type's linearity is known.
        self.validate_linear_containment(module);

        // A struct or enum that holds itself by value has no finite size
        // (issue #83); without this the C compiler failed after a clean check.
        self.errors
            .extend(super::recursive::infinite_size_errors(module));

        // Two constants or statics of one name (G29); the C compiler used to
        // be the one to report it.
        self.errors
            .extend(super::duplicates::duplicate_value_errors(
                module,
                self.source_text.as_deref(),
            ));

        // Register built-in trait stubs AFTER user types so DefIds are consistent
        self.ctx.register_builtin_traits();

        // Second pass: type check all items
        for item in &module.items {
            self.check_item(item);
        }

        // M5: a `par_for` / `par_map` body must have an empty effect row and
        // no way to write shared state.
        self.errors
            .extend(super::parallel::parallel_body_errors(module));
    }

    /// Register built-in vector and matrix struct types (vec2, vec3, vec4, mat4)
    /// so that type annotations resolve correctly and field access works.
    fn register_builtin_vec_types(&mut self) {
        let f64_ty = Ty::float(FloatTy::F64);

        // vec2 { x: f64, y: f64 }
        let def_id = self.ctx.fresh_def_id();
        self.ctx.register_type(TypeDef {
            def_id,
            name: Arc::from("vec2"),
            generics: Vec::new(),
            kind: TypeDefKind::Struct(StructDef {
                fields: vec![
                    (Arc::from("x"), f64_ty.clone()),
                    (Arc::from("y"), f64_ty.clone()),
                ],
                is_tuple: false,
            }),
        });

        // vec3 { x: f64, y: f64, z: f64 }
        let def_id = self.ctx.fresh_def_id();
        self.ctx.register_type(TypeDef {
            def_id,
            name: Arc::from("vec3"),
            generics: Vec::new(),
            kind: TypeDefKind::Struct(StructDef {
                fields: vec![
                    (Arc::from("x"), f64_ty.clone()),
                    (Arc::from("y"), f64_ty.clone()),
                    (Arc::from("z"), f64_ty.clone()),
                ],
                is_tuple: false,
            }),
        });

        // vec4 { x: f64, y: f64, z: f64, w: f64 }
        let def_id = self.ctx.fresh_def_id();
        self.ctx.register_type(TypeDef {
            def_id,
            name: Arc::from("vec4"),
            generics: Vec::new(),
            kind: TypeDefKind::Struct(StructDef {
                fields: vec![
                    (Arc::from("x"), f64_ty.clone()),
                    (Arc::from("y"), f64_ty.clone()),
                    (Arc::from("z"), f64_ty.clone()),
                    (Arc::from("w"), f64_ty.clone()),
                ],
                is_tuple: false,
            }),
        });

        // mat4 - registered as opaque (no user-accessible fields)
        let def_id = self.ctx.fresh_def_id();
        self.ctx.register_type(TypeDef {
            def_id,
            name: Arc::from("mat4"),
            generics: Vec::new(),
            kind: TypeDefKind::Struct(StructDef {
                fields: Vec::new(),
                is_tuple: false,
            }),
        });

        // uvec3 { x: u32, y: u32, z: u32 } - the type of GPU compute built-in
        // thread-index variables (`gl_GlobalInvocationID`, etc.). Components are
        // unsigned 32-bit so `gl_GlobalInvocationID.x` yields a usable index.
        let u32_ty = Ty::int(IntTy::U32);
        let def_id = self.ctx.fresh_def_id();
        self.ctx.register_type(TypeDef {
            def_id,
            name: Arc::from("uvec3"),
            generics: Vec::new(),
            kind: TypeDefKind::Struct(StructDef {
                fields: vec![
                    (Arc::from("x"), u32_ty.clone()),
                    (Arc::from("y"), u32_ty.clone()),
                    (Arc::from("z"), u32_ty.clone()),
                ],
                is_tuple: false,
            }),
        });
    }

    fn register_builtin_option_type(&mut self) {
        if self.ctx.lookup_type_by_name("Option").is_some() {
            return;
        }

        let def_id = self.ctx.fresh_def_id();
        let t_name: Arc<str> = Arc::from("T");
        let t_ty = Ty::param(t_name.clone(), 0);
        self.ctx.register_type(TypeDef {
            def_id,
            name: Arc::from("Option"),
            generics: vec![GenericParam {
                name: t_name,
                index: 0,
                kind: GenericParamKind::Type { bounds: Vec::new() },
            }],
            kind: TypeDefKind::Enum(EnumDef {
                variants: vec![
                    EnumVariant {
                        name: Arc::from("Some"),
                        fields: vec![(None, t_ty)],
                        discriminant: Some(0),
                    },
                    EnumVariant {
                        name: Arc::from("None"),
                        fields: Vec::new(),
                        discriminant: Some(1),
                    },
                ],
            }),
        });
    }

    fn well_known_types_from_ctx(ctx: &TypeContext) -> WellKnownTypes {
        WellKnownTypes {
            range: ctx.lookup_type_by_name("Range").map(|ty| ty.def_id),
            range_inclusive: ctx
                .lookup_type_by_name("RangeInclusive")
                .map(|ty| ty.def_id),
            range_full: ctx.lookup_type_by_name("RangeFull").map(|ty| ty.def_id),
            range_from: ctx.lookup_type_by_name("RangeFrom").map(|ty| ty.def_id),
            range_to: ctx.lookup_type_by_name("RangeTo").map(|ty| ty.def_id),
            option: ctx.lookup_type_by_name("Option").map(|ty| ty.def_id),
            result: ctx.lookup_type_by_name("Result").map(|ty| ty.def_id),
        }
    }

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

    /// Collect type definitions from an item (first pass).
    fn collect_item(&mut self, item: &ast::Item) {
        match &item.kind {
            ItemKind::Struct(s) => {
                self.collect_struct(s, item.span, Self::has_linear_attr(&item.attrs))
            }
            ItemKind::Enum(e) => {
                self.collect_enum(e, item.span, Self::has_linear_attr(&item.attrs))
            }
            ItemKind::TypeAlias(ta) => self.collect_type_alias(ta, item.span),
            ItemKind::Trait(t) => self.collect_trait(t, item.span),
            ItemKind::Function(f) => self.collect_function(f, item.span),
            ItemKind::Effect(e) => self.collect_effect(e, item.span),
            ItemKind::ExternBlock(eb) => self.collect_extern_block(eb, item.span),
            ItemKind::Impl(impl_) => self.collect_impl(impl_, item.span),
            ItemKind::Const(c) => {
                // Pre-register constants so forward references work
                let ty = self.lower_type(&c.ty);
                self.ctx.define_var(c.name.name.clone(), ty);
            }
            ItemKind::Static(s) => {
                // Pre-register statics so forward references work
                let ty = self.lower_type(&s.ty);
                self.ctx.define_var(s.name.name.clone(), ty);
            }
            ItemKind::Use(use_def) => self.resolve_use(&use_def.tree),
            ItemKind::Mod(m) => self.collect_mod(m),
            _ => {}
        }
    }

    /// The file a `mod NAME;` loads: `NAME.bld` beside the source, else the
    /// standard library's copy. The module merge in `buildc` searches the same
    /// two places; without the second, a module that called a standard library
    /// module (`json_quote` from `mod json;`) failed its separate check here
    /// with an undefined name, though the merged program resolved it.
    fn module_file(dir: &std::path::Path, name: &str) -> Option<PathBuf> {
        let local = dir.join(format!("{}.bld", name));
        if local.exists() {
            return Some(local);
        }
        let finder = STDLIB_DIR_FINDER.get()?;
        let std_file = finder()?.join(format!("{}.bld", name));
        std_file.exists().then_some(std_file)
    }

    /// Collect module items during the first pass.
    /// For inline modules, collect their items recursively.
    /// For external modules (`mod foo;`), load and parse the file.
    fn collect_mod(&mut self, m: &ast::ModDef) {
        if let Some(content) = &m.content {
            // Inline module: collect items directly
            for item in &content.items {
                self.collect_item(item);
            }
        } else if m.is_file_module {
            // File-level `module NAME` header: the rest of the file already IS
            // the body, so there is nothing to load. Loading `NAME.bld` here
            // would re-open the file that declared the header (its own stem)
            // and recurse until the stack overflows.
        } else if let Some(ref dir) = self.source_dir.clone() {
            // External submodule: `mod NAME;` loads NAME.bld from disk.
            let mod_name = m.name.name.as_ref();
            if let Some(mod_path) = Self::module_file(dir, mod_name) {
                let key = std::fs::canonicalize(&mod_path).unwrap_or_else(|_| mod_path.clone());
                if !self.loading_modules.insert(key.clone()) {
                    // Already on the load stack: a cycle. Fail closed with a
                    // diagnostic instead of recursing into a stack overflow.
                    self.error(
                        TypeError::ModuleImportCycle {
                            path: mod_path.display().to_string(),
                            module: mod_name.to_string(),
                        },
                        m.name.span,
                    );
                    return;
                }
                if let Ok(source_text) = std::fs::read_to_string(&mod_path) {
                    let source = crate::lexer::SourceFile::new(
                        mod_path.to_string_lossy().as_ref(),
                        source_text,
                    );
                    let mut lexer = crate::lexer::Lexer::new(&source);
                    if let Ok(tokens) = lexer.tokenize() {
                        let mut parser = crate::parser::Parser::new(&source, tokens);
                        if let Ok(module_ast) = parser.parse() {
                            for item in &module_ast.items {
                                self.collect_item(item);
                            }
                        }
                    }
                }
                self.loading_modules.remove(&key);
            }
        }
    }

    /// Collect inherent impl methods during the first pass so they're
    /// available for method resolution when function bodies are checked.
    fn collect_impl(&mut self, impl_: &ast::ImplDef, _span: Span) {
        // Only collect inherent impls (no trait). Trait impls are handled in check_impl.
        if impl_.trait_ref.is_some() {
            return;
        }

        // Push a scope for generic type parameters so they don't leak
        // into the surrounding module's type namespace.
        self.ctx.push_scope(ScopeKind::Block);
        for (idx, param) in impl_.generics.params.iter().enumerate() {
            if let ast::GenericParamKind::Type { .. } = &param.kind {
                let ty = Ty::param(param.ident.name.clone(), idx as u32);
                self.ctx.define_type_param(param.ident.name.clone(), ty);
            }
        }

        let _self_ty = self.lower_type(&impl_.self_ty);
        let type_name = Self::extract_type_name_from_ast(&impl_.self_ty);
        let type_def_id = type_name
            .as_ref()
            .and_then(|n| self.ctx.lookup_type_by_name(n).map(|td| td.def_id));

        for item in &impl_.items {
            match &item.kind {
                ImplItemKind::Function(f) => {
                    if let Some(def_id) = type_def_id {
                        let sig = self.build_fn_sig_from_ast(f);
                        self.ctx
                            .register_inherent_method(def_id, f.name.name.clone(), sig);
                    }
                }
                ImplItemKind::Const { name, ty, .. } => {
                    // Register associated constants at module scope so they're
                    // accessible from other impl blocks (e.g., BRADFORD in
                    // chromatic_adaptation.bld).
                    let const_ty = self.lower_type(ty);
                    self.ctx.define_var(name.name.clone(), const_ty);
                }
                _ => {}
            }
        }

        self.ctx.pop_scope();
    }

    /// Whether an item's attribute list contains the `#[linear]` marker.
    fn has_linear_attr(attrs: &[ast::Attribute]) -> bool {
        attrs.iter().any(|attr| {
            attr.path
                .segments
                .first()
                .map_or(false, |seg| seg.ident.name.as_ref() == "linear")
        })
    }

    /// Enforce the linear containment rule: a non-`#[linear]` struct or enum
    /// must not have a field whose type is `#[linear]`. Otherwise the linear
    /// value could be read out of the untracked aggregate repeatedly,
    /// laundering it past no-cloning.
    fn validate_linear_containment(&mut self, module: &ast::Module) {
        for item in &module.items {
            if Self::has_linear_attr(&item.attrs) {
                continue; // a linear aggregate is itself move-tracked
            }
            match &item.kind {
                ItemKind::Struct(s) => {
                    let container = s.name.name.to_string();
                    self.check_fields_not_linear(&container, &s.fields, item.span);
                }
                ItemKind::Enum(e) => {
                    let container = e.name.name.to_string();
                    for variant in &e.variants {
                        self.check_fields_not_linear(&container, &variant.fields, item.span);
                    }
                }
                _ => {}
            }
        }
    }

    /// Report any field of `fields` whose type resolves to a `#[linear]` type.
    fn check_fields_not_linear(&mut self, container: &str, fields: &ast::StructFields, span: Span) {
        let raw: Vec<(String, &ast::Type)> = match fields {
            StructFields::Named(fs) => fs
                .iter()
                .map(|f| (f.name.name.to_string(), f.ty.as_ref()))
                .collect(),
            StructFields::Tuple(fs) => fs
                .iter()
                .enumerate()
                .map(|(i, f)| (i.to_string(), f.ty.as_ref()))
                .collect(),
            StructFields::Unit => Vec::new(),
        };
        for (field_name, field_ty_ast) in raw {
            let ty = self.lower_type(field_ty_ast);
            if let TyKind::Adt(def_id, _) = &ty.kind {
                if self.ctx.is_linear_def(*def_id) {
                    let field_type = self
                        .ctx
                        .lookup_type(*def_id)
                        .map(|d| d.name.to_string())
                        .unwrap_or_else(|| "?".to_string());
                    self.errors.push(TypeErrorWithSpan::new(
                        TypeError::LinearFieldInNonLinearType {
                            container: container.to_string(),
                            field: field_name,
                            field_type,
                        },
                        span,
                    ));
                }
            }
        }
    }

    fn collect_struct(&mut self, s: &ast::StructDef, _span: Span, is_linear: bool) {
        let def_id = self.ctx.fresh_def_id();
        if is_linear {
            self.ctx.mark_linear(def_id);
        }

        let generics = self.collect_generics(&s.generics);
        let num_generics = generics.len();

        let fields = match &s.fields {
            StructFields::Named(fields) => fields
                .iter()
                .map(|f| {
                    let ty = self.lower_type(&f.ty);
                    (f.name.name.clone(), ty)
                })
                .collect(),
            StructFields::Tuple(fields) => fields
                .iter()
                .enumerate()
                .map(|(i, f)| {
                    let ty = self.lower_type(&f.ty);
                    (Arc::from(i.to_string()), ty)
                })
                .collect(),
            StructFields::Unit => Vec::new(),
        };

        let type_def = TypeDef {
            def_id,
            name: s.name.name.clone(),
            generics,
            kind: TypeDefKind::Struct(StructDef {
                fields,
                is_tuple: matches!(s.fields, StructFields::Tuple(_)),
            }),
        };

        self.ctx.register_type(type_def);

        // For tuple structs, register a constructor function so that
        // `TupleStruct(val)` works as a call expression.
        if matches!(&s.fields, StructFields::Tuple(_)) {
            if let StructFields::Tuple(fields) = &s.fields {
                let param_tys: Vec<Ty> = fields.iter().map(|f| self.lower_type(&f.ty)).collect();
                let substs: Vec<Ty> = (0..num_generics).map(|_| Ty::fresh_var()).collect();
                let ret_ty = Ty::adt(def_id, substs);
                let fn_ty = Ty::function(param_tys, ret_ty);
                self.ctx.define_var(s.name.name.clone(), fn_ty);
            }
        }

        // For unit structs (e.g., `struct Stdin;`), register the name as a
        // variable so it can be used as a value expression: `Stdin` or `let x = Stdin;`
        if matches!(&s.fields, StructFields::Unit) {
            let substs: Vec<Ty> = (0..num_generics).map(|_| Ty::fresh_var()).collect();
            let val_ty = Ty::adt(def_id, substs);
            self.ctx.define_var(s.name.name.clone(), val_ty);
        }
    }

    fn collect_enum(&mut self, e: &ast::EnumDef, _span: Span, is_linear: bool) {
        let def_id = self.ctx.fresh_def_id();
        if is_linear {
            self.ctx.mark_linear(def_id);
        }

        let generics = self.collect_generics(&e.generics);

        let variants = e
            .variants
            .iter()
            .map(|v| {
                let fields = match &v.fields {
                    StructFields::Named(fields) => fields
                        .iter()
                        .map(|f| (Some(f.name.name.clone()), self.lower_type(&f.ty)))
                        .collect(),
                    StructFields::Tuple(types) => types
                        .iter()
                        .map(|t| (None, self.lower_type(&t.ty)))
                        .collect(),
                    StructFields::Unit => Vec::new(),
                };

                EnumVariant {
                    name: v.name.name.clone(),
                    fields,
                    discriminant: v.discriminant.as_ref().and_then(|e| {
                        // Try to evaluate const expression
                        self.eval_const_int(e)
                    }),
                }
            })
            .collect();

        let type_def = TypeDef {
            def_id,
            name: e.name.name.clone(),
            generics,
            kind: TypeDefKind::Enum(EnumDef { variants }),
        };

        self.ctx.register_type(type_def);
    }

    fn collect_type_alias(&mut self, ta: &ast::TypeAliasDef, _span: Span) {
        let def_id = self.ctx.fresh_def_id();
        let generics = self.collect_generics(&ta.generics);

        if let Some(ty_ast) = &ta.ty {
            let ty = self.lower_type(ty_ast);
            let alias = TypeAlias {
                def_id,
                name: ta.name.name.clone(),
                generics,
                ty,
            };
            self.ctx.register_alias(alias);
        }
    }

    fn collect_trait(&mut self, t: &ast::TraitDef, _span: Span) {
        let def_id = self.ctx.fresh_def_id();
        let generics = self.collect_generics(&t.generics);

        let supertraits = t
            .supertraits
            .iter()
            .filter_map(|bound| self.lower_type_bound(bound))
            .collect();

        let assoc_types = t
            .items
            .iter()
            .filter_map(|item| {
                if let TraitItemKind::Type {
                    name,
                    bounds,
                    default,
                    ..
                } = &item.kind
                {
                    Some(AssocType {
                        name: name.name.clone(),
                        bounds: bounds
                            .iter()
                            .filter_map(|b| self.lower_type_bound(b))
                            .collect(),
                        default: default.as_ref().map(|t| self.lower_type(t)),
                    })
                } else {
                    None
                }
            })
            .collect();

        let methods = t
            .items
            .iter()
            .filter_map(|item| {
                if let TraitItemKind::Function(f) = &item.kind {
                    Some(TraitMethod {
                        name: f.name.name.clone(),
                        sig: self.lower_fn_sig(&f.generics, &f.sig),
                        has_default: f.body.is_some(),
                    })
                } else {
                    None
                }
            })
            .collect();

        let trait_def = TraitDef {
            def_id,
            name: t.name.name.clone(),
            generics,
            supertraits,
            assoc_types,
            methods,
        };

        self.ctx.register_trait(trait_def);
    }

    fn collect_function(&mut self, f: &ast::FnDef, _span: Span) {
        let def_id = self.ctx.fresh_def_id();
        // Lower the signature with the function's type parameters in scope, so
        // `T` becomes a type parameter that each reference instantiates afresh
        // (see `infer_ident`), not one inference variable every call shares.
        let has_type_params = f
            .generics
            .params
            .iter()
            .any(|p| matches!(p.kind, ast::GenericParamKind::Type { .. }));
        if has_type_params {
            self.ctx.push_scope(ScopeKind::Function);
            for (idx, param) in f.generics.params.iter().enumerate() {
                if let ast::GenericParamKind::Type { .. } = &param.kind {
                    let ty = Ty::param(param.ident.name.clone(), idx as u32);
                    self.ctx.define_type_param(param.ident.name.clone(), ty);
                }
            }
        }
        let sig = self.lower_fn_sig(&f.generics, &f.sig);
        if has_type_params {
            self.ctx.pop_scope();
        }
        self.ctx.register_function(def_id, sig.clone());

        // Add function to current scope - carry lifetime params for interprocedural analysis
        let param_tys: Vec<_> = sig.params.iter().map(|(_, ty)| ty.clone()).collect();
        let effects = self.lower_effect_annotations(&f.sig.effects);
        let fn_ty = Ty::function_with_effects_and_lifetimes(
            param_tys.clone(),
            sig.ret.clone(),
            effects,
            sig.lifetime_params.clone(),
        );

        // Multiple dispatch: append this definition to the name's candidate set.
        // The FIRST definition of a name is also bound as a plain variable so a
        // bare value reference (fn pointer) still resolves and the single-def
        // fast path in `infer_call` is byte-for-byte identical to before.
        // Subsequent same-name definitions do NOT overwrite that binding (which
        // is what silently clobbered overloads previously); they only extend the
        // candidate set, and the call site resolves by the argument-type tuple.
        let is_first = self.ctx.method_candidates(f.name.name.as_ref()).is_none();
        self.ctx.register_method_candidate(
            f.name.name.clone(),
            MethodCandidate {
                def_id,
                param_tys,
                ret: sig.ret.clone(),
                sig,
            },
        );
        if is_first {
            if has_type_params {
                self.ctx
                    .register_generic_function(f.name.name.clone(), fn_ty.clone());
            }
            self.ctx.define_var(f.name.name.clone(), fn_ty);
        }
    }

    /// Collect extern block declarations. Foreign functions and statics are
    /// registered in the type context so access can be type-checked.
    fn collect_extern_block(&mut self, eb: &ast::ExternBlockDef, _span: Span) {
        for foreign_item in &eb.items {
            match &foreign_item.kind {
                ast::ForeignItemKind::Fn(f) => {
                    let def_id = self.ctx.fresh_def_id();
                    let sig = self.lower_fn_sig(&f.generics, &f.sig);
                    self.ctx.register_function(def_id, sig.clone());

                    let param_tys: Vec<_> = sig.params.iter().map(|(_, ty)| ty.clone()).collect();
                    let effect_name =
                        super::capabilities::capability_effect_for_call(f.name.name.as_ref())
                            .unwrap_or(super::capabilities::FOREIGN);
                    let effects = super::effects::EffectRow::closed([super::effects::Effect::new(
                        effect_name,
                    )]);
                    let fn_ty = Ty::function_with_effects_and_lifetimes(
                        param_tys,
                        sig.ret.clone(),
                        effects,
                        sig.lifetime_params.clone(),
                    )
                    .with_variadic(f.sig.is_variadic);
                    self.ctx.define_var(f.name.name.clone(), fn_ty);
                    self.ctx.register_foreign_function(f.name.name.clone());
                }
                ast::ForeignItemKind::Static { name, ty, .. } => {
                    let static_ty = self.lower_type(ty);
                    self.ctx.define_var(name.name.clone(), static_ty);
                    self.ctx.register_foreign_static(name.name.clone());
                }
                _ => {}
            }
        }
    }

    /// Collect a user-defined effect declaration and register it in the effect context.
    fn collect_effect(&mut self, effect_def: &ast::EffectDef, _span: Span) {
        let def_id = self.ctx.fresh_def_id();

        // Build the types::effects::EffectDef from the AST node
        let mut ty_effect = super::effects::EffectDef::new(def_id, effect_def.name.name.as_ref());

        // Add generic type parameters
        for param in &effect_def.generics.params {
            if let ast::GenericParamKind::Type { .. } = &param.kind {
                ty_effect = ty_effect.with_type_param(param.ident.name.as_ref());
            }
        }

        // Convert each AST operation into a types::effects::EffectOperation
        for op in &effect_def.operations {
            let param_tys: Vec<Ty> = op.params.iter().map(|p| self.lower_type(&p.ty)).collect();

            let return_ty = op
                .return_ty
                .as_ref()
                .map(|t| self.lower_type(t))
                .unwrap_or(Ty::unit());

            let effect_op =
                super::effects::EffectOperation::new(op.name.name.as_ref(), param_tys, return_ty);

            ty_effect = ty_effect.with_operation(effect_op);
        }

        self.effect_ctx.register_effect(ty_effect);
    }

    // =========================================================================
    // TYPE CHECKING PASS
    // =========================================================================

    /// Check an item (second pass).
    fn check_item(&mut self, item: &ast::Item) {
        match &item.kind {
            ItemKind::Function(f) => self.check_function(f, item.span),
            ItemKind::Impl(impl_) => self.check_impl(impl_, item.span),
            ItemKind::Const(c) => self.check_const(c, item.span),
            ItemKind::Static(s) => self.check_static(s, item.span),
            ItemKind::Mod(m) => self.check_mod(m),
            _ => {}
        }
    }

    /// Register the trait bounds declared by a set of generics (both inline
    /// `<T: Trait>` bounds and `where T: Trait` predicates) so that method
    /// resolution can find trait methods on those type parameters. Bounds
    /// accumulate onto whatever is already registered (see
    /// `TypeContext::register_param_bounds`), so an enclosing impl's bounds and
    /// a method's own bounds compose rather than clobber each other.
    fn register_generic_param_bounds(&mut self, generics: &ast::Generics) {
        for param in &generics.params {
            if let ast::GenericParamKind::Type { ref bounds, .. } = &param.kind {
                if !bounds.is_empty() {
                    let trait_names = Self::bound_trait_names(bounds);
                    if !trait_names.is_empty() {
                        self.ctx
                            .register_param_bounds(param.ident.name.clone(), trait_names);
                    }
                }
            }
        }

        for pred in generics.where_clause.iter().flat_map(|wc| &wc.predicates) {
            if let ast::TypeKind::Path(ref path) = pred.ty.kind {
                if let Some(seg) = path.segments.last() {
                    let trait_names = Self::bound_trait_names(&pred.bounds);
                    if !trait_names.is_empty() {
                        self.ctx
                            .register_param_bounds(seg.ident.name.clone(), trait_names);
                    }
                }
            }
        }
    }

    /// Extract the trait names from a list of bounds, dropping `?Sized`-style
    /// maybe bounds (the last path segment is used as the trait's name).
    fn bound_trait_names(bounds: &[ast::TypeBound]) -> Vec<Arc<str>> {
        bounds
            .iter()
            .filter(|b| !b.is_maybe)
            .map(|b| {
                Arc::from(
                    b.path
                        .segments
                        .last()
                        .map(|s| s.ident.name.as_ref())
                        .unwrap_or(""),
                )
            })
            .collect()
    }

    fn check_function(&mut self, f: &ast::FnDef, span: Span) {
        if let Some(body) = &f.body {
            // Generic functions are checked per-instantiation at
            // monomorphization; the abstract body cannot resolve
            // type-parameter method calls or closure-param returns.
            let is_generic = f
                .generics
                .params
                .iter()
                .any(|p| matches!(p.kind, ast::GenericParamKind::Type { .. }));
            self.ctx.push_scope(ScopeKind::Function);

            // Layer this function's own type-parameter bounds on top of any
            // bounds already in scope (e.g. from an enclosing `impl<T: Bound>`),
            // and restore the prior set when the function is done so sibling
            // items are not affected. Without preserving the enclosing bounds, a
            // trait-impl method body could not resolve trait methods on the
            // impl's type parameters (e.g. `self[i].cmp(..)` in `impl<T: Ord>
            // Ord for [T]`).
            let saved_param_bounds = self.ctx.param_bounds_snapshot();

            // Add generic parameters and register their trait bounds.
            for (idx, param) in f.generics.params.iter().enumerate() {
                if let ast::GenericParamKind::Type { .. } = &param.kind {
                    let ty = Ty::param(param.ident.name.clone(), idx as u32);
                    self.ctx.define_type_param(param.ident.name.clone(), ty);
                }
            }
            self.register_generic_param_bounds(&f.generics);

            // Add function parameters. Capture linear-typed Ident params so we
            // can hand them to the body inferer for no-cloning tracking (the
            // inferer is created fresh below and does not see these bindings).
            let mut param_bindings: Vec<(String, Ty)> = Vec::new();
            for param in &f.sig.params {
                let ty = self.lower_type(&param.ty);
                self.bind_pattern(&param.pattern, &ty);
                if let ast::PatternKind::Ident { name, .. } = &param.pattern.kind {
                    param_bindings.push((name.name.as_ref().to_string(), ty));
                }
            }

            // Set expected return type FIRST, before creating TypeInfer
            let expected_ret = f
                .sig
                .return_ty
                .as_ref()
                .map(|t| self.lower_type(t))
                .unwrap_or(Ty::unit());

            // Build expected effect row from function signature annotations
            let expected_effects = self.lower_effect_annotations(&f.sig.effects);

            // Validate that each annotated effect is a known/registered effect
            for eff in &expected_effects.effects {
                if self.effect_ctx.get_effect(eff.name.as_ref()).is_none() {
                    let err = TypeError::UnknownEffect {
                        name: eff.name.to_string(),
                    };
                    let mut err_with_span = TypeErrorWithSpan::new(err, span);
                    err_with_span.help = Some(format!(
                        "define the effect:\n  effect {} {{\n      fn operation_name(params) -> ReturnType,\n  }}",
                        eff.name
                    ));
                    self.errors.push(err_with_span);
                }
            }

            // Collect user-defined effects to pass to the inference context
            let user_effects: Vec<_> = self.effect_ctx.all_effects().into_iter().cloned().collect();

            // Check function body - use block to limit TypeInfer borrow scope
            let (
                body_ty,
                body_effects,
                capability_sources,
                propagated_effect_sources,
                infer_errors,
                has_return,
            ) = {
                let well_known_types = Self::well_known_types_from_ctx(self.ctx);
                let mut infer = if let Some(source_text) = &self.source_text {
                    TypeInfer::with_source_text(self.ctx, source_text.clone(), self.source_id)
                } else {
                    TypeInfer::new(self.ctx)
                };
                infer.set_well_known_types(well_known_types);
                // Pass the expected return type so that `return` statements
                // inside nested control flow (while/if/match) are properly
                // type-checked against the function signature.
                infer.set_return_ty(expected_ret.clone());
                infer.set_unsafe_body(f.sig.is_unsafe);
                // Hand linear-typed parameters to the inferer so consuming a
                // linear parameter more than once is rejected (no-cloning).
                for (name, ty) in &param_bindings {
                    infer.register_linear_param(name, ty);
                }
                // Register all user-defined effects so infer_perform can resolve them
                for eff in user_effects {
                    infer.register_effect(eff);
                }
                let body_ty = infer.infer_block(body);
                let body_effects = infer.current_effect_row().clone();
                let capability_sources = infer.capability_sources().clone();
                let propagated_effect_sources = infer.propagated_effect_sources().clone();
                let has_return = infer.has_explicit_return();
                let tail = (!has_return && !is_generic).then_some((&body_ty, &expected_ret));
                infer.record_inferred_local_ints(tail);
                (
                    body_ty,
                    body_effects,
                    capability_sources,
                    propagated_effect_sources,
                    infer.take_errors(),
                    has_return,
                )
            };

            // Unify body type with return type.
            // If the function contains explicit `return` statements, the body
            // type might be `()` (e.g., from a while loop that returns via
            // `return` inside an `if`). In this case, the return type was
            // already validated by infer_return(), so skip the body check.
            if !has_return && !is_generic {
                if let Err(_) = super::unify::unify(&body_ty, &expected_ret) {
                    // When ADT types mismatch by DefId, check if they match by
                    // name.  This handles cases where inline module re-exports
                    // or registration order give the same struct different
                    // DefIds.
                    let name_match = if let (TyKind::Adt(d1, _), TyKind::Adt(d2, _)) =
                        (&body_ty.kind, &expected_ret.kind)
                    {
                        if d1 != d2 {
                            let n1 = self.ctx.lookup_type(*d1).map(|t| t.name.clone());
                            let n2 = self.ctx.lookup_type(*d2).map(|t| t.name.clone());
                            n1.is_some() && n1 == n2
                        } else {
                            true
                        }
                    } else {
                        false
                    };
                    if !name_match {
                        self.error(
                            TypeError::ReturnTypeMismatch {
                                expected: expected_ret,
                                found: body_ty,
                            },
                            span,
                        );
                    }
                }
            }

            // Check effects: if the function is declared pure (no effect annotations)
            // but the body performs effects, report an error.
            let func_name = f.name.name.to_string();
            let mut declared_effects: Vec<String> = expected_effects
                .effects
                .iter()
                .map(|effect| effect.name.to_string())
                .collect();
            declared_effects.sort();
            self.function_effect_summaries.push(FunctionEffectSummary {
                function: func_name.clone(),
                declared_effects,
                observed_capabilities: capability_sources.clone(),
                propagated_effects: propagated_effect_sources.clone(),
            });

            if expected_effects.is_empty() && !body_effects.is_empty() {
                let missing: Vec<String> = body_effects
                    .effects
                    .iter()
                    .map(|e| e.name.to_string())
                    .collect();
                let row_fix = effect_row_fix(f, &missing);
                for body_eff in &body_effects.effects {
                    let err = TypeError::UnhandledEffect {
                        func_name: func_name.clone(),
                        effect_name: body_eff.name.to_string(),
                    };
                    let mut err_with_span = TypeErrorWithSpan::new(err, span);
                    err_with_span.fix = row_fix.clone();
                    err_with_span.help = Some(format!(
                        "either add `~ {}` to the function signature:\n  fn {}() ~ {} {{ ... }}\n\nor handle the effect with a handler:\n  handle {{ ... }} with {{\n      {}.operation(args) => |resume| {{\n          // handle the operation\n          resume(())\n      }},\n  }}",
                        body_eff.name, func_name, body_eff.name, body_eff.name
                    ));
                    if let Some(sources) = capability_sources.get(body_eff.name.as_ref()) {
                        err_with_span.notes.push(format!(
                            "capability `{}` was triggered by ambient call(s): {}",
                            body_eff.name,
                            sources.iter().cloned().collect::<Vec<_>>().join(", ")
                        ));
                    }
                    if let Some(sources) = propagated_effect_sources.get(body_eff.name.as_ref()) {
                        err_with_span.notes.push(format!(
                            "capability `{}` was propagated by effectful call(s): {}",
                            body_eff.name,
                            sources.iter().cloned().collect::<Vec<_>>().join(", ")
                        ));
                    }
                    self.errors.push(err_with_span);
                }
            } else if !expected_effects.is_empty() && !body_effects.is_empty() {
                // Check that body effects are a subset of declared effects
                let declared_names: Vec<String> = expected_effects
                    .effects
                    .iter()
                    .map(|e| e.name.to_string())
                    .collect();
                let missing: Vec<String> = body_effects
                    .effects
                    .iter()
                    .filter(|e| !expected_effects.contains(e))
                    .map(|e| e.name.to_string())
                    .collect();
                let row_fix = effect_row_fix(f, &missing);
                for body_eff in &body_effects.effects {
                    if !expected_effects.contains(body_eff) {
                        let err = TypeError::UndeclaredEffect {
                            func_name: func_name.clone(),
                            effect_name: body_eff.name.to_string(),
                            declared_effects: declared_names.clone(),
                        };
                        let mut err_with_span = TypeErrorWithSpan::new(err, span);
                        err_with_span.help = err_with_span.error.suggestion();
                        err_with_span.fix = row_fix.clone();
                        if let Some(sources) = capability_sources.get(body_eff.name.as_ref()) {
                            err_with_span.notes.push(format!(
                                "capability `{}` was triggered by ambient call(s): {}",
                                body_eff.name,
                                sources.iter().cloned().collect::<Vec<_>>().join(", ")
                            ));
                        }
                        if let Some(sources) = propagated_effect_sources.get(body_eff.name.as_ref())
                        {
                            err_with_span.notes.push(format!(
                                "capability `{}` was propagated by effectful call(s): {}",
                                body_eff.name,
                                sources.iter().cloned().collect::<Vec<_>>().join(", ")
                            ));
                        }
                        self.errors.push(err_with_span);
                    }
                }
            }

            // Collect errors from inference. For generic functions, defer body
            // type errors to monomorphization (the concrete instantiation at each
            // call site is the real check).
            if !is_generic {
                self.errors.extend(infer_errors);
            }

            // Restore the type-parameter bounds that were in scope on entry,
            // dropping this function's own bounds.
            self.ctx.restore_param_bounds(saved_param_bounds);

            self.ctx.pop_scope();
        }
    }

    /// Lower effect annotations from AST paths to an EffectRow.
    fn lower_effect_annotations(&self, effects: &[ast::Path]) -> super::effects::EffectRow {
        if effects.is_empty() {
            return super::effects::EffectRow::empty();
        }

        let mut row = super::effects::EffectRow::empty();
        for path in effects {
            if let Some(ident) = path.last_ident() {
                let effect = super::effects::Effect::new(ident.name.as_ref());
                row.add(effect);
            }
        }
        row
    }

    fn check_impl(&mut self, impl_: &ast::ImplDef, span: Span) {
        self.ctx.push_scope(ScopeKind::Block);

        // Add generic parameters
        for (idx, param) in impl_.generics.params.iter().enumerate() {
            if let ast::GenericParamKind::Type { .. } = &param.kind {
                let ty = Ty::param(param.ident.name.clone(), idx as u32);
                self.ctx.define_type_param(param.ident.name.clone(), ty);
            }
        }

        // Register the impl's type-parameter trait bounds so method bodies can
        // resolve trait methods on the impl's type parameters. For
        // `impl<T: Ord> Ord for [T]`, this makes `self[i].cmp(..)` (where
        // `self[i]: T`) resolve `cmp` through the `Ord` bound. The bounds are
        // restored on exit so sibling items are unaffected.
        let saved_param_bounds = self.ctx.param_bounds_snapshot();
        self.register_generic_param_bounds(&impl_.generics);

        let self_ty = self.lower_type(&impl_.self_ty);

        // Set the Self type for type resolution within the impl block
        self.ctx.set_self_ty(Some(self_ty.clone()));

        if let Some(trait_ref) = &impl_.trait_ref {
            // Trait implementation
            self.check_trait_impl(impl_, &self_ty, trait_ref, span);
        } else {
            // Inherent implementation
            self.check_inherent_impl(impl_, &self_ty, span);
        }

        // Clear the Self type when leaving the impl block
        self.ctx.set_self_ty(None);
        self.ctx.restore_param_bounds(saved_param_bounds);
        self.ctx.pop_scope();
    }

    fn check_trait_impl(
        &mut self,
        impl_: &ast::ImplDef,
        self_ty: &Ty,
        trait_ref: &ast::TraitRef,
        span: Span,
    ) {
        // Look up trait
        let trait_name = trait_ref
            .path
            .last_ident()
            .map(|i| i.name.as_ref())
            .unwrap_or("");

        let trait_def = self.ctx.lookup_trait_by_name(trait_name).cloned();

        if trait_def.is_none() {
            self.error(
                TypeError::UndefinedType {
                    name: trait_name.to_string(),
                },
                span,
            );
            return;
        }

        let trait_def = trait_def.unwrap();

        // Check that all required items are implemented
        for method in &trait_def.methods {
            if !method.has_default {
                let found = impl_.items.iter().any(|item| {
                    if let ImplItemKind::Function(f) = &item.kind {
                        f.name.name.as_ref() == method.name.as_ref()
                    } else {
                        false
                    }
                });

                if !found {
                    self.error(
                        TypeError::UndefinedMethod {
                            ty: self_ty.clone(),
                            method: method.name.to_string(),
                        },
                        span,
                    );
                }
            }
        }

        // Register the implementation BEFORE checking method bodies so that a
        // method can call sibling methods of the same trait impl (including
        // required methods and defaulted methods). Without this pre-pass,
        // `self.cmp(other)` inside `Ord::max_by` would not resolve because the
        // impl was not yet visible to method resolution.
        let generics = self.collect_generics(&impl_.generics);

        // Collect associated types from impl items
        let mut assoc_types = std::collections::HashMap::new();
        for item in &impl_.items {
            if let ImplItemKind::Type { name, ty, .. } = &item.kind {
                let lowered_ty = self.lower_type(ty);
                assoc_types.insert(name.name.clone(), lowered_ty);
            }
        }

        // Collect method signatures from impl items
        let mut methods: std::collections::HashMap<Arc<str>, DefId> =
            std::collections::HashMap::new();
        for item in &impl_.items {
            if let ImplItemKind::Function(f) = &item.kind {
                let method_def_id = self.ctx.fresh_def_id();
                methods.insert(f.name.name.clone(), method_def_id);
            }
        }

        // Collect where clauses from the impl's where clause
        let where_clauses = impl_
            .generics
            .where_clause
            .as_ref()
            .map(|wc| self.collect_where_predicates(wc))
            .unwrap_or_default();

        let trait_impl = TraitImpl {
            trait_id: trait_def.def_id,
            self_ty: self_ty.clone(),
            generics,
            assoc_types,
            methods,
            where_clauses,
        };

        self.ctx.register_impl(trait_impl);

        // Check each impl item (bodies can now resolve sibling trait methods).
        for item in &impl_.items {
            self.check_impl_item(item, self_ty);
        }
    }

    fn check_inherent_impl(&mut self, impl_: &ast::ImplDef, self_ty: &Ty, _span: Span) {
        // Extract the type DefId for inherent method registration
        let type_name = Self::extract_type_name_from_ast(&impl_.self_ty);
        let type_def_id = type_name
            .as_ref()
            .and_then(|n| self.ctx.lookup_type_by_name(n).map(|td| td.def_id));

        // PASS 1: Pre-register ALL method signatures and constants before
        // checking any bodies. This fixes forward references: method A can
        // call method B even if B is defined after A in the source.
        for item in &impl_.items {
            match &item.kind {
                ImplItemKind::Const { name, ty, .. } => {
                    let const_ty = self.lower_type(ty);
                    self.ctx.define_var(name.name.clone(), const_ty);
                }
                ImplItemKind::Function(f) => {
                    if let Some(def_id) = type_def_id {
                        let sig = self.build_fn_sig_from_ast(f);
                        self.ctx
                            .register_inherent_method(def_id, f.name.name.clone(), sig);
                    }
                }
                _ => {}
            }
        }

        // PASS 2: Check method bodies (all signatures already registered).
        // Methods of a generic impl (impl<T> ...) are checked per-instantiation
        // at monomorphization; their bodies cannot resolve the abstract type
        // parameters (method/field access on T), so defer the bodies here.
        let impl_is_generic = impl_
            .generics
            .params
            .iter()
            .any(|p| matches!(p.kind, ast::GenericParamKind::Type { .. }));
        for item in &impl_.items {
            if impl_is_generic && matches!(item.kind, ImplItemKind::Function(_)) {
                continue;
            }
            self.check_impl_item(item, self_ty);
        }
    }

    /// Extract a type name string from an AST Type node (for inherent impl registration).
    fn extract_type_name_from_ast(ty: &ast::Type) -> Option<String> {
        match &ty.kind {
            ast::TypeKind::Path(path) => path.last_ident().map(|i| i.name.to_string()),
            _ => None,
        }
    }

    /// Build a FnSig from an AST function definition for method registration.
    fn build_fn_sig_from_ast(&mut self, f: &ast::FnDef) -> FnSig {
        let params: Vec<(Arc<str>, Ty)> = f
            .sig
            .params
            .iter()
            .map(|p| {
                let name = match &p.pattern.kind {
                    ast::PatternKind::Ident { name, .. } => name.name.clone(),
                    _ => Arc::from("_"),
                };
                let ty = if name.as_ref() == "self" {
                    // self parameter - use a fresh var since we don't need the exact type
                    Ty::fresh_var()
                } else {
                    self.lower_type(&p.ty)
                };
                (name, ty)
            })
            .collect();

        let ret = f
            .sig
            .return_ty
            .as_ref()
            .map(|t| self.lower_type(t))
            .unwrap_or(Ty::unit());

        // Extract lifetime parameters from generics
        let lifetime_params: Vec<Arc<str>> = f
            .generics
            .params
            .iter()
            .filter_map(|p| {
                if let ast::GenericParamKind::Lifetime { .. } = &p.kind {
                    Some(p.ident.name.clone())
                } else {
                    None
                }
            })
            .collect();

        FnSig {
            generics: Vec::new(),
            lifetime_params,
            params,
            ret,
            effects: self.lower_effect_annotations(&f.sig.effects),
            is_unsafe: f.sig.is_unsafe,
            is_async: f.sig.is_async,
            is_const: f.sig.is_const,
            where_clauses: Vec::new(),
        }
    }

    fn check_impl_item(&mut self, item: &ast::ImplItem, _self_ty: &Ty) {
        match &item.kind {
            ImplItemKind::Function(f) => {
                self.check_function(f, item.span);
            }
            ImplItemKind::Const { name, ty, value } => {
                let c = ast::ConstDef {
                    name: name.clone(),
                    ty: ty.clone(),
                    value: Some(value.clone()),
                };
                self.check_const(&c, item.span);
            }
            ImplItemKind::Type { .. } => {
                // Type alias in impl - already collected
            }
            ImplItemKind::Macro { .. } => {
                // Macro in impl - handled during expansion
            }
        }
    }

    fn check_const(&mut self, c: &ast::ConstDef, span: Span) {
        let ty = self.lower_type(&c.ty);

        if let Some(init) = &c.value {
            // Use block to limit TypeInfer borrow scope
            let (init_ty, infer_errors) = {
                let well_known_types = Self::well_known_types_from_ctx(self.ctx);
                let mut infer = TypeInfer::new(self.ctx);
                infer.set_well_known_types(well_known_types);
                let init_ty = infer.infer_expr(init);
                (init_ty, infer.take_errors())
            };

            if let Err(_) = super::unify::unify(&ty, &init_ty) {
                self.error(
                    TypeError::TypeMismatch {
                        expected: ty.clone(),
                        found: init_ty,
                    },
                    span,
                );
            }

            self.errors.extend(infer_errors);
        }

        self.ctx.define_var(c.name.name.clone(), ty);
    }

    fn check_static(&mut self, s: &ast::StaticDef, span: Span) {
        let ty = self.lower_type(&s.ty);

        if let Some(init) = &s.value {
            // Use block to limit TypeInfer borrow scope
            let (init_ty, infer_errors) = {
                let well_known_types = Self::well_known_types_from_ctx(self.ctx);
                let mut infer = TypeInfer::new(self.ctx);
                infer.set_well_known_types(well_known_types);
                let init_ty = infer.infer_expr(init);
                (init_ty, infer.take_errors())
            };

            if let Err(_) = super::unify::unify(&ty, &init_ty) {
                self.error(
                    TypeError::TypeMismatch {
                        expected: ty.clone(),
                        found: init_ty,
                    },
                    span,
                );
            }

            self.errors.extend(infer_errors);
        }

        self.ctx.define_var(s.name.name.clone(), ty);
    }

    /// Resolve a `use` statement, importing bindings from a module into the
    /// current scope.
    fn resolve_use(&mut self, tree: &ast::UseTree) {
        self.resolve_use_prefixed(tree, &[]);
    }

    /// Resolve a `use` tree carrying the module-path prefix accumulated from
    /// enclosing nested groups, so `use foundation::math::{sign, cbrt}` binds
    /// `sign`/`cbrt` from the `foundation::math` module rather than losing the
    /// `foundation::math` prefix (which the flat handler used to drop).
    fn resolve_use_prefixed(&mut self, tree: &ast::UseTree, prefix: &[Arc<str>]) {
        match &tree.kind {
            ast::UseTreeKind::Simple { path, rename } => {
                let mut segs: Vec<Arc<str>> = prefix.to_vec();
                segs.extend(path.segments.iter().map(|s| s.ident.name.clone()));
                if segs.len() < 2 || Self::is_reserved_use_root(&segs[0]) {
                    return;
                }
                let item = segs[segs.len() - 1].clone();
                // `use a::b::self` names the module itself, not a value binding.
                if item.as_ref() == "self" {
                    return;
                }
                let module_segs = &segs[..segs.len() - 1];
                // First, a module registered by an in-tree `mod NAME;` (real
                // signatures). Fall back to the file-backed export set, binding
                // the imported name as an opaque value so it stops reading as
                // "undefined" without importing a concrete signature that could
                // collide with the consumer's own same-named type.
                let local_name = rename
                    .as_ref()
                    .map(|r| r.name.clone())
                    .unwrap_or_else(|| item.clone());
                if let Some(ty) = self
                    .ctx
                    .lookup_module_binding(module_segs[0].as_ref(), item.as_ref())
                {
                    self.ctx.define_var(local_name, ty);
                    return;
                }
                if self.module_exports_name(module_segs, item.as_ref()) {
                    self.ctx.define_var(local_name, Ty::fresh_var());
                }
            }
            ast::UseTreeKind::Glob(path) => {
                let mut segs: Vec<Arc<str>> = prefix.to_vec();
                segs.extend(path.segments.iter().map(|s| s.ident.name.clone()));
                if segs.is_empty() || Self::is_reserved_use_root(&segs[0]) {
                    return;
                }
                // Real bindings from an in-tree `mod NAME;` win; otherwise bind
                // every file-backed export name as an opaque value.
                if let Some(bindings) = self
                    .ctx
                    .clone_module_bindings(segs[segs.len() - 1].as_ref())
                {
                    for (name, scheme) in bindings {
                        self.ctx.define_var(name, scheme.instantiate());
                    }
                    return;
                }
                if let Some(names) = self.module_export_set(&segs) {
                    for name in names {
                        self.ctx.define_var(name, Ty::fresh_var());
                    }
                }
            }
            ast::UseTreeKind::Nested { path, trees } => {
                let mut new_prefix: Vec<Arc<str>> = prefix.to_vec();
                new_prefix.extend(path.segments.iter().map(|s| s.ident.name.clone()));
                for sub_tree in trees {
                    self.resolve_use_prefixed(sub_tree, &new_prefix);
                }
            }
        }
    }

    /// Roots that name the standard library or a path relative to the current
    /// crate rather than an on-disk sibling module file. These are left to the
    /// existing prelude/name resolution instead of a filesystem load.
    fn is_reserved_use_root(seg: &str) -> bool {
        matches!(seg, "std" | "core" | "crate" | "self" | "super")
    }

    /// Whether the module backing `module_segs` exports a top-level item named
    /// `name`. Thin membership test over [`Self::module_export_set`].
    fn module_exports_name(&mut self, module_segs: &[Arc<str>], name: &str) -> bool {
        self.module_export_set(module_segs)
            .is_some_and(|names| names.contains(name))
    }

    /// The set of top-level item names the `.bld` file backing a `use a::b::c`
    /// path import exports. Read-only: the module file is lexed and parsed to
    /// harvest its item names, and NOTHING is written into the type context, so
    /// no type is registered, no `DefId` is minted, and no diagnostic is
    /// produced. This keeps `use` provably additive: binding an imported leaf as
    /// a fresh var stops it reading as "undefined" without importing a concrete
    /// signature that could collide with the consumer's own same-named type.
    /// Cached per module path (`None` cached for a missing/unparseable file).
    fn module_export_set(&mut self, module_segs: &[Arc<str>]) -> Option<HashSet<Arc<str>>> {
        if module_segs.is_empty() {
            return None;
        }
        let key: Arc<str> = Arc::from(
            module_segs
                .iter()
                .map(|s| s.as_ref())
                .collect::<Vec<_>>()
                .join("::"),
        );
        if let Some(cached) = self.use_module_exports.get(&key) {
            return cached.clone();
        }
        let names = self
            .resolve_use_module_file(module_segs)
            .and_then(|path| Self::collect_export_names(&path));
        self.use_module_exports.insert(key, names.clone());
        names
    }

    /// Resolve module path segments to an on-disk `.bld` file, searching the
    /// source directory and its ancestors so a file under `tests/` can reach a
    /// `foundation/` tree sitting beside the corpus root.
    fn resolve_use_module_file(&self, module_segs: &[Arc<str>]) -> Option<PathBuf> {
        let start = self.source_dir.as_ref()?;
        let mut cur: Option<&std::path::Path> = Some(start.as_path());
        for _ in 0..8 {
            let root = cur?;
            if let Some(f) = Self::use_module_candidate(root, module_segs) {
                return Some(f);
            }
            cur = root.parent();
        }
        None
    }

    /// Build candidate files for `segs` under `root` in preference order,
    /// returning the first that exists. Directory segments may be spelled with
    /// underscores in the import but hyphens on disk (`field_tensor` ->
    /// `field-tensor/`), so both spellings are tried per segment.
    fn use_module_candidate(root: &std::path::Path, segs: &[Arc<str>]) -> Option<PathBuf> {
        let n = segs.len();
        let mut dir = root.to_path_buf();
        for seg in &segs[..n - 1] {
            let as_is = dir.join(seg.as_ref());
            let hyphen = dir.join(seg.replace('_', "-"));
            if as_is.is_dir() {
                dir = as_is;
            } else if hyphen.is_dir() {
                dir = hyphen;
            } else {
                return None;
            }
        }
        let last = &segs[n - 1];
        let last_hyphen = last.replace('_', "-");
        let mut cands: Vec<PathBuf> = vec![
            dir.join(format!("{}.bld", last)),
            dir.join(last.as_ref()).join("lib.bld"),
            dir.join(last.as_ref()).join("mod.bld"),
        ];
        if last_hyphen != last.as_ref() {
            cands.push(dir.join(format!("{}.bld", last_hyphen)));
            cands.push(dir.join(&last_hyphen).join("lib.bld"));
        }
        cands.into_iter().find(|c| c.is_file())
    }

    /// Lex and parse `path` READ-ONLY and return the set of top-level item names
    /// it exports. Touches nothing on `self`: no type context, no error list, no
    /// module stack. Returns `None` when the file cannot be read, lexed, or
    /// parsed, so an unresolved import stays silent for the existing
    /// name-resolution path rather than inventing an error.
    fn collect_export_names(path: &std::path::Path) -> Option<HashSet<Arc<str>>> {
        let source_text = std::fs::read_to_string(path).ok()?;
        let source = crate::lexer::SourceFile::new(path.to_string_lossy().as_ref(), source_text);
        let mut lexer = crate::lexer::Lexer::new(&source);
        let tokens = lexer.tokenize().ok()?;
        let mut parser = crate::parser::Parser::new(&source, tokens);
        let module_ast = parser.parse().ok()?;
        let mut names: HashSet<Arc<str>> = HashSet::new();
        for item in &module_ast.items {
            match &item.kind {
                ItemKind::Function(f) => {
                    names.insert(f.name.name.clone());
                }
                ItemKind::Struct(s) => {
                    names.insert(s.name.name.clone());
                }
                ItemKind::Enum(e) => {
                    names.insert(e.name.name.clone());
                }
                ItemKind::Const(c) => {
                    names.insert(c.name.name.clone());
                }
                ItemKind::Static(s) => {
                    names.insert(s.name.name.clone());
                }
                ItemKind::TypeAlias(ta) => {
                    names.insert(ta.name.name.clone());
                }
                ItemKind::Trait(t) => {
                    names.insert(t.name.name.clone());
                }
                ItemKind::Effect(e) => {
                    names.insert(e.name.name.clone());
                }
                ItemKind::Mod(m) => {
                    names.insert(m.name.name.clone());
                }
                _ => {}
            }
        }
        Some(names)
    }

    fn check_mod(&mut self, m: &ast::ModDef) {
        // External module: `mod foo;` loads foo.bld from disk
        if m.content.is_none() {
            if m.is_file_module {
                // File-level `module NAME` header: the rest of the file already
                // IS the body, so there is nothing to load. Loading `NAME.bld`
                // here would re-open the declaring file and recurse forever.
                return;
            }
            if let Some(ref dir) = self.source_dir {
                let mod_name = m.name.name.as_ref();
                // Only a module beside the source is checked here; a standard
                // library module's signatures are collected (collect_mod) and
                // its bodies are checked in the merged program.
                let local = dir.join(format!("{}.bld", mod_name));
                if let Some(mod_path) = local.exists().then_some(local) {
                    let key = std::fs::canonicalize(&mod_path).unwrap_or_else(|_| mod_path.clone());
                    if !self.loading_modules.insert(key.clone()) {
                        // Already on the load stack: fail closed with a cycle
                        // diagnostic instead of overflowing the stack.
                        self.error(
                            TypeError::ModuleImportCycle {
                                path: mod_path.display().to_string(),
                                module: mod_name.to_string(),
                            },
                            m.name.span,
                        );
                        return;
                    }
                    if let Ok(source_text) = std::fs::read_to_string(&mod_path) {
                        let source = crate::lexer::SourceFile::new(
                            mod_path.to_string_lossy().as_ref(),
                            source_text,
                        );
                        let mut lexer = crate::lexer::Lexer::new(&source);
                        if let Ok(tokens) = lexer.tokenize() {
                            let mut parser = crate::parser::Parser::new(&source, tokens);
                            if let Ok(module_ast) = parser.parse() {
                                // Process the external module's items as if they were inline
                                self.ctx.push_scope(ScopeKind::Module);
                                for item in &module_ast.items {
                                    self.collect_item(item);
                                }
                                for item in &module_ast.items {
                                    self.check_item(item);
                                }
                                let module_name = m.name.name.clone();
                                let bindings = self.ctx.current_scope_bindings();
                                self.ctx
                                    .register_module_bindings(module_name.clone(), bindings);
                                // Re-export to parent scope
                                for item in &module_ast.items {
                                    match &item.kind {
                                        ItemKind::Function(f) => {
                                            self.collect_function(f, item.span)
                                        }
                                        ItemKind::Struct(s) => {
                                            if self
                                                .ctx
                                                .lookup_type_by_name(s.name.name.as_ref())
                                                .is_none()
                                            {
                                                self.collect_struct(
                                                    s,
                                                    item.span,
                                                    Self::has_linear_attr(&item.attrs),
                                                );
                                            }
                                        }
                                        ItemKind::Enum(e) => {
                                            if self
                                                .ctx
                                                .lookup_type_by_name(e.name.name.as_ref())
                                                .is_none()
                                            {
                                                self.collect_enum(
                                                    e,
                                                    item.span,
                                                    Self::has_linear_attr(&item.attrs),
                                                );
                                            }
                                        }
                                        _ => {}
                                    }
                                }
                                self.ctx.pop_scope();
                            }
                        }
                    }
                    self.loading_modules.remove(&key);
                }
            }
            return;
        }
        if let Some(content) = &m.content {
            self.ctx.push_scope(ScopeKind::Module);

            // First pass: collect
            for item in &content.items {
                self.collect_item(item);
            }

            // Second pass: check
            for item in &content.items {
                self.check_item(item);
            }

            // Save module bindings for use-statement resolution before
            // popping the scope (so we capture the module's definitions).
            let module_name = m.name.name.clone();
            let bindings = self.ctx.current_scope_bindings();
            self.ctx.register_module_bindings(module_name, bindings);

            self.ctx.pop_scope();

            // Re-export pub items to parent scope (implicit `use mod::*`).
            // This is the BuildLang ecosystem convention - module contents
            // are accessible by bare name from the parent scope.
            //
            // IMPORTANT: For structs and enums, reuse the existing DefId from
            // the first registration (inside the module scope) instead of
            // calling collect_struct/collect_enum which would create a NEW
            // DefId.  A duplicated DefId causes type mismatches when code
            // inside the module constructs a value (using the original DefId)
            // but the return-type annotation resolves to the re-exported DefId.
            for item in &content.items {
                match &item.kind {
                    ItemKind::Const(c) => {
                        let ty = self.lower_type(&c.ty);
                        self.ctx.define_var(c.name.name.clone(), ty);
                    }
                    ItemKind::Function(f) => {
                        self.collect_function(f, item.span);
                    }
                    ItemKind::Struct(s) => {
                        // Reuse the existing type registration if it exists,
                        // so that the DefId is identical to the one used inside
                        // the module scope.
                        if self.ctx.lookup_type_by_name(s.name.name.as_ref()).is_none() {
                            self.collect_struct(s, item.span, Self::has_linear_attr(&item.attrs));
                        }
                    }
                    ItemKind::Enum(e) => {
                        // Same as structs: reuse existing DefId.
                        if self.ctx.lookup_type_by_name(e.name.name.as_ref()).is_none() {
                            self.collect_enum(e, item.span, Self::has_linear_attr(&item.attrs));
                        }
                    }
                    ItemKind::Impl(impl_) => {
                        // Re-export inherent methods to parent scope so they're
                        // accessible when code outside the module calls methods
                        // on the re-exported types.
                        self.collect_impl(impl_, item.span);
                    }
                    _ => {}
                }
            }
        }
    }

    // =========================================================================
    // HELPER METHODS
    // =========================================================================

    fn collect_generics(&mut self, generics: &ast::Generics) -> Vec<GenericParam> {
        generics
            .params
            .iter()
            .enumerate()
            .map(|(idx, p)| {
                let kind = match &p.kind {
                    ast::GenericParamKind::Type { bounds, .. } => GenericParamKind::Type {
                        bounds: bounds
                            .iter()
                            .filter_map(|b| self.lower_type_bound(b))
                            .collect(),
                    },
                    ast::GenericParamKind::Lifetime { .. } => GenericParamKind::Lifetime,
                    ast::GenericParamKind::Const { ty, .. } => GenericParamKind::Const {
                        ty: self.lower_type(ty),
                    },
                };

                GenericParam {
                    name: p.ident.name.clone(),
                    index: idx as u32,
                    kind,
                }
            })
            .collect()
    }

    fn lower_fn_sig(&mut self, generics: &ast::Generics, sig: &ast::FnSig) -> FnSig {
        let gen_params = self.collect_generics(generics);

        let params: Vec<_> = sig
            .params
            .iter()
            .map(|p| {
                let name = match &p.pattern.kind {
                    ast::PatternKind::Ident { name, .. } => name.name.clone(),
                    _ => Arc::from("_"),
                };
                (name, self.lower_type(&p.ty))
            })
            .collect();

        let ret = sig
            .return_ty
            .as_ref()
            .map(|t| self.lower_type(t))
            .unwrap_or(Ty::unit());

        let where_clauses = generics
            .where_clause
            .as_ref()
            .map(|wc| {
                wc.predicates
                    .iter()
                    .map(|p| WhereClause {
                        ty: self.lower_type(&p.ty),
                        bounds: p
                            .bounds
                            .iter()
                            .filter_map(|b| self.lower_type_bound(b))
                            .collect(),
                    })
                    .collect()
            })
            .unwrap_or_default();

        let lifetime_params: Vec<Arc<str>> = generics
            .params
            .iter()
            .filter_map(|p| {
                if let ast::GenericParamKind::Lifetime { .. } = &p.kind {
                    Some(p.ident.name.clone())
                } else {
                    None
                }
            })
            .collect();

        FnSig {
            generics: gen_params,
            lifetime_params,
            params,
            ret,
            effects: self.lower_effect_annotations(&sig.effects),
            is_unsafe: sig.is_unsafe,
            is_async: sig.is_async,
            is_const: sig.is_const,
            where_clauses,
        }
    }

    fn lower_type_bound(&mut self, bound: &ast::TypeBound) -> Option<TraitBound> {
        // Look up trait by path
        let trait_name = bound.path.last_ident().map(|i| &*i.name)?;

        let trait_def = self.ctx.lookup_trait_by_name(trait_name)?;
        let trait_id = trait_def.def_id; // Extract before the borrow ends

        // Collect type arguments from the trait bound's path generic args
        let args = bound
            .path
            .segments
            .last()
            .map(|seg| {
                seg.generics
                    .iter()
                    .filter_map(|arg| match arg {
                        ast::GenericArg::Type(ty) => Some(self.lower_type(ty)),
                        _ => None,
                    })
                    .collect()
            })
            .unwrap_or_default();

        Some(TraitBound { trait_id, args })
    }

    fn collect_where_predicates(&mut self, wc: &ast::WhereClause) -> Vec<WhereClause> {
        wc.predicates
            .iter()
            .map(|pred| {
                let ty = self.lower_type(&pred.ty);
                let bounds = pred
                    .bounds
                    .iter()
                    .filter_map(|b| self.lower_type_bound(b))
                    .collect();
                WhereClause { ty, bounds }
            })
            .collect()
    }

    fn lower_type(&mut self, ty: &ast::Type) -> Ty {
        // Create a temporary inference context for type lowering
        let well_known_types = Self::well_known_types_from_ctx(self.ctx);
        let mut infer = TypeInfer::new(self.ctx);
        infer.set_well_known_types(well_known_types);
        infer.lower_type(ty)
    }

    fn bind_pattern(&mut self, pattern: &ast::Pattern, ty: &Ty) {
        match &pattern.kind {
            ast::PatternKind::Wildcard => {}
            ast::PatternKind::Ident { name, .. } => {
                self.ctx.define_var(name.name.clone(), ty.clone());
            }
            ast::PatternKind::Tuple(patterns) => {
                if let TyKind::Tuple(elem_tys) = &ty.kind {
                    for (pat, elem_ty) in patterns.iter().zip(elem_tys.iter()) {
                        self.bind_pattern(pat, elem_ty);
                    }
                }
            }
            _ => {}
        }
    }

    fn eval_const_int(&self, expr: &ast::Expr) -> Option<i128> {
        // Basic const evaluation for integer literals and simple expressions
        match &expr.kind {
            ast::ExprKind::Literal(ast::Literal::Int { value, .. }) => Some(*value as i128),
            ast::ExprKind::Unary {
                op: ast::UnaryOp::Neg,
                expr: operand,
            } => self.eval_const_int(operand).and_then(|n| n.checked_neg()),
            ast::ExprKind::Binary { op, left, right } => {
                let l = self.eval_const_int(left)?;
                let r = self.eval_const_int(right)?;
                match op {
                    ast::BinOp::Add => Some(l.checked_add(r)?),
                    ast::BinOp::Sub => Some(l.checked_sub(r)?),
                    ast::BinOp::Mul => Some(l.checked_mul(r)?),
                    ast::BinOp::Div if r != 0 => Some(l.checked_div(r)?),
                    ast::BinOp::Rem if r != 0 => Some(l.checked_rem(r)?),
                    ast::BinOp::Shl => Some(l.checked_shl(r as u32)?),
                    ast::BinOp::Shr => Some(l.checked_shr(r as u32)?),
                    ast::BinOp::BitAnd => Some(l & r),
                    ast::BinOp::BitOr => Some(l | r),
                    ast::BinOp::BitXor => Some(l ^ r),
                    _ => None,
                }
            }
            ast::ExprKind::Paren(inner) => self.eval_const_int(inner),
            _ => None,
        }
    }
}

impl Default for TypeChecker<'_> {
    fn default() -> Self {
        panic!("TypeChecker requires a context")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn check_source(source: &str) -> Vec<TypeErrorWithSpan> {
        let source_file = crate::lexer::SourceFile::new("capability_test.bld", source);
        let mut lexer = crate::lexer::Lexer::new(&source_file);
        let tokens = lexer.tokenize().expect("tokenize capability fixture");
        let mut parser = crate::parser::Parser::new(&source_file, tokens);
        let module = parser.parse().expect("parse capability fixture");

        let mut ctx = TypeContext::new();
        let mut checker = TypeChecker::new(&mut ctx);
        checker.set_source_file(&source_file);
        checker.check_module(&module);
        checker.take_errors()
    }

    #[test]
    fn variadic_extern_call_with_extra_args_typechecks() {
        let errors = check_source(
            "extern \"C\" { fn my_printf(fmt: &str, ...) -> i32; }\n\
             fn main() ~ Foreign { my_printf(\"%d %d\", 1, 2); }",
        );
        assert!(
            !errors
                .iter()
                .any(|e| matches!(e.error, TypeError::ArityMismatch { .. })),
            "a variadic extern call with extra args must not raise ArityMismatch: {:?}",
            errors
        );
    }

    #[test]
    fn non_variadic_call_with_extra_args_still_errors() {
        let errors = check_source(
            "extern \"C\" { fn takes_one(x: i32) -> i32; }\n\
             fn main() ~ Foreign { takes_one(1, 2); }",
        );
        assert!(
            errors
                .iter()
                .any(|e| matches!(e.error, TypeError::ArityMismatch { .. })),
            "a non-variadic call with extra args must still raise ArityMismatch: {:?}",
            errors
        );
    }

    #[test]
    fn call_through_fn_pointer_array_element_is_callable() {
        // Iterating an array of function pointers binds each element by
        // reference, so the callee is a `&fn(..) -> _`. Calling it must
        // auto-deref to the underlying function rather than report the type
        // as NotCallable. Regression for benchmarks.bld's
        // `for bench in [bench_a, bench_b, ..] { let r = bench(); }`.
        let errors = check_source(
            "fn a() -> i32 { 1 }\n\
             fn b() -> i32 { 2 }\n\
             fn run() -> i32 {\n\
                 let mut total = 0;\n\
                 for f in [a, b] {\n\
                     total = total + f();\n\
                 }\n\
                 total\n\
             }",
        );
        assert!(
            !errors
                .iter()
                .any(|e| matches!(e.error, TypeError::NotCallable { .. })),
            "calling an element of a function-pointer array must not be NotCallable: {:?}",
            errors
        );
    }

    #[test]
    fn call_through_plain_reference_to_fn_is_callable() {
        // A bare `&fn(..)` binding (not via an array) is equally callable:
        // `let g = &f; g()` auto-derefs to call `f`.
        let errors = check_source(
            "fn f() -> i32 { 7 }\n\
             fn run() -> i32 {\n\
                 let g = &f;\n\
                 g()\n\
             }",
        );
        assert!(
            !errors
                .iter()
                .any(|e| matches!(e.error, TypeError::NotCallable { .. })),
            "calling through a reference to a function must not be NotCallable: {:?}",
            errors
        );
    }

    #[test]
    fn call_on_reference_to_non_function_still_errors() {
        // Auto-deref applies only when the reference's target is a function.
        // `(&i32)()` must still be reported as not callable (fail closed).
        let errors = check_source(
            "fn run() -> i32 {\n\
                 let x = 5;\n\
                 let r = &x;\n\
                 r()\n\
             }",
        );
        assert!(
            errors
                .iter()
                .any(|e| matches!(e.error, TypeError::NotCallable { .. })),
            "calling a reference to a non-function must still be NotCallable: {:?}",
            errors
        );
    }

    // =========================================================================
    // LINEAR TYPES (no-cloning / no-double-spend) -- opt-in via `#[linear]`.
    //
    // A value whose nominal type is marked `#[linear]` may be *consumed*
    // (used by value) at most once. This is the no-cloning rule for qubits,
    // the no-double-spend rule for on-chain assets, and resource-handle
    // safety for fin-sec settlement obligations -- one type-system feature
    // serving all three. Borrows (`&q`) do not consume. Ordinary types are
    // unaffected (copy-like reuse is preserved).
    // =========================================================================

    const LINEAR_PRELUDE: &str = "#[linear]\nstruct Qubit { id: i64 }\n\
         fn consume(q: Qubit) -> i64 { q.id }\n\
         fn observe(q: &Qubit) -> i64 { 0 }\n";

    fn has_linear_use_after_move(errors: &[TypeErrorWithSpan]) -> bool {
        errors
            .iter()
            .any(|e| matches!(e.error, TypeError::LinearUseAfterMove { .. }))
    }

    #[test]
    fn linear_single_use_is_ok() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let a = consume(q); println(\"{{}}\", a); }}"
        ));
        assert!(
            !has_linear_use_after_move(&errors),
            "using a linear value exactly once must be clean: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_used_twice_via_call_errors() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let a = consume(q); let b = consume(q); println(\"{{}}\", a + b); }}"
        ));
        assert!(
            has_linear_use_after_move(&errors),
            "consuming a linear value twice must be rejected (no-cloning): {errors:#?}"
        );
    }

    #[test]
    fn linear_value_moved_via_let_then_used_errors() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let q2 = q; let a = consume(q); println(\"{{}}\", a); }}"
        ));
        assert!(
            has_linear_use_after_move(&errors),
            "a linear value moved via `let` then used again must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_can_be_borrowed_without_consuming() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let a = observe(&q); let b = observe(&q); let c = consume(q); \
             println(\"{{}}\", a + b + c); }}"
        ));
        assert!(
            !has_linear_use_after_move(&errors),
            "borrowing a linear value must not consume it: {errors:#?}"
        );
    }

    #[test]
    fn ordinary_value_can_still_be_reused() {
        // Backward-compat guard: a non-`#[linear]` struct keeps copy-like reuse.
        let errors = check_source(
            "struct Coin { value: i64 }\n\
             fn spend(c: Coin) -> i64 { c.value }\n\
             fn main() ~ Console { let coin = Coin { value: 1 }; \
             let a = spend(coin); let b = spend(coin); println(\"{}\", a + b); }",
        );
        assert!(
            !has_linear_use_after_move(&errors),
            "ordinary (non-linear) values must remain freely reusable: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_consumed_in_branch_then_used_after_errors() {
        // Conservative soundness: consumed on *any* path -> poisoned afterward.
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let cond = true; if cond {{ let a = consume(q); println(\"{{}}\", a); }} \
             let b = consume(q); println(\"{{}}\", b); }}"
        ));
        assert!(
            has_linear_use_after_move(&errors),
            "a linear value consumed in a branch then used after must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_consumed_in_loop_body_errors() {
        // A loop body may run more than once; consuming an outer linear there
        // is a potential double-use and must be rejected.
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let mut i = 0; while i < 2 {{ let a = consume(q); i = i + 1; }} }}"
        ));
        assert!(
            has_linear_use_after_move(&errors),
            "consuming an outer linear value inside a loop must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_param_single_use_is_ok() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn forward(q: Qubit) -> i64 {{ consume(q) }}\n\
             fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; println(\"{{}}\", forward(q)); }}"
        ));
        assert!(
            !has_linear_use_after_move(&errors),
            "using a linear parameter exactly once must be clean: {errors:#?}"
        );
    }

    #[test]
    fn linear_param_consumed_twice_errors() {
        // A linear function *parameter* must be subject to no-cloning too.
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn waste(q: Qubit) -> i64 {{ let a = consume(q); \
             let b = consume(q); a + b }}\n\
             fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; println(\"{{}}\", waste(q)); }}"
        ));
        assert!(
            has_linear_use_after_move(&errors),
            "consuming a linear parameter twice must be rejected: {errors:#?}"
        );
    }

    fn has_linear_containment(errors: &[TypeErrorWithSpan]) -> bool {
        errors
            .iter()
            .any(|e| matches!(e.error, TypeError::LinearFieldInNonLinearType { .. }))
    }

    #[test]
    fn nonlinear_struct_with_linear_field_is_rejected() {
        // A non-linear type cannot hold a linear field, or the linear value
        // could be laundered (read out repeatedly) past no-cloning.
        let errors = check_source(
            "#[linear]\nstruct Coin { value: i64 }\n\
             struct Wallet { coin: Coin }\n",
        );
        assert!(
            has_linear_containment(&errors),
            "a non-linear struct holding a linear field must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_struct_with_linear_field_is_allowed() {
        // Marking the container `#[linear]` makes the whole aggregate tracked.
        let errors = check_source(
            "#[linear]\nstruct Coin { value: i64 }\n\
             #[linear]\nstruct Wallet { coin: Coin }\n",
        );
        assert!(
            !has_linear_containment(&errors),
            "a linear container may hold a linear field: {errors:#?}"
        );
    }

    // -- Soundness: parse-only constructs must be rejected loudly, never
    //    silently discarded downstream. --

    #[test]
    fn let_else_is_rejected_not_silently_discarded() {
        // let-else parses, but neither the checker nor codegen handles the
        // diverge block: codegen would silently DROP the else path (a silent
        // miscompile). The checker must reject it with UnsupportedConstruct.
        let errors = check_source("fn main() { let Some(x) = opt else { return; }; }");
        assert!(
            errors
                .iter()
                .any(|e| matches!(e.error, TypeError::UnsupportedConstruct { .. })),
            "let-else must be rejected loudly, not silently miscompiled: {errors:#?}"
        );

        // A plain let (no diverge block) is unaffected.
        let errors = check_source("fn main() { let x = 1; }");
        assert!(
            !errors
                .iter()
                .any(|e| matches!(e.error, TypeError::UnsupportedConstruct { .. })),
            "a plain let must not trip the let-else rejection: {errors:#?}"
        );
    }

    // -- Soundness: a linear value may not enter a position the move-analysis
    //    cannot follow (aggregates, generics, closures, deref). These programs
    //    are the confirmed bypasses from the adversarial soundness pass; each
    //    must now be REJECTED with some linear error. --

    fn has_any_linear_error(errors: &[TypeErrorWithSpan]) -> bool {
        errors.iter().any(|e| {
            matches!(
                e.error,
                TypeError::LinearUseAfterMove { .. }
                    | TypeError::LinearFieldInNonLinearType { .. }
                    | TypeError::LinearInUnsupportedPosition { .. }
            )
        })
    }

    #[test]
    fn linear_value_in_tuple_is_rejected() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let t = (q, 0); let a = t.0; let b = t.0; \
             let x = consume(a); let y = consume(b); println(\"{{}}\", x + y); }}"
        ));
        assert!(
            has_any_linear_error(&errors),
            "storing a linear value in a tuple must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_in_array_is_rejected() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let arr = [q]; let a = arr[0]; let b = arr[0]; \
             let x = consume(a); let y = consume(b); println(\"{{}}\", x + y); }}"
        ));
        assert!(
            has_any_linear_error(&errors),
            "storing a linear value in an array must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_in_array_repeat_is_rejected() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let arr = [q; 3]; let a = arr[0]; let b = arr[1]; \
             let x = consume(a); let y = consume(b); println(\"{{}}\", x + y); }}"
        ));
        assert!(
            has_any_linear_error(&errors),
            "array-repeat of a linear value (a literal clone) must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_through_generic_fn_is_rejected() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn thru<T>(x: T) -> T {{ x }}\n\
             fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; let c = thru(q); \
             let a = consume(c); let b = consume(c); println(\"{{}}\", a + b); }}"
        ));
        assert!(
            has_any_linear_error(&errors),
            "passing a linear value through a generic parameter must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_moved_out_of_reference_is_rejected() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let r = &q; let a = *r; let b = *r; \
             let x = consume(a); let y = consume(b); println(\"{{}}\", x + y); }}"
        ));
        assert!(
            has_any_linear_error(&errors),
            "moving a linear value out of a reference (deref-copy) must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_in_generic_struct_is_rejected() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}struct Holder<T> {{ item: T }}\n\
             fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let h = Holder {{ item: q }}; let a = h.item; let b = h.item; \
             let x = consume(a); let y = consume(b); println(\"{{}}\", x + y); }}"
        ));
        assert!(
            has_any_linear_error(&errors),
            "storing a linear value in a generic struct field must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_in_option_is_rejected() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let opt = Some(q); println(\"made an option\"); }}"
        ));
        assert!(
            has_any_linear_error(&errors),
            "wrapping a linear value in Option (a generic container) must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_consumed_then_revived_by_inner_shadow_errors() {
        // An inner-block binding that shadows the (already consumed) outer
        // linear must not revive the outer slot when the block exits.
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let a = consume(q); \
             {{ let q = Qubit {{ id: 2 }}; let _ = observe(&q); }} \
             let b = consume(q); println(\"{{}}\", a + b); }}"
        ));
        assert!(
            has_any_linear_error(&errors),
            "an inner shadow must not revive a consumed outer linear: {errors:#?}"
        );
    }

    #[test]
    fn linear_field_read_through_reference_is_rejected() {
        // Moving a linear field out from behind a borrow (`w.coin` where
        // `w: &Wrap`) does not consume `w`, so it could be repeated.
        let errors = check_source(
            "#[linear]\nstruct Coin { value: i64 }\n\
             #[linear]\nstruct Wrap { coin: Coin }\n\
             fn take(w: &Wrap) -> Coin { w.coin }\n\
             fn spend(c: Coin) -> i64 { c.value }\n\
             fn main() ~ Console { let coin = Coin { value: 1 }; \
             let w = Wrap { coin: coin }; \
             let a = spend(take(&w)); let b = spend(take(&w)); \
             println(\"{} {}\", a, b); }",
        );
        assert!(
            has_any_linear_error(&errors),
            "moving a linear field out through a reference must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_shorthand_field_init_consumes() {
        // `Wallet { coin }` shorthand moves `coin`; using it again is an error.
        let errors = check_source(
            "#[linear]\nstruct Coin { value: i64 }\n\
             #[linear]\nstruct Wallet { coin: Coin }\n\
             fn spend(c: Coin) -> i64 { c.value }\n\
             fn main() ~ Console { let coin = Coin { value: 1 }; \
             let w = Wallet { coin }; let a = spend(coin); println(\"{}\", a); }",
        );
        assert!(
            has_any_linear_error(&errors),
            "a shorthand field init must consume the moved linear local: {errors:#?}"
        );
    }

    #[test]
    fn linear_consumed_in_while_condition_errors() {
        // A while condition is re-evaluated each iteration; consuming an outer
        // linear there is a potential repeat-consume.
        let errors = check_source(
            "#[linear]\nstruct Coin { value: i64 }\n\
             fn drain(c: Coin) -> bool { c.value > 0 }\n\
             fn main() ~ Console { let coin = Coin { value: 1 }; \
             while drain(coin) { println(\"loop\"); } }",
        );
        assert!(
            has_any_linear_error(&errors),
            "consuming a linear value in a while condition must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_method_call_on_borrowed_receiver_is_rejected() {
        // `(&coin).burn()` where `burn(self)` would move the linear out of a
        // borrow; the self-kind isn't visible, so it is conservatively rejected.
        let errors = check_source(
            "#[linear]\nstruct Coin { value: i64 }\n\
             trait Burnable { fn burn(self) -> i64; }\n\
             impl Burnable for Coin { fn burn(self) -> i64 { self.value } }\n\
             fn spend(c: Coin) -> i64 { c.value }\n\
             fn main() ~ Console { let coin = Coin { value: 1 }; \
             let a = (&coin).burn(); let b = spend(coin); println(\"{} {}\", a, b); }",
        );
        assert!(
            has_any_linear_error(&errors),
            "a method call on a borrowed linear receiver must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_in_builtin_collection_is_rejected() {
        // Moving a linear value into a builtin Vec lets it be read out twice.
        let errors = check_source(
            "#[linear]\nstruct Coin { value: i64 }\n\
             fn spend(c: Coin) -> i64 { c.value }\n\
             fn main() ~ Console { let coin = Coin { value: 1 }; \
             let v = vec_new(); vec_push(v, coin); \
             let a = spend(vec_get(v, 0)); let b = spend(vec_get(v, 0)); \
             println(\"{} {}\", a, b); }",
        );
        assert!(
            has_any_linear_error(&errors),
            "storing a linear value in a builtin collection must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn linear_value_captured_in_closure_is_rejected() {
        let errors = check_source(&format!(
            "{LINEAR_PRELUDE}fn main() ~ Console {{ let q = Qubit {{ id: 1 }}; \
             let f = || consume(q); let a = f(); let b = f(); println(\"{{}}\", a + b); }}"
        ));
        assert!(
            has_any_linear_error(&errors),
            "capturing+consuming a linear value in a closure must be rejected: {errors:#?}"
        );
    }

    #[test]
    fn capability_ambient_file_call_requires_filesystem_effect() {
        let errors = check_source(r#"fn main() { read_file("ops.txt"); }"#);

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UnhandledEffect { effect_name, .. } if effect_name == "FileSystem"
            )),
            "expected FileSystem effect error, got {errors:#?}"
        );
        assert!(
            errors
                .iter()
                .any(|err| err.notes.iter().any(|note| note.contains("read_file"))),
            "expected diagnostic note naming read_file, got {errors:#?}"
        );
    }

    #[test]
    fn capability_declared_filesystem_effect_allows_file_call() {
        let errors = check_source(r#"fn main() ~ FileSystem { read_file("ops.txt"); }"#);

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    #[test]
    fn capability_c_runtime_filesystem_call_requires_filesystem_effect() {
        let errors = check_source(
            r#"
            extern "C" {
                fn build_file_exists(path: &str) -> bool;
            }

            fn main() {
                build_file_exists("ops.txt");
            }
            "#,
        );

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UnhandledEffect { effect_name, .. } if effect_name == "FileSystem"
            )),
            "expected FileSystem effect error, got {errors:#?}"
        );
        assert!(
            errors.iter().any(|err| err

                .notes
                .iter()
                .any(|note| note.contains("build_file_exists"))),
            "expected diagnostic note naming build_file_exists, got {errors:#?}"
        );
    }

    #[test]
    fn capability_declared_filesystem_effect_allows_c_runtime_file_call() {
        let errors = check_source(
            r#"
            extern "C" {
                fn build_file_exists(path: &str) -> bool;
            }

            fn main() ~ FileSystem {
                build_file_exists("ops.txt");
            }
            "#,
        );

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    #[test]
    fn capability_wrong_declared_effect_does_not_allow_file_call() {
        let errors = check_source(r#"fn main() ~ Network { read_file("ops.txt"); }"#);

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UndeclaredEffect { effect_name, .. } if effect_name == "FileSystem"
            )),
            "expected undeclared FileSystem error, got {errors:#?}"
        );
    }

    #[test]
    fn capability_console_macro_requires_console_effect() {
        let errors = check_source(r#"fn main() { println!("ops"); }"#);

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UnhandledEffect { effect_name, .. } if effect_name == "Console"
            )),
            "expected Console effect error, got {errors:#?}"
        );
        assert!(
            errors
                .iter()
                .any(|err| err.notes.iter().any(|note| note.contains("println!"))),
            "expected diagnostic note naming println!, got {errors:#?}"
        );
    }

    #[test]
    fn capability_declared_console_effect_allows_console_macro() {
        let errors = check_source(r#"fn main() ~ Console { println!("ops"); }"#);

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    #[test]
    fn capability_direct_console_call_requires_console_effect() {
        let errors = check_source(r#"fn main() { println("ops"); }"#);

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UnhandledEffect { effect_name, .. } if effect_name == "Console"
            )),
            "expected Console effect error, got {errors:#?}"
        );
        assert!(
            errors
                .iter()
                .any(|err| err.notes.iter().any(|note| note.contains("println"))),
            "expected diagnostic note naming println, got {errors:#?}"
        );
    }

    #[test]
    fn capability_declared_console_effect_allows_direct_console_call() {
        let errors = check_source(r#"fn main() ~ Console { println("ops"); }"#);

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    #[test]
    fn capability_wrong_declared_effect_does_not_allow_console_macro() {
        let errors = check_source(r#"fn main() ~ Network { println!("ops"); }"#);

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UndeclaredEffect { effect_name, .. } if effect_name == "Console"
            )),
            "expected undeclared Console error, got {errors:#?}"
        );
    }

    #[test]
    fn capability_gpu_runtime_call_requires_gpu_effect() {
        let errors = check_source(r#"fn main() { build_vk_init(); }"#);

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UnhandledEffect { effect_name, .. } if effect_name == "Gpu"
            )),
            "expected Gpu effect error, got {errors:#?}"
        );
        assert!(
            errors
                .iter()
                .any(|err| err.notes.iter().any(|note| note.contains("build_vk_init"))),
            "expected diagnostic note naming build_vk_init, got {errors:#?}"
        );
    }

    #[test]
    fn capability_declared_gpu_effect_allows_gpu_runtime_call() {
        let errors = check_source(r#"fn main() ~ Gpu { build_vk_init(); }"#);

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    #[test]
    fn capability_c_runtime_graphics_call_requires_gpu_effect() {
        let errors = check_source(
            r#"
            extern "C" {
                fn build_gfx_init(width: i32, height: i32, title: &str) -> i32;
            }

            fn main() {
                build_gfx_init(800, 600, "BuildLang Triangle");
            }
            "#,
        );

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UnhandledEffect { effect_name, .. } if effect_name == "Gpu"
            )),
            "expected Gpu effect error, got {errors:#?}"
        );
        assert!(
            errors
                .iter()
                .any(|err| err.notes.iter().any(|note| note.contains("build_gfx_init"))),
            "expected diagnostic note naming build_gfx_init, got {errors:#?}"
        );
    }

    #[test]
    fn capability_declared_gpu_effect_allows_c_runtime_graphics_call() {
        let errors = check_source(
            r#"
            extern "C" {
                fn build_gfx_init(width: i32, height: i32, title: &str) -> i32;
            }

            fn main() ~ Gpu {
                build_gfx_init(800, 600, "BuildLang Triangle");
            }
            "#,
        );

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    #[test]
    fn capability_wrong_declared_effect_does_not_allow_gpu_runtime_call() {
        let errors = check_source(r#"fn main() ~ FileSystem { build_vk_init(); }"#);

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UndeclaredEffect { effect_name, .. } if effect_name == "Gpu"
            )),
            "expected undeclared Gpu error, got {errors:#?}"
        );
    }

    #[test]
    fn capability_foreign_call_requires_foreign_effect() {
        let errors = check_source(
            r#"
            extern "C" { fn touch(); }
            fn main() { touch(); }
            "#,
        );

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UnhandledEffect { effect_name, .. } if effect_name == "Foreign"
            )),
            "expected Foreign effect error, got {errors:#?}"
        );
        assert!(
            errors
                .iter()
                .any(|err| err.notes.iter().any(|note| note.contains("touch"))),
            "expected diagnostic note naming touch, got {errors:#?}"
        );
    }

    #[test]
    fn capability_foreign_static_requires_foreign_effect() {
        let errors = check_source(
            r#"
            extern "C" { static BUILD_ERRNO: i32; }
            fn main() { let code = BUILD_ERRNO; }
            "#,
        );

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UnhandledEffect { effect_name, .. } if effect_name == "Foreign"
            )),
            "expected Foreign effect error, got {errors:#?}"
        );
        assert!(
            errors
                .iter()
                .any(|err| err.notes.iter().any(|note| note.contains("BUILD_ERRNO"))),
            "expected diagnostic note naming BUILD_ERRNO, got {errors:#?}"
        );
    }

    #[test]
    fn capability_declared_foreign_effect_allows_foreign_static() {
        let errors = check_source(
            r#"
            extern "C" { static BUILD_ERRNO: i32; }
            fn main() ~ Foreign { let code = BUILD_ERRNO; }
            "#,
        );

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    #[test]
    fn check_summary_records_foreign_calls_as_direct_capabilities() {
        let source = r#"
            extern "C" { fn touch(); }
            fn main() ~ Foreign { touch(); }
        "#;
        let source_file = crate::lexer::SourceFile::new("foreign_summary_test.bld", source);
        let mut lexer = crate::lexer::Lexer::new(&source_file);
        let tokens = lexer.tokenize().expect("tokenize foreign summary fixture");
        let mut parser = crate::parser::Parser::new(&source_file, tokens);
        let module = parser.parse().expect("parse foreign summary fixture");

        let mut ctx = TypeContext::new();
        let mut checker = TypeChecker::new(&mut ctx);
        checker.check_module(&module);

        let summaries = checker.function_effect_summaries();
        assert_eq!(summaries.len(), 1);
        assert_eq!(summaries[0].function, "main");
        assert_eq!(summaries[0].declared_effects, vec!["Foreign"]);
        assert_eq!(
            summaries[0]
                .observed_capabilities
                .get("Foreign")
                .expect("Foreign capability should be observed")
                .iter()
                .cloned()
                .collect::<Vec<_>>(),
            vec!["touch"]
        );
        assert!(
            summaries[0].propagated_effects.is_empty(),
            "direct extern call should not be recorded as propagated: {summaries:#?}"
        );
    }

    #[test]
    fn check_summary_records_declared_effects_and_capability_sources() {
        let source = r#"fn main() ~ Console { println!("ops"); }"#;
        let source_file = crate::lexer::SourceFile::new("summary_test.bld", source);
        let mut lexer = crate::lexer::Lexer::new(&source_file);
        let tokens = lexer.tokenize().expect("tokenize summary fixture");
        let mut parser = crate::parser::Parser::new(&source_file, tokens);
        let module = parser.parse().expect("parse summary fixture");

        let mut ctx = TypeContext::new();
        let mut checker = TypeChecker::new(&mut ctx);
        checker.check_module(&module);

        let summaries = checker.function_effect_summaries();
        assert_eq!(summaries.len(), 1);
        assert_eq!(summaries[0].function, "main");
        assert_eq!(summaries[0].declared_effects, vec!["Console"]);
        assert_eq!(
            summaries[0]
                .observed_capabilities
                .get("Console")
                .expect("Console capability should be observed")
                .iter()
                .cloned()
                .collect::<Vec<_>>(),
            vec!["println!"]
        );
    }

    #[test]
    fn check_summary_separates_direct_and_propagated_capabilities() {
        let source = r#"
            fn load_config() ~ FileSystem {
                read_file("ops.txt");
            }

            fn main() ~ FileSystem {
                load_config();
            }
        "#;
        let source_file = crate::lexer::SourceFile::new("summary_test.bld", source);
        let mut lexer = crate::lexer::Lexer::new(&source_file);
        let tokens = lexer.tokenize().expect("tokenize summary fixture");
        let mut parser = crate::parser::Parser::new(&source_file, tokens);
        let module = parser.parse().expect("parse summary fixture");

        let mut ctx = TypeContext::new();
        let mut checker = TypeChecker::new(&mut ctx);
        checker.check_module(&module);
        assert!(
            checker.errors().is_empty(),
            "expected clean type check, got {:#?}",
            checker.errors()
        );

        let summaries = checker.function_effect_summaries();
        let load_config = summaries
            .iter()
            .find(|summary| summary.function == "load_config")
            .expect("load_config summary");
        assert_eq!(
            load_config
                .observed_capabilities
                .get("FileSystem")
                .cloned()
                .unwrap_or_default()
                .into_iter()
                .collect::<Vec<_>>(),
            vec!["read_file".to_string()]
        );
        assert!(
            load_config.propagated_effects.is_empty(),
            "direct boundary should not report propagated callees"
        );

        let main = summaries
            .iter()
            .find(|summary| summary.function == "main")
            .expect("main summary");
        assert!(
            main.observed_capabilities.is_empty(),
            "caller should not report callee helper as direct IO"
        );
        assert_eq!(
            main.propagated_effects
                .get("FileSystem")
                .cloned()
                .unwrap_or_default()
                .into_iter()
                .collect::<Vec<_>>(),
            vec!["load_config".to_string()]
        );
    }

    #[test]
    fn check_summary_records_console_macro_as_direct_not_propagated() {
        let source = r#"fn main() ~ Console { println!("ops"); }"#;
        let source_file = crate::lexer::SourceFile::new("summary_test.bld", source);
        let mut lexer = crate::lexer::Lexer::new(&source_file);
        let tokens = lexer.tokenize().expect("tokenize summary fixture");
        let mut parser = crate::parser::Parser::new(&source_file, tokens);
        let module = parser.parse().expect("parse summary fixture");

        let mut ctx = TypeContext::new();
        let mut checker = TypeChecker::new(&mut ctx);
        checker.check_module(&module);
        assert!(
            checker.errors().is_empty(),
            "expected clean type check, got {:#?}",
            checker.errors()
        );

        let main = checker
            .function_effect_summaries()
            .iter()
            .find(|summary| summary.function == "main")
            .expect("main summary");
        assert_eq!(
            main.observed_capabilities
                .get("Console")
                .cloned()
                .unwrap_or_default()
                .into_iter()
                .collect::<Vec<_>>(),
            vec!["println!".to_string()]
        );
        assert!(
            main.propagated_effects.is_empty(),
            "macro capability should remain direct provenance"
        );
    }

    #[test]
    fn check_summaries_reset_between_modules() {
        let first = r#"fn main() ~ Console { println!("ops"); }"#;
        let second = r#"fn helper() {}"#;

        let parse_module = |name: &str, source: &str| {
            let source_file = crate::lexer::SourceFile::new(name, source);
            let mut lexer = crate::lexer::Lexer::new(&source_file);
            let tokens = lexer.tokenize().expect("tokenize summary fixture");
            let mut parser = crate::parser::Parser::new(&source_file, tokens);
            parser.parse().expect("parse summary fixture")
        };

        let mut ctx = TypeContext::new();
        let mut checker = TypeChecker::new(&mut ctx);
        checker.check_module(&parse_module("first.bld", first));
        assert_eq!(checker.function_effect_summaries().len(), 1);

        checker.check_module(&parse_module("second.bld", second));
        let summaries = checker.function_effect_summaries();
        assert_eq!(summaries.len(), 1);
        assert_eq!(summaries[0].function, "helper");
        assert!(summaries[0].declared_effects.is_empty());
        assert!(summaries[0].observed_capabilities.is_empty());
        assert!(summaries[0].propagated_effects.is_empty());
    }

    #[test]
    fn test_type_checker_creation() {
        let mut ctx = TypeContext::new();
        let checker = TypeChecker::new(&mut ctx);
        assert!(!checker.has_errors());
    }

    // =========================================================================
    // SELF-HOSTING BRICK 1: trait default methods, reference receivers, and
    // closures as method parameters. These patterns are required by the
    // self-hosted `core::cmp` (PartialEq::ne default) and `core::option`
    // (closure-taking combinators) modules.
    // =========================================================================

    /// A trait default method (`ne` calling `eq`) must resolve at a call site
    /// even when the `impl` only provides the required method. This is the
    /// exact shape of `PartialEq::ne` in `stdlib/core/cmp.bld`.
    #[test]
    fn trait_default_method_resolves_with_reference_receiver() {
        let errors = check_source(
            r#"
            trait MyEq {
                fn eq(&self, other: &Self) -> bool;
                fn ne(&self, other: &Self) -> bool {
                    !self.eq(other)
                }
            }

            struct P { x: i32 }

            impl MyEq for P {
                fn eq(&self, other: &P) -> bool {
                    self.x == other.x
                }
            }

            fn check() -> bool {
                let a = P { x: 1 };
                let b = P { x: 2 };
                a.ne(&b)
            }
            "#,
        );

        assert!(
            !errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UndefinedMethod { method, .. } if method == "ne"
            )),
            "default trait method `ne` should resolve, got {errors:#?}"
        );
        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    /// A by-value default method (`greet` calling `name`) must also resolve.
    #[test]
    fn trait_default_method_resolves_by_value() {
        let errors = check_source(
            r#"
            trait Greet {
                fn name(self) -> i32;
                fn greet(self) -> i32 {
                    self.name() + 1
                }
            }

            struct P { x: i32 }

            impl Greet for P {
                fn name(self) -> i32 { self.x }
            }

            fn check() -> i32 {
                let a = P { x: 1 };
                a.greet()
            }
            "#,
        );

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    /// A default method that does not call back into the trait should still
    /// resolve when the impl omits it.
    #[test]
    fn trait_default_method_standalone_resolves() {
        let errors = check_source(
            r#"
            trait Greet {
                fn base(&self) -> i32;
                fn doubled(&self) -> i32 {
                    42
                }
            }

            struct P { x: i32 }

            impl Greet for P {
                fn base(&self) -> i32 { self.x }
            }

            fn check() -> i32 {
                let a = P { x: 1 };
                a.doubled()
            }
            "#,
        );

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    /// An impl that overrides a default method must still resolve to the
    /// overriding signature (no regression from the default-method change).
    #[test]
    fn trait_default_method_override_resolves() {
        let errors = check_source(
            r#"
            trait Greet {
                fn base(&self) -> i32;
                fn doubled(&self) -> i32 { 0 }
            }

            struct P { x: i32 }

            impl Greet for P {
                fn base(&self) -> i32 { self.x }
                fn doubled(&self) -> i32 { self.x * 2 }
            }

            fn check() -> i32 {
                let a = P { x: 5 };
                a.doubled()
            }
            "#,
        );

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    /// Generic `&self` reference receivers in a generic impl, with one method
    /// calling another, mirror `Option::is_none` calling `Option::is_some`.
    #[test]
    fn generic_reference_receiver_methods_resolve() {
        let errors = check_source(
            r#"
            enum Opt<T> {
                None,
                Some(T),
            }

            impl<T> Opt<T> {
                fn is_some(&self) -> bool {
                    match self {
                        Opt::Some(_) => true,
                        Opt::None => false,
                    }
                }
                fn is_none(&self) -> bool {
                    !self.is_some()
                }
            }

            fn check() -> bool {
                let s: Opt<i32> = Opt::None;
                s.is_none()
            }
            "#,
        );

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    /// End-to-end shape of the self-hosted `core::cmp` traits: `PartialEq`
    /// with a defaulted `ne`, an `Ord`-style supertrait, reference receivers,
    /// and a default method that chains through the required method.
    #[test]
    fn cmp_style_trait_hierarchy_checks() {
        let errors = check_source(
            r#"
            trait PartialEq {
                fn eq(&self, other: &Self) -> bool;
                fn ne(&self, other: &Self) -> bool {
                    !self.eq(other)
                }
            }

            trait Ord: PartialEq {
                fn cmp(&self, other: &Self) -> i32;
                fn max_by(self, other: Self) -> Self;
            }

            struct N { v: i32 }

            impl PartialEq for N {
                fn eq(&self, other: &N) -> bool {
                    self.v == other.v
                }
            }

            impl Ord for N {
                fn cmp(&self, other: &N) -> i32 {
                    if self.v < other.v {
                        -1
                    } else if self.ne(other) {
                        1
                    } else {
                        0
                    }
                }
                fn max_by(self, other: N) -> N {
                    if self.cmp(&other) < 0 { other } else { self }
                }
            }

            fn check() -> i32 {
                let a = N { v: 1 };
                let b = N { v: 2 };
                let m = a.max_by(b);
                m.v
            }
            "#,
        );

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    /// Soundness boundary: a trait default method must NOT resolve on a type
    /// that does not implement the trait. The default-method fix only applies
    /// when a matching impl exists.
    #[test]
    fn trait_default_method_does_not_resolve_without_impl() {
        let errors = check_source(
            r#"
            trait MyEq {
                fn eq(&self, other: &Self) -> bool;
                fn ne(&self, other: &Self) -> bool {
                    !self.eq(other)
                }
            }

            struct P { x: i32 }
            struct Q { y: i32 }

            impl MyEq for P {
                fn eq(&self, other: &P) -> bool { self.x == other.x }
            }

            fn check() -> bool {
                let a = Q { y: 1 };
                let b = Q { y: 2 };
                a.ne(&b)
            }
            "#,
        );

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UndefinedMethod { method, .. } if method == "ne"
            )),
            "default method `ne` must not resolve on a non-implementing type, got {errors:#?}"
        );
    }

    /// Closures passed as method parameters (both `impl Trait` and an explicit
    /// `F: FnOnce` bound), chained, mirror `Option::map` / `Option::and_then`.
    #[test]
    fn closures_as_method_parameters_resolve() {
        let errors = check_source(
            r#"
            enum Opt<T> {
                None,
                Some(T),
            }

            impl<T> Opt<T> {
                fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Opt<U> {
                    match self {
                        Opt::Some(x) => Opt::Some(f(x)),
                        Opt::None => Opt::None,
                    }
                }
                fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool {
                    match self {
                        Opt::Some(x) => f(x),
                        Opt::None => false,
                    }
                }
                fn unwrap_or(self, fallback: T) -> T {
                    match self {
                        Opt::Some(x) => x,
                        Opt::None => fallback,
                    }
                }
            }

            fn check() -> i32 {
                let s = Opt::Some(10);
                s.map(|x| x + 1).unwrap_or(0)
            }
            "#,
        );

        assert!(errors.is_empty(), "expected no errors, got {errors:#?}");
    }

    // ── Trait-method resolution on a generic type parameter via its bound ──
    //
    // These tests cover self-hosting brick 2: a call `x.method()` where `x: T`
    // and `T` carries a trait bound providing `method` (inline, where-clause, or
    // from an enclosing `impl<T: Trait>`) must resolve through that bound.
    //
    // Known remaining gaps (intentionally NOT addressed by this brick):
    //   1. Generic *inherent*-impl method bodies are deferred and never
    //      type-checked (see `check_inherent_impl`, the `impl_is_generic`
    //      skip). Method calls on `T` there are not checked at all, so they
    //      neither resolve nor error until monomorphization.
    //   2. Method resolution on an array slice `self[..]` typed as the concrete
    //      slice `[T]` inside `impl Ord for [T; N]` (stdlib `core::cmp`,
    //      `self[..].cmp(&other[..])`) still fails with `[T] has no method cmp`.
    //      That is concrete-slice-type resolution, distinct from the
    //      type-parameter-bound resolution fixed here.

    #[test]
    fn impl_method_resolves_trait_method_on_bounded_type_param() {
        // Inside `impl<T: Foo> Foo for Wrap<T>`, a call `inner.bar()` where
        // `inner: T` must resolve `bar` through the impl-level bound `T: Foo`.
        let errors = check_source(
            r#"
            trait Foo {
                fn bar(&self) -> i32;
            }

            struct Wrap<T>(T);

            impl<T: Foo> Foo for Wrap<T> {
                fn bar(&self) -> i32 {
                    let inner: T = make();
                    inner.bar()
                }
            }

            fn make<T>() -> T {
                make()
            }
            "#,
        );

        assert!(
            !errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UndefinedMethod { method, .. } if method == "bar"
            )),
            "expected `bar` to resolve through impl bound `T: Foo`, got {errors:#?}"
        );
    }

    #[test]
    fn impl_method_resolves_trait_method_on_slice_element() {
        // Inside `impl<T: Foo> Foo for [T]`, indexing yields a `T`; calling a
        // bound trait method on it must resolve through `T: Foo`.
        let errors = check_source(
            r#"
            trait Foo {
                fn bar(&self) -> i32;
            }

            impl<T: Foo> Foo for [T] {
                fn bar(&self) -> i32 {
                    self[0].bar()
                }
            }
            "#,
        );

        assert!(
            !errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UndefinedMethod { method, .. } if method == "bar"
            )),
            "expected `bar` to resolve on `[T]` element through bound `T: Foo`, got {errors:#?}"
        );
    }

    #[test]
    fn impl_method_resolves_trait_method_via_where_clause_bound() {
        // The bound is supplied through a where-clause instead of inline.
        let errors = check_source(
            r#"
            trait Foo {
                fn bar(&self) -> i32;
            }

            struct Wrap<T>(T);

            impl<T> Foo for Wrap<T>
            where
                T: Foo,
            {
                fn bar(&self) -> i32 {
                    let inner: T = make();
                    inner.bar()
                }
            }

            fn make<T>() -> T {
                make()
            }
            "#,
        );

        assert!(
            !errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UndefinedMethod { method, .. } if method == "bar"
            )),
            "expected `bar` to resolve through where-clause bound `T: Foo`, got {errors:#?}"
        );
    }

    #[test]
    fn unbounded_type_param_method_call_still_errors() {
        // Negative case in a CHECKED context: a trait-impl method body (which
        // is type-checked, unlike deferred generic-function bodies) calls a
        // method that none of `T`'s bounds provide. `T: Other` exists but does
        // not supply `missing`, so resolution must still reject the call.
        let errors = check_source(
            r#"
            trait Foo {
                fn bar(&self) -> i32;
            }

            trait Other {
                fn other(&self) -> i32;
            }

            struct Wrap<T>(T);

            impl<T: Other> Foo for Wrap<T> {
                fn bar(&self) -> i32 {
                    let inner: T = make();
                    inner.missing()
                }
            }

            fn make<T>() -> T {
                make()
            }
            "#,
        );

        assert!(
            errors.iter().any(|err| matches!(
                &err.error,
                TypeError::UndefinedMethod { method, .. } if method == "missing"
            )),
            "expected `missing` to be unresolved when no bound provides it, got {errors:#?}"
        );
    }

    // =========================================================================
    // UNIT-ANNOTATED NUMERIC TYPES (`f64<m/s>`, experimental) -- W6 checker
    // slice one. All dimension math below is the shipped `units` algebra
    // (units.rs, unmodified); these tests only prove it is correctly wired
    // into the checker's unifier and `infer_binary`.
    // =========================================================================

    mod unit_annotated_types {
        use super::*;

        fn unit_errors(errors: &[TypeErrorWithSpan]) -> Vec<&TypeError> {
            errors
                .iter()
                .map(|e| &e.error)
                .filter(|e| {
                    matches!(
                        e,
                        TypeError::UnitMismatch { .. } | TypeError::UnitOperationMismatch { .. }
                    )
                })
                .collect()
        }

        #[test]
        fn mismatched_add_refused_with_operation_wording() {
            let errors = check_source(
                "fn main() { let d: f64<m> = 3.0; let t: f64<s> = 1.0; let x = d + t; }",
            );
            assert_eq!(errors.len(), 1, "expected exactly one error: {errors:#?}");
            match &errors[0].error {
                TypeError::UnitOperationMismatch {
                    operation,
                    left,
                    right,
                } => {
                    assert_eq!(*operation, "add");
                    assert_eq!(left, "m");
                    assert_eq!(right, "s");
                }
                other => panic!("expected UnitOperationMismatch, got {other:?}"),
            }
            assert_eq!(
                errors[0].error.to_string(),
                "unit mismatch: cannot add `m` and `s` (dimensions differ)"
            );
        }

        #[test]
        fn mismatched_subtract_refused_with_operation_wording() {
            let errors = check_source(
                "fn main() { let d: f64<m> = 3.0; let t: f64<s> = 1.0; let x = d - t; }",
            );
            let unit_errs = unit_errors(&errors);
            assert_eq!(unit_errs.len(), 1, "{errors:#?}");
            match unit_errs[0] {
                TypeError::UnitOperationMismatch { operation, .. } => {
                    assert_eq!(*operation, "subtract")
                }
                other => panic!("expected UnitOperationMismatch, got {other:?}"),
            }
        }

        #[test]
        fn mismatched_compare_refused_with_operation_wording() {
            let errors = check_source(
                "fn main() { let d: f64<m> = 3.0; let t: f64<s> = 1.0; let x = d < t; }",
            );
            let unit_errs = unit_errors(&errors);
            assert_eq!(unit_errs.len(), 1, "{errors:#?}");
            match unit_errs[0] {
                TypeError::UnitOperationMismatch { operation, .. } => {
                    assert_eq!(*operation, "compare")
                }
                other => panic!("expected UnitOperationMismatch, got {other:?}"),
            }
        }

        #[test]
        fn mismatched_assign_refused() {
            let errors =
                check_source("fn main() { let mut d: f64<m> = 3.0; let t: f64<s> = 1.0; d = t; }");
            let unit_errs = unit_errors(&errors);
            assert_eq!(unit_errs.len(), 1, "{errors:#?}");
            match unit_errs[0] {
                TypeError::UnitMismatch { expected, found } => {
                    assert_eq!(expected, "m");
                    assert_eq!(found, "s");
                }
                other => panic!("expected UnitMismatch, got {other:?}"),
            }
        }

        #[test]
        fn mismatched_let_annotation_refused() {
            let errors = check_source(
                "fn main() { let d: f64<m> = 3.0; let t: f64<s> = 1.0; \
                 let bad: f64<m> = d / t; }",
            );
            let unit_errs = unit_errors(&errors);
            assert_eq!(unit_errs.len(), 1, "{errors:#?}");
            match unit_errs[0] {
                TypeError::UnitMismatch { expected, found } => {
                    assert_eq!(expected, "m");
                    assert_eq!(found, "m/s");
                }
                other => panic!("expected UnitMismatch, got {other:?}"),
            }
        }

        #[test]
        fn mismatched_argument_refused() {
            let errors = check_source(
                "fn go(v: f64<m/s>) { } \
                 fn main() { let d: f64<m> = 3.0; go(d); }",
            );
            let unit_errs = unit_errors(&errors);
            assert_eq!(
                unit_errs.len(),
                1,
                "the unify backstop must catch a unit mismatch through a call \
                 argument: {errors:#?}"
            );
            assert!(matches!(unit_errs[0], TypeError::UnitMismatch { .. }));
        }

        #[test]
        fn derived_division_dimension_accepted() {
            let errors = check_source(
                "fn main() { let d: f64<m> = 3.0; let t: f64<s> = 1.0; \
                 let v: f64<m/s> = d / t; }",
            );
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
        }

        #[test]
        fn unannotated_product_stays_unconstrained_weak_mode() {
            // `None * None` must stay `None` (never invent a dimensionless
            // unit where neither operand wrote one): the product must still
            // mix freely with an explicitly dimensioned quantity, exactly
            // like the unannotated-mixing rule for Add.
            let errors = check_source(
                "fn main() { \
                    let a: f64 = 1.0; let b: f64 = 2.0; let p = a * b; \
                    let d: f64<m> = 3.0; let s = p + d; \
                 }",
            );
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
        }

        #[test]
        fn derived_multiplication_named_unit_equivalence_accepted() {
            // kg*m/s^2 (force) times m (length) is J (energy): proves
            // `multiply` and named-derived-unit equivalence end to end.
            let errors = check_source(
                "fn main() { let f: f64<kg*m/s^2> = 1.0; let len: f64<m> = 2.0; \
                 let e: f64<J> = f * len; }",
            );
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
        }

        #[test]
        fn same_dimension_add_rem_compare_accepted() {
            let errors = check_source(
                "fn main() { \
                    let d: f64<m> = 3.0; \
                    let sum: f64<m> = d + d; \
                    let r: f64<m> = d % d; \
                    let b: bool = d < d; \
                 }",
            );
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
        }

        #[test]
        fn scalar_times_unit_keeps_the_unit() {
            let errors =
                check_source("fn main() { let d: f64<m> = 3.0; let p: f64<m> = 2.0 * d; }");
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
        }

        #[test]
        fn unannotated_mixing_is_allowed_weak_mode() {
            // An unannotated float is UNCONSTRAINED (compatible with any
            // unit); full dimension variables are a deferred follow-up, not
            // this slice.
            let errors =
                check_source("fn main() { let d: f64<m> = 3.0; let p: f64 = 1.0; let s = d + p; }");
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
        }

        #[test]
        fn pow_with_literal_exponent_scales_the_unit() {
            let errors = check_source(
                "fn main() { let d: f64<m> = 3.0; let a: f64<m^2> = d ** 2.0;                  let b: f64<m^-1> = d ** -1; }",
            );
            assert!(errors.is_empty(), "{errors:#?}");
            let errors =
                check_source("fn main() { let d: f64<m> = 3.0; let bad: f64<m> = d ** 2.0; }");
            assert_eq!(unit_errors(&errors).len(), 1, "{errors:#?}");
        }

        #[test]
        fn pow_with_runtime_exponent_on_a_unit_is_refused() {
            let errors = check_source(
                "fn main() { let d: f64<m> = 3.0; let n: f64 = 2.0; let bad = d ** n; }",
            );
            assert!(
                errors.iter().any(|e| matches!(
                    &e.error,
                    TypeError::UnsupportedConstruct { construct, .. }
                        if construct.contains("non-literal exponent")
                )),
                "{errors:#?}"
            );
        }

        #[test]
        fn unary_minus_preserves_the_unit() {
            let errors = check_source("fn main() { let d: f64<m> = 3.0; let neg: f64<m> = -d; }");
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
        }

        #[test]
        fn cast_to_unit_annotated_float_reannotates() {
            // `infer_cast` resolves its target via `lower_type` (the exact
            // path `WithUnit` lowering hooks into), so `x as f64<m>` is a
            // deliberate re-annotation escape hatch: the cast's result
            // carries the annotated dimension from that point on. If casts
            // were instead unclaimed (target ignored), `d` would stay an
            // unconstrained plain float and this would produce no error.
            let errors = check_source(
                "fn main() { let p: f64 = 1.0; let d = p as f64<m>; let bad: f64<s> = d; }",
            );
            assert!(
                errors
                    .iter()
                    .any(|e| matches!(&e.error, TypeError::UnitMismatch { .. })),
                "the cast must have attached `m`, so binding it to `f64<s>` \
                 should mismatch: {errors:#?}"
            );
        }

        #[test]
        fn negative_exponent_form_normalizes_and_unifies() {
            // `m*s^-1` and `m/s` are the same dimension; an argument-passing
            // boundary must accept either spelling for the other.
            let errors = check_source(
                "fn go(v: f64<m/s>) { } \
                 fn main() { let d: f64<m*s^-1> = 3.0; go(d); }",
            );
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
        }

        // =====================================================================
        // TASK 5: Ty-EQUALITY AUDIT (the diffuse risk)
        //
        // `unit_dim` now participates in `Ty`'s derived `Eq`/`Hash`, so any
        // Ty-keyed lookup or equality-driven classification could newly
        // distinguish `f64<m>` from `f64`. The audit (see the commit body)
        // found ONE real hazard: `infer.rs`'s `dispatch_position_match`
        // (multiple-dispatch overload scoring) compared full `Ty` equality
        // for its Exact-match check, but codegen's mangled overload names
        // come from `MirType`, which has no unit slot. Two candidates
        // differing ONLY by unit annotation would therefore mangle to the
        // SAME C name -- a probed program confirmed the checker uniquely
        // resolving such a call while codegen emitted two colliding
        // `go_f64` definitions. Mitigated by stripping `unit_dim` at that
        // one comparison boundary, keeping the checker and codegen decision
        // procedures in agreement (see `dispatch_position_match`'s doc
        // comment). Every other Ty-keyed site audited (dispatch.rs itself
        // is MirType/generic, not Ty-keyed; traits.rs and context.rs's
        // `HashMap<Arc<str>, Ty>` tables are string-keyed, `Ty` only ever
        // the value) was safe as-is: no code change.
        // =====================================================================

        #[test]
        fn overload_set_differing_only_by_unit_is_ambiguous_not_silently_accepted() {
            let errors = check_source(
                "fn go(v: f64<m>) -> f64 { v } \
                 fn go(v: f64<s>) -> f64 { v + 1.0 } \
                 fn main() { let d: f64<m> = 3.0; let r = go(d); }",
            );
            assert!(
                errors
                    .iter()
                    .any(|e| matches!(&e.error, TypeError::AmbiguousMethod { .. })),
                "expected AmbiguousMethod (matching codegen's unit-blindness at the \
                 mangled name), not a silent unique resolution that a real C \
                 compiler would then reject as a duplicate definition: {errors:#?}"
            );
        }

        #[test]
        fn method_call_on_annotated_float_receiver_resolves() {
            // `.abs()` is dimension-preserving (identity on magnitude): a unit
            // riding on the receiver must not break method resolution, and
            // the result keeps the receiver's dimension (inherent float
            // methods return `receiver_ty` unchanged; see infer.rs's FLOAT
            // METHODS arm).
            let errors =
                check_source("fn main() { let d: f64<m> = -3.0; let a: f64<m> = d.abs(); }");
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
        }

        #[test]
        fn annotated_float_survives_a_generic_function() {
            let errors = check_source(
                "fn identity<T>(x: T) -> T { x } \
                 fn main() { let d: f64<m> = 3.0; let r: f64<m> = identity(d); }",
            );
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
        }

        // No negative (mismatch-catching) counterpart: the checker does not
        // thread a generic function's return type back to enforce anything
        // against the caller for ANY type, unit-carrying or not (confirmed:
        // the identical gap reproduces for a plain, unit-free
        // `let bad: i32 = identity(3.0);`, zero diagnostics). Pre-existing,
        // orthogonal to units, and out of scope for this slice ("if the
        // checker supports it" per the plan's Task 5 bullet -- it does not,
        // for generics in general). The positive test above is the honest
        // claim: units are not lost passing through, nothing stronger.

        // =====================================================================
        // Root and power lifting: `.sqrt()`, `.cbrt()`, `.powi()`, `.powf()`
        // scale the exponents; a root that leaves a fraction is refused.
        // =====================================================================

        #[test]
        fn roots_and_powers_scale_the_unit() {
            let errors = check_source(
                "fn main() {                     let area: f64<m*m> = 9.0; let side: f64<m> = area.sqrt();                     let vol: f64<m^3> = 27.0; let edge: f64<m> = vol.cbrt();                     let d: f64<m> = 3.0; let a: f64<m^2> = d.powi(2);                     let t: f64<s> = 2.0; let f: f64<Hz> = t.powf(-1.0);                     let g: f64<Hz> = t.recip();                  }",
            );
            assert!(errors.is_empty(), "{errors:#?}");
        }

        #[test]
        fn root_with_a_fractional_result_is_refused() {
            let errors = check_source("fn main() { let d: f64<m> = 4.0; let bad = d.sqrt(); }");
            assert!(
                errors
                    .iter()
                    .any(|e| matches!(&e.error, TypeError::UnitRootNotExact { .. })),
                "{errors:#?}"
            );
        }

        #[test]
        fn powi_with_runtime_exponent_on_a_unit_is_refused() {
            let errors = check_source(
                "fn main() { let d: f64<m> = 3.0; let n: i32 = 2; let bad = d.powi(n); }",
            );
            assert!(
                errors
                    .iter()
                    .any(|e| matches!(&e.error, TypeError::UnsupportedConstruct { .. })),
                "{errors:#?}"
            );
        }

        #[test]
        fn recip_inverts_the_unit() {
            let errors =
                check_source("fn main() { let t: f64<s> = 2.0; let bad: f64<s> = t.recip(); }");
            assert_eq!(unit_errors(&errors).len(), 1, "{errors:#?}");
        }

        #[test]
        fn trigonometry_of_a_dimensioned_value_is_refused() {
            for call in ["d.sin()", "d.exp()", "d.ln()", "d.log10()", "d.tanh()"] {
                let src = format!("fn main() {{ let d: f64<m> = 1.0; let bad = {call}; }}");
                let errors = check_source(&src);
                assert!(
                    errors
                        .iter()
                        .any(|e| matches!(&e.error, TypeError::UnitNotDimensionless { .. })),
                    "{call}: {errors:#?}"
                );
            }
            // A ratio of like quantities is dimensionless and is accepted.
            let errors = check_source(
                "fn main() { let d: f64<m> = 1.0; let r: f64<m> = 2.0; let ok = (d / r).sin(); }",
            );
            assert!(errors.is_empty(), "{errors:#?}");
        }

        #[test]
        fn binary_float_methods_need_matching_units() {
            for call in [
                "d.hypot(t)",
                "d.min(t)",
                "d.max(t)",
                "d.atan2(t)",
                "d.clamp(d, t)",
            ] {
                let src = format!(
                    "fn main() {{ let d: f64<m> = 1.0; let t: f64<s> = 2.0; let bad = {call}; }}"
                );
                let errors = check_source(&src);
                assert!(
                    errors
                        .iter()
                        .any(|e| matches!(&e.error, TypeError::UnitOperationMismatch { .. })),
                    "{call}: {errors:#?}"
                );
            }
        }

        #[test]
        fn sqrt_on_unannotated_receiver_is_unaffected() {
            // `unit_dim: None` must keep matching the identity-methods arm:
            // the refusal is guarded on `unit_dim.is_some()` and must not
            // fire for a plain, unit-free float.
            let errors = check_source("fn main() { let x: f64 = 9.0; let y: f64 = x.sqrt(); }");
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
            assert!(
                !errors
                    .iter()
                    .any(|e| matches!(&e.error, TypeError::UnsupportedConstruct { .. })),
                "unannotated `.sqrt()` must not be refused: {errors:#?}"
            );
        }

        #[test]
        fn identity_shaped_methods_still_preserve_the_unit() {
            // `.abs()`, `.floor()`, `.ceil()`, `.round()`, `.trunc()`,
            // `.fract()` genuinely preserve dimension (the numeric value
            // changes, the unit it is expressed in does not) and must stay
            // untouched by the sqrt/cbrt/powi/powf refusal.
            let errors = check_source(
                "fn main() { \
                    let d: f64<m> = -3.7; \
                    let a: f64<m> = d.abs(); \
                    let b: f64<m> = d.floor(); \
                    let c: f64<m> = d.ceil(); \
                    let e: f64<m> = d.round(); \
                    let f: f64<m> = d.trunc(); \
                    let g: f64<m> = d.fract(); \
                 }",
            );
            assert!(unit_errors(&errors).is_empty(), "{errors:#?}");
            assert!(
                !errors
                    .iter()
                    .any(|e| matches!(&e.error, TypeError::UnsupportedConstruct { .. })),
                "identity-shaped methods must not be refused: {errors:#?}"
            );
        }
    }
}

/// Exact fix for a function whose body uses capabilities its signature does
/// not declare: write every missing capability into the effect row in one
/// edit. With no row, `~ A + B ` goes just before the body's `{`; with a row,
/// ` + A + B` goes after its last entry. The fix widens authority, so the
/// diagnostics layer never marks it MachineApplicable.
pub(super) fn effect_row_fix(
    f: &ast::FnDef,
    missing: &[String],
) -> Option<crate::diagnostics::Fix> {
    if missing.is_empty() {
        return None;
    }
    let row = missing.join(" + ");
    let message = format!("add `{}` to the function's effect row", row);
    if let Some(last) = f.sig.effects.last() {
        let end = Span::new(last.span.end, last.span.end, last.span.source_id);
        if last.span.end.0 == 0 {
            return None;
        }
        return Some(crate::diagnostics::Fix::insert(
            message,
            end,
            format!(" + {}", row),
            true,
        ));
    }
    let body = f.body.as_ref()?;
    let at = body.span;
    if at.start.0 == 0 {
        return None;
    }
    let text = crate::lexer::source_text_for_id(at.source_id)?;
    let before = text.get(..at.start.0 as usize)?.chars().last();
    let insert = if before.map_or(false, char::is_whitespace) {
        format!("~ {} ", row)
    } else {
        format!(" ~ {} ", row)
    };
    Some(crate::diagnostics::Fix::insert(message, at, insert, true))
}