shape-vm 0.3.1

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
//! Storage Planning Pass — decides the runtime storage class for each binding.
//!
//! After MIR lowering and borrow analysis, this pass examines each local slot
//! and assigns a `BindingStorageClass`:
//!
//! - `Direct`: Default for bindings that are never captured, never aliased, never escape.
//! - `UniqueHeap`: For bindings that escape into closures with mutation (need Arc wrapper).
//! - `SharedCow`: For `var` bindings that are aliased AND mutated (copy-on-write),
//!   or for escaped mutable aliased bindings.
//! - `Reference`: For bindings that hold first-class references.
//! - `Deferred`: Only if analysis was incomplete (had fallbacks).
//!
//! The pass also computes `EscapeStatus` for each slot:
//! - `Local`: Stays within the declaring scope.
//! - `Captured`: Captured by a closure.
//! - `Escaped`: Flows to the return slot (escapes the function).
//!
//! Escape status drives storage decisions (escaped+aliased+mutated → SharedCow)
//! and is consumed by the post-solve relaxation pass to determine whether
//! local containers can safely hold references.
//!
//! The pass runs once per function and produces a `StoragePlan` consumed by codegen.

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

use crate::mir::analysis::{BorrowAnalysis, FunctionBorrowSummary};
use crate::mir::types::*;
use crate::type_tracking::{
    Aliasability, BindingOwnershipClass, BindingSemantics, BindingStorageClass, EscapeStatus,
    MutationCapability,
};

/// Phase V0.a bisect-safety gate; remove once ownership Phase 1 lands.
///
/// When `true` (the default), `var` bindings — i.e. bindings whose ownership
/// class is `BindingOwnershipClass::Flexible` — are assigned
/// `BindingStorageClass::SharedCow` regardless of aliasing/mutation status.
/// This matches the ownership-aware runtime v2 contract: `var` opts into
/// SharedCow aliasing by construction. Flip the flag off (set
/// `SHAPE_V2_VAR_SHAREDCOW=0`) to fall back to the narrower pre-V0.a rule
/// that only promotes to SharedCow when the binding is both aliased AND
/// mutated. This is a temporary bisect safety net; once the rest of ownership
/// Phase 1 lands, the flag (and this helper) can be deleted.
///
/// The env var is read once per process and cached in a `OnceLock`. Values
/// `0`/`false`/`off`/`no` (case-insensitive, trimmed) or an empty string
/// disable the flag; anything else (or the env var being unset) leaves the
/// default `true`.
fn var_sharedcow_default_enabled() -> bool {
    static CACHED: OnceLock<bool> = OnceLock::new();
    *CACHED.get_or_init(|| match std::env::var("SHAPE_V2_VAR_SHAREDCOW") {
        // Explicit opt-out values disable the flag.
        Ok(v) => !matches!(
            v.trim(),
            "0" | "false" | "FALSE" | "False" | "off" | "OFF" | "Off" | "no" | "NO" | "No" | ""
        ),
        // Not set → default on.
        Err(_) => true,
    })
}

/// Maximum element count for a non-escaping aggregate to be eligible for the
/// stack-allocated / inline optimization hint. Arrays larger than this are
/// never flagged, even if they don't escape. The threshold matches the
/// SmallVec inline-capacity target discussed in the Phase D design notes
/// (8 elements × 8 bytes = 64 B, one cache line).
pub const INLINE_ARRAY_MAX_ELEMENTS: usize = 8;

/// The computed storage plan for a single function.
#[derive(Debug, Clone)]
pub struct StoragePlan {
    /// Maps each local slot to its decided storage class.
    pub slot_classes: HashMap<SlotId, BindingStorageClass>,
    /// Maps each local slot to its enriched binding semantics.
    pub slot_semantics: HashMap<SlotId, BindingSemantics>,
    /// Optimization hint (Phase D.2 infrastructure): slots that hold a small,
    /// compile-time-sized aggregate (array/tuple literal) that is provably
    /// non-escaping, non-captured, and non-aliased. The value is the element
    /// count.
    ///
    /// Consumers may choose to:
    ///   * emit inline-on-stack storage (SROA — eliminate the allocation),
    ///   * pick a SmallVec-backed `HeapValue::Array` path, or
    ///   * ignore the hint entirely (semantics-preserving).
    ///
    /// Today no consumer acts on the hint; it is recorded so that future
    /// codegen passes (inline arrays, scalar replacement of aggregates) can
    /// activate without re-running escape analysis.
    pub inline_array_sizes: HashMap<SlotId, usize>,
    /// Closure Spec Phase B: slots that hold closure values (defined by a
    /// `ClosureCapture` statement) and that provably do not escape their
    /// enclosing function via any of the §2.1 escape vectors
    /// (return, container store, field/index/deref write, capture by an
    /// escaping closure, task boundary, call-site argument, or
    /// `UniqueHeap`/`SharedCow` promotion).
    ///
    /// Consumed by Phase C's per-closure specialization decision: when a
    /// closure slot is in this set, the specialization may stack-allocate the
    /// closure and inline its body into the receiving specialization instead
    /// of heap-allocating a `TypedClosure`. Slots NOT in this set are
    /// considered escaping and must use the heap variant.
    ///
    /// Today no consumer acts on the set (Phase C is not landed). It is
    /// recorded so the specialization pass can activate without re-running
    /// escape analysis.
    pub non_escaping_closure_slots: HashSet<SlotId>,
}

/// Input bundle for the storage planner.
pub struct StoragePlannerInput<'a> {
    /// The MIR function to plan storage for.
    pub mir: &'a MirFunction,
    /// Borrow analysis results (includes liveness).
    pub analysis: &'a BorrowAnalysis,
    /// Per-slot ownership/storage semantics from the compiler's type tracker.
    pub binding_semantics: &'a HashMap<u16, BindingSemantics>,
    /// Slots captured by any closure in this function.
    pub closure_captures: &'a HashSet<SlotId>,
    /// Slots that are mutated inside a closure body.
    pub mutable_captures: &'a HashSet<SlotId>,
    /// Whether MIR lowering had fallbacks (incomplete analysis).
    pub had_fallbacks: bool,
    /// Previously-computed callee borrow summaries, keyed by function name.
    /// Used by the closure-escape analysis (Closure Spec Phase B) to check
    /// whether a closure passed as a call-site argument may escape into the
    /// callee. `None` (or missing entries) is treated conservatively — the
    /// closure is assumed to escape. Populated from
    /// `Compiler::function_borrow_summaries`.
    pub callee_summaries: Option<&'a HashMap<String, FunctionBorrowSummary>>,
}

/// Scan MIR statements and terminators to find slots captured by closures.
///
/// Returns `(all_captures, mutable_captures)`:
/// - `all_captures`: slots referenced in `ClosureCapture` statements
/// - `mutable_captures`: subset of captured slots that are assigned more than
///   once in the function (i.e., re-assigned after initial definition). A slot
///   with only its initial definition assignment is not considered mutably captured.
pub fn collect_closure_captures(mir: &MirFunction) -> (HashSet<SlotId>, HashSet<SlotId>) {
    let mut all_captures = HashSet::new();
    let mut assign_counts: HashMap<SlotId, u32> = HashMap::new();

    for block in mir.iter_blocks() {
        for stmt in &block.statements {
            match &stmt.kind {
                StatementKind::ClosureCapture { operands, .. } => {
                    for op in operands {
                        if let Some(slot) = operand_root_slot(op) {
                            all_captures.insert(slot);
                        }
                    }
                }
                StatementKind::Assign(place, _) => {
                    if let Place::Local(slot) = place {
                        *assign_counts.entry(*slot).or_insert(0) += 1;
                    }
                }
                _ => {}
            }
        }
    }

    // A slot is "mutably captured" if it is captured AND assigned more than once
    // (meaning it has re-assignments beyond its initial definition).
    let mutable_captures: HashSet<SlotId> = all_captures
        .iter()
        .filter(|slot| assign_counts.get(slot).copied().unwrap_or(0) > 1)
        .copied()
        .collect();

    (all_captures, mutable_captures)
}

/// Extract the root SlotId from an operand, if it references a local.
fn operand_root_slot(op: &Operand) -> Option<SlotId> {
    match op {
        Operand::Copy(place) | Operand::Move(place) | Operand::MoveExplicit(place) => {
            Some(place.root_local())
        }
        Operand::Constant(_) => None,
    }
}

/// Check whether a slot has any active loan (borrow) in the analysis.
/// A slot with loans is holding or being borrowed as a reference.
fn slot_has_active_loans(slot: SlotId, analysis: &BorrowAnalysis) -> bool {
    for loan_info in analysis.loans.values() {
        if loan_info.borrowed_place.root_local() == slot {
            return true;
        }
    }
    false
}

/// Check whether a slot is aliased — it appears as an operand in more than
/// one `Assign` rvalue across the function, or it is captured.
fn slot_is_aliased(slot: SlotId, mir: &MirFunction, closure_captures: &HashSet<SlotId>) -> bool {
    if closure_captures.contains(&slot) {
        return true;
    }

    let mut use_count = 0u32;
    for block in mir.iter_blocks() {
        for stmt in &block.statements {
            if let StatementKind::Assign(_, rvalue) = &stmt.kind {
                if rvalue_uses_slot(rvalue, slot) {
                    use_count += 1;
                    if use_count > 1 {
                        return true;
                    }
                }
            }
        }
        // Also check terminators for uses
        if let TerminatorKind::Call { func, args, .. } = &block.terminator.kind {
            if operand_uses_slot(func, slot) {
                use_count += 1;
            }
            for arg in args {
                if operand_uses_slot(arg, slot) {
                    use_count += 1;
                }
            }
            if use_count > 1 {
                return true;
            }
        }
    }
    false
}

/// Check if a slot is mutated in the function (assigned to after initial definition).
fn slot_is_mutated(slot: SlotId, mir: &MirFunction) -> bool {
    let mut assign_count = 0u32;
    for block in mir.iter_blocks() {
        for stmt in &block.statements {
            if let StatementKind::Assign(Place::Local(s), _) = &stmt.kind {
                if *s == slot {
                    assign_count += 1;
                    if assign_count > 1 {
                        return true;
                    }
                }
            }
        }
    }
    false
}

/// Check whether an rvalue uses (reads from) a given slot.
fn rvalue_uses_slot(rvalue: &Rvalue, slot: SlotId) -> bool {
    match rvalue {
        Rvalue::Use(op) | Rvalue::Clone(op) | Rvalue::UnaryOp(_, op) => {
            operand_uses_slot(op, slot)
        }
        Rvalue::Borrow(_, place) => place.root_local() == slot,
        Rvalue::BinaryOp(_, lhs, rhs) => {
            operand_uses_slot(lhs, slot) || operand_uses_slot(rhs, slot)
        }
        Rvalue::Aggregate(ops) => ops.iter().any(|op| operand_uses_slot(op, slot)),
        Rvalue::EnumTest { operand, .. }
        | Rvalue::EnumPayload { operand, .. }
        | Rvalue::TypePatternTest { operand, .. }
        | Rvalue::EnumDiscriminantTest { operand, .. } => operand_uses_slot(operand, slot),
    }
}

/// Check whether an operand references a given slot.
fn operand_uses_slot(op: &Operand, slot: SlotId) -> bool {
    match op {
        Operand::Copy(place) | Operand::Move(place) | Operand::MoveExplicit(place) => {
            place.root_local() == slot
        }
        Operand::Constant(_) => false,
    }
}

/// Run the storage planning pass on a single function.
///
/// The algorithm examines each local slot and decides its storage class:
///
/// 1. If `had_fallbacks` is true, all slots remain `Deferred` (analysis incomplete).
/// 2. For each slot, check closure captures, mutations, aliasing, and loans.
/// 3. Assign the appropriate `BindingStorageClass`.
pub fn plan_storage(input: &StoragePlannerInput<'_>) -> StoragePlan {
    let mut slot_classes = HashMap::new();
    let mut slot_semantics = HashMap::new();

    // If MIR lowering had fallbacks, we cannot trust the analysis.
    // Leave everything Deferred so codegen uses conservative paths.
    if input.had_fallbacks {
        for slot_idx in 0..input.mir.num_locals {
            let slot = SlotId(slot_idx);
            slot_classes.insert(slot, BindingStorageClass::Deferred);
            slot_semantics.insert(
                slot,
                BindingSemantics {
                    ownership_class: BindingOwnershipClass::OwnedImmutable,
                    storage_class: BindingStorageClass::Deferred,
                    aliasability: Aliasability::Unique,
                    mutation_capability: MutationCapability::Immutable,
                    escape_status: EscapeStatus::Local,
                    return_ownership_hint: None,
                },
            );
        }
        return StoragePlan {
            slot_classes,
            slot_semantics,
            inline_array_sizes: HashMap::new(),
            non_escaping_closure_slots: HashSet::new(),
        };
    }

    let var_sharedcow_enabled = var_sharedcow_default_enabled();
    for slot_idx in 0..input.mir.num_locals {
        let slot = SlotId(slot_idx);
        let (storage_class, semantics) =
            decide_slot_storage(slot, input, var_sharedcow_enabled);
        slot_classes.insert(slot, storage_class);
        slot_semantics.insert(slot, semantics);
    }

    // Detect small non-escaping aggregates and record the hint. This is
    // gathered after slot decisions so we can consult `slot_semantics` for the
    // authoritative escape/aliasing verdict.
    let inline_array_sizes = detect_inline_array_candidates(input, &slot_semantics);

    // Closure Spec Phase B: classify every closure slot (each slot defined by
    // a `ClosureCapture` statement) as escaping or non-escaping, using the
    // full §2.1 escape-vector table plus a fixed-point over transitive
    // closure captures.
    let non_escaping_closure_slots =
        detect_non_escaping_closure_slots(input, &slot_classes);

    // Closure Spec Phase D: promote the storage class of outer slots whose
    // ONLY heap-indirection driver is a mutable capture by a non-escaping
    // closure to `LocalMutablePtr`. The previous pass assigned `UniqueHeap`
    // to such slots (Rule 2 in `decide_slot_storage`) — that was the v1-style
    // "box into SharedCell on capture" decision. In v2 the closure env holds
    // a typed stack pointer instead; the binding can stay on the frame.
    //
    // Preconditions (all must hold):
    //   1. The slot is the root of a mutably-captured operand in a
    //      `ClosureCapture` statement.
    //   2. The closure slot that captures it is in
    //      `non_escaping_closure_slots`.
    //   3. The slot is not itself a first-class reference or promoted to a
    //      heap-aliased class for some other reason (e.g. also stored into
    //      a collection).
    //
    // Escape fallback (§4.3): for `let mut` + escaping closure with a mutable
    // capture, `compile_expr_closure` emits `B0003`. For `var` + escaping
    // closure, the SharedCow path is unchanged.
    promote_local_mutable_ptr_slots(
        input,
        &non_escaping_closure_slots,
        &mut slot_classes,
        &mut slot_semantics,
    );

    StoragePlan {
        slot_classes,
        slot_semantics,
        inline_array_sizes,
        non_escaping_closure_slots,
    }
}

/// Phase D — promote outer-slot storage class to `LocalMutablePtr` when the
/// slot is captured by a non-escaping closure.
///
/// This runs AFTER the main storage-class decision pass and AFTER the
/// `non_escaping_closure_slots` computation. It walks every `ClosureCapture`
/// in the MIR; for each operand whose root slot currently has a conservative
/// class (`Direct` / `Deferred` / `UniqueHeap`) it promotes to
/// `LocalMutablePtr`. The MIR statement does not distinguish
/// mutable-vs-immutable operands — the closure-compiler side inspects the
/// closure body via `EnvironmentAnalyzer::analyze_function_with_mutability`
/// and only emits `LoadCaptureMutPtr<T>` / `StoreCaptureMutPtr<T>` for
/// captures that the body actually mutates. Unused promotions are harmless:
/// `LocalMutablePtr` carries the same "slot stays on the frame" meaning as
/// `Direct` and reads through the existing non-closure code paths unchanged.
///
/// Conservative: if the outer slot has any other escape vector (it is also
/// returned, stored in a container, or captured by a different escaping
/// closure), `decide_slot_storage` already put it in a non-promotable class
/// (e.g. `SharedCow`) and we leave it alone.
fn promote_local_mutable_ptr_slots(
    input: &StoragePlannerInput<'_>,
    non_escaping_closure_slots: &HashSet<SlotId>,
    slot_classes: &mut HashMap<SlotId, BindingStorageClass>,
    slot_semantics: &mut HashMap<SlotId, BindingSemantics>,
) {
    for block in input.mir.iter_blocks() {
        for stmt in &block.statements {
            let StatementKind::ClosureCapture {
                closure_slot,
                operands,
                ..
            } = &stmt.kind
            else {
                continue;
            };

            if !non_escaping_closure_slots.contains(closure_slot) {
                continue;
            }

            for op in operands {
                let Some(root) = operand_root_slot(op) else {
                    continue;
                };
                let Some(current) = slot_classes.get(&root).copied() else {
                    continue;
                };
                match current {
                    BindingStorageClass::UniqueHeap
                    | BindingStorageClass::Direct
                    | BindingStorageClass::Deferred => {
                        slot_classes.insert(root, BindingStorageClass::LocalMutablePtr);
                        if let Some(sem) = slot_semantics.get_mut(&root) {
                            sem.storage_class = BindingStorageClass::LocalMutablePtr;
                        }
                    }
                    // SharedCow / Reference / LocalMutablePtr: leave alone.
                    _ => {}
                }
            }
        }
    }
}

/// Scan MIR for aggregate assignments that are safe to inline on the stack.
///
/// A slot is a candidate when **all** of the following hold:
/// - It is assigned exactly one `Rvalue::Aggregate` with `N <= INLINE_ARRAY_MAX_ELEMENTS`.
/// - Its computed `escape_status` is `Local` (does not flow to the return slot).
/// - It is not captured by any closure.
/// - It is not re-assigned after the aggregate initialization (otherwise the
///   slot can't be treated as a fixed-shape value).
/// - It is not mutated through index assignment (future work: inline arrays
///   with index writes would need per-element tracking).
///
/// The hint is purely advisory — emitting it does not commit to any specific
/// codegen strategy. Zero-size aggregates are also skipped since they add no
/// allocation pressure to begin with.
fn detect_inline_array_candidates(
    input: &StoragePlannerInput<'_>,
    slot_semantics: &HashMap<SlotId, BindingSemantics>,
) -> HashMap<SlotId, usize> {
    let mut aggregate_sizes: HashMap<SlotId, usize> = HashMap::new();
    let mut disqualified: HashSet<SlotId> = HashSet::new();

    for block in input.mir.iter_blocks() {
        for stmt in &block.statements {
            let StatementKind::Assign(place, rvalue) = &stmt.kind else {
                continue;
            };
            let Place::Local(slot) = place else {
                // A projection write (e.g. `arr[i] = x`) into a candidate
                // slot disqualifies it — the aggregate shape is mutable.
                disqualified.insert(place.root_local());
                continue;
            };

            match rvalue {
                Rvalue::Aggregate(ops) => {
                    // Only the first aggregate assignment counts. A later
                    // reassignment (even another aggregate) means the slot
                    // isn't a fixed-shape value.
                    if aggregate_sizes.contains_key(slot) {
                        disqualified.insert(*slot);
                    } else {
                        aggregate_sizes.insert(*slot, ops.len());
                    }
                }
                _ => {
                    // Any non-aggregate assignment (re-binding, function
                    // result, etc.) after the aggregate disqualifies the slot.
                    if aggregate_sizes.contains_key(slot) {
                        disqualified.insert(*slot);
                    }
                }
            }
        }
    }

    let mut hints = HashMap::new();
    for (slot, size) in aggregate_sizes {
        if disqualified.contains(&slot) {
            continue;
        }
        if size == 0 || size > INLINE_ARRAY_MAX_ELEMENTS {
            continue;
        }
        let Some(sem) = slot_semantics.get(&slot) else {
            continue;
        };
        if sem.escape_status != EscapeStatus::Local {
            continue;
        }
        // Be defensive: any aliasing (shared-immutable or shared-mutable)
        // rules out the SROA-style optimization, even though the aggregate
        // itself would remain addressable on the stack.
        if sem.aliasability != Aliasability::Unique {
            continue;
        }
        if input.closure_captures.contains(&slot) {
            continue;
        }
        hints.insert(slot, size);
    }
    hints
}

// ── Closure Spec Phase B: non-escape detection for closure slots ────────────
//
// The analysis implements the 10-row escape-vector table from
// `docs/v2-closure-specialization.md` §2.1. Its output is the set of closure
// slots that are provably non-escaping, recorded on `StoragePlan` for the
// Phase C specialization pass to consume.
//
// Soundness discipline: when an escape vector cannot be decided (missing
// callee summary, unknown operand shape), the slot is marked as escaping.
// Any precision lost here is recoverable by Phase C's monomorphization work;
// the cost of a false "non-escaping" verdict is a stack-pointer outliving a
// frame, which is unacceptable.

/// Collect every slot that is defined as a closure value (the destination of
/// a `ClosureCapture` statement). The `closure_slot` field of a
/// `ClosureCapture` identifies the slot that will hold the closure object
/// once the follow-up `Assign(..., ClosurePlaceholder)` completes the
/// definition. Functions with no closure literals produce an empty set.
fn collect_closure_slots(mir: &MirFunction) -> HashSet<SlotId> {
    let mut slots = HashSet::new();
    for block in mir.iter_blocks() {
        for stmt in &block.statements {
            if let StatementKind::ClosureCapture { closure_slot, .. } = &stmt.kind {
                slots.insert(*closure_slot);
            }
        }
    }
    slots
}

/// Build the transitive closure-capture graph: if closure A captures closure
/// B, the map records `A -> {B}`. Used for the §2.4 fixed-point — if A
/// escapes, B escapes too because it is carried inside A's capture layout.
fn build_closure_capture_graph(
    mir: &MirFunction,
    closure_slots: &HashSet<SlotId>,
) -> HashMap<SlotId, HashSet<SlotId>> {
    let mut graph: HashMap<SlotId, HashSet<SlotId>> = HashMap::new();
    for block in mir.iter_blocks() {
        for stmt in &block.statements {
            if let StatementKind::ClosureCapture {
                closure_slot,
                operands,
                ..
            } = &stmt.kind
            {
                for op in operands {
                    let Some(root) = operand_root_slot(op) else {
                        continue;
                    };
                    if closure_slots.contains(&root) {
                        graph
                            .entry(*closure_slot)
                            .or_default()
                            .insert(root);
                    }
                }
            }
        }
    }
    graph
}

/// §2.1 direct-vector escape check for a single closure slot `c`.
///
/// Walks the MIR once per call. Returns `true` if any of rows 1-3, 5-7, 9-10
/// fire; row 4 (transitive capture) and row 8 (call-argument through callee
/// summary) are handled by `detect_non_escaping_closure_slots` after direct
/// vectors are classified.
///
/// The walk uses a single-pass monotonic scan: starting from the singleton
/// tracked set `{c}`, each `Assign(Place::Local(dest), Rvalue::Use(Copy/Move
/// of a tracked slot))` widens the tracked set to include `dest`. This mirrors
/// the existing `slot_flows_to_return` pattern but generalized to every sink
/// the table names, without requiring a separate dataflow pass.
fn closure_slot_escapes_direct(
    c: SlotId,
    input: &StoragePlannerInput<'_>,
) -> bool {
    let mir = input.mir;

    // Row 10: the semantics planner promoted the slot to heap-aliased
    // storage. Any such promotion escapes by construction.
    if let Some(sem) = input.binding_semantics.get(&c.0) {
        match sem.storage_class {
            BindingStorageClass::UniqueHeap | BindingStorageClass::SharedCow => {
                return true;
            }
            _ => {}
        }
    }

    // Iteratively widen the tracked set as the closure flows through local
    // aliases. Each pass also evaluates every escape vector against the
    // current tracked set — reaching any escape sink is a definite "yes".
    let mut tracked: HashSet<SlotId> = HashSet::new();
    tracked.insert(c);

    let mut changed = true;
    while changed {
        changed = false;

        for block in mir.iter_blocks() {
            for stmt in &block.statements {
                match &stmt.kind {
                    // Row 1 (return), Row 2 (Aggregate), Row 3 (struct
                    // field), Row 9 (deref), and local-alias propagation.
                    StatementKind::Assign(place, rvalue) => {
                        let reads_tracked = rvalue_uses_any_slot(rvalue, &tracked);
                        match place {
                            Place::Local(dest) => {
                                // Row 1: dest is the return slot.
                                if *dest == SlotId(0) && reads_tracked {
                                    return true;
                                }
                                // Local-alias propagation: widen the tracked
                                // set so downstream vectors see the alias.
                                if reads_tracked && tracked.insert(*dest) {
                                    changed = true;
                                }
                            }
                            // Row 3: struct-field write `foo.f = c`.
                            Place::Field(..) => {
                                if reads_tracked {
                                    return true;
                                }
                            }
                            // Row 2 subcase / Row 9 variant: index/deref
                            // writes both materialize the value into some
                            // other container.
                            Place::Index(..) | Place::Deref(..) => {
                                if reads_tracked {
                                    return true;
                                }
                            }
                        }

                        // Row 2: `Rvalue::Aggregate` feeding any slot — the
                        // aggregate itself is the escaping container.
                        if let Rvalue::Aggregate(ops) = rvalue {
                            if ops.iter().any(|op| operand_uses_any_slot(op, &tracked)) {
                                return true;
                            }
                        }
                    }
                    // Row 2: store into array / object / enum literal.
                    StatementKind::ArrayStore { operands, .. }
                    | StatementKind::ObjectStore { operands, .. }
                    | StatementKind::EnumStore { operands, .. } => {
                        if operands.iter().any(|op| operand_uses_any_slot(op, &tracked)) {
                            return true;
                        }
                    }
                    // Rows 5 + 6: detached or structured task boundary.
                    // §5.5 allows stack closures across structured boundaries
                    // in the future, but Phase B takes the conservative
                    // verdict — any boundary is escape.
                    StatementKind::TaskBoundary(operands, _) => {
                        if operands.iter().any(|op| operand_uses_any_slot(op, &tracked)) {
                            return true;
                        }
                    }
                    // Row 4 direct contribution: if we find a closure
                    // capturing a tracked slot and that enclosing closure
                    // later turns out to escape, the tracked slot escapes
                    // transitively. Handled by the fixed-point in
                    // `detect_non_escaping_closure_slots`.
                    StatementKind::ClosureCapture { .. }
                    | StatementKind::Drop(_)
                    | StatementKind::Nop => {}
                }
            }

            // Row 8: call-site argument. Conservative default — any call
            // with a tracked slot in its args escapes, unless the callee is a
            // statically-known function whose `FunctionBorrowSummary` marks
            // the corresponding param as non-escaping.
            if let TerminatorKind::Call { func, args, .. } = &block.terminator.kind {
                // Row 7: `snapshot()` is an opaque FFI in v1 — there is no
                // dedicated MIR terminator, so any named call to `snapshot`
                // must be treated as escape. The full treatment lives in §9
                // open question #7.
                let callee_name = match func {
                    Operand::Constant(MirConstant::Function(name)) => Some(name.as_str()),
                    _ => None,
                };
                if callee_name == Some("snapshot") {
                    if args.iter().any(|op| operand_uses_any_slot(op, &tracked)) {
                        return true;
                    }
                }

                let callee_summary = callee_name
                    .and_then(|n| input.callee_summaries.and_then(|m| m.get(n)));

                for (arg_idx, arg) in args.iter().enumerate() {
                    if !operand_uses_any_slot(arg, &tracked) {
                        continue;
                    }
                    // With a summary + a matching param slot, we can trust
                    // the callee's per-param escape bit. Otherwise: escape.
                    match callee_summary {
                        Some(summary) if arg_idx < summary.closure_param_escapes.len() => {
                            if summary.closure_param_escapes[arg_idx] {
                                return true;
                            }
                            // else: callee is transparent for this arg;
                            // continue checking other vectors.
                        }
                        _ => return true,
                    }
                }

                // Indirect call target itself: if the call *target* is the
                // tracked slot, we treat it as non-escape (the closure is
                // invoked in-place). Not a separate vector.
                let _ = func; // explicitly documenting intent
            }
        }
    }

    false
}

/// §2.4 fixed-point over the closure capture graph: if closure A escapes,
/// every closure it captures (B in `graph[A]`) also escapes. The worklist
/// iterates until the escaping set stops growing — monotone, terminates in
/// at most `|closure_slots|` passes.
fn propagate_transitive_closure_escape(
    closure_slots: &HashSet<SlotId>,
    capture_graph: &HashMap<SlotId, HashSet<SlotId>>,
    escaping: &mut HashSet<SlotId>,
) {
    let mut changed = true;
    while changed {
        changed = false;
        for &a in closure_slots {
            if !escaping.contains(&a) {
                continue;
            }
            let Some(captured_closures) = capture_graph.get(&a) else {
                continue;
            };
            for &b in captured_closures {
                if escaping.insert(b) {
                    changed = true;
                }
            }
        }
    }
}

/// Does the MIR contain any named call to `snapshot`, regardless of args?
///
/// Closure spec Phase G §5.6: `snapshot()` captures the full VM state into
/// `SerializableCallFrame` via the interpreter's locals array. Stack-allocated
/// closures live in Cranelift StackSlots and are invisible to that
/// serializer, so any function that may invoke `snapshot()` must not
/// stack-allocate its closures — independent of whether a specific closure
/// flows into `snapshot()`'s argument list. The spec's "forces deopt first"
/// policy reduces to "promote every closure in the function to heap." Phase G
/// implements the conservative half (§5.6 short-circuit); the precise
/// per-closure deopt-with-rematerialization path is future work once MIR
/// gains a first-class `TerminatorKind::Snapshot` (§9 open question #7).
fn mir_contains_snapshot_call(mir: &MirFunction) -> bool {
    for block in mir.iter_blocks() {
        if let TerminatorKind::Call { func, .. } = &block.terminator.kind {
            if let Operand::Constant(MirConstant::Function(name)) = func {
                if name == "snapshot" {
                    return true;
                }
            }
        }
    }
    false
}

/// Populate `StoragePlan.non_escaping_closure_slots` for the function under
/// analysis. Orchestrates: (1) collect closure slots, (2) classify each via
/// §2.1 direct vectors, (3) run the §2.4 transitive-capture fixed-point, (4)
/// invert — any closure slot NOT in the escaping set is non-escaping.
fn detect_non_escaping_closure_slots(
    input: &StoragePlannerInput<'_>,
    _slot_classes: &HashMap<SlotId, BindingStorageClass>,
) -> HashSet<SlotId> {
    let closure_slots = collect_closure_slots(input.mir);
    if closure_slots.is_empty() {
        return HashSet::new();
    }

    // Closure spec Phase G §5.6: function-wide `snapshot()` escape.
    // If any terminator in the function calls `snapshot`, force every
    // closure slot to heap — stack closures cannot survive the VM-state
    // serialization path that snapshot takes. This is the conservative
    // complement to Phase G's JIT-side "snapshot forces deopt first"
    // policy: the MIR planner takes the easy win (heap-allocate every
    // closure in a snapshottable function) so we do not need to emit a
    // JIT deopt guard for every snapshot-reachable stack slot.
    if mir_contains_snapshot_call(input.mir) {
        // All closure slots escape; return the empty "non-escaping" set.
        return HashSet::new();
    }

    // Step 1: direct-vector escape verdict per closure slot.
    let mut escaping: HashSet<SlotId> = HashSet::new();
    for &c in &closure_slots {
        if closure_slot_escapes_direct(c, input) {
            escaping.insert(c);
        }
    }

    // Step 2: transitive propagation via the capture graph.
    let capture_graph = build_closure_capture_graph(input.mir, &closure_slots);
    propagate_transitive_closure_escape(&closure_slots, &capture_graph, &mut escaping);

    // Step 3: invert — slots not in `escaping` are non-escaping.
    closure_slots
        .difference(&escaping)
        .copied()
        .collect()
}

/// Does `rvalue` read from any slot in `slots`? Covers all rvalue shapes.
fn rvalue_uses_any_slot(rvalue: &Rvalue, slots: &HashSet<SlotId>) -> bool {
    match rvalue {
        Rvalue::Use(op) | Rvalue::Clone(op) | Rvalue::UnaryOp(_, op) => {
            operand_uses_any_slot(op, slots)
        }
        Rvalue::Borrow(_, place) => slots.contains(&place.root_local()),
        Rvalue::BinaryOp(_, lhs, rhs) => {
            operand_uses_any_slot(lhs, slots) || operand_uses_any_slot(rhs, slots)
        }
        Rvalue::Aggregate(ops) => ops.iter().any(|op| operand_uses_any_slot(op, slots)),
        Rvalue::EnumTest { operand, .. }
        | Rvalue::EnumPayload { operand, .. }
        | Rvalue::TypePatternTest { operand, .. }
        | Rvalue::EnumDiscriminantTest { operand, .. } => operand_uses_any_slot(operand, slots),
    }
}

/// Does `op` reference a slot in `slots`?
fn operand_uses_any_slot(op: &Operand, slots: &HashSet<SlotId>) -> bool {
    match op {
        Operand::Copy(place) | Operand::Move(place) | Operand::MoveExplicit(place) => {
            slots.contains(&place.root_local())
        }
        Operand::Constant(_) => false,
    }
}

/// Decide the storage class for a single slot, returning both the storage class
/// and enriched binding semantics.
/// Decide the storage class and enriched semantics for a single slot.
///
/// ## Decision matrix
///
/// Priority order (first matching rule wins):
///
/// | #  | Condition                                      | Storage class  |
/// |----|------------------------------------------------|----------------|
/// | 0  | Explicit `Reference` already set               | `Reference`    |
/// | 1  | Slot holds a first-class reference              | `Reference`    |
/// | 1b | **V0.a**: `var` (Flexible) + flag on           | `SharedCow`    |
/// | 2  | Captured by closure with mutation               | `UniqueHeap`   |
/// | 3  | `var` (Flexible) + aliased + mutated            | `SharedCow`    |
/// | 3b | Escaped + aliased + mutated (any ownership)     | `SharedCow`    |
/// | 4  | Everything else                                 | `Direct`       |
///
/// Rule 1b (Phase V0.a): when `SHAPE_V2_VAR_SHAREDCOW` is enabled (the
/// default), every `var` binding is promoted to `SharedCow` regardless of
/// aliasing/mutation. The legacy Rule 3 remains as a safety net and as the
/// behavior observed when the flag is disabled. Rule 1b runs BEFORE Rule 2
/// so that a `var` slot that happens to be mutably captured stays `SharedCow`
/// rather than being routed through the `UniqueHeap` → `LocalMutablePtr`
/// promotion: the spec's Phase 4 contract is that `var` is aliased by
/// construction.
///
/// Notes:
/// - "Aliased" means either captured by a closure or referenced from multiple
///   MIR places (e.g. through a borrow chain).
/// - `UniqueHeap` and `SharedCow` both result in heap boxing at runtime, but
///   `SharedCow` adds copy-on-write semantics for safe shared mutation.
/// - Immutable closure captures stay `Direct` — the closure gets a plain copy.
fn decide_slot_storage(
    slot: SlotId,
    input: &StoragePlannerInput<'_>,
    var_sharedcow_enabled: bool,
) -> (BindingStorageClass, BindingSemantics) {
    let is_captured = input.closure_captures.contains(&slot);
    let is_mutably_captured = input.mutable_captures.contains(&slot);
    let _has_loans = slot_has_active_loans(slot, input.analysis);
    let is_mutated = slot_is_mutated(slot, input.mir);
    let is_aliased = slot_is_aliased(slot, input.mir, input.closure_captures);

    // Look up ownership class from binding semantics
    let ownership = input
        .binding_semantics
        .get(&slot.0)
        .map(|s| s.ownership_class);

    // Check if the binding already has an explicit storage class set
    let explicit_storage = input
        .binding_semantics
        .get(&slot.0)
        .map(|s| s.storage_class);

    let is_escaped = detect_escape_status(slot, input.mir, input.closure_captures)
        == EscapeStatus::Escaped;

    let storage_class = if let Some(BindingStorageClass::Reference) = explicit_storage {
        // Already marked as a reference binding — preserve it.
        BindingStorageClass::Reference
    } else if slot_holds_reference(slot, input.mir) {
        // Rule 1: Bindings that hold first-class references.
        BindingStorageClass::Reference
    } else if matches!(ownership, Some(BindingOwnershipClass::Flexible)) && var_sharedcow_enabled {
        // Rule 1b (Phase V0.a): `var` bindings are SharedCow by default when
        // the `SHAPE_V2_VAR_SHAREDCOW` flag is on. `var`'s ownership class is
        // `Flexible`, which the spec's Phase 4 defines as "aliased by
        // construction" — SharedCow regardless of whether the MIR pass
        // observed an actual alias+mutation pair. The flag defaults to on;
        // setting the env var to `0` falls back to the narrower Rule 3.
        BindingStorageClass::SharedCow
    } else if is_mutably_captured {
        // Rule 2: Captured by closure with mutation → UniqueHeap.
        BindingStorageClass::UniqueHeap
    } else if matches!(ownership, Some(BindingOwnershipClass::Flexible))
        && is_aliased
        && is_mutated
    {
        // Rule 3: `var` bindings that are aliased AND mutated → SharedCow.
        // Still present as a safety net: when the V0.a flag is disabled the
        // planner falls back to this narrower rule.
        BindingStorageClass::SharedCow
    } else if is_escaped && is_aliased && is_mutated {
        // Rule 3b: Escaped mutable aliased bindings → SharedCow.
        // Even non-Flexible bindings need COW when they escape with aliasing.
        BindingStorageClass::SharedCow
    } else {
        // Rule 4: Captured by closure (immutably) — still Direct.
        // Default: Direct storage (stack slot).
        BindingStorageClass::Direct
    };

    // Compute enriched metadata
    let aliasability = if is_captured || is_aliased {
        if is_mutated {
            Aliasability::SharedMutable
        } else {
            Aliasability::SharedImmutable
        }
    } else {
        Aliasability::Unique
    };

    let mutation_capability = match (ownership, is_mutated) {
        (Some(BindingOwnershipClass::OwnedImmutable), _) => MutationCapability::Immutable,
        (Some(BindingOwnershipClass::OwnedMutable), _) => MutationCapability::LocalMutable,
        (Some(BindingOwnershipClass::Flexible), true) => MutationCapability::SharedMutable,
        (Some(BindingOwnershipClass::Flexible), false) => MutationCapability::Immutable,
        (None, true) => MutationCapability::LocalMutable,
        (None, false) => MutationCapability::Immutable,
    };

    let escape_status = detect_escape_status(slot, input.mir, input.closure_captures);

    // Preserve the Phase 5.B return-ownership hint through storage planning:
    // it was populated on the incoming binding semantics by the compiler's
    // let-statement path and is consumed at codegen time.
    let return_ownership_hint = input
        .binding_semantics
        .get(&slot.0)
        .and_then(|s| s.return_ownership_hint);

    let enriched = BindingSemantics {
        ownership_class: ownership.unwrap_or(BindingOwnershipClass::OwnedImmutable),
        storage_class: storage_class,
        aliasability,
        mutation_capability,
        escape_status,
        return_ownership_hint,
    };

    (storage_class, enriched)
}

/// Detect the escape status of a slot by examining MIR dataflow.
///
/// - `Escaped`: The slot's value flows, directly or through local aliases, into
///   the return slot (`SlotId(0)`).
/// - `Captured`: The slot is captured by a closure.
/// - `Local`: The slot stays within the declaring scope.
pub fn detect_escape_status(
    slot: SlotId,
    mir: &MirFunction,
    closure_captures: &HashSet<SlotId>,
) -> EscapeStatus {
    if slot != SlotId(0) {
        let mut visited = HashSet::new();
        if slot_flows_to_return(slot, mir, &mut visited) {
            return EscapeStatus::Escaped;
        }
    }

    if closure_captures.contains(&slot) {
        EscapeStatus::Captured
    } else {
        EscapeStatus::Local
    }
}

fn slot_flows_to_return(
    slot: SlotId,
    mir: &MirFunction,
    visited: &mut HashSet<SlotId>,
) -> bool {
    if !visited.insert(slot) {
        return false;
    }

    let return_slot = SlotId(0);
    for block in mir.iter_blocks() {
        for stmt in &block.statements {
            let StatementKind::Assign(Place::Local(dest), rvalue) = &stmt.kind else {
                continue;
            };
            if !rvalue_uses_slot(rvalue, slot) {
                continue;
            }
            if *dest == return_slot {
                return true;
            }
            if *dest != slot && slot_flows_to_return(*dest, mir, visited) {
                return true;
            }
        }
    }

    false
}

/// Check if a slot was assigned a `Borrow` rvalue anywhere in the function.
fn slot_holds_reference(slot: SlotId, mir: &MirFunction) -> bool {
    for block in mir.iter_blocks() {
        for stmt in &block.statements {
            if let StatementKind::Assign(Place::Local(s), Rvalue::Borrow(_, _)) = &stmt.kind {
                if *s == slot {
                    return true;
                }
            }
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mir::analysis::BorrowAnalysis;
    use crate::mir::liveness::LivenessResult;
    use crate::mir::types::*;
    use crate::type_tracking::{
        Aliasability, BindingOwnershipClass, BindingSemantics, BindingStorageClass, EscapeStatus,
        MutationCapability,
    };

    fn span() -> shape_ast::ast::Span {
        shape_ast::ast::Span { start: 0, end: 1 }
    }

    fn make_stmt(kind: StatementKind, point: u32) -> MirStatement {
        MirStatement {
            kind,
            span: span(),
            point: Point(point),
        }
    }

    fn make_terminator(kind: TerminatorKind) -> Terminator {
        Terminator { kind, span: span() }
    }

    fn empty_analysis() -> BorrowAnalysis {
        BorrowAnalysis::empty()
    }

    /// Helper: create a simple MIR function with the given blocks.
    fn make_mir(name: &str, blocks: Vec<BasicBlock>, num_locals: u16) -> MirFunction {
        MirFunction {
            name: name.to_string(),
            blocks,
            num_locals,
            param_slots: vec![],
            param_reference_kinds: vec![],
            local_types: (0..num_locals).map(|_| LocalTypeInfo::Unknown).collect(),
            span: span(),
            field_name_table: std::collections::HashMap::new(),
            local_struct_type_names: std::collections::HashMap::new(),
            local_typed_array_element_types: std::collections::HashMap::new(),
            local_declared_scalar_types: std::collections::HashMap::new(),
        }
    }

    // ── Test: Direct storage for simple binding ──────────────────────────

    #[test]
    fn test_simple_binding_gets_direct() {
        // bb0: _0 = 42; return
        let mir = make_mir(
            "test_direct",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(0)),
                        Rvalue::Use(Operand::Constant(MirConstant::Int(42))),
                    ),
                    0,
                )],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            1,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert_eq!(
            plan.slot_classes.get(&SlotId(0)),
            Some(&BindingStorageClass::Direct)
        );
    }

    // ── Test: Deferred when had_fallbacks ─────────────────────────────────

    #[test]
    fn test_fallback_gives_deferred() {
        let mir = make_mir(
            "test_deferred",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: true,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert_eq!(
            plan.slot_classes.get(&SlotId(0)),
            Some(&BindingStorageClass::Deferred)
        );
        assert_eq!(
            plan.slot_classes.get(&SlotId(1)),
            Some(&BindingStorageClass::Deferred)
        );
    }

    // ── Test: Mutable capture → LocalMutablePtr (Phase D) or UniqueHeap ───
    //
    // Before Phase D this scenario produced `UniqueHeap` unconditionally
    // (Rule 2 in `decide_slot_storage`). Phase D adds a post-processing pass:
    // when the closure itself is non-escaping, the outer slot is demoted to
    // `LocalMutablePtr` so the slot can stay on the stack and the closure env
    // holds a typed pointer instead of an `Arc<RwLock<ValueWord>>` cell.

    #[test]
    fn test_mutable_capture_gets_local_mutable_ptr() {
        // bb0: _0 = 0; ClosureCapture(copy _0); _0 = 1; return
        let mir = make_mir(
            "test_unique_heap",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(0))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::ClosureCapture {
                            closure_slot: SlotId(0),
                            operands: vec![Operand::Copy(Place::Local(SlotId(0)))],
                            function_id: None,
                        },
                        1,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(1))),
                        ),
                        2,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            1,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();

        // Simulate what collect_closure_captures would find
        let mut closure_captures = HashSet::new();
        closure_captures.insert(SlotId(0));
        let mut mutable_captures = HashSet::new();
        mutable_captures.insert(SlotId(0));

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        // Phase D: when the closure is non-escaping, mutable-capture slots
        // drop from `UniqueHeap` to `LocalMutablePtr`. The test MIR has the
        // closure_slot at SlotId(0) and no escape vectors, so the closure is
        // non-escaping and the demotion fires.
        assert_eq!(
            plan.slot_classes.get(&SlotId(0)),
            Some(&BindingStorageClass::LocalMutablePtr)
        );
    }

    // ── Test: SharedCow for aliased+mutated var binding ──────────────────

    #[test]
    fn test_aliased_mutated_var_gets_shared_cow() {
        // bb0: _0 = "hello"; _1 = copy _0; _2 = copy _0; _0 = "world"; return
        let mir = make_mir(
            "test_shared_cow",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::StringId(0))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Copy(Place::Local(SlotId(0)))),
                        ),
                        1,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(2)),
                            Rvalue::Use(Operand::Copy(Place::Local(SlotId(0)))),
                        ),
                        2,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::StringId(1))),
                        ),
                        3,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            3,
        );

        let analysis = empty_analysis();
        let mut binding_semantics = HashMap::new();
        // Mark slot 0 as a `var` (Flexible) binding
        binding_semantics.insert(
            0u16,
            BindingSemantics::deferred(BindingOwnershipClass::Flexible),
        );

        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert_eq!(
            plan.slot_classes.get(&SlotId(0)),
            Some(&BindingStorageClass::SharedCow),
            "aliased + mutated + Flexible => SharedCow"
        );
    }

    // ── Test: Reference for borrow-holding slot ──────────────────────────

    #[test]
    fn test_borrow_holder_gets_reference() {
        // bb0: _0 = 42; _1 = &_0; return
        let mir = make_mir(
            "test_reference",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(42))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Borrow(BorrowKind::Shared, Place::Local(SlotId(0))),
                        ),
                        1,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        // Create analysis with a loan on slot 0
        let mut analysis = empty_analysis();
        analysis.loans.insert(
            LoanId(0),
            crate::mir::analysis::LoanInfo {
                id: LoanId(0),
                borrowed_place: Place::Local(SlotId(0)),
                kind: BorrowKind::Shared,
                issued_at: Point(1),
                span: span(),
                region_depth: 1,
            },
        );

        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        // _1 holds a borrow rvalue → Reference
        assert_eq!(
            plan.slot_classes.get(&SlotId(1)),
            Some(&BindingStorageClass::Reference),
            "_1 holds &_0 borrow → Reference"
        );
    }

    // ── Test: Explicit Reference preserved ───────────────────────────────

    #[test]
    fn test_explicit_reference_preserved() {
        let mir = make_mir(
            "test_explicit_ref",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            1,
        );

        let analysis = empty_analysis();
        let mut binding_semantics = HashMap::new();
        binding_semantics.insert(
            0u16,
            BindingSemantics {
                ownership_class: BindingOwnershipClass::OwnedImmutable,
                storage_class: BindingStorageClass::Reference,
                aliasability: Aliasability::Unique,
                mutation_capability: MutationCapability::Immutable,
                escape_status: EscapeStatus::Local,
                return_ownership_hint: None,
            },
        );

        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert_eq!(
            plan.slot_classes.get(&SlotId(0)),
            Some(&BindingStorageClass::Reference),
            "explicit Reference annotation preserved"
        );
    }

    // ── Test: collect_closure_captures ────────────────────────────────────

    #[test]
    fn test_collect_closure_captures() {
        // bb0: _0 = 1; _1 = 2; ClosureCapture(copy _0, copy _1); _0 = 3; return
        let mir = make_mir(
            "test_collect",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(1))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(2))),
                        ),
                        1,
                    ),
                    make_stmt(
                        StatementKind::ClosureCapture {
                            closure_slot: SlotId(2),
                            operands: vec![
                                Operand::Copy(Place::Local(SlotId(0))),
                                Operand::Copy(Place::Local(SlotId(1))),
                            ],
                            function_id: None,
                        },
                        2,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(3))),
                        ),
                        3,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let (captures, mutable) = collect_closure_captures(&mir);
        assert!(captures.contains(&SlotId(0)));
        assert!(captures.contains(&SlotId(1)));
        // _0 is assigned twice (before and after capture) → mutably captured
        assert!(mutable.contains(&SlotId(0)));
        // _1 is assigned only once (initial definition) → not mutably captured
        // Note: our conservative check counts any assignment, but _1 only has one
        assert!(!mutable.contains(&SlotId(1)));
    }

    // ── Test: Immutable captured slot stays Direct ───────────────────────

    #[test]
    fn test_immutable_capture_stays_direct() {
        // bb0: _0 = 1; ClosureCapture(copy _0); return
        let mir = make_mir(
            "test_immutable_capture",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(1))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::ClosureCapture {
                            closure_slot: SlotId(0),
                            operands: vec![Operand::Copy(Place::Local(SlotId(0)))],
                            function_id: None,
                        },
                        1,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            1,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let mut closure_captures = HashSet::new();
        closure_captures.insert(SlotId(0));
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        // Phase D: when a non-escaping closure captures the slot, the planner
        // promotes `Direct` → `LocalMutablePtr` unconditionally (the compiler
        // side decides whether to actually emit the typed-pointer opcodes
        // based on the closure body's mutation analysis). `LocalMutablePtr`
        // is semantically equivalent to `Direct` for immutable captures:
        // the slot stays on the frame and no heap indirection is introduced.
        let class = plan.slot_classes.get(&SlotId(0)).copied();
        assert!(
            matches!(
                class,
                Some(BindingStorageClass::Direct)
                    | Some(BindingStorageClass::LocalMutablePtr)
            ),
            "immutable capture stays on stack (Direct or LocalMutablePtr), got {:?}",
            class
        );
    }

    // ── Test: Non-Flexible ownership doesn't get SharedCow ───────────────

    #[test]
    fn test_owned_mutable_aliased_mutated_stays_direct() {
        // A `let mut` binding that is aliased and mutated does NOT get
        // SharedCow — only `var` (Flexible) does.
        let mir = make_mir(
            "test_let_mut_no_cow",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(0))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Copy(Place::Local(SlotId(0)))),
                        ),
                        1,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(2)),
                            Rvalue::Use(Operand::Copy(Place::Local(SlotId(0)))),
                        ),
                        2,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(99))),
                        ),
                        3,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            3,
        );

        let analysis = empty_analysis();
        let mut binding_semantics = HashMap::new();
        binding_semantics.insert(
            0u16,
            BindingSemantics::deferred(BindingOwnershipClass::OwnedMutable),
        );

        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert_eq!(
            plan.slot_classes.get(&SlotId(0)),
            Some(&BindingStorageClass::Direct),
            "OwnedMutable (let mut) stays Direct even when aliased+mutated"
        );
    }

    // ── Test: All slots planned ──────────────────────────────────────────

    #[test]
    fn test_all_slots_planned() {
        let mir = make_mir(
            "test_all_planned",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            5,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert_eq!(plan.slot_classes.len(), 5, "all slots must be planned");
        for i in 0..5 {
            assert!(
                plan.slot_classes.contains_key(&SlotId(i)),
                "slot {} must be in plan",
                i
            );
        }
    }

    // ── Test: UniqueHeap takes priority over SharedCow ───────────────────

    #[test]
    fn test_mutable_capture_beats_shared_cow() {
        // A `var` binding that is both mutably captured AND aliased+mutated
        // should get UniqueHeap (closure mutation takes priority over COW).
        let mir = make_mir(
            "test_priority",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(0))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::ClosureCapture {
                            closure_slot: SlotId(0),
                            operands: vec![Operand::Copy(Place::Local(SlotId(0)))],
                            function_id: None,
                        },
                        1,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(1))),
                        ),
                        2,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            1,
        );

        let analysis = empty_analysis();
        let mut binding_semantics = HashMap::new();
        binding_semantics.insert(
            0u16,
            BindingSemantics::deferred(BindingOwnershipClass::Flexible),
        );

        let mut closure_captures = HashSet::new();
        closure_captures.insert(SlotId(0));
        let mut mutable_captures = HashSet::new();
        mutable_captures.insert(SlotId(0));

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        // Phase V0.a changes the storage class depending on the
        // `SHAPE_V2_VAR_SHAREDCOW` flag state observed at process start:
        //
        //   * Flag ON (default): Rule 1b fires first and promotes the `var`
        //     slot to `SharedCow`; Phase D's promotion leaves `SharedCow`
        //     untouched.
        //   * Flag OFF: Rule 1b is suppressed; Rule 2 fires → `UniqueHeap`;
        //     Phase D then demotes to `LocalMutablePtr` because the closure
        //     is non-escaping.
        //
        // `plan_storage` consults the cached env-backed flag, so we accept
        // whichever outcome matches the process's flag state and cross-check
        // the other outcome via `decide_slot_storage` directly.
        let plan = plan_storage(&input);
        let actual = plan.slot_classes.get(&SlotId(0)).copied();
        if var_sharedcow_default_enabled() {
            assert_eq!(
                actual,
                Some(BindingStorageClass::SharedCow),
                "Phase V0.a flag on: mutably-captured `var` is SharedCow"
            );
            // Cross-check: with the flag forced off, the legacy
            // UniqueHeap → Phase-D-demote path is still exercised.
            assert_eq!(
                decide_slot_storage(SlotId(0), &input, /* var_sharedcow_enabled */ false).0,
                BindingStorageClass::UniqueHeap,
                "legacy path (flag off) still assigns UniqueHeap before Phase D demotion"
            );
        } else {
            assert_eq!(
                actual,
                Some(BindingStorageClass::LocalMutablePtr),
                "Phase V0.a flag off: non-escaping mutable capture → LocalMutablePtr (Phase D)"
            );
        }
    }

    // ── Test: detect_escape_status ───────────────────────────────────────

    #[test]
    fn test_escape_status_local() {
        // bb0: _1 = 42; return
        // _1 never flows to _0 (return slot) → Local
        let mir = make_mir(
            "test_local_escape",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::Int(42))),
                    ),
                    0,
                )],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let captures = HashSet::new();
        assert_eq!(
            detect_escape_status(SlotId(1), &mir, &captures),
            EscapeStatus::Local,
            "slot that doesn't escape should be Local"
        );
    }

    #[test]
    fn test_escape_status_escaped_via_return() {
        // bb0: _1 = 42; _0 = copy _1; return
        // _1 flows to return slot _0 → Escaped
        let mir = make_mir(
            "test_escaped",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(42))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Copy(Place::Local(SlotId(1)))),
                        ),
                        1,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let captures = HashSet::new();
        assert_eq!(
            detect_escape_status(SlotId(1), &mir, &captures),
            EscapeStatus::Escaped,
            "slot assigned to return slot should be Escaped"
        );
    }

    #[test]
    fn test_escape_status_escaped_via_local_alias_chain() {
        // bb0: _2 = 42; _1 = copy _2; _0 = copy _1; return
        // _2 reaches the return slot transitively through _1.
        let mir = make_mir(
            "test_transitive_escape",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(2)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(42))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Copy(Place::Local(SlotId(2)))),
                        ),
                        1,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Copy(Place::Local(SlotId(1)))),
                        ),
                        2,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            3,
        );

        let captures = HashSet::new();
        assert_eq!(
            detect_escape_status(SlotId(2), &mir, &captures),
            EscapeStatus::Escaped,
            "slot flowing into a returned local alias should be Escaped"
        );
    }

    #[test]
    fn test_escape_status_captured() {
        // bb0: _1 = 42; ClosureCapture(copy _1); return
        let mir = make_mir(
            "test_captured",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(42))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::ClosureCapture {
                            closure_slot: SlotId(1),
                            operands: vec![Operand::Copy(Place::Local(SlotId(1)))],
                            function_id: None,
                        },
                        1,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let mut captures = HashSet::new();
        captures.insert(SlotId(1));
        assert_eq!(
            detect_escape_status(SlotId(1), &mir, &captures),
            EscapeStatus::Captured,
            "slot captured by closure should be Captured"
        );
    }

    #[test]
    fn test_escape_status_escaped_beats_captured() {
        // A slot that both escapes to return AND is captured → Escaped takes priority
        // bb0: _1 = 42; ClosureCapture(copy _1); _0 = copy _1; return
        let mir = make_mir(
            "test_escaped_captured",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(42))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::ClosureCapture {
                            closure_slot: SlotId(1),
                            operands: vec![Operand::Copy(Place::Local(SlotId(1)))],
                            function_id: None,
                        },
                        1,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Copy(Place::Local(SlotId(1)))),
                        ),
                        2,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let mut captures = HashSet::new();
        captures.insert(SlotId(1));
        assert_eq!(
            detect_escape_status(SlotId(1), &mir, &captures),
            EscapeStatus::Escaped,
            "Escaped takes priority over Captured"
        );
    }

    #[test]
    fn test_escape_semantics_in_plan() {
        // Verify that the storage plan captures Escaped status on semantics
        // bb0: _1 = 42; _0 = copy _1; return
        let mir = make_mir(
            "test_escape_in_plan",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(42))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Copy(Place::Local(SlotId(1)))),
                        ),
                        1,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert_eq!(
            plan.slot_semantics.get(&SlotId(1)).map(|s| s.escape_status),
            Some(EscapeStatus::Escaped),
            "slot flowing to return should have Escaped status in plan"
        );
    }

    // ── Tests: inline-array-candidate detection (Phase D.2 infrastructure) ──

    #[test]
    fn test_inline_hint_for_small_local_aggregate() {
        // bb0: _1 = [1, 2, 3]; return
        // _1 is a 3-element aggregate that never flows to _0 → candidate.
        let mir = make_mir(
            "test_inline_small_local",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Aggregate(vec![
                            Operand::Constant(MirConstant::Int(1)),
                            Operand::Constant(MirConstant::Int(2)),
                            Operand::Constant(MirConstant::Int(3)),
                        ]),
                    ),
                    0,
                )],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert_eq!(
            plan.inline_array_sizes.get(&SlotId(1)),
            Some(&3),
            "3-element non-escaping aggregate should be hinted"
        );
    }

    #[test]
    fn test_no_inline_hint_when_aggregate_escapes() {
        // bb0: _1 = [1, 2]; _0 = copy _1; return
        // _1 flows to return → escapes, so no hint.
        let mir = make_mir(
            "test_no_inline_escape",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Aggregate(vec![
                                Operand::Constant(MirConstant::Int(1)),
                                Operand::Constant(MirConstant::Int(2)),
                            ]),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Copy(Place::Local(SlotId(1)))),
                        ),
                        1,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert!(
            !plan.inline_array_sizes.contains_key(&SlotId(1)),
            "escaping aggregate must not be hinted"
        );
    }

    #[test]
    fn test_no_inline_hint_when_aggregate_too_large() {
        // bb0: _1 = [1; 9]; return
        // 9 > INLINE_ARRAY_MAX_ELEMENTS (8) → no hint.
        let big_ops: Vec<Operand> = (0..9)
            .map(|_| Operand::Constant(MirConstant::Int(0)))
            .collect();
        let mir = make_mir(
            "test_no_inline_too_large",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Aggregate(big_ops),
                    ),
                    0,
                )],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert!(
            !plan.inline_array_sizes.contains_key(&SlotId(1)),
            "oversize aggregate must not be hinted"
        );
    }

    #[test]
    fn test_no_inline_hint_when_aggregate_captured() {
        // bb0: _1 = [1, 2]; ClosureCapture(copy _1); return
        let mir = make_mir(
            "test_no_inline_captured",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Aggregate(vec![
                                Operand::Constant(MirConstant::Int(1)),
                                Operand::Constant(MirConstant::Int(2)),
                            ]),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::ClosureCapture {
                            closure_slot: SlotId(1),
                            operands: vec![Operand::Copy(Place::Local(SlotId(1)))],
                            function_id: None,
                        },
                        1,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let mut closure_captures = HashSet::new();
        closure_captures.insert(SlotId(1));
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert!(
            !plan.inline_array_sizes.contains_key(&SlotId(1)),
            "captured aggregate must not be hinted"
        );
    }

    #[test]
    fn test_no_inline_hint_when_reassigned() {
        // bb0: _1 = [1, 2]; _1 = [3, 4]; return
        // Two aggregate assignments to the same slot → disqualify.
        let mir = make_mir(
            "test_no_inline_reassigned",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Aggregate(vec![
                                Operand::Constant(MirConstant::Int(1)),
                                Operand::Constant(MirConstant::Int(2)),
                            ]),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Aggregate(vec![
                                Operand::Constant(MirConstant::Int(3)),
                                Operand::Constant(MirConstant::Int(4)),
                            ]),
                        ),
                        1,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert!(
            !plan.inline_array_sizes.contains_key(&SlotId(1)),
            "re-assigned slot must not be hinted"
        );
    }

    #[test]
    fn test_inline_hint_at_boundary_size() {
        // Exactly INLINE_ARRAY_MAX_ELEMENTS elements → eligible.
        let ops: Vec<Operand> = (0..INLINE_ARRAY_MAX_ELEMENTS)
            .map(|_| Operand::Constant(MirConstant::Int(0)))
            .collect();
        let mir = make_mir(
            "test_inline_boundary",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Aggregate(ops),
                    ),
                    0,
                )],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert_eq!(
            plan.inline_array_sizes.get(&SlotId(1)),
            Some(&INLINE_ARRAY_MAX_ELEMENTS),
            "boundary-size aggregate should be hinted"
        );
    }

    #[test]
    fn test_no_inline_hint_with_fallbacks() {
        // had_fallbacks=true → planner bails to Deferred and records no hints.
        let mir = make_mir(
            "test_no_inline_fallback",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Aggregate(vec![
                            Operand::Constant(MirConstant::Int(1)),
                        ]),
                    ),
                    0,
                )],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            2,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: true,
            callee_summaries: None,
        };

        let plan = plan_storage(&input);
        assert!(
            plan.inline_array_sizes.is_empty(),
            "fallback path must not record any hints"
        );
    }

    // ── Closure Spec Phase B: non-escape detection for closure slots ────────
    //
    // These tests exercise the 10-row escape-vector table from
    // `docs/v2-closure-specialization.md` §2.1 plus the §2.4 transitive
    // fixed-point. They operate directly on synthetic MIR so they can target
    // specific vectors without relying on the higher-level compiler pipeline.
    //
    // Convention: closure slot := the `closure_slot` field of a
    // `StatementKind::ClosureCapture`. A followup
    // `Assign(_, ClosurePlaceholder)` would complete the definition in real
    // MIR; the tests omit it because `collect_closure_slots` keys solely on
    // the `ClosureCapture` statement.
    //
    // Helper: build MIR with a single block + terminator.
    fn single_block_mir(name: &str, statements: Vec<MirStatement>, num_locals: u16) -> MirFunction {
        make_mir(
            name,
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements,
                terminator: make_terminator(TerminatorKind::Return),
            }],
            num_locals,
        )
    }

    fn run_planner(mir: &MirFunction) -> StoragePlan {
        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();
        let input = StoragePlannerInput {
            mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };
        plan_storage(&input)
    }

    #[test]
    fn test_phase_b_pure_local_closure_is_non_escaping() {
        // let f = || 1; f()  — the closure slot is defined via
        // ClosureCapture (no captures) and then only invoked. No escape
        // vector fires.
        // Slots: _0 = return, _1 = closure, _2 = call result
        let mir = single_block_mir(
            "phase_b_pure_local",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
            ],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "pure let f = || 1 should be non-escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_closure_returned_is_escaping() {
        // fn make() { || 42 } — the closure slot flows into the return slot.
        // Slots: _0 = return, _1 = closure
        let mir = single_block_mir(
            "phase_b_returned",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(0)),
                        Rvalue::Use(Operand::Copy(Place::Local(SlotId(1)))),
                    ),
                    2,
                ),
            ],
            2,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "returned closure must be escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_closure_in_array_literal_is_escaping() {
        // let a = [|x| x]  — Rvalue::Aggregate row 2.
        // Slots: _0 = return, _1 = closure, _2 = array
        let mir = single_block_mir(
            "phase_b_in_array_literal",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Aggregate(vec![Operand::Copy(Place::Local(SlotId(1)))]),
                    ),
                    2,
                ),
            ],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "closure stored in array literal must be escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_closure_pushed_via_array_store_is_escaping() {
        // let a = []; a.push(|x| x)  — StatementKind::ArrayStore row 2.
        // Slots: _0 = return, _1 = array, _2 = closure
        let mir = single_block_mir(
            "phase_b_array_store",
            vec![
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Aggregate(vec![]),
                    ),
                    0,
                ),
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(2),
                        operands: vec![],
                        function_id: None,
                    },
                    1,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    2,
                ),
                make_stmt(
                    StatementKind::ArrayStore {
                        container_slot: SlotId(1),
                        operands: vec![Operand::Copy(Place::Local(SlotId(2)))],
                    },
                    3,
                ),
            ],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(2)),
            "closure pushed into array via ArrayStore must be escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_closure_stored_in_object_field_is_escaping() {
        // foo.f = || 1  — Place::Field write row 3.
        // Slots: _0 = return, _1 = foo (struct), _2 = closure
        let mir = single_block_mir(
            "phase_b_field_store",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(2),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Field(Box::new(Place::Local(SlotId(1))), FieldIdx(0)),
                        Rvalue::Use(Operand::Copy(Place::Local(SlotId(2)))),
                    ),
                    2,
                ),
            ],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(2)),
            "closure stored in struct field must be escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_closure_across_detached_task_is_escaping() {
        // async scope { || 1 } — TaskBoundary(Detached) row 5.
        let mir = single_block_mir(
            "phase_b_detached_task",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::TaskBoundary(
                        vec![Operand::Copy(Place::Local(SlotId(1)))],
                        TaskBoundaryKind::Detached,
                    ),
                    2,
                ),
            ],
            2,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "closure crossing detached task boundary must be escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_closure_across_structured_task_is_escaping() {
        // Structured task boundaries conservatively escape in Phase B per
        // §5.5 — stack allocation through structured boundaries is deferred.
        let mir = single_block_mir(
            "phase_b_structured_task",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::TaskBoundary(
                        vec![Operand::Copy(Place::Local(SlotId(1)))],
                        TaskBoundaryKind::Structured,
                    ),
                    2,
                ),
            ],
            2,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "closure crossing structured task boundary must be escaping (conservative); got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_closure_written_through_deref_is_escaping() {
        // *p = |x| x — Place::Deref write row 9.
        // Slots: _0 = return, _1 = pointer-holding slot, _2 = closure
        let mir = single_block_mir(
            "phase_b_deref_write",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(2),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Deref(Box::new(Place::Local(SlotId(1)))),
                        Rvalue::Use(Operand::Copy(Place::Local(SlotId(2)))),
                    ),
                    2,
                ),
            ],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(2)),
            "closure written through deref must be escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_closure_promoted_to_shared_cow_is_escaping() {
        // Row 10: if the semantics planner assigns the closure slot
        // SharedCow/UniqueHeap storage, the closure value is escaping by
        // construction.
        let mir = single_block_mir(
            "phase_b_shared_cow_promotion",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
            ],
            2,
        );

        let analysis = empty_analysis();
        let mut binding_semantics = HashMap::new();
        binding_semantics.insert(
            1u16,
            BindingSemantics {
                ownership_class: BindingOwnershipClass::Flexible,
                storage_class: BindingStorageClass::SharedCow,
                aliasability: Aliasability::SharedMutable,
                mutation_capability: MutationCapability::SharedMutable,
                escape_status: EscapeStatus::Local,
                return_ownership_hint: None,
            },
        );
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();
        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };
        let plan = plan_storage(&input);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "SharedCow-promoted closure slot must be escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_transitive_closure_capture_escapes_together() {
        // let f = |x| x; let g = |y| f(y) + y — g captures f. If g escapes
        // (returned), f must also be classified as escaping. Row 4 +
        // transitive fixed-point (§2.4).
        // Slots: _0 = return, _1 = f, _2 = g
        let mir = single_block_mir(
            "phase_b_transitive_escape",
            vec![
                // Define f
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                // Define g, capturing f
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(2),
                        operands: vec![Operand::Copy(Place::Local(SlotId(1)))],
                        function_id: None,
                    },
                    2,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    3,
                ),
                // g flows to the return slot — g escapes.
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(0)),
                        Rvalue::Use(Operand::Copy(Place::Local(SlotId(2)))),
                    ),
                    4,
                ),
            ],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(2)),
            "escaping g must not be classified non-escaping"
        );
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "f is captured by escaping g → f must also escape (§2.4); got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_transitive_capture_both_non_escaping() {
        // Dual of the test above — when g is non-escaping, the closure it
        // captures (f) should also be non-escaping. Proves the fixed-point
        // does not over-mark as escaping.
        // Slots: _0 = return, _1 = f, _2 = g
        let mir = single_block_mir(
            "phase_b_transitive_non_escape",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(2),
                        operands: vec![Operand::Copy(Place::Local(SlotId(1)))],
                        function_id: None,
                    },
                    2,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    3,
                ),
            ],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "non-escaping g keeps f non-escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
        assert!(
            plan.non_escaping_closure_slots.contains(&SlotId(2)),
            "g itself is non-escaping"
        );
    }

    #[test]
    fn test_phase_b_call_arg_conservative_without_summary() {
        // arr.map(|x| x+1) — without a callee summary, Phase B must
        // classify the closure as escaping (sub-task 6 conservative
        // fallback). Phase C will refine this via the mono key.
        // Slots: _0 = return, _1 = closure, _2 = result, _3 = arr
        let mir = make_mir(
            "phase_b_call_arg_conservative",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::ClosureCapture {
                            closure_slot: SlotId(1),
                            operands: vec![],
                            function_id: None,
                        },
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                        ),
                        1,
                    ),
                ],
                terminator: Terminator {
                    kind: TerminatorKind::Call {
                        func: Operand::Constant(MirConstant::Function("map".to_string())),
                        args: vec![
                            Operand::Copy(Place::Local(SlotId(3))),
                            Operand::Copy(Place::Local(SlotId(1))),
                        ],
                        destination: Place::Local(SlotId(2)),
                        next: BasicBlockId(0),
                    },
                    span: span(),
                },
            }],
            4,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "closure passed as call arg without a callee summary must be conservative = escaping"
        );
    }

    #[test]
    fn test_phase_b_call_arg_with_non_escaping_summary() {
        // arr.map(|x| x+1) — with a callee summary marking the
        // corresponding parameter as non-escaping, the closure is allowed to
        // be classified as non-escaping.
        use crate::mir::analysis::{FunctionBorrowSummary, ReturnOwnershipMode};

        let mir = make_mir(
            "phase_b_call_arg_with_summary",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::ClosureCapture {
                            closure_slot: SlotId(1),
                            operands: vec![],
                            function_id: None,
                        },
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                        ),
                        1,
                    ),
                ],
                terminator: Terminator {
                    kind: TerminatorKind::Call {
                        func: Operand::Constant(MirConstant::Function(
                            "trusted_non_escaping".to_string(),
                        )),
                        args: vec![
                            Operand::Copy(Place::Local(SlotId(3))),
                            Operand::Copy(Place::Local(SlotId(1))),
                        ],
                        destination: Place::Local(SlotId(2)),
                        next: BasicBlockId(0),
                    },
                    span: span(),
                },
            }],
            4,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();
        let mut summaries: HashMap<String, FunctionBorrowSummary> = HashMap::new();
        summaries.insert(
            "trusted_non_escaping".to_string(),
            FunctionBorrowSummary {
                param_borrows: vec![None, None],
                conflict_pairs: vec![],
                return_summary: None,
                return_ownership_mode: ReturnOwnershipMode::Unknown,
                // Both params non-escaping.
                closure_param_escapes: vec![false, false],
            },
        );

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: Some(&summaries),
        };
        let plan = plan_storage(&input);
        assert!(
            plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "closure passed to a callee with a non-escaping param summary is non-escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    #[test]
    fn test_phase_b_snapshot_call_forces_escape() {
        // Row 7: `snapshot()` is opaque FFI — any closure flowing into it
        // must be treated as escaping.
        let mir = make_mir(
            "phase_b_snapshot_escape",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::ClosureCapture {
                            closure_slot: SlotId(1),
                            operands: vec![],
                            function_id: None,
                        },
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(1)),
                            Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                        ),
                        1,
                    ),
                ],
                terminator: Terminator {
                    kind: TerminatorKind::Call {
                        func: Operand::Constant(MirConstant::Function("snapshot".to_string())),
                        args: vec![Operand::Copy(Place::Local(SlotId(1)))],
                        destination: Place::Local(SlotId(2)),
                        next: BasicBlockId(0),
                    },
                    span: span(),
                },
            }],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "closure fed to snapshot() must be escaping"
        );
    }

    #[test]
    fn test_phase_b_enum_store_is_escaping() {
        // Rvalue 2 subcase: closure stored into an enum payload.
        // Slots: _0 = return, _1 = closure, _2 = enum
        let mir = single_block_mir(
            "phase_b_enum_store",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::EnumStore {
                        container_slot: SlotId(2),
                        operands: vec![Operand::Copy(Place::Local(SlotId(1)))],
                        variant_name: None,
                    },
                    2,
                ),
            ],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "closure stored in enum payload must be escaping"
        );
    }

    #[test]
    fn test_phase_b_object_store_is_escaping() {
        // Rvalue 2 subcase: closure stored into an object/struct literal.
        // Slots: _0 = return, _1 = closure, _2 = object
        let mir = single_block_mir(
            "phase_b_object_store",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::ObjectStore {
                        container_slot: SlotId(2),
                        operands: vec![Operand::Copy(Place::Local(SlotId(1)))],
                        field_names: vec!["f".to_string()],
                        schema_id: None,
                    },
                    2,
                ),
            ],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "closure stored in object literal must be escaping"
        );
    }

    #[test]
    fn test_phase_b_two_independent_closures() {
        // Two independent closures in the same function, one escapes the
        // other does not — verifies the per-slot classification doesn't
        // over-report.
        // Slots: _0 = return, _1 = escaping, _2 = local, _3 = result of local call
        let mir = single_block_mir(
            "phase_b_two_independent",
            vec![
                // First closure: escapes via return.
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                // Second closure: never used beyond its assignment.
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(2),
                        operands: vec![],
                        function_id: None,
                    },
                    2,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    3,
                ),
                // Return the first.
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(0)),
                        Rvalue::Use(Operand::Copy(Place::Local(SlotId(1)))),
                    ),
                    4,
                ),
            ],
            3,
        );

        let plan = run_planner(&mir);
        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "first closure escapes via return"
        );
        assert!(
            plan.non_escaping_closure_slots.contains(&SlotId(2)),
            "second closure is independent and does not escape; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    // ── Closure Spec Phase D: LocalMutablePtr promotion ──────────────────

    /// Build a minimal MIR: outer mutable slot `_1`, closure slot `_2`
    /// captures `_1`, closure is invoked. Phase B classifies `_2` as
    /// non-escaping; Phase D demotes `_1` from `UniqueHeap` → `LocalMutablePtr`.
    fn phase_d_basic_mir() -> MirFunction {
        single_block_mir(
            "phase_d_local_ptr",
            vec![
                // _1 = 0
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::Int(0))),
                    ),
                    0,
                ),
                // ClosureCapture { closure_slot: _2, operands: [copy _1] }
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(2),
                        operands: vec![Operand::Copy(Place::Local(SlotId(1)))],
                        function_id: None,
                    },
                    1,
                ),
                // _2 = <closure placeholder>
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    2,
                ),
                // Reassign outer (proves slot is mutably captured).
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::Int(5))),
                    ),
                    3,
                ),
            ],
            3,
        )
    }

    #[test]
    fn test_phase_d_non_escaping_closure_promotes_outer_slot_to_local_mutable_ptr() {
        let mir = phase_d_basic_mir();
        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let mut closure_captures = HashSet::new();
        closure_captures.insert(SlotId(1));
        let mut mutable_captures = HashSet::new();
        mutable_captures.insert(SlotId(1));

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };
        let plan = plan_storage(&input);

        assert_eq!(
            plan.slot_classes.get(&SlotId(1)),
            Some(&BindingStorageClass::LocalMutablePtr),
            "non-escaping mutable capture → LocalMutablePtr"
        );
        assert!(
            plan.non_escaping_closure_slots.contains(&SlotId(2)),
            "closure in _2 is non-escaping"
        );
    }

    #[test]
    fn test_phase_d_escaping_closure_leaves_outer_slot_as_unique_heap() {
        // The closure escapes via return, so its mutable capture must stay
        // on the heap — Phase D's demotion is gated on `non_escaping`.
        let mut mir = phase_d_basic_mir();
        // Replace the trailing statement with `_0 = copy _2` so the closure
        // flows into the return slot.
        let last_block_idx = mir.blocks.len() - 1;
        let stmts = &mut mir.blocks[last_block_idx].statements;
        // Drop the reassignment (index 3) and add a return-flow statement.
        stmts.pop();
        stmts.push(make_stmt(
            StatementKind::Assign(
                Place::Local(SlotId(0)),
                Rvalue::Use(Operand::Copy(Place::Local(SlotId(2)))),
            ),
            3,
        ));

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let mut closure_captures = HashSet::new();
        closure_captures.insert(SlotId(1));
        let mut mutable_captures = HashSet::new();
        mutable_captures.insert(SlotId(1));

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };
        let plan = plan_storage(&input);

        assert!(
            !plan.non_escaping_closure_slots.contains(&SlotId(2)),
            "closure is escaping via return"
        );
        assert_eq!(
            plan.slot_classes.get(&SlotId(1)),
            Some(&BindingStorageClass::UniqueHeap),
            "escaping closure → outer slot stays UniqueHeap"
        );
    }

    #[test]
    fn test_phase_d_multiple_disjoint_captures_all_local_mutable_ptr() {
        // fn f() { let mut a = 0; let mut b = 0; let c = |x| { a = a + 1; b = b + 2 }; c(); }
        // Two disjoint mutably-captured slots by the same non-escaping closure.
        // Both should be `LocalMutablePtr`.
        let mir = single_block_mir(
            "phase_d_disjoint",
            vec![
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::Int(0))),
                    ),
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Use(Operand::Constant(MirConstant::Int(0))),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(3),
                        operands: vec![
                            Operand::Copy(Place::Local(SlotId(1))),
                            Operand::Copy(Place::Local(SlotId(2))),
                        ],
                        function_id: None,
                    },
                    2,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(3)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    3,
                ),
                // Reassignments to force `mutable_captures` membership.
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::Int(1))),
                    ),
                    4,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Use(Operand::Constant(MirConstant::Int(2))),
                    ),
                    5,
                ),
            ],
            4,
        );

        let analysis = empty_analysis();
        let binding_semantics = HashMap::new();
        let mut closure_captures = HashSet::new();
        closure_captures.insert(SlotId(1));
        closure_captures.insert(SlotId(2));
        let mut mutable_captures = HashSet::new();
        mutable_captures.insert(SlotId(1));
        mutable_captures.insert(SlotId(2));

        let input = StoragePlannerInput {
            mir: &mir,
            analysis: &analysis,
            binding_semantics: &binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };
        let plan = plan_storage(&input);
        assert_eq!(
            plan.slot_classes.get(&SlotId(1)),
            Some(&BindingStorageClass::LocalMutablePtr)
        );
        assert_eq!(
            plan.slot_classes.get(&SlotId(2)),
            Some(&BindingStorageClass::LocalMutablePtr)
        );
    }

    // ─────────────────────────────────────────────────────────────────────
    // Closure Spec Phase G — snapshot forces all closures to heap
    // (docs/v2-closure-specialization.md §5.6)
    // ─────────────────────────────────────────────────────────────────────

    /// A function that calls `snapshot()` must not stack-allocate any of
    /// its closures. The storage planner short-circuits the non-escaping
    /// set because `snapshot()` serializes `SerializableCallFrame` from the
    /// interpreter's locals array and cannot see Cranelift stack slots.
    #[test]
    fn test_phase_g_snapshot_call_forces_all_closures_escaping() {
        // Bytecode MIR shape (no escape vector fires for the closure slot
        // itself):
        //   _1 = ClosureCapture(|| 1)
        //   _2 = snapshot()        ← terminator: Call(snapshot)
        //   _3 = f(5)              ← second block, irrelevant
        let bb0 = BasicBlock {
            id: BasicBlockId(0),
            statements: vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
            ],
            terminator: Terminator {
                kind: TerminatorKind::Call {
                    func: Operand::Constant(MirConstant::Function(
                        "snapshot".to_string(),
                    )),
                    args: vec![],
                    destination: Place::Local(SlotId(2)),
                    next: BasicBlockId(1),
                },
                span: span(),
            },
        };
        let bb1 = BasicBlock {
            id: BasicBlockId(1),
            statements: vec![],
            terminator: make_terminator(TerminatorKind::Return),
        };
        let mir = make_mir("phase_g_snapshot_escape", vec![bb0, bb1], 3);

        let plan = run_planner(&mir);
        assert!(
            plan.non_escaping_closure_slots.is_empty(),
            "snapshot() in function body must force every closure to heap; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    /// Control: the same-shape function WITHOUT `snapshot()` allows the
    /// closure to remain non-escaping (no escape vector fires). This
    /// proves the previous test's failure mode is specifically the
    /// snapshot short-circuit, not a generic escape artifact.
    #[test]
    fn test_phase_g_no_snapshot_keeps_closure_non_escaping() {
        let mir = single_block_mir(
            "phase_g_no_snapshot",
            vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
            ],
            2,
        );

        let plan = run_planner(&mir);
        assert!(
            plan.non_escaping_closure_slots.contains(&SlotId(1)),
            "closure with no escape vector (and no snapshot) must be non-escaping; got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    /// Snapshot call with a closure also present: both the closure slot
    /// AND any local alias of it must end up heap-allocated. Exercises
    /// the "snapshot forces deopt / re-materialize" policy from §5.6
    /// without needing to actually run the JIT deopt path.
    #[test]
    fn test_phase_g_snapshot_forces_aliased_closure_to_heap() {
        // _1 = ClosureCapture  ; _2 = _1 (alias)  ; snapshot()
        let bb0 = BasicBlock {
            id: BasicBlockId(0),
            statements: vec![
                make_stmt(
                    StatementKind::ClosureCapture {
                        closure_slot: SlotId(1),
                        operands: vec![],
                        function_id: None,
                    },
                    0,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(1)),
                        Rvalue::Use(Operand::Constant(MirConstant::ClosurePlaceholder)),
                    ),
                    1,
                ),
                make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(2)),
                        Rvalue::Use(Operand::Copy(Place::Local(SlotId(1)))),
                    ),
                    2,
                ),
            ],
            terminator: Terminator {
                kind: TerminatorKind::Call {
                    func: Operand::Constant(MirConstant::Function(
                        "snapshot".to_string(),
                    )),
                    args: vec![],
                    destination: Place::Local(SlotId(3)),
                    next: BasicBlockId(1),
                },
                span: span(),
            },
        };
        let bb1 = BasicBlock {
            id: BasicBlockId(1),
            statements: vec![],
            terminator: make_terminator(TerminatorKind::Return),
        };
        let mir = make_mir("phase_g_snapshot_aliased", vec![bb0, bb1], 4);

        let plan = run_planner(&mir);
        assert!(
            plan.non_escaping_closure_slots.is_empty(),
            "snapshot() with aliased closure must still force every closure slot to heap; \
             got {:?}",
            plan.non_escaping_closure_slots
        );
    }

    // ─── Phase V0.a: `var` → `SharedCow` default ─────────────────────────
    //
    // These tests exercise `decide_slot_storage` directly with an explicit
    // `var_sharedcow_enabled` flag so they don't depend on — and aren't
    // affected by — the process-wide `SHAPE_V2_VAR_SHAREDCOW` env-var cache
    // that `plan_storage` consults.

    fn run_decide(
        slot: SlotId,
        mir: &MirFunction,
        binding_semantics: &HashMap<u16, BindingSemantics>,
        flag_on: bool,
    ) -> BindingStorageClass {
        let analysis = empty_analysis();
        let closure_captures = HashSet::new();
        let mutable_captures = HashSet::new();
        let input = StoragePlannerInput {
            mir,
            analysis: &analysis,
            binding_semantics,
            closure_captures: &closure_captures,
            mutable_captures: &mutable_captures,
            had_fallbacks: false,
            callee_summaries: None,
        };
        decide_slot_storage(slot, &input, flag_on).0
    }

    #[test]
    fn test_v0a_var_gets_sharedcow_when_flag_on() {
        // `var x = 0; x = x + 1;` — no closure capture, no cross-scope
        // reference. With the V0.a flag on, Rule 1b fires unconditionally
        // because the binding is `Flexible`; with the flag off, the binding
        // is neither aliased nor (by the planner's single-rvalue heuristic)
        // alias-chained, so it falls through to `Direct`.
        let mir = make_mir(
            "v0a_var_flag_on",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(0))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::BinaryOp(
                                BinOp::Add,
                                Operand::Copy(Place::Local(SlotId(0))),
                                Operand::Constant(MirConstant::Int(1)),
                            ),
                        ),
                        1,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            1,
        );

        let mut binding_semantics = HashMap::new();
        binding_semantics.insert(
            0u16,
            BindingSemantics::deferred(BindingOwnershipClass::Flexible),
        );

        // Flag on: Rule 1b promotes `var` → SharedCow regardless of aliasing.
        assert_eq!(
            run_decide(SlotId(0), &mir, &binding_semantics, true),
            BindingStorageClass::SharedCow,
            "Phase V0.a: `var` binding with flag on must be SharedCow"
        );

        // Flag off: Rule 1b is suppressed. The binding is not aliased
        // (only one rvalue read), so Rule 3 does not fire. The planner
        // falls through to `Direct`.
        assert_eq!(
            run_decide(SlotId(0), &mir, &binding_semantics, false),
            BindingStorageClass::Direct,
            "Phase V0.a: `var` binding with flag off falls back to Direct when not aliased+mutated"
        );
    }

    #[test]
    fn test_v0a_let_stays_direct_regardless_of_flag() {
        // `let x = 0;` — `OwnedImmutable`. Never promoted to SharedCow
        // under either flag state.
        let mir = make_mir(
            "v0a_let_direct",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![make_stmt(
                    StatementKind::Assign(
                        Place::Local(SlotId(0)),
                        Rvalue::Use(Operand::Constant(MirConstant::Int(0))),
                    ),
                    0,
                )],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            1,
        );

        let mut binding_semantics = HashMap::new();
        binding_semantics.insert(
            0u16,
            BindingSemantics::deferred(BindingOwnershipClass::OwnedImmutable),
        );

        for flag_on in [true, false] {
            assert_eq!(
                run_decide(SlotId(0), &mir, &binding_semantics, flag_on),
                BindingStorageClass::Direct,
                "Phase V0.a: `let` binding stays Direct (flag_on = {flag_on})"
            );
        }
    }

    #[test]
    fn test_v0a_let_mut_not_sharedcow_under_flag() {
        // `let mut x = 0; x = x + 1;` — `OwnedMutable`, no closure capture,
        // no cross-scope reference. Rule 1b must NOT fire (only Flexible
        // bindings get the V0.a promotion). Rule 3 also does not fire
        // (OwnedMutable is not Flexible). Slot stays `Direct` under both
        // flag states.
        let mir = make_mir(
            "v0a_let_mut_no_cow",
            vec![BasicBlock {
                id: BasicBlockId(0),
                statements: vec![
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::Use(Operand::Constant(MirConstant::Int(0))),
                        ),
                        0,
                    ),
                    make_stmt(
                        StatementKind::Assign(
                            Place::Local(SlotId(0)),
                            Rvalue::BinaryOp(
                                BinOp::Add,
                                Operand::Copy(Place::Local(SlotId(0))),
                                Operand::Constant(MirConstant::Int(1)),
                            ),
                        ),
                        1,
                    ),
                ],
                terminator: make_terminator(TerminatorKind::Return),
            }],
            1,
        );

        let mut binding_semantics = HashMap::new();
        binding_semantics.insert(
            0u16,
            BindingSemantics::deferred(BindingOwnershipClass::OwnedMutable),
        );

        for flag_on in [true, false] {
            let class = run_decide(SlotId(0), &mir, &binding_semantics, flag_on);
            assert!(
                matches!(
                    class,
                    BindingStorageClass::Direct | BindingStorageClass::UniqueHeap
                ),
                "Phase V0.a: `let mut` must not become SharedCow under V0.a \
                 flag (flag_on = {flag_on}); got {class:?}"
            );
            assert_ne!(
                class,
                BindingStorageClass::SharedCow,
                "Phase V0.a: `let mut` must NEVER become SharedCow (flag_on = {flag_on})"
            );
        }
    }
}