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
//! Variable operations for the VM executor
//!
//! Handles: LoadLocal, StoreLocal, LoadModuleBinding, StoreModuleBinding,
//! LoadClosure, StoreClosure, CloseUpvalue, MakeRef, MakeFieldRef,
//! MakeIndexRef, DerefLoad, DerefStore, SetIndexRef, plus the typed
//! Owned/Shared capture and shared-local/module-binding opcodes.
//!
//! ## Wave-δ B6-round-2 close (2026-05-09)
//!
//! Final close for cluster B's `variables/mod.rs`. Migration sources kind
//! through the §2.7.7 stack parallel-`Vec<NativeKind>` track and the §2.7.8
//! cell-storage parallel-kind tracks (`OwnedClosureBlock` /
//! `ClosureLayout::capture_native_kinds` per Wave-γ G-owned-closure-block
//! commit `cb0bf86`, `module_binding_*_kinded` API per Wave-γ
//! G-module-bindings-kind commit `27e2918`, `SharedCell::kind()` per
//! Wave-α B8-shared-cell). Slot kind is the parallel-track `kinds[slot]`;
//! the `FrameDescriptor` is not consulted by the VM interpreter at all
//! (it is a JIT-only marshaling input — WS-10b verifier note).
//!
//! The polymorphic legacy paths that dispatched on `tag_bits::is_tagged`
//! / `tag_bits::get_tag` (the deleted ValueWord NaN-box discriminator) and
//! `nanboxed::RefTarget` / `RefProjection` (the deleted ValueWord
//! reference encoding) are surfaced as `NotImplemented(SURFACE)` per
//! playbook §7 REVISED #4. The §2.7.4 / Phase-2c amendment territory
//! includes:
//!
//! - `read_ref_target` / `write_ref_target` / `resolve_ref_value` /
//! `set_matrix_row_element` / `cow_matrix_write` —
//! `nanboxed::RefTarget` and `RefProjection` are deleted; the
//! reference-value carrier needs a kinded redesign (probable shape:
//! `KindedSlot` carries a `RefTarget`-like enum at the runtime tier).
//! - `op_make_ref` / `op_make_field_ref` / `op_make_index_ref` —
//! construct `RefTarget` ValueWord-shaped bits; depend on the same
//! redesign as above.
//! - `op_deref_load` / `op_deref_store` / `op_set_index_ref` — pop a
//! `RefTarget`-bearing slot, project through `RefProjection::TypedField`
//! / `Index` / `MatrixRow`; same dependency.
//! - `op_load_owned_mutable_capture` / `op_store_owned_mutable_capture`
//! polymorphic — Wave D's typed Load/Store opcodes have replaced these;
//! the polymorphic versions called the deleted `ValueWord::from_raw_bits`
//! / `vw_clone` / `vw_drop` for the Ptr arm. Surfaced.
//! - `op_load_local_clone` already migrated in Wave-α to
//! `stack_read_kinded_raw` + `clone_with_kind` — preserved here.
//!
//! No new forbidden-pattern introductions: zero `vw_clone` / `vw_drop` /
//! `tag_bits::*` / `as_heap_ref` / `NativeKind::Unknown` / Bool-default
//! fallbacks. Every kind sourced from a §2.7.7/§2.7.8 parallel track or
//! the FrameDescriptor's per-local kind. SURFACE markers cite the
//! deleted shape by name per CLAUDE.md "describe deleted code by name".
use crate::{
bytecode::{Instruction, OpCode, Operand},
executor::VirtualMachine,
memory::{record_heap_write, write_barrier_slot},
};
use shape_value::{HeapKind, NativeKind, VMError};
impl VirtualMachine {
/// Resolve the `ClosureLayout` for the currently-executing closure
/// frame.
///
/// Returns `None` if the frame is not a closure call or the function
/// has no registered layout.
#[inline]
fn current_closure_layout(
&self,
) -> Option<std::sync::Arc<shape_value::v2::closure_layout::ClosureLayout>> {
let frame = self.call_stack.last()?;
let func_id = frame.function_id?;
self.program
.closure_function_layouts
.get(func_id as usize)
.and_then(|l| l.as_ref())
.cloned()
}
/// Read the raw u64 bits stored behind upvalue `upvalue_idx`.
/// `frame.upvalues` is the post-`ValueWord`-deletion `Vec<u64>` raw
/// payload (`executor/mod.rs:200`); for `OwnedMutable` captures the
/// bits are a `*mut T` cell pointer, for `Shared` captures a
/// `*const SharedCell` Arc share. Used by every typed and ptr
/// capture handler below.
#[inline]
fn read_capture_raw_pointer_bits(&self, upvalue_idx: u16) -> Result<u64, VMError> {
let frame = self.call_stack.last().ok_or_else(|| {
VMError::RuntimeError(
"mutable/shared capture access outside a call frame".to_string(),
)
})?;
let upvalues = frame.upvalues.as_ref().ok_or_else(|| {
VMError::RuntimeError(
"mutable/shared capture access in a frame without upvalues".to_string(),
)
})?;
let bits = upvalues.get(upvalue_idx as usize).copied().ok_or_else(|| {
VMError::RuntimeError(format!(
"capture index {} not found in closure",
upvalue_idx
))
})?;
Ok(bits)
}
#[inline(always)]
pub(in crate::executor) fn exec_variables(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use OpCode::*;
match instruction.opcode {
LoadLocal => self.op_load_local(instruction)?,
LoadLocalTrusted => self.op_load_local_trusted(instruction)?,
LoadLocalMove => self.op_load_local_move(instruction)?,
LoadLocalClone => self.op_load_local_clone(instruction)?,
StoreLocal => self.op_store_local(instruction)?,
StoreLocalTyped => self.op_store_local_typed(instruction)?,
StoreLocalDrop => self.op_store_local_drop(instruction)?,
LoadLocalI64 => self.op_load_local_i64(instruction)?,
LoadLocalU64 => self.op_load_local_u64(instruction)?,
LoadLocalF64 => self.op_load_local_f64(instruction)?,
LoadLocalI32 => self.op_load_local_i32(instruction)?,
LoadLocalU32 => self.op_load_local_u32(instruction)?,
LoadLocalI16 => self.op_load_local_i16(instruction)?,
LoadLocalU16 => self.op_load_local_u16(instruction)?,
LoadLocalI8 => self.op_load_local_i8(instruction)?,
LoadLocalU8 => self.op_load_local_u8(instruction)?,
LoadLocalBool => self.op_load_local_bool(instruction)?,
LoadLocalPtr => self.op_load_local_ptr(instruction)?,
StoreLocalI64 => self.op_store_local_i64(instruction)?,
StoreLocalU64 => self.op_store_local_u64(instruction)?,
StoreLocalF64 => self.op_store_local_f64(instruction)?,
StoreLocalI32 => self.op_store_local_i32(instruction)?,
StoreLocalU32 => self.op_store_local_u32(instruction)?,
StoreLocalI16 => self.op_store_local_i16(instruction)?,
StoreLocalU16 => self.op_store_local_u16(instruction)?,
StoreLocalI8 => self.op_store_local_i8(instruction)?,
StoreLocalU8 => self.op_store_local_u8(instruction)?,
StoreLocalBool => self.op_store_local_bool(instruction)?,
StoreLocalPtr => self.op_store_local_ptr(instruction)?,
LoadModuleBinding => self.op_load_module_binding(instruction)?,
StoreModuleBinding => self.op_store_module_binding(instruction)?,
StoreModuleBindingTyped => self.op_store_module_binding_typed(instruction)?,
LoadModuleBindingI64 => self.op_load_module_binding_i64(instruction)?,
LoadModuleBindingU64 => self.op_load_module_binding_u64(instruction)?,
LoadModuleBindingF64 => self.op_load_module_binding_f64(instruction)?,
LoadModuleBindingI32 => self.op_load_module_binding_i32(instruction)?,
LoadModuleBindingU32 => self.op_load_module_binding_u32(instruction)?,
LoadModuleBindingI16 => self.op_load_module_binding_i16(instruction)?,
LoadModuleBindingU16 => self.op_load_module_binding_u16(instruction)?,
LoadModuleBindingI8 => self.op_load_module_binding_i8(instruction)?,
LoadModuleBindingU8 => self.op_load_module_binding_u8(instruction)?,
LoadModuleBindingBool => self.op_load_module_binding_bool(instruction)?,
LoadModuleBindingPtr => self.op_load_module_binding_ptr(instruction)?,
StoreModuleBindingI64 => self.op_store_module_binding_i64(instruction)?,
StoreModuleBindingU64 => self.op_store_module_binding_u64(instruction)?,
StoreModuleBindingF64 => self.op_store_module_binding_f64(instruction)?,
StoreModuleBindingI32 => self.op_store_module_binding_i32(instruction)?,
StoreModuleBindingU32 => self.op_store_module_binding_u32(instruction)?,
StoreModuleBindingI16 => self.op_store_module_binding_i16(instruction)?,
StoreModuleBindingU16 => self.op_store_module_binding_u16(instruction)?,
StoreModuleBindingI8 => self.op_store_module_binding_i8(instruction)?,
StoreModuleBindingU8 => self.op_store_module_binding_u8(instruction)?,
StoreModuleBindingBool => self.op_store_module_binding_bool(instruction)?,
StoreModuleBindingPtr => self.op_store_module_binding_ptr(instruction)?,
LoadClosure => self.op_load_closure(instruction)?,
StoreClosure => self.op_store_closure(instruction)?,
CloseUpvalue => self.op_close_upvalue(instruction)?,
MakeRef => self.op_make_ref(instruction)?,
MakeFieldRef => self.op_make_field_ref(instruction)?,
MakeIndexRef => self.op_make_index_ref(instruction)?,
DerefLoad => self.op_deref_load(instruction)?,
DerefStore => self.op_deref_store(instruction)?,
SetIndexRef => self.op_set_index_ref(instruction)?,
LoadOwnedMutableCapture => self.op_load_owned_mutable_capture(instruction)?,
StoreOwnedMutableCapture => self.op_store_owned_mutable_capture(instruction)?,
LoadOwnedMutableCaptureI64 => self.op_load_owned_mutable_capture_i64(instruction)?,
LoadOwnedMutableCaptureU64 => self.op_load_owned_mutable_capture_u64(instruction)?,
LoadOwnedMutableCaptureF64 => self.op_load_owned_mutable_capture_f64(instruction)?,
LoadOwnedMutableCaptureI32 => self.op_load_owned_mutable_capture_i32(instruction)?,
LoadOwnedMutableCaptureU32 => self.op_load_owned_mutable_capture_u32(instruction)?,
LoadOwnedMutableCaptureI16 => self.op_load_owned_mutable_capture_i16(instruction)?,
LoadOwnedMutableCaptureU16 => self.op_load_owned_mutable_capture_u16(instruction)?,
LoadOwnedMutableCaptureI8 => self.op_load_owned_mutable_capture_i8(instruction)?,
LoadOwnedMutableCaptureU8 => self.op_load_owned_mutable_capture_u8(instruction)?,
LoadOwnedMutableCaptureBool => self.op_load_owned_mutable_capture_bool(instruction)?,
LoadOwnedMutableCapturePtr => self.op_load_owned_mutable_capture_ptr(instruction)?,
StoreOwnedMutableCaptureI64 => self.op_store_owned_mutable_capture_i64(instruction)?,
StoreOwnedMutableCaptureU64 => self.op_store_owned_mutable_capture_u64(instruction)?,
StoreOwnedMutableCaptureF64 => self.op_store_owned_mutable_capture_f64(instruction)?,
StoreOwnedMutableCaptureI32 => self.op_store_owned_mutable_capture_i32(instruction)?,
StoreOwnedMutableCaptureU32 => self.op_store_owned_mutable_capture_u32(instruction)?,
StoreOwnedMutableCaptureI16 => self.op_store_owned_mutable_capture_i16(instruction)?,
StoreOwnedMutableCaptureU16 => self.op_store_owned_mutable_capture_u16(instruction)?,
StoreOwnedMutableCaptureI8 => self.op_store_owned_mutable_capture_i8(instruction)?,
StoreOwnedMutableCaptureU8 => self.op_store_owned_mutable_capture_u8(instruction)?,
StoreOwnedMutableCaptureBool => self.op_store_owned_mutable_capture_bool(instruction)?,
StoreOwnedMutableCapturePtr => self.op_store_owned_mutable_capture_ptr(instruction)?,
LoadSharedCapture => self.op_load_shared_capture(instruction)?,
StoreSharedCapture => self.op_store_shared_capture(instruction)?,
LoadSharedCaptureI64 => self.op_load_shared_capture_i64(instruction)?,
LoadSharedCaptureU64 => self.op_load_shared_capture_u64(instruction)?,
LoadSharedCaptureF64 => self.op_load_shared_capture_f64(instruction)?,
LoadSharedCaptureI32 => self.op_load_shared_capture_i32(instruction)?,
LoadSharedCaptureU32 => self.op_load_shared_capture_u32(instruction)?,
LoadSharedCaptureI16 => self.op_load_shared_capture_i16(instruction)?,
LoadSharedCaptureU16 => self.op_load_shared_capture_u16(instruction)?,
LoadSharedCaptureI8 => self.op_load_shared_capture_i8(instruction)?,
LoadSharedCaptureU8 => self.op_load_shared_capture_u8(instruction)?,
LoadSharedCaptureBool => self.op_load_shared_capture_bool(instruction)?,
LoadSharedCapturePtr => self.op_load_shared_capture_ptr(instruction)?,
StoreSharedCaptureI64 => self.op_store_shared_capture_i64(instruction)?,
StoreSharedCaptureU64 => self.op_store_shared_capture_u64(instruction)?,
StoreSharedCaptureF64 => self.op_store_shared_capture_f64(instruction)?,
StoreSharedCaptureI32 => self.op_store_shared_capture_i32(instruction)?,
StoreSharedCaptureU32 => self.op_store_shared_capture_u32(instruction)?,
StoreSharedCaptureI16 => self.op_store_shared_capture_i16(instruction)?,
StoreSharedCaptureU16 => self.op_store_shared_capture_u16(instruction)?,
StoreSharedCaptureI8 => self.op_store_shared_capture_i8(instruction)?,
StoreSharedCaptureU8 => self.op_store_shared_capture_u8(instruction)?,
StoreSharedCaptureBool => self.op_store_shared_capture_bool(instruction)?,
StoreSharedCapturePtr => self.op_store_shared_capture_ptr(instruction)?,
AllocSharedLocal => self.op_alloc_shared_local(instruction)?,
LoadSharedLocal => self.op_load_shared_local(instruction)?,
StoreSharedLocal => self.op_store_shared_local(instruction)?,
DropSharedLocal => self.op_drop_shared_local(instruction)?,
AllocSharedModuleBinding => self.op_alloc_shared_module_binding(instruction)?,
LoadSharedModuleBinding => self.op_load_shared_module_binding(instruction)?,
StoreSharedModuleBinding => self.op_store_shared_module_binding(instruction)?,
_ => unreachable!(
"exec_variables called with non-variable opcode: {:?}",
instruction.opcode
),
}
Ok(())
}
// ─────────────────────────────────────────────────────────────────────
// Closure upvalue Load/Store
// ─────────────────────────────────────────────────────────────────────
/// `LoadClosure { upvalue_idx }`: read the raw u64 capture bits and
/// push them onto the stack.
///
/// SURFACE (ADR-006 §2.7.4 — Phase-2c) — the polymorphic LoadClosure
/// path does not source a `NativeKind` for the pushed slot. Per
/// playbook §2 kind-sourcing rules the closure-capture kind comes
/// from `current_closure_layout()?.capture_native_kind(idx)` (the
/// Wave-γ G-owned-closure-block API at `closure_layout.rs:971`),
/// which DOES classify the capture slot — but the polymorphic
/// `LoadClosure` opcode is dispatched against captures of any
/// `CaptureKind` (Immutable / OwnedMutable / Shared). For
/// `Immutable` captures the raw u64 IS the value (kind matches
/// `capture_native_kind`); for `OwnedMutable` it's a `*mut T` cell
/// pointer (the inner-typed Load handler must run, the polymorphic
/// path corrupts width); for `Shared` it's `*const SharedCell`
/// (same — the SharedCell handler must run).
///
/// The compiler's Wave D / Wave E flip emits the typed
/// `LoadOwnedMutableCapture<Kind>` / `LoadSharedCapture<Kind>`
/// opcodes; the polymorphic `LoadClosure` is the legacy dispatch
/// for `Immutable` captures only. For Immutable captures the kind
/// IS the layout's `capture_native_kind(upvalue_idx)`. Migrated.
fn op_load_closure(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(upvalue_idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(upvalue_idx)?;
// ADR-006 §2.7.8 / Q10: kind comes from the closure layout's
// per-capture `NativeKind` track (Wave-γ G-owned-closure-block
// commit `cb0bf86`). For `Immutable` captures this IS the slot's
// kind; for `OwnedMutable` / `Shared` the typed dispatch runs
// through `LoadOwnedMutableCapture<Kind>` / `LoadSharedCapture<Kind>`
// and never reaches this polymorphic shell.
let kind = self
.current_closure_layout()
.map(|l| l.capture_native_kind(upvalue_idx as usize))
.ok_or_else(|| {
VMError::RuntimeError(format!(
"LoadClosure[{}]: no closure layout registered for the current frame",
upvalue_idx
))
})?;
// WB2.4 retain-on-read: bump the heap refcount for the pushed
// share. The closure block continues to own its own share.
crate::executor::vm_impl::stack::clone_with_kind(bits, kind);
self.push_kinded(bits, kind)
}
/// `StoreClosure { upvalue_idx }`: pop a kinded slot and store the
/// new capture bits into `frame.upvalues[upvalue_idx]`.
///
/// The compiler emits this for `Immutable` captures only when the
/// closure body upgrades the capture to mutable. For
/// `OwnedMutable` / `Shared` captures the typed Store opcodes run.
fn op_store_closure(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(upvalue_idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (new_bits, src_kind) = self.pop_kinded()?;
let layout = self.current_closure_layout().ok_or_else(|| {
// Drop the popped share — we own it but cannot install it.
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
VMError::RuntimeError(format!(
"StoreClosure[{}]: no closure layout registered for the current frame",
upvalue_idx
))
})?;
let cell_kind = layout.capture_native_kind(upvalue_idx as usize);
// Mid-life kind change refused per ADR-006 §2.7.8 — the layout's
// `capture_native_kind` is set at construction (constant per
// `ClosureTypeId`) and immutable. A `Store` whose source kind
// disagrees would silently misclassify the cell on retire.
if cell_kind != src_kind {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(format!(
"StoreClosure[{}]: source kind {:?} does not match capture kind {:?} \
(ADR-006 §2.7.8 / Q10 — capture kind is fixed at closure construction)",
upvalue_idx, src_kind, cell_kind
)));
}
let frame = self.call_stack.last_mut().ok_or_else(|| {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
VMError::RuntimeError("StoreClosure outside a call frame".into())
})?;
let upvalues = frame.upvalues.as_mut().ok_or_else(|| {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
VMError::RuntimeError("StoreClosure in a frame without upvalues".into())
})?;
let slot = upvalues.get_mut(upvalue_idx as usize).ok_or_else(|| {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
VMError::RuntimeError(format!(
"Upvalue index {} not found in closure",
upvalue_idx
))
})?;
record_heap_write();
let old_bits = *slot;
write_barrier_slot(old_bits, new_bits);
*slot = new_bits;
// Release the previous capture's heap share (if any) via
// `drop_with_kind` using the cell's persistent kind.
crate::executor::vm_impl::stack::drop_with_kind(old_bits, cell_kind);
Ok(())
}
/// `CloseUpvalue`: legacy no-op — closures capture by value through
/// `OwnedClosureBlock` cell layout; "closing" is implicit on capture.
fn op_close_upvalue(&mut self, _instruction: &Instruction) -> Result<(), VMError> {
Ok(())
}
// ─────────────────────────────────────────────────────────────────────
// OwnedMutable capture: polymorphic legacy + typed handlers
// ─────────────────────────────────────────────────────────────────────
/// `LoadOwnedMutableCapture { idx }` — polymorphic legacy entry.
///
/// SURFACE (ADR-006 §2.7.4 — Phase-2c): the polymorphic body
/// matched on `layout.capture_inner_kind(idx)` and pushed a
/// `ValueWord::from_raw_bits(bits)` for the Ptr arm via the deleted
/// `vw_clone(cell_bits)` retain. Both `ValueWord` and `vw_clone` are
/// deleted (CLAUDE.md "Forbidden code"). The typed Wave D opcodes
/// (`LoadOwnedMutableCapture<Kind>`) replace this dispatch
/// per-FieldKind; the compiler's Wave E flip emits the typed form
/// for every capture site. This polymorphic shell stays as a SURFACE
/// marker until it is removed from the bytecode entirely (out of
/// B6 territory — bytecode-level cleanup).
fn op_load_owned_mutable_capture(
&mut self,
_instruction: &Instruction,
) -> Result<(), VMError> {
Err(VMError::NotImplemented(
"LoadOwnedMutableCapture (polymorphic): the deleted ValueWord/vw_clone \
dispatch path is replaced by per-FieldKind LoadOwnedMutableCapture<Kind> \
opcodes (Wave D). Polymorphic shell remains as a SURFACE marker per \
ADR-006 §2.7.4 / Phase-2c — the compiler's Wave E flip emits the typed \
form; this shell should be removed from the bytecode dispatch in a \
follow-up cleanup wave (out of B6 territory)."
.into(),
))
}
/// `StoreOwnedMutableCapture { idx }` — polymorphic legacy entry.
///
/// SURFACE — same gap as `op_load_owned_mutable_capture`.
fn op_store_owned_mutable_capture(
&mut self,
_instruction: &Instruction,
) -> Result<(), VMError> {
Err(VMError::NotImplemented(
"StoreOwnedMutableCapture (polymorphic): paired with the LoadOwnedMutableCapture \
SURFACE — the deleted ValueWord/vw_drop release path is replaced by typed \
StoreOwnedMutableCapture<Kind> opcodes (Wave D). Polymorphic shell remains \
as a SURFACE marker per ADR-006 §2.7.4 / Phase-2c."
.into(),
))
}
fn op_load_owned_mutable_capture_i64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut i64;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
// SAFETY: `cell_ptr` was produced by `alloc_owned_mutable_i64` in
// `op_make_closure`. The interior FieldKind is determined by
// `layout.capture_inner_kind(idx) == FieldKind::I64`.
let value = unsafe { shape_value::v2::closure_raw::read_owned_mutable_i64(cell_ptr) };
self.push_kinded(value as u64, NativeKind::Int64)
}
fn op_load_owned_mutable_capture_u64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut u64;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_owned_mutable_u64(cell_ptr) };
self.push_kinded(value, NativeKind::UInt64)
}
fn op_load_owned_mutable_capture_f64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut f64;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_owned_mutable_f64(cell_ptr) };
self.push_kinded(value.to_bits(), NativeKind::Float64)
}
fn op_load_owned_mutable_capture_i32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut i32;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_owned_mutable_i32(cell_ptr) };
// Sign-extend to 8-byte slot.
self.push_kinded(value as i64 as u64, NativeKind::Int32)
}
fn op_load_owned_mutable_capture_u32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut u32;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_owned_mutable_u32(cell_ptr) };
self.push_kinded(value as u64, NativeKind::UInt32)
}
fn op_load_owned_mutable_capture_i16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut i16;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_owned_mutable_i16(cell_ptr) };
self.push_kinded(value as i64 as u64, NativeKind::Int16)
}
fn op_load_owned_mutable_capture_u16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut u16;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_owned_mutable_u16(cell_ptr) };
self.push_kinded(value as u64, NativeKind::UInt16)
}
fn op_load_owned_mutable_capture_i8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut i8;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_owned_mutable_i8(cell_ptr) };
self.push_kinded(value as i64 as u64, NativeKind::Int8)
}
fn op_load_owned_mutable_capture_u8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut u8;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_owned_mutable_u8(cell_ptr) };
self.push_kinded(value as u64, NativeKind::UInt8)
}
fn op_load_owned_mutable_capture_bool(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut bool;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_owned_mutable_bool(cell_ptr) };
self.push_kinded(value as u64, NativeKind::Bool)
}
/// `LoadOwnedMutableCapturePtr { idx }` — typed Ptr load with kind
/// threaded via the §2.7.8 OwnedClosureBlock per-capture kind track.
///
/// Wave-γ G-owned-closure-block (commit `cb0bf86`) added
/// `ClosureLayout::capture_native_kind(i)` and
/// `OwnedClosureBlock::read_capture_kinded(i)`. The `OwnedMutable`
/// cell's interior kind is `layout.capture_native_kind(idx)` —
/// the layout descriptor classifies the inner payload's
/// `NativeKind` (heap-bearing arms like
/// `Ptr(HeapKind::TypedArray)`, `String`, etc., or inline scalars
/// for narrower-kind override paths). The Load reads the bits via
/// the typed `read_owned_mutable_ptr` helper and pushes with the
/// layout-resolved kind — WB2.4 retain-on-read bumps the heap
/// share via `clone_with_kind`.
fn op_load_owned_mutable_capture_ptr(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut u64;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
// ADR-006 §2.7.8 / Q10 (Wave-γ G-owned-closure-block close,
// commit `cb0bf86`): the layout's `capture_native_kinds[idx]`
// classifies the cell's interior payload. For Ptr-typed
// captures the kind is the heap arm
// (`Ptr(HeapKind::TypedArray)`, etc.) or `String`.
let layout = self.current_closure_layout().ok_or_else(|| {
VMError::RuntimeError(
"LoadOwnedMutableCapturePtr without registered ClosureLayout".to_string(),
)
})?;
let kind = layout.capture_native_kind(idx as usize);
// SAFETY: `cell_ptr` was produced by `alloc_owned_mutable_ptr`
// in `op_make_closure`. The cell stores one `u64` cell with
// `Arc<T>::into_raw` bits per construction-side contract; the
// layout's `capture_native_kinds[idx]` carries the matching
// `NativeKind` (Wave-γ G-owned-closure-block lockstep
// invariant).
let cell_bits = unsafe { shape_value::v2::closure_raw::read_owned_mutable_ptr(cell_ptr) };
// WB2.4 retain-on-read: cell continues to own its share; the
// pushed stack slot needs an independent share.
crate::executor::vm_impl::stack::clone_with_kind(cell_bits, kind);
self.push_kinded(cell_bits, kind)
}
fn op_store_owned_mutable_capture_i64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as i64;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut i64;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_owned_mutable_i64(cell_ptr, new_value) };
Ok(())
}
fn op_store_owned_mutable_capture_u64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (new_value, _src_kind) = self.pop_kinded()?;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut u64;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_owned_mutable_u64(cell_ptr, new_value) };
Ok(())
}
fn op_store_owned_mutable_capture_f64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = f64::from_bits(src_bits);
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut f64;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_owned_mutable_f64(cell_ptr, new_value) };
Ok(())
}
fn op_store_owned_mutable_capture_i32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as i32;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut i32;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_owned_mutable_i32(cell_ptr, new_value) };
Ok(())
}
fn op_store_owned_mutable_capture_u32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as u32;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut u32;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_owned_mutable_u32(cell_ptr, new_value) };
Ok(())
}
fn op_store_owned_mutable_capture_i16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as i16;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut i16;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_owned_mutable_i16(cell_ptr, new_value) };
Ok(())
}
fn op_store_owned_mutable_capture_u16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as u16;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut u16;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_owned_mutable_u16(cell_ptr, new_value) };
Ok(())
}
fn op_store_owned_mutable_capture_i8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as i8;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut i8;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_owned_mutable_i8(cell_ptr, new_value) };
Ok(())
}
fn op_store_owned_mutable_capture_u8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as u8;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut u8;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_owned_mutable_u8(cell_ptr, new_value) };
Ok(())
}
fn op_store_owned_mutable_capture_bool(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits != 0;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut bool;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_owned_mutable_bool(cell_ptr, new_value) };
Ok(())
}
/// `StoreOwnedMutableCapturePtr { idx }` — typed Ptr store with
/// kind threaded via the §2.7.8 OwnedClosureBlock per-capture kind
/// track. Releases the prior cell payload's heap share via
/// `drop_with_kind` using the layout-resolved kind, then installs
/// the new payload (which retains the share transferred on the
/// stack pop).
fn op_store_owned_mutable_capture_ptr(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (new_bits, src_kind) = self.pop_kinded()?;
let layout = self.current_closure_layout().ok_or_else(|| {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
VMError::RuntimeError(
"StoreOwnedMutableCapturePtr without registered ClosureLayout".to_string(),
)
})?;
let cell_kind = layout.capture_native_kind(idx as usize);
// ADR-006 §2.7.8 mid-life kind change refusal — capture kind is
// set at construction (constant per `ClosureTypeId`) and must
// match the source kind of every Store.
if cell_kind != src_kind {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(format!(
"StoreOwnedMutableCapturePtr[{}]: source kind {:?} does not match \
capture kind {:?} (ADR-006 §2.7.8 / Q10 — kind fixed at construction)",
idx, src_kind, cell_kind
)));
}
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *mut u64;
if cell_ptr.is_null() {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(
"OwnedMutable capture pointer is null".to_string(),
));
}
record_heap_write();
// Read the previous payload bits before overwriting so we can
// release that share via `drop_with_kind` after the write.
// SAFETY: `cell_ptr` was produced by `alloc_owned_mutable_ptr`;
// it stores exactly one `u64` cell.
let prev_bits = unsafe { shape_value::v2::closure_raw::read_owned_mutable_ptr(cell_ptr) };
unsafe { shape_value::v2::closure_raw::write_owned_mutable_ptr(cell_ptr, new_bits) };
// Release the previous cell payload's heap share per ADR-006
// §2.7.8 retain-on-overwrite. The cell now owns `new_bits`
// (the share transferred from the popped stack slot).
crate::executor::vm_impl::stack::drop_with_kind(prev_bits, cell_kind);
Ok(())
}
// ─────────────────────────────────────────────────────────────────────
// Shared capture: polymorphic legacy + typed handlers
// ─────────────────────────────────────────────────────────────────────
/// `LoadSharedCapture { idx }` — polymorphic legacy entry.
///
/// Migrated to the §2.7.8 `SharedCell::kind()` API (Wave-α
/// B8-shared-cell) — the cell's kind is set at construction and
/// read alongside the payload bits for every Load.
fn op_load_shared_capture(&mut self, instruction: &Instruction) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
// SAFETY: `cell_ptr` was produced by `Arc::into_raw(Arc::new(...))`
// in `op_make_closure`; the closure block keeps the share alive.
let cell_ref = unsafe { &*cell_ptr };
let kind = cell_ref.kind();
let payload_bits = {
let guard = cell_ref.lock();
*guard
};
// WB2.4 retain-on-read: cell keeps its share, stack push needs
// an independent share.
crate::executor::vm_impl::stack::clone_with_kind(payload_bits, kind);
self.push_kinded(payload_bits, kind)
}
/// `StoreSharedCapture { idx }` — polymorphic legacy entry.
///
/// Migrated to use `SharedCell::kind()` for retain-on-overwrite.
/// Pops the kinded source, verifies the source kind matches the
/// cell kind (§2.7.8 mid-life kind-change refusal), takes the
/// cell's lock to swap bits, releases the prior payload's heap
/// share via `drop_with_kind` outside the lock.
fn op_store_shared_capture(&mut self, instruction: &Instruction) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (new_bits, src_kind) = self.pop_kinded()?;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
// SAFETY: same invariants as `op_load_shared_capture`.
let cell_ref = unsafe { &*cell_ptr };
let cell_kind = cell_ref.kind();
if cell_kind != src_kind {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(format!(
"StoreSharedCapture[{}]: source kind {:?} does not match cell kind {:?} \
(ADR-006 §2.7.8 / Q10 — SharedCell kind is fixed at construction)",
idx, src_kind, cell_kind
)));
}
record_heap_write();
let prev_bits = {
let mut guard = cell_ref.lock();
let prev = *guard;
*guard = new_bits;
prev
};
// Release the previous payload's heap share outside the lock.
crate::executor::vm_impl::stack::drop_with_kind(prev_bits, cell_kind);
Ok(())
}
fn op_load_shared_capture_i64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_shared_i64(cell_ptr) };
self.push_kinded(value as u64, NativeKind::Int64)
}
fn op_load_shared_capture_u64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_shared_u64(cell_ptr) };
self.push_kinded(value, NativeKind::UInt64)
}
fn op_load_shared_capture_f64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_shared_f64(cell_ptr) };
self.push_kinded(value.to_bits(), NativeKind::Float64)
}
fn op_load_shared_capture_i32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_shared_i32(cell_ptr) };
self.push_kinded(value as i64 as u64, NativeKind::Int32)
}
fn op_load_shared_capture_u32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_shared_u32(cell_ptr) };
self.push_kinded(value as u64, NativeKind::UInt32)
}
fn op_load_shared_capture_i16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_shared_i16(cell_ptr) };
self.push_kinded(value as i64 as u64, NativeKind::Int16)
}
fn op_load_shared_capture_u16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_shared_u16(cell_ptr) };
self.push_kinded(value as u64, NativeKind::UInt16)
}
fn op_load_shared_capture_i8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_shared_i8(cell_ptr) };
self.push_kinded(value as i64 as u64, NativeKind::Int8)
}
fn op_load_shared_capture_u8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_shared_u8(cell_ptr) };
self.push_kinded(value as u64, NativeKind::UInt8)
}
fn op_load_shared_capture_bool(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
let value = unsafe { shape_value::v2::closure_raw::read_shared_bool(cell_ptr) };
self.push_kinded(value as u64, NativeKind::Bool)
}
/// `LoadSharedCapturePtr { idx }` — typed Ptr load via
/// `SharedCell::kind()` (Wave-β B6 round-1, commit `c785174`).
fn op_load_shared_capture_ptr(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
// SAFETY: same invariants as `op_load_shared_capture`.
let cell_ref = unsafe { &*cell_ptr };
let kind = cell_ref.kind();
let payload_bits = {
let guard = cell_ref.lock();
*guard
};
crate::executor::vm_impl::stack::clone_with_kind(payload_bits, kind);
self.push_kinded(payload_bits, kind)
}
fn op_store_shared_capture_i64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as i64;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_shared_i64(cell_ptr, new_value) };
Ok(())
}
fn op_store_shared_capture_u64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (new_value, _src_kind) = self.pop_kinded()?;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_shared_u64(cell_ptr, new_value) };
Ok(())
}
fn op_store_shared_capture_f64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = f64::from_bits(src_bits);
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_shared_f64(cell_ptr, new_value) };
Ok(())
}
fn op_store_shared_capture_i32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as i64 as i32;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_shared_i32(cell_ptr, new_value) };
Ok(())
}
fn op_store_shared_capture_u32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as u32;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_shared_u32(cell_ptr, new_value) };
Ok(())
}
fn op_store_shared_capture_i16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as i64 as i16;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_shared_i16(cell_ptr, new_value) };
Ok(())
}
fn op_store_shared_capture_u16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as u16;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_shared_u16(cell_ptr, new_value) };
Ok(())
}
fn op_store_shared_capture_i8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as i64 as i8;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_shared_i8(cell_ptr, new_value) };
Ok(())
}
fn op_store_shared_capture_u8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits as u8;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_shared_u8(cell_ptr, new_value) };
Ok(())
}
fn op_store_shared_capture_bool(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let new_value = src_bits != 0;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
record_heap_write();
unsafe { shape_value::v2::closure_raw::write_shared_bool(cell_ptr, new_value) };
Ok(())
}
/// `StoreSharedCapturePtr { idx }` — typed Ptr store via
/// `SharedCell::kind()` (Wave-β B6 round-1, commit `c785174`).
fn op_store_shared_capture_ptr(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (new_bits, src_kind) = self.pop_kinded()?;
let bits = self.read_capture_raw_pointer_bits(idx)?;
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(
"Shared capture pointer is null".to_string(),
));
}
// SAFETY: see `op_load_shared_capture`.
let cell_ref = unsafe { &*cell_ptr };
let cell_kind = cell_ref.kind();
if cell_kind != src_kind {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(format!(
"StoreSharedCapturePtr[{}]: source kind {:?} does not match cell kind \
{:?} (ADR-006 §2.7.8 / Q10 — SharedCell kind fixed at construction)",
idx, src_kind, cell_kind
)));
}
record_heap_write();
let prev_bits = {
let mut guard = cell_ref.lock();
let prev = *guard;
*guard = new_bits;
prev
};
crate::executor::vm_impl::stack::drop_with_kind(prev_bits, cell_kind);
Ok(())
}
// ─────────────────────────────────────────────────────────────────────
// Shared local opcodes (AllocSharedLocal / Load / Store / Drop)
// ─────────────────────────────────────────────────────────────────────
fn op_alloc_shared_local(&mut self, instruction: &Instruction) -> Result<(), VMError> {
// Wave 8 W8-T25 close (ADR-006 §2.7.12 / Q13 amendment,
// 2026-05-10): with `HeapKind::SharedCell` now in the heap-
// variants enum and wired through every Q8/Q10 dispatch table
// (`clone_with_kind` / `drop_with_kind` in `vm_impl/stack.rs`,
// `KindedSlot::clone` / `KindedSlot::drop` in `kinded_slot.rs`,
// `SharedCell::drop` in `v2/closure_layout.rs`,
// `TypedObjectStorage::drop` in `heap_value.rs`), the parallel-
// kind track has the discriminator required to label
// `*const SharedCell` cell-pointer bits.
//
// Lifecycle (per `bytecode/opcode_defs.rs:1426`):
// 1. Pop the initial value (raw bits + payload `NativeKind`)
// off the kinded stack — the share owned by the popped
// slot transfers into the cell's `value` field.
// 2. Allocate `Arc::new(SharedCell::new(value_bits, value_kind))`.
// `SharedCell::new` records the cell's persistent kind
// companion per §2.7.8 / Q10 — the lockstep invariant the
// Drop matrix relies on.
// 3. `Arc::into_raw(arc) as u64` produces the cell-pointer
// bits; the local slot becomes the unique strong-count
// owner.
// 4. Write the cell-pointer + `NativeKind::Ptr(HeapKind::SharedCell)`
// kind into the local slot via `stack_write_kinded`. The
// previous occupant (zero/Bool sentinel from frame
// pre-init) is released as a no-op.
//
// Forbidden shapes refused on sight:
// * §2.7.8 #9 Bool-default fallback for the cell's interior
// kind — `value_kind` is sourced from the popped stack
// slot's parallel-kind track (the same kind the producer
// wrote at push time).
// * `(decode|tag|kind|dispatch|...) (bridge|probe|helper|hop|
// translator|adapter|shim)` defection-attractor framing
// for the cell-pointer share — the `Arc<SharedCell>`
// retain/release goes through the §2.7.7 / §2.7.8 dispatch
// tables directly (the `HeapKind::SharedCell` arm), not
// through any "bridge" or "probe".
use shape_value::v2::closure_layout::SharedCell;
use std::sync::Arc as StdArc;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (value_bits, value_kind) = self.pop_kinded()?;
// SAFETY: `SharedCell::new(bits, kind)` records the kind
// companion in lockstep with the value bits per §2.7.8 / Q10.
// `pop_kinded` transferred the share ownership out of the
// stack slot into our local; passing it to the cell transfers
// the share into the cell's `value` field. `SharedCell::Drop`
// will retire that share via `drop_with_kind(value_bits, value_kind)`
// when the last `Arc<SharedCell>` share retires.
let cell = StdArc::new(SharedCell::new(value_bits, value_kind));
let cell_bits = StdArc::into_raw(cell) as u64;
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
// Reclaim the share we were about to install. Use the same
// `Arc::from_raw` shape `op_drop_shared_local` uses.
unsafe {
drop(StdArc::from_raw(cell_bits as *const SharedCell));
}
return Err(VMError::RuntimeError(format!(
"AllocSharedLocal: slot {} out of bounds (stack len {})",
idx,
self.stack.len()
)));
}
// The frame-init sentinel at `slot` is `(NONE_BITS, Bool)`;
// `stack_write_kinded` releases that no-op then installs the
// new (cell_bits, SharedCell) pair in lockstep.
self.stack_write_kinded(
slot,
cell_bits,
NativeKind::Ptr(HeapKind::SharedCell),
);
Ok(())
}
fn op_load_shared_local(&mut self, instruction: &Instruction) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
return Err(VMError::RuntimeError(format!(
"LoadSharedLocal: slot {} out of bounds (stack len {})",
idx,
self.stack.len()
)));
}
let bits = self.stack[slot];
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"LoadSharedLocal: Shared local pointer is null (not initialised or already dropped)"
.to_string(),
));
}
// SAFETY: see `op_load_shared_capture`.
let cell_ref = unsafe { &*cell_ptr };
let kind = cell_ref.kind();
let payload_bits = {
let guard = cell_ref.lock();
*guard
};
crate::executor::vm_impl::stack::clone_with_kind(payload_bits, kind);
self.push_kinded(payload_bits, kind)
}
fn op_store_shared_local(&mut self, instruction: &Instruction) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (new_bits, src_kind) = self.pop_kinded()?;
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(format!(
"StoreSharedLocal: slot {} out of bounds (stack len {})",
idx,
self.stack.len()
)));
}
let bits = self.stack[slot];
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(
"StoreSharedLocal: Shared local pointer is null".to_string(),
));
}
// SAFETY: see `op_load_shared_capture`.
let cell_ref = unsafe { &*cell_ptr };
let cell_kind = cell_ref.kind();
if cell_kind != src_kind {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(format!(
"StoreSharedLocal[{}]: source kind {:?} does not match cell kind {:?} \
(ADR-006 §2.7.8 / Q10 — SharedCell kind fixed at construction)",
idx, src_kind, cell_kind
)));
}
record_heap_write();
let prev_bits = {
let mut guard = cell_ref.lock();
let prev = *guard;
*guard = new_bits;
prev
};
crate::executor::vm_impl::stack::drop_with_kind(prev_bits, cell_kind);
Ok(())
}
fn op_drop_shared_local(&mut self, instruction: &Instruction) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
use std::sync::Arc as StdArc;
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
return Err(VMError::RuntimeError(format!(
"DropSharedLocal: slot {} out of bounds (stack len {})",
idx,
self.stack.len()
)));
}
let bits = self.stack[slot];
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"DropSharedLocal: Shared local pointer is null".to_string(),
));
}
// Take the slot via `stack_take_kinded` to clear both the bits
// and kind track in lockstep (zero/Bool sentinel after take).
let _ = self.stack_take_kinded(slot);
// Reclaim the Arc strong-count share allocated by
// `op_alloc_shared_local`. The cell payload's interior share
// (if any) was already released by the matching
// `StoreSharedLocal`/`Drop`-time release path inside the Arc's
// `Drop` glue — `SharedCell`'s `Drop` calls `drop_with_kind`
// on its inner payload using its persistent kind.
unsafe {
drop(StdArc::from_raw(cell_ptr));
}
Ok(())
}
// ─────────────────────────────────────────────────────────────────────
// Shared module-binding opcodes
// ─────────────────────────────────────────────────────────────────────
fn op_alloc_shared_module_binding(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
// Wave 8 W8-T25 close (ADR-006 §2.7.12 / Q13 amendment,
// 2026-05-10): paired with `op_alloc_shared_local` above. The
// Wave-γ G-module-bindings-kind `module_binding_write_kinded`
// API was already in place; only the `HeapKind::SharedCell`
// amendment was missing.
//
// Lifecycle (per `bytecode/opcode_defs.rs:1494`):
// 1. Pop the initial value (raw bits + payload `NativeKind`)
// off the kinded stack.
// 2. Allocate `Arc::new(SharedCell::new(value_bits, value_kind))`.
// 3. `Arc::into_raw(arc) as u64` and write into
// `module_bindings[idx]` via `module_binding_write_kinded`
// with kind `NativeKind::Ptr(HeapKind::SharedCell)`.
// 4. Register `idx` with `shared_module_bindings` so the
// VM-Drop special-case loop reclaims the Arc share via
// `Arc::from_raw` (the kind-aware second loop sees the
// zero/Bool sentinel left behind by the special-case loop
// and is a no-op — see `executor/mod.rs::Drop for VirtualMachine`).
//
// Forbidden shapes refused on sight: same as
// `op_alloc_shared_local` — no Bool-default fallback, no
// `(decode|tag|...) (bridge|probe|...)` defection-attractor
// framing.
use shape_value::v2::closure_layout::SharedCell;
use std::sync::Arc as StdArc;
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (value_bits, value_kind) = self.pop_kinded()?;
// SAFETY: same construction-side contract as
// `op_alloc_shared_local`. The popped slot's share transfers
// into the cell's `value` field; `SharedCell::Drop` retires it
// via `drop_with_kind` at refcount=0.
let cell = StdArc::new(SharedCell::new(value_bits, value_kind));
let cell_bits = StdArc::into_raw(cell) as u64;
let index = idx as usize;
// `module_binding_write_kinded` grows the parallel tracks if
// `index` is past the current end (via `module_binding_pad_to_kinded`),
// releases the previous occupant via `drop_with_kind`, and
// installs `(cell_bits, NativeKind::Ptr(HeapKind::SharedCell))`
// in lockstep.
self.module_binding_write_kinded(
index,
cell_bits,
NativeKind::Ptr(HeapKind::SharedCell),
);
// Register the slot so VM-Drop reclaims the Arc<SharedCell>
// share via `Arc::from_raw`. The kind-aware second loop in
// `Drop for VirtualMachine` zeroes both bits and kind first,
// so the parallel-kind dispatch is a no-op for this slot at
// teardown — the explicit `Arc::from_raw` retire is the sole
// release path.
self.shared_module_bindings.insert(index);
Ok(())
}
fn op_load_shared_module_binding(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let index = idx as usize;
if index >= self.module_bindings_len() {
return Err(VMError::RuntimeError(format!(
"LoadSharedModuleBinding: slot {} out of bounds (module_bindings len {})",
index,
self.module_bindings_len()
)));
}
let (bits, _stored_kind) = self.module_binding_read_kinded_raw(index);
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
return Err(VMError::RuntimeError(
"LoadSharedModuleBinding: Shared module binding pointer is null".to_string(),
));
}
// SAFETY: see `op_load_shared_capture`.
let cell_ref = unsafe { &*cell_ptr };
let kind = cell_ref.kind();
let payload_bits = {
let guard = cell_ref.lock();
*guard
};
crate::executor::vm_impl::stack::clone_with_kind(payload_bits, kind);
self.push_kinded(payload_bits, kind)
}
fn op_store_shared_module_binding(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::v2::closure_layout::SharedCell;
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (new_bits, src_kind) = self.pop_kinded()?;
let index = idx as usize;
if index >= self.module_bindings_len() {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(format!(
"StoreSharedModuleBinding: slot {} out of bounds (module_bindings len {})",
index,
self.module_bindings_len()
)));
}
let (bits, _stored_kind) = self.module_binding_read_kinded_raw(index);
let cell_ptr = bits as *const SharedCell;
if cell_ptr.is_null() {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(
"StoreSharedModuleBinding: Shared module binding pointer is null".to_string(),
));
}
let cell_ref = unsafe { &*cell_ptr };
let cell_kind = cell_ref.kind();
if cell_kind != src_kind {
crate::executor::vm_impl::stack::drop_with_kind(new_bits, src_kind);
return Err(VMError::RuntimeError(format!(
"StoreSharedModuleBinding[{}]: source kind {:?} does not match cell \
kind {:?} (ADR-006 §2.7.8 / Q10 — SharedCell kind fixed at \
construction)",
index, src_kind, cell_kind
)));
}
record_heap_write();
let prev_bits = {
let mut guard = cell_ref.lock();
let prev = *guard;
*guard = new_bits;
prev
};
crate::executor::vm_impl::stack::drop_with_kind(prev_bits, cell_kind);
Ok(())
}
// ─────────────────────────────────────────────────────────────────────
// LoadLocal / LoadLocalTrusted (polymorphic) — kind from FrameDescriptor
// ─────────────────────────────────────────────────────────────────────
/// `LoadLocal { idx }` — kind from `FrameDescriptor.slots[idx]` per
/// playbook §2 kind-sourcing rules. The slot's bits are read raw
/// and pushed kinded; `clone_with_kind` bumps the heap share so
/// the slot stays live.
pub(in crate::executor) fn op_load_local(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocal slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
// ADR-006 §2.7.7 / playbook §2: source kind from the parallel
// kind track (the lockstep `kinds[slot]` matches the producing
// typed Store / typed initial-write). Replaces the deleted
// `tag_bits::is_tagged` / `get_tag` / `ValueWord::clone_from_bits`
// legacy dispatch (CLAUDE.md "Forbidden code" #3 — runtime
// tag_bits dispatch).
let (bits, kind) = self.stack_read_kinded_raw(slot);
// WB2.4 retain-on-read: bump the heap refcount so the pushed
// share is independent of the slot's share.
crate::executor::vm_impl::stack::clone_with_kind(bits, kind);
self.push_kinded(bits, kind)
}
/// `LoadLocalTrusted { idx }` — same shape as `LoadLocal`. The
/// "trusted" contract used to mean the compiler skipped runtime
/// tag-bit validation; post-ADR-006 §2.7.7 every slot has a
/// concrete kind in the parallel track, so the trusted vs untrusted
/// distinction is no longer about tag dispatch — both paths read
/// the slot's lockstep `(bits, kind)` directly.
#[inline(always)]
pub(in crate::executor) fn op_load_local_trusted(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalTrusted slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let (bits, kind) = self.stack_read_kinded_raw(slot);
crate::executor::vm_impl::stack::clone_with_kind(bits, kind);
self.push_kinded(bits, kind)
}
/// `LoadLocalMove { idx }` — transfer ownership: zero out the slot
/// (kind goes to the no-op Bool sentinel) and push the bits +
/// original kind onto the stack with no refcount change.
fn op_load_local_move(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalMove slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let (bits, kind) = self.stack_take_kinded(slot);
self.push_kinded(bits, kind)
}
/// `LoadLocalClone { idx }` — clone semantics: bump the heap share
/// via `clone_with_kind`, push the share onto the stack; slot
/// stays live.
fn op_load_local_clone(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalClone slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let (bits, kind) = self.stack_read_kinded_raw(slot);
crate::executor::vm_impl::stack::clone_with_kind(bits, kind);
self.push_kinded(bits, kind)
}
/// `StoreLocalDrop { idx }` — pop a kinded source, install into
/// the slot via `stack_write_kinded` (which releases the prior
/// occupant's share via `drop_with_kind` using the slot's prior
/// kind track entry — the canonical retain-on-overwrite path).
fn op_store_local_drop(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (new_bits, new_kind) = self.pop_kinded()?;
record_heap_write();
write_barrier_slot(self.stack[slot], new_bits);
self.stack_write_kinded(slot, new_bits, new_kind);
Ok(())
}
/// `StoreLocal { idx }` — pop a kinded source and install into the
/// slot. The §2.7.7 stack parallel-kind track and the slot's
/// existing kind handle the retain-on-overwrite via
/// `stack_write_kinded`.
pub(in crate::executor) fn op_store_local(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (new_bits, new_kind) = self.pop_kinded()?;
record_heap_write();
write_barrier_slot(self.stack[slot], new_bits);
self.stack_write_kinded(slot, new_bits, new_kind);
Ok(())
}
/// `StoreLocalTyped { idx, width }` — pop a kinded numeric source
/// and width-truncate (sub-i64 integer kinds) before storing the
/// raw native bits into the slot.
fn op_store_local_typed(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::TypedLocal(idx, width)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, src_kind) = self.pop_kinded()?;
let truncated_bits: u64 = if let Some(int_w) = width.to_int_width() {
int_w.truncate(src_bits as i64) as u64
} else {
src_bits
};
record_heap_write();
write_barrier_slot(self.stack[slot], truncated_bits);
self.stack_write_kinded(slot, truncated_bits, src_kind);
Ok(())
}
// ─────────────────────────────────────────────────────────────────────
// Typed local Load/Store (per-Kind handlers)
// ─────────────────────────────────────────────────────────────────────
fn op_load_local_i64(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalI64 slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let bits = unsafe { *(self.stack.as_ptr().add(slot) as *const u64) };
self.push_kinded(bits, NativeKind::Int64)
}
fn op_load_local_u64(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalU64 slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let bits = unsafe { *(self.stack.as_ptr().add(slot) as *const u64) };
self.push_kinded(bits, NativeKind::UInt64)
}
fn op_load_local_f64(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalF64 slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let bits = unsafe { *(self.stack.as_ptr().add(slot) as *const u64) };
self.push_kinded(bits, NativeKind::Float64)
}
fn op_load_local_i32(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalI32 slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let bits = unsafe { *(self.stack.as_ptr().add(slot) as *const u64) };
let value = bits as i32;
self.push_kinded(value as i64 as u64, NativeKind::Int32)
}
fn op_load_local_u32(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalU32 slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let bits = unsafe { *(self.stack.as_ptr().add(slot) as *const u64) };
let value = bits as u32;
self.push_kinded(value as u64, NativeKind::UInt32)
}
fn op_load_local_i16(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalI16 slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let bits = unsafe { *(self.stack.as_ptr().add(slot) as *const u64) };
let value = bits as i16;
self.push_kinded(value as i64 as u64, NativeKind::Int16)
}
fn op_load_local_u16(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalU16 slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let bits = unsafe { *(self.stack.as_ptr().add(slot) as *const u64) };
let value = bits as u16;
self.push_kinded(value as u64, NativeKind::UInt16)
}
fn op_load_local_i8(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalI8 slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let bits = unsafe { *(self.stack.as_ptr().add(slot) as *const u64) };
let value = bits as i8;
self.push_kinded(value as i64 as u64, NativeKind::Int8)
}
fn op_load_local_u8(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalU8 slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let bits = unsafe { *(self.stack.as_ptr().add(slot) as *const u64) };
let value = bits as u8;
self.push_kinded(value as u64, NativeKind::UInt8)
}
fn op_load_local_bool(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalBool slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let bits = unsafe { *(self.stack.as_ptr().add(slot) as *const u64) };
self.push_kinded(bits, NativeKind::Bool)
}
fn op_load_local_ptr(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"LoadLocalPtr slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
// ADR-006 §2.7.7 / playbook §2: kind comes from the §2.7.7 stack
// parallel-kind track; the slot's lockstep entry classifies the
// Ptr variant (e.g. `Ptr(HeapKind::TypedArray)`, `String`).
let (bits, kind) = self.stack_read_kinded_raw(slot);
self.push_kinded(bits, kind)
}
fn op_store_local_i64(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, _src_kind) = self.pop_kinded()?;
record_heap_write();
write_barrier_slot(self.stack[slot], src_bits);
self.stack_write_kinded(slot, src_bits, NativeKind::Int64);
Ok(())
}
fn op_store_local_u64(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, _src_kind) = self.pop_kinded()?;
record_heap_write();
write_barrier_slot(self.stack[slot], src_bits);
self.stack_write_kinded(slot, src_bits, NativeKind::UInt64);
Ok(())
}
fn op_store_local_f64(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, _src_kind) = self.pop_kinded()?;
record_heap_write();
write_barrier_slot(self.stack[slot], src_bits);
self.stack_write_kinded(slot, src_bits, NativeKind::Float64);
Ok(())
}
fn op_store_local_i32(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as i32 as i64 as u64;
record_heap_write();
write_barrier_slot(self.stack[slot], value);
self.stack_write_kinded(slot, value, NativeKind::Int32);
Ok(())
}
fn op_store_local_u32(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as u32 as u64;
record_heap_write();
write_barrier_slot(self.stack[slot], value);
self.stack_write_kinded(slot, value, NativeKind::UInt32);
Ok(())
}
fn op_store_local_i16(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as i16 as i64 as u64;
record_heap_write();
write_barrier_slot(self.stack[slot], value);
self.stack_write_kinded(slot, value, NativeKind::Int16);
Ok(())
}
fn op_store_local_u16(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as u16 as u64;
record_heap_write();
write_barrier_slot(self.stack[slot], value);
self.stack_write_kinded(slot, value, NativeKind::UInt16);
Ok(())
}
fn op_store_local_i8(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as i8 as i64 as u64;
record_heap_write();
write_barrier_slot(self.stack[slot], value);
self.stack_write_kinded(slot, value, NativeKind::Int8);
Ok(())
}
fn op_store_local_u8(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as u8 as u64;
record_heap_write();
write_barrier_slot(self.stack[slot], value);
self.stack_write_kinded(slot, value, NativeKind::UInt8);
Ok(())
}
fn op_store_local_bool(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = (src_bits != 0) as u64;
record_heap_write();
write_barrier_slot(self.stack[slot], value);
self.stack_write_kinded(slot, value, NativeKind::Bool);
Ok(())
}
fn op_store_local_ptr(&mut self, instruction: &Instruction) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
if slot >= self.stack.len() {
self.stack.resize_with(slot + 1, || Self::NONE_BITS);
self.kinds.resize(slot + 1, NativeKind::Bool);
}
let (src_bits, src_kind) = self.pop_kinded()?;
record_heap_write();
write_barrier_slot(self.stack[slot], src_bits);
// Ptr stores propagate the source's heap kind so the slot's
// parallel kind track records the matching `Ptr(HeapKind::*)`
// / `String` arm — `stack_write_kinded` handles
// retain-on-overwrite of the prior occupant.
self.stack_write_kinded(slot, src_bits, src_kind);
Ok(())
}
// ─────────────────────────────────────────────────────────────────────
// Module-binding Load/Store (polymorphic + typed)
// ─────────────────────────────────────────────────────────────────────
/// `LoadModuleBinding { idx }` — Wave-γ G-module-bindings-kind
/// (commit `27e2918`) — read kinded bits from the parallel
/// module-binding kind track and push with `clone_with_kind`
/// retain-on-read.
pub(in crate::executor) fn op_load_module_binding(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, kind) = self.module_binding_read_kinded_raw(idx as usize);
// WB2.4 retain-on-read: the binding slot keeps its share, the
// pushed slot needs an independent share.
crate::executor::vm_impl::stack::clone_with_kind(bits, kind);
self.push_kinded(bits, kind)
}
// ────────────────────────────────────────────────────────────────────
// `MakeRef` / `MakeFieldRef` / `MakeIndexRef` / `DerefLoad` /
// `DerefStore` / `SetIndexRef` — kinded RefTarget redesign per
// ADR-006 §2.7.13 / Q14 (Wave 8 W8-T26, 2026-05-10).
//
// The deleted carrier (`nanboxed::RefTarget` / `RefProjection`
// packed into a TAG_REF `ValueWord`) is replaced by typed-`Arc`
// `RefTarget` payloads emitted to the kinded stack with kind
// `NativeKind::Ptr(HeapKind::Reference)`. Each `RefTarget` variant
// carries the `NativeKind` of the **projected slot**, threaded
// from the producing-opcode emit per §2.7.7 / §2.7.8 / §2.7.10 /
// §2.7.11 invariant — no tag-bit decoding, no kind fabrication
// at projection time, no `is_heap()` probe.
//
// Slot bits for a Reference-labeled slot are
// `Arc::into_raw(Arc<RefTarget>) as u64` directly (mirror of the
// §2.7.9 FilterExpr precedent — `slot.as_heap_value()` is undefined
// on Reference-labeled bits; recovery is `Arc::from_raw::<RefTarget>`).
// ────────────────────────────────────────────────────────────────────
/// `MakeRef { Operand::Local(slot) | Operand::ModuleBinding(idx) }` —
/// constructs a `RefTarget::Local { frame_index, slot_index, kind }`
/// or `RefTarget::ModuleBinding { binding_idx, kind }` and pushes
/// it onto the kinded stack as
/// `Arc::into_raw(Arc<RefTarget>) as u64` with kind
/// `NativeKind::Ptr(HeapKind::Reference)`. The kind is sourced from
/// the §2.7.7 stack parallel-kind track (for locals) or the §2.7.8
/// module-binding parallel-kind track (for module bindings) — never
/// fabricated.
pub(in crate::executor) fn op_make_ref(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::HeapKind;
let rt = match instruction.operand {
Some(Operand::Local(local_idx)) => {
// R8 W9 B3 Drop runtime fix: top-level frame sentinel.
//
// `MakeRef Local` may be emitted at top-level (outside any
// call frame) for typed-field reads like `f.path` inside a
// top-level block scope. The audit recipe surfaces this via
// `impl Drop for T { method drop() { print(self.x) } }` at
// top-level (the Drop body's own `self.x` read is fine —
// it runs inside a frame pushed by `op_drop_call_impl` —
// but the *enclosing* top-level block emits MakeRef Local
// for `f.path` reads, and that path had no frame).
//
// Encode the top-level slot space as `frame_index =
// u32::MAX` (sentinel). Consumers
// (`resolve_typed_object_receiver`, `read_ref_target`,
// `write_ref_target`) check this sentinel and use
// `base_pointer = 0` instead of looking up the frame in
// `call_stack`. The sentinel survives across frame
// boundaries — a Drop method body that received a ref
// captured against the top-level frame still resolves to
// slot 0 of the stack root.
//
// Slot bits are read from absolute slot index `local_idx`
// (top-level `current_locals_base()` is 0), matching the
// §2.7.7 parallel-kind track at the same index.
let frame_index = if self.call_stack.is_empty() {
u32::MAX
} else {
(self.call_stack.len() - 1) as u32
};
let bp = self.current_locals_base();
let slot = bp + local_idx as usize;
if slot >= self.stack.len() {
return Err(VMError::RuntimeError(format!(
"MakeRef Local {} out of bounds (stack len {})",
local_idx,
self.stack.len()
)));
}
// Kind sourced from the §2.7.7 parallel-kind track at
// construction time. The producing typed-Store / typed-
// initial-write emitted this kind; refs capture it
// verbatim, no fabrication.
let (_bits, kind) = self.stack_read_kinded_raw(slot);
shape_value::RefTarget::Local {
frame_index,
slot_index: local_idx as u32,
kind,
}
}
Some(Operand::ModuleBinding(binding_idx)) => {
// Kind sourced from the §2.7.8 module-binding parallel-
// kind track at construction time.
let (_bits, kind) =
self.module_binding_read_kinded_raw(binding_idx as usize);
shape_value::RefTarget::ModuleBinding {
binding_idx: binding_idx as u32,
kind,
}
}
_ => return Err(VMError::InvalidOperand),
};
// Wrap in Arc<RefTarget>, transfer the strong-count share onto
// the stack via `Arc::into_raw`. Slot bits are the `Arc<RefTarget>`
// pointer directly per the §2.7.9 FilterExpr precedent — NOT a
// `Box<HeapValue>` wrap.
let arc = std::sync::Arc::new(rt);
let bits = std::sync::Arc::into_raw(arc) as u64;
self.push_kinded(bits, NativeKind::Ptr(HeapKind::Reference))
}
/// `MakeFieldRef { Operand::TypedField{type_id, field_idx,
/// field_type_tag} }` — pops a base-ref carrier from the stack,
/// resolves the receiver to a `TypedObjectPtr` (v2-raw carrier per
/// ADR-006 §2.3), and pushes a projected `RefTarget::TypedField`
/// ref. The projected
/// slot's kind is sourced from `field_type_tag` via
/// `field_tag_to_native_kind` (heap arms + inline scalars) — never
/// fabricated.
pub(in crate::executor) fn op_make_field_ref(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::HeapKind;
let Some(Operand::TypedField {
field_idx,
field_type_tag,
..
}) = instruction.operand
else {
return Err(VMError::InvalidOperand);
};
// Source the projected slot's NativeKind from the operand-encoded
// field_type_tag — playbook §2 kind-sourcing rules. Surface (no
// fabrication, no Bool-default fallback per §2.7.7 #9) when the
// tag is FIELD_TAG_ANY / FIELD_TAG_UNKNOWN.
let projected_kind = crate::executor::typed_object_ops::field_tag_to_native_kind(
field_type_tag,
)
.ok_or_else(|| {
VMError::NotImplemented(format!(
"MakeFieldRef SURFACE: field_type_tag {} (FIELD_TAG_ANY / \
FIELD_TAG_UNKNOWN) has no statically-sourceable NativeKind \
— ADR-006 §2.7.13 / Q14 forbids fabrication. Producing emitter \
must stamp a concrete tag.",
field_type_tag
))
})?;
// Pop the base-ref carrier. The stack transfers one
// `Arc<RefTarget>` strong-count share to us via `pop_kinded`.
let (base_bits, base_kind) = self.pop_kinded()?;
if base_kind != NativeKind::Ptr(HeapKind::Reference) {
// Release the popped share even on failure — stack ownership
// discipline (§2.7.7 / WB2.4).
crate::executor::vm_impl::stack::drop_with_kind(base_bits, base_kind);
return Err(VMError::RuntimeError(format!(
"MakeFieldRef expected Reference receiver, got {:?}",
base_kind
)));
}
// Resolve the base RefTarget. We hold one strong-count share via
// `base_bits`; recover the `Arc<RefTarget>` and read it. We must
// chase the base ref's *receiver* (the underlying TypedObject) —
// for a Local/ModuleBinding base, read the place's bits to get
// the TypedObject's `Arc::into_raw` pointer; for a TypedField
// base (chained projection), recursively resolve the receiver
// through the parent.
// SAFETY: kind == Ptr(HeapKind::Reference) is the §2.7.9-style
// 1:1 dispatch-table invariant — `base_bits` came from
// `Arc::into_raw::<RefTarget>` at the matching MakeRef /
// MakeFieldRef / MakeIndexRef site.
let base_arc: std::sync::Arc<shape_value::RefTarget> =
unsafe { std::sync::Arc::from_raw(base_bits as *const shape_value::RefTarget) };
let receiver = match self.resolve_typed_object_receiver(&base_arc) {
Ok(r) => r,
Err(e) => {
// Drop the base ref before bubbling the error (the share
// we held via base_arc auto-drops here as it goes out of
// scope).
drop(base_arc);
return Err(e);
}
};
// The base ref share retires here as `base_arc` goes out of scope
// (the popped share was transferred to base_arc; base_arc::drop
// decrements it).
drop(base_arc);
// Bounds check against the receiver's slot count.
if (field_idx as usize) >= receiver.slots.len() {
return Err(VMError::RuntimeError(format!(
"MakeFieldRef field_idx {} out of bounds (slot count {})",
field_idx,
receiver.slots.len()
)));
}
let rt = shape_value::RefTarget::TypedField {
receiver,
field_offset: field_idx as u32,
kind: projected_kind,
};
let arc = std::sync::Arc::new(rt);
let bits = std::sync::Arc::into_raw(arc) as u64;
self.push_kinded(bits, NativeKind::Ptr(HeapKind::Reference))
}
/// `MakeIndexRef` — pops [base_ref, index] from the kinded stack.
///
/// ## V3-S5 ckpt-5 surface (2026-05-15)
///
/// The pre-ckpt-1 body constructed `RefTarget::TypedIndex { receiver:
/// Arc<TypedArrayData>, index, elem_kind }`. The
/// `RefTarget::TypedIndex` variant was DELETED at ckpt-4 in lockstep
/// with the `TypedArrayData` enum + `TypedBuffer<T>` wrapper layer
/// deletion (commits `aac8495e` ckpt-1 + `654c7202` ckpt-4) per
/// W12-typed-array-data-deletion-audit §3.5 + §B + ADR-006 §2.7.24
/// Q25.A SUPERSEDED.
///
/// Construction-site rebuild lands at ckpt-6 STRICT close per the
/// per-element-kind receiver variant target (`Arc<TypedArray<f64>>` /
/// `Arc<TypedArray<i64>>` / etc.) — the replacement requires
/// per-element-kind RefTarget variants, not a single
/// `Arc<TypedArrayData>` enum.
///
/// Stack discipline: pops [base_ref, index] and retires both shares
/// via `drop_with_kind` before surfacing. Refusal #1 binding.
pub(in crate::executor) fn op_make_index_ref(
&mut self,
_instruction: &Instruction,
) -> Result<(), VMError> {
let (idx_bits, idx_kind) = self.pop_kinded()?;
crate::executor::vm_impl::stack::drop_with_kind(idx_bits, idx_kind);
if let Ok((base_bits, base_kind)) = self.pop_kinded() {
crate::executor::vm_impl::stack::drop_with_kind(base_bits, base_kind);
}
Err(VMError::NotImplemented(
"MakeIndexRef: SURFACE — V3-S5 ckpt-5 consumer-cascade tier 3 \
surface. `RefTarget::TypedIndex { receiver: Arc<TypedArrayData>, \
... }` variant DELETED at ckpt-4 in lockstep with TypedArrayData \
enum + Buf<T> wrapper layer deletion (W12-typed-array-\
data-deletion-audit §3.5 + §B + ADR-006 §2.7.24 Q25.A \
SUPERSEDED). Construction-site rebuild lands at ckpt-6 STRICT \
close per per-element-kind RefTarget variant target. \
REFUSED ON SIGHT: TypedArrayData / RefTarget::TypedIndex \
resurrection under any rename (Refusal #1)."
.to_string(),
))
}
/// `DerefLoad { Operand::Local(idx) }` — reads the ref-bearing local
/// (without consuming the slot's share), recovers the `RefTarget`,
/// reads the projected slot's `(bits, kind)`, runs `clone_with_kind`
/// to bump the underlying heap share, and pushes the value onto the
/// kinded stack. The local's ref-share stays live (the binding
/// retains it).
pub(in crate::executor) fn op_deref_load(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::HeapKind;
let Some(Operand::Local(local_idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + local_idx as usize;
if slot >= self.stack.len() {
return Err(VMError::RuntimeError(format!(
"DerefLoad slot {} out of bounds (stack len {})",
local_idx,
self.stack.len()
)));
}
// Read the ref-bearing local without consuming its share — the
// local retains the `Arc<RefTarget>` share; we borrow.
let (ref_bits, ref_kind) = self.stack_read_kinded_raw(slot);
if ref_kind != NativeKind::Ptr(HeapKind::Reference) {
return Err(VMError::RuntimeError(format!(
"DerefLoad expected Reference local, got {:?}",
ref_kind
)));
}
// SAFETY: kind == Ptr(HeapKind::Reference) — `ref_bits` is an
// `Arc::into_raw::<RefTarget>` pointer and the slot keeps one
// share live for us.
let rt: &shape_value::RefTarget =
unsafe { &*(ref_bits as *const shape_value::RefTarget) };
let (out_bits, out_kind) = self.read_ref_target(rt)?;
// WB2.4 retain-on-read: bump the projected share so the pushed
// slot's share is independent of the place's share. The place
// retains its own ownership (the local / module-binding /
// typed-object-field / typed-array-element keeps its share).
crate::executor::vm_impl::stack::clone_with_kind(out_bits, out_kind);
self.push_kinded(out_bits, out_kind)
}
/// `DerefStore { Operand::Local(idx) }` — pops the kinded value to
/// store, reads the ref-bearing local (without consuming its share),
/// recovers the `RefTarget`, releases the projected place's prior
/// occupant via `drop_with_kind`, and writes the new bits. The
/// stored value's share transfers to the place.
pub(in crate::executor) fn op_deref_store(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
use shape_value::HeapKind;
let Some(Operand::Local(local_idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
// Pop the value to store FIRST — we own its share. If the ref-
// shape check fails below, we'll release this share before
// returning the error.
let (val_bits, val_kind) = self.pop_kinded()?;
let bp = self.current_locals_base();
let slot = bp + local_idx as usize;
if slot >= self.stack.len() {
crate::executor::vm_impl::stack::drop_with_kind(val_bits, val_kind);
return Err(VMError::RuntimeError(format!(
"DerefStore slot {} out of bounds (stack len {})",
local_idx,
self.stack.len()
)));
}
let (ref_bits, ref_kind) = self.stack_read_kinded_raw(slot);
if ref_kind != NativeKind::Ptr(HeapKind::Reference) {
crate::executor::vm_impl::stack::drop_with_kind(val_bits, val_kind);
return Err(VMError::RuntimeError(format!(
"DerefStore expected Reference local, got {:?}",
ref_kind
)));
}
// SAFETY: same as DerefLoad.
let rt: &shape_value::RefTarget =
unsafe { &*(ref_bits as *const shape_value::RefTarget) };
// Cross-check: the popped value's kind matches the projected
// slot's kind (§2.7.5.1 stack-contents-are-post-proof). On a
// mismatch, surface — never silently fabricate.
let projected_kind = rt.projected_kind();
debug_assert_eq!(
val_kind, projected_kind,
"DerefStore kind drift: popped {:?}, place {:?} — \
ADR-006 §2.7.13 invariant violated",
val_kind, projected_kind
);
// The write_ref_target helper takes ownership of val_bits and
// releases the prior occupant via drop_with_kind. record_heap_write
// is invoked inside per the GC discipline.
record_heap_write();
self.write_ref_target(rt, val_bits, val_kind)
}
/// `SetIndexRef { Operand::Local(idx) }` — `arr[i] = value` shape.
///
/// ## V3-S5 ckpt-5 surface (2026-05-15)
///
/// The pre-ckpt-1 body resolved the ref's receiver to
/// `Arc<TypedArrayData>`, sourced the element kind from the variant,
/// constructed a synthetic `RefTarget::TypedIndex` projection, and
/// wrote through it via `write_index_in_place`. All three pieces
/// (`Arc<TypedArrayData>` carrier + `RefTarget::TypedIndex` variant +
/// the `write_index_in_place` API) were DELETED at ckpt-1..ckpt-4
/// per W12-typed-array-data-deletion-audit §3.5 + §B + ADR-006
/// §2.7.24 Q25.A SUPERSEDED.
///
/// Construction-site rebuild lands at ckpt-6 STRICT close per the
/// per-element-kind v2-raw `TypedArray<T>` direct-mutation target.
///
/// Stack discipline: pops [index, value] and retires both shares via
/// `drop_with_kind` before surfacing. Refusal #1 binding.
pub(in crate::executor) fn op_set_index_ref(
&mut self,
_instruction: &Instruction,
) -> Result<(), VMError> {
let (val_bits, val_kind) = self.pop_kinded()?;
crate::executor::vm_impl::stack::drop_with_kind(val_bits, val_kind);
if let Ok((idx_bits, idx_kind)) = self.pop_kinded() {
crate::executor::vm_impl::stack::drop_with_kind(idx_bits, idx_kind);
}
Err(VMError::NotImplemented(
"SetIndexRef: SURFACE — V3-S5 ckpt-5 consumer-cascade tier 3 \
surface. `RefTarget::TypedIndex` variant + \
the deleted typed-array-data `write_index_in_place` API + the deleted-enum's \
`Arc<...>` carrier all DELETED at ckpt-1..ckpt-4 per \
W12-typed-array-data-deletion-audit §3.5 + §B + ADR-006 \
§2.7.24 Q25.A SUPERSEDED. Rebuild lands at ckpt-6 STRICT \
close per per-element-kind v2-raw `TypedArray<T>` \
direct-mutation target. REFUSED ON SIGHT: TypedArrayData / \
RefTarget::TypedIndex resurrection under any rename \
(Refusal #1)."
.to_string(),
))
}
// ────────────────────────────────────────────────────────────────────
// RefTarget resolution + read/write helpers (ADR-006 §2.7.13).
// ────────────────────────────────────────────────────────────────────
/// Resolve a `RefTarget` to its underlying `TypedObjectPtr` receiver.
/// For chained projections (TypedField → TypedField), walks the inner
/// ref. Returns an error if the ref points at a non-TypedObject place
/// (e.g. an array or scalar local), which is a construction-side bug.
///
/// Production `TypedObjectStorage` is allocated via the v2-raw `_new`
/// path (`op_new_typed_object`), so the receiver slot bits are the raw
/// struct pointer with `HeapHeader` at offset 0. The retained share is
/// taken via `v2_retain` against that header and handed back wrapped
/// in `TypedObjectPtr` (ADR-006 §2.3 typed-Arc carrier) — NOT via
/// `Arc::increment_strong_count` / `Arc::from_raw`, which would treat
/// the pointer as `&ArcInner.data` and bump/dealloc 16 bytes before
/// the real allocation. Mirror of `clone_with_kind`'s `TypedObject`
/// arm at `vm_impl/stack.rs`.
fn resolve_typed_object_receiver(
&self,
rt: &shape_value::RefTarget,
) -> Result<shape_value::heap_value::TypedObjectPtr, VMError> {
use shape_value::HeapKind;
use shape_value::heap_value::{TypedObjectPtr, TypedObjectStorage};
match rt {
shape_value::RefTarget::Local {
frame_index,
slot_index,
kind,
} => {
if *kind != NativeKind::Ptr(HeapKind::TypedObject) {
return Err(VMError::RuntimeError(format!(
"MakeFieldRef base must reference a TypedObject; got {:?}",
kind
)));
}
// R8 W9 B3 Drop runtime fix: top-level frame sentinel.
// `frame_index == u32::MAX` means the ref was captured at
// top-level (no call frame); base_pointer is 0 (the stack
// root). See `op_make_ref` for construction site.
let base_pointer = if *frame_index == u32::MAX {
0
} else {
self.call_stack
.get(*frame_index as usize)
.ok_or_else(|| {
VMError::RuntimeError(format!(
"RefTarget::Local frame_index {} out of bounds",
frame_index
))
})?
.base_pointer
};
let slot = base_pointer + *slot_index as usize;
let (bits, _) = self.stack_read_kinded_raw(slot);
// SAFETY: kind == Ptr(HeapKind::TypedObject) means the
// bits are the raw `*const TypedObjectStorage` from the
// v2-raw `_new` path with `HeapHeader` at offset 0. We
// bump the on-header refcount to hand the caller an
// independent share (the local retains its own share).
let ptr = bits as *const TypedObjectStorage;
unsafe {
shape_value::v2::refcount::v2_retain(&(*ptr).header);
}
Ok(TypedObjectPtr::new(ptr))
}
shape_value::RefTarget::ModuleBinding { binding_idx, kind } => {
if *kind != NativeKind::Ptr(HeapKind::TypedObject) {
return Err(VMError::RuntimeError(format!(
"MakeFieldRef base must reference a TypedObject; got {:?}",
kind
)));
}
let (bits, _) =
self.module_binding_read_kinded_raw(*binding_idx as usize);
let ptr = bits as *const TypedObjectStorage;
// SAFETY: as above — v2-raw `_new` carrier, HeapHeader at
// offset 0. The module binding retains its own share.
unsafe {
shape_value::v2::refcount::v2_retain(&(*ptr).header);
}
Ok(TypedObjectPtr::new(ptr))
}
shape_value::RefTarget::TypedField {
receiver,
field_offset,
kind,
} => {
if *kind != NativeKind::Ptr(HeapKind::TypedObject) {
return Err(VMError::RuntimeError(format!(
"Chained MakeFieldRef base must reference a TypedObject; got {:?}",
kind
)));
}
let bits = receiver.slots[*field_offset as usize].raw();
let ptr = bits as *const TypedObjectStorage;
// SAFETY: as above — the chained-projection field slot
// holds a v2-raw `_new` `*const TypedObjectStorage`; the
// parent receiver retains its own share.
unsafe {
shape_value::v2::refcount::v2_retain(&(*ptr).header);
}
Ok(TypedObjectPtr::new(ptr))
}
// V3-S5 ckpt-6 STRICT close (2026-05-15):
// `RefTarget::TypedIndex { .. }` arm DELETED in lockstep with
// the variant retirement at `shape-value/src/reference.rs`
// (per ADR-006 §2.7.24 Q25.A SUPERSEDED). The variant carried
// a deleted Arc payload; per-element-T v2-raw receiver
// variants are downstream-wave territory.
}
}
// V3-S5 ckpt-5 (2026-05-15): `resolve_typed_array_receiver` DELETED.
// The helper produced `Arc<TypedArrayData>` (deleted at ckpt-1) for
// the `MakeIndexRef` / `SetIndexRef` consumers; both consumers
// surface-and-stop at ckpt-5 per the V3-S5 ckpt-1..ckpt-4 cascade.
// Per-element-kind v2-raw `TypedArray<T>` receiver resolution lands
// at ckpt-6 STRICT close per W12-typed-array-data-deletion-audit
// §B + ADR-006 §2.7.24 Q25.A SUPERSEDED.
/// Read the projected slot of a `RefTarget` as `(bits, kind)` —
/// borrows the place's share (the place retains ownership). Caller
/// is responsible for `clone_with_kind` if pushing onto the stack.
fn read_ref_target(
&self,
rt: &shape_value::RefTarget,
) -> Result<(u64, NativeKind), VMError> {
match rt {
shape_value::RefTarget::Local {
frame_index,
slot_index,
kind,
} => {
// R8 W9 B3 Drop runtime fix: top-level frame sentinel.
let base_pointer = if *frame_index == u32::MAX {
0
} else {
self.call_stack
.get(*frame_index as usize)
.ok_or_else(|| {
VMError::RuntimeError(format!(
"DerefLoad: RefTarget::Local frame_index {} out of bounds",
frame_index
))
})?
.base_pointer
};
let slot = base_pointer + *slot_index as usize;
let (bits, _stored_kind) = self.stack_read_kinded_raw(slot);
Ok((bits, *kind))
}
shape_value::RefTarget::ModuleBinding { binding_idx, kind } => {
let (bits, _stored_kind) =
self.module_binding_read_kinded_raw(*binding_idx as usize);
Ok((bits, *kind))
}
shape_value::RefTarget::TypedField {
receiver,
field_offset,
kind,
} => {
let bits = receiver.slots[*field_offset as usize].raw();
Ok((bits, *kind))
}
// V3-S5 ckpt-5: `RefTarget::TypedIndex` arm deleted (variant
// retired at ckpt-4 lockstep with TypedArrayData enum). The
// match is now exhaustive on Local | ModuleBinding |
// TypedField; the read-via-index path surface-and-stops at
// `op_make_index_ref` (one level up) per V3-S5 ckpt-5.
}
}
/// Write `(val_bits, val_kind)` into the projected slot of a
/// `RefTarget`, releasing the prior occupant's share via
/// `drop_with_kind`. Caller transfers ownership of `val_bits` to
/// the place.
fn write_ref_target(
&mut self,
rt: &shape_value::RefTarget,
val_bits: u64,
val_kind: NativeKind,
) -> Result<(), VMError> {
match rt {
shape_value::RefTarget::Local {
frame_index,
slot_index,
kind,
} => {
// R8 W9 B3 Drop runtime fix: top-level frame sentinel.
let base_pointer = if *frame_index == u32::MAX {
0
} else {
match self.call_stack.get(*frame_index as usize) {
Some(f) => f.base_pointer,
None => {
crate::executor::vm_impl::stack::drop_with_kind(
val_bits, val_kind,
);
return Err(VMError::RuntimeError(format!(
"DerefStore: RefTarget::Local frame_index {} out of bounds",
frame_index
)));
}
}
};
let slot = base_pointer + *slot_index as usize;
// Cross-check: the place's stored kind matches the ref's
// captured kind (drift = construction-side bug).
let (prior_bits, prior_kind) = self.stack_read_kinded_raw(slot);
debug_assert_eq!(
prior_kind, *kind,
"DerefStore: place kind drift (stored {:?}, ref {:?}) — \
ADR-006 §2.7.13",
prior_kind, kind
);
write_barrier_slot(prior_bits, val_bits);
self.stack_write_kinded(slot, val_bits, val_kind);
Ok(())
}
shape_value::RefTarget::ModuleBinding { binding_idx, kind } => {
let (prior_bits, prior_kind) =
self.module_binding_read_kinded_raw(*binding_idx as usize);
debug_assert_eq!(
prior_kind, *kind,
"DerefStore: module-binding kind drift (stored {:?}, ref {:?}) — \
ADR-006 §2.7.13",
prior_kind, kind
);
write_barrier_slot(prior_bits, val_bits);
self.module_binding_write_kinded(
*binding_idx as usize,
val_bits,
val_kind,
);
Ok(())
}
shape_value::RefTarget::TypedField {
receiver,
field_offset,
kind,
} => {
// Q14 / ADR-006 §2.7.13 projection-write: the receiver
// `TypedObjectPtr` (v2-raw carrier per ADR-006 §2.3)
// shares the underlying `TypedObjectStorage` with the
// originating binding, so no copy-on-write applies
// (refcount > 1 by construction; the struct is
// intentionally not `Clone`). The in-place writer
// (`TypedObjectStorage::write_slot_in_place`, reached
// through `TypedObjectPtr`'s `Deref`) takes the
// kind-aware projected place and rotates the slot's share
// — prior occupant returned for caller release, new
// occupant transferred in.
let field_idx = *field_offset as usize;
if field_idx >= receiver.slots.len() {
crate::executor::vm_impl::stack::drop_with_kind(
val_bits, val_kind,
);
return Err(VMError::RuntimeError(format!(
"DerefStore: TypedField field_offset {} out of bounds \
(slot count {})",
field_idx,
receiver.slots.len()
)));
}
// Kind invariance contract (§2.7.5.1 post-proof): the
// projection's captured `kind` must match the receiver's
// `field_kinds[field_idx]` (set at construction time) AND
// match the popped value's kind (the producing opcode is
// post-proof). Drift = construction-side bug surfaced via
// debug_assert; in release this writes through the captured
// kind since the place's heap_mask bit was set for that
// kind and the prior bits decode under it.
debug_assert_eq!(
receiver.field_kinds[field_idx], *kind,
"DerefStore: TypedField field_kinds[{}] = {:?} drift vs \
RefTarget captured kind {:?} — ADR-006 §2.7.13 / Q14",
field_idx, receiver.field_kinds[field_idx], kind,
);
// Pre-read the prior bits for the write-barrier helper.
let prior_bits = receiver.slots[field_idx].raw();
write_barrier_slot(prior_bits, val_bits);
// SAFETY: single-threaded VM; refs cannot escape across
// task boundaries (§3.1); no aliased `&mut ValueSlot`
// outstanding (this is the only mutator path in the VM
// for typed-object slots, gated by Q14 dispatch); kind
// invariance debug_asserted above. Per
// `TypedObjectStorage::write_slot_in_place` contract,
// returns the same `prior_bits` we just read.
let _returned_prior = unsafe {
receiver.write_slot_in_place(field_idx, val_bits)
};
debug_assert_eq!(
_returned_prior, prior_bits,
"DerefStore: write_slot_in_place prior_bits mismatch — \
concurrent write detected? ADR-006 §2.7.13 / Q14",
);
// Release the prior occupant's share via the kind-aware
// dispatch table (§2.7.7 WB2.4).
crate::executor::vm_impl::stack::drop_with_kind(
prior_bits, *kind,
);
Ok(())
}
// V3-S5 ckpt-5: `RefTarget::TypedIndex` arm deleted (variant
// retired at ckpt-4 lockstep with TypedArrayData enum +
// `write_index_in_place` API). The match is now exhaustive on
// Local | ModuleBinding | TypedField; the write-via-index
// path surface-and-stops at `op_set_index_ref` (one level
// up) per V3-S5 ckpt-5.
}
}
/// `StoreModuleBinding { idx }` — Wave-γ G-module-bindings-kind:
/// pop kinded source and write via `module_binding_write_kinded`,
/// which releases the prior slot's share via `drop_with_kind`.
pub(in crate::executor) fn op_store_module_binding(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (new_bits, new_kind) = self.pop_kinded()?;
record_heap_write();
// module_binding_write_kinded grows the parallel tracks if
// necessary and runs drop_with_kind on the prior occupant.
self.module_binding_write_kinded(idx as usize, new_bits, new_kind);
Ok(())
}
/// `StoreModuleBindingTyped { idx, width }` — pop kinded numeric
/// source, width-truncate, write via the kinded module-binding
/// API.
pub(in crate::executor) fn op_store_module_binding_typed(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::TypedModuleBinding(idx, width)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, src_kind) = self.pop_kinded()?;
let truncated_bits = if let Some(int_w) = width.to_int_width() {
int_w.truncate(src_bits as i64) as u64
} else {
src_bits
};
record_heap_write();
self.module_binding_write_kinded(idx as usize, truncated_bits, src_kind);
Ok(())
}
fn op_load_module_binding_i64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, _kind) = self.module_binding_read_kinded_raw(idx as usize);
self.push_kinded(bits, NativeKind::Int64)
}
fn op_load_module_binding_u64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, _kind) = self.module_binding_read_kinded_raw(idx as usize);
self.push_kinded(bits, NativeKind::UInt64)
}
fn op_load_module_binding_f64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, _kind) = self.module_binding_read_kinded_raw(idx as usize);
self.push_kinded(bits, NativeKind::Float64)
}
fn op_load_module_binding_i32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, _kind) = self.module_binding_read_kinded_raw(idx as usize);
let value = bits as i32 as i64 as u64;
self.push_kinded(value, NativeKind::Int32)
}
fn op_load_module_binding_u32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, _kind) = self.module_binding_read_kinded_raw(idx as usize);
let value = bits as u32 as u64;
self.push_kinded(value, NativeKind::UInt32)
}
fn op_load_module_binding_i16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, _kind) = self.module_binding_read_kinded_raw(idx as usize);
let value = bits as i16 as i64 as u64;
self.push_kinded(value, NativeKind::Int16)
}
fn op_load_module_binding_u16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, _kind) = self.module_binding_read_kinded_raw(idx as usize);
let value = bits as u16 as u64;
self.push_kinded(value, NativeKind::UInt16)
}
fn op_load_module_binding_i8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, _kind) = self.module_binding_read_kinded_raw(idx as usize);
let value = bits as i8 as i64 as u64;
self.push_kinded(value, NativeKind::Int8)
}
fn op_load_module_binding_u8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, _kind) = self.module_binding_read_kinded_raw(idx as usize);
let value = bits as u8 as u64;
self.push_kinded(value, NativeKind::UInt8)
}
fn op_load_module_binding_bool(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, _kind) = self.module_binding_read_kinded_raw(idx as usize);
let value = ((bits as u8) != 0) as u64;
self.push_kinded(value, NativeKind::Bool)
}
/// `LoadModuleBindingPtr { idx }` — Wave-γ G-module-bindings-kind:
/// the parallel kind track now classifies the binding's
/// heap-bearing arm; read kinded bits + bump the share via
/// `clone_with_kind`.
fn op_load_module_binding_ptr(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (bits, kind) = self.module_binding_read_kinded_raw(idx as usize);
// WB2.4 retain-on-read: the binding slot keeps its share, the
// pushed slot needs an independent share. The kind track
// classifies the heap arm — `clone_with_kind` runs the matching
// `Arc<T>::increment_strong_count` for `Ptr(HeapKind::*)` /
// `String`, no-op for inline scalars.
crate::executor::vm_impl::stack::clone_with_kind(bits, kind);
self.push_kinded(bits, kind)
}
fn op_store_module_binding_i64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (value, _src_kind) = self.pop_kinded()?;
record_heap_write();
self.module_binding_write_kinded(idx as usize, value, NativeKind::Int64);
Ok(())
}
fn op_store_module_binding_u64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (value, _src_kind) = self.pop_kinded()?;
record_heap_write();
self.module_binding_write_kinded(idx as usize, value, NativeKind::UInt64);
Ok(())
}
fn op_store_module_binding_f64(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (value, _src_kind) = self.pop_kinded()?;
record_heap_write();
self.module_binding_write_kinded(idx as usize, value, NativeKind::Float64);
Ok(())
}
fn op_store_module_binding_i32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as i32 as i64 as u64;
record_heap_write();
self.module_binding_write_kinded(idx as usize, value, NativeKind::Int32);
Ok(())
}
fn op_store_module_binding_u32(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as u32 as u64;
record_heap_write();
self.module_binding_write_kinded(idx as usize, value, NativeKind::UInt32);
Ok(())
}
fn op_store_module_binding_i16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as i16 as i64 as u64;
record_heap_write();
self.module_binding_write_kinded(idx as usize, value, NativeKind::Int16);
Ok(())
}
fn op_store_module_binding_u16(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as u16 as u64;
record_heap_write();
self.module_binding_write_kinded(idx as usize, value, NativeKind::UInt16);
Ok(())
}
fn op_store_module_binding_i8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as i8 as i64 as u64;
record_heap_write();
self.module_binding_write_kinded(idx as usize, value, NativeKind::Int8);
Ok(())
}
fn op_store_module_binding_u8(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = src_bits as u8 as u64;
record_heap_write();
self.module_binding_write_kinded(idx as usize, value, NativeKind::UInt8);
Ok(())
}
fn op_store_module_binding_bool(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (src_bits, _src_kind) = self.pop_kinded()?;
let value = (src_bits != 0) as u64;
record_heap_write();
self.module_binding_write_kinded(idx as usize, value, NativeKind::Bool);
Ok(())
}
/// `StoreModuleBindingPtr { idx }` — Wave-γ G-module-bindings-kind:
/// pop kinded heap source and install via the kinded module-
/// binding API; the prior occupant's share is released via
/// `drop_with_kind` using the prior kind track entry.
fn op_store_module_binding_ptr(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::ModuleBinding(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let (new_bits, src_kind) = self.pop_kinded()?;
record_heap_write();
// The source kind classifies the heap arm; module_binding_write_kinded
// routes prior-occupant release through drop_with_kind with the
// prior kind track entry.
self.module_binding_write_kinded(idx as usize, new_bits, src_kind);
Ok(())
}
// ─────────────────────────────────────────────────────────────────────
// V1.1B ownership-aware local opcodes (MoveLocal / CloneLocal / DropLocal)
// ─────────────────────────────────────────────────────────────────────
/// `MoveLocal(idx)` — transfer ownership of the local slot onto
/// the stack. Reads the slot via `stack_take_kinded` (which clears
/// the slot to the zero/Bool sentinel without releasing) and
/// pushes onto the stack.
pub(in crate::executor) fn op_move_local(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"MoveLocal slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let (bits, kind) = self.stack_take_kinded(slot);
self.push_kinded(bits, kind)
}
/// `CloneLocal(idx)` — clone the local slot's value via
/// `clone_with_kind`, leaving the slot live with its own share.
pub(in crate::executor) fn op_clone_local(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"CloneLocal slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let (bits, kind) = self.stack_read_kinded_raw(slot);
crate::executor::vm_impl::stack::clone_with_kind(bits, kind);
self.push_kinded(bits, kind)
}
/// `DropLocal(idx)` — release the local slot's value via
/// `drop_with_kind` and zero the slot.
pub(in crate::executor) fn op_drop_local(
&mut self,
instruction: &Instruction,
) -> Result<(), VMError> {
let Some(Operand::Local(idx)) = instruction.operand else {
return Err(VMError::InvalidOperand);
};
let bp = self.current_locals_base();
let slot = bp + idx as usize;
debug_assert!(
slot < self.stack.len(),
"DropLocal slot {} out of bounds (stack len {})",
slot,
self.stack.len()
);
let (bits, kind) = self.stack_take_kinded(slot);
crate::executor::vm_impl::stack::drop_with_kind(bits, kind);
Ok(())
}
}
// ────────────────────────────────────────────────────────────────────────
// V3-S5 ckpt-5 (2026-05-15): `typed_array_element_kind` +
// `typed_array_read_index_raw` helpers DELETED. Both consumed
// `Arc<TypedArrayData>` (deleted at ckpt-1) and dispatched through the
// per-variant grid (`I64` / `F64` / `Bool` / `I8` / `I16` / `I32` / `U8`
// / `U16` / `U32` / `U64` / `F32` / `String` / `Decimal` / `BigInt` /
// `Char` / `TypedObject`) which is gone wholesale per W12-typed-array-
// data-deletion-audit §3.5 + ADR-006 §2.7.24 Q25.A SUPERSEDED.
//
// `op_make_index_ref` / `op_set_index_ref` (the only callers) surface-
// and-stop at V3-S5 ckpt-5 per the multi-session-chain pattern step 2.
// Per-element-kind v2-raw `TypedArray<T>` read/write helpers land at
// ckpt-6 STRICT close per the per-element-kind RefTarget variant target.
// ────────────────────────────────────────────────────────────────────────
// ────────────────────────────────────────────────────────────────────────
// Test module — gated until the deleted ValueWord / ValueWordExt ABI
// is replaced (Phase-2c host-API rebuild per ADR-006 §2.7.4).
//
// The pre-deletion tests built `BytecodeProgram`s and asserted on
// `ValueWord` accessors (`as_i64()`, `as_f64()`, `as_bool()`,
// `as_string()`, `from_i64()`, etc.). All of those types are deleted
// per CLAUDE.md "Forbidden code" #1 (the strict-typing bulldozer
// removed `ValueWord` entirely). The replacement test surface uses
// `KindedSlot` (the §2.7 runtime-tier carrier) plus the per-slot
// `NativeKind` parallel track — a Phase-2c test-harness rebuild that
// is out of B6 territory.
//
// The whole module is gated so the file compiles cleanly without
// reintroducing any deleted-ABI imports. The tests themselves are
// preserved in git history at `c785174` (Wave-β B6 round-1) for
// reference when the host-API rebuild lands.
// ────────────────────────────────────────────────────────────────────────
#[cfg(any())]
mod tests {
// SURFACE (ADR-006 §2.7.4 / Phase-2c): the pre-deletion test body
// used the deleted `ValueWord` / `ValueWordExt` accessors plus the
// deleted ValueWord-shape stack shims (the bulldozer removed both
// alongside `ValueWord` itself per CLAUDE.md Forbidden Patterns
// §"Forbidden code" #1, and §2.7.7's Forbidden #6 last bullet
// refused the shim layer once `ValueWord` was gone). Restoring
// this test module requires the Phase-2c
// host-API rebuild (the runtime-tier `KindedSlot` carrier needs
// surface-equivalent assertions for `as_i64()` / `as_f64()` /
// `as_bool()` / `as_string_arc()` etc.). Tracked as Phase-2c
// test-harness work; out of B6 territory.
}
// ────────────────────────────────────────────────────────────────────────
// R5c-2-β1 typedfield-doublefree regression suite (2026-05-20)
// ────────────────────────────────────────────────────────────────────────
//
// `RefTarget::TypedField.receiver` was a stale legacy `Arc<TypedObjectStorage>`
// carrier while production allocates `TypedObjectStorage` via the v2-raw
// `_new` path (`op_new_typed_object`) — the slot bits are the RAW struct
// pointer with `HeapHeader` at offset 0. The pre-fix
// `resolve_typed_object_receiver` ran `Arc::increment_strong_count` /
// `Arc::from_raw`, which treat the pointer as `&ArcInner.data` (allocation
// start = `ptr - 16`) — bumping/deallocating 16 bytes before the real
// allocation → intermittent `free(): double free detected` SIGABRT.
//
// The fix migrates the carrier to the v2-raw `TypedObjectPtr` (ADR-006
// §2.3) and retains via `v2_retain` against the on-header refcount. These
// tests pin the retain/release balance and the `&mut` typed-field-ref
// round-trip.
#[cfg(test)]
mod typedfield_ref_tests {
use crate::executor::{VMConfig, VirtualMachine};
use shape_value::heap_value::TypedObjectStorage;
use shape_value::v2::refcount::v2_get_refcount;
use shape_value::{HeapKind, NativeKind, RefTarget, ValueSlot};
use std::sync::Arc;
/// Build a fresh single-field `TypedObjectStorage` via the v2-raw
/// `_new` path (the production allocator) with one i64 field. Returns
/// the raw pointer (refcount = 1).
fn make_box(value: i64) -> *mut TypedObjectStorage {
let slots = vec![ValueSlot::from_raw(value as u64)];
TypedObjectStorage::_new(
7, // arbitrary schema_id
slots.into_boxed_slice(),
0, // heap_mask: the i64 field is an inline scalar
Arc::from(vec![NativeKind::Int64].into_boxed_slice()),
)
}
/// Install a `_new`-allocated TypedObject pointer into module binding
/// `idx`, transferring one share to the binding. `module_binding_write_
/// kinded` grows the parallel tracks and runs `drop_with_kind` on the
/// (zero) prior occupant. Returns a base `RefTarget::ModuleBinding`.
fn install_module_box(
vm: &mut VirtualMachine,
idx: u32,
ptr: *const TypedObjectStorage,
) -> RefTarget {
vm.module_binding_write_kinded(
idx as usize,
ptr as u64,
NativeKind::Ptr(HeapKind::TypedObject),
);
RefTarget::ModuleBinding {
binding_idx: idx,
kind: NativeKind::Ptr(HeapKind::TypedObject),
}
}
/// `resolve_typed_object_receiver` bumps the on-header refcount exactly
/// once and hands back a `TypedObjectPtr` whose Drop retires exactly
/// that share — no leak, no double-free. Pre-fix, the
/// `Arc::increment_strong_count` path bumped 16 bytes before the real
/// `_new` allocation, corrupting an adjacent malloc chunk.
#[test]
fn typed_field_receiver_retain_release_balances_refcount() {
let mut vm = VirtualMachine::new(VMConfig::default());
let ptr = make_box(9);
// Refcount = 1 (the `_new` allocation's own share).
assert_eq!(unsafe { v2_get_refcount(&(*ptr).header) }, 1);
// Installing it into the module binding transfers that share to
// the binding — refcount stays 1.
let base_rt = install_module_box(&mut vm, 0, ptr);
assert_eq!(unsafe { v2_get_refcount(&(*ptr).header) }, 1);
{
let receiver = vm.resolve_typed_object_receiver(&base_rt).unwrap();
// The resolve bumped the refcount to 2 (binding share + the
// receiver's independent share).
assert_eq!(
unsafe { v2_get_refcount(&(*ptr).header) },
2,
"resolve_typed_object_receiver must bump refcount exactly once"
);
// Reading a field through the receiver works via Deref.
assert_eq!(receiver.slots[0].raw(), 9u64);
// `receiver` drops here — TypedObjectPtr::Drop retires its share.
}
assert_eq!(
unsafe { v2_get_refcount(&(*ptr).header) },
1,
"TypedObjectPtr::Drop must retire exactly the resolve share"
);
// Retire the binding's share via the kind-aware drop dispatch —
// refcount hits 0 and the allocation is freed.
vm.module_binding_write_kinded(0, 0u64, NativeKind::Bool);
}
/// Constructing a `RefTarget::TypedField` via `MakeFieldRef`-shape
/// resolution and then dropping it balances the refcount — the
/// `Arc<RefTarget>` Drop chains through `TypedObjectPtr::Drop`.
#[test]
fn typed_field_reftarget_construct_drop_balances_refcount() {
let mut vm = VirtualMachine::new(VMConfig::default());
let ptr = make_box(40);
let base_rt = install_module_box(&mut vm, 0, ptr);
assert_eq!(unsafe { v2_get_refcount(&(*ptr).header) }, 1);
// Resolve the receiver and build the projected TypedField ref —
// exactly the shape `op_make_field_ref` produces.
let receiver = vm.resolve_typed_object_receiver(&base_rt).unwrap();
assert_eq!(unsafe { v2_get_refcount(&(*ptr).header) }, 2);
let projected = Arc::new(RefTarget::TypedField {
receiver,
field_offset: 0,
kind: NativeKind::Int64,
});
// Still 2 — moving the receiver into the variant transfers the
// share, no new bump.
assert_eq!(unsafe { v2_get_refcount(&(*ptr).header) }, 2);
// Dropping the `Arc<RefTarget>` chains: RefTarget::TypedField drop
// → TypedObjectPtr::Drop → release_elem.
drop(projected);
assert_eq!(
unsafe { v2_get_refcount(&(*ptr).header) },
1,
"Arc<RefTarget::TypedField> Drop must retire the receiver share"
);
vm.module_binding_write_kinded(0, 0u64, NativeKind::Bool);
}
/// `&mut`-typed-field-ref round-trip: read the projected slot, write a
/// new value through it, read back. Mirrors the `DerefLoad` /
/// `DerefStore` op pair against a `RefTarget::TypedField`.
#[test]
fn typed_field_ref_read_write_round_trip() {
let mut vm = VirtualMachine::new(VMConfig::default());
let ptr = make_box(9);
let base_rt = install_module_box(&mut vm, 0, ptr);
let receiver = vm.resolve_typed_object_receiver(&base_rt).unwrap();
let projected = RefTarget::TypedField {
receiver,
field_offset: 0,
kind: NativeKind::Int64,
};
// DerefLoad: the projected slot reads back the constructed value.
let (bits, kind) = vm.read_ref_target(&projected).unwrap();
assert_eq!(bits, 9u64);
assert_eq!(kind, NativeKind::Int64);
// DerefStore: write a new value through the ref.
vm.write_ref_target(&projected, 10u64, NativeKind::Int64)
.unwrap();
// DerefLoad again: the write landed.
let (bits_after, _) = vm.read_ref_target(&projected).unwrap();
assert_eq!(
bits_after, 10u64,
"&mut typed-field-ref write must be observable through the ref"
);
// The write is also visible on the underlying storage.
assert_eq!(unsafe { (*ptr).slots[0].raw() }, 10u64);
drop(projected);
vm.module_binding_write_kinded(0, 0u64, NativeKind::Bool);
}
/// Resolving a non-TypedObject base surfaces an error WITHOUT
/// corrupting the allocation (the pre-fix path could bump a
/// 16-byte-misaligned address before erroring).
#[test]
fn typed_field_non_typed_object_base_errors_cleanly() {
let mut vm = VirtualMachine::new(VMConfig::default());
let bad_rt = RefTarget::ModuleBinding {
binding_idx: 0,
kind: NativeKind::Int64, // not a TypedObject
};
let result = vm.resolve_typed_object_receiver(&bad_rt);
assert!(
result.is_err(),
"non-TypedObject base must surface an error, not fabricate a receiver"
);
}
}