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

use ::rust_alloc::sync::Arc;

use crate::alloc::prelude::*;
use crate::alloc::{self, String};
use crate::hash::{Hash, IntoHash, ToTypeHash};
use crate::modules::{option, result};
use crate::runtime::budget;
use crate::runtime::future::SelectFuture;
use crate::runtime::unit::{UnitFn, UnitStorage};
use crate::runtime::{
    self, Args, Awaited, BorrowMut, Bytes, Call, ControlFlow, EmptyStruct, Format, FormatSpec,
    Formatter, FromValue, Function, Future, Generator, GuardedArgs, Inst, InstAddress,
    InstAssignOp, InstOp, InstRange, InstTarget, InstValue, InstVariant, Object, OwnedTuple, Panic,
    Protocol, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,
    RuntimeContext, Select, Shared, Stack, Stream, Struct, Type, TypeCheck, TypeOf, Unit, Value,
    Variant, VariantData, Vec, VmError, VmErrorKind, VmExecution, VmHalt, VmIntegerRepr, VmResult,
    VmSendExecution,
};

/// Small helper function to build errors.
fn err<T, E>(error: E) -> VmResult<T>
where
    VmErrorKind: From<E>,
{
    VmResult::err(error)
}

/// The result from a dynamic call. Indicates if the attempted operation is
/// supported.
#[derive(Debug)]
pub(crate) enum CallResult<T> {
    /// Call successful. Return value is on the stack.
    Ok(T),
    /// Call failed because function was missing so the method is unsupported.
    /// Contains target value.
    Unsupported(Value),
}

enum TargetFallback<'a> {
    Value(Value, Value),
    Field(&'a Value, Hash, Value),
    Index(&'a Value, usize, Value),
}

enum TargetValue<'a, 'b> {
    /// Resolved internal target to mutable value.
    Value(&'a mut Value, Value),
    /// Fallback to a different kind of operation.
    Fallback(TargetFallback<'b>),
}

macro_rules! target_value {
    ($vm:ident, $target:expr, $guard:ident, $lhs:ident) => {{
        let rhs = vm_try!($vm.stack.pop());

        match $target {
            InstTarget::Offset(offset) => {
                TargetValue::Value(vm_try!($vm.stack.at_offset_mut(offset)), rhs)
            }
            InstTarget::TupleField(index) => {
                $lhs = vm_try!($vm.stack.pop());

                if let Some(value) = vm_try!(Vm::try_tuple_like_index_get_mut(&$lhs, index)) {
                    $guard = value;
                    TargetValue::Value(&mut *$guard, rhs)
                } else {
                    TargetValue::Fallback(TargetFallback::Index(&$lhs, index, rhs))
                }
            }
            InstTarget::Field(field) => {
                let field = vm_try!($vm.unit.lookup_string(field));
                $lhs = vm_try!($vm.stack.pop());

                if let Some(value) = vm_try!(Vm::try_object_like_index_get_mut(&$lhs, field)) {
                    $guard = value;
                    TargetValue::Value(&mut *$guard, rhs)
                } else {
                    TargetValue::Fallback(TargetFallback::Field(&$lhs, field.hash(), rhs))
                }
            }
        }
    }};
}

/// A stack which references variables indirectly from a slab.
#[derive(Debug)]
pub struct Vm {
    /// Context associated with virtual machine.
    context: Arc<RuntimeContext>,
    /// Unit associated with virtual machine.
    unit: Arc<Unit>,
    /// The current instruction pointer.
    ip: usize,
    /// The length of the last executed instruction.
    last_ip_len: u8,
    /// The current stack.
    stack: Stack,
    /// Frames relative to the stack.
    call_frames: alloc::Vec<CallFrame>,
}

impl Vm {
    /// Construct a new virtual machine.
    pub const fn new(context: Arc<RuntimeContext>, unit: Arc<Unit>) -> Self {
        Self::with_stack(context, unit, Stack::new())
    }

    /// Construct a new virtual machine with a custom stack.
    pub const fn with_stack(context: Arc<RuntimeContext>, unit: Arc<Unit>, stack: Stack) -> Self {
        Self {
            context,
            unit,
            ip: 0,
            last_ip_len: 0,
            stack,
            call_frames: alloc::Vec::new(),
        }
    }

    /// Construct a vm with a default empty [RuntimeContext]. This is useful
    /// when the [Unit] was constructed with an empty
    /// [Context][crate::compile::Context].
    pub fn without_runtime(unit: Arc<Unit>) -> Self {
        Self::new(Default::default(), unit)
    }

    /// Test if the virtual machine is the same context and unit as specified.
    pub fn is_same(&self, context: &Arc<RuntimeContext>, unit: &Arc<Unit>) -> bool {
        Arc::ptr_eq(&self.context, context) && Arc::ptr_eq(&self.unit, unit)
    }

    /// Test if the virtual machine is the same context.
    pub fn is_same_context(&self, context: &Arc<RuntimeContext>) -> bool {
        Arc::ptr_eq(&self.context, context)
    }

    /// Test if the virtual machine is the same context.
    pub fn is_same_unit(&self, unit: &Arc<Unit>) -> bool {
        Arc::ptr_eq(&self.unit, unit)
    }

    /// Set  the current instruction pointer.
    #[inline]
    pub fn set_ip(&mut self, ip: usize) {
        self.ip = ip;
    }

    /// Get the stack.
    #[inline]
    pub fn call_frames(&self) -> &[CallFrame] {
        &self.call_frames
    }

    /// Get the stack.
    #[inline]
    pub fn stack(&self) -> &Stack {
        &self.stack
    }

    /// Get the stack mutably.
    #[inline]
    pub fn stack_mut(&mut self) -> &mut Stack {
        &mut self.stack
    }

    /// Access the context related to the virtual machine mutably.
    #[inline]
    pub fn context_mut(&mut self) -> &mut Arc<RuntimeContext> {
        &mut self.context
    }

    /// Access the context related to the virtual machine.
    #[inline]
    pub fn context(&self) -> &Arc<RuntimeContext> {
        &self.context
    }

    /// Access the underlying unit of the virtual machine mutablys.
    #[inline]
    pub fn unit_mut(&mut self) -> &mut Arc<Unit> {
        &mut self.unit
    }

    /// Access the underlying unit of the virtual machine.
    #[inline]
    pub fn unit(&self) -> &Arc<Unit> {
        &self.unit
    }

    /// Access the current instruction pointer.
    #[inline]
    pub fn ip(&self) -> usize {
        self.ip
    }

    /// Access the last instruction that was executed.
    #[inline]
    pub fn last_ip(&self) -> usize {
        self.ip.wrapping_sub(self.last_ip_len as usize)
    }

    /// Reset this virtual machine, freeing all memory used.
    pub fn clear(&mut self) {
        self.ip = 0;
        self.stack.clear();
        self.call_frames.clear();
    }

    /// Look up a function in the virtual machine by its name.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::{Context, Vm, Unit};
    /// use rune::compile::ItemBuf;
    ///
    /// use std::sync::Arc;
    ///
    /// let context = Context::with_default_modules()?;
    /// let context = Arc::new(context.runtime()?);
    ///
    /// let mut sources = rune::sources! {
    ///     entry => {
    ///         pub fn max(a, b) {
    ///             if a > b {
    ///                 a
    ///             } else {
    ///                 b
    ///             }
    ///         }
    ///     }
    /// };
    ///
    /// let unit = rune::prepare(&mut sources).build()?;
    /// let unit = Arc::new(unit);
    ///
    /// let vm = Vm::new(context, unit);
    ///
    /// // Looking up an item from the source.
    /// let dynamic_max = vm.lookup_function(["max"])?;
    ///
    /// let value: i64 = rune::from_value(dynamic_max.call((10, 20)).into_result()?)?;
    /// assert_eq!(value, 20);
    ///
    /// // Building an item buffer to lookup an `::std` item.
    /// let mut item = ItemBuf::with_crate("std")?;
    /// item.push("i64")?;
    /// item.push("max")?;
    ///
    /// let max = vm.lookup_function(&item)?;
    ///
    /// let value: i64 = rune::from_value(max.call((10, 20)).into_result()?)?;
    /// assert_eq!(value, 20);
    /// # Ok::<_, rune::support::Error>(())
    /// ```
    pub fn lookup_function<N>(&self, name: N) -> Result<Function, VmError>
    where
        N: ToTypeHash,
    {
        Ok(self.lookup_function_by_hash(name.to_type_hash())?)
    }

    /// Convert into an execution.
    pub(crate) fn into_execution(self) -> VmExecution<Self> {
        VmExecution::new(self)
    }

    /// Run the given vm to completion.
    ///
    /// If any async instructions are encountered, this will error.
    pub fn complete(self) -> Result<Value, VmError> {
        self.into_execution().complete().into_result()
    }

    /// Run the given vm to completion with support for async functions.
    pub async fn async_complete(self) -> Result<Value, VmError> {
        self.into_execution().async_complete().await.into_result()
    }

    /// Call the function identified by the given name.
    ///
    /// Computing the function hash from the name can be a bit costly, so it's
    /// worth noting that it can be precalculated:
    ///
    /// ```
    /// use rune::Hash;
    ///
    /// let name = Hash::type_hash(["main"]);
    /// ```
    ///
    /// # Examples
    ///
    /// ```,no_run
    /// use rune::{Context, Unit};
    /// use std::sync::Arc;
    ///
    /// let context = Context::with_default_modules()?;
    /// let context = Arc::new(context.runtime()?);
    ///
    /// // Normally the unit would be created by compiling some source,
    /// // and since this one is empty it won't do anything.
    /// let unit = Arc::new(Unit::default());
    ///
    /// let mut vm = rune::Vm::new(context, unit);
    ///
    /// let output = vm.execute(["main"], (33i64,))?.complete().into_result()?;
    /// let output: i64 = rune::from_value(output)?;
    ///
    /// println!("output: {}", output);
    /// # Ok::<_, rune::support::Error>(())
    /// ```
    ///
    /// You can use a `Vec<Value>` to provide a variadic collection of
    /// arguments.
    ///
    /// ```,no_run
    /// use rune::{Context, Unit};
    /// use std::sync::Arc;
    ///
    /// let context = Context::with_default_modules()?;
    /// let context = Arc::new(context.runtime()?);
    ///
    /// // Normally the unit would be created by compiling some source,
    /// // and since this one is empty it won't do anything.
    /// let unit = Arc::new(Unit::default());
    ///
    /// let mut vm = rune::Vm::new(context, unit);
    ///
    /// let mut args = Vec::new();
    /// args.push(rune::to_value(1u32)?);
    /// args.push(rune::to_value(String::from("Hello World"))?);
    ///
    /// let output = vm.execute(["main"], args)?.complete().into_result()?;
    /// let output: i64 = rune::from_value(output)?;
    ///
    /// println!("output: {}", output);
    /// # Ok::<_, rune::support::Error>(())
    /// ```
    pub fn execute<A, N>(&mut self, name: N, args: A) -> Result<VmExecution<&mut Self>, VmError>
    where
        N: ToTypeHash,
        A: Args,
    {
        self.set_entrypoint(name, args.count())?;
        args.into_stack(&mut self.stack).into_result()?;
        Result::Ok(VmExecution::new(self))
    }

    /// An `execute` variant that returns an execution which implements
    /// [`Send`], allowing it to be sent and executed on a different thread.
    ///
    /// This is accomplished by preventing values escaping from being
    /// non-exclusively sent with the execution or escaping the execution. We
    /// only support encoding arguments which themselves are `Send`.
    pub fn send_execute<A, N>(mut self, name: N, args: A) -> Result<VmSendExecution, VmError>
    where
        N: ToTypeHash,
        A: Send + Args,
    {
        // Safety: make sure the stack is clear, preventing any values from
        // being sent along with the virtual machine.
        self.stack.clear();

        self.set_entrypoint(name, args.count())?;
        args.into_stack(&mut self.stack).into_result()?;
        Result::Ok(VmSendExecution(VmExecution::new(self)))
    }

    /// Call the given function immediately, returning the produced value.
    ///
    /// This function permits for using references since it doesn't defer its
    /// execution.
    ///
    /// # Panics
    ///
    /// If any of the arguments passed in are references, and that references is
    /// captured somewhere in the call as [`Mut<T>`] or [`Ref<T>`]
    /// this call will panic as we are trying to free the metadata relatedc to
    /// the reference.
    ///
    /// [`Mut<T>`]: crate::runtime::Mut
    /// [`Ref<T>`]: crate::runtime::Ref
    pub fn call<A, N>(&mut self, name: N, args: A) -> Result<Value, VmError>
    where
        N: ToTypeHash,
        A: GuardedArgs,
    {
        self.set_entrypoint(name, args.count())?;

        // Safety: We hold onto the guard until the vm has completed and
        // `VmExecution` will clear the stack before this function returns.
        // Erronously or not.
        let guard = unsafe { args.unsafe_into_stack(&mut self.stack).into_result()? };

        let value = {
            // Clearing the stack here on panics has safety implications - see
            // above.
            let vm = ClearStack(self);
            VmExecution::new(&mut *vm.0).complete().into_result()?
        };

        // Note: this might panic if something in the vm is holding on to a
        // reference of the value. We should prevent it from being possible to
        // take any owned references to values held by this.
        drop(guard);
        Result::Ok(value)
    }

    /// Call the given function immediately asynchronously, returning the
    /// produced value.
    ///
    /// This function permits for using references since it doesn't defer its
    /// execution.
    ///
    /// # Panics
    ///
    /// If any of the arguments passed in are references, and that references is
    /// captured somewhere in the call as [`Mut<T>`] or [`Ref<T>`]
    /// this call will panic as we are trying to free the metadata relatedc to
    /// the reference.
    ///
    /// [`Mut<T>`]: crate::runtime::Mut
    /// [`Ref<T>`]: crate::runtime::Ref
    pub async fn async_call<A, N>(&mut self, name: N, args: A) -> Result<Value, VmError>
    where
        N: ToTypeHash,
        A: GuardedArgs,
    {
        self.set_entrypoint(name, args.count())?;

        // Safety: We hold onto the guard until the vm has completed and
        // `VmExecution` will clear the stack before this function returns.
        // Erronously or not.
        let guard = unsafe { args.unsafe_into_stack(&mut self.stack).into_result()? };

        let value = {
            // Clearing the stack here on panics has safety implications - see
            // above.
            let vm = ClearStack(self);
            VmExecution::new(&mut *vm.0)
                .async_complete()
                .await
                .into_result()?
        };

        // Note: this might panic if something in the vm is holding on to a
        // reference of the value. We should prevent it from being possible to
        // take any owned references to values held by this.
        drop(guard);
        Result::Ok(value)
    }

    /// Update the instruction pointer to match the function matching the given
    /// name and check that the number of argument matches.
    fn set_entrypoint<N>(&mut self, name: N, count: usize) -> Result<(), VmErrorKind>
    where
        N: ToTypeHash,
    {
        let hash = name.to_type_hash();

        let Some(info) = self.unit.function(hash) else {
            return Err(if let Some(item) = name.to_item()? {
                VmErrorKind::MissingEntry { hash, item }
            } else {
                VmErrorKind::MissingEntryHash { hash }
            });
        };

        let offset = match info {
            // NB: we ignore the calling convention.
            // everything is just async when called externally.
            UnitFn::Offset {
                offset,
                args: expected,
                ..
            } => {
                check_args(count, expected)?;
                offset
            }
            _ => {
                return Err(VmErrorKind::MissingFunction { hash });
            }
        };

        self.ip = offset;
        self.stack.clear();
        self.call_frames.clear();
        Ok(())
    }

    /// Helper function to call an instance function.
    #[inline(always)]
    pub(crate) fn call_instance_fn<H, A>(
        &mut self,
        target: Value,
        hash: H,
        args: A,
    ) -> VmResult<CallResult<()>>
    where
        H: ToTypeHash,
        A: GuardedArgs,
    {
        let count = args.count().wrapping_add(1);
        let type_hash = vm_try!(target.type_hash());
        let hash = Hash::associated_function(type_hash, hash.to_type_hash());

        if let Some(UnitFn::Offset {
            offset,
            call,
            args: expected,
        }) = self.unit.function(hash)
        {
            vm_try!(self.stack.push(target));
            // Safety: We hold onto the guard for the duration of this call.
            let _guard = unsafe { vm_try!(args.unsafe_into_stack(&mut self.stack)) };
            vm_try!(check_args(count, expected));
            vm_try!(self.call_offset_fn(offset, call, count));
            return VmResult::Ok(CallResult::Ok(()));
        }

        if let Some(handler) = self.context.function(hash) {
            vm_try!(self.stack.push(target));
            // Safety: We hold onto the guard for the duration of this call.
            let _guard = unsafe { vm_try!(args.unsafe_into_stack(&mut self.stack)) };
            vm_try!(handler(&mut self.stack, count));
            return VmResult::Ok(CallResult::Ok(()));
        }

        VmResult::Ok(CallResult::Unsupported(target))
    }

    /// Helper to call a field function.
    #[inline(always)]
    fn call_field_fn<N, A>(
        &mut self,
        protocol: Protocol,
        target: Value,
        name: N,
        args: A,
    ) -> VmResult<CallResult<()>>
    where
        N: IntoHash,
        A: GuardedArgs,
    {
        let count = args.count().wrapping_add(1);
        let hash = Hash::field_function(protocol, vm_try!(target.type_hash()), name);

        if let Some(handler) = self.context.function(hash) {
            vm_try!(self.stack.push(target));
            let _guard = unsafe { vm_try!(args.unsafe_into_stack(&mut self.stack)) };
            vm_try!(handler(&mut self.stack, count));
            return VmResult::Ok(CallResult::Ok(()));
        }

        VmResult::Ok(CallResult::Unsupported(target))
    }

    /// Helper to call an index function.
    #[inline(always)]
    fn call_index_fn<A>(
        &mut self,
        protocol: Protocol,
        target: Value,
        index: usize,
        args: A,
    ) -> VmResult<CallResult<()>>
    where
        A: GuardedArgs,
    {
        let count = args.count().wrapping_add(1);
        let hash = Hash::index_function(protocol, vm_try!(target.type_hash()), Hash::index(index));

        if let Some(handler) = self.context.function(hash) {
            vm_try!(self.stack.push(target));
            let _guard = unsafe { vm_try!(args.unsafe_into_stack(&mut self.stack)) };
            vm_try!(handler(&mut self.stack, count));
            return VmResult::Ok(CallResult::Ok(()));
        }

        VmResult::Ok(CallResult::Unsupported(target))
    }

    fn internal_boolean_ops(
        &mut self,
        int_op: fn(i64, i64) -> bool,
        float_op: fn(f64, f64) -> bool,
        match_ordering: fn(Ordering) -> bool,
        lhs: InstAddress,
        rhs: InstAddress,
    ) -> VmResult<()> {
        let rhs = vm_try!(self.stack.address(rhs));
        let lhs = vm_try!(self.stack.address(lhs));

        let out = match (lhs, rhs) {
            (Value::Integer(lhs), Value::Integer(rhs)) => int_op(lhs, rhs),
            (Value::Float(lhs), Value::Float(rhs)) => float_op(lhs, rhs),
            (lhs, rhs) => {
                let ordering = vm_try!(Value::partial_cmp_with(&lhs, &rhs, self));

                match ordering {
                    Some(ordering) => match_ordering(ordering),
                    None => false,
                }
            }
        };

        vm_try!(self.stack.push(Value::from(out)));
        VmResult::Ok(())
    }

    /// Push a new call frame.
    ///
    /// This will cause the `args` number of elements on the stack to be
    /// associated and accessible to the new call frame.
    #[tracing::instrument(skip(self), fields(call_frames = self.call_frames.len(), stack_bottom = self.stack.stack_bottom(), stack = self.stack.len(), self.ip))]
    pub(crate) fn push_call_frame(
        &mut self,
        ip: usize,
        args: usize,
        isolated: bool,
    ) -> Result<(), VmErrorKind> {
        tracing::trace!("pushing call frame");

        let stack_bottom = self.stack.swap_stack_bottom(args)?;
        let ip = replace(&mut self.ip, ip);

        let frame = CallFrame {
            ip,
            stack_bottom,
            isolated,
        };

        self.call_frames.try_push(frame)?;
        Ok(())
    }

    /// Pop a call frame from an internal call, which needs the current stack
    /// pointer to be returned and does not check for context isolation through
    /// [`CallFrame::isolated`].
    #[tracing::instrument(skip(self), fields(call_frames = self.call_frames.len(), stack_bottom = self.stack.stack_bottom(), stack = self.stack.len(), self.ip))]
    pub(crate) fn pop_call_frame_from_call(&mut self) -> Result<Option<usize>, VmErrorKind> {
        tracing::trace!("popping call frame from call");

        let Some(frame) = self.call_frames.pop() else {
            return Ok(None);
        };

        tracing::trace!(?frame);
        self.stack.pop_stack_top(frame.stack_bottom)?;
        Ok(Some(replace(&mut self.ip, frame.ip)))
    }

    /// Pop a call frame and return it.
    #[tracing::instrument(skip(self), fields(call_frames = self.call_frames.len(), stack_bottom = self.stack.stack_bottom(), stack = self.stack.len(), self.ip))]
    pub(crate) fn pop_call_frame(&mut self) -> Result<bool, VmErrorKind> {
        tracing::trace!("popping call frame");

        let Some(frame) = self.call_frames.pop() else {
            self.stack.check_stack_top()?;
            return Ok(true);
        };

        tracing::trace!(?frame);
        self.stack.pop_stack_top(frame.stack_bottom)?;
        self.ip = frame.ip;
        Ok(frame.isolated)
    }

    /// Implementation of getting a string index on an object-like type.
    fn try_object_like_index_get(target: &Value, field: &str) -> VmResult<Option<Value>> {
        let value = match &target {
            Value::Object(target) => vm_try!(target.borrow_ref()).get(field).cloned(),
            Value::Struct(target) => vm_try!(target.borrow_ref()).get(field).cloned(),
            Value::Variant(variant) => match vm_try!(variant.borrow_ref()).data() {
                VariantData::Struct(target) => target.get(field).cloned(),
                _ => return VmResult::Ok(None),
            },
            _ => return VmResult::Ok(None),
        };

        let value = match value {
            Some(value) => value,
            None => {
                return err(VmErrorKind::MissingField {
                    target: vm_try!(target.type_info()),
                    field: vm_try!(field.try_to_owned()),
                });
            }
        };

        VmResult::Ok(Some(value))
    }

    /// Implementation of getting a string index on an object-like type.
    fn try_tuple_like_index_get(target: &Value, index: usize) -> VmResult<Option<Value>> {
        let value = match target {
            Value::EmptyTuple => None,
            Value::Tuple(tuple) => vm_try!(tuple.borrow_ref()).get(index).cloned(),
            Value::Vec(vec) => vm_try!(vec.borrow_ref()).get(index).cloned(),
            Value::Result(result) => {
                let result = vm_try!(result.borrow_ref());

                match &*result {
                    Result::Ok(value) if index == 0 => Some(value.clone()),
                    Result::Err(value) if index == 0 => Some(value.clone()),
                    _ => None,
                }
            }
            Value::Option(option) => {
                let option = vm_try!(option.borrow_ref());

                match &*option {
                    Some(value) if index == 0 => Some(value.clone()),
                    _ => None,
                }
            }
            Value::GeneratorState(state) => {
                use crate::runtime::GeneratorState::*;
                let state = vm_try!(state.borrow_ref());

                match &*state {
                    Yielded(value) if index == 0 => Some(value.clone()),
                    Complete(value) if index == 0 => Some(value.clone()),
                    _ => None,
                }
            }
            Value::TupleStruct(tuple_struct) => {
                let tuple_struct = vm_try!(tuple_struct.borrow_ref());
                tuple_struct.data().get(index).cloned()
            }
            Value::Variant(variant) => {
                let variant = vm_try!(variant.borrow_ref());

                match variant.data() {
                    VariantData::Tuple(tuple) => tuple.get(index).cloned(),
                    _ => return VmResult::Ok(None),
                }
            }
            _ => return VmResult::Ok(None),
        };

        let Some(value) = value else {
            return err(VmErrorKind::MissingIndexInteger {
                target: vm_try!(target.type_info()),
                index: VmIntegerRepr::from(index),
            });
        };

        VmResult::Ok(Some(value))
    }

    /// Implementation of getting a mutable value out of a tuple-like value.
    fn try_tuple_like_index_get_mut(
        target: &Value,
        index: usize,
    ) -> VmResult<Option<BorrowMut<'_, Value>>> {
        let value = match target {
            Value::EmptyTuple => None,
            Value::Tuple(tuple) => {
                let tuple = vm_try!(tuple.borrow_mut());

                BorrowMut::try_map(tuple, |tuple| tuple.get_mut(index))
            }
            Value::Vec(vec) => {
                let vec = vm_try!(vec.borrow_mut());

                BorrowMut::try_map(vec, |vec| vec.get_mut(index))
            }
            Value::Result(result) => {
                let result = vm_try!(result.borrow_mut());

                BorrowMut::try_map(result, |result| match result {
                    Result::Ok(value) if index == 0 => Some(value),
                    Result::Err(value) if index == 0 => Some(value),
                    _ => None,
                })
            }
            Value::Option(option) => {
                let option = vm_try!(option.borrow_mut());

                BorrowMut::try_map(option, |option| match option {
                    Some(value) if index == 0 => Some(value),
                    _ => None,
                })
            }
            Value::GeneratorState(state) => {
                use crate::runtime::GeneratorState::*;
                let state = vm_try!(state.borrow_mut());

                BorrowMut::try_map(state, |state| match state {
                    Yielded(value) if index == 0 => Some(value),
                    Complete(value) if index == 0 => Some(value),
                    _ => None,
                })
            }
            Value::TupleStruct(tuple_struct) => {
                let tuple_struct = vm_try!(tuple_struct.borrow_mut());

                BorrowMut::try_map(tuple_struct, |tuple_struct| tuple_struct.get_mut(index))
            }
            Value::Variant(variant) => {
                let variant = vm_try!(variant.borrow_mut());

                BorrowMut::try_map(variant, |variant| match variant.data_mut() {
                    VariantData::Tuple(tuple) => tuple.get_mut(index),
                    _ => None,
                })
            }
            _ => return VmResult::Ok(None),
        };

        let Some(value) = value else {
            return err(VmErrorKind::MissingIndexInteger {
                target: vm_try!(target.type_info()),
                index: VmIntegerRepr::from(index),
            });
        };

        VmResult::Ok(Some(value))
    }

    /// Implementation of getting a mutable string index on an object-like type.
    fn try_object_like_index_get_mut<'a>(
        target: &'a Value,
        field: &str,
    ) -> VmResult<Option<BorrowMut<'a, Value>>> {
        let value = match &target {
            Value::Object(target) => {
                let target = vm_try!(target.borrow_mut());
                BorrowMut::try_map(target, |target| target.get_mut(field))
            }
            Value::Struct(target) => {
                let target = vm_try!(target.borrow_mut());
                BorrowMut::try_map(target, |target| target.get_mut(field))
            }
            Value::Variant(target) => BorrowMut::try_map(vm_try!(target.borrow_mut()), |target| {
                match target.data_mut() {
                    VariantData::Struct(st) => st.get_mut(field),
                    _ => None,
                }
            }),
            _ => return VmResult::Ok(None),
        };

        let value = match value {
            Some(value) => value,
            None => {
                return err(VmErrorKind::MissingField {
                    target: vm_try!(target.type_info()),
                    field: vm_try!(field.try_to_owned()),
                });
            }
        };

        VmResult::Ok(Some(value))
    }

    /// Implementation of getting a string index on an object-like type.
    fn try_tuple_like_index_set(target: &Value, index: usize, value: Value) -> VmResult<bool> {
        match target {
            Value::EmptyTuple => VmResult::Ok(false),
            Value::Tuple(tuple) => {
                let mut tuple = vm_try!(tuple.borrow_mut());

                if let Some(target) = tuple.get_mut(index) {
                    *target = value;
                    return VmResult::Ok(true);
                }

                VmResult::Ok(false)
            }
            Value::Vec(vec) => {
                let mut vec = vm_try!(vec.borrow_mut());

                if let Some(target) = vec.get_mut(index) {
                    *target = value;
                    return VmResult::Ok(true);
                }

                VmResult::Ok(false)
            }
            Value::Result(result) => {
                let mut result = vm_try!(result.borrow_mut());

                let target = match &mut *result {
                    Result::Ok(ok) if index == 0 => ok,
                    Result::Err(err) if index == 1 => err,
                    _ => return VmResult::Ok(false),
                };

                *target = value;
                VmResult::Ok(true)
            }
            Value::Option(option) => {
                let mut option = vm_try!(option.borrow_mut());

                let target = match &mut *option {
                    Some(some) if index == 0 => some,
                    _ => return VmResult::Ok(false),
                };

                *target = value;
                VmResult::Ok(true)
            }
            Value::TupleStruct(tuple_struct) => {
                let mut tuple_struct = vm_try!(tuple_struct.borrow_mut());

                if let Some(target) = tuple_struct.get_mut(index) {
                    *target = value;
                    return VmResult::Ok(true);
                }

                VmResult::Ok(false)
            }
            Value::Variant(variant) => {
                let mut variant = vm_try!(variant.borrow_mut());

                if let VariantData::Tuple(data) = variant.data_mut() {
                    if let Some(target) = data.get_mut(index) {
                        *target = value;
                        return VmResult::Ok(true);
                    }
                }

                VmResult::Ok(false)
            }
            _ => VmResult::Ok(false),
        }
    }

    /// Implementation of getting a string index on an object-like type.
    fn try_object_slot_index_get(
        &mut self,
        target: Value,
        string_slot: usize,
    ) -> VmResult<CallResult<Value>> {
        let index = vm_try!(self.unit.lookup_string(string_slot));

        match target {
            Value::Object(object) => {
                let object = vm_try!(object.borrow_ref());

                if let Some(value) = object.get(index.as_str()) {
                    return VmResult::Ok(CallResult::Ok(value.clone()));
                }
            }
            Value::Struct(typed_object) => {
                let typed_object = vm_try!(typed_object.borrow_ref());

                if let Some(value) = typed_object.get(index.as_str()) {
                    return VmResult::Ok(CallResult::Ok(value.clone()));
                }
            }
            Value::Variant(variant) => {
                let variant = vm_try!(variant.borrow_ref());

                if let VariantData::Struct(data) = variant.data() {
                    if let Some(value) = data.get(index.as_str()) {
                        return VmResult::Ok(CallResult::Ok(value.clone()));
                    }
                }
            }
            target => {
                let hash = index.hash();

                return VmResult::Ok(
                    match vm_try!(self.call_field_fn(Protocol::GET, target, hash, ())) {
                        CallResult::Ok(()) => CallResult::Ok(vm_try!(self.stack.pop())),
                        CallResult::Unsupported(target) => CallResult::Unsupported(target),
                    },
                );
            }
        }

        err(VmErrorKind::ObjectIndexMissing { slot: string_slot })
    }

    fn try_object_slot_index_set(
        &mut self,
        target: Value,
        string_slot: usize,
        value: Value,
    ) -> VmResult<CallResult<()>> {
        let field = vm_try!(self.unit.lookup_string(string_slot));

        VmResult::Ok(match target {
            Value::Object(object) => {
                let mut object = vm_try!(object.borrow_mut());
                let key = vm_try!(field.as_str().try_to_owned());
                vm_try!(object.insert(key, value));
                return VmResult::Ok(CallResult::Ok(()));
            }
            Value::Struct(typed_object) => {
                let mut typed_object = vm_try!(typed_object.borrow_mut());

                if let Some(v) = typed_object.get_mut(field.as_str()) {
                    *v = value;
                    return VmResult::Ok(CallResult::Ok(()));
                }

                return err(VmErrorKind::MissingField {
                    target: typed_object.type_info(),
                    field: vm_try!(field.as_str().try_to_owned()),
                });
            }
            Value::Variant(variant) => {
                let mut variant = vm_try!(variant.borrow_mut());

                if let VariantData::Struct(data) = variant.data_mut() {
                    if let Some(v) = data.get_mut(field.as_str()) {
                        *v = value;
                        return VmResult::Ok(CallResult::Ok(()));
                    }
                }

                return err(VmErrorKind::MissingField {
                    target: variant.type_info(),
                    field: vm_try!(field.as_str().try_to_owned()),
                });
            }
            target => {
                let hash = field.hash();

                match vm_try!(self.call_field_fn(Protocol::SET, target, hash, (value,))) {
                    CallResult::Ok(()) => {
                        vm_try!(<()>::from_value(vm_try!(self.stack.pop())));
                        CallResult::Ok(())
                    }
                    result => result,
                }
            }
        })
    }

    fn on_tuple<F, O>(&mut self, ty: TypeCheck, value: &Value, f: F) -> VmResult<Option<O>>
    where
        F: FnOnce(&[Value]) -> O,
    {
        VmResult::Ok(match (ty, value) {
            (TypeCheck::EmptyTuple, Value::EmptyTuple) => Some(f(&[])),
            (TypeCheck::Tuple, Value::Tuple(tuple)) => Some(f(&vm_try!(tuple.borrow_ref()))),
            (TypeCheck::Vec, Value::Vec(vec)) => Some(f(&vm_try!(vec.borrow_ref()))),
            (TypeCheck::Result(v), Value::Result(result)) => {
                let result = vm_try!(result.borrow_ref());

                Some(match (v, &*result) {
                    (0, Result::Ok(ok)) => f(slice::from_ref(ok)),
                    (1, Result::Err(err)) => f(slice::from_ref(err)),
                    _ => return VmResult::Ok(None),
                })
            }
            (TypeCheck::Option(v), Value::Option(option)) => {
                let option = vm_try!(option.borrow_ref());

                Some(match (v, &*option) {
                    (0, Some(some)) => f(slice::from_ref(some)),
                    (1, None) => f(&[]),
                    _ => return VmResult::Ok(None),
                })
            }
            (TypeCheck::GeneratorState(v), Value::GeneratorState(state)) => {
                use crate::runtime::GeneratorState::*;
                let state = vm_try!(state.borrow_ref());

                Some(match (v, &*state) {
                    (0, Complete(complete)) => f(slice::from_ref(complete)),
                    (1, Yielded(yielded)) => f(slice::from_ref(yielded)),
                    _ => return VmResult::Ok(None),
                })
            }
            _ => None,
        })
    }

    /// Internal implementation of the instance check.
    fn as_op(&mut self, lhs: InstAddress, rhs: InstAddress) -> VmResult<Value> {
        let b = vm_try!(self.stack.address(rhs));
        let a = vm_try!(self.stack.address(lhs));

        let ty = match b {
            Value::Type(ty) => ty,
            _ => {
                return err(VmErrorKind::UnsupportedIs {
                    value: vm_try!(a.type_info()),
                    test_type: vm_try!(b.type_info()),
                });
            }
        };

        macro_rules! convert {
            ($from:ty, $value:ident, $ty:expr) => {
                match $ty.into_hash() {
                    runtime::static_type::FLOAT_TYPE_HASH => Value::Float($value as f64),
                    runtime::static_type::BYTE_TYPE_HASH => Value::Byte($value as u8),
                    runtime::static_type::INTEGER_TYPE_HASH => Value::Integer($value as i64),
                    ty => {
                        return err(VmErrorKind::UnsupportedAs {
                            value: <$from as TypeOf>::type_info(),
                            type_hash: ty,
                        });
                    }
                }
            };
        }

        VmResult::Ok(match a {
            Value::Integer(a) => convert!(i64, a, ty),
            Value::Float(a) => convert!(f64, a, ty),
            Value::Byte(a) => convert!(u8, a, ty),
            value => {
                return err(VmErrorKind::UnsupportedAs {
                    value: vm_try!(value.type_info()),
                    type_hash: ty.into_hash(),
                });
            }
        })
    }

    /// Internal implementation of the instance check.
    fn test_is_instance(&mut self, lhs: InstAddress, rhs: InstAddress) -> VmResult<bool> {
        let b = vm_try!(self.stack.address(rhs));
        let a = vm_try!(self.stack.address(lhs));

        let ty = match b {
            Value::Type(ty) => ty,
            _ => {
                return err(VmErrorKind::UnsupportedIs {
                    value: vm_try!(a.type_info()),
                    test_type: vm_try!(b.type_info()),
                });
            }
        };

        VmResult::Ok(vm_try!(a.type_hash()) == ty.into_hash())
    }

    fn internal_boolean_op(
        &mut self,
        bool_op: impl FnOnce(bool, bool) -> bool,
        op: &'static str,
        lhs: InstAddress,
        rhs: InstAddress,
    ) -> VmResult<()> {
        let rhs = vm_try!(self.stack.address(rhs));
        let lhs = vm_try!(self.stack.address(lhs));

        let out = match (lhs, rhs) {
            (Value::Bool(lhs), Value::Bool(rhs)) => bool_op(lhs, rhs),
            (lhs, rhs) => {
                return err(VmErrorKind::UnsupportedBinaryOperation {
                    op,
                    lhs: vm_try!(lhs.type_info()),
                    rhs: vm_try!(rhs.type_info()),
                });
            }
        };

        vm_try!(self.stack.push(Value::from(out)));
        VmResult::Ok(())
    }

    /// Construct a future from calling an async function.
    fn call_generator_fn(&mut self, offset: usize, args: usize) -> Result<(), VmErrorKind> {
        let stack = self.stack.drain(args)?.try_collect::<Stack>()?;
        let mut vm = Self::with_stack(self.context.clone(), self.unit.clone(), stack);
        vm.ip = offset;
        self.stack.push(Value::try_from(Generator::new(vm))?)?;
        Ok(())
    }

    /// Construct a stream from calling a function.
    fn call_stream_fn(&mut self, offset: usize, args: usize) -> Result<(), VmErrorKind> {
        let stack = self.stack.drain(args)?.try_collect::<Stack>()?;
        let mut vm = Self::with_stack(self.context.clone(), self.unit.clone(), stack);
        vm.ip = offset;
        self.stack.push(Value::try_from(Stream::new(vm))?)?;
        Ok(())
    }

    /// Construct a future from calling a function.
    fn call_async_fn(&mut self, offset: usize, args: usize) -> Result<(), VmErrorKind> {
        let stack = self.stack.drain(args)?.try_collect::<Stack>()?;
        let mut vm = Self::with_stack(self.context.clone(), self.unit.clone(), stack);
        vm.ip = offset;
        let mut execution = vm.into_execution();
        let future = Future::new(async move { execution.async_complete().await })?;
        self.stack.push(Value::try_from(future)?)?;
        Ok(())
    }

    /// Helper function to call the function at the given offset.
    fn call_offset_fn(
        &mut self,
        offset: usize,
        call: Call,
        args: usize,
    ) -> Result<bool, VmErrorKind> {
        let moved = match call {
            Call::Async => {
                self.call_async_fn(offset, args)?;
                false
            }
            Call::Immediate => {
                self.push_call_frame(offset, args, false)?;
                true
            }
            Call::Stream => {
                self.call_stream_fn(offset, args)?;
                false
            }
            Call::Generator => {
                self.call_generator_fn(offset, args)?;
                false
            }
        };

        Ok(moved)
    }

    fn internal_num_assign(
        &mut self,
        target: InstTarget,
        protocol: Protocol,
        error: fn() -> VmErrorKind,
        integer_op: fn(i64, i64) -> Option<i64>,
        float_op: fn(f64, f64) -> f64,
    ) -> VmResult<()> {
        let lhs;
        let mut guard;

        let fallback = match target_value!(self, target, guard, lhs) {
            TargetValue::Value(lhs, rhs) => match (lhs, rhs) {
                (Value::Integer(lhs), Value::Integer(rhs)) => {
                    let out = vm_try!(integer_op(*lhs, rhs).ok_or_else(error));
                    *lhs = out;
                    return VmResult::Ok(());
                }
                (Value::Float(lhs), Value::Float(rhs)) => {
                    let out = float_op(*lhs, rhs);
                    *lhs = out;
                    return VmResult::Ok(());
                }
                (lhs, rhs) => TargetFallback::Value(lhs.clone(), rhs),
            },
            TargetValue::Fallback(fallback) => fallback,
        };

        self.target_fallback_assign(fallback, protocol)
    }

    /// Execute a fallback operation.
    fn target_fallback_assign(
        &mut self,
        fallback: TargetFallback<'_>,
        protocol: Protocol,
    ) -> VmResult<()> {
        match fallback {
            TargetFallback::Value(lhs, rhs) => {
                if let CallResult::Unsupported(lhs) =
                    vm_try!(self.call_instance_fn(lhs, protocol, (&rhs,)))
                {
                    return err(VmErrorKind::UnsupportedBinaryOperation {
                        op: protocol.name,
                        lhs: vm_try!(lhs.type_info()),
                        rhs: vm_try!(rhs.type_info()),
                    });
                };

                vm_try!(<()>::from_value(vm_try!(self.stack.pop())));
                VmResult::Ok(())
            }
            TargetFallback::Field(lhs, hash, rhs) => {
                if let CallResult::Unsupported(lhs) =
                    vm_try!(self.call_field_fn(protocol, lhs.clone(), hash, (rhs,)))
                {
                    return err(VmErrorKind::UnsupportedObjectSlotIndexGet {
                        target: vm_try!(lhs.type_info()),
                    });
                }

                let value = vm_try!(self.stack.pop());
                vm_try!(<()>::from_value(value));
                VmResult::Ok(())
            }
            TargetFallback::Index(lhs, index, rhs) => {
                if let CallResult::Unsupported(lhs) =
                    vm_try!(self.call_index_fn(protocol, lhs.clone(), index, (&rhs,)))
                {
                    return err(VmErrorKind::UnsupportedTupleIndexGet {
                        target: vm_try!(lhs.type_info()),
                        index,
                    });
                }

                vm_try!(<()>::from_value(vm_try!(self.stack.pop())));
                VmResult::Ok(())
            }
        }
    }

    /// Internal impl of a numeric operation.
    fn internal_num(
        &mut self,
        protocol: Protocol,
        error: fn() -> VmErrorKind,
        integer_op: fn(i64, i64) -> Option<i64>,
        float_op: fn(f64, f64) -> f64,
        lhs: InstAddress,
        rhs: InstAddress,
    ) -> VmResult<()> {
        let rhs = vm_try!(self.stack.address(rhs));
        let lhs = vm_try!(self.stack.address(lhs));

        let (lhs, rhs) = match (lhs, rhs) {
            (Value::Integer(lhs), Value::Integer(rhs)) => {
                vm_try!(self
                    .stack
                    .push(Value::from(vm_try!(integer_op(lhs, rhs).ok_or_else(error)))));
                return VmResult::Ok(());
            }
            (Value::Float(lhs), Value::Float(rhs)) => {
                vm_try!(self.stack.push(Value::from(float_op(lhs, rhs))));
                return VmResult::Ok(());
            }
            (lhs, rhs) => (lhs, rhs),
        };

        if let CallResult::Unsupported(lhs) = vm_try!(self.call_instance_fn(lhs, protocol, (&rhs,)))
        {
            return err(VmErrorKind::UnsupportedBinaryOperation {
                op: protocol.name,
                lhs: vm_try!(lhs.type_info()),
                rhs: vm_try!(rhs.type_info()),
            });
        }

        VmResult::Ok(())
    }

    /// Internal impl of a numeric operation.
    fn internal_infallible_bitwise(
        &mut self,
        protocol: Protocol,
        integer_op: fn(i64, i64) -> i64,
        lhs: InstAddress,
        rhs: InstAddress,
    ) -> VmResult<()> {
        let rhs = vm_try!(self.stack.address(rhs));
        let lhs = vm_try!(self.stack.address(lhs));

        let (lhs, rhs) = match (lhs, rhs) {
            (Value::Integer(lhs), Value::Integer(rhs)) => {
                vm_try!(self.stack.push(Value::from(integer_op(lhs, rhs))));
                return VmResult::Ok(());
            }
            (lhs, rhs) => (lhs, rhs),
        };

        if let CallResult::Unsupported(lhs) = vm_try!(self.call_instance_fn(lhs, protocol, (&rhs,)))
        {
            return err(VmErrorKind::UnsupportedBinaryOperation {
                op: protocol.name,
                lhs: vm_try!(lhs.type_info()),
                rhs: vm_try!(rhs.type_info()),
            });
        }

        VmResult::Ok(())
    }

    /// Internal impl of a numeric operation.
    fn internal_infallible_bitwise_bool(
        &mut self,
        protocol: Protocol,
        integer_op: fn(i64, i64) -> i64,
        bool_op: fn(bool, bool) -> bool,
        lhs: InstAddress,
        rhs: InstAddress,
    ) -> VmResult<()> {
        let rhs = vm_try!(self.stack.address(rhs));
        let lhs = vm_try!(self.stack.address(lhs));

        let (lhs, rhs) = match (lhs, rhs) {
            (Value::Integer(lhs), Value::Integer(rhs)) => {
                vm_try!(self.stack.push(Value::from(integer_op(lhs, rhs))));
                return VmResult::Ok(());
            }
            (Value::Bool(lhs), Value::Bool(rhs)) => {
                vm_try!(self.stack.push(Value::from(bool_op(lhs, rhs))));
                return VmResult::Ok(());
            }
            (lhs, rhs) => (lhs, rhs),
        };

        if let CallResult::Unsupported(lhs) = vm_try!(self.call_instance_fn(lhs, protocol, (&rhs,)))
        {
            return err(VmErrorKind::UnsupportedBinaryOperation {
                op: protocol.name,
                lhs: vm_try!(lhs.type_info()),
                rhs: vm_try!(rhs.type_info()),
            });
        }

        VmResult::Ok(())
    }

    fn internal_infallible_bitwise_assign(
        &mut self,
        target: InstTarget,
        protocol: Protocol,
        integer_op: fn(&mut i64, i64),
    ) -> VmResult<()> {
        let lhs;
        let mut guard;

        let fallback = match target_value!(self, target, guard, lhs) {
            TargetValue::Value(lhs, rhs) => match (lhs, rhs) {
                (Value::Integer(lhs), Value::Integer(rhs)) => {
                    integer_op(lhs, rhs);
                    return VmResult::Ok(());
                }
                (lhs, rhs) => TargetFallback::Value(lhs.clone(), rhs),
            },
            TargetValue::Fallback(fallback) => fallback,
        };

        self.target_fallback_assign(fallback, protocol)
    }

    fn internal_bitwise(
        &mut self,
        protocol: Protocol,
        error: fn() -> VmErrorKind,
        integer_op: fn(i64, i64) -> Option<i64>,
        lhs: InstAddress,
        rhs: InstAddress,
    ) -> VmResult<()> {
        let rhs = vm_try!(self.stack.address(rhs));
        let lhs = vm_try!(self.stack.address(lhs));

        let (lhs, rhs) = match (lhs, rhs) {
            (Value::Integer(lhs), Value::Integer(rhs)) => {
                let integer = vm_try!(integer_op(lhs, rhs).ok_or_else(error));
                vm_try!(self.stack.push(Value::from(integer)));
                return VmResult::Ok(());
            }
            (lhs, rhs) => (lhs, rhs),
        };

        if let CallResult::Unsupported(lhs) = vm_try!(self.call_instance_fn(lhs, protocol, (&rhs,)))
        {
            return err(VmErrorKind::UnsupportedBinaryOperation {
                op: protocol.name,
                lhs: vm_try!(lhs.type_info()),
                rhs: vm_try!(rhs.type_info()),
            });
        }

        VmResult::Ok(())
    }

    fn internal_bitwise_assign(
        &mut self,
        target: InstTarget,
        protocol: Protocol,
        error: fn() -> VmErrorKind,
        integer_op: fn(i64, i64) -> Option<i64>,
    ) -> VmResult<()> {
        let lhs;
        let mut guard;

        let fallback = match target_value!(self, target, guard, lhs) {
            TargetValue::Value(lhs, rhs) => match (lhs, rhs) {
                (Value::Integer(lhs), Value::Integer(rhs)) => {
                    let out = vm_try!(integer_op(*lhs, rhs).ok_or_else(error));
                    *lhs = out;
                    return VmResult::Ok(());
                }
                (lhs, rhs) => TargetFallback::Value(lhs.clone(), rhs),
            },
            TargetValue::Fallback(fallback) => fallback,
        };

        self.target_fallback_assign(fallback, protocol)
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_await(&mut self) -> VmResult<Shared<Future>> {
        vm_try!(self.stack.pop()).into_future()
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_select(&mut self, len: usize) -> VmResult<Option<Select>> {
        let futures = futures_util::stream::FuturesUnordered::new();

        for (branch, value) in vm_try!(self.stack.drain(len)).enumerate() {
            let future = vm_try!(vm_try!(value.into_future()).into_mut());

            if !future.is_completed() {
                futures.push(SelectFuture::new(branch, future));
            }
        }

        // NB: nothing to poll.
        if futures.is_empty() {
            vm_try!(self.stack.push(Value::from(())));
            return VmResult::Ok(None);
        }

        VmResult::Ok(Some(Select::new(futures)))
    }

    /// Pop a number of values from the stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_popn(&mut self, n: usize) -> VmResult<()> {
        vm_try!(self.stack.popn(n));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_push(&mut self, value: InstValue) -> VmResult<()> {
        vm_try!(self.stack.push(value.into_value()));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_pop(&mut self) -> VmResult<()> {
        vm_try!(self.stack.pop());
        VmResult::Ok(())
    }

    /// pop-and-jump-if-not instruction.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_pop_and_jump_if_not(&mut self, count: usize, jump: usize) -> VmResult<()> {
        if vm_try!(vm_try!(self.stack.pop()).into_bool()) {
            return VmResult::Ok(());
        }

        vm_try!(self.stack.popn(count));
        self.ip = vm_try!(self.unit.translate(jump));
        VmResult::Ok(())
    }

    /// Pop a number of values from the stack, while preserving the top of the
    /// stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_clean(&mut self, n: usize) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());
        vm_try!(self.op_popn(n));
        vm_try!(self.stack.push(value));
        VmResult::Ok(())
    }

    /// Copy a value from a position relative to the top of the stack, to the
    /// top of the stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_copy(&mut self, offset: usize) -> VmResult<()> {
        let value = vm_try!(self.stack.at_offset(offset)).clone();
        vm_try!(self.stack.push(value));
        VmResult::Ok(())
    }

    /// Move a value from a position relative to the top of the stack, to the
    /// top of the stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_move(&mut self, offset: usize) -> VmResult<()> {
        let value = vm_try!(self.stack.at_offset(offset)).clone();
        vm_try!(self.stack.push(vm_try!(value.take())));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_drop(&mut self, offset: usize) -> VmResult<()> {
        let _ = vm_try!(self.stack.at_offset(offset));
        VmResult::Ok(())
    }

    /// Copy a value from a position relative to the top of the stack, to the
    /// top of the stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_replace(&mut self, offset: usize) -> VmResult<()> {
        let mut value = vm_try!(self.stack.pop());
        let stack_value = vm_try!(self.stack.at_offset_mut(offset));
        swap(stack_value, &mut value);
        VmResult::Ok(())
    }

    /// Swap two values on the stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_swap(&mut self, a: usize, b: usize) -> VmResult<()> {
        vm_try!(self.stack.swap(a, b));
        VmResult::Ok(())
    }

    /// Perform a jump operation.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_jump(&mut self, jump: usize) -> VmResult<()> {
        self.ip = vm_try!(self.unit.translate(jump));
        VmResult::Ok(())
    }

    /// Perform a conditional jump operation.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_jump_if(&mut self, jump: usize) -> VmResult<()> {
        if vm_try!(vm_try!(self.stack.pop()).into_bool()) {
            self.ip = vm_try!(self.unit.translate(jump));
        }

        VmResult::Ok(())
    }

    /// Perform a conditional jump operation. Pops the stack if the jump is
    /// not performed.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_jump_if_or_pop(&mut self, jump: usize) -> VmResult<()> {
        if vm_try!(vm_try!(self.stack.last()).as_bool()) {
            self.ip = vm_try!(self.unit.translate(jump));
        } else {
            vm_try!(self.stack.pop());
        }

        VmResult::Ok(())
    }

    /// Perform a conditional jump operation. Pops the stack if the jump is
    /// not performed.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_jump_if_not_or_pop(&mut self, jump: usize) -> VmResult<()> {
        if !vm_try!(vm_try!(self.stack.last()).as_bool()) {
            self.ip = vm_try!(self.unit.translate(jump));
        } else {
            vm_try!(self.stack.pop());
        }

        VmResult::Ok(())
    }

    /// Perform a branch-conditional jump operation.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_jump_if_branch(&mut self, branch: i64, jump: usize) -> VmResult<()> {
        if let Some(Value::Integer(current)) = self.stack.peek() {
            if *current == branch {
                self.ip = vm_try!(self.unit.translate(jump));
                vm_try!(self.stack.pop());
            }
        }

        VmResult::Ok(())
    }

    /// Construct a new vec.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_vec(&mut self, count: usize) -> VmResult<()> {
        let vec = Vec::from(vm_try!(vm_try!(self.stack.pop_sequence(count))));
        vm_try!(self.stack.push(Value::from(vm_try!(Shared::new(vec)))));
        VmResult::Ok(())
    }

    /// Construct a new tuple.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_tuple(&mut self, count: usize) -> VmResult<()> {
        let tuple = vm_try!(vm_try!(self.stack.pop_sequence(count)));
        vm_try!(self
            .stack
            .push(vm_try!(Value::try_from(vm_try!(OwnedTuple::try_from(
                tuple
            ))))));
        VmResult::Ok(())
    }

    /// Construct a new tuple with a fixed number of arguments.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_tuple_n(&mut self, args: &[InstAddress]) -> VmResult<()> {
        let mut tuple = vec![Value::EmptyTuple; args.len()];

        for (n, arg) in args.iter().enumerate().rev() {
            tuple[n] = vm_try!(self.stack.address(*arg));
        }

        vm_try!(self
            .stack
            .push(vm_try!(Value::try_from(vm_try!(OwnedTuple::try_from(
                tuple
            ))))));

        VmResult::Ok(())
    }

    /// Push the tuple that is on top of the stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_push_tuple(&mut self) -> VmResult<()> {
        let tuple = vm_try!(vm_try!(self.stack.pop()).into_tuple());
        vm_try!(self
            .stack
            .extend(vm_try!(tuple.borrow_ref()).iter().cloned()));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_not(&mut self) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        let value = match value {
            Value::Bool(value) => Value::from(!value),
            Value::Integer(value) => Value::from(!value),
            other => {
                let operand = vm_try!(other.type_info());
                return err(VmErrorKind::UnsupportedUnaryOperation { op: "!", operand });
            }
        };

        vm_try!(self.stack.push(value));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_neg(&mut self) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        let value = match value {
            Value::Float(value) => Value::from(-value),
            Value::Integer(value) => Value::from(-value),
            other => {
                let operand = vm_try!(other.type_info());
                return err(VmErrorKind::UnsupportedUnaryOperation { op: "-", operand });
            }
        };

        vm_try!(self.stack.push(value));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_op(&mut self, op: InstOp, lhs: InstAddress, rhs: InstAddress) -> VmResult<()> {
        match op {
            InstOp::Add => {
                vm_try!(self.internal_num(
                    Protocol::ADD,
                    || VmErrorKind::Overflow,
                    i64::checked_add,
                    ops::Add::add,
                    lhs,
                    rhs,
                ));
            }
            InstOp::Sub => {
                vm_try!(self.internal_num(
                    Protocol::SUB,
                    || VmErrorKind::Underflow,
                    i64::checked_sub,
                    ops::Sub::sub,
                    lhs,
                    rhs,
                ));
            }
            InstOp::Mul => {
                vm_try!(self.internal_num(
                    Protocol::MUL,
                    || VmErrorKind::Overflow,
                    i64::checked_mul,
                    ops::Mul::mul,
                    lhs,
                    rhs,
                ));
            }
            InstOp::Div => {
                vm_try!(self.internal_num(
                    Protocol::DIV,
                    || VmErrorKind::DivideByZero,
                    i64::checked_div,
                    ops::Div::div,
                    lhs,
                    rhs,
                ));
            }
            InstOp::Rem => {
                vm_try!(self.internal_num(
                    Protocol::REM,
                    || VmErrorKind::DivideByZero,
                    i64::checked_rem,
                    ops::Rem::rem,
                    lhs,
                    rhs,
                ));
            }
            InstOp::BitAnd => {
                use ops::BitAnd as _;
                vm_try!(self.internal_infallible_bitwise_bool(
                    Protocol::BIT_AND,
                    i64::bitand,
                    bool::bitand,
                    lhs,
                    rhs,
                ));
            }
            InstOp::BitXor => {
                use ops::BitXor as _;
                vm_try!(self.internal_infallible_bitwise_bool(
                    Protocol::BIT_XOR,
                    i64::bitxor,
                    bool::bitxor,
                    lhs,
                    rhs,
                ));
            }
            InstOp::BitOr => {
                use ops::BitOr as _;
                vm_try!(self.internal_infallible_bitwise_bool(
                    Protocol::BIT_OR,
                    i64::bitor,
                    bool::bitor,
                    lhs,
                    rhs,
                ));
            }
            InstOp::Shl => {
                vm_try!(self.internal_bitwise(
                    Protocol::SHL,
                    || VmErrorKind::Overflow,
                    |a, b| a.checked_shl(u32::try_from(b).ok()?),
                    lhs,
                    rhs,
                ));
            }
            InstOp::Shr => {
                vm_try!(self.internal_infallible_bitwise(Protocol::SHR, ops::Shr::shr, lhs, rhs));
            }
            InstOp::Gt => {
                vm_try!(self.internal_boolean_ops(
                    |a, b| a > b,
                    |a, b| a > b,
                    |o| matches!(o, Ordering::Greater),
                    lhs,
                    rhs
                ));
            }
            InstOp::Gte => {
                vm_try!(self.internal_boolean_ops(
                    |a, b| a >= b,
                    |a, b| a >= b,
                    |o| matches!(o, Ordering::Greater | Ordering::Equal),
                    lhs,
                    rhs
                ));
            }
            InstOp::Lt => {
                vm_try!(self.internal_boolean_ops(
                    |a, b| a < b,
                    |a, b| a < b,
                    |o| matches!(o, Ordering::Less),
                    lhs,
                    rhs
                ));
            }
            InstOp::Lte => {
                vm_try!(self.internal_boolean_ops(
                    |a, b| a <= b,
                    |a, b| a <= b,
                    |o| matches!(o, Ordering::Less | Ordering::Equal),
                    lhs,
                    rhs
                ));
            }
            InstOp::Eq => {
                let rhs = vm_try!(self.stack.address(rhs));
                let lhs = vm_try!(self.stack.address(lhs));
                let test = vm_try!(Value::partial_eq_with(&lhs, &rhs, self));
                vm_try!(self.stack.push(Value::from(test)));
            }
            InstOp::Neq => {
                let rhs = vm_try!(self.stack.address(rhs));
                let lhs = vm_try!(self.stack.address(lhs));
                let test = vm_try!(Value::partial_eq_with(&lhs, &rhs, self));
                vm_try!(self.stack.push(Value::from(!test)));
            }
            InstOp::And => {
                vm_try!(self.internal_boolean_op(|a, b| a && b, "&&", lhs, rhs));
            }
            InstOp::Or => {
                vm_try!(self.internal_boolean_op(|a, b| a || b, "||", lhs, rhs));
            }
            InstOp::As => {
                let value = vm_try!(self.as_op(lhs, rhs));
                vm_try!(self.stack.push(value));
            }
            InstOp::Is => {
                let is_instance = vm_try!(self.test_is_instance(lhs, rhs));
                vm_try!(self.stack.push(Value::from(is_instance)));
            }
            InstOp::IsNot => {
                let is_instance = vm_try!(self.test_is_instance(lhs, rhs));
                vm_try!(self.stack.push(Value::from(!is_instance)));
            }
        }

        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_assign(&mut self, target: InstTarget, op: InstAssignOp) -> VmResult<()> {
        match op {
            InstAssignOp::Add => {
                vm_try!(self.internal_num_assign(
                    target,
                    Protocol::ADD_ASSIGN,
                    || VmErrorKind::Overflow,
                    i64::checked_add,
                    ops::Add::add,
                ));
            }
            InstAssignOp::Sub => {
                vm_try!(self.internal_num_assign(
                    target,
                    Protocol::SUB_ASSIGN,
                    || VmErrorKind::Underflow,
                    i64::checked_sub,
                    ops::Sub::sub,
                ));
            }
            InstAssignOp::Mul => {
                vm_try!(self.internal_num_assign(
                    target,
                    Protocol::MUL_ASSIGN,
                    || VmErrorKind::Overflow,
                    i64::checked_mul,
                    ops::Mul::mul,
                ));
            }
            InstAssignOp::Div => {
                vm_try!(self.internal_num_assign(
                    target,
                    Protocol::DIV_ASSIGN,
                    || VmErrorKind::DivideByZero,
                    i64::checked_div,
                    ops::Div::div,
                ));
            }
            InstAssignOp::Rem => {
                vm_try!(self.internal_num_assign(
                    target,
                    Protocol::REM_ASSIGN,
                    || VmErrorKind::DivideByZero,
                    i64::checked_rem,
                    ops::Rem::rem,
                ));
            }
            InstAssignOp::BitAnd => {
                vm_try!(self.internal_infallible_bitwise_assign(
                    target,
                    Protocol::BIT_AND_ASSIGN,
                    ops::BitAndAssign::bitand_assign,
                ));
            }
            InstAssignOp::BitXor => {
                vm_try!(self.internal_infallible_bitwise_assign(
                    target,
                    Protocol::BIT_XOR_ASSIGN,
                    ops::BitXorAssign::bitxor_assign,
                ));
            }
            InstAssignOp::BitOr => {
                vm_try!(self.internal_infallible_bitwise_assign(
                    target,
                    Protocol::BIT_OR_ASSIGN,
                    ops::BitOrAssign::bitor_assign,
                ));
            }
            InstAssignOp::Shl => {
                vm_try!(self.internal_bitwise_assign(
                    target,
                    Protocol::SHL_ASSIGN,
                    || VmErrorKind::Overflow,
                    |a, b| a.checked_shl(u32::try_from(b).ok()?),
                ));
            }
            InstAssignOp::Shr => {
                vm_try!(self.internal_infallible_bitwise_assign(
                    target,
                    Protocol::SHR_ASSIGN,
                    ops::ShrAssign::shr_assign,
                ));
            }
        }

        VmResult::Ok(())
    }

    /// Perform an index set operation.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_index_set(&mut self) -> VmResult<()> {
        let index = vm_try!(self.stack.pop());
        let target = vm_try!(self.stack.pop());
        let value = vm_try!(self.stack.pop());

        'out: {
            let field = match &index {
                Value::String(string) => vm_try!(string.borrow_ref()),
                _ => break 'out,
            };

            let field = field.as_str();

            match &target {
                Value::Object(object) => {
                    let mut object = vm_try!(object.borrow_mut());
                    vm_try!(object.insert(vm_try!(field.try_to_owned()), value));
                    return VmResult::Ok(());
                }
                Value::Struct(typed_object) => {
                    let mut typed_object = vm_try!(typed_object.borrow_mut());

                    if let Some(v) = typed_object.get_mut(field) {
                        *v = value;
                        return VmResult::Ok(());
                    }

                    return err(VmErrorKind::MissingField {
                        target: typed_object.type_info(),
                        field: vm_try!(field.try_to_owned()),
                    });
                }
                Value::Variant(variant) => {
                    let mut variant = vm_try!(variant.borrow_mut());

                    if let VariantData::Struct(st) = variant.data_mut() {
                        if let Some(v) = st.get_mut(field) {
                            *v = value;
                            return VmResult::Ok(());
                        }
                    }

                    return err(VmErrorKind::MissingField {
                        target: variant.type_info(),
                        field: vm_try!(field.try_to_owned()),
                    });
                }
                _ => {}
            }
        }

        if let CallResult::Unsupported(target) =
            vm_try!(self.call_instance_fn(target, Protocol::INDEX_SET, (&index, &value)))
        {
            return err(VmErrorKind::UnsupportedIndexSet {
                target: vm_try!(target.type_info()),
                index: vm_try!(index.type_info()),
                value: vm_try!(value.type_info()),
            });
        }

        vm_try!(<()>::from_value(vm_try!(self.stack.pop())));
        VmResult::Ok(())
    }

    #[inline]
    #[tracing::instrument(skip(self))]
    fn op_return_internal(
        &mut self,
        return_value: Value,
        clean: usize,
    ) -> Result<bool, VmErrorKind> {
        if clean > 0 {
            self.stack.popn(clean)?;
        }

        let exit = self.pop_call_frame()?;
        self.stack.push(return_value)?;
        Ok(exit)
    }

    fn lookup_function_by_hash(&self, hash: Hash) -> Result<Function, VmErrorKind> {
        Ok(match self.unit.function(hash) {
            Some(info) => match info {
                UnitFn::Offset { offset, call, args } => Function::from_vm_offset(
                    self.context.clone(),
                    self.unit.clone(),
                    offset,
                    call,
                    args,
                    hash,
                ),
                UnitFn::EmptyStruct { hash } => {
                    let rtti = self
                        .unit
                        .lookup_rtti(hash)
                        .ok_or(VmErrorKind::MissingRtti { hash })?;

                    Function::from_unit_struct(rtti.clone())
                }
                UnitFn::TupleStruct { hash, args } => {
                    let rtti = self
                        .unit
                        .lookup_rtti(hash)
                        .ok_or(VmErrorKind::MissingRtti { hash })?;

                    Function::from_tuple_struct(rtti.clone(), args)
                }
                UnitFn::UnitVariant { hash } => {
                    let rtti = self
                        .unit
                        .lookup_variant_rtti(hash)
                        .ok_or(VmErrorKind::MissingVariantRtti { hash })?;

                    Function::from_unit_variant(rtti.clone())
                }
                UnitFn::TupleVariant { hash, args } => {
                    let rtti = self
                        .unit
                        .lookup_variant_rtti(hash)
                        .ok_or(VmErrorKind::MissingVariantRtti { hash })?;

                    Function::from_tuple_variant(rtti.clone(), args)
                }
            },
            None => {
                let handler = self
                    .context
                    .function(hash)
                    .ok_or(VmErrorKind::MissingContextFunction { hash })?;

                Function::from_handler(handler.clone(), hash)
            }
        })
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_return(&mut self, address: InstAddress, clean: usize) -> Result<bool, VmErrorKind> {
        let return_value = self.stack.address(address)?;
        self.op_return_internal(return_value, clean)
    }

    #[cfg_attr(feature = "bench", inline(never))]
    #[tracing::instrument(skip(self))]
    fn op_return_unit(&mut self) -> Result<bool, VmErrorKind> {
        let exit = self.pop_call_frame()?;
        self.stack.push(Value::from(()))?;
        Ok(exit)
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_load_instance_fn(&mut self, hash: Hash) -> Result<(), VmError> {
        let instance = self.stack.pop()?;
        let ty = instance.type_hash()?;
        let hash = Hash::associated_function(ty, hash);
        self.stack.push(Value::Type(Type::new(hash)))?;
        Ok(())
    }

    /// Perform an index get operation.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_index_get(&mut self, target: InstAddress, index: InstAddress) -> VmResult<()> {
        let index = vm_try!(self.stack.address(index));
        let target = vm_try!(self.stack.address_ref(target));

        match &index {
            Value::String(string) => {
                let string_ref = vm_try!(string.borrow_ref());

                if let Some(value) = vm_try!(Self::try_object_like_index_get(
                    &target,
                    string_ref.as_str()
                )) {
                    vm_try!(self.stack.push(value));
                    return VmResult::Ok(());
                }
            }
            Value::Integer(index) => {
                let Ok(index) = (*index).try_into() else {
                    return err(VmErrorKind::MissingIndexInteger {
                        target: vm_try!(target.type_info()),
                        index: VmIntegerRepr::from(*index),
                    });
                };

                if let Some(value) = vm_try!(Self::try_tuple_like_index_get(&target, index)) {
                    vm_try!(self.stack.push(value));
                    return VmResult::Ok(());
                }
            }
            _ => (),
        }

        let target = vm_try!(target.try_into_owned());

        if let CallResult::Unsupported(target) =
            vm_try!(self.call_instance_fn(target, Protocol::INDEX_GET, (&index,)))
        {
            return err(VmErrorKind::UnsupportedIndexGet {
                target: vm_try!(target.type_info()),
                index: vm_try!(index.type_info()),
            });
        }

        // NB: Should leave a value on the stack.
        VmResult::Ok(())
    }

    /// Perform an index get operation specialized for tuples.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_tuple_index_get(&mut self, index: usize) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        if let Some(value) = vm_try!(Self::try_tuple_like_index_get(&value, index)) {
            vm_try!(self.stack.push(value));
            return VmResult::Ok(());
        }

        if let CallResult::Unsupported(value) =
            vm_try!(self.call_index_fn(Protocol::GET, value, index, ()))
        {
            return err(VmErrorKind::UnsupportedTupleIndexGet {
                target: vm_try!(value.type_info()),
                index,
            });
        }

        // NB: Should leave a value on the stack.
        VmResult::Ok(())
    }

    /// Perform an index get operation specialized for tuples.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_tuple_index_set(&mut self, index: usize) -> VmResult<()> {
        let tuple = vm_try!(self.stack.pop());
        let value = vm_try!(self.stack.pop());

        if vm_try!(Self::try_tuple_like_index_set(&tuple, index, value)) {
            return VmResult::Ok(());
        }

        err(VmErrorKind::UnsupportedTupleIndexSet {
            target: vm_try!(tuple.type_info()),
        })
    }

    /// Perform an index get operation specialized for tuples.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_tuple_index_get_at(&mut self, offset: usize, index: usize) -> VmResult<()> {
        let value = vm_try!(self.stack.at_offset(offset));

        if let Some(value) = vm_try!(Self::try_tuple_like_index_get(value, index)) {
            vm_try!(self.stack.push(value));
            return VmResult::Ok(());
        }

        let value = value.clone();

        if let CallResult::Unsupported(value) =
            vm_try!(self.call_index_fn(Protocol::GET, value, index, ()))
        {
            return err(VmErrorKind::UnsupportedTupleIndexGet {
                target: vm_try!(value.type_info()),
                index,
            });
        }

        // NB: Should leave a value on the stack.
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_eq_bool(&mut self, boolean: bool) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        vm_try!(self.stack.push(Value::from(match value {
            Value::Bool(actual) => actual == boolean,
            _ => false,
        })));

        VmResult::Ok(())
    }

    /// Perform a specialized index get operation on an object.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_object_index_get(&mut self, string_slot: usize) -> VmResult<()> {
        let target = vm_try!(self.stack.pop());

        match vm_try!(self.try_object_slot_index_get(target, string_slot)) {
            CallResult::Ok(value) => {
                vm_try!(self.stack.push(value));
                VmResult::Ok(())
            }
            CallResult::Unsupported(target) => err(VmErrorKind::UnsupportedObjectSlotIndexGet {
                target: vm_try!(target.type_info()),
            }),
        }
    }

    /// Perform a specialized index set operation on an object.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_object_index_set(&mut self, string_slot: usize) -> VmResult<()> {
        let target = vm_try!(self.stack.pop());
        let value = vm_try!(self.stack.pop());

        if let CallResult::Unsupported(target) =
            vm_try!(self.try_object_slot_index_set(target, string_slot, value))
        {
            return err(VmErrorKind::UnsupportedObjectSlotIndexSet {
                target: vm_try!(target.type_info()),
            });
        }

        VmResult::Ok(())
    }

    /// Perform a specialized index get operation on an object.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_object_index_get_at(&mut self, offset: usize, string_slot: usize) -> VmResult<()> {
        let target = vm_try!(self.stack.at_offset(offset)).clone();

        match vm_try!(self.try_object_slot_index_get(target, string_slot)) {
            CallResult::Ok(value) => {
                vm_try!(self.stack.push(value));
                VmResult::Ok(())
            }
            CallResult::Unsupported(target) => err(VmErrorKind::UnsupportedObjectSlotIndexGet {
                target: vm_try!(target.type_info()),
            }),
        }
    }

    /// Operation to allocate an object.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_object(&mut self, slot: usize) -> VmResult<()> {
        let keys = vm_try!(self
            .unit
            .lookup_object_keys(slot)
            .ok_or(VmErrorKind::MissingStaticObjectKeys { slot }));

        let mut object = vm_try!(Object::with_capacity(keys.len()));
        let values = vm_try!(self.stack.drain(keys.len()));

        for (key, value) in keys.iter().zip(values) {
            let key = vm_try!(String::try_from(key.as_str()));
            vm_try!(object.insert(key, value));
        }

        vm_try!(self.stack.push(Value::from(vm_try!(Shared::new(object)))));
        VmResult::Ok(())
    }

    /// Operation to allocate an object.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_range(&mut self, range: InstRange) -> VmResult<()> {
        let value = match range {
            InstRange::RangeFrom => {
                let start = vm_try!(self.stack.pop());
                vm_try!(Value::try_from(RangeFrom::new(start)))
            }
            InstRange::RangeFull => {
                vm_try!(Value::try_from(RangeFull::new()))
            }
            InstRange::RangeInclusive => {
                let end = vm_try!(self.stack.pop());
                let start = vm_try!(self.stack.pop());
                vm_try!(Value::try_from(RangeInclusive::new(start, end)))
            }
            InstRange::RangeToInclusive => {
                let end = vm_try!(self.stack.pop());
                vm_try!(Value::try_from(RangeToInclusive::new(end)))
            }
            InstRange::RangeTo => {
                let end = vm_try!(self.stack.pop());
                vm_try!(Value::try_from(RangeTo::new(end)))
            }
            InstRange::Range => {
                let end = vm_try!(self.stack.pop());
                let start = vm_try!(self.stack.pop());
                vm_try!(Value::try_from(Range::new(start, end)))
            }
        };

        vm_try!(self.stack.push(value));
        VmResult::Ok(())
    }

    /// Operation to allocate an empty struct.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_empty_struct(&mut self, hash: Hash) -> VmResult<()> {
        let rtti = vm_try!(self
            .unit
            .lookup_rtti(hash)
            .ok_or(VmErrorKind::MissingRtti { hash }));

        vm_try!(self
            .stack
            .push(vm_try!(Value::try_from(EmptyStruct { rtti: rtti.clone() }))));
        VmResult::Ok(())
    }

    /// Operation to allocate an object struct.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_struct(&mut self, hash: Hash, slot: usize) -> VmResult<()> {
        let keys = vm_try!(self
            .unit
            .lookup_object_keys(slot)
            .ok_or(VmErrorKind::MissingStaticObjectKeys { slot }));

        let rtti = vm_try!(self
            .unit
            .lookup_rtti(hash)
            .ok_or(VmErrorKind::MissingRtti { hash }));

        let values = vm_try!(self.stack.drain(keys.len()));
        let mut data = vm_try!(Object::with_capacity(keys.len()));

        for (key, value) in keys.iter().zip(values) {
            let key = vm_try!(String::try_from(key.as_str()));
            vm_try!(data.insert(key, value));
        }

        vm_try!(self.stack.push(vm_try!(Value::try_from(Struct {
            rtti: rtti.clone(),
            data,
        }))));

        VmResult::Ok(())
    }

    /// Operation to allocate an object.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_unit_variant(&mut self, hash: Hash) -> VmResult<()> {
        let rtti = vm_try!(self
            .unit
            .lookup_variant_rtti(hash)
            .ok_or(VmErrorKind::MissingVariantRtti { hash }));

        vm_try!(self
            .stack
            .push(vm_try!(Value::try_from(Variant::unit(rtti.clone())))));
        VmResult::Ok(())
    }

    /// Operation to allocate an object variant.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_object_variant(&mut self, hash: Hash, slot: usize) -> VmResult<()> {
        let keys = vm_try!(self
            .unit
            .lookup_object_keys(slot)
            .ok_or(VmErrorKind::MissingStaticObjectKeys { slot }));

        let rtti = vm_try!(self
            .unit
            .lookup_variant_rtti(hash)
            .ok_or(VmErrorKind::MissingVariantRtti { hash }));

        let mut data = vm_try!(Object::with_capacity(keys.len()));
        let values = vm_try!(self.stack.drain(keys.len()));

        for (key, value) in keys.iter().zip(values) {
            let key = vm_try!(String::try_from(key.as_str()));
            vm_try!(data.insert(key, value));
        }

        vm_try!(self.stack.push(vm_try!(Value::try_from(Variant::struct_(
            rtti.clone(),
            data
        )))));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_string(&mut self, slot: usize) -> VmResult<()> {
        let string = vm_try!(self.unit.lookup_string(slot));
        vm_try!(self
            .stack
            .push(vm_try!(Value::try_from(vm_try!(String::try_from(
                string.as_str()
            ))))));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_bytes(&mut self, slot: usize) -> VmResult<()> {
        let bytes = vm_try!(alloc::Vec::<u8>::try_from(vm_try!(self
            .unit
            .lookup_bytes(slot))));
        vm_try!(self
            .stack
            .push(vm_try!(Value::try_from(Bytes::from_vec(bytes)))));
        VmResult::Ok(())
    }

    /// Optimize operation to perform string concatenation.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_string_concat(&mut self, len: usize, size_hint: usize) -> VmResult<()> {
        let values = vm_try!(vm_try!(self.stack.drain(len)).try_collect::<alloc::Vec<_>>());

        let mut f = vm_try!(Formatter::with_capacity(size_hint));

        for value in values {
            vm_try!(value.string_display_with(&mut f, &mut *self));
        }

        vm_try!(self.stack.push(vm_try!(Value::try_from(f.string))));
        VmResult::Ok(())
    }

    /// Push a format specification onto the stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_format(&mut self, spec: FormatSpec) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());
        vm_try!(self
            .stack
            .push(vm_try!(Value::try_from(Format { value, spec }))));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_is_unit(&mut self) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());
        vm_try!(self
            .stack
            .push(Value::from(matches!(value, Value::EmptyTuple))));
        VmResult::Ok(())
    }

    /// Perform the try operation on the given stack location.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_try(&mut self, address: InstAddress, clean: usize, preserve: bool) -> VmResult<bool> {
        let value = vm_try!(self.stack.address(address));

        let result = match value {
            Value::Result(result) => vm_try!(result::result_try(vm_try!(result.take()))),
            Value::Option(option) => vm_try!(option::option_try(vm_try!(option.take()))),
            value => {
                if let CallResult::Unsupported(target) =
                    vm_try!(self.call_instance_fn(value, Protocol::TRY, ()))
                {
                    return err(VmErrorKind::UnsupportedTryOperand {
                        actual: vm_try!(target.type_info()),
                    });
                }

                let value = vm_try!(self.stack.pop());
                vm_try!(ControlFlow::from_value(value))
            }
        };

        match result {
            ControlFlow::Continue(value) => {
                if preserve {
                    vm_try!(self.stack.push(value));
                }

                VmResult::Ok(false)
            }
            ControlFlow::Break(error) => {
                VmResult::Ok(vm_try!(self.op_return_internal(error, clean)))
            }
        }
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_eq_byte(&mut self, byte: u8) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        vm_try!(self.stack.push(Value::from(match value {
            Value::Byte(actual) => actual == byte,
            _ => false,
        })));

        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_eq_character(&mut self, character: char) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        vm_try!(self.stack.push(Value::from(match value {
            Value::Char(actual) => actual == character,
            _ => false,
        })));

        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_eq_integer(&mut self, integer: i64) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        vm_try!(self.stack.push(Value::from(match value {
            Value::Integer(actual) => actual == integer,
            _ => false,
        })));

        VmResult::Ok(())
    }

    /// Test if the top of stack is equal to the string at the given static
    /// string slot.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_eq_string(&mut self, slot: usize) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        let equal = match value {
            Value::String(actual) => {
                let string = vm_try!(self.unit.lookup_string(slot));
                let actual = vm_try!(actual.borrow_ref());
                actual.as_str() == string.as_str()
            }
            _ => false,
        };

        vm_try!(self.stack.push(Value::Bool(equal)));
        VmResult::Ok(())
    }

    /// Test if the top of stack is equal to the string at the given static
    /// bytes slot.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_eq_bytes(&mut self, slot: usize) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        let equal = match value {
            Value::Bytes(actual) => {
                let bytes = vm_try!(self.unit.lookup_bytes(slot));
                let actual = vm_try!(actual.borrow_ref());
                *actual == *bytes
            }
            _ => false,
        };

        vm_try!(self.stack.push(Value::Bool(equal)));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_match_sequence(&mut self, ty: TypeCheck, len: usize, exact: bool) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        let result = vm_try!(self.on_tuple(ty, &value, move |tuple| {
            if exact {
                tuple.len() == len
            } else {
                tuple.len() >= len
            }
        }));

        vm_try!(self.stack.push(Value::Bool(result.unwrap_or_default())));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_match_type(&mut self, hash: Hash) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());
        let is_match = vm_try!(value.type_hash()) == hash;
        vm_try!(self.stack.push(Value::from(is_match)));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_match_variant(
        &mut self,
        enum_hash: Hash,
        variant_hash: Hash,
        index: usize,
    ) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        let is_match = match &value {
            Value::Variant(variant) => vm_try!(variant.borrow_ref()).rtti().hash == variant_hash,
            Value::Any(any) => {
                let hash = vm_try!(any.borrow_ref()).type_hash();

                if hash == enum_hash {
                    match vm_try!(self.call_instance_fn(value, Protocol::IS_VARIANT, (index,))) {
                        CallResult::Ok(()) => vm_try!(vm_try!(self.stack.pop()).as_bool()),
                        CallResult::Unsupported(..) => false,
                    }
                } else {
                    false
                }
            }
            _ => false,
        };

        vm_try!(self.stack.push(Value::from(is_match)));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_match_builtin(&mut self, type_check: TypeCheck) -> VmResult<()> {
        let value = vm_try!(self.stack.pop());

        let is_match = match (type_check, value) {
            (TypeCheck::Tuple, Value::Tuple(..)) => true,
            (TypeCheck::Vec, Value::Vec(..)) => true,
            (TypeCheck::Result(v), Value::Result(result)) => {
                let result = vm_try!(result.borrow_ref());

                match (v, &*result) {
                    (0, Result::Ok(..)) => true,
                    (1, Result::Err(..)) => true,
                    _ => false,
                }
            }
            (TypeCheck::Option(v), Value::Option(option)) => {
                let option = vm_try!(option.borrow_ref());

                match (v, &*option) {
                    (0, Some(..)) => true,
                    (1, None) => true,
                    _ => false,
                }
            }
            (TypeCheck::GeneratorState(v), Value::GeneratorState(state)) => {
                use crate::runtime::GeneratorState::*;
                let state = vm_try!(state.borrow_ref());

                match (v, &*state) {
                    (0, Complete(..)) => true,
                    (1, Yielded(..)) => true,
                    _ => false,
                }
            }
            (TypeCheck::EmptyTuple, Value::EmptyTuple) => true,
            _ => false,
        };

        vm_try!(self.stack.push(Value::from(is_match)));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_match_object(&mut self, slot: usize, exact: bool) -> VmResult<()> {
        fn test(object: &Object, keys: &[alloc::String], exact: bool) -> bool {
            if exact {
                if object.len() != keys.len() {
                    return false;
                }
            } else if object.len() < keys.len() {
                return false;
            }

            for key in keys {
                if !object.contains_key(key.as_str()) {
                    return false;
                }
            }

            true
        }

        let value = vm_try!(self.stack.pop());

        let is_match = match value {
            Value::Object(object) => {
                let keys = vm_try!(self
                    .unit
                    .lookup_object_keys(slot)
                    .ok_or(VmErrorKind::MissingStaticObjectKeys { slot }));

                let object = vm_try!(object.borrow_ref());
                test(&object, keys, exact)
            }
            _ => false,
        };

        vm_try!(self.stack.push(Value::from(is_match)));
        VmResult::Ok(())
    }

    /// Push the given variant onto the stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_variant(&mut self, variant: InstVariant) -> VmResult<()> {
        match variant {
            InstVariant::Some => {
                let some = vm_try!(self.stack.pop());
                vm_try!(self
                    .stack
                    .push(Value::Option(vm_try!(Shared::new(Some(some))))));
            }
            InstVariant::None => {
                vm_try!(self.stack.push(Value::Option(vm_try!(Shared::new(None)))));
            }
            InstVariant::Ok => {
                let some = vm_try!(self.stack.pop());
                vm_try!(self
                    .stack
                    .push(Value::Result(vm_try!(Shared::new(Result::Ok(some))))));
            }
            InstVariant::Err => {
                let some = vm_try!(self.stack.pop());
                vm_try!(self
                    .stack
                    .push(Value::Result(vm_try!(Shared::new(Result::Err(some))))));
            }
        }

        VmResult::Ok(())
    }

    /// Load a function as a value onto the stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_load_fn(&mut self, hash: Hash) -> VmResult<()> {
        let function = vm_try!(self.lookup_function_by_hash(hash));
        vm_try!(self
            .stack
            .push(Value::Function(vm_try!(Shared::new(function)))));
        VmResult::Ok(())
    }

    /// Construct a closure on the top of the stack.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_closure(&mut self, hash: Hash, count: usize) -> VmResult<()> {
        let info = vm_try!(self
            .unit
            .function(hash)
            .ok_or(VmErrorKind::MissingFunction { hash }));

        let (offset, call, args) = match info {
            UnitFn::Offset { offset, call, args } => (offset, call, args),
            _ => return err(VmErrorKind::MissingFunction { hash }),
        };

        let environment =
            vm_try!(vm_try!(vm_try!(self.stack.pop_sequence(count))).try_into_boxed_slice());

        let function = Function::from_vm_closure(
            self.context.clone(),
            self.unit.clone(),
            offset,
            call,
            args,
            environment,
            hash,
        );

        vm_try!(self
            .stack
            .push(Value::Function(vm_try!(Shared::new(function)))));
        VmResult::Ok(())
    }

    /// Implementation of a function call.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_call(&mut self, hash: Hash, args: usize) -> VmResult<()> {
        match self.unit.function(hash) {
            Some(info) => match info {
                UnitFn::Offset {
                    offset,
                    call,
                    args: expected,
                } => {
                    vm_try!(check_args(args, expected));
                    vm_try!(self.call_offset_fn(offset, call, args));
                }
                UnitFn::EmptyStruct { hash } => {
                    vm_try!(check_args(args, 0));

                    let rtti = vm_try!(self
                        .unit
                        .lookup_rtti(hash)
                        .ok_or(VmErrorKind::MissingRtti { hash }));

                    vm_try!(self.stack.push(vm_try!(Value::empty_struct(rtti.clone()))));
                }
                UnitFn::TupleStruct {
                    hash,
                    args: expected,
                } => {
                    vm_try!(check_args(args, expected));
                    let tuple = vm_try!(vm_try!(self.stack.pop_sequence(args)));

                    let rtti = vm_try!(self
                        .unit
                        .lookup_rtti(hash)
                        .ok_or(VmErrorKind::MissingRtti { hash }));

                    vm_try!(self
                        .stack
                        .push(vm_try!(Value::tuple_struct(rtti.clone(), tuple))));
                }
                UnitFn::TupleVariant {
                    hash,
                    args: expected,
                } => {
                    vm_try!(check_args(args, expected));

                    let rtti = vm_try!(self
                        .unit
                        .lookup_variant_rtti(hash)
                        .ok_or(VmErrorKind::MissingVariantRtti { hash }));

                    let tuple = vm_try!(vm_try!(self.stack.pop_sequence(args)));
                    vm_try!(self
                        .stack
                        .push(vm_try!(Value::tuple_variant(rtti.clone(), tuple))));
                }
                UnitFn::UnitVariant { hash } => {
                    vm_try!(check_args(args, 0));

                    let rtti = vm_try!(self
                        .unit
                        .lookup_variant_rtti(hash)
                        .ok_or(VmErrorKind::MissingVariantRtti { hash }));

                    vm_try!(self.stack.push(vm_try!(Value::unit_variant(rtti.clone()))));
                }
            },
            None => {
                let handler = vm_try!(self
                    .context
                    .function(hash)
                    .ok_or(VmErrorKind::MissingFunction { hash }));

                vm_try!(handler(&mut self.stack, args));
            }
        }

        VmResult::Ok(())
    }

    /// Call a function at the given offset with the given number of arguments.
    #[cfg_attr(feature = "bench", inline(never))]
    fn op_call_offset(&mut self, offset: usize, call: Call, args: usize) -> VmResult<()> {
        vm_try!(self.call_offset_fn(offset, call, args));
        VmResult::Ok(())
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_call_associated(&mut self, hash: Hash, args: usize) -> VmResult<()> {
        // NB: +1 to include the instance itself.
        let args = args + 1;
        let instance = vm_try!(self.stack.at_offset_from_top(args));
        let type_hash = vm_try!(instance.type_hash());
        let hash = Hash::associated_function(type_hash, hash);

        if let Some(UnitFn::Offset {
            offset,
            call,
            args: expected,
        }) = self.unit.function(hash)
        {
            vm_try!(check_args(args, expected));
            vm_try!(self.call_offset_fn(offset, call, args));
            return VmResult::Ok(());
        }

        if let Some(handler) = self.context.function(hash) {
            vm_try!(handler(&mut self.stack, args));
            return VmResult::Ok(());
        }

        err(VmErrorKind::MissingInstanceFunction {
            instance: vm_try!(instance.type_info()),
            hash,
        })
    }

    #[cfg_attr(feature = "bench", inline(never))]
    #[tracing::instrument(skip(self))]
    fn op_call_fn(&mut self, args: usize) -> VmResult<Option<VmHalt>> {
        let function = vm_try!(self.stack.pop());

        let ty = match function {
            Value::Type(ty) => ty,
            Value::Function(function) => {
                let function = vm_try!(function.into_ref());
                return function.call_with_vm(self, args);
            }
            actual => {
                let actual = vm_try!(actual.type_info());
                return err(VmErrorKind::UnsupportedCallFn { actual });
            }
        };

        vm_try!(self.op_call(ty.into_hash(), args));
        VmResult::Ok(None)
    }

    #[cfg_attr(feature = "bench", inline(never))]
    fn op_iter_next(&mut self, offset: usize, jump: usize) -> VmResult<()> {
        let value = vm_try!(self.stack.at_offset_mut(offset));

        let some = match value {
            Value::Option(option) => {
                let option = vm_try!(option.borrow_ref()).clone();

                match option {
                    Some(some) => some,
                    None => {
                        self.ip = vm_try!(self.unit.translate(jump));
                        return VmResult::Ok(());
                    }
                }
            }
            other => {
                return err(VmErrorKind::UnsupportedIterNextOperand {
                    actual: vm_try!(other.type_info()),
                });
            }
        };

        *value = some;
        VmResult::Ok(())
    }

    /// Call the provided closure within the context of this virtual machine.
    ///
    /// This allows for calling protocol function helpers like
    /// [Value::string_display] which requires access to a virtual machine.
    ///
    /// ```,no_run
    /// use rune::{Context, Unit};
    /// use rune::runtime::Formatter;
    /// use std::sync::Arc;
    ///
    /// let context = Context::with_default_modules()?;
    /// let context = Arc::new(context.runtime()?);
    ///
    /// // Normally the unit would be created by compiling some source,
    /// // and since this one is empty it'll just error.
    /// let unit = Arc::new(Unit::default());
    ///
    /// let mut vm = rune::Vm::new(context, unit);
    ///
    /// let output = vm.call(["main"], ())?;
    ///
    /// // Call the string_display protocol on `output`. This requires
    /// // access to a virtual machine since it might use functions
    /// // registered in the unit associated with it.
    /// let mut f = Formatter::new();
    ///
    /// // Note: We do an extra unwrap because the return value is
    /// // `fmt::Result`.
    /// vm.with(|| output.string_display(&mut f)).into_result()?;
    /// # Ok::<_, rune::support::Error>(())
    /// ```
    pub fn with<F, T>(&mut self, f: F) -> T
    where
        F: FnOnce() -> T,
    {
        let _guard = crate::runtime::env::Guard::new(&self.context, &self.unit);
        f()
    }

    /// Evaluate a single instruction.
    pub(crate) fn run(&mut self) -> VmResult<VmHalt> {
        // NB: set up environment so that native function can access context and
        // unit.
        let _guard = crate::runtime::env::Guard::new(&self.context, &self.unit);

        loop {
            if !budget::take() {
                return VmResult::Ok(VmHalt::Limited);
            }

            let Some((inst, inst_len)) = vm_try!(self.unit.instruction_at(self.ip)) else {
                return VmResult::err(VmErrorKind::IpOutOfBounds {
                    ip: self.ip,
                    length: self.unit.instructions().end(),
                });
            };

            tracing::trace!(ip = ?self.ip, ?inst);

            self.ip = self.ip.wrapping_add(inst_len);
            self.last_ip_len = inst_len as u8;

            match inst {
                Inst::Not => {
                    vm_try!(self.op_not());
                }
                Inst::Neg => {
                    vm_try!(self.op_neg());
                }
                Inst::Closure { hash, count } => {
                    vm_try!(self.op_closure(hash, count));
                }
                Inst::Call { hash, args } => {
                    vm_try!(self.op_call(hash, args));
                }
                Inst::CallOffset { offset, call, args } => {
                    vm_try!(self.op_call_offset(offset, call, args));
                }
                Inst::CallAssociated { hash, args } => {
                    vm_try!(self.op_call_associated(hash, args));
                }
                Inst::CallFn { args } => {
                    if let Some(reason) = vm_try!(self.op_call_fn(args)) {
                        return VmResult::Ok(reason);
                    }
                }
                Inst::LoadInstanceFn { hash } => {
                    vm_try!(self.op_load_instance_fn(hash));
                }
                Inst::IndexGet { target, index } => {
                    vm_try!(self.op_index_get(target, index));
                }
                Inst::TupleIndexGet { index } => {
                    vm_try!(self.op_tuple_index_get(index));
                }
                Inst::TupleIndexSet { index } => {
                    vm_try!(self.op_tuple_index_set(index));
                }
                Inst::TupleIndexGetAt { offset, index } => {
                    vm_try!(self.op_tuple_index_get_at(offset, index));
                }
                Inst::ObjectIndexGet { slot } => {
                    vm_try!(self.op_object_index_get(slot));
                }
                Inst::ObjectIndexSet { slot } => {
                    vm_try!(self.op_object_index_set(slot));
                }
                Inst::ObjectIndexGetAt { offset, slot } => {
                    vm_try!(self.op_object_index_get_at(offset, slot));
                }
                Inst::IndexSet => {
                    vm_try!(self.op_index_set());
                }
                Inst::Return { address, clean } => {
                    if vm_try!(self.op_return(address, clean)) {
                        return VmResult::Ok(VmHalt::Exited);
                    }
                }
                Inst::ReturnUnit => {
                    if vm_try!(self.op_return_unit()) {
                        return VmResult::Ok(VmHalt::Exited);
                    }
                }
                Inst::Await => {
                    let future = vm_try!(self.op_await());
                    return VmResult::Ok(VmHalt::Awaited(Awaited::Future(future)));
                }
                Inst::Select { len } => {
                    if let Some(select) = vm_try!(self.op_select(len)) {
                        return VmResult::Ok(VmHalt::Awaited(Awaited::Select(select)));
                    }
                }
                Inst::LoadFn { hash } => {
                    vm_try!(self.op_load_fn(hash));
                }
                Inst::Push { value } => {
                    vm_try!(self.op_push(value));
                }
                Inst::Pop => {
                    vm_try!(self.op_pop());
                }
                Inst::PopN { count } => {
                    vm_try!(self.op_popn(count));
                }
                Inst::PopAndJumpIfNot { count, jump } => {
                    vm_try!(self.op_pop_and_jump_if_not(count, jump));
                }
                Inst::Clean { count } => {
                    vm_try!(self.op_clean(count));
                }
                Inst::Copy { offset } => {
                    vm_try!(self.op_copy(offset));
                }
                Inst::Move { offset } => {
                    vm_try!(self.op_move(offset));
                }
                Inst::Drop { offset } => {
                    vm_try!(self.op_drop(offset));
                }
                Inst::Swap { a, b } => {
                    vm_try!(self.op_swap(a, b));
                }
                Inst::Replace { offset } => {
                    vm_try!(self.op_replace(offset));
                }
                Inst::Jump { jump } => {
                    vm_try!(self.op_jump(jump));
                }
                Inst::JumpIf { jump } => {
                    vm_try!(self.op_jump_if(jump));
                }
                Inst::JumpIfOrPop { jump } => {
                    vm_try!(self.op_jump_if_or_pop(jump));
                }
                Inst::JumpIfNotOrPop { jump } => {
                    vm_try!(self.op_jump_if_not_or_pop(jump));
                }
                Inst::JumpIfBranch { branch, jump } => {
                    vm_try!(self.op_jump_if_branch(branch, jump));
                }
                Inst::Vec { count } => {
                    vm_try!(self.op_vec(count));
                }
                Inst::Tuple { count } => {
                    vm_try!(self.op_tuple(count));
                }
                Inst::Tuple1 { args } => {
                    vm_try!(self.op_tuple_n(&args[..]));
                }
                Inst::Tuple2 { args } => {
                    vm_try!(self.op_tuple_n(&args[..]));
                }
                Inst::Tuple3 { args } => {
                    vm_try!(self.op_tuple_n(&args[..]));
                }
                Inst::Tuple4 { args } => {
                    vm_try!(self.op_tuple_n(&args[..]));
                }
                Inst::PushTuple => {
                    vm_try!(self.op_push_tuple());
                }
                Inst::Object { slot } => {
                    vm_try!(self.op_object(slot));
                }
                Inst::Range { range } => {
                    vm_try!(self.op_range(range));
                }
                Inst::EmptyStruct { hash } => {
                    vm_try!(self.op_empty_struct(hash));
                }
                Inst::Struct { hash, slot } => {
                    vm_try!(self.op_struct(hash, slot));
                }
                Inst::UnitVariant { hash } => {
                    vm_try!(self.op_unit_variant(hash));
                }
                Inst::StructVariant { hash, slot } => {
                    vm_try!(self.op_object_variant(hash, slot));
                }
                Inst::String { slot } => {
                    vm_try!(self.op_string(slot));
                }
                Inst::Bytes { slot } => {
                    vm_try!(self.op_bytes(slot));
                }
                Inst::StringConcat { len, size_hint } => {
                    vm_try!(self.op_string_concat(len, size_hint));
                }
                Inst::Format { spec } => {
                    vm_try!(self.op_format(spec));
                }
                Inst::IsUnit => {
                    vm_try!(self.op_is_unit());
                }
                Inst::Try {
                    address,
                    clean,
                    preserve,
                } => {
                    if vm_try!(self.op_try(address, clean, preserve)) {
                        return VmResult::Ok(VmHalt::Exited);
                    }
                }
                Inst::EqByte { byte } => {
                    vm_try!(self.op_eq_byte(byte));
                }
                Inst::EqChar { char: character } => {
                    vm_try!(self.op_eq_character(character));
                }
                Inst::EqInteger { integer } => {
                    vm_try!(self.op_eq_integer(integer));
                }
                Inst::EqBool { boolean } => {
                    vm_try!(self.op_eq_bool(boolean));
                }
                Inst::EqString { slot } => {
                    vm_try!(self.op_eq_string(slot));
                }
                Inst::EqBytes { slot } => {
                    vm_try!(self.op_eq_bytes(slot));
                }
                Inst::MatchSequence {
                    type_check,
                    len,
                    exact,
                } => {
                    vm_try!(self.op_match_sequence(type_check, len, exact));
                }
                Inst::MatchType { hash } => {
                    vm_try!(self.op_match_type(hash));
                }
                Inst::MatchVariant {
                    enum_hash,
                    variant_hash,
                    index,
                } => {
                    vm_try!(self.op_match_variant(enum_hash, variant_hash, index));
                }
                Inst::MatchBuiltIn { type_check } => {
                    vm_try!(self.op_match_builtin(type_check));
                }
                Inst::MatchObject { slot, exact } => {
                    vm_try!(self.op_match_object(slot, exact));
                }
                Inst::Yield => {
                    return VmResult::Ok(VmHalt::Yielded);
                }
                Inst::YieldUnit => {
                    vm_try!(self.stack.push(Value::EmptyTuple));
                    return VmResult::Ok(VmHalt::Yielded);
                }
                Inst::Variant { variant } => {
                    vm_try!(self.op_variant(variant));
                }
                Inst::Op { op, a, b } => {
                    vm_try!(self.op_op(op, a, b));
                }
                Inst::Assign { target, op } => {
                    vm_try!(self.op_assign(target, op));
                }
                Inst::IterNext { offset, jump } => {
                    vm_try!(self.op_iter_next(offset, jump));
                }
                Inst::Panic { reason } => {
                    return err(VmErrorKind::Panic {
                        reason: Panic::from(reason),
                    });
                }
            }
        }
    }
}

impl TryClone for Vm {
    fn try_clone(&self) -> alloc::Result<Self> {
        Ok(Self {
            context: self.context.clone(),
            unit: self.unit.clone(),
            ip: self.ip,
            last_ip_len: self.last_ip_len,
            stack: self.stack.try_clone()?,
            call_frames: self.call_frames.try_clone()?,
        })
    }
}

impl AsMut<Vm> for Vm {
    #[inline]
    fn as_mut(&mut self) -> &mut Vm {
        self
    }
}

impl AsRef<Vm> for Vm {
    #[inline]
    fn as_ref(&self) -> &Vm {
        self
    }
}

/// A call frame.
///
/// This is used to store the return point after an instruction has been run.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct CallFrame {
    /// The stored instruction pointer.
    pub ip: usize,
    /// The top of the stack at the time of the call to ensure stack isolation
    /// across function calls.
    ///
    /// I.e. a function should not be able to manipulate the size of any other
    /// stack than its own.
    pub stack_bottom: usize,
    /// Indicates that the call frame is isolated and should force an exit into
    /// the vm execution context.
    pub isolated: bool,
}

impl TryClone for CallFrame {
    #[inline]
    fn try_clone(&self) -> alloc::Result<Self> {
        Ok(*self)
    }
}

/// Clear stack on drop.
struct ClearStack<'a>(&'a mut Vm);

impl Drop for ClearStack<'_> {
    fn drop(&mut self) {
        self.0.stack.clear();
    }
}

/// Check that arguments matches expected or raise the appropriate error.
fn check_args(args: usize, expected: usize) -> Result<(), VmErrorKind> {
    if args != expected {
        return Err(VmErrorKind::BadArgumentCount {
            actual: args,
            expected,
        });
    }

    Result::Ok(())
}