tycho-vm 0.3.6

TON-compatible VM for the Tycho node.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
use tycho_types::models::SignatureDomain;
use tycho_types::prelude::*;
use tycho_vm_proc::vm_module;

use crate::cont::{ArgContExt, ControlData, ControlRegs, OrdCont, PushIntCont, RcCont};
#[cfg(feature = "dump")]
use crate::dispatch::DumpOutput;
use crate::error::VmResult;
#[cfg(feature = "dump")]
use crate::error::{DumpError, DumpResult};
use crate::gas::{GasConsumer, GasConsumerDeriveParams, GasParams};
use crate::instr::codepage0;
use crate::saferc::SafeRc;
use crate::stack::{Stack, StackValueType};
use crate::state::{EXC_QUIT, ParentVmState, QUIT0, QUIT1, QUIT11, SaveCr, VmState};

pub struct ContOps;

#[vm_module]
impl ContOps {
    // === Jump ops ===

    #[op(code = "d8", fmt = "EXECUTE")]
    fn exec_execute(st: &mut VmState) -> VmResult<i32> {
        let cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        st.call(cont)
    }

    #[op(code = "d9", fmt = "JMPX")]
    fn exec_jmpx(st: &mut VmState) -> VmResult<i32> {
        let cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        st.jump(cont)
    }

    #[op(code = "dapr", fmt = "CALLXARGS {p},{r}")]
    fn exec_callx_args(st: &mut VmState, p: u32, r: u32) -> VmResult<i32> {
        let cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        st.call_ext(cont, Some(p as _), Some(r as _))
    }

    #[op(code = "db0p", fmt = "CALLXARGS {p},-1")]
    fn exec_callx_args_p(st: &mut VmState, p: u32) -> VmResult<i32> {
        let cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        st.call_ext(cont, Some(p as _), None)
    }

    #[op(code = "db1p", fmt = "JMPXARGS {p}")]
    fn exec_jmpx_args(st: &mut VmState, p: u32) -> VmResult<i32> {
        let cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        st.jump_ext(cont, Some(p as _))
    }

    #[op(code = "db2r", fmt = "RETARGS {r}")]
    fn exec_ret_args(st: &mut VmState, r: u32) -> VmResult<i32> {
        st.ret_ext(Some(r as _))
    }

    #[op(code = "db30", fmt = "RET")]
    fn exec_ret(st: &mut VmState) -> VmResult<i32> {
        st.ret()
    }

    #[op(code = "db31", fmt = "RETALT")]
    fn exec_ret_alt(st: &mut VmState) -> VmResult<i32> {
        st.ret_alt()
    }

    #[op(code = "db32", fmt = "RETBOOL")]
    fn exec_ret_bool(st: &mut VmState) -> VmResult<i32> {
        if ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) {
            st.ret()
        } else {
            st.ret_alt()
        }
    }

    #[op(code = "db34", fmt = "CALLCC")]
    fn exec_callcc(st: &mut VmState) -> VmResult<i32> {
        let cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        let cc = ok!(st.extract_cc(SaveCr::C0_C1, None, None));
        ok!(SafeRc::make_mut(&mut st.stack).push_raw(cc));
        st.jump(cont)
    }

    #[op(code = "db35", fmt = "JMPXDATA")]
    fn exec_jmpx_data(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let cont = ok!(stack.pop_cont());
        ok!(stack.push(st.code.clone()));
        st.jump(cont)
    }

    #[op(code = "db36pr", fmt = "CALLCCARGS {p},{r}", args(r = ((args as i32 + 1) & 0xf) - 1))]
    fn exec_callcc_args(st: &mut VmState, p: u32, r: i32) -> VmResult<i32> {
        let cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        let cc = ok!(st.extract_cc(SaveCr::C0_C1, Some(p as _), (r >= 0).then_some(r as _)));
        ok!(SafeRc::make_mut(&mut st.stack).push_raw(cc));
        st.jump(cont)
    }

    #[op(code = "db38", fmt = "CALLXVARARGS")]
    fn exec_callx_varargs(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let r = ok!(stack.pop_smallint_signed_range(-1, 254));
        let p = ok!(stack.pop_smallint_signed_range(-1, 254));
        let cont = ok!(stack.pop_cont());
        st.call_ext(cont, (p >= 0).then_some(p as _), (r >= 0).then_some(r as _))
    }

    #[op(code = "db39", fmt = "RETVARARGS")]
    fn exec_ret_varargs(st: &mut VmState) -> VmResult<i32> {
        let r = ok!(SafeRc::make_mut(&mut st.stack).pop_smallint_signed_range(-1, 254));
        st.ret_ext((r >= 0).then_some(r as _))
    }

    #[op(code = "db3a", fmt = "JMPXVARARGS")]
    fn exec_jmpx_varargs(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let p = ok!(stack.pop_smallint_signed_range(-1, 254));
        let cont = ok!(stack.pop_cont());
        st.jump_ext(cont, (p >= 0).then_some(p as _))
    }

    #[op(code = "db3b", fmt = "CALLCCVARARGS")]
    fn exec_callcc_varargs(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let r = ok!(stack.pop_smallint_signed_range(-1, 254));
        let p = ok!(stack.pop_smallint_signed_range(-1, 254));
        let cont = ok!(stack.pop_cont());
        let cc = ok!(st.extract_cc(
            SaveCr::C0_C1,
            (p >= 0).then_some(p as _),
            (r >= 0).then_some(r as _)
        ));
        ok!(SafeRc::make_mut(&mut st.stack).push_raw(cc));
        st.jump(cont)
    }

    #[op_ext(code = 0xdb3c, code_bits = 16, arg_bits = 0, dump_with = dump_callref)]
    fn exec_callref(st: &mut VmState, _: u32, bits: u16) -> VmResult<i32> {
        let cont = ok!(exec_ref_prefix(st, bits, "CALLREF"));
        st.call(cont)
    }

    #[cfg(feature = "dump")]
    fn dump_callref(
        code: &mut CellSlice<'_>,
        _: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        dump_ref_prefix(code, bits, "CALLREF", f)
    }

    #[op_ext(code = 0xdb3d, code_bits = 16, arg_bits = 0, dump_with = dump_jmpref)]
    fn exec_jmpref(st: &mut VmState, _: u32, bits: u16) -> VmResult<i32> {
        let cont = ok!(exec_ref_prefix(st, bits, "JMPREF"));
        st.jump(cont)
    }

    #[cfg(feature = "dump")]
    fn dump_jmpref(
        code: &mut CellSlice<'_>,
        _: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        dump_ref_prefix(code, bits, "JMPREF", f)
    }

    #[op_ext(code = 0xdb3e, code_bits = 16, arg_bits = 0, dump_with = dump_jmpref_data)]
    fn exec_jmpref_data(st: &mut VmState, _: u32, bits: u16) -> VmResult<i32> {
        let cont = ok!(exec_ref_prefix(st, bits, "JMPREFDATA"));
        ok!(SafeRc::make_mut(&mut st.stack).push(st.code.clone()));
        st.jump(cont)
    }

    #[cfg(feature = "dump")]
    fn dump_jmpref_data(
        code: &mut CellSlice<'_>,
        _: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        dump_ref_prefix(code, bits, "JMPREFDATA", f)
    }

    #[op(code = "db3f", fmt = "RETDATA")]
    fn exec_ret_data(st: &mut VmState) -> VmResult<i32> {
        ok!(SafeRc::make_mut(&mut st.stack).push(st.code.clone()));
        st.ret()
    }

    #[op(code = "db4xxx", fmt = "RUNVM {x}")]
    fn exec_runvm(st: &mut VmState, x: u32) -> VmResult<i32> {
        exec_runvm_common(st, RunVmArgs(x))
    }

    #[op(code = "db50", fmt = "RUNVMX")]
    fn exec_runvmx(st: &mut VmState) -> VmResult<i32> {
        let x = ok!(SafeRc::make_mut(&mut st.stack).pop_smallint_range(0, 0xfff));
        exec_runvm_common(st, RunVmArgs(x))
    }

    // === Conditions and loops ===

    #[op(code = "dc", fmt = "IFRET")]
    fn exec_ifret(st: &mut VmState) -> VmResult<i32> {
        if ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) {
            st.ret()
        } else {
            Ok(0)
        }
    }

    #[op(code = "dd", fmt = "IFNOTRET")]
    fn exec_ifnotret(st: &mut VmState) -> VmResult<i32> {
        if ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) {
            Ok(0)
        } else {
            st.ret()
        }
    }

    #[op(code = "de", fmt = "IF")]
    fn exec_if(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let cont = ok!(stack.pop_cont());
        if ok!(stack.pop_bool()) {
            st.call(cont)
        } else {
            Ok(0)
        }
    }

    #[op(code = "df", fmt = "IFNOT")]
    fn exec_ifnot(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let cont = ok!(stack.pop_cont());
        if ok!(stack.pop_bool()) {
            Ok(0)
        } else {
            st.call(cont)
        }
    }

    #[op(code = "e0", fmt = "IFJMP")]
    fn exec_if_jmp(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let cont = ok!(stack.pop_cont());
        if ok!(stack.pop_bool()) {
            st.jump(cont)
        } else {
            Ok(0)
        }
    }

    #[op(code = "e1", fmt = "IFNOTJMP")]
    fn exec_ifnot_jmp(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let cont = ok!(stack.pop_cont());
        if ok!(stack.pop_bool()) {
            Ok(0)
        } else {
            st.jump(cont)
        }
    }

    #[op(code = "e2", fmt = "IFELSE")]
    fn exec_if_else(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let cont = {
            let cont0 = ok!(stack.pop_cont());
            let cont1 = ok!(stack.pop_cont());
            match ok!(stack.pop_bool()) {
                false => cont0,
                true => cont1,
            }
        };
        st.call(cont)
    }

    #[op_ext(code = 0xe300, code_bits = 16, arg_bits = 0, dump_with = dump_ifref)]
    fn exec_ifref(st: &mut VmState, _: u32, bits: u16) -> VmResult<i32> {
        let cell = ok!(exec_cell_prefix(st, bits, "IFREF"));
        if ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) {
            let cont = ok!(st.ref_to_cont(cell));
            st.call(cont)
        } else {
            Ok(0)
        }
    }

    #[cfg(feature = "dump")]
    fn dump_ifref(
        code: &mut CellSlice<'_>,
        _: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        dump_ref_prefix(code, bits, "IFREF", f)
    }

    #[op_ext(code = 0xe301, code_bits = 16, arg_bits = 0, dump_with = dump_ifnotref)]
    fn exec_ifnotref(st: &mut VmState, _: u32, bits: u16) -> VmResult<i32> {
        let cell = ok!(exec_cell_prefix(st, bits, "IFNOTREF"));
        if ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) {
            Ok(0)
        } else {
            let cont = ok!(st.ref_to_cont(cell));
            st.call(cont)
        }
    }

    #[cfg(feature = "dump")]
    fn dump_ifnotref(
        code: &mut CellSlice<'_>,
        _: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        dump_ref_prefix(code, bits, "IFNOTREF", f)
    }

    #[op_ext(code = 0xe302, code_bits = 16, arg_bits = 0, dump_with = dump_ifjmpref)]
    fn exec_ifjmpref(st: &mut VmState, _: u32, bits: u16) -> VmResult<i32> {
        let cell = ok!(exec_cell_prefix(st, bits, "IFJMPREF"));
        if ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) {
            let cont = ok!(st.ref_to_cont(cell));
            st.jump(cont)
        } else {
            Ok(0)
        }
    }

    #[cfg(feature = "dump")]
    fn dump_ifjmpref(
        code: &mut CellSlice<'_>,
        _: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        dump_ref_prefix(code, bits, "IFJMPREF", f)
    }

    #[op_ext(code = 0xe303, code_bits = 16, arg_bits = 0, dump_with = dump_ifnotjmpref)]
    fn exec_ifnotjmpref(st: &mut VmState, _: u32, bits: u16) -> VmResult<i32> {
        let cell = ok!(exec_cell_prefix(st, bits, "IFNOTJMPREF"));
        if ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) {
            Ok(0)
        } else {
            let cont = ok!(st.ref_to_cont(cell));
            st.jump(cont)
        }
    }

    #[cfg(feature = "dump")]
    fn dump_ifnotjmpref(
        code: &mut CellSlice<'_>,
        _: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        dump_ref_prefix(code, bits, "IFNOTJMPREF", f)
    }

    #[op(code = "e304", fmt = "CONDSEL")]
    fn exec_condsel(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let y = ok!(stack.pop());
        let x = ok!(stack.pop());
        let cond = ok!(stack.pop_bool());
        ok!(stack.push_raw(match cond {
            true => x,
            false => y,
        }));
        Ok(0)
    }

    #[op(code = "e305", fmt = "CONDSELCHK")]
    fn exec_condsel_chk(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let y = ok!(stack.pop());
        let x = ok!(stack.pop());
        vm_ensure!(x.raw_ty() == y.raw_ty(), InvalidType {
            expected: x.raw_ty(),
            actual: y.raw_ty(),
        });
        let cond = ok!(stack.pop_bool());
        ok!(stack.push_raw(match cond {
            true => x,
            false => y,
        }));
        Ok(0)
    }

    #[op(code = "e308", fmt = "IFRETALT")]
    fn exec_ifretalt(st: &mut VmState) -> VmResult<i32> {
        if ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) {
            st.ret_alt()
        } else {
            Ok(0)
        }
    }

    #[op(code = "e309", fmt = "IFNOTRETALT")]
    fn exec_ifnotretalt(st: &mut VmState) -> VmResult<i32> {
        if ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) {
            Ok(0)
        } else {
            st.ret_alt()
        }
    }

    #[op_ext(code = 0xe30d, code_bits = 16, arg_bits = 0, dump_with = dump_ifrefelse)]
    fn exec_ifrefelse(st: &mut VmState, _: u32, bits: u16) -> VmResult<i32> {
        exec_ifelse_ref_impl(st, bits, true)
    }

    #[cfg(feature = "dump")]
    fn dump_ifrefelse(
        code: &mut CellSlice<'_>,
        _: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        dump_ref_prefix(code, bits, "IFREFELSE", f)
    }

    #[op_ext(code = 0xe30e, code_bits = 16, arg_bits = 0, dump_with = dump_ifelseref)]
    fn exec_ifelseref(st: &mut VmState, _: u32, bits: u16) -> VmResult<i32> {
        exec_ifelse_ref_impl(st, bits, false)
    }

    #[cfg(feature = "dump")]
    fn dump_ifelseref(
        code: &mut CellSlice<'_>,
        _: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        dump_ref_prefix(code, bits, "IFELSEREF", f)
    }

    #[op_ext(code = 0xe30f, code_bits = 16, arg_bits = 0, dump_with = dump_ifref_elseref)]
    fn exec_ifref_elseref(st: &mut VmState, _: u32, bits: u16) -> VmResult<i32> {
        let cell = {
            let code = &mut st.code;
            vm_ensure!(code.range().has_remaining(bits, 2), InvalidOpcode);
            let ok = code.range_mut().skip_first(bits, 0).is_ok();
            debug_assert!(ok);

            let Some(cell1) = code.cell().reference_cloned(code.range().offset_refs()) else {
                vm_bail!(CellError(tycho_types::error::Error::CellUnderflow));
            };
            let ok = code.range_mut().skip_first(0, 1).is_ok();
            debug_assert!(ok);

            let Some(cell0) = code.cell().reference_cloned(code.range().offset_refs()) else {
                vm_bail!(CellError(tycho_types::error::Error::CellUnderflow));
            };
            let ok = code.range_mut().skip_first(0, 1).is_ok();
            debug_assert!(ok);

            vm_log_op!(
                "IFREFELSEREF ({}) ({})",
                cell1.repr_hash(),
                cell0.repr_hash()
            );

            match ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) {
                false => cell0,
                true => cell1,
            }
        };
        let cont = ok!(st.ref_to_cont(cell));
        st.call(cont)
    }

    #[cfg(feature = "dump")]
    fn dump_ifref_elseref(
        code: &mut CellSlice<'_>,
        _: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        if !code.has_remaining(bits, 2) {
            return Err(DumpError::InvalidOpcode);
        }
        code.skip_first(bits, 0)?;

        let cell1 = code.load_reference_cloned()?;
        let cell0 = code.load_reference_cloned()?;

        f.record_cont(cell1.clone())?;
        f.record_cont(cell0.clone())?;

        f.record_opcode(&format_args!(
            "IFREFELSEREF ({}) ({})",
            cell1.repr_hash(),
            cell0.repr_hash()
        ))
    }

    #[op(code = "e3$10nx#x", fmt = ("IF{}BITJMP {x}", if n { "N" } else { "" }))]
    fn exec_if_bit_jmp(st: &mut VmState, n: bool, x: u32) -> VmResult<i32> {
        let (cont, bit) = {
            let stack = SafeRc::make_mut(&mut st.stack);
            let cont = ok!(stack.pop_cont());
            let value = ok!(stack.pop_int());
            let bit = value.bit(x as _);
            ok!(stack.push_raw(value));
            (cont, bit)
        };

        if bit ^ n { st.jump(cont) } else { Ok(0) }
    }

    #[op_ext(code = 0xe3c0 >> 6, code_bits = 10, arg_bits = 0, dump_with = dump_if_bit_jmpref)]
    fn exec_if_bit_jmpref(st: &mut VmState, args: u32, bits: u16) -> VmResult<i32> {
        let code_range = st.code.range();
        vm_ensure!(code_range.has_remaining(bits, 1), InvalidOpcode);
        let ok = st.code.range_mut().skip_first(bits, 0).is_ok();
        debug_assert!(ok);

        let Some(cell) = st.code.cell().reference_cloned(code_range.offset_refs()) else {
            vm_bail!(CellError(tycho_types::error::Error::CellUnderflow));
        };
        let ok = st.code.range_mut().skip_first(0, 1).is_ok();
        debug_assert!(ok);

        let negate = (args & 0x20) != 0;
        let bit = args & 0x1f;
        vm_log_op!(
            "{}BITJMPREF {bit} ({})",
            if negate { "N" } else { "" },
            cell.repr_hash()
        );

        let bit = {
            let stack = SafeRc::make_mut(&mut st.stack);
            let value = ok!(stack.pop_int());
            let bit = value.bit(bit as _);
            ok!(stack.push_raw(value));
            bit
        };

        if bit ^ negate {
            let cont = ok!(st.ref_to_cont(cell));
            st.jump(cont)
        } else {
            Ok(0)
        }
    }

    #[cfg(feature = "dump")]
    fn dump_if_bit_jmpref(
        code: &mut CellSlice<'_>,
        args: u32,
        bits: u16,
        f: &mut dyn DumpOutput,
    ) -> DumpResult {
        if !code.has_remaining(bits, 1) {
            return Err(DumpError::InvalidOpcode);
        }
        code.skip_first(bits, 0)?;
        let cell = code.load_reference_cloned()?;

        let negate = (args & 0x20) != 0;
        let bit = args & 0x1f;

        f.record_cont(cell.clone())?;
        f.record_opcode(&format_args!(
            "{}BITJMPREF {bit} ({})",
            if negate { "N" } else { "" },
            cell.repr_hash()
        ))
    }

    #[op(code = "e4", fmt = "REPEAT", args(brk = false))]
    #[op(code = "e314", fmt = "REPEATBRK", args(brk = true))]
    fn exec_repeat(st: &mut VmState, brk: bool) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let body = ok!(stack.pop_cont());
        let n = ok!(stack.pop_smallint_signed_range(i32::MIN, i32::MAX));
        if n <= 0 {
            return Ok(0);
        }

        let cc = ok!(st.extract_cc(SaveCr::C0, None, None));
        let after = st.c1_envelope_if(brk, cc, true);
        st.repeat(body, after, n as _)
    }

    #[op(code = "e5", fmt = "REPEATEND", args(brk = false))]
    #[op(code = "e315", fmt = "REPEATENDBRK", args(brk = true))]
    fn exec_repeat_end(st: &mut VmState, brk: bool) -> VmResult<i32> {
        let n = ok!(SafeRc::make_mut(&mut st.stack).pop_smallint_signed_range(i32::MIN, i32::MAX));
        if n <= 0 {
            return st.ret();
        }
        let body = ok!(st.extract_cc(SaveCr::NONE, None, None));
        let Some(c0) = st.cr.c[0].clone() else {
            vm_bail!(InvalidOpcode);
        };
        let after = st.c1_envelope_if(brk, c0, true);
        st.repeat(body, after, n as _)
    }

    #[op(code = "e6", fmt = "UNTIL", args(brk = false))]
    #[op(code = "e316", fmt = "UNTILBRK", args(brk = true))]
    fn exec_until(st: &mut VmState, brk: bool) -> VmResult<i32> {
        let body = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        let cc = ok!(st.extract_cc(SaveCr::C0, None, None));
        let after = st.c1_envelope_if(brk, cc, true);
        st.until(body, after)
    }

    #[op(code = "e7", fmt = "UNTILEND", args(brk = false))]
    #[op(code = "e317", fmt = "UNTILENDBRK", args(brk = true))]
    fn exec_until_end(st: &mut VmState, brk: bool) -> VmResult<i32> {
        let body = ok!(st.extract_cc(SaveCr::NONE, None, None));
        let Some(c0) = st.cr.c[0].clone() else {
            vm_bail!(InvalidOpcode);
        };
        let after = st.c1_envelope_if(brk, c0, true);
        st.until(body, after)
    }

    #[op(code = "e8", fmt = "WHILE", args(brk = false))]
    #[op(code = "e318", fmt = "WHILEBRK", args(brk = true))]
    fn exec_while(st: &mut VmState, brk: bool) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let body = ok!(stack.pop_cont());
        let cond = ok!(stack.pop_cont());

        let cc = ok!(st.extract_cc(SaveCr::C0, None, None));
        let after = st.c1_envelope_if(brk, cc, true);
        st.loop_while(cond, body, after)
    }

    #[op(code = "e9", fmt = "WHILEEND", args(brk = false))]
    #[op(code = "e319", fmt = "WHILEENDBRK", args(brk = true))]
    fn exec_while_end(st: &mut VmState, brk: bool) -> VmResult<i32> {
        let cond = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        let body = ok!(st.extract_cc(SaveCr::NONE, None, None));
        let Some(c0) = st.cr.c[0].clone() else {
            vm_bail!(InvalidOpcode);
        };
        let after = st.c1_envelope_if(brk, c0, true);
        st.loop_while(cond, body, after)
    }

    #[op(code = "ea", fmt = "AGAIN", args(brk = false))]
    #[op(code = "e31a", fmt = "AGAINBRK", args(brk = true))]
    fn exec_again(st: &mut VmState, brk: bool) -> VmResult<i32> {
        if brk {
            let cc = ok!(st.extract_cc(SaveCr::C0_C1, None, None));
            st.cr.c[1] = Some(cc);
        }
        let body = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        st.again(body)
    }

    #[op(code = "eb", fmt = "AGAINEND", args(brk = false))]
    #[op(code = "e31b", fmt = "AGAINENDBRK", args(brk = true))]
    fn exec_again_end(st: &mut VmState, brk: bool) -> VmResult<i32> {
        if brk {
            st.c1_save_set();
        }
        let cc = ok!(st.extract_cc(SaveCr::NONE, None, None));
        st.again(cc)
    }

    // === Continuation change ===

    #[op(code = "ecrn", fmt = "SETCONTARGS {r},{n}", args(n = ((args as i32 + 1) & 0xf) - 1))]
    fn exec_setcontargs(st: &mut VmState, r: u32, n: i32) -> VmResult<i32> {
        ok!(exec_setcontargs_common(st, r, n));
        Ok(0)
    }

    #[op(code = "ed0p", fmt = "RETURNARGS {p}")]
    fn exec_return_args(st: &mut VmState, p: u32) -> VmResult<i32> {
        ok!(exec_return_args_common(st, p));
        Ok(0)
    }

    #[op(code = "ed10", fmt = "RETURNVARARGS")]
    fn exec_return_varargs(st: &mut VmState) -> VmResult<i32> {
        let count = ok!(SafeRc::make_mut(&mut st.stack).pop_smallint_range(0, 255));
        ok!(exec_return_args_common(st, count));
        Ok(0)
    }

    #[op(code = "ed11", fmt = "SETCONTVARARGS")]
    fn exec_setcont_varargs(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let more = ok!(stack.pop_smallint_signed_range(-1, 255));
        let copy = ok!(stack.pop_smallint_range(0, 255));
        ok!(exec_setcontargs_common(st, copy, more));
        Ok(0)
    }

    #[op(code = "ed12", fmt = "SETNUMVARARGS")]
    fn exec_setnum_varargs(st: &mut VmState) -> VmResult<i32> {
        let more = ok!(SafeRc::make_mut(&mut st.stack).pop_smallint_signed_range(-1, 255));
        ok!(exec_setcontargs_common(st, 0, more));
        Ok(0)
    }

    #[op(code = "ed1e", fmt = "BLESS")]
    fn exec_bless(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let code = ok!(stack.pop_cs());
        let cont = SafeRc::new(OrdCont::simple(SafeRc::unwrap_or_clone(code), st.cp.id()));
        ok!(stack.push_raw(cont));
        Ok(0)
    }

    #[op(code = "ed1f", fmt = "BLESSVARARGS")]
    fn exec_bless_varargs(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let more = ok!(stack.pop_smallint_signed_range(-1, 255));
        let copy = ok!(stack.pop_smallint_range(0, 255));
        ok!(exec_bless_args_common(st, copy, more));
        Ok(0)
    }

    #[op(code = "ed4i", fmt = "PUSH c{i}")]
    fn exec_push_ctr(st: &mut VmState, i: u32) -> VmResult<i32> {
        vm_ensure!(ControlRegs::is_valid_idx(i as _), InvalidOpcode);
        ok!(SafeRc::make_mut(&mut st.stack).push_opt_raw(st.cr.get_as_stack_value(i as _)));
        Ok(0)
    }

    #[op(code = "ed5i", fmt = "POP c{i}")]
    fn exec_pop_ctr(st: &mut VmState, i: u32) -> VmResult<i32> {
        vm_ensure!(ControlRegs::is_valid_idx(i as _), InvalidOpcode);
        let value = ok!(SafeRc::make_mut(&mut st.stack).pop());
        ok!(st.cr.set(i as _, value));
        Ok(0)
    }

    #[op(code = "ed6i", fmt = "SETCONTCTR c{i}")]
    fn exec_setcont_ctr(st: &mut VmState, i: u32) -> VmResult<i32> {
        vm_ensure!(ControlRegs::is_valid_idx(i as _), InvalidOpcode);
        let stack = SafeRc::make_mut(&mut st.stack);
        let mut cont = ok!(stack.pop_cont());
        let value = ok!(stack.pop());
        ok!(force_cdata(&mut cont).save.define(i as _, value));
        ok!(stack.push_raw(cont));
        Ok(0)
    }

    #[op(code = "ed7i", fmt = "SETRETCTR c{i}")]
    fn exec_setret_ctr(st: &mut VmState, i: u32) -> VmResult<i32> {
        vm_ensure!(ControlRegs::is_valid_idx(i as _), InvalidOpcode);
        let cont = st.cr.c[0].as_mut().expect("c0 should always be set");
        let value = ok!(SafeRc::make_mut(&mut st.stack).pop());
        ok!(force_cdata(cont).save.define(i as _, value));
        Ok(0)
    }

    #[op(code = "ed8i", fmt = "SETALTCTR c{i}")]
    fn exec_setalt_ctr(st: &mut VmState, i: u32) -> VmResult<i32> {
        vm_ensure!(ControlRegs::is_valid_idx(i as _), InvalidOpcode);
        // TODO: Check if c1 is always set
        let cont = st.cr.c[1].as_mut().expect("c1 should always be set");
        let value = ok!(SafeRc::make_mut(&mut st.stack).pop());
        ok!(force_cdata(cont).save.define(i as _, value));
        Ok(0)
    }

    #[op(code = "ed9i", fmt = "POPSAVE c{i}")]
    fn exec_popsave(st: &mut VmState, i: u32) -> VmResult<i32> {
        vm_ensure!(ControlRegs::is_valid_idx(i as _), InvalidOpcode);
        let stack = SafeRc::make_mut(&mut st.stack);
        let value = ok!(stack.pop());
        let mut c0 = st.cr.c[0].clone().expect("c0 should always be set");

        vm_ensure!(
            i > 0 || value.raw_ty() == StackValueType::Cont as u8,
            InvalidType {
                expected: StackValueType::Cont as _,
                actual: value.raw_ty(),
            }
        );

        let prev = st
            .cr
            .get_as_stack_value(i as _)
            .unwrap_or_else(Stack::make_null);

        // NOTE: Is it ok to ignore redefinition errors?
        force_cdata(&mut c0).save.define(i as _, prev).ok();

        // TODO: Check if the order of setting c0 and `cr.set(..)` really matters
        if i == 0 {
            st.cr.c[0] = Some(c0);
            ok!(st.cr.set(i as _, value));
        } else {
            ok!(st.cr.set(i as _, value));
            st.cr.c[0] = Some(c0);
        }

        Ok(0)
    }

    #[op(code = "edai", fmt = "SAVECTR c{i}")]
    fn exec_savectr(st: &mut VmState, i: u32) -> VmResult<i32> {
        vm_ensure!(ControlRegs::is_valid_idx(i as _), InvalidOpcode);

        let mut c0 = st.cr.c[0].clone().expect("c0 should always be set");

        let value = st
            .cr
            .get_as_stack_value(i as _)
            .unwrap_or_else(Stack::make_null);

        ok!(force_cdata(&mut c0).save.define(i as _, value));
        st.cr.c[0] = Some(c0);
        Ok(0)
    }

    #[op(code = "edbi", fmt = "SAVEALTCTR c{i}")]
    fn exec_savealt_ctr(st: &mut VmState, i: u32) -> VmResult<i32> {
        vm_ensure!(ControlRegs::is_valid_idx(i as _), InvalidOpcode);

        // TODO: Check if c1 is always set
        let mut c1 = st.cr.c[1].clone().expect("c1 should always be set");

        let value = st
            .cr
            .get_as_stack_value(i as _)
            .unwrap_or_else(Stack::make_null);

        ok!(force_cdata(&mut c1).save.define(i as _, value));
        st.cr.c[1] = Some(c1);
        Ok(0)
    }

    #[op(code = "edci", fmt = "SAVEBOTHCTR c{i}")]
    fn exec_saveboth_ctr(st: &mut VmState, i: u32) -> VmResult<i32> {
        vm_ensure!(ControlRegs::is_valid_idx(i as _), InvalidOpcode);

        let mut c0 = st.cr.c[0].clone().expect("c0 should always be set");
        let mut c1 = st.cr.c[1].clone().expect("c1 should always be set");

        let value = st
            .cr
            .get_as_stack_value(i as _)
            .unwrap_or_else(Stack::make_null);

        // NOTE: Is it ok to ignore redefinition errors?
        force_cdata(&mut c0).save.define(i as _, value.clone()).ok();
        force_cdata(&mut c1).save.define(i as _, value).ok();
        st.cr.c[0] = Some(c0);
        st.cr.c[1] = Some(c1);
        Ok(0)
    }

    #[op(code = "ede0", fmt = "PUSHCTRX")]
    fn exec_push_ctr_var(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let idx = ok!(stack.pop_smallint_range(0, 16)) as usize;
        let Some(value) = st.cr.get_as_stack_value(idx) else {
            vm_bail!(ControlRegisterOutOfRange(idx));
        };
        ok!(stack.push_raw(value));
        Ok(0)
    }

    #[op(code = "ede1", fmt = "POPCTRX")]
    fn exec_pop_ctr_var(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let idx = ok!(stack.pop_smallint_range(0, 16)) as usize;
        vm_ensure!(
            ControlRegs::is_valid_idx(idx),
            ControlRegisterOutOfRange(idx)
        );

        let value = ok!(stack.pop());
        ok!(st.cr.set(idx, value));
        Ok(0)
    }

    #[op(code = "ede2", fmt = "SETCONTCTRX")]
    fn exec_setcont_ctr_var(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let idx = ok!(stack.pop_smallint_range(0, 16)) as usize;
        vm_ensure!(
            ControlRegs::is_valid_idx(idx),
            ControlRegisterOutOfRange(idx)
        );
        let mut cont = ok!(stack.pop_cont());
        let value = ok!(stack.pop());
        ok!(force_cdata(&mut cont).save.define(idx, value));
        ok!(stack.push_raw(cont));
        Ok(0)
    }

    #[op(code = "ede3xx", fmt = ("SETCONTCTRMANY {}", args & 0xff), args(x = Some(args & 0xff)))]
    #[op(code = "ede4", fmt = "SETCONTCTRMANYX", args(x = None))]
    fn exec_setcont_ctr_many(st: &mut VmState, x: Option<u32>) -> VmResult<i32> {
        ok!(st.version.require_ton(9..));

        let stack = SafeRc::make_mut(&mut st.stack);
        let x = match x {
            Some(x) => x,
            None => ok!(stack.pop_smallint_range(0, 255)),
        };
        vm_ensure!(x & (1 << 6) == 0, ControlRegisterOutOfRange(6));

        let mut cont = ok!(stack.pop_cont());

        for i in 0..8 {
            if x & (1 << i) == 0 {
                continue;
            }

            let Some(st_value) = st.cr.get_as_stack_value(i) else {
                vm_bail!(InvalidType {
                    expected: StackValueType::Cont as _,
                    actual: StackValueType::Null as _
                })
            };
            ok!(force_cdata(&mut cont).save.define(i, st_value));
        }

        ok!(stack.push_raw(cont));
        Ok(0)
    }

    #[op(code = "edf0", fmt = "BOOLAND", args(op = Compose::And))]
    #[op(code = "edf1", fmt = "BOOLOR", args(op = Compose::Or))]
    #[op(code = "edf2", fmt = "COMPOSBOTH", args(op = Compose::Both))]
    fn exec_compos(st: &mut VmState, op: Compose) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let value = ok!(stack.pop_cont());
        let mut cont = ok!(stack.pop_cont());
        let refs = &mut force_cdata(&mut cont).save;
        match op {
            Compose::And => refs.define_c0(&Some(value)),
            Compose::Or => refs.define_c1(&Some(value)),
            Compose::Both => {
                refs.define_c0(&Some(value.clone()));
                refs.define_c1(&Some(value));
            }
        }
        ok!(stack.push_raw(cont));
        Ok(0)
    }

    #[op(code = "edf3", fmt = "ATEXIT")]
    fn exec_atexit(st: &mut VmState) -> VmResult<i32> {
        let mut cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        force_cdata(&mut cont).save.define_c0(&st.cr.c[0]);
        st.cr.c[0] = Some(cont);
        Ok(0)
    }

    #[op(code = "edf4", fmt = "ATEXITALT")]
    fn exec_atexit_alt(st: &mut VmState) -> VmResult<i32> {
        let mut cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        force_cdata(&mut cont).save.define_c1(&st.cr.c[1]);
        st.cr.c[1] = Some(cont);
        Ok(0)
    }

    #[op(code = "edf5", fmt = "SETEXITALT")]
    fn exec_setexit_alt(st: &mut VmState) -> VmResult<i32> {
        let mut cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());
        let cr = force_cdata(&mut cont);
        cr.save.define_c0(&st.cr.c[0]);
        cr.save.define_c1(&st.cr.c[1]);
        st.cr.c[1] = Some(cont);
        Ok(0)
    }

    #[op(code = "edf6", fmt = "THENRET")]
    fn exec_thenret(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let mut cont = ok!(stack.pop_cont());
        force_cdata(&mut cont).save.define_c0(&st.cr.c[0]);
        ok!(stack.push_raw(cont));
        Ok(0)
    }

    #[op(code = "edf7", fmt = "THENRETALT")]
    fn exec_thenret_alt(st: &mut VmState) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        let mut cont = ok!(stack.pop_cont());
        force_cdata(&mut cont).save.define_c1(&st.cr.c[1]);
        ok!(stack.push_raw(cont));
        Ok(0)
    }

    #[op(code = "edf8", fmt = "INVERT")]
    fn exec_invert(st: &mut VmState) -> VmResult<i32> {
        st.cr.c.swap(0, 1);
        Ok(0)
    }

    #[op(code = "edf9", fmt = "BOOLEVAL")]
    fn exec_booleval(st: &mut VmState) -> VmResult<i32> {
        let cont = ok!(SafeRc::make_mut(&mut st.stack).pop_cont());

        let next = ok!(st.extract_cc(SaveCr::C0_C1, None, None));
        st.cr.c[0] = Some(SafeRc::from(PushIntCont {
            value: -1,
            next: next.clone(),
        }));
        st.cr.c[1] = Some(SafeRc::from(PushIntCont { value: 0, next }));

        st.jump(cont)
    }

    #[op(code = "edfa", fmt = "SAMEALT", args(save = false))]
    #[op(code = "edfb", fmt = "SAMEALTSAVE", args(save = true))]
    fn exec_samealt(st: &mut VmState, save: bool) -> VmResult<i32> {
        let [c0, c1, ..] = &mut st.cr.c;

        // TODO: Check if there are no ways to leave `None` in c0
        let c0 = c0.as_mut().expect("c0 should be always set");
        if save {
            force_cdata(c0).save.define_c1(c1);
        }

        *c1 = Some(c0.clone());
        Ok(0)
    }

    #[op(code = "eern", fmt = "BLESSARGS {r},{n}", args(n = ((args as i32 + 1) & 0xf) - 1))]
    fn exec_bless_args(st: &mut VmState, r: u32, n: i32) -> VmResult<i32> {
        ok!(exec_bless_args_common(st, r, n));
        Ok(0)
    }

    // === Dictjump ===

    #[op(code = "f0nn", fmt = "CALLDICT {n}")]
    #[op(code = "f1$00nn#nnn", fmt = "CALLDICT {n}")]
    fn exec_calldict_short(st: &mut VmState, n: u32) -> VmResult<i32> {
        ok!(SafeRc::make_mut(&mut st.stack).push_int(n));
        let Some(c3) = st.cr.c[3].clone() else {
            vm_bail!(InvalidType {
                expected: StackValueType::Cont as _,
                actual: StackValueType::Null as _,
            });
        };
        st.call(c3)
    }

    #[op(code = "f1$01nn#nnn", fmt = "JMPDICT {n}")]
    fn exec_jmpdict(st: &mut VmState, n: u32) -> VmResult<i32> {
        ok!(SafeRc::make_mut(&mut st.stack).push_int(n));
        let Some(c3) = st.cr.c[3].clone() else {
            vm_bail!(InvalidType {
                expected: StackValueType::Cont as _,
                actual: StackValueType::Null as _,
            });
        };
        st.jump(c3)
    }

    #[op(code = "f1$10nn#nnn", fmt = "PREPAREDICT {n}")]
    fn exec_preparedict(st: &mut VmState, n: u32) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);
        ok!(stack.push_int(n));

        let c3 = match st.cr.c[3].clone() {
            Some(c3) => c3.into_dyn_value(),
            None => Stack::make_null(),
        };
        ok!(stack.push_raw(c3));
        Ok(0)
    }

    // === Exceptions ===

    #[op(code = "f2$00nn#n", fmt = "THROW {n}", args(mode = ThrowMode::Direct))]
    #[op(code = "f2$01nn#n", fmt = "THROWIF {n}", args(mode = ThrowMode::Cond(true)))]
    #[op(code = "f2$10nn#n", fmt = "THROWIFNOT {n}", args(mode = ThrowMode::Cond(false)))]
    #[op(code = "f2c$0nnn#nn", fmt = "THROW {n}", args(mode = ThrowMode::Direct))]
    #[op(code = "f2d$0nnn#nn", fmt = "THROWIF {n}", args(mode = ThrowMode::Cond(true)))]
    #[op(code = "f2e$0nnn#nn", fmt = "THROWIFNOT {n}", args(mode = ThrowMode::Cond(false)))]
    fn exec_throw_fixed(st: &mut VmState, n: u32, mode: ThrowMode) -> VmResult<i32> {
        if let ThrowMode::Cond(cond) = mode
            && ok!(SafeRc::make_mut(&mut st.stack).pop_bool()) != cond
        {
            return Ok(0);
        }

        st.throw_exception(n as i32)
    }

    #[op(code = "f2c$1nnn#nn", fmt = "THROWARG {n}", args(mode = ThrowMode::Direct))]
    #[op(code = "f2d$1nnn#nn", fmt = "THROWARGIF {n}", args(mode = ThrowMode::Cond(true)))]
    #[op(code = "f2e$1nnn#nn", fmt = "THROWARGIFNOT {n}", args(mode = ThrowMode::Cond(false)))]
    fn exec_throw_arg_fixed(st: &mut VmState, n: u32, mode: ThrowMode) -> VmResult<i32> {
        let stack = SafeRc::make_mut(&mut st.stack);

        if let ThrowMode::Cond(cond) = mode
            && ok!(stack.pop_bool()) != cond
        {
            ok!(stack.pop());
            return Ok(0);
        }

        let arg = ok!(stack.pop());
        st.throw_exception_with_arg(n as i32, arg)
    }

    #[op(code = "f2fx @ ..f2f6", fmt = ThrowAnyArgs(x))]
    fn exec_throw_any(st: &mut VmState, x: u32) -> VmResult<i32> {
        let args = ThrowAnyArgs(x);

        let stack = SafeRc::make_mut(&mut st.stack);
        let cond = if args.has_cond() {
            ok!(stack.pop_bool())
        } else {
            args.throw_cond()
        };

        let n = ok!(stack.pop_smallint_range(0, 0xffff));
        if cond != args.throw_cond() {
            if args.has_param() {
                ok!(stack.pop());
            }
            Ok(0)
        } else if args.has_param() {
            let arg = ok!(stack.pop());
            st.throw_exception_with_arg(n as i32, arg)
        } else {
            st.throw_exception(n as i32)
        }
    }

    #[op(code = "f2ff", fmt = "TRY")]
    fn exec_try(st: &mut VmState) -> VmResult<i32> {
        exec_try_common(st, None)
    }

    #[op(code = "f3pr", fmt = "TRYARGS {p},{r}")]
    fn exec_tryargs(st: &mut VmState, p: u32, r: u32) -> VmResult<i32> {
        exec_try_common(st, Some((p as u16, r as u16)))
    }

    // === Codepage ops ===
    #[op(code = "fff0", fmt = "SETCPX")]
    fn exec_set_cp_any(st: &mut VmState) -> VmResult<i32> {
        let cp = ok!(SafeRc::make_mut(&mut st.stack).pop_smallint_signed_range(-0x8000, 0x7fff));
        ok!(st.force_cp(cp as i16 as u16));
        Ok(0)
    }

    #[op(code = "ff00", fmt = "SETCP0", args(x = 0i16))]
    #[op(code = "ffxx @ ff01..fff0", fmt = "SETCP", args(x = (args & 0xff) as i16),)]
    #[op(code = "fffx @ fff1..", fmt = "SETCP {x}", args(x = (args & 0xf) as i16 - 16))]
    fn exec_set_cp(st: &mut VmState, x: i16) -> VmResult<i32> {
        ok!(st.force_cp(x as u16));
        Ok(0)
    }
}

fn exec_ref_prefix(st: &mut VmState, bits: u16, name: &str) -> VmResult<RcCont> {
    let code_range = st.code.range();
    vm_ensure!(code_range.has_remaining(bits, 1), InvalidOpcode);
    let ok = st.code.range_mut().skip_first(bits, 0).is_ok();
    debug_assert!(ok);

    let Some(code) = st.code.cell().reference_cloned(code_range.offset_refs()) else {
        vm_bail!(CellError(tycho_types::error::Error::CellUnderflow));
    };
    let ok = st.code.range_mut().skip_first(0, 1).is_ok();
    debug_assert!(ok);

    vm_log_op!("{name} ({})", code.repr_hash());
    st.ref_to_cont(code)
}

#[cfg(feature = "dump")]
fn dump_ref_prefix(
    code: &mut CellSlice<'_>,
    bits: u16,
    name: &str,
    f: &mut dyn DumpOutput,
) -> DumpResult {
    if !code.has_remaining(bits, 1) {
        return Err(DumpError::InvalidOpcode);
    }
    code.skip_first(bits, 0)?;
    let code = code.load_reference_cloned()?;

    f.record_cont(code.clone())?;
    f.record_opcode(&format_args!("{name} ({})", code.repr_hash()))
}

fn exec_cell_prefix(st: &mut VmState, bits: u16, name: &str) -> VmResult<Cell> {
    let code_range = st.code.range();
    vm_ensure!(code_range.has_remaining(bits, 1), InvalidOpcode);
    let ok = st.code.range_mut().skip_first(bits, 0).is_ok();
    debug_assert!(ok);

    let Some(cell) = st.code.cell().reference_cloned(code_range.offset_refs()) else {
        vm_bail!(CellError(tycho_types::error::Error::CellUnderflow));
    };
    let ok = st.code.range_mut().skip_first(0, 1).is_ok();
    debug_assert!(ok);

    vm_log_op!("{name} ({})", cell.repr_hash());
    Ok(cell)
}

fn exec_ifelse_ref_impl(st: &mut VmState, bits: u16, ref_first: bool) -> VmResult<i32> {
    let cont = {
        let code_range = st.code.range();
        vm_ensure!(code_range.has_remaining(bits, 1), InvalidOpcode);
        let ok = st.code.range_mut().skip_first(bits, 0).is_ok();
        debug_assert!(ok);

        let Some(cell) = st.code.cell().reference_cloned(code_range.offset_refs()) else {
            vm_bail!(CellError(tycho_types::error::Error::CellUnderflow));
        };
        let ok = st.code.range_mut().skip_first(0, 1).is_ok();
        debug_assert!(ok);

        let name = match ref_first {
            true => "IFREFELSE",
            false => "IFELSEREF",
        };

        vm_log_op!("{name} ({})", cell.repr_hash());

        let stack = SafeRc::make_mut(&mut st.stack);
        let cont = ok!(stack.pop_cont());

        if ok!(stack.pop_bool()) == ref_first {
            ok!(st.ref_to_cont(cell))
        } else {
            cont
        }
    };
    st.call(cont)
}

fn exec_setcontargs_common(st: &mut VmState, copy: u32, more: i32) -> VmResult<()> {
    let stack = SafeRc::make_mut(&mut st.stack);
    let mut cont = ok!(stack.pop_cont());
    if copy > 0 || more >= 0 {
        let cdata = force_cdata(&mut cont);

        if copy > 0 {
            ok!(cdata.require_nargs(copy as _));
            if let Some(cdata_stack) = &mut cdata.stack {
                ok!(SafeRc::make_mut(cdata_stack).move_from_stack(stack, copy as _));
            } else {
                cdata.stack = Some(ok!(stack.split_top(copy as _)));
            }

            st.gas.try_consume_stack_gas(cdata.stack.as_ref())?;

            if let Some(n) = &mut cdata.nargs {
                *n -= copy as u16;
            }
        }

        if more >= 0 {
            match &mut cdata.nargs {
                Some(n) => {
                    if *n as i32 > more {
                        *n = u16::MAX; // will throw an exception if run
                    }
                }
                None => cdata.nargs = Some(more as _),
            }
        }
    }

    ok!(stack.push_raw(cont));
    Ok(())
}

fn exec_return_args_common(st: &mut VmState, count: u32) -> VmResult<()> {
    let (copy, alt_stack) = {
        let stack = SafeRc::make_mut(&mut st.stack);

        let depth = stack.depth();
        let copy = match (count as usize).cmp(&depth) {
            std::cmp::Ordering::Less => depth - count as usize,
            std::cmp::Ordering::Equal => return Ok(()),
            std::cmp::Ordering::Greater => vm_bail!(StackUnderflow(count as _)),
        };
        let new_stack = ok!(stack.split_top(count as _));

        (copy, std::mem::replace(&mut st.stack, new_stack))
    };

    let cont = st.cr.c[0].as_mut().expect("c0 should always be set");
    let cdata = force_cdata(cont);
    ok!(cdata.require_nargs(copy));

    if let Some(cdata_stack) = &mut cdata.stack {
        ok!(SafeRc::make_mut(cdata_stack)
            .move_from_stack(&mut SafeRc::unwrap_or_clone(alt_stack), copy))
    } else {
        cdata.stack = Some(alt_stack);
    }

    st.gas.try_consume_stack_gas(cdata.stack.as_ref())?;

    if let Some(n) = &mut cdata.nargs {
        *n -= copy as u16;
    }
    Ok(())
}

fn exec_bless_args_common(st: &mut VmState, copy: u32, more: i32) -> VmResult<()> {
    let stack = SafeRc::make_mut(&mut st.stack);
    let cs = ok!(stack.pop_cs());
    let new_stack = ok!(stack.split_top(copy as _));
    st.gas.try_consume_stack_gas(Some(&new_stack))?;
    let cont = SafeRc::new(OrdCont {
        data: ControlData {
            nargs: (more >= 0).then_some(more as _),
            stack: Some(new_stack),
            save: Default::default(),
            cp: Some(st.cp.id()),
        },
        code: SafeRc::unwrap_or_clone(cs),
    });
    ok!(stack.push_raw(cont));
    Ok(())
}

fn exec_try_common(st: &mut VmState, args: Option<(u16, u16)>) -> VmResult<i32> {
    let stack = SafeRc::make_mut(&mut st.stack);
    let mut handler_cont = ok!(stack.pop_cont());
    let cont = ok!(stack.pop_cont());
    let old_c2 = st.cr.c[2].clone();

    let (stack_copy, nargs) = args.unzip();
    let cc = ok!(st.extract_cc(SaveCr::FULL, stack_copy, nargs));

    let handler_cr = &mut force_cdata(&mut handler_cont).save;
    handler_cr.define_c2(&old_c2);
    if handler_cr.c[0].is_none() {
        handler_cr.c[0] = Some(cc.clone());
    }

    st.cr.c[0] = Some(cc);
    st.cr.c[2] = Some(handler_cont);
    st.jump(cont)
}

fn force_cdata(cont: &mut RcCont) -> &mut ControlData {
    if cont.get_control_data().is_some() {
        return SafeRc::make_mut(cont)
            .get_control_data_mut()
            .expect("always has control data");
    }

    *cont = SafeRc::from(ArgContExt {
        data: Default::default(),
        ext: cont.clone(), // TODO: Somehow reduce this `clone`
    });

    SafeRc::get_mut(cont)
        .expect("only one instance")
        .get_control_data_mut()
        .expect("always has control data")
}

#[derive(Debug, Clone, Copy)]
enum Compose {
    And,
    Or,
    Both,
}

#[derive(Debug, Clone, Copy)]
enum ThrowMode {
    Direct,
    Cond(bool),
}

#[derive(Clone, Copy)]
struct ThrowAnyArgs(u32);

impl ThrowAnyArgs {
    const fn has_param(self) -> bool {
        self.0 & 0b001 != 0
    }

    const fn has_cond(self) -> bool {
        self.0 & 0b110 != 0
    }

    const fn throw_cond(self) -> bool {
        self.0 & 0b010 != 0
    }
}

impl std::fmt::Display for ThrowAnyArgs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let arg = if self.has_param() { "ARG" } else { "" };
        let cond = if self.has_cond() {
            if self.throw_cond() { "IF" } else { "IFNOT" }
        } else {
            ""
        };

        write!(f, "THROW{arg}ANY{cond}")
    }
}

#[derive(Clone, Copy)]
struct RunVmArgs(u32);

impl RunVmArgs {
    /// +1 = same_c3 (set c3 to code).
    const fn same_c3(self) -> bool {
        self.0 & 0b000000001 != 0
    }

    /// +2 = push_0 (push an implicit 0 before running the code).
    const fn push_0(self) -> bool {
        self.0 & 0b000000010 != 0
    }

    /// +4 = load c4 (persistent data) from stack and return its final value.
    const fn load_c4(self) -> bool {
        self.0 & 0b000000100 != 0
    }

    /// +8 = load gas limit from stack and return consumed gas.
    const fn load_gas(self) -> bool {
        self.0 & 0b000001000 != 0
    }

    /// +16 = load c7 (smart-contract context).
    const fn load_c7(self) -> bool {
        self.0 & 0b000010000 != 0
    }

    /// +32 = return c5 (actions).
    const fn return_c5(self) -> bool {
        self.0 & 0b000100000 != 0
    }

    /// +64 = pop hard gas limit (enabled by ACCEPT) from stack as well.
    const fn load_hard_gas_limit(self) -> bool {
        self.0 & 0b001000000 != 0
    }

    /// +128 = isolated gas consumption (separate set of visited cells, reset chksgn counter).
    const fn isolate_gas(self) -> bool {
        self.0 & 0b010000000 != 0
    }

    /// +256 = pop number N, return exactly N values from stack
    /// (only if res=0 or 1; if not enough then res=stk_und).
    const fn ret_n(self) -> bool {
        self.0 & 0b100000000 != 0
    }
}

fn exec_runvm_common(st: &mut VmState, args: RunVmArgs) -> VmResult<i32> {
    // Check possible args range (all other bits are reserved for future).
    vm_ensure!(args.0 < 512, IntegerOutOfRange {
        min: 0,
        max: 511,
        actual: args.0.to_string()
    });

    // Compensate vm creation.
    st.gas.try_consume(GasConsumer::RUNVM_GAS_PRICE)?;

    // Read args from the stack.
    let stack = SafeRc::make_mut(&mut st.stack);

    let mut gas_max = if args.load_hard_gas_limit() {
        ok!(stack.pop_long_range(0, GasParams::MAX_GAS))
    } else {
        GasParams::MAX_GAS
    };
    let gas_limit = if args.load_gas() {
        ok!(stack.pop_long_range(0, GasParams::MAX_GAS))
    } else {
        GasParams::MAX_GAS
    };

    if args.load_hard_gas_limit() {
        gas_max = std::cmp::max(gas_max, gas_limit);
    } else {
        gas_max = gas_limit;
    }

    let child_c7 = if args.load_c7() {
        ok!(stack.pop_tuple())
    } else {
        SafeRc::new(Vec::new())
    };

    let child_data = if args.load_c4() {
        SafeRc::unwrap_or_clone(ok!(stack.pop_cell()))
    } else {
        Cell::default()
    };

    let return_values = if args.ret_n() {
        Some(ok!(stack.pop_smallint_range(0, 1 << 30)))
    } else {
        None
    };

    let child_code = SafeRc::unwrap_or_clone(ok!(stack.pop_cs()));
    let stack_size = ok!(stack.pop_long_range(0, stack.depth().saturating_sub(1) as u64));
    let mut child_stack = ok!(stack.split_top(stack_size as usize));
    st.gas.try_consume_stack_gas(Some(&child_stack))?;

    let child_signature_domains = SafeRc::new(match st.signature_domains.last() {
        None | Some(SignatureDomain::Empty) => Vec::new(),
        Some(signature_domain) => vec![*signature_domain],
    });

    // Build child VM state.

    let parent_gas = ok!(st.gas.derive(GasConsumerDeriveParams {
        gas_max,
        gas_limit,
        isolate: args.isolate_gas(),
    }));

    // === ↓↓↓ Must not return any error afterwards ↓↓↓ ===

    let child_quit0 = QUIT0.with(SafeRc::clone);
    let child_quit1 = QUIT1.with(SafeRc::clone);
    let child_cp = codepage0();
    let child_c3 = if args.same_c3() {
        if args.push_0() {
            vm_log_trace!("implicit PUSH 0 at start");
            SafeRc::make_mut(&mut child_stack)
                .items
                .push(Stack::make_zero());
        }
        SafeRc::from(OrdCont::simple(child_code.clone(), child_cp.id()))
    } else {
        QUIT11.with(SafeRc::clone).into_dyn_cont()
    };

    let child_cr = ControlRegs {
        c: [
            Some(child_quit0.clone().into_dyn_cont()),
            Some(child_quit1.clone().into_dyn_cont()),
            Some(EXC_QUIT.with(SafeRc::clone).into_dyn_cont()),
            Some(child_c3),
        ],
        d: [Some(child_data), Some(Cell::empty_cell())],
        c7: Some(child_c7),
    };

    st.parent = Some(Box::new(ParentVmState {
        code: std::mem::replace(&mut st.code, child_code),
        stack: std::mem::replace(&mut st.stack, child_stack),
        signature_domains: std::mem::replace(&mut st.signature_domains, child_signature_domains),
        cr: std::mem::replace(&mut st.cr, child_cr),
        committed_state: std::mem::take(&mut st.committed_state),
        steps: std::mem::take(&mut st.steps),
        quit0: std::mem::replace(&mut st.quit0, child_quit0),
        quit1: std::mem::replace(&mut st.quit1, child_quit1),
        gas: parent_gas,
        cp: std::mem::replace(&mut st.cp, child_cp),
        return_data: args.load_c4(),
        return_actions: args.return_c5(),
        return_gas: args.load_gas(),
        return_values,
        parent: st.parent.take(),
    }));

    Ok(0)
}

#[cfg(test)]
mod tests {
    use num_bigint::BigInt;
    use tracing_test::traced_test;
    use tycho_types::boc::Boc;

    use super::*;
    use crate::OwnedCellSlice;
    use crate::cont::QuitCont;
    use crate::instr::codepage0;
    use crate::state::IntoCode;

    #[test]
    #[traced_test]
    fn argument_contops() {
        assert_run_vm!(
            r#"
            PUSHINT 1
            PUSHCONT {
                PUSHINT 3
                PUSHINT 2
            }
            CALLXARGS 1, 2
            "#,
            [] => [int 3, int 2],
        );

        assert_run_vm!(
            r#"
            PUSHINT 1
            PUSHCONT {
                NOP
            }
            CALLXARGS 1, 1
            "#,
            [] => [int 1],
        );

        assert_run_vm!(
            r#"
            PUSHCONT {
                NOP
            }
            CALLXARGS 1, 0
            "#,
            [] => [int 0],
            exit_code: 2
        );

        assert_run_vm!(
            r#"
            PUSHCONT {
                PUSHINT 3
                PUSHINT 2
            }
            CALLXARGS 0, 3
            "#,
            [] => [int 0],
            exit_code: 2
        );

        assert_run_vm!(
            r#"
            PUSHCONT {
                PUSHINT 3
                PUSHINT 2
            }
            CALLXARGS 0, 3
            "#,
            [] => [int 0],
            exit_code: 2
        );

        assert_run_vm!(
            r#"
            PUSHCONT {
                PUSHINT 3
                PUSHINT 2
            }
            CALLXARGS 0, -1
            "#,
            [] => [int 3, int 2]
        );

        assert_run_vm!(
            r#"
            PUSHINT 1
            PUSHCONT {
                PUSHINT 3
                PUSHINT 2
            }
            CALLXARGS 1, -1
            "#,
            [] => [int 1, int 3, int 2]
        );

        assert_run_vm!(
            r#"
            PUSHINT 1
            PUSHINT 2
            PUSHCONT {
                PUSHINT 3
                PUSHINT 4
            }
            JMPXARGS 1
            PUSHINT 1
            "#,
            [] => [int 2, int 3, int 4]
        );

        assert_run_vm!(
            r#"
            PUSHINT 1
            PUSHINT 2
            PUSHCONT {
                PUSHINT 3
                PUSHINT 4
            }
            JMPXARGS 1
            PUSHINT 1
            "#,
            [] => [int 2, int 3, int 4]
        );

        assert_run_vm!(
            r#"
            PUSHINT 1
            PUSHCONT {
                PUSHINT 123
                PUSHINT 245
                RETARGS 2
            }
            EXECUTE
            "#,
            [] => [int 123, int 245]
        );
    }

    #[test]
    #[traced_test]
    fn basic_contops() -> anyhow::Result<()> {
        let cont = SafeRc::new_dyn_value(PushIntCont {
            value: 1,
            next: SafeRc::from(PushIntCont {
                value: 2,
                next: SafeRc::from(QuitCont { exit_code: 0 }),
            }),
        });

        assert_run_vm!(
            "EXECUTE",
            [raw cont.clone()] => [int 1, int 2],
        );

        let code = make_code(tvmasm! {
            r#"
            PUSHINT 1
            PUSHINT 2
            "#
        });
        let cont = SafeRc::new_dyn_value(OrdCont::simple(code, codepage0().id()));

        assert_run_vm!(
            "EXECUTE",
            [raw cont.clone()] => [int 1, int 2],
        );

        assert_run_vm!(
            "JMPX",
            [raw cont.clone()] => [int 1, int 2],
        );

        Ok(())
    }

    #[test]
    #[traced_test]
    fn conditional_contops() -> anyhow::Result<()> {
        let code = make_code(tvmasm! {
            r#"
            PUSHINT 1
            PUSHINT 2
            IFRET
            PUSHINT 0
            "#
        });
        let cont = SafeRc::new_dyn_value(OrdCont::simple(code, codepage0().id()));

        assert_run_vm!(
            "EXECUTE",
            [raw cont.clone()] => [int 1]
        );

        //--------

        let code = make_code(tvmasm! {
            r#"
            PUSHINT 1
            PUSHINT 0
            IFRET
            PUSHINT 2
            "#
        });
        let cont = SafeRc::new_dyn_value(OrdCont::simple(code, codepage0().id()));

        assert_run_vm!(
            "EXECUTE",
            [raw cont.clone()] => [int 1, int 2]
        );

        assert_run_vm!(
            "IFRET",
            [null] => [int 0],
            exit_code: 7
        );

        //-------

        let code = make_code(tvmasm! {
            r#"
            PUSHINT 2
            PUSHINT 0
            IFNOTRET
            PUSHINT 1
            "#
        });
        let cont = SafeRc::new_dyn_value(OrdCont::simple(code, codepage0().id()));

        assert_run_vm!(
            "EXECUTE",
            [raw cont.clone()] => [int 2]
        );

        //--------

        let code = make_code(tvmasm! {
            r#"
            PUSHINT 2
            PUSHINT 1
            IFNOTRET
            PUSHINT 1
            "#
        });
        let cont = SafeRc::new_dyn_value(OrdCont::simple(code, codepage0().id()));

        assert_run_vm!(
            "EXECUTE",
            [raw cont.clone()] => [int 2, int 1]
        );

        //-------------

        let code = make_code(tvmasm! {
            r#"
            PUSHINT 1
            PUSHINT 2
            "#
        });
        let cont = SafeRc::new_dyn_value(OrdCont::simple(code, codepage0().id()));

        assert_run_vm!(
            "IF",
            [int 0, raw cont.clone()] => [],
        );
        assert_run_vm!(
            "IF",
            [int 123, raw cont.clone()] => [int 1, int 2],
        );

        assert_run_vm!(
            "IFNOT",
            [int 1, raw cont.clone()] => [],
        );

        assert_run_vm!(
            "IFNOT",
            [int 13890, raw cont.clone()] => [],
        );

        assert_run_vm!(
            "IFNOT",
            [int 0, raw cont.clone()] => [int 1, int 2],
        );

        //-------

        let code1 = make_code(tvmasm! {
            r#"
            PUSHINT 1
            PUSHINT 2
            "#
        });
        let cont1 = SafeRc::new_dyn_value(OrdCont::simple(code1, codepage0().id()));

        let code2 = make_code(tvmasm! {
            r#"
            PUSHINT 3
            PUSHINT 4
            "#
        });
        let cont2 = SafeRc::new_dyn_value(OrdCont::simple(code2, codepage0().id()));

        assert_run_vm!(
            "IFELSE",
            [int 0, raw cont1.clone(), raw cont2.clone()] => [int 3, int 4]
        );

        assert_run_vm!(
            "IFELSE",
            [int 1, raw cont1.clone(), raw cont2.clone()] => [int 1, int 2]
        );

        assert_run_vm!(
            "IFELSE",
            [null, raw cont1.clone(), raw cont2.clone()] => [int 0],
            exit_code: 7
        );

        Ok(())
    }

    #[test]
    #[traced_test]
    fn conditional_refcontops() -> anyhow::Result<()> {
        let code = make_code(tvmasm! {
            r#"
            PUSHINT 1
            PUSHINT 2
            "#
        });
        let cont = SafeRc::new_dyn_value(OrdCont::simple(code, codepage0().id()));

        // assert_run_vm!(
        //     "IFREF",
        //     code.as,
        //     [int 0, raw cont.clone()] => [],
        // );

        assert_run_vm!(
            "IF",
            [int 123, raw cont.clone()] => [int 1, int 2],
        );

        assert_run_vm!(
            r#"PUSHCONT { PUSHINT 1 PUSHINT 2 } EXECUTE"#,
            [] => [int 1, int 2],
        );

        assert_run_vm!(
            "IF",
            [int 0, raw cont.clone()] => [],
        );

        assert_run_vm!(
            "IFNOT",
            [int 1, raw cont.clone()] => [],
        );

        assert_run_vm!(
            "IFNOT",
            [int 13890, raw cont.clone()] => [],
        );

        assert_run_vm!(
            "IFNOT",
            [int 0, raw cont.clone()] => [int 1, int 2],
        );

        Ok(())
    }

    #[test]
    #[traced_test]
    fn conditional_altcontops() -> anyhow::Result<()> {
        assert_run_vm!(
            r#"
            PUSHCONT { PUSHINT 1 }
            POP c0
            PUSHCONT { PUSHINT 2 }
            POP c1
            PUSHINT 1
            IFRETALT
            "#,
            [] => [int 2, int 1]
        );

        assert_run_vm!(
            r#"
            PUSHCONT { PUSHINT 1 }
            POP c0
            PUSHCONT { PUSHINT 2 }
            POP c1
            PUSHINT 0
            IFRETALT
            "#,
            [] => [int 1]
        );

        Ok(())
    }

    #[test]
    #[traced_test]
    fn loops() -> anyhow::Result<()> {
        // REPEAT
        let code = make_code(tvmasm! {
            r#"
            PUSHINT 2
            "#
        });
        let cont = SafeRc::new_dyn_value(OrdCont::simple(code, codepage0().id()));

        let code1 = make_code(tvmasm! {
            r#"
            PUSHINT 2
            PUSHINT 1
            "#
        });
        let cont1 = SafeRc::new_dyn_value(OrdCont::simple(code1, codepage0().id()));

        assert_run_vm!(
            "REPEAT",
            [int 5, raw cont.clone()] => [int 2, int 2,int 2, int 2, int 2 ]
        );

        assert_run_vm!(
            "REPEAT",
            [int -1, raw cont.clone()] => []
        );

        assert_run_vm!(
            "REPEAT",
            [int (BigInt::from(1) << 31), raw cont.clone()] => [int 0],
            exit_code: 5
        );

        // REPEATEND

        assert_run_vm!(
            "REPEATEND PUSHINT 2",
            [int 3] => [int 2, int 2, int 2]
        );

        // UNTIL
        assert_run_vm!(
            "UNTIL",
            [raw cont1.clone()] => [int 2]
        );

        // UNTILEND
        // TODO: case for other branch
        assert_run_vm!(
            "UNTILEND PUSHINT 0 PUSHINT 1",
            [int 3] => [int 3, int 0]
        );

        // WHILE
        let code0 = make_code(tvmasm! {
            r#"
            PUSHINT 2
            "#
        });
        let c0 = SafeRc::new_dyn_value(OrdCont::simple(code0, codepage0().id()));

        let code1 = make_code(tvmasm! {
            r#"
            PUSHINT 0
            "#
        });
        let c1 = SafeRc::new_dyn_value(OrdCont::simple(code1, codepage0().id()));

        assert_run_vm!(
            "WHILE",
            [int 2, raw c1.clone(), raw c0.clone()] => [int 2]
        );

        // WHILEEND
        // TODO: case for other branch
        assert_run_vm!(
            "WHILEEND PUSHINT 1",
            [int 2, raw c1.clone()] => [int 2]
        );

        // AGAIN
        // TODO: TEST MORE CASES

        let code_c0 = make_code(tvmasm! {
            r#"
            PUSHINT 2
            RETALT
            "#
        });
        let cont_c0 = SafeRc::new_dyn_value(OrdCont::simple(code_c0, codepage0().id()));

        // TODO: probably this behaviour with exit code 1 is okay. Add more cases with more loops

        assert_run_vm!(
            "AGAIN",
            [int 2, raw cont_c0.clone()] => [int 2, int 2],
            exit_code: 1
        );

        // AGAINEND
        assert_run_vm!(
            "AGAINEND PUSHINT 2 RETALT",
            [int 2] => [int 2, int 2],
            exit_code: 1
        );

        // REPEATBRK

        let code_c0 = make_code(tvmasm! {
            r#"
            PUSHINT 0
            DUMPSTK
            SWAP
            DEC
            DUP
            PUSHCONT {
                DROP
                RETALT
            }
            IFNOT
            "#
        });
        let cont_c0 = SafeRc::new_dyn_value(OrdCont::simple(code_c0, codepage0().id()));

        assert_run_vm!(
            "REPEATBRK",
            [int 5, int 10, raw cont_c0.clone()] => [int 0, int 0, int 0, int 0, int 0]
        );

        // REPEATENDBRK

        assert_run_vm!(
            r#"
            PUSHCONT {
                REPEATENDBRK
                PUSHINT 0
                SWAP
                DEC
                DUP
                PUSHCONT {
                    DROP
                    RETALT
                }
                IFNOT
                POP s1
            }
            EXECUTE
            "#,
            [int 5, int 10] => [int 0]
        );

        let code_c0 = make_code(tvmasm! {
            r#"
            INC
            SWAP
            DUP
            PUSHCONT {
                DROP
                RETALT
            }
            IFNOT
            SWAP
            DUMPSTK
            "#
        });
        let cont_c0 = SafeRc::new_dyn_value(OrdCont::simple(code_c0, codepage0().id()));

        assert_run_vm!(
            "UNTILBRK",
            [int 0, int -5, raw cont_c0.clone()] => [int -4]
        );

        Ok(())
    }

    #[test]
    #[traced_test]
    fn callcc() {
        assert_run_vm!(
            r#"
            PUSHCONT { DROP }
            INT 0
            INT -1
            CALLCCVARARGS
            "#,
            [] => []
        );

        assert_run_vm!(
            r#"
            PUSHCONT { DROP }
            POPSAVE c0

            INT 2
            REPEATEND
            PUSH c0
            CALLCCARGS 0, 3
            DROP
            "#,
            [] => [],
        );

        assert_run_vm!(
            r#"
            INT 0
            SAVECTR c2
            RETURNARGS 0
            "#,
            [] => [int 0],
        );
    }

    #[test]
    #[traced_test]
    fn runvm_simple() {
        let child_code = make_code(tvmasm!(
            r#"
            ADD
            DEPTH
            PUSH c4 CTOS SBITREFS
            PUSH c5 CTOS SBITREFS
            PUSH c7
            PUSHREF x{99991111} POP c4
            PUSHREF x{aaaabbbb} POP c5

            NIL
            INT 100
            TPUSH
            INT 200
            TPUSH
            POP c7

            INT 123
            "#
        ));

        assert_run_vm!(
            r#"
            PUSHREF x{1234} POP c4
            PUSHREF x{5678} POP c5
            NIL
            INT 5
            TPUSH
            INT 6
            TPUSH
            POP c7

            RUNVM 0

            PUSH c4 CTOS
            PUSH c5 CTOS
            PUSH c7
            "#,
            [int 111, int 10, int 20, int 2, slice child_code] => [
                int 111,
                int 30,
                int 1,
                int 0,
                int 0,
                int 0,
                int 0,
                [],
                int 123,
                int 0,
                slice make_slice(0x1234_u16),
                slice make_slice(0x5678_u16),
                [int 5, int 6],
            ],
        );
    }

    #[test]
    #[traced_test]
    fn runvm_exception() {
        // === Simple exception ===

        let child_code = make_code(tvmasm!(
            r#"
            INT 22
            INT 55 THROWARG 66
            "#
        ));

        assert_run_vm!(
            "RUNVM 0",
            [int 111, int 10, int 20, int 2, slice child_code] => [
                int 111,
                int 55,
                int 66,
            ],
        );

        // === c4, c5 with exception ===

        let child_code = make_code(tvmasm!(
            r#"
            PUSHREF x{abcdaaaa} POP c4
            PUSHREF x{abcdbbbb} POP c5
            THROW 55
            "#,
        ));

        assert_run_vm!(
            r#"
            PUSHREF x{1234aaaa} POP c4
            PUSHREF x{1234bbbb} POP c5
            RUNVM 36
            PUSH c4 CTOS
            PUSH c5 CTOS
            "#,
            [int 0, slice child_code, cell make_cell(0x5678_u16)] => [
                int 0,
                int 55,
                null,
                null,
                slice make_slice(0x1234aaaa_u32),
                slice make_slice(0x1234bbbb_u32),
            ],
        );

        // === c4, c5 with exception and commit ===

        let child_code = make_code(tvmasm!(
            r#"
            PUSHREF x{abcdaaaa} POP c4
            PUSHREF x{abcdbbbb} POP c5
            COMMIT
            PUSHREF x{} POP c4
            @newcell
            PUSHREF x{} POP c5
            THROW 55
            "#,
        ));

        assert_run_vm!(
            r#"
            PUSHREF x{1234aaaa} POP c4
            PUSHREF x{1234bbbb} POP c5
            RUNVM 36
            CTOS SWAP CTOS SWAP
            PUSH c4 CTOS
            PUSH c5 CTOS
            "#,
            [int 0, slice child_code, cell make_cell(0x5678_u16)] => [
                int 0,
                int 55,
                slice make_slice(0xabcdaaaa_u32),
                slice make_slice(0xabcdbbbb_u32),
                slice make_slice(0x1234aaaa_u32),
                slice make_slice(0x1234bbbb_u32),
            ],
        );

        // === Gas limit of parent VM is too low ===

        let child_code = make_code(tvmasm!("PUSHCONT { NOP } AGAIN"));
        assert_run_vm!(
            "RUNVM 8 INT 1234",
            gas: 300,
            [int 0, slice child_code, int 1000000] => [int 301],
            exit_code: -14,
        )
    }

    #[test]
    #[traced_test]
    fn runvm_flags_1_2() {
        // === flag +1: same c3 ===

        assert_run_vm!(
            r#"
            @define(simpleProg) {
                SETCP 0
                DICTPUSHCONST 19, [
                    0 => {
                        DUP
                        CALLDICT 22
                        INC
                    }
                    22 => {
                        MUL
                    }
                ]
                DICTIGETJMPZ
                THROWARG 11
            }

            INT 10 INT 0 INT 2 PUSHSLICE @use(simpleProg) RUNVM 1
            INT 10 INT 0 INT 2 PUSHSLICE @use(simpleProg) RUNVM 0
            "#,
            [] => [int 101, int 0, int 22, int 11],
        );

        // === flag +2(+1): push0 ===

        assert_run_vm!(
            "INT 10 INT 1 PUSHSLICE {
                SETCP 0
                DICTPUSHCONST 19, [
                    0 => {
                        DUP
                        CALLDICT 22
                        INC
                    }
                    22 => {
                        MUL
                    }
                ]
                DICTIGETJMPZ
                THROWARG 11
            } RUNVM 3",
            [] => [int 101, int 0]
        );
    }

    #[test]
    #[traced_test]
    fn runvm_flag_4() {
        // flag +4 - load and return c4

        let child_code = make_code(tvmasm!(
            r#"
            PUSHCTR c4 CTOS
            PUSHREF x{abcd} POPCTR c4
            INT 1000
            "#
        ));

        assert_run_vm!(
            r#"
            PUSHREF x{1234} POP c4
            RUNVM 4
            CTOS
            PUSH c4 CTOS
            "#,
            [int 0, slice child_code, cell make_cell(0x5678_u16)] => [
                slice make_slice(0x5678_u16),
                int 1000,
                int 0,
                slice make_slice(0xabcd_u16),
                slice make_slice(0x1234_u16),
            ]
        );
    }

    #[test]
    #[traced_test]
    fn runvm_flag_8() {
        // flag: +8 - gas limit

        let child_code = make_code(tvmasm!("PUSHCONT { NOP } AGAIN"));

        assert_run_vm!(
            r#"RUNVM 8 INT 1234"#,
            [int 0, slice child_code, int 200] => [
                int 215,
                int -14,
                int 215,
                int 1234,
            ]
        );
    }

    #[test]
    #[traced_test]
    fn runvm_flag_16() {
        // flag +16 - load c7

        let child_code = make_code(tvmasm!(
            r#"
            PUSH c7
            NIL
            INT 111 TPUSH
            INT 222 TPUSH
            INT 3333 TPUSH
            POP c7
            INT 1000
            "#
        ));

        assert_run_vm!(
            r#"
            NIL
            INT 1 TPUSH
            INT 2 TPUSH
            INT 3 TPUSH
            POP c7
            RUNVM 16
            PUSH c7
            "#,
            [int 0, slice child_code, [int 10, int 15, int 20]] => [
                [int 10, int 15, int 20],
                int 1000,
                int 0,
                [int 1, int 2, int 3],
            ],
        );
    }

    #[test]
    #[traced_test]
    fn runvm_flag_32() {
        // flag +32 - return c5

        let child_code = make_code(tvmasm!(
            r#"
            PUSH c5 CTOS SBITREFS
            PUSHREF x{5678} POP c5
            INT 1000
            "#
        ));

        assert_run_vm!(
            r#"
            PUSHREF x{1234} POP c5
            RUNVM 32
            CTOS
            PUSH c5 CTOS
            "#,
            [int 0, slice child_code] => [
                int 0,
                int 0,
                int 1000,
                int 0,
                slice make_slice(0x5678_u16),
                slice make_slice(0x1234_u16),
            ],
        );
    }

    #[test]
    #[traced_test]
    fn runvm_flag_64() {
        // flag +64 - hard gas limit

        let child_code = make_code(tvmasm!("PUSHCONT { NOP } AGAIN"));
        assert_run_vm!(
            "RUNVM 72 INT 1234",
            [int 0, slice child_code, int 200, int 500] => [int 215, int -14, int 215, int 1234],
        );

        let child_code = make_code(tvmasm!("ACCEPT PUSHCONT { NOP } AGAIN"));
        assert_run_vm!(
            "RUNVM 72 INT 1234",
            [int 0, slice child_code, int 200, int 500] => [int 517, int -14, int 517, int 1234],
        );
    }

    #[test]
    #[traced_test]
    fn runvm_flag_128() {
        // flag +128 - separate loaded_cells

        assert_run_vm!(
            r#"
            DUP CTOS DROP
            INT 2
            PUSHSLICE { CTOS DROP CTOS DROP }
            INT 10000
            RUNVM 8
            "#,
            [cell make_cell(0x12345678_u32), cell make_cell(0x87654321_u32)] => [
                int 0,
                int 202,
            ],
        );
    }

    #[test]
    #[traced_test]
    fn runvm_flag_256() {
        // +256 - fixed number of return values

        let child_code = make_code(tvmasm!("INT 1 INT 2 INT 3 INT 4 INT 5"));
        assert_run_vm!(
            "RUNVM 256",
            [int 11, int 22, int 33, int 3, slice child_code.clone(), int 3] => [
                int 3,
                int 4,
                int 5,
                int 0,
            ]
        );
        assert_run_vm!(
            "RUNVM 256",
            [int 11, int 22, int 33, int 3, slice child_code.clone(), int 0] => [int 0]
        );
        assert_run_vm!(
            "RUNVM 256",
            [int 11, int 22, int 33, int 3, slice child_code, int 20] => [int 0, int -3]
        );

        let child_code = make_code(tvmasm!("INT 1 INT 2 INT 3 INT 4 INT 5 THROW 77"));
        assert_run_vm!(
            "RUNVM 256",
            [int 11, int 22, int 33, int 3, slice child_code, int 3] => [int 0, int 77]
        );
    }

    #[test]
    // #[traced_test]
    fn runvm_compute_big() {
        assert_run_vm!(
            r#"
            @define(slice) {
                DUP EQINT 0
                PUSHCONT {
                    DROP DROP
                    ZERO
                } IFJMP
                OVER OVER DEC
                INT 2
                PUSH s2
                RUNVM 0 THROWIF 11
                ADD NIP
            }
            PUSHSLICE @use(slice)
            INT 10000
            INT 2
            PUSHSLICE @use(slice) RUNVM 0
            "#,
            gas: 10000000,
            [] => [int 50005000, int 0],
        );

        assert_run_vm!(
            r#"
            @define(slice) {
                DUP EQINT 0
                PUSHCONT {
                    DROP DROP
                    ZERO
                } IFJMP
                OVER OVER DEC
                INT 2
                PUSH s2
                RUNVM 0 THROWIF 11
                ADD NIP
            }
            PUSHSLICE @use(slice)
            INT 10000
            INT 2
            PUSHSLICE @use(slice) RUNVM 0
            "#,
            gas: 100000,
            [] => [int 100001],
            exit_code: -14,
        );
    }

    #[test]
    #[traced_test]
    fn runvmx() {
        let child_code = make_code(tvmasm!("PUSHCONT { NOP } AGAIN"));
        assert_run_vm!(
            r#"INT 8 RUNVMX INT 1234"#,
            [int 0, slice child_code, int 200] => [int 215, int -14, int 215, int 1234],
        );
    }

    #[test]
    #[traced_test]
    fn runvm_signdomain() {
        assert_run_vm!(
            "INT 0 PUSHSLICE { SIGNDOMAIN } RUNVM 0",
            [] => [null, int 0]
        );
        assert_run_vm!(
            "INT 123 SIGNDOMAIN_PUSH INT 0 PUSHSLICE { SIGNDOMAIN } RUNVM 0",
            [] => [int 123, int 0]
        );
        assert_run_vm!(
            r#"
            INT 123 SIGNDOMAIN_PUSH
            INT 234 SIGNDOMAIN_PUSH
            INT 0 PUSHSLICE {
                SIGNDOMAIN_POP
                SIGNDOMAIN_POP
                SIGNDOMAIN_POP
            } RUNVM 0
            SIGNDOMAIN_POP
            SIGNDOMAIN_POP
            SIGNDOMAIN_POP
            "#,
            [] => [int 234, null, null, int 0, int 234, int 123, null]
        );
        assert_run_vm!(
            r#"
            INT 123 SIGNDOMAIN_PUSH
            INT 234 SIGNDOMAIN_PUSH
            INT 0 PUSHSLICE {
                INT 345 SIGNDOMAIN_PUSH
                SIGNDOMAIN_POP
                SIGNDOMAIN_POP
                SIGNDOMAIN_POP
            } RUNVM 0
            SIGNDOMAIN_POP
            SIGNDOMAIN_POP
            SIGNDOMAIN_POP
            "#,
            [] => [int 345, int 234, null, int 0, int 234, int 123, null]
        );
        assert_run_vm!(
            r#"
            INT 123 SIGNDOMAIN_PUSH
            NULL SIGNDOMAIN_PUSH
            INT 0 PUSHSLICE {
                SIGNDOMAIN
                INT 234 SIGNDOMAIN_PUSH
                SIGNDOMAIN
            } RUNVM 0
            SIGNDOMAIN_POP
            SIGNDOMAIN_POP
            SIGNDOMAIN_POP
            "#,
            [] => [null, int 234, int 0, null, int 123, null]
        );
    }

    #[test]
    // #[traced_test]
    fn infinite_recursion() {
        assert_run_vm!(
            r#"
            PUSHCONT {
                DUP
                EXECUTE
            }
            DUP
            EXECUTE
            "#,
            [] => [int 1000008],
            exit_code: -14,
        );
    }

    #[test]
    // #[traced_test]
    fn infinite_loop_1() {
        assert_run_vm!(
            r#"
            AGAINEND
            SAVEBOTHCTR c0
            "#,
            [] => [int 1000011],
            exit_code: -14,
        );
    }

    #[test]
    // #[traced_test]
    fn infinite_loop_2() {
        assert_run_vm!(
            r#"
            PUSHINT -1
            PUSHINT 10
            PUSHCONT { PUSHCONT {} }
            AGAIN
            AND
            AGAINEND
            DEPTH
            "#,
            [] => [int 1000015],
            exit_code: -14,
        );
    }

    #[test]
    // #[traced_test]
    fn infinite_loop_3() {
        assert_run_vm!(
            r#"
            PUSHCONT {
                @inline x{94ed}
            }
            POPSAVE c2
            AGAINEND
            @inline x{8a}
            "#,
            [] => [int 1000002],
            exit_code: -14,
        );
    }

    #[test]
    // #[traced_test]
    fn oom_1() {
        assert_run_vm!(
            r#"
            PUSHCONT {
                PUSHNULL
                PUSHINT 7
                REPEATEND
                BLKPUSH 15, 0
                TUPLE 15
            }
            CALLXARGS 0, 0
            "#,
            [] => [],
        );
    }

    #[test]
    #[traced_test]
    fn empty_stack_on_exit() {
        assert_run_vm!(
            r#"
            PUSHCONT {
                PUSHINT 7
                REPEATEND

                DEPTH
                DUMPSTK
            }
            CALLXARGS 0, 0
            "#,
            [] => [],
        );
    }

    #[test]
    // #[traced_test]
    fn safe_infinite_recursion() {
        assert_run_vm!(
            r#"
            PUSHCONT {
                DUP
                POPSAVE c0
            }
            DUP
            EXECUTE
            "#,
            [] => [int 1000015],
            exit_code: -14,
        );
    }

    #[test]
    // #[traced_test]
    fn infinite_tuple() {
        assert_run_vm!(
            r#"
            NIL
            PUSHCONT {
                SWAP SINGLE SWAP
                DUP
                POPSAVE c0
            }
            DUP
            EXECUTE
            "#,
            [] => [int 1000011],
            exit_code: -14,
        );
    }

    #[test]
    // #[traced_test]
    fn infinite_runvm() {
        assert_run_vm!(
            r#"
            PUSHSLICE x{00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000}
            PUSHSLICE x{29b80902c424a3bb10064298f03e315e179ddc47d6a6f5695500f793f05d0b9b}
            LDU 256
            DROP

            PUSHSLICE {
                PUSH s2
                PUSH s2
                ZERO ROTREV
                CHKSIGNU DROP

                DUP
                INT 3 SWAP INT 128 RUNVMX
            }
            DUP
            INT 3 SWAP INT 128 RUNVMX
            "#,
            [] => [int 1000001],
            exit_code: -14,
        );
    }

    fn make_code(code: &[u8]) -> OwnedCellSlice {
        Boc::decode(code).unwrap().into_code().unwrap()
    }

    fn make_cell<T: Store>(value: T) -> Cell {
        CellBuilder::build_from(value).unwrap()
    }

    fn make_slice<T: Store>(value: T) -> OwnedCellSlice {
        OwnedCellSlice::new_allow_exotic(CellBuilder::build_from(value).unwrap())
    }
}