shape-vm 0.3.2

Stack-based bytecode virtual machine for the Shape programming language
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
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
//! Function and closure compilation

use crate::bytecode::{Instruction, OpCode, Operand};
use shape_ast::ast::{FunctionDef, Item, Span, Statement};
use shape_ast::error::{ErrorNote, Result, ShapeError, SourceLocation};
use std::collections::HashMap;

use super::{BytecodeCompiler, ParamPassMode};

/// Bridge from an LSDS [`shape_diagnostics::Diagnostic`] to a
/// [`ShapeError::SemanticError`].
///
/// Phase 2 vertical-slice helper: the LSDS is the source of truth, and
/// the legacy `ShapeError::SemanticError` is derived from it. Subsequent
/// sessions will introduce direct LSDS sinks (LSP renderer, MCP
/// renderer) and the bridge becomes optional. For now it preserves the
/// existing `[B00XX] body` message shape so downstream consumers
/// (test snapshots, terminal output) keep working without flag-day
/// migration.
pub(crate) fn diagnostic_to_shape_error(diag: &shape_diagnostics::Diagnostic) -> ShapeError {
    let message = format!("[{}] {}", diag.diagnostic_id, diag.message);
    let mut loc = SourceLocation::new(diag.location.line as usize, diag.location.col as usize);
    if let Some(file) = &diag.location.file {
        loc = loc.with_file(file.clone());
    }
    let span_len = diag.location.span[1].saturating_sub(diag.location.span[0]) as usize;
    if span_len > 0 {
        loc = loc.with_length(span_len);
    }
    for fix in &diag.fixes {
        loc.hints.push(fix.label.clone());
    }
    for note in &diag.notes {
        let note_loc = note.location.as_ref().map(|nl| {
            let mut sl = SourceLocation::new(nl.line as usize, nl.col as usize);
            if let Some(file) = &nl.file {
                sl = sl.with_file(file.clone());
            }
            sl
        });
        loc.notes.push(ErrorNote {
            message: note.message.clone(),
            location: note_loc,
        });
    }
    ShapeError::SemanticError {
        message,
        location: Some(loc),
    }
}

impl BytecodeCompiler {
    pub(super) fn explicit_param_pass_modes(
        params: &[shape_ast::ast::FunctionParameter],
    ) -> Vec<ParamPassMode> {
        params
            .iter()
            .map(|param| {
                if param.is_mut_reference {
                    ParamPassMode::ByRefExclusive
                } else if param.is_reference {
                    ParamPassMode::ByRefShared
                } else {
                    ParamPassMode::ByValue
                }
            })
            .collect()
    }

    pub(super) fn effective_function_like_pass_modes(
        &self,
        name: Option<&str>,
        params: &[shape_ast::ast::FunctionParameter],
        body: Option<&[shape_ast::ast::Statement]>,
    ) -> Vec<ParamPassMode> {
        if let Some(name) = name {
            if let Some(inferred_modes) = self.inferred_param_pass_modes.get(name) {
                let fallback_modes = Self::explicit_param_pass_modes(params);
                return fallback_modes
                    .into_iter()
                    .enumerate()
                    .map(|(idx, fallback)| inferred_modes.get(idx).copied().unwrap_or(fallback))
                    .collect();
            }
            if let Some(func_idx) = self.find_function(name)
                && let Some(func) = self.program.functions.get(func_idx)
            {
                let fallback_modes = Self::explicit_param_pass_modes(params);
                let registered_modes =
                    Self::pass_modes_from_ref_flags(&func.ref_params, &func.ref_mutates);
                return fallback_modes
                    .into_iter()
                    .enumerate()
                    .map(|(idx, fallback)| registered_modes.get(idx).copied().unwrap_or(fallback))
                    .collect();
            }
        }

        let mut modes = Self::explicit_param_pass_modes(params);
        let Some(body) = body else {
            return modes;
        };

        let caller_ref_params: Vec<_> = modes.iter().map(|mode| mode.is_reference()).collect();
        if !caller_ref_params.iter().any(|is_ref| *is_ref) {
            return modes;
        }

        let mut known_callable_modes: HashMap<String, Vec<ParamPassMode>> = self
            .program
            .functions
            .iter()
            .map(|func| {
                (
                    func.name.clone(),
                    Self::pass_modes_from_ref_flags(&func.ref_params, &func.ref_mutates),
                )
            })
            .collect();
        for scope in &self.locals {
            for (binding_name, local_idx) in scope {
                if let Some(pass_modes) = self.local_callable_pass_modes.get(local_idx) {
                    known_callable_modes.insert(binding_name.clone(), pass_modes.clone());
                }
            }
        }
        for (binding_name, binding_idx) in &self.module_bindings {
            if let Some(pass_modes) = self.module_binding_callable_pass_modes.get(binding_idx) {
                known_callable_modes.insert(binding_name.clone(), pass_modes.clone());
            }
        }

        let callee_ref_params: HashMap<String, Vec<bool>> = known_callable_modes
            .iter()
            .map(|(callee_name, pass_modes)| {
                (
                    callee_name.clone(),
                    pass_modes.iter().map(|mode| mode.is_reference()).collect(),
                )
            })
            .collect();
        let caller_name = name.unwrap_or("__function_expr__");
        let mut direct_mutates = vec![false; params.len()];
        let mut edges = Vec::new();
        let mut param_index_by_name = HashMap::new();
        for (idx, param) in params.iter().enumerate() {
            for param_name in param.get_identifiers() {
                param_index_by_name.insert(param_name, idx);
            }
        }
        for stmt in body {
            Self::analyze_statement_for_ref_mutation(
                stmt,
                caller_name,
                &param_index_by_name,
                &caller_ref_params,
                &callee_ref_params,
                &mut direct_mutates,
                &mut edges,
            );
        }
        for (_, caller_idx, callee_name, callee_idx) in edges {
            if known_callable_modes
                .get(&callee_name)
                .and_then(|modes| modes.get(callee_idx))
                .is_some_and(|mode| mode.is_exclusive())
                && let Some(flag) = direct_mutates.get_mut(caller_idx)
            {
                *flag = true;
            }
        }
        for (idx, direct_mutates) in direct_mutates.into_iter().enumerate() {
            if direct_mutates && modes.get(idx).is_some_and(|mode| mode.is_reference()) {
                modes[idx] = ParamPassMode::ByRefExclusive;
            }
        }

        modes
    }

    pub(super) fn compile_function(&mut self, func_def: &FunctionDef) -> Result<()> {
        // Validate annotation target kinds before compilation
        self.validate_annotation_targets(func_def)?;

        // In non-comptime mode (i.e., the outer/runtime compiler), `comptime fn`
        // helpers are only needed as AST in `function_defs` (for
        // collect_comptime_helpers). Skip compiling their bodies into the runtime
        // bytecode — doing so wastes space and leaks comptime-only code into the
        // runtime program where it can collide with runtime names.
        // In comptime mode (inside the mini-VM compiler), we DO compile them
        // because the mini-VM actually needs to execute them.
        if func_def.is_comptime && !self.comptime_mode {
            return Ok(());
        }

        // Skip compiling bodies of generic extend methods (those with
        // unresolved type params like T, U, K, V). Their AST is preserved
        // in `function_defs` for on-demand monomorphization at call sites.
        // Monomorphized specializations (where type params are substituted
        // with concrete types) are compiled normally.
        if func_def
            .type_params
            .as_ref()
            .is_some_and(|tps| !tps.is_empty())
        {
            return Ok(());
        }

        let mut effective_def = func_def.clone();
        let effective_pass_modes = self.effective_function_like_pass_modes(
            Some(&effective_def.name),
            &effective_def.params,
            Some(&effective_def.body),
        );
        for (idx, param) in effective_def.params.iter_mut().enumerate() {
            let effective_mode = effective_pass_modes
                .get(idx)
                .copied()
                .unwrap_or(ParamPassMode::ByValue);
            if param.type_annotation.is_none()
                && param.simple_name().is_some()
                && effective_mode.is_reference()
            {
                param.is_reference = true;
            }
            if effective_mode.is_exclusive() {
                param.is_mut_reference = true;
            }
        }
        let has_const_template_params = effective_def.params.iter().any(|p| p.is_const);
        let has_specialization_bindings = self
            .specialization_const_bindings
            .contains_key(&effective_def.name);

        // Execute comptime annotation handlers before compilation.
        // These run at compile time and can inspect/modify the target.
        // Template bases (functions with const parameters) skip comptime handler
        // execution until a concrete call-site specialization binds those consts.
        if !(has_const_template_params && !has_specialization_bindings)
            && self.execute_comptime_handlers(&mut effective_def)?
        {
            // Track removed functions so call sites produce a clear error
            // instead of jumping to an invalid entry point (stack overflow).
            self.removed_functions.insert(effective_def.name.clone());
            self.function_defs.remove(&effective_def.name);
            return Ok(());
        }

        // Keep the registry synchronized with the final mutated function shape.
        // This is used by expansion/inspection tooling.
        self.function_defs
            .insert(effective_def.name.clone(), effective_def.clone());

        // Lower every compiled function to MIR and run the shared borrow analysis.
        // MIR borrow analysis is the primary authority for functions with clean
        // lowering (no fallbacks). When authoritative, the lexical borrow checker
        // calls in helpers.rs are skipped. For functions where MIR lowering had
        // fallbacks, the lexical checker remains the active fallback.
        let mir_lowering = crate::mir::lowering::lower_function_detailed(
            &effective_def.name,
            &effective_def.params,
            &effective_def.body,
            effective_def.name_span,
        );
        let callee_summaries =
            self.build_callee_summaries(Some(&effective_def.name), &mir_lowering.all_local_names);
        let mut mir_analysis = crate::mir::solver::analyze(&mir_lowering.mir, &callee_summaries);
        mir_analysis.mutability_errors =
            crate::mir::lowering::compute_mutability_errors(&mir_lowering);
        crate::mir::repair::attach_repairs(&mut mir_analysis, &mir_lowering.mir);
        // MIR is the sole authority for borrow checking. Span-granular error
        // filtering: when lowering had fallbacks, only suppress errors whose span
        // overlaps a fallback span. Errors in cleanly-lowered regions pass through.
        let first_mutability_error = if mir_lowering.fallback_spans.is_empty() {
            mir_analysis.mutability_errors.first().cloned()
        } else {
            mir_analysis
                .mutability_errors
                .iter()
                .find(|e| !Self::span_overlaps_any(&e.span, &mir_lowering.fallback_spans))
                .cloned()
        };
        let first_mir_error = if mir_lowering.fallback_spans.is_empty() {
            mir_analysis.errors.first().cloned()
        } else {
            mir_analysis
                .errors
                .iter()
                .find(|e| !Self::span_overlaps_any(&e.span, &mir_lowering.fallback_spans))
                .cloned()
        };
        if let Some(summary) = mir_analysis.return_reference_summary.clone() {
            self.function_return_reference_summaries
                .insert(effective_def.name.clone(), summary.into());
        } else {
            self.function_return_reference_summaries
                .remove(&effective_def.name);
        }
        // Run storage planning pass: decide Direct / UniqueHeap / SharedCow / Reference
        // for each MIR slot based on closure captures, aliasing, and mutation.
        {
            let (closure_captures, mutable_captures) =
                crate::mir::storage_planning::collect_closure_captures(&mir_lowering.mir);

            // Gather binding semantics from the type tracker for each slot.
            let mut binding_semantics = std::collections::HashMap::new();
            for slot_idx in 0..mir_lowering.mir.num_locals {
                if let Some(sem) = self.type_tracker.get_local_binding_semantics(slot_idx) {
                    binding_semantics.insert(slot_idx, *sem);
                }
            }

            let planner_input = crate::mir::storage_planning::StoragePlannerInput {
                mir: &mir_lowering.mir,
                analysis: &mir_analysis,
                binding_semantics: &binding_semantics,
                closure_captures: &closure_captures,
                mutable_captures: &mutable_captures,
                had_fallbacks: mir_lowering.had_fallbacks,
                callee_summaries: Some(&self.function_borrow_summaries),
            };

            let storage_plan = crate::mir::storage_planning::plan_storage(&planner_input);

            self.mir_storage_plans
                .insert(effective_def.name.clone(), storage_plan);
        }

        // Run field-level definite-initialization and liveness analysis.
        // This is Phase 2 of the two-phase TypedObject hoisting design:
        // the AST pre-pass (Phase 1, in compiler_impl_part4.rs) collects
        // property assignments for initial schema sizing, and this MIR
        // analysis validates initialization flow and detects dead fields.
        let field_cfg = crate::mir::cfg::ControlFlowGraph::build(&mir_lowering.mir);
        let mut field_analysis = crate::mir::field_analysis::analyze_fields(
            &crate::mir::field_analysis::FieldAnalysisInput {
                mir: &mir_lowering.mir,
                cfg: &field_cfg,
            },
        );

        // Populate hoisting_recommendations from field names (MIR-authoritative).
        // Dead fields are pruned: if a field is written but never read, it's
        // excluded from the recommendation (schema compaction).
        for (slot_id, field_indices) in &field_analysis.hoisted_fields {
            let recommendations: Vec<(crate::mir::FieldIdx, String)> = field_indices
                .iter()
                .filter(|idx| !field_analysis.dead_fields.contains(&(*slot_id, **idx)))
                .filter_map(|idx| {
                    mir_lowering
                        .field_names
                        .get(idx)
                        .map(|name| (*idx, name.clone()))
                })
                .collect();
            if !recommendations.is_empty() {
                field_analysis
                    .hoisting_recommendations
                    .insert(*slot_id, recommendations);
            }
        }

        // Merge MIR-derived hoisted fields into the AST pre-pass hoisted_fields map.
        // MIR field analysis is authoritative per-function: it refines the AST
        // pre-pass (which over-hoists conservatively). Dead fields detected by MIR
        // are excluded from the hoisted list.
        for (slot_id, field_indices) in &field_analysis.hoisted_fields {
            if let Some(binding) = mir_lowering
                .binding_infos
                .iter()
                .find(|b| b.slot == *slot_id)
            {
                let var_name = &binding.name;
                let field_names: Vec<String> = field_indices
                    .iter()
                    // Prune dead fields from hoisted list (schema compaction)
                    .filter(|idx| !field_analysis.dead_fields.contains(&(*slot_id, **idx)))
                    .filter_map(|idx| mir_lowering.field_names.get(idx))
                    .cloned()
                    .collect();
                if !field_names.is_empty() {
                    // For function scope, use MIR list as authoritative (replace, don't merge)
                    self.hoisted_fields.insert(var_name.clone(), field_names);
                }
            }
        }

        self.mir_field_analyses
            .insert(effective_def.name.clone(), field_analysis);

        // Build span→point mapping for ownership decision lookups.
        // This lets the bytecode compiler translate AST spans (which it knows
        // at expression compile time) into MIR Points (which the ownership
        // decision API expects).
        {
            let mut span_to_point = HashMap::new();
            for block in mir_lowering.mir.iter_blocks() {
                for stmt in &block.statements {
                    span_to_point.entry(stmt.span).or_insert(stmt.point);
                }
            }
            self.mir_span_to_point
                .insert(effective_def.name.clone(), span_to_point);
        }

        // Extract and store borrow summary for interprocedural alias checking.
        // Thread previously-computed return-ownership modes into the inference
        // pass so call-through functions (fn wrap() { make() }) can inherit
        // their callee's mode instead of falling back to Unknown.
        let callee_return_modes = self.build_callee_return_modes(Some(&effective_def.name));
        let borrow_summary = crate::mir::solver::extract_borrow_summary_with_callees(
            &mir_lowering.mir,
            mir_analysis.return_reference_summary.clone(),
            &callee_return_modes,
        );
        let has_informative_summary = !borrow_summary.conflict_pairs.is_empty()
            || borrow_summary.return_summary.is_some()
            || borrow_summary.return_ownership_mode != crate::mir::ReturnOwnershipMode::Unknown
            // Any non-escaping closure-param bit is useful for the storage
            // planner (Closure Spec Phase B).
            || borrow_summary.closure_param_escapes.iter().any(|escapes| !escapes);
        if has_informative_summary {
            self.function_borrow_summaries
                .insert(effective_def.name.clone(), borrow_summary);
        } else {
            self.function_borrow_summaries.remove(&effective_def.name);
        }

        // Interprocedural alias checking: scan call sites in this function's MIR
        // for argument aliasing conflicts using stored callee summaries.
        let alias_errors =
            self.check_call_site_aliasing(&mir_lowering.mir, &mir_lowering.fallback_spans);
        let first_alias_error = alias_errors.first().cloned();
        mir_analysis.errors.extend(alias_errors);

        self.mir_functions
            .insert(effective_def.name.clone(), mir_lowering.mir);
        self.mir_borrow_analyses
            .insert(effective_def.name.clone(), mir_analysis);
        if let Some(error) = first_mutability_error.as_ref() {
            return Err(self.mir_mutability_error(error));
        }
        if let Some(error) = first_mir_error.as_ref() {
            return Err(self.mir_borrow_error(error));
        }
        if let Some(error) = first_alias_error.as_ref() {
            return Err(self.mir_borrow_error(error));
        }

        // Track whether __original__ alias is active so we can clean it up.
        let has_original_alias = self.function_aliases.contains_key("__original__");

        // Enable __* builtin access only for stdlib-origin functions
        // (or preserve if an enclosing stdlib compilation context already enabled it).
        let saved_allow_internal = self.allow_internal_builtins;
        self.allow_internal_builtins = saved_allow_internal
            || effective_def
                .declaring_module_path
                .as_deref()
                .is_some_and(|module_path| module_path.starts_with("std::"));

        // Check for annotation-based wrapping BEFORE compiling
        let annotations = self.find_compiled_annotations(&effective_def);
        if annotations.len() == 1 {
            // SAFETY invariant: the `len() == 1` guard above guarantees
            // `.next()` yields `Some`. This is a compile-time structural
            // invariant, not a runtime condition, so `expect` is appropriate.
            self.compile_wrapped_function(
                &effective_def,
                annotations.into_iter().next().expect("checked len == 1"),
            )?;
        } else if annotations.len() > 1 {
            self.compile_chained_annotations(&effective_def, annotations)?;
        } else {
            self.compile_function_body(&effective_def)?;
        }

        // Restore previous flag (safe for nested compilation).
        self.allow_internal_builtins = saved_allow_internal;

        // Cache MIR data in the Function struct for JIT v2 (MirToIR compilation).
        // Clone from the compiler's caches so both the compiler (for diagnostics/LSP)
        // and the JIT (via Function.mir_data) have access.
        if let Some(func_idx) = self.find_function(&effective_def.name) {
            let mir_opt = self.mir_functions.get(&effective_def.name).cloned();
            let borrow_opt = self.mir_borrow_analyses.get(&effective_def.name).cloned();
            let storage_opt = self.mir_storage_plans.get(&effective_def.name).cloned();
            if let (Some(mut mir), Some(borrow_analysis), Some(storage_plan)) =
                (mir_opt, borrow_opt, storage_opt)
            {
                // Back-patch MIR: replace ClosurePlaceholder and ClosureCapture
                // with resolved closure function names/IDs from bytecode compilation.
                if !self.closure_function_ids.is_empty() {
                    let mut closure_idx = 0;
                    let closure_ids = self.closure_function_ids.clone();
                    let mut has_capture = false;
                    for block in &mut mir.blocks {
                        for stmt in &mut block.statements {
                            let is_placeholder = matches!(
                                &stmt.kind,
                                crate::mir::types::StatementKind::Assign(
                                    _,
                                    crate::mir::types::Rvalue::Use(
                                        crate::mir::types::Operand::Constant(
                                            crate::mir::types::MirConstant::ClosurePlaceholder
                                        )
                                    )
                                )
                            );
                            if is_placeholder {
                                if has_capture {
                                    stmt.kind = crate::mir::types::StatementKind::Nop;
                                    has_capture = false;
                                } else if closure_idx < closure_ids.len() {
                                    let (ref name, _) = closure_ids[closure_idx];
                                    let slot = match &stmt.kind {
                                        crate::mir::types::StatementKind::Assign(p, _) => {
                                            p.root_local()
                                        }
                                        _ => unreachable!(),
                                    };
                                    stmt.kind = crate::mir::types::StatementKind::Assign(
                                        crate::mir::types::Place::Local(slot),
                                        crate::mir::types::Rvalue::Use(
                                            crate::mir::types::Operand::Constant(
                                                crate::mir::types::MirConstant::Function(
                                                    name.clone(),
                                                ),
                                            ),
                                        ),
                                    );
                                    closure_idx += 1;
                                }
                                continue;
                            }
                            if let crate::mir::types::StatementKind::ClosureCapture {
                                function_id,
                                ..
                            } = &mut stmt.kind
                            {
                                if closure_idx < closure_ids.len() {
                                    let (_, idx) = closure_ids[closure_idx];
                                    *function_id = Some(idx);
                                    closure_idx += 1;
                                    has_capture = true;
                                }
                            }
                        }
                    }
                }
                // Clear closure_function_ids for the next function
                self.closure_function_ids.clear();

                // ADR-006 §2.7.5 stamp-at-compile-time, Phase 3
                // cluster-0 Round 16 W17-narrow-follow-up-A: thread
                // the user-declared (or anonymous-inline) schema id
                // through every `StatementKind::ObjectStore` carrier
                // before the MIR ships to the JIT. The bytecode-side
                // `OpCode::NewTypedObject` operand carries the same
                // id; this back-patch aligns the two so the JIT's
                // `typed_object_alloc(schema_id, ...)` preserves the
                // user-declared schema identity.
                crate::compiler::mir_schema_threading::back_patch_schema_ids(
                    &mut mir,
                    &mut self.type_tracker,
                );

                self.program.functions[func_idx].mir_data =
                    Some(std::sync::Arc::new(crate::bytecode::MirFunctionData {
                        mir,
                        storage_plan,
                        borrow_analysis,
                    }));
            }
        }

        // Clean up __original__ alias after the replacement body is compiled.
        if has_original_alias {
            self.function_aliases.remove("__original__");
        }

        // Runtime lifecycle hooks (`on_define`, `metadata`) are invoked at
        // definition time by emitting top-level calls after function compilation.
        self.emit_annotation_lifecycle_calls(&effective_def)
    }

    /// Return the (message_body, hint) pair for a MIR borrow error kind.
    ///
    /// The message body does NOT include the `[B00XX]` prefix — that is
    /// prepended by `mir_borrow_error` using `BorrowErrorKind::code()` so
    /// the code mapping is defined in exactly one place.
    fn mir_borrow_error_message(
        &self,
        kind: crate::mir::analysis::BorrowErrorKind,
    ) -> (&'static str, &'static str) {
        match kind {
            crate::mir::analysis::BorrowErrorKind::ConflictSharedExclusive => (
                "cannot mutably borrow this value while shared borrows are active",
                "move the mutable borrow later, or end the shared borrow sooner",
            ),
            crate::mir::analysis::BorrowErrorKind::ConflictExclusiveExclusive => (
                "cannot mutably borrow this value because it is already borrowed",
                "end the previous mutable borrow before creating another one",
            ),
            crate::mir::analysis::BorrowErrorKind::ReadWhileExclusivelyBorrowed => (
                "cannot read this value while it is mutably borrowed",
                "read through the existing reference, or move the read after the borrow ends",
            ),
            crate::mir::analysis::BorrowErrorKind::WriteWhileBorrowed => (
                "cannot write to this value while it is borrowed",
                "move this write after the borrow ends",
            ),
            crate::mir::analysis::BorrowErrorKind::ReferenceEscape => (
                "cannot return or store a reference that outlives its owner",
                "return an owned value instead of a reference",
            ),
            crate::mir::analysis::BorrowErrorKind::ReferenceStoredInArray => (
                "cannot store a reference in an array — references are scoped borrows that cannot escape into collections. Use owned values instead",
                "store owned values in the array instead of references",
            ),
            crate::mir::analysis::BorrowErrorKind::ReferenceStoredInObject => (
                "cannot store a reference in an object or struct literal — references are scoped borrows that cannot escape into aggregate values. Use owned values instead",
                "store owned values in the object or struct instead of references",
            ),
            crate::mir::analysis::BorrowErrorKind::ReferenceStoredInEnum => (
                "cannot store a reference in an enum payload — references are scoped borrows that cannot escape into aggregate values. Use owned values instead",
                "store owned values in the enum payload instead of references",
            ),
            crate::mir::analysis::BorrowErrorKind::ReferenceEscapeIntoClosure => (
                "reference cannot escape into a closure",
                "capture an owned value instead of a reference",
            ),
            crate::mir::analysis::BorrowErrorKind::UseAfterMove => (
                "cannot use this value after it was moved",
                "clone the value before moving it, or stop using the original after the move",
            ),
            crate::mir::analysis::BorrowErrorKind::ExclusiveRefAcrossTaskBoundary => (
                "cannot move an exclusive reference across a task boundary",
                "keep the mutable reference within the current task or pass an owned value instead",
            ),
            crate::mir::analysis::BorrowErrorKind::SharedRefAcrossDetachedTask => (
                "cannot send a shared reference across a detached task boundary",
                "clone the value before sending it to a detached task, or use a structured task instead",
            ),
            crate::mir::analysis::BorrowErrorKind::InconsistentReferenceReturn => (
                "reference-returning functions must return a reference on every path from the same borrowed origin and borrow kind",
                "return a reference from the same borrowed origin on every path, or return owned values instead",
            ),
            crate::mir::analysis::BorrowErrorKind::CallSiteAliasConflict => (
                "cannot pass the same variable to multiple parameters that require non-aliased access",
                "use separate variables or clone one of the arguments",
            ),
            crate::mir::analysis::BorrowErrorKind::NonSendableAcrossTaskBoundary => (
                "cannot send a closure with mutable captures across a detached task boundary",
                "clone the captured values before spawning the task",
            ),
        }
    }

    fn mir_borrow_origin_note(&self, kind: crate::mir::analysis::BorrowErrorKind) -> &'static str {
        match kind {
            crate::mir::analysis::BorrowErrorKind::ConflictSharedExclusive
            | crate::mir::analysis::BorrowErrorKind::ConflictExclusiveExclusive
            | crate::mir::analysis::BorrowErrorKind::ReadWhileExclusivelyBorrowed
            | crate::mir::analysis::BorrowErrorKind::WriteWhileBorrowed => {
                "conflicting borrow originates here"
            }
            crate::mir::analysis::BorrowErrorKind::ReferenceEscape
            | crate::mir::analysis::BorrowErrorKind::ReferenceStoredInArray
            | crate::mir::analysis::BorrowErrorKind::ReferenceStoredInObject
            | crate::mir::analysis::BorrowErrorKind::ReferenceStoredInEnum
            | crate::mir::analysis::BorrowErrorKind::ReferenceEscapeIntoClosure => {
                "reference originates here"
            }
            crate::mir::analysis::BorrowErrorKind::UseAfterMove => "value was moved here",
            crate::mir::analysis::BorrowErrorKind::ExclusiveRefAcrossTaskBoundary
            | crate::mir::analysis::BorrowErrorKind::SharedRefAcrossDetachedTask => {
                "reference originates here"
            }
            crate::mir::analysis::BorrowErrorKind::InconsistentReferenceReturn => {
                "borrowed origin on another return path originates here"
            }
            crate::mir::analysis::BorrowErrorKind::CallSiteAliasConflict => {
                "conflicting argument originates here"
            }
            crate::mir::analysis::BorrowErrorKind::NonSendableAcrossTaskBoundary => {
                "closure with mutable captures originates here"
            }
        }
    }

    fn mir_borrow_error(&self, error: &crate::mir::analysis::BorrowError) -> ShapeError {
        // Phase 2 (ADR-006 §9): produce LSDS first; ShapeError::SemanticError
        // is derived from the LSDS so the wire-format truth lives in the
        // diagnostic struct, not in the message string. The vertical-slice
        // path covers all BorrowError kinds; subsequent sessions migrate
        // remaining diagnostic emission sites the same way.
        let diag = self.borrow_error_to_lsds(error);
        diagnostic_to_shape_error(&diag)
    }

    /// Convert a [`crate::mir::analysis::BorrowError`] into an LSDS
    /// [`shape_diagnostics::Diagnostic`].
    ///
    /// This is the **canonical** emission path for the B-series borrow /
    /// lifetime / aliasing diagnostics per ADR-006 §9. The diagnostic id
    /// matches `BorrowErrorKind::code()` (`"B0001"`..`"B0014"`); the
    /// message body is taken verbatim from `mir_borrow_error_message`
    /// (no `[B00XX]` prefix — that's the diagnostic_id field).
    ///
    /// Hints from the message table and the repair candidates surface as
    /// suggested fixes; the loan-origin span and last-use span surface as
    /// LSDS notes. When the kind is one of the type-mismatch-shaped
    /// variants (currently none — borrow errors are aliasing errors, not
    /// type errors), `expected`/`found` would be populated; for the
    /// B-series they are left `None`.
    pub(crate) fn borrow_error_to_lsds(
        &self,
        error: &crate::mir::analysis::BorrowError,
    ) -> shape_diagnostics::Diagnostic {
        let (body, default_hint) = self.mir_borrow_error_message(error.kind.clone());
        let code = error.kind.code();
        let primary = self.shape_loc_to_lsds(&self.span_to_source_location(error.span));

        let mut builder = shape_diagnostics::DiagnosticBuilder::new(
            code.as_str(),
            shape_diagnostics::Severity::Error,
            primary,
            body,
        )
        .rule("ADR-006-§9");

        // Default hint → top-ranked suggested fix. Confidence is a fixed
        // 0.5 placeholder; richer ranking is later-session scope.
        builder = builder.with_fix(shape_diagnostics::SuggestedFix::new(default_hint, 0.5));

        // Repair candidate → second suggested fix when present.
        if let Some(repair) = error.repairs.first() {
            builder =
                builder.with_fix(shape_diagnostics::SuggestedFix::new(repair.description.clone(), 0.7));
        }

        // Loan-origin note.
        let loan_loc = self.shape_loc_to_lsds(&self.span_to_source_location(error.loan_span));
        builder = builder.with_note(shape_diagnostics::DiagnosticNote::new(
            self.mir_borrow_origin_note(error.kind.clone()),
            Some(loan_loc),
        ));

        // Last-use note (when known).
        if let Some(last_use_span) = error.last_use_span {
            let last_use_loc =
                self.shape_loc_to_lsds(&self.span_to_source_location(last_use_span));
            builder = builder.with_note(shape_diagnostics::DiagnosticNote::new(
                "borrow is still needed here",
                Some(last_use_loc),
            ));
        }

        builder.build()
    }

    /// Bridge: existing `SourceLocation` (line/col + optional file) →
    /// LSDS `Location`. Spans collapse to `[0, 0]` when the existing
    /// location lacks length info; LSDS emitters with span data should
    /// populate the byte range directly.
    fn shape_loc_to_lsds(
        &self,
        loc: &shape_ast::error::SourceLocation,
    ) -> shape_diagnostics::Location {
        let span_start = 0;
        let span_end = loc.length.unwrap_or(0) as u32;
        shape_diagnostics::Location::new(
            loc.file.clone(),
            loc.line as u32,
            loc.column as u32,
            span_start,
            span_end,
        )
    }

    fn mir_mutability_error(&self, error: &crate::mir::analysis::MutabilityError) -> ShapeError {
        let mut location = self.span_to_source_location(error.span);
        if error.is_const {
            location
                .hints
                .push("const bindings cannot be reassigned".to_string());
        } else if error.is_explicit_let {
            location
                .hints
                .push("declare it as `let mut` if mutation is intended".to_string());
        } else {
            location
                .hints
                .push("this binding is immutable in this context".to_string());
        }
        location.notes.push(ErrorNote {
            message: "binding declared here".to_string(),
            location: Some(self.span_to_source_location(error.declaration_span)),
        });
        ShapeError::SemanticError {
            message: if error.is_const {
                format!("cannot assign to const binding '{}'", error.variable_name)
            } else {
                format!(
                    "cannot assign to immutable binding '{}'",
                    error.variable_name
                )
            },
            location: Some(location),
        }
    }

    /// Build callee return-reference summaries for interprocedural composition.
    ///
    /// Only includes names that are confirmed direct global function calls.
    /// Excludes names that shadow globals: locals, captures, module bindings,
    /// and the function being compiled (prevents stale self-summary).
    ///
    /// This mirrors the bytecode compiler's call resolution order
    /// (function_calls.rs:514-516): locals → captures → module bindings → globals.
    pub(crate) fn build_callee_summaries(
        &self,
        exclude_name: Option<&str>,
        mir_local_names: &std::collections::HashSet<String>,
    ) -> crate::mir::solver::CalleeSummaries {
        self.function_borrow_summaries
            .iter()
            .filter_map(|(name, summary)| {
                if exclude_name == Some(name.as_str()) {
                    return None;
                }
                // Mirror call resolution: locals → captures → module bindings → globals
                if mir_local_names.contains(name.as_str()) {
                    return None;
                }
                if self.mutable_closure_captures.contains_key(name.as_str()) {
                    return None;
                }
                if self.resolve_scoped_module_binding_name(name).is_some() {
                    return None;
                }
                summary
                    .return_summary
                    .as_ref()
                    .map(|s| (name.clone(), s.clone()))
            })
            .collect()
    }

    /// Gather previously-computed return-ownership modes for all module-level
    /// functions, for use by the return-ownership inference pass on the
    /// function currently being compiled (Phase 5.A). Excludes the function
    /// under compilation so we don't consume a stale self-summary.
    pub(crate) fn build_callee_return_modes(
        &self,
        exclude_name: Option<&str>,
    ) -> std::collections::HashMap<String, crate::mir::ReturnOwnershipMode> {
        self.function_borrow_summaries
            .iter()
            .filter_map(|(name, summary)| {
                if exclude_name == Some(name.as_str()) {
                    return None;
                }
                if summary.return_ownership_mode == crate::mir::ReturnOwnershipMode::Unknown {
                    return None;
                }
                Some((name.clone(), summary.return_ownership_mode))
            })
            .collect()
    }

    /// Check call sites in a function's MIR for interprocedural alias conflicts.
    /// Returns errors for each call where the same variable is passed to multiple
    /// parameters that the callee's borrow summary says must not alias.
    fn check_call_site_aliasing(
        &self,
        mir: &crate::mir::types::MirFunction,
        fallback_spans: &[Span],
    ) -> Vec<crate::mir::analysis::BorrowError> {
        use crate::mir::analysis::{BorrowError, BorrowErrorKind};
        use crate::mir::types::*;
        let mut errors = Vec::new();

        for block in mir.iter_blocks() {
            if let TerminatorKind::Call { func, args, .. } = &block.terminator.kind {
                // Determine callee name from the func operand
                let callee_name = match func {
                    Operand::Constant(MirConstant::Function(name)) => Some(name.as_str()),
                    _ => None,
                };

                let Some(callee_name) = callee_name else {
                    continue;
                };

                // Look up the callee's borrow summary
                let Some(summary) = self.function_borrow_summaries.get(callee_name) else {
                    continue;
                };

                // For each conflict pair, check if the corresponding args share root slots
                for &(i, j) in &summary.conflict_pairs {
                    if i >= args.len() || j >= args.len() {
                        continue;
                    }
                    let root_i = arg_root_slot(block, &args[i]);
                    let root_j = arg_root_slot(block, &args[j]);
                    if let (Some(ri), Some(rj)) = (root_i, root_j) {
                        if ri == rj {
                            let span = block.terminator.span;
                            // Skip if this span overlaps a fallback region
                            if !fallback_spans.is_empty()
                                && Self::span_overlaps_any(&span, fallback_spans)
                            {
                                continue;
                            }
                            errors.push(BorrowError {
                                kind: BorrowErrorKind::CallSiteAliasConflict,
                                span,
                                conflicting_loan: LoanId(0),
                                loan_span: span,
                                last_use_span: None,
                                repairs: Vec::new(),
                            });
                            break; // one error per call site
                        }
                    }
                }
            }
        }

        errors
    }

    /// Check if a span overlaps with any span in a list.
    /// Used for span-granular error filtering: errors in fallback regions are suppressed.
    fn span_overlaps_any(span: &Span, fallback_spans: &[Span]) -> bool {
        fallback_spans.iter().any(|fb| {
            // Overlap: not (span ends before fb starts || span starts after fb ends)
            !(span.end <= fb.start || span.start >= fb.end)
        })
    }

    fn synthetic_item_sequence_span(items: &[Item]) -> Span {
        items
            .first()
            .map(|item| match item {
                Item::Import(_, span)
                | Item::Export(_, span)
                | Item::Module(_, span)
                | Item::TypeAlias(_, span)
                | Item::Trait(_, span)
                | Item::Enum(_, span)
                | Item::Extend(_, span)
                | Item::Impl(_, span)
                | Item::Function(_, span)
                | Item::Query(_, span)
                | Item::VariableDecl(_, span)
                | Item::Assignment(_, span)
                | Item::Expression(_, span)
                | Item::Stream(_, span)
                | Item::Test(_, span)
                | Item::Optimize(_, span)
                | Item::AnnotationDef(_, span)
                | Item::StructType(_, span)
                | Item::DataSource(_, span)
                | Item::QueryDecl(_, span)
                | Item::Statement(_, span)
                | Item::Comptime(_, span)
                | Item::BuiltinTypeDecl(_, span)
                | Item::BuiltinFunctionDecl(_, span)
                | Item::ForeignFunction(_, span) => *span,
            })
            .unwrap_or(Span::DUMMY)
    }

    fn synthetic_mir_statements_for_items(items: &[Item]) -> Vec<Statement> {
        let mut body = Vec::new();
        for item in items {
            match item {
                Item::VariableDecl(var_decl, span) => {
                    body.push(Statement::VariableDecl(var_decl.clone(), *span));
                }
                Item::Assignment(assign, span) => {
                    body.push(Statement::Assignment(assign.clone(), *span));
                }
                Item::Expression(expr, span) => {
                    body.push(Statement::Expression(expr.clone(), *span));
                }
                Item::Statement(stmt, _) => body.push(stmt.clone()),
                Item::Export(export, span) => {
                    if let Some(source_decl) = &export.source_decl {
                        body.push(Statement::VariableDecl(source_decl.clone(), *span));
                    }
                }
                Item::Comptime(..)
                | Item::Function(..)
                | Item::Module(..)
                | Item::Import(..)
                | Item::TypeAlias(..)
                | Item::Trait(..)
                | Item::Enum(..)
                | Item::Extend(..)
                | Item::Impl(..)
                | Item::Query(..)
                | Item::Stream(..)
                | Item::Test(..)
                | Item::Optimize(..)
                | Item::AnnotationDef(..)
                | Item::StructType(..)
                | Item::DataSource(..)
                | Item::QueryDecl(..)
                | Item::BuiltinTypeDecl(..)
                | Item::BuiltinFunctionDecl(..)
                | Item::ForeignFunction(..) => {}
            }
        }
        body
    }

    pub(super) fn analyze_non_function_items_with_mir(
        &mut self,
        context_name: &str,
        items: &[Item],
    ) -> Result<()> {
        let body = Self::synthetic_mir_statements_for_items(items);
        if body.is_empty() {
            return Ok(());
        }

        let lowering = crate::mir::lowering::lower_function_detailed(
            context_name,
            &[],
            &body,
            Self::synthetic_item_sequence_span(items),
        );
        let callee_summaries = self.build_callee_summaries(None, &lowering.all_local_names);
        let mut analysis = crate::mir::solver::analyze(&lowering.mir, &callee_summaries);
        analysis.mutability_errors = crate::mir::lowering::compute_mutability_errors(&lowering);
        crate::mir::repair::attach_repairs(&mut analysis, &lowering.mir);

        // Span-granular error filtering: when lowering had fallbacks, only
        // suppress errors whose span overlaps a fallback span. Errors in
        // cleanly-lowered regions pass through even when other regions fell back.
        let first_mutability_error = if lowering.fallback_spans.is_empty() {
            analysis.mutability_errors.first().cloned()
        } else {
            analysis
                .mutability_errors
                .iter()
                .find(|e| !Self::span_overlaps_any(&e.span, &lowering.fallback_spans))
                .cloned()
        };
        let first_borrow_error = if lowering.fallback_spans.is_empty() {
            analysis.errors.first().cloned()
        } else {
            analysis
                .errors
                .iter()
                .find(|e| !Self::span_overlaps_any(&e.span, &lowering.fallback_spans))
                .cloned()
        };

        // Build span→point mapping for non-function MIR contexts too.
        {
            let mut span_to_point = HashMap::new();
            for block in lowering.mir.iter_blocks() {
                for stmt in &block.statements {
                    span_to_point.entry(stmt.span).or_insert(stmt.point);
                }
            }
            self.mir_span_to_point
                .insert(context_name.to_string(), span_to_point);
        }

        self.mir_functions
            .insert(context_name.to_string(), lowering.mir);
        self.mir_borrow_analyses
            .insert(context_name.to_string(), analysis);

        if let Some(error) = first_mutability_error.as_ref() {
            return Err(self.mir_mutability_error(error));
        }
        if let Some(error) = first_borrow_error.as_ref() {
            return Err(self.mir_borrow_error(error));
        }

        Ok(())
    }

    /// Core function body compilation (shared by normal functions and ___impl functions)
    pub(super) fn compile_function_body(&mut self, func_def: &FunctionDef) -> Result<()> {
        // Find function index
        let func_idx = self
            .program
            .functions
            .iter()
            .position(|f| f.name == func_def.name)
            .ok_or_else(|| ShapeError::RuntimeError {
                message: format!("Function not found: {}", func_def.name),
                location: None,
            })?;

        // Always emit a jump-over for the function body. This prevents the
        // VM from falling through into the function body during normal
        // execution at the call site.
        //
        // Two cases motivate this:
        //   1. Top-level: function defs are sandwiched between top-level
        //      statements. Without a jump, top-level execution would fall
        //      through into the body.
        //   2. Nested: a function compile triggered mid-body of another
        //      function (closure literal compiled by closures.rs, or a
        //      generic monomorphization triggered from inside a call-site
        //      compile_expr) emits its body into the live instruction
        //      stream. The outer function's `entry_point` was already set
        //      before the nested compile started, so any inlined body that
        //      precedes the outer's first emitted instruction would
        //      OVERLAP the outer's `entry_point`. Emitting a jump-over
        //      around the nested body keeps the outer's entry_point
        //      pointing at a Jump that skips the nested body, leaving the
        //      outer's actual logic intact.
        let jump_over = Some(self.emit_jump(OpCode::Jump, 0));

        // Save current state
        let saved_function = self.current_function;
        let saved_next_local = self.next_local;
        let saved_locals = std::mem::take(&mut self.locals);
        let saved_is_async = self.current_function_is_async;
        let saved_ref_locals = std::mem::take(&mut self.ref_locals);
        let saved_exclusive_ref_locals = std::mem::take(&mut self.exclusive_ref_locals);
        let saved_inferred_ref_locals = std::mem::take(&mut self.inferred_ref_locals);
        let saved_local_callable_pass_modes = std::mem::take(&mut self.local_callable_pass_modes);
        let saved_local_callable_return_reference_summaries =
            std::mem::take(&mut self.local_callable_return_reference_summaries);
        // Sweep phase 3c.x: snapshot/restore the closure return-type map
        // and array-callable map alongside the existing pass-mode/summary
        // maps. `compile_function` clears them via `clear_locals`-adjacent
        // logic at line ~1089; without snapshot/restore, any closure
        // recorded in the outer function before the inner-function
        // compile is invisible after it returns. Reproduces as
        // `let f = |…| …; let ra = f(4); ra + …` failing with
        // `unknown + int` because f's tracked return type was wiped when
        // a sibling closure compiled.
        let saved_local_callable_return_types =
            std::mem::take(&mut self.local_callable_return_types);
        let saved_local_array_callable_return_types =
            std::mem::take(&mut self.local_array_callable_return_types);
        // cluster-2-cw-IB-class-b: snapshot/restore retained closure
        // bodies alongside the existing callable-binding maps so the
        // outer function's `let f = |..|` peek doesn't leak into the
        // nested function compile (or get overwritten by a same-slot
        // binding inside the nested function).
        let saved_local_callable_closure_bodies =
            std::mem::take(&mut self.local_callable_closure_bodies);
        let saved_reference_value_locals = std::mem::take(&mut self.reference_value_locals);
        let saved_exclusive_reference_value_locals =
            std::mem::take(&mut self.exclusive_reference_value_locals);
        let saved_reference_value_module_bindings = self.reference_value_module_bindings.clone();
        let saved_exclusive_reference_value_module_bindings =
            self.exclusive_reference_value_module_bindings.clone();
        let saved_comptime_mode = self.comptime_mode;
        let saved_drop_locals = std::mem::take(&mut self.drop_locals);
        // Phase V1.1C fix: the ownership-aware drop-local scope stack must be
        // saved & restored in lockstep with `drop_locals`. Previously it
        // was left untouched, which caused the function's ownership drop
        // scope to leak back into the enclosing (main) scope. When main's
        // own `pop_drop_scope` ran at program end it emitted `DropLocal`
        // opcodes for slot indices that were only valid inside the callee's
        // frame — writing 0u64 into arbitrary caller stack slots and
        // corrupting results like `test()`'s DateTime return value.
        let saved_ownership_drop_locals = std::mem::take(&mut self.ownership_drop_locals);
        let saved_boxed_locals = std::mem::take(&mut self.boxed_locals);
        // Track A.1C.2: isolate per-function shared-local tracking so an
        // `AllocSharedLocal` emitted inside a nested function body does
        // not accidentally extend the outer function's DropSharedLocal
        // scope (parallel to the ownership/boxed restoration above).
        let saved_shared_locals = std::mem::take(&mut self.shared_locals);
        let saved_shared_drop_locals = std::mem::take(&mut self.shared_drop_locals);
        // Session 1 (Rust-move for let-mut captures): the moved-set is
        // function-scoped — a `let mut` binding moved into a closure in
        // the OUTER function must not leak its "moved" status into a
        // nested function compilation. Restore on exit, matching the
        // shared_locals discipline above.
        let saved_captured_let_mut_moved = std::mem::take(&mut self.captured_let_mut_moved);
        // Track A.1C.2: snapshot the outer function's local binding
        // semantics. `compile_function` calls `type_tracker.clear_locals`
        // below to prepare the nested function's own slot indexing, which
        // would otherwise erase the outer function's `var` / `let mut`
        // classification and leave the subsequent closure literals in
        // the outer scope unable to derive `CaptureKind`s. Restored after
        // the nested compilation completes.
        let saved_local_binding_semantics = self.type_tracker.snapshot_local_binding_semantics();
        // Sweep phase 3c.1: snapshot outer-function local types so
        // post-closure call sites in the outer scope can still resolve
        // outer-scope identifier types. `compile_function`'s
        // `clear_locals` below would otherwise erase entries like
        // `base: int` from `let base = 100`, breaking strict-typing's
        // closure-return-type inference for `let f = |x| x + base`.
        let saved_local_types = self.type_tracker.snapshot_local_types();
        let saved_param_locals = std::mem::take(&mut self.param_locals);
        let saved_function_params =
            std::mem::replace(&mut self.current_function_params, func_def.params.clone());
        let saved_current_function_return_reference_summary =
            self.current_function_return_reference_summary.clone();
        // Phase 4b Round 6 WS-1b W16.2-C residual: empty-array accumulators
        // are keyed by per-function local slot index — isolate them to this
        // function's compilation so a sibling function's slot index cannot
        // collide. `finalize_function_empty_array_accumulators` (called at
        // every exit point) surface-and-stops any that were never resolved,
        // then restores the saved map.
        let saved_empty_array_accumulators =
            std::mem::take(&mut self.empty_array_accumulators);
        // Per-function `v2_typed_array_locals` are also slot-index keyed;
        // isolate them so a promoted accumulator's typed-kind record cannot
        // bleed across function boundaries.
        let saved_v2_typed_array_locals =
            std::mem::take(&mut self.v2_typed_array_locals);

        // Set up isolated locals for function compilation
        self.current_function = Some(func_idx);
        self.current_function_is_async = func_def.is_async;
        self.current_function_return_reference_summary = self
            .function_return_reference_summaries
            .get(&func_def.name)
            .cloned();

        // If this is a `comptime fn`, mark the compilation context as comptime
        // so that calls to other `comptime fn` functions within the body are allowed.
        if func_def.is_comptime {
            self.comptime_mode = true;
        }
        self.locals = vec![HashMap::new()];
        self.type_tracker.clear_locals(); // Clear local type info for new function
        self.ref_locals.clear();
        self.exclusive_ref_locals.clear();
        self.inferred_ref_locals.clear();
        self.local_callable_pass_modes.clear();
        self.local_callable_return_reference_summaries.clear();
        self.local_callable_return_types.clear();
        self.local_callable_closure_bodies.clear();
        self.reference_value_locals.clear();
        self.exclusive_reference_value_locals.clear();
        self.immutable_locals.clear();
        self.param_locals.clear();
        // v0.3 WS-6: per-function local ConcreteType table — local slot
        // indices are per-function, so it must be cleared at each function
        // entry to avoid a stale prior-function entry colliding.
        self.current_function_local_concrete_types.clear();
        self.push_scope();
        self.push_drop_scope();
        self.next_local = 0;

        // Reset expression-level tracking to prevent stale values from previous
        // function compilations leaking into parameter binding
        self.last_expr_schema = None;
        self.last_expr_numeric_type = None;
        self.last_expr_type_info = None;

        // Set function entry point (AFTER the jump instruction)
        self.program.functions[func_idx].entry_point = self.program.current_offset();

        // Start blob builder for this function (snapshot global pool sizes).
        let saved_blob_builder = self.current_blob_builder.take();
        self.current_blob_builder = Some(super::FunctionBlobBuilder::new(
            func_def.name.clone(),
            self.program.current_offset(),
            self.program.constants.len(),
            self.program.strings.len(),
        ));

        let inferred_modes = self.inferred_param_pass_modes.get(&func_def.name).cloned();

        // Bind parameters as locals - destructure each parameter value
        // Parameters arrive in local slots 0, 1, 2, ... from caller
        for (idx, param) in func_def.params.iter().enumerate() {
            let effective_pass_mode = inferred_modes
                .as_ref()
                .and_then(|modes| modes.get(idx))
                .copied()
                .unwrap_or_else(|| {
                    if param.is_mut_reference {
                        ParamPassMode::ByRefExclusive
                    } else if param.is_reference {
                        ParamPassMode::ByRefShared
                    } else {
                        ParamPassMode::ByValue
                    }
                });

            // Load parameter value from its slot
            self.emit(Instruction::new(
                OpCode::LoadLocal,
                Some(Operand::Local(idx as u16)),
            ));
            // Destructure into bindings (self declares locals and binds them)
            self.compile_destructure_pattern(&param.pattern)?;
            self.apply_binding_semantics_to_pattern_bindings(
                &param.pattern,
                true,
                Self::binding_semantics_for_param(param, effective_pass_mode),
            );
            for (binding_name, _) in param.pattern.get_bindings() {
                if let Some(local_idx) = self.resolve_local(&binding_name) {
                    if param.is_const {
                        self.const_locals.insert(local_idx);
                        self.immutable_locals.insert(local_idx);
                    } else if matches!(effective_pass_mode, ParamPassMode::ByRefShared) {
                        self.immutable_locals.insert(local_idx);
                    }
                }
            }

            // Propagate parameter type annotations into local type tracker so
            // dot-access compiles to typed field ops (no runtime property fallback).
            if let Some(name) = param.pattern.as_identifier() {
                if let Some(local_idx) = self.resolve_local(name) {
                    if let Some(type_ann) = &param.type_annotation {
                        match type_ann {
                            shape_ast::ast::TypeAnnotation::Object(fields) => {
                                // W17.2-C §4.D.5 migration: route through
                                // typed-with-Any (NOT per-field lowering;
                                // schema layout changes from Any-uniform
                                // break downstream consumers that assume
                                // the legacy layout — same disposition as
                                // `extract_object_schema_id_from_annotation`
                                // at `expressions/function_calls.rs`).
                                // Per-field-typed schema layout migration
                                // is v0.4 W17.3+ territory. Verification-
                                // pass safety net via `__inline_obj_*`.
                                let typed_fields: Vec<(&str, shape_runtime::type_schema::FieldType)> =
                                    fields
                                        .iter()
                                        .map(|f| {
                                            (
                                                f.name.as_str(),
                                                shape_runtime::type_schema::FieldType::Any,
                                            )
                                        })
                                        .collect();
                                let schema_id = self
                                    .type_tracker
                                    .register_inline_object_schema_typed(&typed_fields);
                                let schema_name = self
                                    .type_tracker
                                    .schema_registry()
                                    .get_by_id(schema_id)
                                    .map(|s| s.name.clone())
                                    .unwrap_or_else(|| format!("__anon_{}", schema_id));
                                let info = crate::type_tracking::VariableTypeInfo::known(
                                    schema_id,
                                    schema_name,
                                );
                                self.type_tracker.set_local_type(local_idx, info);
                            }
                            _ => {
                                if let Some(type_name) =
                                    Self::tracked_type_name_from_annotation(type_ann)
                                {
                                    self.set_local_type_info(local_idx, &type_name);
                                }
                            }
                        }
                        // v0.3 WS-6: record the parameter's concrete type from
                        // its explicit annotation so the slot ConcreteType is
                        // available to the JIT MIR resolver. Without this a
                        // monomorphized function's struct/enum/Option/Result
                        // parameter slot stays unstamped and downstream
                        // ownership/field codegen mis-classifies it.
                        if let Some(ct) = crate::compiler::monomorphization::type_resolution::declared_annotation_concrete_type(self, type_ann) {
                            self.current_function_local_concrete_types.insert(local_idx, ct);
                        }
                        self.try_track_datatable_type(type_ann, local_idx, true)?;
                    } else {
                        // Mark as a param local with inferred type (no explicit annotation).
                        // storage_hint_for_expr will not trust these for typed Add emission.
                        self.param_locals.insert(local_idx);

                        // WS-9b: an unannotated parameter whose program-wide
                        // inferred type is an ANONYMOUS object (e.g.
                        // `aabb_overlaps(a, b)` where `a`/`b` were observed
                        // at a call site as the object literal `aabb(...)`
                        // returns) has no named schema — its hint name is
                        // the structural string `"{min_x: number, ...}"`,
                        // which `set_local_type_info` cannot match to a
                        // registered schema, so the slot would carry no
                        // `schema_id` and `param.field` would type as
                        // `unknown`. Register an inline `__inline_obj_*`
                        // schema from inference's proven per-field types and
                        // stamp the slot's `schema_id` — `infer_expr_type`'s
                        // `PropertyAccess` arm then resolves `a.min_x` to
                        // the proven field type via `tracker_schema_id_for_
                        // expr`, exactly the way a named-struct field
                        // resolves. The field types are inference output,
                        // never fabricated.
                        let object_fields = self
                            .inferred_param_object_fields
                            .get(&func_def.name)
                            .and_then(|fields| fields.get(idx))
                            .and_then(|entry| entry.clone());
                        let stamped_object_schema = object_fields.is_some();
                        if let Some(object_fields) = object_fields {
                            let typed_fields: Vec<(
                                &str,
                                shape_runtime::type_schema::FieldType,
                            )> = object_fields
                                .iter()
                                .map(|(n, ft)| (n.as_str(), ft.clone()))
                                .collect();
                            let schema_id = self
                                .type_tracker
                                .register_inline_object_schema_typed(&typed_fields);
                            let schema_name = self
                                .type_tracker
                                .schema_registry()
                                .get_by_id(schema_id)
                                .map(|s| s.name.clone())
                                .unwrap_or_else(|| format!("__anon_{}", schema_id));
                            self.type_tracker.set_local_type(
                                local_idx,
                                crate::type_tracking::VariableTypeInfo::known(
                                    schema_id,
                                    schema_name,
                                ),
                            );
                        }
                        // W14.2-G4-derefstore-drift fix (ADR-006 §2.7.13
                        // producer-side ref-chain stamp): for ref-params
                        // (`&x`) without type annotation, the program-wide
                        // type-inference pass at `infer_param_type_hints_
                        // from_types` widens int-only ref-param bodies to
                        // `"number"` because the engine's reference-erasure
                        // path drops the integer-literal pairing signal
                        // present in `x = x + 1`. The body-local heuristic
                        // `infer_param_type_from_body` recovers `"int"`
                        // from the literal pairing (closures.rs:43-50).
                        // Prefer the body-local heuristic for ref-params
                        // when the global inference produced the wider
                        // `"number"` — this re-stamps the ref-param's
                        // local-slot type tracker with the producer-side
                        // (caller's `let a = 0`) projected kind, matching
                        // the `RefTarget::Local { kind: Int64 }` carried
                        // through the ref chain. Without this re-stamp,
                        // the binop emitter at `expressions/binary_ops.rs:
                        // 880` coerces `x + 1` to `AddNumber` (Float64
                        // result), and the `DerefStore Local(x_slot)`
                        // executor at `executor/variables/mod.rs:2696`
                        // surfaces the §2.7.13 invariant violation
                        // (`debug_assert_eq!(val_kind, projected_kind)`)
                        // with `popped Float64, place Int64`.
                        let global_inferred = self
                            .inferred_param_type_hints
                            .get(&func_def.name)
                            .and_then(|hints| hints.get(idx))
                            .and_then(|hint| hint.clone());
                        let body_local_inferred = if param.is_reference {
                            crate::compiler::expressions::closures::infer_param_type_from_body(
                                name,
                                &func_def.body,
                            )
                            .as_ref()
                            .and_then(Self::tracked_type_name_from_annotation)
                        } else {
                            None
                        };
                        let inferred_type_name = match (
                            global_inferred.as_deref(),
                            body_local_inferred.as_deref(),
                        ) {
                            // Ref-param widening attractor: global says
                            // "number", body-local literal pairing says
                            // "int" (or another narrower primitive). The
                            // body-local signal observed the actual
                            // operand in `x op <int-literal>` —
                            // authoritative for the producer-side stamp.
                            (Some("number"), Some(local @ ("int" | "i8" | "i16" | "i32" | "i64"
                                | "u8" | "u16" | "u32" | "u64")))
                                if param.is_reference =>
                            {
                                Some(local.to_string())
                            }
                            _ => global_inferred,
                        };
                        if stamped_object_schema {
                            // WS-9b: the anonymous-object inline schema was
                            // already stamped above. `inferred_type_name`
                            // here would be the structural object string
                            // (`"{min_x: number, ...}"`); routing it through
                            // `set_local_type_info` would overwrite the
                            // schema-bearing `VariableTypeInfo::known` with a
                            // schema-less `VariableTypeInfo::named`, undoing
                            // the field-type resolution. Keep the schema
                            // stamp.
                        } else if let Some(type_name) = inferred_type_name {
                            self.set_local_type_info(local_idx, &type_name);
                            // Strict-typing-sweep: when inference produces a
                            // concrete primitive name, the param is no longer
                            // ambiguous — drop the param_locals guard so
                            // typed binary-op dispatch trusts the type info.
                            if Self::tracker_type_name_is_primitive(&type_name) {
                                self.param_locals.remove(&local_idx);
                            }
                        } else if let Some(ann) =
                            crate::compiler::expressions::closures::infer_param_type_from_body(
                                name,
                                &func_def.body,
                            )
                        {
                            // Strict-typing-sweep: inference engine may
                            // have produced a Type::Variable (which
                            // inferred_type_to_hint_name discards).
                            // Fall back to a body-level literal-pairing
                            // scan — the same heuristic closure
                            // synthesis uses — so e.g.
                            // `function add_ten(x) { x + 10 }` types
                            // x as int from the literal pairing.
                            if let Some(type_name) =
                                Self::tracked_type_name_from_annotation(&ann)
                            {
                                self.set_local_type_info(local_idx, &type_name);
                                if Self::tracker_type_name_is_primitive(&type_name) {
                                    self.param_locals.remove(&local_idx);
                                }
                            }
                        }
                    }
                }
            }
        }

        // Mark reference parameters in ref_locals so identifier/assignment compilation
        // emits DerefLoad/DerefStore/SetIndexRef instead of LoadLocal/StoreLocal/SetLocalIndex.
        // Also track which ref_locals were INFERRED (not explicitly declared) so that
        // closure capture can distinguish true borrows from pass-by-ref optimizations.
        for (idx, param) in func_def.params.iter().enumerate() {
            if param.is_reference {
                self.ref_locals.insert(idx as u16);
                if param.is_mut_reference {
                    self.exclusive_ref_locals.insert(idx as u16);
                }
                // A param is "inferred ref" if it has no type annotation and no explicit
                // mut reference — the compiler's pass-mode inference set is_reference.
                let was_inferred = param.type_annotation.is_none()
                    && !param.is_mut_reference
                    && inferred_modes
                        .as_ref()
                        .and_then(|modes| modes.get(idx))
                        .map_or(false, |mode| mode.is_reference());
                if was_inferred {
                    self.inferred_ref_locals.insert(idx as u16);
                }
            }
        }

        // If self is a DataTable closure, tag the first user parameter as RowView
        if let Some((schema_id, type_name)) = self.closure_row_schema.take() {
            let row_param_slot = func_def
                .params
                .first()
                .and_then(|param| param.pattern.as_identifier())
                .and_then(|name| self.resolve_local(name))
                .unwrap_or_else(|| self.program.functions[func_idx].captures_count);

            self.type_tracker.set_local_type(
                row_param_slot,
                crate::type_tracking::VariableTypeInfo::row_view(schema_id, type_name),
            );
        }

        // Parameter defaults: only check parameters that have a default value.
        // Required parameters are guaranteed to have a real value from the caller
        // (arity is enforced at call sites), so no unit-check is needed for them.
        for (idx, param) in func_def.params.iter().enumerate() {
            if let Some(default_expr) = &param.default_value {
                // Check if the caller omitted this argument (sent unit sentinel).
                // Stage 2.6.5.2: typed IsNull replaces `emit_unit; Eq`. IsNull
                // matches both None and Unit absence sentinels, so a single
                // typed instruction covers what previously took three.
                self.emit(Instruction::new(
                    OpCode::LoadLocal,
                    Some(Operand::Local(idx as u16)),
                ));
                self.emit(Instruction::simple(OpCode::IsNull));

                let skip_jump = self.emit_jump(OpCode::JumpIfFalse, 0);

                // Caller omitted this arg — fill in the default value
                self.compile_expr(default_expr)?;
                self.emit(Instruction::new(
                    OpCode::StoreLocal,
                    Some(Operand::Local(idx as u16)),
                ));

                self.patch_jump(skip_jump);
            }
        }

        // Compile function body with implicit return support
        let body_len = func_def.body.len();
        for (idx, stmt) in func_def.body.iter().enumerate() {
            let is_last = idx == body_len - 1;

            // Check if the last statement is an expression - if so, use implicit return
            if is_last {
                match stmt {
                    Statement::Expression(expr, _) => {
                        // Compile expression and keep value on stack for implicit return.
                        if self.current_function_return_reference_summary.is_some() {
                            self.compile_expr_preserving_refs(expr)?;
                        } else {
                            self.compile_expr(expr)?;
                        }
                        // Emit drops for function-level locals before returning
                        let total_scopes = self.drop_locals.len();
                        if total_scopes > 0 {
                            self.emit_drops_for_early_exit(total_scopes)?;
                        }
                        self.emit_return_value_with_ownership();
                        // Skip the fallback return below since we've already returned
                        // Update function locals count
                        self.program.functions[func_idx].locals_count = self.next_local;
                        self.capture_function_local_storage_hints(func_idx);
                        // Finalize blob builder and store completed blob
                        self.finalize_current_blob(func_idx);
                        self.current_blob_builder = saved_blob_builder;
                        // Restore state
                        self.drop_locals = saved_drop_locals;
                        self.ownership_drop_locals = saved_ownership_drop_locals;
                        self.boxed_locals = saved_boxed_locals;
                        self.shared_locals = saved_shared_locals;
                        self.shared_drop_locals = saved_shared_drop_locals;
                        self.captured_let_mut_moved = saved_captured_let_mut_moved;
                        self.type_tracker
                            .restore_local_binding_semantics(saved_local_binding_semantics);
                        self.param_locals = saved_param_locals;
                        self.current_function_params = saved_function_params;
                        self.pop_scope();
                        // Sweep phase 3c.1: restore outer-function local
                        // types AFTER pop_scope. pop_scope reads from
                        // local_type_scopes to evict matching local_types
                        // entries — restoring before pop_scope would let
                        // the (about-to-be-popped) inner-closure scope's
                        // slot indices evict outer-function entries.
                        self.type_tracker.restore_local_types(saved_local_types);
                        self.locals = saved_locals;
                        self.current_function = saved_function;
                        self.current_function_is_async = saved_is_async;
                        self.next_local = saved_next_local;
                        self.ref_locals = saved_ref_locals;
                        self.exclusive_ref_locals = saved_exclusive_ref_locals.clone();
                        self.inferred_ref_locals = saved_inferred_ref_locals.clone();
                        self.local_callable_pass_modes = saved_local_callable_pass_modes.clone();
                        self.local_callable_return_reference_summaries =
                            saved_local_callable_return_reference_summaries.clone();
                        // Sweep phase 3c.x: restore closure return-type +
                        // array-callable maps alongside.
                        self.local_callable_return_types =
                            saved_local_callable_return_types.clone();
                        self.local_array_callable_return_types =
                            saved_local_array_callable_return_types.clone();
                        // cluster-2-cw-IB-class-b: restore retained
                        // closure bodies after the nested function
                        // compile completes.
                        self.local_callable_closure_bodies =
                            saved_local_callable_closure_bodies.clone();
                        self.reference_value_locals = saved_reference_value_locals;
                        self.exclusive_reference_value_locals =
                            saved_exclusive_reference_value_locals;
                        self.reference_value_module_bindings =
                            saved_reference_value_module_bindings;
                        self.exclusive_reference_value_module_bindings =
                            saved_exclusive_reference_value_module_bindings;
                        self.comptime_mode = saved_comptime_mode;
                        self.current_function_return_reference_summary =
                            saved_current_function_return_reference_summary;
                        // WS-1b: surface-and-stop any unresolved empty-array
                        // accumulator, then restore the caller's maps.
                        let acc_result =
                            self.finalize_unresolved_empty_array_accumulators();
                        self.empty_array_accumulators =
                            saved_empty_array_accumulators;
                        self.v2_typed_array_locals = saved_v2_typed_array_locals;
                        acc_result?;
                        // Patch the jump-over instruction if we emitted one
                        if let Some(jump_addr) = jump_over {
                            self.patch_jump(jump_addr);
                        }
                        return Ok(());
                    }
                    Statement::Return(_, _) => {
                        // Explicit return - compile normally, it will handle its own return
                        let future_names = self
                            .future_reference_use_names_for_remaining_statements(
                                &func_def.body[idx + 1..],
                            );
                        self.push_future_reference_use_names(future_names);
                        let compile_result = self.compile_statement(stmt);
                        self.pop_future_reference_use_names();
                        compile_result?;
                        // After an explicit return, we still need the fallback below for
                        // control flow that might skip the return (though rare)
                    }
                    _ => {
                        // Other statement types - compile normally
                        let future_names = self
                            .future_reference_use_names_for_remaining_statements(
                                &func_def.body[idx + 1..],
                            );
                        self.push_future_reference_use_names(future_names);
                        let compile_result = self.compile_statement(stmt);
                        self.pop_future_reference_use_names();
                        compile_result?;
                        self.release_unused_local_reference_borrows_for_remaining_statements(
                            &func_def.body[idx + 1..],
                        );
                    }
                }
            } else {
                let mut future_names = self
                    .future_reference_use_names_for_remaining_statements(&func_def.body[idx + 1..]);
                if self.current_function_return_reference_summary.is_some()
                    && idx + 1 < body_len
                    && let Some(Statement::Expression(expr, _)) = func_def.body.last()
                {
                    self.collect_reference_use_names_from_expr(expr, true, &mut future_names);
                }
                self.push_future_reference_use_names(future_names);
                let compile_result = self.compile_statement(stmt);
                self.pop_future_reference_use_names();
                compile_result?;
                self.release_unused_local_reference_borrows_for_remaining_statements(
                    &func_def.body[idx + 1..],
                );
            }
        }

        // Emit drops for function-level locals before implicit null return
        let total_scopes = self.drop_locals.len();
        if total_scopes > 0 {
            self.emit_drops_for_early_exit(total_scopes)?;
        }

        // Implicit return null if no explicit return and last stmt wasn't an expression
        self.emit(Instruction::simple(OpCode::PushNull));
        self.emit(Instruction::simple(OpCode::ReturnValue));

        // Update function locals count
        self.program.functions[func_idx].locals_count = self.next_local;
        self.capture_function_local_storage_hints(func_idx);

        // Finalize blob builder and store completed blob
        self.finalize_current_blob(func_idx);
        self.current_blob_builder = saved_blob_builder;

        // Restore state
        self.drop_locals = saved_drop_locals;
        self.ownership_drop_locals = saved_ownership_drop_locals;
        self.boxed_locals = saved_boxed_locals;
        self.shared_locals = saved_shared_locals;
        self.shared_drop_locals = saved_shared_drop_locals;
        self.captured_let_mut_moved = saved_captured_let_mut_moved;
        self.type_tracker
            .restore_local_binding_semantics(saved_local_binding_semantics);
        self.current_function_params = saved_function_params;
        self.pop_scope();
        // Sweep phase 3c.1: restore outer-function local types AFTER
        // pop_scope (see early-return path comment).
        self.type_tracker.restore_local_types(saved_local_types);
        self.locals = saved_locals;
        self.current_function = saved_function;
        self.current_function_is_async = saved_is_async;
        self.next_local = saved_next_local;
        self.ref_locals = saved_ref_locals;
        self.exclusive_ref_locals = saved_exclusive_ref_locals;
        self.inferred_ref_locals = saved_inferred_ref_locals;
        self.local_callable_pass_modes = saved_local_callable_pass_modes;
        self.local_callable_return_reference_summaries =
            saved_local_callable_return_reference_summaries;
        // Sweep phase 3c.x: restore closure return-type + array-callable
        // maps alongside.
        self.local_callable_return_types = saved_local_callable_return_types;
        self.local_array_callable_return_types = saved_local_array_callable_return_types;
        // cluster-2-cw-IB-class-b: restore retained closure bodies.
        self.local_callable_closure_bodies = saved_local_callable_closure_bodies;
        self.reference_value_locals = saved_reference_value_locals;
        self.exclusive_reference_value_locals = saved_exclusive_reference_value_locals;
        self.reference_value_module_bindings = saved_reference_value_module_bindings;
        self.exclusive_reference_value_module_bindings =
            saved_exclusive_reference_value_module_bindings;
        self.comptime_mode = saved_comptime_mode;
        self.current_function_return_reference_summary =
            saved_current_function_return_reference_summary;

        // WS-1b: surface-and-stop any unresolved empty-array accumulator,
        // then restore the caller's maps.
        let acc_result = self.finalize_unresolved_empty_array_accumulators();
        self.empty_array_accumulators = saved_empty_array_accumulators;
        self.v2_typed_array_locals = saved_v2_typed_array_locals;
        acc_result?;

        // Patch the jump-over instruction if we emitted one
        if let Some(jump_addr) = jump_over {
            self.patch_jump(jump_addr);
        }

        Ok(())
    }

    // Compile a statement
}

/// Extract the root SlotId from a MIR operand if it references a local.
fn arg_root_slot(
    block: &crate::mir::types::BasicBlock,
    op: &crate::mir::types::Operand,
) -> Option<crate::mir::types::SlotId> {
    use crate::mir::types::{Operand, Place, Rvalue, StatementKind};
    use std::collections::{HashMap, HashSet};

    fn resolve_slot_root(
        slot: crate::mir::types::SlotId,
        alias_roots: &HashMap<crate::mir::types::SlotId, crate::mir::types::SlotId>,
    ) -> crate::mir::types::SlotId {
        let mut current = slot;
        let mut seen = HashSet::new();
        while seen.insert(current) {
            let Some(next) = alias_roots.get(&current).copied() else {
                break;
            };
            current = next;
        }
        current
    }

    fn operand_root_slot(
        op: &Operand,
        alias_roots: &HashMap<crate::mir::types::SlotId, crate::mir::types::SlotId>,
    ) -> Option<crate::mir::types::SlotId> {
        match op {
            Operand::Copy(place) | Operand::Move(place) | Operand::MoveExplicit(place) => {
                Some(resolve_slot_root(place.root_local(), alias_roots))
            }
            Operand::Constant(_) => None,
        }
    }

    let mut alias_roots = HashMap::new();
    for stmt in &block.statements {
        let StatementKind::Assign(Place::Local(dst), rvalue) = &stmt.kind else {
            continue;
        };

        match rvalue {
            Rvalue::Borrow(_, place) => {
                alias_roots.insert(*dst, resolve_slot_root(place.root_local(), &alias_roots));
            }
            Rvalue::Use(inner) | Rvalue::Clone(inner) | Rvalue::UnaryOp(_, inner) => {
                if let Some(root) = operand_root_slot(inner, &alias_roots) {
                    alias_roots.insert(*dst, root);
                } else {
                    alias_roots.remove(dst);
                }
            }
            _ => {
                alias_roots.remove(dst);
            }
        }
    }

    operand_root_slot(op, &alias_roots)
}

// Tests gated `deep-tests` post-W11: bodies use deleted `ValueWord` /
// `ValueWordExt` ABI for end-to-end execution checks. Restoration requires
// migration to the kinded `KindedSlot` API per ADR-006 §2.7.4.
#[cfg(all(test, feature = "deep-tests"))]
mod tests {
    use crate::bytecode::Constant;
    use crate::compiler::{BytecodeCompiler, ParamPassMode};
    use crate::executor::{VMConfig, VirtualMachine};
    use crate::mir::analysis::BorrowErrorKind;
    use crate::type_tracking::{BindingOwnershipClass, BindingStorageClass};
    use shape_ast::ast::{DestructurePattern, FunctionParameter, Item, Span};
    use shape_value::{ValueWord, ValueWordExt};

    fn eval(code: &str) -> ValueWord {
        let program = shape_ast::parser::parse_program(code).expect("parse failed");
        let mut compiler = BytecodeCompiler::new();
        compiler.allow_internal_builtins = true;
        let bytecode = compiler.compile(&program).expect("compile failed");
        let mut vm = VirtualMachine::new(VMConfig::default());
        vm.load_program(bytecode);
        vm.execute(None).expect("execution failed").clone()
    }

    fn compiles(code: &str) -> Result<crate::bytecode::BytecodeProgram, String> {
        let program =
            shape_ast::parser::parse_program(code).map_err(|e| format!("parse: {}", e))?;
        let mut compiler = BytecodeCompiler::new();
        compiler.allow_internal_builtins = true;
        compiler
            .compile(&program)
            .map_err(|e| format!("compile: {}", e))
    }

    fn test_param(is_const: bool, is_reference: bool, is_mut_reference: bool) -> FunctionParameter {
        FunctionParameter {
            pattern: DestructurePattern::Identifier("value".to_string(), Span::DUMMY),
            is_const,
            is_reference,
            is_mut_reference,
            is_out: false,
            type_annotation: None,
            default_value: None,
        }
    }

    #[test]
    fn test_binding_semantics_for_param_modes() {
        let by_value = BytecodeCompiler::binding_semantics_for_param(
            &test_param(false, false, false),
            ParamPassMode::ByValue,
        );
        assert_eq!(
            by_value.ownership_class,
            BindingOwnershipClass::OwnedMutable
        );
        assert_eq!(by_value.storage_class, BindingStorageClass::Direct);

        let const_value = BytecodeCompiler::binding_semantics_for_param(
            &test_param(true, false, false),
            ParamPassMode::ByValue,
        );
        assert_eq!(
            const_value.ownership_class,
            BindingOwnershipClass::OwnedImmutable
        );
        assert_eq!(const_value.storage_class, BindingStorageClass::Direct);

        let shared_ref = BytecodeCompiler::binding_semantics_for_param(
            &test_param(false, true, false),
            ParamPassMode::ByRefShared,
        );
        assert_eq!(
            shared_ref.ownership_class,
            BindingOwnershipClass::OwnedImmutable
        );
        assert_eq!(shared_ref.storage_class, BindingStorageClass::Reference);

        let exclusive_ref = BytecodeCompiler::binding_semantics_for_param(
            &test_param(false, true, true),
            ParamPassMode::ByRefExclusive,
        );
        assert_eq!(
            exclusive_ref.ownership_class,
            BindingOwnershipClass::OwnedMutable
        );
        assert_eq!(exclusive_ref.storage_class, BindingStorageClass::Reference);
    }

    #[test]
    #[ignore = "Wave B made array literals emit v2 typed opcodes unconditionally; destructuring `let [a, b] = [1, 2]` doesn't yet handle v2 typed array elements. Wave C follow-up."]
    fn test_block_expr_destructured_binding_still_runs() {
        let code = r#"
            let value = {
                let [a, b] = [1, 2]
                a + b
            }
            value
        "#;
        let result = eval(code);
        assert_eq!(result.as_number_coerce().unwrap(), 3.0);
    }

    #[test]
    fn test_const_param_requires_compile_time_constant_argument() {
        let code = r#"
            function connect(const conn_str: string) {
                conn_str
            }
            let value = "duckdb://local.db"
            connect(value)
        "#;
        let err = compiles(code).expect_err("non-constant argument for const param should fail");
        assert!(
            err.contains("declared `const` and requires a compile-time constant argument"),
            "Expected const argument diagnostic, got: {}",
            err
        );
    }

    #[test]
    fn test_const_template_skips_comptime_until_specialized() {
        let code = r#"
            annotation schema_connect() {
                comptime post(target, ctx) {
                    // `uri` is a const template parameter and is only bound on specialization.
                    if uri == "duckdb://analytics.db" {
                        set return int
                    } else {
                        set return int
                    }
                }
            }

            @schema_connect()
            function connect(const uri) {
                1
            }
        "#;
        let _ = compiles(code).expect("template base should compile without specialization");
    }

    #[test]
    fn test_const_template_specialization_binds_const_values() {
        let code = r#"
            annotation schema_connect() {
                comptime post(target, ctx) {
                    if uri == "duckdb://analytics.db" {
                        set return int
                    } else {
                        set return int
                    }
                }
            }

            @schema_connect()
            function connect(const uri) {
                1
            }

            let a = connect("duckdb://analytics.db")
            let b = connect("duckdb://other.db")
        "#;
        let bytecode = compiles(code).expect("const specialization should compile");
        let specialization_count = bytecode
            .functions
            .iter()
            .filter(|f| f.name.starts_with("connect__const_"))
            .count();
        assert_eq!(
            specialization_count, 2,
            "expected one specialization per distinct const argument"
        );
    }

    #[test]
    fn test_comptime_before_cannot_override_explicit_param_type() {
        let code = r#"
            annotation force_string() {
                comptime pre(target, ctx) {
                    set param x: string
                }
            }
            @force_string()
            function foo(x: int) {
                x
            }
        "#;
        let err = compiles(code).expect_err("explicit param type override should fail");
        assert!(
            err.contains("cannot override explicit type of parameter 'x'"),
            "Expected explicit param override error, got: {}",
            err
        );
    }

    #[test]
    fn test_comptime_after_cannot_override_explicit_return_type() {
        let code = r#"
            annotation force_string_return() {
                comptime post(target, ctx) {
                    set return string
                }
            }
            @force_string_return()
            function foo() -> int {
                1
            }
        "#;
        let err = compiles(code).expect_err("explicit return type override should fail");
        assert!(
            err.contains("cannot override explicit function return type annotation"),
            "Expected explicit return override error, got: {}",
            err
        );
    }

    #[test]
    fn test_comptime_after_receives_annotation_args() {
        let code = r#"
            annotation set_return_type_from_annotation(type_name) {
                comptime post(target, ctx, ty) {
                    if ty == "int" {
                        set return int
                    } else {
                        set return string
                    }
                }
            }
            @set_return_type_from_annotation("int")
            fn foo() {
                1
            }
            foo()
        "#;
        let result = eval(code);
        assert_eq!(
            result.as_number_coerce().expect("Expected numeric result"),
            1.0
        );
    }

    #[test]
    fn test_comptime_after_variadic_annotation_args() {
        let code = r#"
            annotation variadic_schema() {
                comptime post(target, ctx, ...config) {
                    set return int
                }
            }
            @variadic_schema(1, "x", true)
            fn foo() {
                1
            }
            foo()
        "#;
        let result = eval(code);
        assert_eq!(
            result.as_number_coerce().expect("Expected numeric result"),
            1.0
        );
    }

    #[test]
    fn test_comptime_after_arg_arity_errors() {
        let missing_arg = r#"
            annotation needs_arg() {
                comptime post(target, ctx, config) {
                    target.name
                }
            }
            @needs_arg()
            fn foo() { 1 }
        "#;
        let err = compiles(missing_arg).expect_err("missing annotation arg should fail");
        assert!(
            err.contains("missing annotation argument for comptime handler parameter 'config'"),
            "unexpected error: {}",
            err
        );

        let too_many = r#"
            annotation one_arg() {
                comptime post(target, ctx, config) {
                    target.name
                }
            }
            @one_arg(1, 2)
            fn foo() { 1 }
        "#;
        let err = compiles(too_many).expect_err("too many annotation args should fail");
        assert!(
            err.contains("too many annotation arguments"),
            "unexpected error: {}",
            err
        );
    }

    #[test]
    fn test_comptime_after_can_replace_function_body() {
        let code = r#"
            annotation synthesize_body() {
                comptime post(target, ctx) {
                    replace body {
                        return 42
                    }
                }
            }
            @synthesize_body()
            function foo() {
            }
            foo()
        "#;
        let result = eval(code);
        assert_eq!(
            result
                .as_number_coerce()
                .expect("Expected 42 from synthesized body"),
            42.0
        );
    }

    #[test]
    fn test_comptime_after_can_replace_function_body_from_expr() {
        let code = r#"
            comptime fn body_src() {
                "return 7"
            }

            annotation synthesize_body_expr() {
                comptime post(target, ctx) {
                    replace body (body_src())
                }
            }
            @synthesize_body_expr()
            function foo() {
            }
            foo()
        "#;
        let result = eval(code);
        assert_eq!(
            result
                .as_number_coerce()
                .expect("Expected 7 from synthesized body"),
            7.0
        );
    }

    #[test]
    fn test_comptime_handler_extend_generates_method() {
        // A comptime handler using direct `extend` should register generated methods.
        let code = r#"
            annotation add_method() {
                targets: [type]
                comptime post(target, ctx) {
                    extend Number {
                        method doubled() { self * 2.0 }
                    }
                }
            }

            @add_method()
            type Marker { x: int }

            (5.0).doubled()
        "#;
        let result = eval(code);
        assert_eq!(
            result.as_number_coerce().expect("Expected Number(10.0)"),
            10.0
        );
    }

    #[test]
    fn test_comptime_handler_extend_method_executes() {
        // Verify the generated extend method actually runs correctly
        let code = r#"
            annotation auto_extend() {
                targets: [type]
                comptime post(target, ctx) {
                    extend Number {
                        method tripled() { self * 3.0 }
                    }
                }
            }
            @auto_extend()
            type Marker { x: int }
            (10.0).tripled()
        "#;
        let result = eval(code);
        assert_eq!(
            result.as_number_coerce().expect("Expected Number(30.0)"),
            30.0
        );
    }

    #[test]
    fn test_comptime_handler_non_object_result_ignored() {
        // Handler values are ignored unless explicit directives are emitted.
        let code = r#"
            annotation no_op() {
                comptime post(target, ctx) {
                    "just a string"
                }
            }
            @no_op()
            function my_func(x) {
                return x + 1.0
            }
            my_func(5.0)
        "#;
        let result = eval(code);
        assert_eq!(
            result.as_number_coerce().expect("Expected Number(6.0)"),
            6.0
        );
    }

    #[test]
    fn test_legacy_action_object_not_processed() {
        // Legacy action-object return values are intentionally ignored.
        let code = r#"
            annotation legacy() {
                comptime post(target, ctx) {
                    { action: "extend", source: "method doubled() { return self * 2.0 }", type: "Number" }
                }
            }
            @legacy()
            function placeholder() { 0 }
            (5.0).doubled()
        "#;
        let result = compiles(code).expect("legacy action object should not fail compilation");
        let has_doubled = result
            .functions
            .iter()
            .any(|f| f.name.ends_with("::doubled"));
        assert!(
            !has_doubled,
            "Legacy action-object return should not generate methods"
        );
    }

    #[test]
    fn test_comptime_handler_extend_multiple_methods() {
        // A comptime handler can emit multiple methods in one extend block.
        let code = r#"
            annotation math_ops() {
                targets: [type]
                comptime post(target, ctx) {
                    extend Number {
                        method add_ten() { self + 10.0 }
                        method sub_ten() { self - 10.0 }
                    }
                }
            }
            @math_ops()
            type Marker { x: int }
            let a = (25.0).add_ten()
            let b = (25.0).sub_ten()
            a + b
        "#;
        let result = eval(code);
        assert_eq!(
            result.as_number_coerce().expect("Expected Number(50.0)"),
            50.0
        );
    }

    #[test]
    fn test_expression_annotation_comptime_handler_executes() {
        // Expression-level annotation should run comptime handler and process extend directives.
        let code = r#"
            annotation expr_extend() {
                targets: [expression]
                comptime post(target, ctx) {
                    extend Number {
                        method quadrupled() { self * 4.0 }
                    }
                }
            }

            let x = @expr_extend() 2.0
            x.quadrupled()
        "#;
        let result = eval(code);
        assert_eq!(
            result.as_number_coerce().expect("Expected Number(8.0)"),
            8.0
        );
    }

    #[test]
    fn test_expression_annotation_target_validation() {
        // Type-only annotation applied to an expression should fail with a target error.
        let code = r#"
            annotation only_type() {
                targets: [type]
                comptime post(target, ctx) {
                    target.kind
                }
            }

            let x = @only_type() 1
        "#;
        let err = compiles(code).expect_err("type-only annotation on expression should fail");
        assert!(
            err.contains("cannot be applied to a expression"),
            "Expected expression target error, got: {}",
            err
        );
    }

    #[test]
    fn test_expression_annotation_rejects_definition_lifecycle_hooks() {
        let code = r#"
            annotation info() {
                metadata(target, ctx) {
                    target.kind
                }
            }

            let x = @info() 1
        "#;
        let err =
            compiles(code).expect_err("definition-time lifecycle hooks on expression should fail");
        assert!(
            err.contains("definition-time lifecycle hooks"),
            "Expected definition-time lifecycle target error, got: {}",
            err
        );
    }

    #[test]
    fn test_await_annotation_target_validation() {
        // Await-only annotation should compile in await context.
        let ok_code = r#"
            annotation only_await() {
                targets: [await_expr]
                comptime post(target, ctx) {
                    target.kind
                }
            }

            async function ready() {
                return 1
            }

            async function run() {
                await @only_await() ready()
                return 1
            }
        "#;
        assert!(
            compiles(ok_code).is_ok(),
            "await annotation should be accepted in await context"
        );

        // The same await-only annotation on a plain expression must fail.
        let bad_code = r#"
            annotation only_await() {
                targets: [await_expr]
                comptime post(target, ctx) {
                    target.kind
                }
            }

            let x = @only_await() 1
        "#;
        let err = compiles(bad_code).expect_err("await-only annotation on expression should fail");
        assert!(
            err.contains("cannot be applied to a expression"),
            "Expected expression target error, got: {}",
            err
        );
    }

    #[test]
    fn test_direct_extend_target_on_type_via_comptime_handler() {
        // Direct `extend target { ... }` should work without action-object indirection.
        let code = r#"
            annotation add_sum() {
                targets: [type]
                comptime post(target, ctx) {
                    extend target {
                        method sum() {
                            self.x + self.y
                        }
                    }
                }
            }

            @add_sum()
            type Point { x: int, y: int }

            Point { x: 2, y: 3 }.sum()
        "#;
        let result = eval(code);
        assert_eq!(result.as_number_coerce().expect("Expected 5"), 5.0);
    }

    #[test]
    fn test_direct_remove_target_on_expression() {
        // `remove target` on an expression target should replace the expression with null.
        let code = r#"
            annotation drop_expr() {
                targets: [expression]
                comptime post(target, ctx) {
                    remove target
                }
            }

            let x = @drop_expr() 123
            x
        "#;
        let result = eval(code);
        assert!(
            result.is_none(),
            "Expected None after remove target, got {:?}",
            result
        );
    }

    #[test]
    fn test_replace_body_original_calls_original_function() {
        // __original__ should call the original function body from a replacement body.
        let code = r#"
            annotation wrap() {
                comptime post(target, ctx) {
                    replace body {
                        return __original__(5) + 100
                    }
                }
            }
            @wrap()
            function add_ten(x) {
                return x + 10
            }
            add_ten(0)
        "#;
        let result = eval(code);
        assert_eq!(
            result
                .as_number_coerce()
                .expect("Expected 115 from __original__ call"),
            115.0,
        );
    }

    #[test]
    fn test_replace_body_args_contains_function_parameters() {
        // `args` should be an array of the function's parameters in the replacement body.
        let code = r#"
            annotation with_args() {
                comptime post(target, ctx) {
                    replace body {
                        return args.len()
                    }
                }
            }
            @with_args()
            function three_params(a, b, c) {
                return 0
            }
            three_params(10, 20, 30)
        "#;
        let result = eval(code);
        assert_eq!(
            result
                .as_number_coerce()
                .expect("Expected 3 from args.len()"),
            3.0,
        );
    }

    #[test]
    fn test_replace_body_original_with_no_params() {
        // __original__ should work even with zero-parameter functions.
        let code = r#"
            annotation add_one() {
                comptime post(target, ctx) {
                    replace body {
                        return __original__() + 1
                    }
                }
            }
            @add_one()
            function get_value() {
                return 41
            }
            get_value()
        "#;
        let result = eval(code);
        assert_eq!(
            result
                .as_number_coerce()
                .expect("Expected 42 from __original__() + 1"),
            42.0,
        );
    }

    #[test]
    fn test_content_addressed_program_has_main_and_functions() {
        let code = r#"
            function add(a, b) { a + b }
            function mul(a, b) { a * b }
            let x = add(2, 3)
            mul(x, 4)
        "#;
        let bytecode = compiles(code).expect("should compile");
        let ca = bytecode
            .content_addressed
            .expect("content_addressed program should be Some");

        // Should have at least __main__, add, and mul blobs
        assert!(
            ca.function_store.len() >= 3,
            "Expected at least 3 blobs (__main__, add, mul), got {}",
            ca.function_store.len()
        );

        // Entry should be set (non-zero hash)
        assert_ne!(
            ca.entry,
            crate::bytecode::FunctionHash::ZERO,
            "Entry hash should not be zero"
        );

        // Entry should be in the function store
        assert!(
            ca.function_store.contains_key(&ca.entry),
            "Entry hash should be present in function_store"
        );

        // Check that each blob has a non-zero content hash
        for (hash, blob) in &ca.function_store {
            assert_ne!(
                *hash,
                crate::bytecode::FunctionHash::ZERO,
                "Blob '{}' should have non-zero hash",
                blob.name
            );
            assert_eq!(
                *hash, blob.content_hash,
                "Blob '{}' key should match its content_hash",
                blob.name
            );
            assert!(
                !blob.instructions.is_empty(),
                "Blob '{}' should have instructions",
                blob.name
            );
        }
    }

    #[test]
    fn test_content_addressed_blob_has_local_pools() {
        let code = r#"
            function greet(name) { "hello " + name }
            greet("world")
        "#;
        let bytecode = compiles(code).expect("should compile");
        let ca = bytecode
            .content_addressed
            .expect("content_addressed program should be Some");

        // Find the greet blob
        let greet_blob = ca
            .function_store
            .values()
            .find(|b| b.name == "greet")
            .expect("greet blob should exist");

        assert_eq!(greet_blob.arity, 1);
        assert_eq!(greet_blob.param_names, vec!["name".to_string()]);
        // Should have at least one string in its local pool ("hello ")
        assert!(
            !greet_blob.strings.is_empty() || !greet_blob.constants.is_empty(),
            "greet blob should have local constants or strings"
        );
    }

    #[test]
    fn test_content_addressed_stable_hash() {
        // Compiling the same code twice should produce the same content hashes
        let code = r#"
            function double(x) { x * 2 }
            double(21)
        "#;
        let bytecode1 = compiles(code).expect("should compile");
        let bytecode2 = compiles(code).expect("should compile");

        let ca1 = bytecode1.content_addressed.expect("should have ca1");
        let ca2 = bytecode2.content_addressed.expect("should have ca2");

        // Find the double blob in both
        let double1 = ca1
            .function_store
            .values()
            .find(|b| b.name == "double")
            .expect("double blob in ca1");
        let double2 = ca2
            .function_store
            .values()
            .find(|b| b.name == "double")
            .expect("double blob in ca2");

        assert_eq!(
            double1.content_hash, double2.content_hash,
            "Same code should produce same content hash"
        );
    }

    #[test]
    fn test_extern_c_signature_supports_callback_and_nullable_cstring() {
        let code = r#"
            extern C fn walk(
                root: Option<string>,
                on_entry: (path: ptr, data: ptr) => i32
            ) -> Option<string> from "libwalk";
        "#;
        let bytecode = compiles(code).expect("should compile");
        assert_eq!(bytecode.foreign_functions.len(), 1);
        let entry = &bytecode.foreign_functions[0];
        let native = entry
            .native_abi
            .as_ref()
            .expect("extern C binding should carry native ABI metadata");
        assert_eq!(
            native.signature,
            "fn(cstring?, callback(fn(ptr, ptr) -> i32)) -> cstring?"
        );
    }

    #[test]
    fn test_extern_c_signature_maps_vec_to_native_slice() {
        let code = r#"
            extern C fn hash_bytes(data: Vec<byte>) -> u64 from "libhash";
            extern C fn split_words(data: Vec<Option<string>>) -> Vec<Option<string>> from "libhash";
        "#;
        let bytecode = compiles(code).expect("should compile");
        assert_eq!(bytecode.foreign_functions.len(), 2);
        let hash = bytecode.foreign_functions[0]
            .native_abi
            .as_ref()
            .expect("extern C function should carry native ABI metadata");
        assert_eq!(hash.signature, "fn(cslice<u8>) -> u64");
        let split = bytecode.foreign_functions[1]
            .native_abi
            .as_ref()
            .expect("extern C function should carry native ABI metadata");
        assert_eq!(split.signature, "fn(cslice<cstring?>) -> cslice<cstring?>");
    }

    #[test]
    fn test_extern_c_cmut_slice_param_marks_ref_mutate_contract() {
        let code = r#"
            extern C fn hash_bytes(data: Vec<byte>) -> u64 from "libhash";
            extern C fn mutate_bytes(data: CMutSlice<byte>) -> void from "libhash";
        "#;
        let bytecode = compiles(code).expect("should compile");
        let hash_fn = bytecode
            .functions
            .iter()
            .find(|func| func.name == "hash_bytes")
            .expect("hash_bytes function should exist");
        assert_eq!(hash_fn.ref_params, vec![false]);
        assert_eq!(hash_fn.ref_mutates, vec![false]);

        let mutate_fn = bytecode
            .functions
            .iter()
            .find(|func| func.name == "mutate_bytes")
            .expect("mutate_bytes function should exist");
        assert_eq!(mutate_fn.ref_params, vec![true]);
        assert_eq!(mutate_fn.ref_mutates, vec![true]);
    }

    #[test]
    fn test_extern_c_signature_rejects_nested_vec_type() {
        let code = r#"
            extern C fn bad(data: Vec<Vec<byte>>) -> i32 from "libbad";
        "#;
        let err = compiles(code).expect_err("nested Vec native slice should be rejected");
        assert!(err.contains("unsupported parameter type 'Vec<Vec<byte>>'"));
    }

    #[test]
    fn test_extern_c_call_targets_stub_then_call_foreign() {
        let code = r#"
            extern C fn cos_c(x: f64) -> f64 from "libm.so.6" as "cos";
            let value = cos_c(0.0)
            value
        "#;
        let bytecode = compiles(code).expect("should compile");
        let cos_idx = bytecode
            .functions
            .iter()
            .position(|f| f.name == "cos_c")
            .expect("cos_c function should exist") as u16;
        let mut saw_call_value = false;
        for ip in 0..bytecode.instructions.len() {
            let instr = bytecode.instructions[ip];
            if instr.opcode == crate::bytecode::OpCode::CallValue {
                saw_call_value = true;
            }
        }
        assert!(
            saw_call_value,
            "top-level should invoke function values through CallValue"
        );

        let cos = &bytecode.functions[cos_idx as usize];
        let stub_instrs = &bytecode.instructions[cos.entry_point..];
        assert!(
            stub_instrs
                .iter()
                .take(8)
                .any(|i| i.opcode == crate::bytecode::OpCode::CallForeign),
            "foreign stub should contain CallForeign opcode near its entry"
        );
        let ca = bytecode
            .content_addressed
            .as_ref()
            .expect("content-addressed program should exist");
        let cos_hash = *ca
            .function_store
            .iter()
            .find(|(_, blob)| blob.name == "cos_c")
            .map(|(hash, _)| hash)
            .expect("cos_c blob should exist");
        let main_blob = ca
            .function_store
            .values()
            .find(|blob| blob.name == "__main__")
            .expect("__main__ blob should exist");
        assert!(
            main_blob.dependencies.contains(&cos_hash),
            "__main__ blob must depend on cos_c hash so function constants remap correctly"
        );
        let has_dep_function_constant = main_blob
            .constants
            .iter()
            .any(|c| matches!(c, Constant::Function(0)));
        assert!(
            has_dep_function_constant,
            "__main__ constants should store function references as dependency-local indices"
        );
    }

    #[test]
    fn test_duckdb_package_style_arrow_import_compiles() {
        let code = r#"
            extern C fn duckdb_query_arrow(conn: ptr, sql: string, out_result: ptr) -> i32 from "duckdb";
            extern C fn duckdb_query_arrow_schema(result: ptr, out_schema: ptr) -> i32 from "duckdb";
            extern C fn duckdb_query_arrow_array(result: ptr, out_array: ptr) -> i32 from "duckdb";
            extern C fn duckdb_destroy_arrow(result_p: ptr) -> void from "duckdb" as "duckdb_destroy_arrow";

            type CandleRow {
                ts: i64,
                close: f64,
            }

            fn query_typed(conn: ptr, sql: string) -> Result<Table<CandleRow>, AnyError> {
                let result_cell = __native_ptr_new_cell()
                __native_ptr_write_ptr(result_cell, 0)
                duckdb_query_arrow(conn, sql, result_cell)
                let arrow_result = __native_ptr_read_ptr(result_cell)

                let schema_cell = __native_ptr_new_cell()
                __native_ptr_write_ptr(schema_cell, 0)
                duckdb_query_arrow_schema(arrow_result, schema_cell)
                let schema_handle = __native_ptr_read_ptr(schema_cell)
                let schema_ptr = __native_ptr_read_ptr(schema_handle)

                let array_cell = __native_ptr_new_cell()
                __native_ptr_write_ptr(array_cell, 0)
                duckdb_query_arrow_array(arrow_result, array_cell)
                let array_handle = __native_ptr_read_ptr(array_cell)
                let array_ptr = __native_ptr_read_ptr(array_handle)

                let typed: Result<Table<CandleRow>, AnyError> =
                    __native_table_from_arrow_c_typed(schema_ptr, array_ptr, "CandleRow")

                duckdb_destroy_arrow(result_cell)
                __native_ptr_free_cell(array_cell)
                __native_ptr_free_cell(schema_cell)
                __native_ptr_free_cell(result_cell)

                typed
            }
        "#;
        compiles(code).expect("duckdb package-style native code should compile");
    }

    #[test]
    fn test_extern_c_resolution_is_package_scoped_not_global() {
        let code = r#"
            extern C fn dep_a_call() -> i32 from "shared";
            extern C fn dep_b_call() -> i32 from "shared";
        "#;
        let mut program = shape_ast::parser::parse_program(code).expect("parse failed");
        for item in &mut program.items {
            if let shape_ast::ast::Item::ForeignFunction(def, _) = item
                && let Some(native) = def.native_abi.as_mut()
            {
                native.package_key = Some(match def.name.as_str() {
                    "dep_a_call" => "dep_a@1.0.0".to_string(),
                    "dep_b_call" => "dep_b@1.0.0".to_string(),
                    other => panic!("unexpected foreign function '{}'", other),
                });
            }
        }

        let mut compiler = BytecodeCompiler::new();
        compiler.allow_internal_builtins = true;

        let mut resolutions = shape_runtime::native_resolution::NativeResolutionSet::default();
        resolutions.insert(shape_runtime::native_resolution::ResolvedNativeDependency {
            package_name: "dep_a".to_string(),
            package_version: "1.0.0".to_string(),
            package_key: "dep_a@1.0.0".to_string(),
            alias: "shared".to_string(),
            target: shape_runtime::project::NativeTarget::current(),
            provider: shape_runtime::project::NativeDependencyProvider::System,
            resolved_value: "libdep_a_shared.so".to_string(),
            load_target: "/tmp/libdep_a_shared.so".to_string(),
            fingerprint: "test-a".to_string(),
            declared_version: Some("1.0.0".to_string()),
            cache_key: None,
            provenance: shape_runtime::native_resolution::NativeProvenance::UpdateResolved,
        });
        resolutions.insert(shape_runtime::native_resolution::ResolvedNativeDependency {
            package_name: "dep_b".to_string(),
            package_version: "1.0.0".to_string(),
            package_key: "dep_b@1.0.0".to_string(),
            alias: "shared".to_string(),
            target: shape_runtime::project::NativeTarget::current(),
            provider: shape_runtime::project::NativeDependencyProvider::System,
            resolved_value: "libdep_b_shared.so".to_string(),
            load_target: "/tmp/libdep_b_shared.so".to_string(),
            fingerprint: "test-b".to_string(),
            declared_version: Some("1.0.0".to_string()),
            cache_key: None,
            provenance: shape_runtime::native_resolution::NativeProvenance::UpdateResolved,
        });
        compiler.native_resolution_context = Some(resolutions);

        let bytecode = compiler.compile(&program).expect("compile should succeed");
        let dep_a = bytecode.foreign_functions[0]
            .native_abi
            .as_ref()
            .expect("dep_a native ABI");
        let dep_b = bytecode.foreign_functions[1]
            .native_abi
            .as_ref()
            .expect("dep_b native ABI");

        assert_eq!(dep_a.library, "/tmp/libdep_a_shared.so");
        assert_eq!(dep_b.library, "/tmp/libdep_b_shared.so");
    }

    #[test]
    fn test_out_param_extern_c_compiles() {
        let code = r#"
            extern C fn duckdb_open(path: string, out out_db: ptr) -> i32 from "duckdb";
            extern C fn duckdb_connect(db: ptr, out out_conn: ptr) -> i32 from "duckdb";

            fn test() {
                let [status, db] = duckdb_open("test.db")
                let [s2, conn] = duckdb_connect(db)
                conn
            }
        "#;
        compiles(code).expect("out param extern C should compile");
    }

    #[test]
    fn test_out_param_void_return_single_out() {
        let code = r#"
            extern C fn duckdb_close(out db_p: ptr) -> void from "duckdb";

            fn test() {
                let db = duckdb_close()
                db
            }
        "#;
        // Single out + void return → return type is out value directly
        compiles(code).expect("single out param with void return should compile");
    }

    #[test]
    fn test_out_param_not_allowed_on_non_extern_c() {
        let code = r#"
            fn python test(out x: ptr) -> i32 { "pass" }
        "#;
        let err = compiles(code).expect_err("out params should not work on non-extern-C");
        assert!(
            err.contains("`out` parameter") && err.contains("only valid on `extern C`"),
            "Expected out-param validation error, got: {}",
            err
        );
    }

    #[test]
    fn test_out_param_must_be_ptr_type() {
        let code = r#"
            extern C fn foo(out x: i32) -> void from "lib";
        "#;
        let err = compiles(code).expect_err("out params must be ptr type");
        assert!(
            err.contains("must have type `ptr`"),
            "Expected ptr type error, got: {}",
            err
        );
    }

    #[test]
    fn test_native_builtin_blocked_from_user_code() {
        // Verify that __native_ptr_new_cell is not accessible from user code.
        let code = r#"
            fn test() {
                let cell = __native_ptr_new_cell()
                cell
            }
        "#;
        let compiler = BytecodeCompiler::new();
        // Do NOT set allow_internal_builtins — simulates user code
        let program = shape_ast::parser::parse_program(code).unwrap();
        let err = compiler
            .compile(&program)
            .expect_err("__native_* should be blocked from user code");
        let msg = format!("{}", err);
        assert!(
            msg.contains("'__native_ptr_new_cell' resolves to internal intrinsic scope")
                && msg.contains("not available from ordinary user code"),
            "Expected internal-only intrinsic error, got: {}",
            msg
        );
    }

    #[test]
    fn test_intrinsic_builtin_blocked_from_user_code() {
        // Verify that __intrinsic_* and __json_* builtins are gated from user code.
        // Note: __into_*/__try_into_* are NOT gated (compiler-generated for type assertions).
        // W12-stdlib-intrinsic-collapse (Wave-2-Agent-G, 2026-05-14):
        // `__intrinsic_sum` deleted — substitute another still-gated
        // intrinsic (`__intrinsic_std`) to exercise the gating path.
        for intrinsic in &["__intrinsic_std", "__intrinsic_mean", "__json_object_get"] {
            let code = format!(
                r#"
                fn test() {{
                    let x = {}([1, 2, 3])
                    x
                }}
            "#,
                intrinsic
            );
            let compiler = BytecodeCompiler::new();
            let program = shape_ast::parser::parse_program(&code).unwrap();
            let err = compiler
                .compile(&program)
                .expect_err(&format!("{} should be blocked from user code", intrinsic));
            let msg = format!("{}", err);
            assert!(
                msg.contains(&format!(
                    "'{}' resolves to internal intrinsic scope",
                    intrinsic
                )) && msg.contains("not available from ordinary user code"),
                "Expected internal-only intrinsic error for {}, got: {}",
                intrinsic,
                msg
            );
        }
    }

    #[test]
    fn test_intrinsic_builtin_method_syntax_blocked_from_user_code() {
        // W12-stdlib-intrinsic-collapse (Wave-2-Agent-G, 2026-05-14):
        // `__intrinsic_sum` was deleted — substitute `__intrinsic_std`
        // (still gated) to exercise the gating path.
        let code = r#"
            fn test() {
                [1, 2, 3].__intrinsic_std()
            }
        "#;
        let compiler = BytecodeCompiler::new();
        let program = shape_ast::parser::parse_program(code).unwrap();
        let err = compiler
            .compile(&program)
            .expect_err("__intrinsic_* method syntax should be blocked from user code");
        let msg = format!("{}", err);
        assert!(
            msg.contains("'__intrinsic_std' resolves to internal intrinsic scope")
                && msg.contains("not available from ordinary user code"),
            "Expected internal-only intrinsic method error, got: {}",
            msg
        );
    }

    #[test]
    fn test_unknown_function_message_mentions_resolution_scopes() {
        let code = r#"
            fn test() {
                totally_unknown_function()
            }
        "#;
        let program = shape_ast::parser::parse_program(code).unwrap();
        let err = BytecodeCompiler::new()
            .compile(&program)
            .expect_err("unknown function should fail");
        let msg = format!("{}", err);
        assert!(
            msg.contains(
                "Function names resolve from module scope, explicit imports, type-associated scope, and the implicit prelude."
            ),
            "Expected function scope guidance, got: {}",
            msg
        );
    }

    #[test]
    fn test_undefined_variable_message_mentions_resolution_scopes() {
        let code = r#"
            fn test() {
                missing_value
            }
        "#;
        let program = shape_ast::parser::parse_program(code).unwrap();
        let err = BytecodeCompiler::new()
            .compile(&program)
            .expect_err("unknown variable should fail");
        let msg = format!("{}", err);
        assert!(
            msg.contains("Variable names resolve from local scope and module scope."),
            "Expected variable scope guidance, got: {}",
            msg
        );
    }

    #[test]
    fn test_internal_builtin_not_unlocked_by_stdlib_name_collision() {
        let code = r#"
            type Json { payload: any }

            extend Json {
                method get(key: string) -> any {
                    __json_object_get(self.payload, key)
                }
            }
        "#;
        let mut compiler = BytecodeCompiler::new();
        compiler
            .stdlib_function_names
            .insert("Json.get".to_string());
        let program = shape_ast::parser::parse_program(code).unwrap();
        let err = compiler
            .compile(&program)
            .expect_err("user-defined Json.get must not gain __* access");
        let msg = format!("{}", err);
        assert!(
            msg.contains("'__json_object_get' resolves to internal intrinsic scope")
                && msg.contains("not available from ordinary user code"),
            "Expected internal-only intrinsic error, got: {}",
            msg
        );
    }

    #[test]
    fn test_compile_function_records_mir_analysis() {
        let program = shape_ast::parser::parse_program(
            r#"
                function choose(flag, left, right) {
                    if flag { left } else { right }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("function should compile");

        let mir = compiler
            .mir_functions
            .get("choose")
            .expect("mir should be recorded");
        assert_eq!(mir.name, "choose");
        assert!(mir.num_locals >= 3, "params should appear in MIR locals");

        let analysis = compiler
            .mir_borrow_analyses
            .get("choose")
            .expect("borrow analysis should be recorded");
        assert_eq!(analysis.loans.len(), 0);
        assert!(analysis.errors.is_empty(), "analysis should be clean");

        // JIT v2: verify mir_data is cached on the Function struct.
        let func_entry = compiler
            .program
            .functions
            .iter()
            .find(|f| f.name == "choose")
            .expect("choose should be in program.functions");
        assert!(
            func_entry.mir_data.is_some(),
            "mir_data should be populated on the Function struct"
        );
        let mir_data = func_entry.mir_data.as_ref().unwrap();
        assert_eq!(mir_data.mir.name, "choose");
    }

    #[test]
    fn test_compile_function_records_return_reference_summary() {
        let program = shape_ast::parser::parse_program(
            r#"
                function borrow_id(&x) {
                    x
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("reference-returning function should compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("borrow_id")
            .expect("borrow analysis should be recorded");
        assert_eq!(
            analysis.return_reference_summary,
            Some(crate::mir::analysis::ReturnReferenceSummary {
                param_index: 0,
                kind: crate::mir::types::BorrowKind::Shared,
                projection: Some(Vec::new()),
            })
        );
    }

    #[test]
    fn test_compile_function_allows_expression_return_reference_with_summary() {
        let program = shape_ast::parser::parse_program(
            r#"
                function borrow_id(&x) {
                    let ignored = {
                        return &x
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("expression-form reference return should compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("borrow_id")
            .expect("borrow analysis should be recorded");
        assert_eq!(
            analysis.return_reference_summary,
            Some(crate::mir::analysis::ReturnReferenceSummary {
                param_index: 0,
                kind: crate::mir::types::BorrowKind::Shared,
                projection: Some(Vec::new()),
            })
        );
    }

    #[test]
    fn test_compile_function_rejects_inconsistent_return_reference_summary() {
        let program = shape_ast::parser::parse_program(
            r#"
                function borrow_id(flag, &x) {
                    if flag {
                        return x
                    }
                    return 1
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("mixed ref/value returns should be rejected");
        assert!(
            format!("{}", err).contains("same borrowed origin and borrow kind"),
            "expected inconsistent-ref-return error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("borrow_id")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::InconsistentReferenceReturn),
            "expected inconsistent reference return error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_borrow_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function clash() {
                    let mut x = 1
                    let shared = &x
                    let exclusive = &mut x
                    shared
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR borrow conflict should surface as a compile error");
        assert!(
            format!("{}", err).contains("B0001"),
            "expected B0001-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("clash")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::ConflictSharedExclusive),
            "expected MIR borrow conflict, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_mutability_error() {
        let program = shape_ast::parser::parse_program(
            r#"
                function reassign() {
                    let x = 1
                    x = 2
                    x
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("immutable reassignment should surface as a compile error");
        assert!(
            format!("{}", err).contains("cannot assign to immutable binding 'x'"),
            "expected immutable binding error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("reassign")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .mutability_errors
                .iter()
                .any(|error| error.variable_name == "x"),
            "expected MIR mutability error, got {:?}",
            analysis.mutability_errors
        );
    }

    // Tests for MIR authority tracking removed: MIR is now the sole authority,
    // there is no longer a lexical fallback mechanism.

    #[test]
    fn test_compile_function_records_mir_const_mutability_error() {
        let program = shape_ast::parser::parse_program(
            r#"
                function reassign() {
                    const x = 1
                    x = 2
                    x
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("const reassignment should surface as a compile error");
        assert!(
            format!("{}", err).contains("cannot assign to const binding 'x'"),
            "expected const binding error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("reassign")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .mutability_errors
                .iter()
                .any(|error| error.variable_name == "x" && error.is_const),
            "expected MIR const mutability error, got {:?}",
            analysis.mutability_errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_const_param_mutability_error() {
        let program = shape_ast::parser::parse_program(
            r#"
                function reassign(const x) {
                    x = 2
                    x
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("const parameter reassignment should surface as a compile error");
        assert!(
            format!("{}", err).contains("cannot assign to const binding 'x'"),
            "expected const parameter binding error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("reassign")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .mutability_errors
                .iter()
                .any(|error| error.variable_name == "x" && error.is_const),
            "expected MIR const parameter mutability error, got {:?}",
            analysis.mutability_errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_write_while_borrowed() {
        let program = shape_ast::parser::parse_program(
            r#"
                function reassign() {
                    let mut x = 1
                    let shared = &x
                    x = 2
                    shared
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR write-while-borrowed should surface as a compile error");
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("reassign")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_read_while_exclusive_borrow() {
        let program = shape_ast::parser::parse_program(
            r#"
                function read_owner() {
                    let mut x = 1
                    let exclusive = &mut x
                    let copy = x
                    exclusive
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR read-while-exclusive should surface as a compile error");
        assert!(
            format!("{}", err).contains("B0001"),
            "expected B0001-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("read_owner")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::ReadWhileExclusivelyBorrowed),
            "expected MIR read-while-exclusive error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                function escape_ref() {
                    let x = 1
                    let r = &x
                    let alias = r
                    return alias
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR reference escape should surface as a compile error");
        assert!(
            format!("{}", err).contains("outlives its owner"),
            "expected reference-escape error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("escape_ref")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::ReferenceEscape),
            "expected MIR reference-escape error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_use_after_explicit_move() {
        let program = shape_ast::parser::parse_program(
            r#"
                function moved_then_read() {
                    let x = "hi"
                    let y = move x
                    let z = x
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR use-after-move should surface as a compile error");
        assert!(
            format!("{}", err).contains("after it was moved"),
            "expected use-after-move error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("moved_then_read")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::UseAfterMove),
            "expected MIR use-after-move error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_async_let_exclusive_ref_task_boundary() {
        let program = shape_ast::parser::parse_program(
            r#"
                async function spawn_conflict() {
                    let mut x = 1
                    async let fut = &mut x
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR task-boundary error should surface as a compile error");
        assert!(
            format!("{}", err).contains("task boundary"),
            "expected task-boundary error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("spawn_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::ExclusiveRefAcrossTaskBoundary),
            "expected MIR task-boundary error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_async_let_nested_task_boundary() {
        let program = shape_ast::parser::parse_program(
            r#"
                async function compute(a, &mut b, c) {
                    return a
                }
                async function spawn_nested_conflict() {
                    let mut x = 1
                    async let fut = compute(1, &mut x, 3)
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[1] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        for item in &program.items {
            if let Item::Function(func, _) = item {
                compiler
                    .register_function(func)
                    .expect("function should register");
            }
        }
        let err = compiler
            .compile_function(func)
            .expect_err("nested MIR task-boundary error should surface as a compile error");
        assert!(
            format!("{}", err).contains("task boundary"),
            "expected task-boundary error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("spawn_nested_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::ExclusiveRefAcrossTaskBoundary),
            "expected MIR task-boundary error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_join_task_boundary() {
        let program = shape_ast::parser::parse_program(
            r#"
                async function join_conflict() {
                    let mut x = 1
                    await join all {
                        &mut x,
                        2,
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("join MIR task-boundary error should surface as a compile error");
        assert!(
            format!("{}", err).contains("task boundary"),
            "expected task-boundary error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("join_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::ExclusiveRefAcrossTaskBoundary),
            "expected MIR task-boundary error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_closure_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                function closure_escape() {
                    let x = 1
                    let r = &x
                    let f = || r
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("non-escaping closure ref capture should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("closure_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "non-escaping closure ref capture should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_array_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                function array_escape() {
                    let x = 1
                    let arr = [&x]
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local array ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("array_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local array ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_indirect_array_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                function indirect_array_escape() {
                    let x = 1
                    let r = &x
                    let arr = [r]
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local indirect array ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("indirect_array_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local indirect array ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_object_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                function object_escape() {
                    let x = 1
                    let obj = { value: &x }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local object ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("object_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local object ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_indirect_object_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                function indirect_object_escape() {
                    let x = 1
                    let r = &x
                    let obj = { value: r }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local indirect object ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("indirect_object_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local indirect object ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_struct_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                type Point { value: int }

                function struct_escape() {
                    let x = 1
                    let point = Point { value: &x }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[1] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .compile_item_with_context(&program.items[0], false)
            .expect("struct type should register");
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local struct ref storage should now compile");
        let analysis = compiler
            .mir_borrow_analyses
            .get("struct_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local struct ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_top_level_object_direct_reference_storage_rejected() {
        let program = shape_ast::parser::parse_program(
            r#"
                let x = 1
                let obj = { value: &x }
            "#,
        )
        .expect("parse failed");

        let err = BytecodeCompiler::new()
            .compile(&program)
            .expect_err("top-level object reference storage should surface as a compile error");
        assert!(
            format!("{}", err).contains("cannot store a reference in an object or struct literal"),
            "expected top-level object-storage error, got {}",
            err
        );
    }

    #[test]
    fn test_compile_top_level_array_direct_reference_storage_rejected() {
        let program = shape_ast::parser::parse_program(
            r#"
                let x = 1
                let arr = [&x]
            "#,
        )
        .expect("parse failed");

        let err = BytecodeCompiler::new()
            .compile(&program)
            .expect_err("top-level array reference storage should surface as a compile error");
        assert!(
            format!("{}", err).contains("cannot store a reference in an array"),
            "expected top-level array-storage error, got {}",
            err
        );
    }

    #[test]
    fn test_compile_top_level_reference_cannot_escape_into_closure() {
        let program = shape_ast::parser::parse_program(
            r#"
                let x = 1
                let r = &x
                let f = || r
            "#,
        )
        .expect("parse failed");

        let err = BytecodeCompiler::new()
            .compile(&program)
            .expect_err("top-level closure capture should reject escaped references");
        assert!(
            format!("{}", err).contains("[B0003]"),
            "expected top-level closure reference escape error, got {}",
            err
        );
    }

    #[test]
    fn test_compile_top_level_struct_direct_reference_storage_rejected() {
        let program = shape_ast::parser::parse_program(
            r#"
                type Point { value: int }
                let x = 1
                let point = Point { value: &x }
            "#,
        )
        .expect("parse failed");

        let err = BytecodeCompiler::new()
            .compile(&program)
            .expect_err("top-level struct reference storage should surface as a compile error");
        assert!(
            format!("{}", err).contains("cannot store a reference in an object or struct literal"),
            "expected top-level struct-storage error, got {}",
            err
        );
    }

    #[test]
    fn test_compile_function_records_mir_enum_tuple_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                enum Maybe { Value(int), Other }

                function enum_tuple_escape() {
                    let x = 1
                    let value = Maybe::Value(&x)
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[1] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .compile_item_with_context(&program.items[0], false)
            .expect("enum should register");
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local enum tuple ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("enum_tuple_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local enum tuple ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_indirect_enum_tuple_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                enum Maybe { Value(int), Other }

                function indirect_enum_tuple_escape() {
                    let x = 1
                    let r = &x
                    let value = Maybe::Value(r)
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[1] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .compile_item_with_context(&program.items[0], false)
            .expect("enum should register");
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local indirect enum tuple ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("indirect_enum_tuple_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local indirect enum tuple ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_enum_struct_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                enum Maybe {
                    Err { code: int }
                }

                function enum_struct_escape() {
                    let x = 1
                    let value = Maybe::Err { code: &x }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[1] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .compile_item_with_context(&program.items[0], false)
            .expect("enum should register");
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local enum struct ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("enum_struct_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local enum struct ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_top_level_enum_direct_reference_storage_rejected() {
        let program = shape_ast::parser::parse_program(
            r#"
                enum Maybe { Value(int), Other }
                let x = 1
                let value = Maybe::Value(&x)
            "#,
        )
        .expect("parse failed");

        let err = BytecodeCompiler::new()
            .compile(&program)
            .expect_err("top-level enum reference storage should surface as a compile error");
        assert!(
            format!("{}", err).contains("cannot store a reference in an enum payload"),
            "expected top-level enum-payload error, got {}",
            err
        );
    }

    #[test]
    fn test_compile_function_records_mir_property_assignment_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                function property_assignment_escape() {
                    var obj = { value: 0 }
                    let x = 1
                    obj.value = &x
                    0
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local property ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("property_assignment_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local property ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_indirect_property_assignment_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                function indirect_property_assignment_escape() {
                    var obj = { value: 0 }
                    let x = 1
                    let r = &x
                    obj.value = r
                    0
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local indirect property ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("indirect_property_assignment_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local indirect property ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_index_assignment_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                function index_assignment_escape() {
                    var arr = [0]
                    let x = 1
                    arr[0] = &x
                    0
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local index ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("index_assignment_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local index ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_indirect_index_assignment_reference_escape() {
        let program = shape_ast::parser::parse_program(
            r#"
                function indirect_index_assignment_escape() {
                    var arr = [0]
                    let x = 1
                    let r = &x
                    arr[0] = r
                    0
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("local indirect index ref storage should now compile");

        let analysis = compiler
            .mir_borrow_analyses
            .get("indirect_index_assignment_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "local indirect index ref storage should now be accepted, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_returning_local_array_with_ref_still_errors() {
        let program = shape_ast::parser::parse_program(
            r#"
                function array_escape() {
                    let x = 1
                    let arr = [&x]
                    return arr
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("returned local array ref storage should still surface as a compile error");
        assert!(
            format!("{}", err).contains("cannot store a reference in an array"),
            "expected returned array-storage error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("array_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::ReferenceStoredInArray),
            "expected returned array ref storage error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_returning_closure_with_ref_still_errors() {
        let program = shape_ast::parser::parse_program(
            r#"
                function closure_escape() {
                    let x = 1
                    let r = &x
                    let f = || r
                    return f
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("returned closure ref capture should still surface as a compile error");
        assert!(
            format!("{}", err).contains("[B0003]"),
            "expected returned closure escape error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("closure_escape")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::ReferenceEscapeIntoClosure),
            "expected returned closure ref capture error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_top_level_property_assignment_direct_reference_storage_rejected() {
        let program = shape_ast::parser::parse_program(
            r#"
                let x = 1
                var obj = { value: 0 }
                obj.value = &x
            "#,
        )
        .expect("parse failed");

        let err = BytecodeCompiler::new()
            .compile(&program)
            .expect_err("top-level property assignment reference storage should error");
        assert!(
            format!("{}", err).contains("cannot store a reference in an object or struct literal"),
            "expected top-level object-field storage error, got {}",
            err
        );
    }

    #[test]
    fn test_compile_top_level_index_assignment_direct_reference_storage_rejected() {
        let program = shape_ast::parser::parse_program(
            r#"
                let x = 1
                var arr = [0]
                arr[0] = &x
            "#,
        )
        .expect("parse failed");

        let err = BytecodeCompiler::new()
            .compile(&program)
            .expect_err("top-level index assignment reference storage should error");
        assert!(
            format!("{}", err).contains("cannot store a reference in an array"),
            "expected top-level array-element storage error, got {}",
            err
        );
    }

    #[test]
    fn test_compile_function_records_mir_owned_closure_capture() {
        let program = shape_ast::parser::parse_program(
            r#"
                function closure_ok() {
                    let x = 1
                    let f = || x
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("owned closure captures should compile cleanly");

        let analysis = compiler
            .mir_borrow_analyses
            .get("closure_ok")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "owned closure capture should stay borrow-clean, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_assignment_expr_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function nested_write() {
                    let mut x = 1
                    let shared = &x
                    let y = (x = 2)
                    shared
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler.compile_function(func).expect_err(
            "MIR assignment-expression write conflict should surface as a compile error",
        );
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("nested_write")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_if_expression_analysis() {
        let program = shape_ast::parser::parse_program(
            r#"
                function branch_write(flag) {
                    let mut x = 1
                    let shared = if flag { &x } else { &x }
                    x = 2
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("if-expression MIR lowering should stay in the supported subset");

        let analysis = compiler
            .mir_borrow_analyses
            .get("branch_write")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "simple if-expression borrow analysis should stay clean, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_while_expression_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function while_expr_conflict() {
                    let mut x = 1
                    let y = while true {
                        let shared = &x
                        x = 2
                        shared
                        0
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR while-expression write conflict should surface as a compile error");
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("while_expr_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR while-expression write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_for_expression_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function for_expr_conflict(items) {
                    let mut x = 1
                    let y = for item in items {
                        let shared = &x
                        x = 2
                        shared
                        0
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR for-expression write conflict should surface as a compile error");
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("for_expr_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR for-expression write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_loop_expression_break_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function loop_expr_conflict() {
                    let mut x = 1
                    let y = loop {
                        let shared = &x
                        x = 2
                        shared
                        break 0
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler.compile_function(func).expect_err(
            "MIR loop-expression break write conflict should surface as a compile error",
        );
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("loop_expr_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR loop-expression write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_continue_expression_analysis() {
        let program = shape_ast::parser::parse_program(
            r#"
                function continue_expr(flag) {
                    let mut x = 1
                    let y = while flag {
                        if flag { continue } else { x }
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("continue inside while-expression should stay in the supported subset");

        let analysis = compiler
            .mir_borrow_analyses
            .get("continue_expr")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "continue-only while-expression analysis should stay clean, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_destructure_decl_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function destructure_decl_conflict(pair) {
                    var [left, right] = pair
                    let shared = &left
                    left = 2
                    shared
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler.compile_function(func).expect_err(
            "MIR destructuring declaration write conflict should surface as a compile error",
        );
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("destructure_decl_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR destructuring-declaration write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_destructure_param_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function destructure_param_conflict([left, right]) {
                    let mut left_copy = left
                    let shared = &left_copy
                    left_copy = 2
                    shared
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler.compile_function(func).expect_err(
            "MIR destructured-parameter write conflict should surface as a compile error",
        );
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("destructure_param_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR destructured-parameter write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_destructure_for_loop_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function destructure_for_conflict(items) {
                    for [left, right] in items {
                        let mut left_copy = left
                        let shared = &left_copy
                        left_copy = 2
                        shared
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler.compile_function(func).expect_err(
            "MIR destructuring for-loop write conflict should surface as a compile error",
        );
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("destructure_for_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR destructuring for-loop write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_match_expression_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function match_expr_conflict(flag) {
                    let mut x = 1
                    let y = match flag {
                        true => {
                            let shared = &x
                            x = 2
                            shared
                            0
                        }
                        _ => 0
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR match-expression write conflict should surface as a compile error");
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("match_expr_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR match-expression write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_match_expression_identifier_guard_analysis() {
        let program = shape_ast::parser::parse_program(
            r#"
                function guarded_match(v) {
                    let y = match v {
                        x where x > 0 => x
                        _ => 0
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        compiler
            .compile_function(func)
            .expect("simple guarded match should stay in the MIR-supported subset");

        let analysis = compiler
            .mir_borrow_analyses
            .get("guarded_match")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "guarded match analysis should stay clean, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_match_expression_array_pattern_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function array_match_conflict(pair) {
                    let mut x = 1
                    let y = match pair {
                        [left, right] => {
                            let shared = &x
                            x = 2
                            shared
                            0
                        }
                        _ => 0
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR array-pattern match write conflict should surface as a compile error");
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("array_match_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR array-pattern match write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_match_expression_constructor_pattern_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function constructor_match_conflict(opt) {
                    let mut x = 1
                    let y = match opt {
                        Some(v) => {
                            let shared = &x
                            x = 2
                            shared
                            0
                        }
                        None => 0
                    }
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler.compile_function(func).expect_err(
            "MIR constructor-pattern match write conflict should surface as a compile error",
        );
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("constructor_match_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR constructor-pattern match write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_rest_destructure_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function rest_destructure_conflict(items) {
                    var [head, ...tail] = items
                    let shared = &tail
                    tail = items
                    shared
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR rest-destructure write conflict should surface as a compile error");
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("rest_destructure_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR rest-destructure write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_decomposition_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function decomposition_conflict(merged) {
                    var (left: {x}, right: {y}) = merged
                    let shared = &left
                    left = merged
                    shared
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler.compile_function(func).expect_err(
            "MIR decomposition-pattern write conflict should surface as a compile error",
        );
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("decomposition_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR decomposition-pattern write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_list_comprehension_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function list_comp_conflict() {
                    let mut x = 1
                    let shared = &x
                    let xs = [(x = 2) for y in [1]]
                    shared
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR list-comprehension write conflict should surface as a compile error");
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("list_comp_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR list-comprehension write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_function_records_mir_from_query_write_conflict() {
        let program = shape_ast::parser::parse_program(
            r#"
                function from_query_conflict() {
                    let mut x = 1
                    let shared = &x
                    let rows = from y in [1] where (x = 2) > 0 select y
                    shared
                }
            "#,
        )
        .expect("parse failed");
        let func = match &program.items[0] {
            Item::Function(func, _) => func,
            _ => panic!("expected function item"),
        };

        let mut compiler = BytecodeCompiler::new();
        compiler
            .register_function(func)
            .expect("function should register");
        let err = compiler
            .compile_function(func)
            .expect_err("MIR from-query write conflict should surface as a compile error");
        assert!(
            format!("{}", err).contains("B0002"),
            "expected B0002-style error, got {}",
            err
        );

        let analysis = compiler
            .mir_borrow_analyses
            .get("from_query_conflict")
            .expect("borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected MIR from-query write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_removed_function_produces_error_not_stack_overflow() {
        // When a comptime annotation handler removes a function via `remove target`,
        // calling that function should produce a clear compile error, not a stack overflow.
        let code = r#"
            annotation remove_me() {
                targets: [function]
                comptime post(target, ctx) {
                    remove target
                }
            }

            @remove_me()
            fn doomed() {
                42
            }

            doomed()
        "#;
        let result = compiles(code);
        assert!(
            result.is_err(),
            "Calling a removed function should produce a compile error"
        );
        let err_msg = result.unwrap_err();
        assert!(
            err_msg.contains("removed"),
            "Error should mention function was removed: {}",
            err_msg
        );
    }

    #[test]
    fn test_removed_function_ref_produces_error() {
        // Referencing a removed function (not calling it) should also error.
        let code = r#"
            annotation remove_me() {
                targets: [function]
                comptime post(target, ctx) {
                    remove target
                }
            }

            @remove_me()
            fn doomed() {
                42
            }

            let f = doomed
        "#;
        let result = compiles(code);
        assert!(
            result.is_err(),
            "Referencing a removed function should produce a compile error"
        );
        let err_msg = result.unwrap_err();
        assert!(
            err_msg.contains("removed"),
            "Error should mention function was removed: {}",
            err_msg
        );
    }

    #[test]
    fn test_analyze_non_function_items_records_main_context() {
        let program = shape_ast::parser::parse_program(
            r#"
                let x = 1
                x
            "#,
        )
        .expect("parse failed");

        let mut compiler = BytecodeCompiler::new();
        compiler
            .analyze_non_function_items_with_mir("__main__", &program.items)
            .expect("top-level MIR analysis should succeed");

        // MIR is now the sole authority - no need to check authority flag.
        let analysis = compiler
            .mir_borrow_analyses
            .get("__main__")
            .expect("top-level borrow analysis should be recorded");
        assert!(
            analysis.errors.is_empty(),
            "unexpected top-level MIR errors: {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_analyze_non_function_items_reports_top_level_write_while_borrowed() {
        let program = shape_ast::parser::parse_program(
            r#"
                let mut x = [1]
                let r = &x
                x = [2]
                let y = r
            "#,
        )
        .expect("parse failed");

        let mut compiler = BytecodeCompiler::new();
        let err = compiler
            .analyze_non_function_items_with_mir("__main__", &program.items)
            .expect_err("top-level MIR analysis should reject write-while-borrowed");

        assert!(
            format!("{}", err).contains("[B0002]"),
            "expected MIR top-level borrow diagnostic, got {}",
            err
        );
        let analysis = compiler
            .mir_borrow_analyses
            .get("__main__")
            .expect("top-level borrow analysis should be recorded");
        assert!(
            analysis
                .errors
                .iter()
                .any(|error| error.kind == BorrowErrorKind::WriteWhileBorrowed),
            "expected top-level write-while-borrowed error, got {:?}",
            analysis.errors
        );
    }

    #[test]
    fn test_compile_reports_top_level_mir_borrow_error() {
        // Direct call to analyze_non_function_items_with_mir validates that
        // the MIR analysis correctly detects borrow violations in top-level code.
        // (Not yet wired into the compilation pipeline due to false positives
        // on method chains.)
        let source = r#"
                let mut x = [1]
                let r = &x
                x = [2]
                let y = r
            "#;
        let program = shape_ast::parser::parse_program(source).expect("parse");
        let mut compiler = BytecodeCompiler::new();
        let result = compiler.analyze_non_function_items_with_mir("__main__", &program.items);

        assert!(result.is_err(), "expected top-level compile error");
        let err = format!("{:?}", result.unwrap_err());
        assert!(
            err.contains("B0002"),
            "expected top-level MIR borrow diagnostic, got {}",
            err
        );
    }

    #[test]
    fn test_compile_reports_module_body_mir_borrow_error() {
        // Direct call to analyze_non_function_items_with_mir validates that
        // the MIR analysis correctly detects borrow violations in module-level code.
        let source = r#"
                let mut x = [1]
                let r = &x
                x = [2]
                let y = r
            "#;
        let program = shape_ast::parser::parse_program(source).expect("parse");
        let mut compiler = BytecodeCompiler::new();
        let result = compiler.analyze_non_function_items_with_mir("__module__", &program.items);

        assert!(result.is_err(), "expected module-body compile error");
        let err = format!("{:?}", result.unwrap_err());
        assert!(
            err.contains("B0002"),
            "expected module-body MIR borrow diagnostic, got {}",
            err
        );
    }

    #[test]
    fn test_interprocedural_alias_summary_extracted() {
        let code = r#"
            function touch(a, b) {
                a[0] = 1
                return b[0]
            }
        "#;
        let program = shape_ast::parser::parse_program(code).expect("parse failed");
        let mut compiler = BytecodeCompiler::new();
        if let Item::Function(func, _) = &program.items[0] {
            compiler.register_function(func).expect("register");
            compiler.compile_function(func).expect("compile touch");
        }
        let summary = compiler
            .function_borrow_summaries
            .get("touch")
            .expect("touch should have a borrow summary");
        assert!(
            !summary.conflict_pairs.is_empty(),
            "touch should have conflict pairs: mutated param 0 vs read param 1"
        );
    }

    // =========================================================================
    // Composable return reference summary integration tests
    // =========================================================================

    #[test]
    fn test_composable_return_reference_summary() {
        // fn identity(&x) { x }
        // fn wrapper(&y) { identity(y) }
        // wrapper should have return_summary tracing to param 0
        let code = r#"
fn identity(&x) { x }
fn wrapper(&y) { identity(y) }
"#;
        let program = shape_ast::parser::parse_program(code).expect("parse failed");
        let mut compiler = BytecodeCompiler::new();
        compiler.allow_internal_builtins = true;
        // Register both functions first (two-pass)
        for item in &program.items {
            if let Item::Function(func, _) = item {
                compiler.register_function(func).expect("register");
            }
        }
        // Compile in order: identity first, then wrapper
        for item in &program.items {
            if let Item::Function(func, _) = item {
                compiler.compile_function(func).expect("compile");
            }
        }

        let summary = compiler
            .function_borrow_summaries
            .get("wrapper")
            .expect("wrapper should have a borrow summary");
        assert!(
            summary.return_summary.is_some(),
            "wrapper should have a return_summary from composed identity call"
        );
        let ret = summary.return_summary.as_ref().unwrap();
        assert_eq!(ret.param_index, 0, "should trace to wrapper's param 0");
    }

    #[test]
    fn test_composable_return_summary_local_shadow_conservative() {
        // Global fn foo(&x) { x }, then bar defines local closure `foo` that
        // shadows the global. The call `foo(y)` in bar should NOT get composed
        // return summary from global foo.
        let code = r#"
fn foo(&x) { x }
fn bar(&y) {
    let foo = |z| { z }
    foo(y)
}
"#;
        let program = shape_ast::parser::parse_program(code).expect("parse failed");
        let mut compiler = BytecodeCompiler::new();
        compiler.allow_internal_builtins = true;
        for item in &program.items {
            if let Item::Function(func, _) = item {
                compiler.register_function(func).expect("register");
            }
        }
        for item in &program.items {
            if let Item::Function(func, _) = item {
                compiler.compile_function(func).expect("compile");
            }
        }

        // bar should NOT have a composed return summary from global foo,
        // because the local closure `foo` shadows it
        let has_composed = compiler
            .function_borrow_summaries
            .get("bar")
            .and_then(|s| s.return_summary.as_ref())
            .is_some();
        assert!(
            !has_composed,
            "local shadow should prevent composition with global foo"
        );
    }

    #[test]
    fn test_composable_return_summary_module_binding_shadow() {
        // A module binding named "foo" should prevent composition with a
        // global function "foo". This exercises the
        // resolve_scoped_module_binding_name() check in build_callee_summaries().
        let code = r#"
fn foo(&x) { x }
fn bar(&y) { foo(y) }
"#;
        let program = shape_ast::parser::parse_program(code).expect("parse failed");
        let mut compiler = BytecodeCompiler::new();
        compiler.allow_internal_builtins = true;
        for item in &program.items {
            if let Item::Function(func, _) = item {
                compiler.register_function(func).expect("register");
            }
        }
        // Compile foo first so it gets a return_summary
        for item in &program.items {
            if let Item::Function(func, _) = item {
                compiler.compile_function(func).expect("compile");
            }
        }
        // Sanity: without module binding shadow, bar DOES get a composed summary
        assert!(
            compiler
                .function_borrow_summaries
                .get("bar")
                .and_then(|s| s.return_summary.as_ref())
                .is_some(),
            "bar should have composed summary before module binding shadow"
        );

        // Now simulate a module binding named "foo" and recompile bar.
        // This mimics `import { foo } from some_module` shadowing global foo.
        compiler.module_bindings.insert("foo".to_string(), 999);
        // Re-register and recompile bar
        if let Item::Function(func, _) = &program.items[1] {
            compiler.register_function(func).expect("re-register bar");
            compiler.compile_function(func).expect("recompile bar");
        }
        let has_composed = compiler
            .function_borrow_summaries
            .get("bar")
            .and_then(|s| s.return_summary.as_ref())
            .is_some();
        assert!(
            !has_composed,
            "module binding shadow should prevent composition with global foo"
        );
    }
}