nova_vm 1.0.0

Nova Virtual Machine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

mod assignment;
mod block_declaration_instantiation;
mod class_definition_evaluation;
mod compile_context;
mod executable_context;
mod exports;
mod finaliser_stack;
mod for_in_of_statement;
mod function_declaration_instantiation;
mod labelled_statement;
mod template_literals;
mod with_statement;

pub(crate) use compile_context::*;

use std::{convert::Infallible, ops::ControlFlow};

use super::{FunctionExpression, Instruction, SendableRef, executable::ArrowFunctionExpression};
use crate::ecmascript::{
    BUILTIN_STRING_MEMORY, BigInt, ContainsExpression, LexicallyScopedDeclaration,
    LexicallyScopedDeclarations, Number, String, Value,
};
#[cfg(feature = "typescript")]
use crate::{ecmascript::ObjectShapeRecord, heap::CreateHeapData};
use crate::{
    ecmascript::{
        Agent, ExceptionType, ObjectShape, Primitive, PropertyKey, to_property_key_simple,
    },
    engine::{Bindable, NoGcScope},
};
use num_traits::Num;
use oxc_ast::ast;
use oxc_ecmascript::BoundNames;
use oxc_semantic::{NodeId, ScopeFlags, SymbolFlags};
use oxc_syntax::operator::{BinaryOperator, UnaryOperator};
use template_literals::get_template_object;
use wtf8::{CodePoint, Wtf8Buf};

/// Defines the compiled output of a place expression. Place expressions define
/// a location in memory, instead of a concrete value. Examples are:
///
/// ```javascript
/// foo; // foo environment variable
/// expr.bar; // bar member of some expression
/// ```
///
/// Place expressions can appear on both the right and left side of assignment
/// expressions. On the left side they're eventually used as an input to
/// PutValue, while on the right hand side they're eventually used as an input
/// to GetValue.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Place<'s, 'gc> {
    /// A variable on the stack. The variable data is stored on the VM stack
    /// instead of being in the environment. Stack-slot variables never produce
    /// references.
    Stack {
        name: String<'gc>,
        stack_slot: u32,
        mutable: bool,
    },
    /// A variable in the environment. The variable data is stored in the
    /// declarative environment's hash map and accessed through a reference.
    Env { name: String<'gc> },
    /// A variable in the global environment. The variable data is stored in
    /// the global object's properties and accessed through a reference.
    Global { name: String<'gc> },
    /// A member property. The name may or may not be known. Member references
    /// always produce references.
    Member { name: Option<PropertyKey<'gc>> },
    /// A variable on the stack that is uninitialised at the point of reference.
    /// Using the reference will throw a ReferenceError.
    TemporalDeadZone { name: &'s str },
}

impl<'s, 'gc> Place<'s, 'gc> {
    fn identifier(&self) -> Option<String<'gc>> {
        match self {
            Place::Stack { name, .. } | Place::Env { name } | Place::Global { name } => Some(*name),
            Place::Member { name } => name.and_then(|n| {
                match n {
                    PropertyKey::SmallString(s) => Some(String::SmallString(s)),
                    PropertyKey::String(s) => Some(String::String(s)),
                    // TODO: we probably want to convert integers to strings.
                    _ => None,
                }
            }),
            Place::TemporalDeadZone { .. } => unreachable!(),
        }
    }

    /// Returns true if the place has a Reference on the reference stack
    /// associated with it.
    #[inline]
    fn has_reference(&self) -> bool {
        matches!(
            self,
            Self::Env { .. } | Self::Global { .. } | Self::Member { .. }
        )
    }

    fn initialise_referenced_binding_to_undefined(&self, ctx: &mut CompileContext) {
        match self {
            Place::Env { .. } | Place::Global { .. } | Place::Member { .. } => {
                ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Undefined);
                ctx.add_instruction(Instruction::InitializeReferencedBinding);
            }
            Place::Stack { .. } => {
                // Note: stack variables are initialised to undefined
                // automatically.
            }
            Place::TemporalDeadZone { .. } => {
                // Stack variables being initialised should never resolve to
                // TDZ.
                unreachable!();
            }
        }
    }

    fn initialise_referenced_binding(&self, ctx: &mut CompileContext, value: ValueOutput) {
        match self {
            Place::Env { .. } | Place::Global { .. } | Place::Member { .. } => {
                ctx.add_instruction(Instruction::InitializeReferencedBinding);
            }
            Place::Stack { stack_slot, .. } => {
                if value == ValueOutput::Literal(Primitive::Undefined) {
                    // Note: stack variables are initialised to undefined
                    // automatically.
                    return;
                }
                ctx.add_instruction_with_immediate(
                    Instruction::PutValueToIndex,
                    *stack_slot as usize,
                );
            }
            Place::TemporalDeadZone { .. } => {
                // Stack variables being initialised should never resolve to
                // TDZ.
                unreachable!();
            }
        }
    }

    fn get_value(
        &self,
        ctx: &mut CompileContext<'_, '_, 'gc, '_>,
    ) -> Result<ValueOutput<'static>, ExpressionError> {
        match self {
            Place::Stack { stack_slot, .. } => {
                // Variable is stored on the stack. Caching doesn't help here.
                ctx.add_instruction_with_immediate(
                    Instruction::GetValueFromIndex,
                    *stack_slot as usize,
                );
                Ok(ValueOutput::Value)
            }
            Place::Global { name } => {
                // Variable is stored in the global environment. Caching helps with
                // these accesses.
                let cache = ctx.create_property_lookup_cache(name.to_property_key());
                ctx.add_instruction_with_cache(Instruction::GetValueWithCache, cache);
                Ok(ValueOutput::Value)
            }
            Place::Member { name: Some(name) } => {
                // Property access. Caching helps with these.
                let cache = ctx.create_property_lookup_cache(*name);
                ctx.add_instruction_with_cache(Instruction::GetValueWithCache, cache);
                Ok(ValueOutput::Value)
            }
            Place::Member { .. } | Place::Env { .. } => {
                // Variable is stored in the environment or we don't know the
                // property name at compile time. Caching doesn't help with these.
                ctx.add_instruction(Instruction::GetValue);
                Ok(ValueOutput::Value)
            }
            Place::TemporalDeadZone { name } => {
                let message =
                    format!("can't access lexical declaration '{name}' before initialization");
                let message = ctx.create_string_from_owned(message);
                ctx.add_instruction_with_constant(Instruction::StoreConstant, message);
                ctx.add_instruction_with_immediate(
                    Instruction::ThrowError,
                    ExceptionType::ReferenceError as usize,
                );
                Err(ExpressionError::Error)
            }
        }
    }

    fn get_value_keep_reference(
        &self,
        ctx: &mut CompileContext<'_, '_, 'gc, '_>,
    ) -> Result<ValueOutput<'static>, ExpressionError> {
        match self {
            Self::Stack { stack_slot, .. } => {
                // Variable is stored on the stack. Caching doesn't help here and
                // we never have a reference to keep here.
                ctx.add_instruction_with_immediate(
                    Instruction::GetValueFromIndex,
                    *stack_slot as usize,
                );
                Ok(ValueOutput::Value)
            }
            Self::Global { name } => {
                // Variable is stored in the global environment. Caching helps with
                // these accesses.
                let cache = ctx.create_property_lookup_cache(name.to_property_key());
                ctx.add_instruction_with_cache(Instruction::GetValueWithCacheKeepReference, cache);
                Ok(ValueOutput::Value)
            }
            Self::Member { name: Some(name) } => {
                // Property access. Caching helps with these.
                let cache = ctx.create_property_lookup_cache(*name);
                ctx.add_instruction_with_cache(Instruction::GetValueWithCacheKeepReference, cache);
                Ok(ValueOutput::Value)
            }
            Self::Member { .. } | Self::Env { .. } => {
                // Variable is stored in the environment or we don't know the
                // property name at compile time. Caching doesn't help with these.
                ctx.add_instruction(Instruction::GetValueKeepReference);
                Ok(ValueOutput::Value)
            }
            Self::TemporalDeadZone { name } => {
                let message =
                    format!("can't access lexical declaration '{name}' before initialization");
                let message = ctx.create_string_from_owned(message);
                ctx.add_instruction_with_constant(Instruction::StoreConstant, message);
                ctx.add_instruction_with_immediate(
                    Instruction::ThrowError,
                    ExceptionType::ReferenceError as usize,
                );
                Err(ExpressionError::Error)
            }
        }
    }

    #[inline]
    fn get_value_maybe_keep_reference(
        &self,
        ctx: &mut CompileContext<'_, '_, 'gc, '_>,
        keep_reference: bool,
    ) -> Result<ValueOutput<'static>, ExpressionError> {
        if keep_reference {
            self.get_value_keep_reference(ctx)
        } else {
            self.get_value(ctx)
        }
    }

    fn put_value(
        &self,
        ctx: &mut CompileContext<'_, '_, 'gc, '_>,
        _value: ValueOutput,
    ) -> Result<(), ExpressionError> {
        // Note: _value is currently unused but may be used in the future to
        // perform optimisations.
        match self {
            Self::Stack {
                stack_slot,
                mutable,
                name,
            } => {
                if !mutable {
                    // a. Assert: This is an attempt to change the value of an
                    //    immutable binding. b. If S is true, throw a TypeError
                    //    exception.
                    let message = format!(
                        "invalid assignment to const '{}'",
                        name.to_string_lossy_(ctx.get_agent())
                    );
                    let message = ctx.create_string_from_owned(message);
                    ctx.add_instruction_with_constant(Instruction::StoreConstant, message);
                    ctx.add_instruction_with_immediate(
                        Instruction::ThrowError,
                        ExceptionType::TypeError as usize,
                    );
                    Err(ExpressionError::Error)
                } else {
                    ctx.add_instruction_with_immediate(
                        Instruction::PutValueToIndex,
                        *stack_slot as usize,
                    );
                    Ok(())
                }
            }
            Self::Global { name } => {
                let cache = ctx.create_property_lookup_cache(name.to_property_key());
                ctx.add_instruction_with_cache(Instruction::PutValueWithCache, cache);
                Ok(())
            }
            Self::Member { name: Some(name) } => {
                let cache = ctx.create_property_lookup_cache(*name);
                ctx.add_instruction_with_cache(Instruction::PutValueWithCache, cache);
                Ok(())
            }
            Self::Member { .. } | Self::Env { .. } => {
                ctx.add_instruction(Instruction::PutValue);
                Ok(())
            }
            Self::TemporalDeadZone { name } => {
                let message =
                    format!("can't access lexical declaration '{name}' before initialization");
                let message = ctx.create_string_from_owned(message);
                ctx.add_instruction_with_constant(Instruction::StoreConstant, message);
                ctx.add_instruction_with_immediate(
                    Instruction::ThrowError,
                    ExceptionType::ReferenceError as usize,
                );
                Err(ExpressionError::Error)
            }
        }
    }

    fn delete(
        self,
        ctx: &mut CompileContext<'_, '_, 'gc, '_>,
    ) -> Result<ValueOutput<'static>, ExpressionError> {
        match self {
            Self::Stack { .. } => {
                // Delete on a stack variable is only allowed for lexical
                // declarations, as they always return `false`.
                ctx.add_instruction_with_constant(Instruction::StoreConstant, false);
                Ok(false.into())
            }
            Self::Global { .. } | Self::Member { .. } | Self::Env { .. } => {
                ctx.add_instruction(Instruction::Delete);
                // Can return `true` or `false`.
                Ok(ValueOutput::Value)
            }
            Self::TemporalDeadZone { name } => {
                let message =
                    format!("can't access lexical declaration '{name}' before initialization");
                let message = ctx.create_string_from_owned(message);
                ctx.add_instruction_with_constant(Instruction::StoreConstant, message);
                ctx.add_instruction_with_immediate(
                    Instruction::ThrowError,
                    ExceptionType::ReferenceError as usize,
                );
                Err(ExpressionError::Error)
            }
        }
    }
}

impl<'gc> From<PropertyKey<'gc>> for Place<'_, 'gc> {
    #[inline]
    fn from(name: PropertyKey<'gc>) -> Self {
        Self::Member { name: Some(name) }
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum ValueOutput<'gc> {
    /// Expression evaluates to some unknown value.
    Value,
    /// Expression evaluates to a known literal value.
    Literal(Primitive<'gc>),
}

impl<'gc> ValueOutput<'gc> {
    fn to_expression_key(self) -> Place<'static, 'gc> {
        match self {
            Self::Value => Place::Member { name: None },
            Self::Literal(p) => match p {
                Primitive::Undefined => BUILTIN_STRING_MEMORY.undefined.to_property_key().into(),
                Primitive::Null => BUILTIN_STRING_MEMORY.null.to_property_key().into(),
                Primitive::Boolean(true) => BUILTIN_STRING_MEMORY.r#true.to_property_key().into(),
                Primitive::Boolean(false) => BUILTIN_STRING_MEMORY.r#false.to_property_key().into(),
                Primitive::String(s) => PropertyKey::String(s).into(),
                Primitive::SmallString(s) => PropertyKey::SmallString(s).into(),
                // Other members don't benefit from caching anyway.
                _ => Place::Member { name: None },
            },
        }
    }
}

impl<'gc, T> From<T> for ValueOutput<'gc>
where
    T: 'gc + Into<Primitive<'gc>>,
{
    #[inline]
    fn from(value: T) -> Self {
        Self::Literal(value.into())
    }
}

fn combine_value_results<'gc>(
    a: Result<ValueOutput<'gc>, ExpressionError>,
    b: Result<ValueOutput<'gc>, ExpressionError>,
) -> Result<ValueOutput<'gc>, ExpressionError> {
    match (a, b) {
        // If two branches unconditionally error, the combination
        // unconditionally errors.
        (Err(err), Err(_)) => Err(err),
        // If two branches evaluate to the same literal, the combination
        // unconditionally evaluates to that literal.
        (Ok(ValueOutput::Literal(a)), Ok(ValueOutput::Literal(b))) if a == b => {
            Ok(ValueOutput::Literal(a))
        }
        // If one branch unconditionally errors and the other does not, the only
        // possible value is the one from the successful one.
        (Ok(v), Err(_)) | (Err(_), Ok(v)) => Ok(v),
        // Otherwise we just end up in unknown value land.
        _ => Ok(ValueOutput::Value),
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum PlaceOrValue<'s, 'gc> {
    /// Expression evaluates to a value.
    Value(ValueOutput<'gc>),
    /// Expression evaluates to a place.
    Place(Place<'s, 'gc>),
}

impl<'gc, T> From<T> for PlaceOrValue<'static, 'gc>
where
    T: 'gc + Into<ValueOutput<'gc>>,
{
    #[inline]
    fn from(value: T) -> Self {
        Self::Value(value.into())
    }
}

impl<'s, 'gc> From<Place<'s, 'gc>> for PlaceOrValue<'s, 'gc> {
    #[inline]
    fn from(value: Place<'s, 'gc>) -> Self {
        Self::Place(value)
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
#[must_use]
pub(crate) enum ExpressionError {
    /// Expression evaluates to an abrupt throw.
    Error,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum StatementContinue<'gc> {
    /// Statement evaluates to some unknown value.
    Value,
    /// Statement evaluates to a known literal value.
    Literal(Primitive<'gc>),
    /// Statement evaluates to EMPTY (coerces to undefined).
    Empty,
}

impl<'gc> From<ValueOutput<'gc>> for StatementContinue<'gc> {
    #[inline]
    fn from(value: ValueOutput<'gc>) -> Self {
        match value {
            ValueOutput::Value => Self::Value,
            ValueOutput::Literal(lit) => Self::Literal(lit),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
#[must_use]
pub(crate) enum StatementBreak {
    /// Statement evaluates to an abrupt throw.
    Error,
    /// Statement evaluates to an abrupt return.
    Return,
    /// Statement evaluates to an abrupt break.
    Break,
    /// Statement evaluates to an abrupt continue.
    Continue,
}

impl From<ExpressionError> for StatementBreak {
    #[inline]
    fn from(value: ExpressionError) -> StatementBreak {
        match value {
            ExpressionError::Error => Self::Error,
        }
    }
}

pub(crate) type StatementResult<'gc> = ControlFlow<StatementBreak, StatementContinue<'gc>>;

#[inline]
pub(super) fn value_result_to_statement_result<'gc>(
    result: Result<ValueOutput<'gc>, ExpressionError>,
) -> StatementResult<'gc> {
    match result {
        Ok(v) => ControlFlow::Continue(v.into()),
        Err(e) => ControlFlow::Break(e.into()),
    }
}

impl<'gc> From<StatementContinue<'gc>> for StatementResult<'gc> {
    #[inline]
    fn from(value: StatementContinue<'gc>) -> StatementResult<'gc> {
        Self::Continue(value)
    }
}

impl From<StatementBreak> for StatementResult<'static> {
    #[inline]
    fn from(value: StatementBreak) -> StatementResult<'static> {
        Self::Break(value)
    }
}

impl<'s, 'gc> PlaceOrValue<'s, 'gc> {
    #[inline]
    fn is_stack_variable(&self) -> bool {
        matches!(self, PlaceOrValue::Place(Place::Stack { .. }))
    }

    /// Returns true if the expression has a Reference on the reference stack
    /// associated with it.
    #[inline]
    fn has_reference(&self) -> bool {
        match self {
            PlaceOrValue::Place(place) => place.has_reference(),
            _ => false,
        }
    }

    fn get_value(
        self,
        ctx: &mut CompileContext<'_, '_, 'gc, '_>,
    ) -> Result<ValueOutput<'gc>, ExpressionError> {
        match self {
            Self::Place(place) => {
                place.get_value(ctx)?;
                // After evaluating the GetValue we return an unknown Value.
                Ok(ValueOutput::Value)
            }
            // No GetValue needed.
            Self::Value(value) => Ok(value),
        }
    }

    fn get_value_keep_reference(
        self,
        ctx: &mut CompileContext<'_, '_, 'gc, '_>,
    ) -> Result<ValueOutput<'gc>, ExpressionError> {
        match self {
            Self::Place(place) => {
                place.get_value_keep_reference(ctx)?;
                // After evaluating the GetValue we return an unknown Value.
                Ok(ValueOutput::Value)
            }
            // No GetValue needed.
            Self::Value(value) => Ok(value),
        }
    }

    fn delete(
        self,
        ctx: &mut CompileContext<'_, '_, 'gc, '_>,
    ) -> Result<ValueOutput<'gc>, ExpressionError> {
        match self {
            PlaceOrValue::Place(place) => place.delete(ctx),
            _ => {
                // 2. If ref is not a Reference Record, return true.
                ctx.add_instruction_with_constant(Instruction::StoreConstant, true);
                Ok(true.into())
            }
        }
    }
}

impl<'a, 's, 'gc, 'scope, T: CompileEvaluation<'a, 's, 'gc, 'scope>>
    CompileLabelledEvaluation<'a, 's, 'gc, 'scope> for T
{
    type Output = ();

    fn compile_labelled(
        &'s self,
        _label_set: Option<&mut Vec<&'s ast::LabelIdentifier<'s>>>,
        ctx: &mut CompileContext<'a, 's, 'gc, 'scope>,
    ) {
        self.compile(ctx);
    }
}

fn variable_escapes_scope(
    ctx: &CompileContext,
    identifier: &oxc_ast::ast::BindingIdentifier,
) -> bool {
    let agent = ctx.get_agent();
    let sc = ctx.get_source_code();
    let scoping = sc.get_scoping(agent);
    let nodes = sc.get_nodes(agent);
    let s = identifier.symbol_id();
    if !scoping.symbol_redeclarations(s).is_empty() {
        // Redeclarations are a pain to deal with.
        return true;
    }
    let decl_scope = scoping.symbol_scope_id(s);
    if scoping.scope_flags(decl_scope).contains_direct_eval() {
        return true;
    }
    let decl_id = scoping.symbol_declaration(s);
    let symbol_flags = scoping.symbol_flags(s);
    let is_lexical = symbol_flags.intersects(SymbolFlags::BlockScopedVariable);
    let is_class = symbol_flags.is_class();
    for reference in scoping.get_resolved_references(s) {
        let ref_id = reference.node_id();
        if !is_lexical
            && nodes
                .get_node(ref_id)
                .kind()
                .as_unary_expression()
                .is_some_and(|expr| expr.operator.is_delete())
        {
            // Deleting non-lexical references has effects outside of the
            // immediate scope and is thus considered escaping.
            return true;
        }
        let mut scope = nodes.get_node(ref_id).scope_id();
        while scope != decl_scope {
            let flags = scoping.scope_flags(scope);
            if flags.is_var() || flags.contains_direct_eval() || flags.is_with() {
                return true;
            }
            let Some(s) = scoping.scope_parent_id(scope) else {
                panic!("reference in a different scope?")
            };
            scope = s;
        }
        // Classes can refer to themselves both during their creation and in
        // field declarations that escape creation time. We need to check for
        // them.
        if is_class {
            let mut node = ref_id;
            while decl_id < node {
                node = nodes.parent_id(node);
            }
            if decl_id == node {
                // Self-referential class declaration.
                return true;
            }
        }
    }
    false
}

pub(crate) fn is_reference(expression: &ast::Expression) -> bool {
    matches!(
        expression.get_inner_expression(),
        ast::Expression::Identifier(_)
            | ast::Expression::ComputedMemberExpression(_)
            | ast::Expression::StaticMemberExpression(_)
            | ast::Expression::PrivateFieldExpression(_)
    )
}

pub(crate) fn is_boolean_literal_true(expression: &ast::Expression) -> bool {
    matches!(expression.get_inner_expression(), ast::Expression::BooleanLiteral(lit) if lit.value)
}

pub(crate) fn is_boolean_literal_false(expression: &ast::Expression) -> bool {
    matches!(expression.get_inner_expression(), ast::Expression::BooleanLiteral(lit) if !lit.value)
}

fn is_chain_expression(expression: &ast::Expression) -> bool {
    matches!(
        expression.get_inner_expression(),
        ast::Expression::ChainExpression(_)
    )
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::NumericLiteral<'s> {
    type Output = Primitive<'gc>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        let constant = ctx.create_number(self.value);
        ctx.add_instruction_with_constant(Instruction::StoreConstant, constant);
        constant.into()
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::BooleanLiteral {
    type Output = Primitive<'gc>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        ctx.add_instruction_with_constant(Instruction::StoreConstant, self.value);
        self.value.into()
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::BigIntLiteral<'s> {
    type Output = BigInt<'gc>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // Drop out the trailing 'n' from BigInt literals.
        let raw_str = self
            .raw
            .as_ref()
            .expect("BigInt literal should have raw text")
            .as_str();
        let last_index = raw_str.len() - 1;
        let (literal, radix) = match self.base {
            oxc_syntax::number::BigintBase::Decimal => (&raw_str[..last_index], 10),
            oxc_syntax::number::BigintBase::Binary => (&raw_str[2..last_index], 2),
            oxc_syntax::number::BigintBase::Octal => (&raw_str[2..last_index], 8),
            oxc_syntax::number::BigintBase::Hex => (&raw_str[2..last_index], 16),
        };
        let constant = ctx.create_bigint(literal, radix);
        ctx.add_instruction_with_constant(Instruction::StoreConstant, constant);
        constant
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::NullLiteral {
    type Output = Primitive<'static>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Null);
        Primitive::Null
    }
}

pub(crate) fn string_literal_to_wtf8<'a>(
    agent: &mut Agent,
    string: &ast::StringLiteral,
    gc: NoGcScope<'a, '_>,
) -> String<'a> {
    if string.lone_surrogates {
        let mut buf = Wtf8Buf::with_capacity(string.value.len());
        let mut str = string.value.as_str();
        while let Some(replacement_character_index) = str.find("\u{FFFD}") {
            // Lone surrogates are encoded as \u{FFFD}XXXX and \u{FFFD}
            // itself is encoded as \u{FFFD}fffd: hence the fact that we
            // found a replacement character means that we're guaranteed to
            // have 7 bytes ahead of the replacement character index: 3 for
            // the replacement character itself, 4 for the encoded bytes.

            let (preceding, following) = str.split_at(replacement_character_index);
            let (encoded_surrogate, rest) = following.split_at(7);

            // First copy our preceding slice into the buffer.
            if !preceding.is_empty() {
                // SAFETY: we're working within our search buffer.
                buf.push_str(preceding);
            }
            // Drop the replacement character from our str slice.
            str = rest;
            // Then split off the encoded bytes.
            let encoded_bytes: &[u8; 7] = encoded_surrogate.as_bytes().first_chunk().unwrap();
            fn char_code_to_u16(char_code: u8) -> u16 {
                if char_code >= 97 {
                    // 'a'..'f'
                    (char_code - 87) as u16
                } else {
                    // '0'..'9'
                    (char_code - 48) as u16
                }
            }
            let value = (char_code_to_u16(encoded_bytes[3]) << 12)
                + (char_code_to_u16(encoded_bytes[4]) << 8)
                + (char_code_to_u16(encoded_bytes[5]) << 4)
                + char_code_to_u16(encoded_bytes[6]);
            // SAFETY: Value cannot be larger than 0xFFFF.
            let code_point = unsafe { CodePoint::from_u32_unchecked(value as u32) };
            buf.push(code_point);
        }
        if !str.is_empty() {
            buf.push_str(str);
        }
        String::from_wtf8_buf(agent, buf, gc)
    } else {
        String::from_str(agent, string.value.as_str(), gc)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::StringLiteral<'s> {
    type Output = Primitive<'gc>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        let (agent, gc) = ctx.get_agent_and_gc();
        let constant = string_literal_to_wtf8(agent, self, gc);
        ctx.add_instruction_with_constant(Instruction::StoreConstant, constant);
        constant.into()
    }
}

enum VariableKind {
    /// Stored on the stack, not accessible by name at all.
    Stack { stack_slot: u32, mutable: bool },
    /// Reference to a stack variable in the temporal dead zone of a lexical
    /// declaration. The referrer should throw an error in the bytecode and
    /// skip any further work.
    TemporalDeadZone,
    /// Stored in an environment.
    Local,
    /// Found in the global scope.
    Global,
}

impl VariableKind {
    fn compile<'s, 'gc>(
        self,
        ctx: &mut CompileContext<'_, 's, 'gc, '_>,
        name: &'s str,
    ) -> Place<'s, 'gc> {
        match self {
            VariableKind::Stack {
                stack_slot,
                mutable,
            } => {
                let name = ctx.create_string(name);
                // variable on the stack
                Place::Stack {
                    name,
                    stack_slot,
                    mutable,
                }
            }
            VariableKind::TemporalDeadZone => Place::TemporalDeadZone { name },
            VariableKind::Local => {
                let name = ctx.create_string(name);
                // Local variable: property name caching is not useful here.
                ctx.add_instruction_with_identifier(
                    Instruction::ResolveBinding,
                    name.to_property_key(),
                );
                Place::Env { name }
            }
            VariableKind::Global => {
                let name = ctx.create_string(name);
                // Global variable: property name caching is useful here.
                let cache = ctx.create_property_lookup_cache(name.to_property_key());
                ctx.add_instruction_with_identifier_and_cache(
                    Instruction::ResolveBindingWithCache,
                    name,
                    cache,
                );
                Place::Global { name }
            }
        }
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::IdentifierReference<'s> {
    type Output = Place<'s, 'gc>;
    /// Compile a reference TO a variable. This is used to read or write to a
    /// variable.
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        let kind = if let Some(id) = self.reference_id.get() {
            let source_code = ctx.get_source_code();
            let scoping = source_code.get_scoping(ctx.get_agent());
            let reference = scoping.get_reference(id);
            if let Some(s) = reference.symbol_id() {
                // SymbolId means we might be a global, local, or a stack
                // variable.
                let symbol_flags = scoping.symbol_flags(s);
                let mutable = !symbol_flags.is_const_variable();
                if let Some(stack_slot) = ctx.get_variable_stack_index(s) {
                    // We're a stack variable.
                    let nodes = source_code.get_nodes(ctx.get_agent());
                    let ref_id = reference.node_id();
                    let decl_id = scoping.symbol_declaration(s);
                    if decl_id == ref_id {
                        // Reference should never be the declaration itself.
                        unreachable!();
                    }
                    let is_lexical = symbol_flags.intersects(SymbolFlags::BlockScopedVariable);
                    // We might be in the temporal dead-zone.
                    if is_lexical && ref_id < decl_id
                        || !is_lexical && is_parameter_tdz(nodes, decl_id, ref_id)
                    {
                        // Reference before initialization: this is TDZ.
                        VariableKind::TemporalDeadZone
                    } else if nodes.get_node(decl_id).scope_id() == scoping.symbol_scope_id(s) {
                        // If the node comes after the declaration and is in the
                        // same scope, it's still possible for it to be in the
                        // TDZ if it is itself within the declaration
                        // expression. To detect this, we iterate parent nodes
                        // until we find one that is equal to or before the
                        // declaration. If we found the declaration this way,
                        // then this is TDZ.
                        let mut node = ref_id;
                        while decl_id < node {
                            node = nodes.parent_id(node);
                        }
                        if decl_id == node {
                            // Self-referential declaration.
                            VariableKind::TemporalDeadZone
                        } else {
                            VariableKind::Stack {
                                stack_slot,
                                mutable,
                            }
                        }
                    } else {
                        VariableKind::Stack {
                            stack_slot,
                            mutable,
                        }
                    }
                } else {
                    let scope_id = scoping.symbol_scope_id(s);
                    let scope_flags = scoping.scope_flags(scope_id);
                    // Functions declarations and variables defined at the top
                    // level scope end up in the globalThis; we want a property
                    // lookup cache for those.
                    if scope_flags.contains(ScopeFlags::Top)
                        && (symbol_flags.contains(SymbolFlags::FunctionScopedVariable)
                            | symbol_flags.contains(SymbolFlags::Function))
                    {
                        VariableKind::Global
                    } else {
                        VariableKind::Local
                    }
                }
            } else {
                // No SymbolId means this must be a global name.
                VariableKind::Global
            }
        } else {
            // No reference at all: global I guess?
            VariableKind::Global
        };
        kind.compile(ctx, &self.name)
    }
}

/// Formal parameter lists also have a temporal dead-zone; when the list does
/// not contain duplicates (which we consider always escaping), any reference to
/// later parameters from earlier parameters' default expressions is in a TDZ.
fn is_parameter_tdz(nodes: &oxc_semantic::AstNodes, decl_id: NodeId, ref_id: NodeId) -> bool {
    let decl_parent_id = nodes.parent_id(decl_id);
    let oxc_ast::AstKind::FormalParameters(_) = nodes.get_node(decl_parent_id).kind() else {
        // If the declaration isn't a formal parameter, then this cannot be in
        // TDZ.
        return false;
    };
    // Reference points to a formal parameter: this means that we might be in
    // its TDZ.
    if ref_id < decl_id {
        // If our reference is before the formal parameter then we definitely
        // are in the TDZ.
        return true;
    }
    // If our reference comes after the formal parameter we might still be in
    // the TDZ but a followup check tests for that.
    false
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::BindingIdentifier<'s> {
    type Output = Place<'s, 'gc>;
    /// Compile variable binding. This is used to create a variable.
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        let kind = {
            let s = self.symbol_id();
            if let Some(stack_slot) = ctx.get_variable_stack_index(s) {
                // We're a stack variable declaration.
                VariableKind::Stack {
                    stack_slot,
                    // Variable declarations can always mutate the stack slot.
                    mutable: true,
                }
            } else {
                let source_code = ctx.get_source_code();
                let scoping = source_code.get_scoping(ctx.get_agent());
                let scope_id = scoping.symbol_scope_id(s);
                let scope_flags = scoping.scope_flags(scope_id);
                let symbol_flags = scoping.symbol_flags(s);
                // Functions declarations and variables defined at the top
                // level scope end up in the globalThis; we want a property
                // lookup cache for those.
                if scope_flags.contains(ScopeFlags::Top)
                    && (symbol_flags.contains(SymbolFlags::FunctionScopedVariable)
                        | symbol_flags.contains(SymbolFlags::Function))
                {
                    VariableKind::Global
                } else {
                    VariableKind::Local
                }
            }
        };
        kind.compile(ctx, &self.name)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::IdentifierName<'s> {
    type Output = Place<'s, 'gc>;

    /// Property name in member expressions etc. Has nothing to do with `foo`
    /// in `let foo` unlike type documentation states.
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        let identifier = ctx.create_string(self.name.as_str());
        ctx.add_instruction_with_identifier(
            Instruction::EvaluatePropertyAccessWithIdentifierKey,
            identifier.to_property_key(),
        );
        identifier.to_property_key().into()
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::UnaryExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    /// # ['a 13.5 Unary Operators](https://tc39.es/ecma262/#sec-unary-operators)
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        match self.operator {
            // 13.5.5 Unary - Operator
            // https://tc39.es/ecma262/#sec-unary-minus-operator-runtime-semantics-evaluation
            // UnaryExpression : - UnaryExpression
            UnaryOperator::UnaryNegation => {
                // 1. Let expr be ? Evaluation of UnaryExpression.
                // 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
                self.argument.compile(ctx)?.get_value(ctx)?;
                ctx.add_instruction(Instruction::ToNumeric);

                // 3. If oldValue is a Number, then
                //    a. Return Number::unaryMinus(oldValue).
                // 4. Else,
                //    a. Assert: oldValue is a BigInt.
                //    b. Return BigInt::unaryMinus(oldValue).
                ctx.add_instruction(Instruction::UnaryMinus);
                Ok(ValueOutput::Value)
            }
            // 13.5.4 Unary + Operator
            // https://tc39.es/ecma262/#sec-unary-plus-operator
            // UnaryExpression : + UnaryExpression
            UnaryOperator::UnaryPlus => {
                // 1. Let expr be ? Evaluation of UnaryExpression.
                // 2. Return ? ToNumber(? GetValue(expr)).
                self.argument.compile(ctx)?.get_value(ctx)?;
                ctx.add_instruction(Instruction::ToNumber);
                Ok(ValueOutput::Value)
            }
            // 13.5.6 Unary ! Operator
            // https://tc39.es/ecma262/#sec-logical-not-operator-runtime-semantics-evaluation
            // UnaryExpression : ! UnaryExpression
            UnaryOperator::LogicalNot => {
                // 1. Let expr be ? Evaluation of UnaryExpression.
                // 2. Let oldValue be ToBoolean(? GetValue(expr)).
                self.argument.compile(ctx)?.get_value(ctx)?;
                // 3. If oldValue is true, return false.
                // 4. Return true.
                ctx.add_instruction(Instruction::LogicalNot);
                Ok(ValueOutput::Value)
            }
            // 13.5.7 Unary ~ Operator
            // https://tc39.es/ecma262/#sec-bitwise-not-operator-runtime-semantics-evaluation
            // UnaryExpression : ~ UnaryExpression
            UnaryOperator::BitwiseNot => {
                // 1. Let expr be ? Evaluation of UnaryExpression.
                // 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
                self.argument.compile(ctx)?.get_value(ctx)?;
                ctx.add_instruction(Instruction::ToNumeric);

                // 3. If oldValue is a Number, then
                //    a. Return Number::bitwiseNOT(oldValue).
                // 4. Else,
                //    a. Assert: oldValue is a BigInt.
                //    b. Return BigInt::bitwiseNOT(oldValue).
                ctx.add_instruction(Instruction::BitwiseNot);
                Ok(ValueOutput::Value)
            }
            // 13.5.3 The typeof Operator
            // UnaryExpression : typeof UnaryExpression
            UnaryOperator::Typeof => {
                // 1. Let val be ? Evaluation of UnaryExpression.
                let val = self.argument.compile(ctx)?;
                if val.is_stack_variable() {
                    // Stack variables would normally be references but as
                    // they have no Reference (and are known to be resolvable),
                    // we call GetValue directly.
                    val.get_value(ctx)?;
                }
                // 3. Set val to ? GetValue(val).
                ctx.add_instruction(Instruction::Typeof);
                Ok(ValueOutput::Value)
            }
            // 13.5.2 The void operator
            // UnaryExpression : void UnaryExpression
            UnaryOperator::Void => {
                // 1. Let expr be ? Evaluation of UnaryExpression.
                // NOTE: GetValue must be called even though its value is not used because it may have observable side-effects.
                // 2. Perform ? GetValue(expr).
                if !self.argument.is_literal() {
                    self.argument.compile(ctx)?.get_value(ctx)?;
                }
                // 3. Return undefined.
                ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Undefined);
                Ok(ValueOutput::Value)
            }
            // 13.5.1 The delete operator
            // https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
            // UnaryExpression : delete UnaryExpression
            UnaryOperator::Delete => {
                // Let ref be ? Evaluation of UnaryExpression.
                self.argument.compile(ctx)?.delete(ctx)
            }
        }
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::BinaryExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // 1. Let lref be ? Evaluation of leftOperand.
        let lref = self.left.compile(ctx)?;
        // 2. Let lval be ? GetValue(lref).
        let _lval = lref.get_value(ctx)?;
        let lval_on_stack = ctx.load_to_stack();

        // 3. Let rref be ? Evaluation of rightOperand.
        let rref = self.right.compile(ctx);
        // 4. Let rval be ? GetValue(rref).
        let rval = rref.and_then(|r| r.get_value(ctx));

        if let Err(err) = rval {
            lval_on_stack.forget(ctx);
            return Err(err);
        }

        let op_text = match self.operator {
            BinaryOperator::LessThan => Instruction::LessThan,
            BinaryOperator::LessEqualThan => Instruction::LessThanEquals,
            BinaryOperator::GreaterThan => Instruction::GreaterThan,
            BinaryOperator::GreaterEqualThan => Instruction::GreaterThanEquals,
            BinaryOperator::StrictEquality => Instruction::IsStrictlyEqual,
            BinaryOperator::StrictInequality => {
                ctx.add_instruction(Instruction::IsStrictlyEqual);
                Instruction::LogicalNot
            }
            BinaryOperator::Equality => Instruction::IsLooselyEqual,
            BinaryOperator::Inequality => {
                ctx.add_instruction(Instruction::IsLooselyEqual);
                Instruction::LogicalNot
            }
            BinaryOperator::In => Instruction::HasProperty,
            BinaryOperator::Instanceof => Instruction::InstanceofOperator,
            BinaryOperator::Addition => Instruction::ApplyAdditionBinaryOperator,
            BinaryOperator::Subtraction => Instruction::ApplySubtractionBinaryOperator,
            BinaryOperator::Multiplication => Instruction::ApplyMultiplicationBinaryOperator,
            BinaryOperator::Division => Instruction::ApplyDivisionBinaryOperator,
            BinaryOperator::Remainder => Instruction::ApplyRemainderBinaryOperator,
            BinaryOperator::Exponential => Instruction::ApplyExponentialBinaryOperator,
            BinaryOperator::ShiftLeft => Instruction::ApplyShiftLeftBinaryOperator,
            BinaryOperator::ShiftRight => Instruction::ApplyShiftRightBinaryOperator,
            BinaryOperator::ShiftRightZeroFill => {
                Instruction::ApplyShiftRightZeroFillBinaryOperator
            }
            BinaryOperator::BitwiseOR => Instruction::ApplyBitwiseORBinaryOperator,
            BinaryOperator::BitwiseXOR => Instruction::ApplyBitwiseXORBinaryOperator,
            BinaryOperator::BitwiseAnd => Instruction::ApplyBitwiseAndBinaryOperator,
        };
        // 5. Return ? ApplyStringOrNumericBinaryOperator(lval, opText, rval).
        lval_on_stack.forget(ctx);
        ctx.add_instruction(op_text);
        Ok(ValueOutput::Value)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::LogicalExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        let lref = self.left.compile(ctx)?;
        let lval = lref.get_value(ctx)?;

        // We store the left value on the stack, because we'll need to restore
        // it later.
        let lval_copy = ctx.load_copy_to_stack();

        match self.operator {
            oxc_syntax::operator::LogicalOperator::Or => {
                ctx.add_instruction(Instruction::LogicalNot);
            }
            oxc_syntax::operator::LogicalOperator::And => {}
            oxc_syntax::operator::LogicalOperator::Coalesce => {
                ctx.add_instruction(Instruction::IsNullOrUndefined);
            }
        }
        let jump_to_return_left = ctx.add_instruction_with_jump_slot(Instruction::JumpIfNot);

        // We're returning the right expression, so we discard the left value
        // at the top of the stack.
        lval_copy.pop(ctx);

        let rref = self.right.compile(ctx);
        let rval = rref.and_then(|r| r.get_value(ctx));

        let jump_to_end = ctx.add_instruction_with_jump_slot(Instruction::Jump);

        ctx.set_jump_target_here(jump_to_return_left);
        // Return the result of the left expression.
        let lval_copy = ctx.mark_stack_value();
        lval_copy.store(ctx);
        ctx.set_jump_target_here(jump_to_end);
        combine_value_results(Ok(lval), rval)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope>
    for ast::ParenthesizedExpression<'s>
{
    type Output = Result<PlaceOrValue<'s, 'gc>, ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        self.expression.compile(ctx)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope>
    for ast::ArrowFunctionExpression<'s>
{
    type Output = ();
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // CompileContext holds a name identifier for us if this is NamedEvaluation.
        let identifier = ctx.name_identifier.take();
        ctx.add_arrow_function_expression(ArrowFunctionExpression {
            expression: SendableRef::new(unsafe {
                core::mem::transmute::<
                    &ast::ArrowFunctionExpression<'_>,
                    &'static ast::ArrowFunctionExpression<'static>,
                >(self)
            }),
            identifier,
        });
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::Function<'s> {
    type Output = ();
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // CompileContext holds a name identifier for us if this is NamedEvaluation.
        let identifier = ctx.name_identifier.take();
        ctx.add_instruction_with_function_expression(
            Instruction::InstantiateOrdinaryFunctionExpression,
            FunctionExpression {
                expression: SendableRef::new(unsafe {
                    core::mem::transmute::<&ast::Function<'_>, &'static ast::Function<'static>>(
                        self,
                    )
                }),
                identifier,
                compiled_bytecode: None,
            },
        );
    }
}

fn create_object_with_shape<'s, 'gc>(
    expr: &'s ast::ObjectExpression<'s>,
    ctx: &mut CompileContext<'_, 's, 'gc, '_>,
) -> Result<ValueOutput<'gc>, ExpressionError> {
    let proto_prop = expr.properties.iter().find(|prop| {
        let ast::ObjectPropertyKind::ObjectProperty(prop) = prop else {
            unreachable!()
        };
        prop.key.is_specific_static_name("__proto__")
            && prop.kind == ast::PropertyKind::Init
            && !prop.shorthand
    });
    let prototype = if let Some(proto_prop) = proto_prop {
        let ast::ObjectPropertyKind::ObjectProperty(proto_prop) = proto_prop else {
            unreachable!()
        };
        if proto_prop.value.is_null() {
            None
        } else {
            Some(
                ctx.get_agent()
                    .current_realm_record()
                    .intrinsics()
                    .object_prototype()
                    .into(),
            )
        }
    } else {
        Some(
            ctx.get_agent()
                .current_realm_record()
                .intrinsics()
                .object_prototype()
                .into(),
        )
    };
    let mut shape = ObjectShape::get_shape_for_prototype(ctx.get_agent_mut(), prototype);
    let mut prop_values_on_stack: Vec<StackValue> = Vec::with_capacity(expr.properties.len());
    for prop in expr.properties.iter() {
        let ast::ObjectPropertyKind::ObjectProperty(prop) = prop else {
            unreachable!()
        };
        if !prop.shorthand && prop.key.is_specific_static_name("__proto__") {
            continue;
        }
        let ast::PropertyKey::StaticIdentifier(id) = &prop.key else {
            unreachable!()
        };
        let identifier = ctx.create_property_key(&id.name);
        shape = shape
            .get_child_shape(ctx.get_agent_mut(), identifier)
            .expect("Should perform GC here");
        if is_anonymous_function_definition(&prop.value) {
            ctx.add_instruction_with_constant(Instruction::StoreConstant, identifier);
            ctx.name_identifier = Some(NamedEvaluationParameter::Result);
        }
        if let Err(err) = prop.value.compile(ctx).and_then(|r| r.get_value(ctx)) {
            for prop_on_stack in prop_values_on_stack {
                prop_on_stack.forget(ctx);
            }
            return Err(err);
        }

        prop_values_on_stack.push(ctx.load_to_stack());
    }
    // ObjectCreateWithShape consumes the props from the stack.
    for prop_on_stack in prop_values_on_stack {
        prop_on_stack.forget(ctx);
    }
    ctx.add_instruction_with_shape(Instruction::ObjectCreateWithShape, shape);
    Ok(ValueOutput::Value)
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ObjectExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if !self.properties.is_empty()
            && self.properties.iter().all(|prop| {
                !prop.is_spread() && {
                    let ast::ObjectPropertyKind::ObjectProperty(prop) = prop else {
                        unreachable!()
                    };
                    prop.kind == ast::PropertyKind::Init
                        && !prop.method
                        && prop.key.is_identifier()
                        && if prop.key.is_specific_static_name("__proto__") && !prop.shorthand {
                            prop.value.is_null_or_undefined()
                        } else {
                            true
                        }
                }
            })
        {
            let mut dedup_keys = self
                .properties
                .iter()
                .map(|prop| {
                    let ast::ObjectPropertyKind::ObjectProperty(prop) = prop else {
                        unreachable!()
                    };
                    let ast::PropertyKey::StaticIdentifier(key) = &prop.key else {
                        unreachable!()
                    };
                    key.name.as_str()
                })
                .collect::<Vec<_>>();
            dedup_keys.sort();
            dedup_keys.dedup();
            // Check that there are no duplicates.
            if dedup_keys.len() == self.properties.len() {
                // Can create Object Shape beforehand and calculate
                return create_object_with_shape(self, ctx);
            }
        }
        // TODO: Consider preparing the properties onto the stack and creating
        // the object with a known size.
        ctx.add_instruction(Instruction::ObjectCreate);
        let obj = ctx.mark_stack_value();
        for property in self.properties.iter() {
            match property {
                ast::ObjectPropertyKind::ObjectProperty(prop) => {
                    let mut is_proto_setter = false;
                    match &prop.key {
                        // It shouldn't be possible for objects to be created
                        // with private identifiers as keys.
                        ast::PropertyKey::PrivateIdentifier(_) => unreachable!(),
                        ast::PropertyKey::StaticIdentifier(id) => {
                            if id.name == "__proto__" {
                                if prop.kind == ast::PropertyKind::Init && !prop.shorthand {
                                    // If property key is "__proto__" then we
                                    // should dispatch a SetPrototype instruction.
                                    is_proto_setter = true;
                                } else {
                                    ctx.add_instruction_with_constant(
                                        Instruction::StoreConstant,
                                        BUILTIN_STRING_MEMORY.__proto__,
                                    );
                                }
                            } else {
                                let identifier = ctx.create_property_key(&id.name);
                                ctx.add_instruction_with_constant(
                                    Instruction::StoreConstant,
                                    identifier,
                                );
                            }
                        }
                        _ => {
                            let prop_key = prop.key.as_expression().unwrap();
                            if is_reference(prop_key) {
                                assert!(!is_proto_setter);
                            }
                            if let Err(err) = prop_key.compile(ctx).and_then(|r| r.get_value(ctx)) {
                                obj.forget(ctx);
                                return Err(err);
                            }
                        }
                    }
                    match prop.kind {
                        ast::PropertyKind::Init => {
                            if is_proto_setter {
                                if let Err(err) =
                                    prop.value.compile(ctx).and_then(|r| r.get_value(ctx))
                                {
                                    obj.forget(ctx);
                                    return Err(err);
                                }
                                // 7. If isProtoSetter is true, then
                                // a. If propValue is an Object or propValue is null, then
                                //     i. Perform ! object.[[SetPrototypeOf]](propValue).
                                // b. Return unused.
                                ctx.add_instruction(Instruction::ObjectSetPrototype);
                            } else if prop.method {
                                let ast::Expression::FunctionExpression(value) = &prop.value else {
                                    unreachable!()
                                };
                                let identifier = if is_anonymous_function_definition(&prop.value) {
                                    Some(NamedEvaluationParameter::Stack)
                                } else {
                                    None
                                };
                                // Note: not load_copy_to_stack as this is
                                // immediately consumed
                                ctx.add_instruction(Instruction::Load);
                                ctx.add_instruction_with_function_expression_and_immediate(
                                    Instruction::ObjectDefineMethod,
                                    FunctionExpression {
                                        expression: SendableRef::new(unsafe {
                                            core::mem::transmute::<
                                                &ast::Function<'_>,
                                                &'static ast::Function<'static>,
                                            >(value)
                                        }),
                                        identifier,
                                        compiled_bytecode: None,
                                    },
                                    // enumerable: true,
                                    true.into(),
                                );
                            } else {
                                if is_anonymous_function_definition(&prop.value) {
                                    ctx.name_identifier = Some(NamedEvaluationParameter::Stack);
                                }
                                let key_copy = ctx.load_to_stack();
                                let result = prop.value.compile(ctx).and_then(|r| r.get_value(ctx));
                                // Note: key copy is either forgotten on stack
                                // and gets cleaned up by try-catch if result is
                                // Err, or is consumed by ObjectDefineProperty.
                                key_copy.forget(ctx);
                                if let Err(err) = result {
                                    obj.forget(ctx);
                                    return Err(err);
                                }
                                ctx.add_instruction(Instruction::ObjectDefineProperty);
                            }
                        }
                        ast::PropertyKind::Get | ast::PropertyKind::Set => {
                            // Note: no load_copy_to_stack as this is
                            // immediately consumed.
                            ctx.add_instruction(Instruction::Load);
                            let is_get = prop.kind == ast::PropertyKind::Get;
                            let ast::Expression::FunctionExpression(function_expression) =
                                &prop.value
                            else {
                                unreachable!()
                            };
                            ctx.add_instruction_with_function_expression_and_immediate(
                                if is_get {
                                    Instruction::ObjectDefineGetter
                                } else {
                                    Instruction::ObjectDefineSetter
                                },
                                FunctionExpression {
                                    expression: SendableRef::new(unsafe {
                                        core::mem::transmute::<
                                            &ast::Function<'_>,
                                            &'static ast::Function<'static>,
                                        >(
                                            function_expression
                                        )
                                    }),
                                    identifier: None,
                                    compiled_bytecode: None,
                                },
                                // enumerable: true,
                                true.into(),
                            );
                        }
                    }
                }
                ast::ObjectPropertyKind::SpreadProperty(spread) => {
                    if let Err(err) = spread.argument.compile(ctx).and_then(|r| r.get_value(ctx)) {
                        obj.forget(ctx);
                        return Err(err);
                    }
                    ctx.add_instruction(Instruction::CopyDataProperties);
                }
            }
        }
        // 3. Return obj
        obj.store(ctx);
        Ok(ValueOutput::Value)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ArrayExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        let elements_min_count = self.elements.len();
        ctx.add_instruction_with_immediate(Instruction::ArrayCreate, elements_min_count);
        if self.elements.is_empty() {
            return Ok(ValueOutput::Value);
        }
        let array_on_stack = ctx.load_to_stack();
        let try_catch_block = if self
            .elements
            .iter()
            .all(|e| e.is_elision() || e.as_expression().is_some_and(|e| e.is_literal()))
        {
            // Note: if all elements are elisions or literals, then the
            // whole ArrayExpression is infallible.
            None
        } else {
            Some(ctx.enter_try_catch_block())
        };
        let mut jumps_to_pop_iterator = vec![];
        let mut err = None;
        for ele in &self.elements {
            match ele {
                ast::ArrayExpressionElement::SpreadElement(spread) => {
                    if let Err(e) = spread.argument.compile(ctx).and_then(|s| s.get_value(ctx)) {
                        err = Some(e);
                        break;
                    }
                    let sync_iterator = ctx.push_sync_iterator();

                    let iteration_start = ctx.get_jump_index_to_here();
                    let iteration_end =
                        ctx.add_instruction_with_jump_slot(Instruction::IteratorStepValue);
                    ctx.add_instruction(Instruction::ArrayPush);
                    ctx.add_jump_instruction_to_index(Instruction::Jump, iteration_start);
                    ctx.set_jump_target_here(iteration_end);
                    jumps_to_pop_iterator.push(sync_iterator.exit(ctx));
                }
                ast::ArrayExpressionElement::Elision(_) => {
                    ctx.add_instruction(Instruction::ArrayElision);
                }
                _ => {
                    let expression = ele.to_expression();
                    if let Err(e) = expression.compile(ctx).and_then(|s| s.get_value(ctx)) {
                        err = Some(e);
                        break;
                    }
                    ctx.add_instruction(Instruction::ArrayPush);
                }
            }
        }
        if let Some(try_catch_block) = try_catch_block {
            // Note: if our ArrayExpression is fallible, then we need to
            // compile our catch block here and (unfortunately) also jump over
            // it as well.
            let jump_to_update_empty = try_catch_block.exit(ctx);
            let jump_over_catch = ctx.add_instruction_with_jump_slot(Instruction::Jump);
            // ## Catch block
            if !jumps_to_pop_iterator.is_empty() {
                for jump in jumps_to_pop_iterator {
                    ctx.set_jump_target_here(jump);
                }
                // Rest iterator threw an error: pop the jump_to_update_empty
                // exception handler and the failing iterator off their stacks.
                // Note: IteratorPop is infallible, so we can pop here safely.
                ctx.add_instruction(Instruction::PopExceptionJumpTarget);
                ctx.add_instruction(Instruction::IteratorPop);
            }
            ctx.set_jump_target_here(jump_to_update_empty);
            // Note: we use UpdateEmpty to pop the Array off the stack here,
            // since the result register is always non-empty in throw paths.
            ctx.add_instruction(Instruction::UpdateEmpty);
            ctx.add_instruction(Instruction::Throw);
            ctx.set_jump_target_here(jump_over_catch);
        } else {
            // If we have an infallible loop, it cannot contain a spread
            // element.
            debug_assert!(jumps_to_pop_iterator.is_empty());
        }
        array_on_stack.store(ctx);
        if let Some(err) = err {
            Err(err)
        } else {
            Ok(ValueOutput::Value)
        }
    }
}

const MAX_STATIC_ARG_COUNT: usize = (IndexType::MAX - 1) as usize;
fn prep_arguments<'s>(
    ctx: &mut CompileContext<'_, 's, '_, '_>,
    arguments: &'s [ast::Argument<'s>],
) -> Option<StackResultValue> {
    let total_arg_count = arguments.len();
    let has_spread = arguments.iter().any(|arg| arg.is_spread());
    let static_arg_count = if has_spread {
        arguments.iter().filter(|arg| !arg.is_spread()).count()
    } else {
        total_arg_count
    };
    if static_arg_count > MAX_STATIC_ARG_COUNT || has_spread {
        Some(ctx.push_stack_result_value(Some(static_arg_count as u32)))
    } else {
        None
    }
}

fn compile_arguments<'s>(
    ctx: &mut CompileContext<'_, 's, '_, '_>,
    arguments: &'s [ast::Argument<'s>],
    dynamic_arg_count: &Option<StackResultValue>,
) -> Result<usize, ExpressionError> {
    let mut spread_iterator_throw_handlers = if dynamic_arg_count.is_some() {
        Vec::with_capacity(1)
    } else {
        vec![]
    };

    let mut stack_values: Vec<StackValue> = Vec::with_capacity(arguments.len());

    for argument in arguments {
        // If known_num_arguments is None, the stack contains the number of
        // arguments, followed by the arguments.
        if let ast::Argument::SpreadElement(spread) = argument {
            // If the spread evaluation unconditionally fails, the spread
            // iteration and the function call itself becomes unreachable.
            if let Err(err) = spread.argument.compile(ctx).and_then(|s| s.get_value(ctx)) {
                for v in stack_values {
                    v.forget(ctx);
                }
                return Err(err);
            }
            let dynamic_arg_count = dynamic_arg_count.as_ref().unwrap();

            let iterator = ctx.push_sync_iterator();

            let iteration_start = ctx.get_jump_index_to_here();
            let iteration_end = ctx.add_instruction_with_jump_slot(Instruction::IteratorStepValue);
            // result: value; stack: [...args, num]

            // Note: no load_to_stack here as this Load gets performed between 0
            // and N times and we cannot know the true stack depth.
            // Unfortunately this means that stack depth tracking after an
            // arguments spread is invalid...
            ctx.add_instruction(Instruction::Load);
            // result: EMPTY; stack: [value, ...args, num]
            dynamic_arg_count.read(ctx);
            // result: num; stack: [value, ...args, num]
            ctx.add_instruction(Instruction::Increment);
            // result: num + 1; stack: [value, ...args, num]
            dynamic_arg_count.write(ctx);
            // result: EMPTY; stack: [value, ...args, num + 1]
            ctx.add_jump_instruction_to_index(Instruction::Jump, iteration_start);
            ctx.set_jump_target_here(iteration_end);
            spread_iterator_throw_handlers.push(iterator.exit(ctx));
        } else {
            let expression = argument.to_expression();

            // If a parameter evaluation unconditionally fails, the rest of the
            // parameters and the call itself become unreachable.
            if let Err(err) = expression.compile(ctx).and_then(|s| s.get_value(ctx)) {
                for v in stack_values {
                    v.forget(ctx);
                }
                return Err(err);
            }
            stack_values.push(ctx.load_to_stack());
            // stack: [value, ...args]
        }
    }

    let result = if let Some(num_arguments) = dynamic_arg_count.as_ref() {
        // stack: [...args, num]
        num_arguments.read(ctx);
        // result: num; stack: [...args, num]
        IndexType::MAX as usize
    } else {
        debug_assert!(stack_values.len() < MAX_STATIC_ARG_COUNT);
        stack_values.len()
    };

    // All values pushed onto the stack either get forgotten and cleaned up in
    // try-catch, or are consumed by EvaluateCall / EvaluateNew.
    for v in stack_values {
        v.forget(ctx);
    }

    if !spread_iterator_throw_handlers.is_empty() {
        // Create a spread iterator try-catch block.
        let jump_over_catch = ctx.add_instruction_with_jump_slot(Instruction::Jump);
        for jump_to_throw_handler in spread_iterator_throw_handlers {
            ctx.set_jump_target_here(jump_to_throw_handler);
        }
        // Arguments spread threw an error: we need to pop the iterator stack
        // and rethrow.
        ctx.add_instruction(Instruction::IteratorPop);
        ctx.add_instruction(Instruction::Throw);
        ctx.set_jump_target_here(jump_over_catch);
    }
    Ok(result)
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::CallExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if !self.optional
            && let ast::Expression::Identifier(ident) = &self.callee
            && ident.name == "eval"
        {
            // Direct eval(...)
            let dynamic_arg_count = prep_arguments(ctx, &self.arguments);
            let num_arguments = compile_arguments(ctx, &self.arguments, &dynamic_arg_count);
            if let Some(v) = dynamic_arg_count {
                v.forget(ctx);
            }
            ctx.add_instruction_with_immediate(Instruction::DirectEvalCall, num_arguments?);
            return Ok(ValueOutput::Value);
        } else if matches!(self.callee, ast::Expression::Super(_)) {
            // super(...)
            let dynamic_arg_count = prep_arguments(ctx, &self.arguments);
            let num_arguments = compile_arguments(ctx, &self.arguments, &dynamic_arg_count);
            if let Some(v) = dynamic_arg_count {
                v.forget(ctx);
            }
            ctx.add_instruction_with_immediate(Instruction::EvaluateSuper, num_arguments?);
            return Ok(ValueOutput::Value);
        }
        // 1. Let ref be ? Evaluation of CallExpression.
        ctx.is_call_optional_chain_this = is_chain_expression(&self.callee);
        let r#ref = self.callee.compile(ctx)?;
        // Optimization: If we know arguments is empty, we don't need to
        // worry about arguments evaluation clobbering our function's this
        // reference.
        let need_pop_reference = r#ref.has_reference() && !self.arguments.is_empty();
        // 2. Let func be ? GetValue(ref).
        let _func = r#ref.get_value_keep_reference(ctx)?;
        if need_pop_reference {
            ctx.add_instruction(Instruction::PushReference);
        }

        let func_on_stack = if self.optional {
            // Optional Chains

            // Load copy of func to stack.
            let func_copy = ctx.load_copy_to_stack();
            // 3. If func is either undefined or null, then
            ctx.add_instruction(Instruction::IsNullOrUndefined);
            // a. Return undefined

            // To return undefined we jump over the rest of the call handling.
            let jump_over_call = if need_pop_reference {
                // If we need to pop the reference stack, then we must do it
                // here before we go to the nullish case handling.
                // Note the inverted jump condition here!
                let jump_to_call = ctx.add_instruction_with_jump_slot(Instruction::JumpIfNot);
                // Now we're in our local nullish case handling.
                // First we pop our reference.
                ctx.add_instruction(Instruction::PopReference);
                // And now we're ready to jump over the call.
                let jump_over_call = ctx.add_instruction_with_jump_slot(Instruction::Jump);
                // But if we're jumping to call then we need to land here.
                ctx.set_jump_target_here(jump_to_call);
                jump_over_call
            } else {
                ctx.add_instruction_with_jump_slot(Instruction::JumpIfTrue)
            };
            // Register our jump slot to the chain nullish case handling.
            ctx.optional_chains.as_mut().unwrap().push(jump_over_call);
            func_copy
        } else {
            ctx.load_to_stack()
        };
        // If we're in an optional chain, we need to pluck it out while we're
        // compiling the parameters: They do not join our chain.
        let optional_chain = ctx.optional_chains.take();
        let dynamic_arg_count = prep_arguments(ctx, &self.arguments);
        let result = compile_arguments(ctx, &self.arguments, &dynamic_arg_count);
        // After we're done with compiling parameters we go back into the chain.
        if let Some(optional_chain) = optional_chain {
            ctx.optional_chains.replace(optional_chain);
        }

        // Note: func on stack and the possible dynamic arg count are consumed
        // by EvaluateCall.
        if let Some(v) = dynamic_arg_count {
            v.forget(ctx);
        }
        func_on_stack.forget(ctx);

        let num_arguments = result?;

        if need_pop_reference {
            ctx.add_instruction(Instruction::PopReference);
        }
        ctx.add_instruction_with_immediate(Instruction::EvaluateCall, num_arguments);
        Ok(ValueOutput::Value)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::NewExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        self.callee.compile(ctx)?.get_value(ctx)?;
        let func_on_stack = ctx.load_to_stack();

        let dynamic_arg_count = prep_arguments(ctx, &self.arguments);
        let num_arguments = compile_arguments(ctx, &self.arguments, &dynamic_arg_count);

        // Note: func and possible dynamic arg count on stack are consumed by
        // EvaluateNew.
        if let Some(v) = dynamic_arg_count {
            v.forget(ctx);
        }
        func_on_stack.forget(ctx);

        ctx.add_instruction_with_immediate(Instruction::EvaluateNew, num_arguments?);
        Ok(ValueOutput::Value)
    }
}

/// Compile the baseReference part of a member expression with possible
/// optional chaining.
///
/// ```text
/// 1. Let baseReference be ? Evaluation of MemberExpression.
/// 2. Let baseValue be ? GetValue(baseReference).
/// 3. If baseValue is either undefined or null, then
///     a. Return undefined.
/// 4. Return ? ChainEvaluation of OptionalChain with arguments baseValue and baseReference.
/// ```
///
/// After this call, if optional chaining isn't present then the base value is
/// in the result register. If optional chaining is present, then the base
/// value is at the top of the stack.
fn compile_optional_base_reference<'s, 'gc>(
    object: &'s ast::Expression<'s>,
    is_optional: bool,
    ctx: &mut CompileContext<'_, 's, 'gc, '_>,
) -> Result<ValueOutput<'gc>, ExpressionError> {
    // 1. Let baseReference be ? Evaluation of MemberExpression.
    // 2. Let baseValue be ? GetValue(baseReference).
    let base_value = object.compile(ctx)?.get_value(ctx)?;

    if is_optional {
        // Optional Chains

        // Load copy of baseValue to stack.
        ctx.add_instruction(Instruction::LoadCopy);
        // 3. If baseValue is either undefined or null, then
        ctx.add_instruction(Instruction::IsNullOrUndefined);
        // a. Return undefined

        // To return undefined we jump over the property access.
        let jump_over_property_access = ctx.add_instruction_with_jump_slot(Instruction::JumpIfTrue);

        // Register our jump slot to the chain nullish case handling.
        ctx.optional_chains
            .as_mut()
            .unwrap()
            .push(jump_over_property_access);
    }
    Ok(base_value)
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope>
    for ast::ComputedMemberExpression<'s>
{
    type Output = Result<Place<'s, 'gc>, ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if self.object.is_super() {
            // super[expression]
            let output = self.expression.compile(ctx)?.get_value(ctx)?;
            if let ValueOutput::Literal(literal) = output {
                let (agent, gc) = ctx.get_agent_and_gc();
                if let Some(identifier) = to_property_key_simple(agent, literal, gc) {
                    ctx.add_instruction_with_identifier(
                        Instruction::MakeSuperPropertyReferenceWithIdentifierKey,
                        identifier,
                    );
                    return Ok(identifier.into());
                }
            }
            ctx.add_instruction(Instruction::MakeSuperPropertyReferenceWithExpressionKey);
            return Ok(Place::Member { name: None });
        }
        compile_optional_base_reference(&self.object, self.optional, ctx)?;
        // If we do not have optional chaining present it means that base value
        // is currently in the result slot. We need to store it on the stack.
        if !self.optional {
            ctx.add_instruction(Instruction::Load);
        }
        let base_value_on_stack = ctx.mark_stack_value();

        // If we're in an optional chain, we need to pluck it out while we're
        // compiling the member expression: They do not join our chain.
        let optional_chain = ctx.optional_chains.take();
        // 1. Let baseReference be ? Evaluation of expression.
        // 2. Let baseValue be ? GetValue(baseReference).
        let output = self.expression.compile(ctx).and_then(|r| r.get_value(ctx));
        // After we're done with compiling the member expression we go back
        // into the chain.
        if let Some(optional_chain) = optional_chain {
            ctx.optional_chains.replace(optional_chain);
        }

        let output = match output {
            Ok(o) => o,
            Err(err) => {
                base_value_on_stack.forget(ctx);
                return Err(err);
            }
        };

        if let ValueOutput::Literal(literal) = output {
            let (agent, gc) = ctx.get_agent_and_gc();
            if let Some(identifier) = to_property_key_simple(agent, literal, gc) {
                base_value_on_stack.store(ctx);
                // 4. Return ? EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict).
                ctx.add_instruction_with_identifier(
                    Instruction::EvaluatePropertyAccessWithIdentifierKey,
                    identifier,
                );
                return Ok(identifier.into());
            }
        }
        // 4. Return ? EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict).
        base_value_on_stack.forget(ctx);
        ctx.add_instruction(Instruction::EvaluatePropertyAccessWithExpressionKey);
        Ok(Place::Member { name: None })
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope>
    for ast::StaticMemberExpression<'s>
{
    type Output = Result<Place<'s, 'gc>, ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if self.object.is_super() {
            // super.property
            let identifier = ctx.create_string(self.property.name.as_str());
            ctx.add_instruction_with_identifier(
                Instruction::MakeSuperPropertyReferenceWithIdentifierKey,
                identifier.to_property_key(),
            );
            return Ok(identifier.to_property_key().into());
        }
        compile_optional_base_reference(&self.object, self.optional, ctx)?;
        // If we are in an optional chain then result will be on the top of the
        // stack. We need to pop it into the register slot in that case.
        if self.optional {
            ctx.add_instruction(Instruction::Store);
        }

        // 4. Return EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict).
        Ok(self.property.compile(ctx))
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope>
    for ast::PrivateFieldExpression<'s>
{
    type Output = Result<Place<'static, 'static>, ExpressionError>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        compile_optional_base_reference(&self.object, self.optional, ctx)?;
        // If we are in an optional chain then result will be on the top of the
        // stack. We need to pop it into the register slot in that case.
        if self.optional {
            ctx.add_instruction(Instruction::Store);
        }

        //  MemberExpression : MemberExpression . PrivateIdentifier
        // 3. Let fieldNameString be the StringValue of PrivateIdentifier.
        // 4. Return MakePrivateReference(baseValue, fieldNameString).

        // 4. Return EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict).
        let identifier = ctx.create_string(&self.field.name);
        ctx.add_instruction_with_identifier(
            Instruction::MakePrivateReference,
            identifier.to_property_key(),
        );
        Ok(Place::Member { name: None })
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::AwaitExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // 1. Let exprRef be ? Evaluation of UnaryExpression.
        // 2. Let value be ? GetValue(exprRef).
        let value = self.argument.compile(ctx)?.get_value(ctx)?;
        // 3. Return ? Await(value).
        ctx.add_instruction(Instruction::Await);
        Ok(value)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ChainExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // It's possible that we're compiling a ChainExpression inside a call
        // that is itself in a ChainExpression. We will drop into the previous
        // chain in this case.
        let installed_own_chains = if ctx.optional_chains.is_none() {
            // We prepare for at least two chains to exist. One chain is often
            // enough but two is a bit safer. Three is rare.
            ctx.optional_chains.replace(Vec::with_capacity(2));
            true
        } else {
            false
        };
        let result = match &self.expression {
            ast::ChainElement::CallExpression(expr) => expr.compile(ctx),
            ast::ChainElement::ComputedMemberExpression(expr) => {
                let place = expr.compile(ctx);
                let result = place.and_then(|p| {
                    p.get_value_maybe_keep_reference(ctx, ctx.is_call_optional_chain_this)
                });
                ctx.is_call_optional_chain_this = false;
                result
            }
            ast::ChainElement::StaticMemberExpression(expr) => {
                let place = expr.compile(ctx);
                let result = place.and_then(|p| {
                    p.get_value_maybe_keep_reference(ctx, ctx.is_call_optional_chain_this)
                });
                ctx.is_call_optional_chain_this = false;
                result
            }
            ast::ChainElement::PrivateFieldExpression(expr) => {
                let place = expr.compile(ctx);
                let result = place.and_then(|p| {
                    p.get_value_maybe_keep_reference(ctx, ctx.is_call_optional_chain_this)
                });
                ctx.is_call_optional_chain_this = false;
                result
            }
            #[cfg(feature = "typescript")]
            ast::ChainElement::TSNonNullExpression(expr) => {
                let result = expr.expression.compile(ctx).and_then(|r| match r {
                    PlaceOrValue::Value(r) => Ok(r),
                    PlaceOrValue::Place(place) => {
                        place.get_value_maybe_keep_reference(ctx, ctx.is_call_optional_chain_this)
                    }
                });
                ctx.is_call_optional_chain_this = false;
                result
            }
            #[cfg(not(feature = "typescript"))]
            ast::ChainElement::TSNonNullExpression(_) => unreachable!(),
        };
        // If chain succeeded, we come here and should jump over the nullish
        // case handling.
        if installed_own_chains {
            let own_chains = ctx.optional_chains.take().unwrap();
            if !own_chains.is_empty() {
                let jump_over_return_undefined =
                    ctx.add_instruction_with_jump_slot(Instruction::Jump);
                for jump_to_return_undefined in own_chains {
                    ctx.set_jump_target_here(jump_to_return_undefined);
                }
                // All optional chains come here with a copy of their null or
                // undefined baseValue on the stack. Pop it off.
                ctx.add_instruction(Instruction::Store);
                // Replace any possible null with undefined.
                ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Undefined);
                ctx.set_jump_target_here(jump_over_return_undefined);
                // Note: because we have incoming jumps, it's possible for us to
                // return any result.
                Ok(ValueOutput::Value)
            } else {
                // If we have no incoming jumps, then the expression result
                // rules.
                result
            }
        } else {
            // If we're just a link in a chain, then our own result is our final
            // word.
            result
        }
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope>
    for ast::ConditionalExpression<'s>
{
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    /// # ['a 13.14 Conditional Operator ( ? : )](https://tc39.es/ecma262/#sec-conditional-operator)
    /// ### [13.14.1 Runtime Semantics: Evaluation](https://tc39.es/ecma262/#sec-conditional-operator-runtime-semantics-evaluation)
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // 1. Let lref be ? Evaluation of ShortCircuitExpression.
        // 2. Let lval be ToBoolean(? GetValue(lref)).
        let _lval = self.test.compile(ctx)?.get_value(ctx)?;
        // Jump over first AssignmentExpression (consequent) if test fails.
        // Note: JumpIfNot performs ToBoolean from above step.
        let jump_to_second = ctx.add_instruction_with_jump_slot(Instruction::JumpIfNot);
        // 3. If lval is true, then
        // a. Let trueRef be ? Evaluation of the first AssignmentExpression.
        // b. Return ? GetValue(trueRef).
        let true_ref = self.consequent.compile(ctx).and_then(|c| c.get_value(ctx));
        // Jump over second AssignmentExpression (alternate).
        let jump_over_second = ctx.add_instruction_with_jump_slot(Instruction::Jump);
        // 4. Else,
        ctx.set_jump_target_here(jump_to_second);
        // a. Let falseRef be ? Evaluation of the second AssignmentExpression.
        // b. Return ? GetValue(falseRef).
        let false_ref = self.alternate.compile(ctx).and_then(|c| c.get_value(ctx));
        ctx.set_jump_target_here(jump_over_second);
        combine_value_results(true_ref, false_ref)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ImportExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    /// ### [13.3.10.1 Runtime Semantics: Evaluation](https://tc39.es/ecma262/#sec-import-call-runtime-semantics-evaluation)
    ///
    /// ```text
    /// ImportCall : import ( AssignmentExpression , (opt) )
    ///
    /// 1. Return ? EvaluateImportCall(AssignmentExpression).
    /// ```
    ///
    /// ```text
    /// ImportCall : import ( AssignmentExpression , AssignmentExpression , (opt) )
    ///
    /// 1. Return ? EvaluateImportCall(the first AssignmentExpression, the second AssignmentExpression).
    /// ```
    ///
    /// ### [13.3.10.2 EvaluateImportCall ( specifierExpression \[ , optionsExpression \] )](https://tc39.es/ecma262/#sec-evaluate-import-call)
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // Note: referrer cannot change dynamically, so we don't need to get it
        // right here and now; we'll defer that to after all the other steps.
        // 3. Let specifierRef be ? Evaluation of specifierExpression.
        let specifier_ref = self.source.compile(ctx)?;
        // 4. Let specifier be ? GetValue(specifierRef).
        let _specifier = specifier_ref.get_value(ctx)?;
        // Note: no load_to_stack as we ImportCall consumes it immediately
        // if we don't have options.
        ctx.add_instruction(Instruction::Load);
        // 5. If optionsExpression is present, then
        if let Some(options) = &self.options {
            // Mark the stack value so that options.compile sees it.
            let specifier_on_stack = ctx.mark_stack_value();
            // a. Let optionsRef be ? Evaluation of optionsExpression.
            // b. Let options be ? GetValue(optionsRef).
            let options = options.compile(ctx).and_then(|r| r.get_value(ctx));
            specifier_on_stack.forget(ctx);
            options?;
        }
        // 6. Else,
        // a. Let options be undefined.
        // Note: we don't store an undefined constant; the ImportCall
        // instruction can take care of that.
        ctx.add_instruction(Instruction::ImportCall);
        Ok(ValueOutput::Value)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::MetaProperty<'s> {
    type Output = ();
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if self.meta.name == "new" && self.property.name == "target" {
            ctx.add_instruction(Instruction::GetNewTarget);
        } else if self.meta.name == "import" && self.property.name == "meta" {
            ctx.add_instruction(Instruction::ImportMeta);
        } else {
            unreachable!()
        };
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::PrivateInExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    /// ### [13.10.1 Runtime Semantics: Evaluation](https://tc39.es/ecma262/#sec-relational-operators-runtime-semantics-evaluation)
    /// ###  RelationalExpression : PrivateIdentifier in ShiftExpression
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // 1. Let privateIdentifier be the StringValue of PrivateIdentifier.
        let private_identifier = ctx.create_string(&self.left.name);
        // 2. Let rRef be ? Evaluation of ShiftExpression.
        // 3. Let rVal be ? GetValue(rRef).
        let _rval = self.right.compile(ctx)?.get_value(ctx)?;
        // 4. If rVal is not an Object, throw a TypeError exception.
        // 5. Let privateEnv be the running execution context's PrivateEnvironment.
        // 6. Assert: privateEnv is not null.
        // 7. Let privateName be ResolvePrivateIdentifier(privateEnv, privateIdentifier).
        ctx.add_instruction_with_identifier(
            Instruction::MakePrivateReference,
            private_identifier.to_property_key(),
        );
        // 8. If PrivateElementFind(rVal, privateName) is not empty, return true.
        // 9. Return false.
        ctx.add_instruction(Instruction::HasPrivateElement);
        Ok(ValueOutput::Value)
    }
}
#[cfg(feature = "regexp")]
impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::RegExpLiteral<'s> {
    type Output = ();
    /// ### [13.2.7.3 Runtime Semantics: Evaluation](https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation)
    ///
    /// ```text
    /// PrimaryExpression : RegularExpressionLiteral
    /// ```
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // 1. Let pattern be CodePointsToString(BodyText of RegularExpressionLiteral).
        // 2. Let flags be CodePointsToString(FlagText of RegularExpressionLiteral).

        let pattern = self.regex.pattern.text.as_str();
        // 3. Return ! RegExpCreate(pattern, flags).
        let regexp = ctx.create_regexp(pattern, self.regex.flags);
        ctx.add_instruction_with_constant(Instruction::StoreConstant, regexp);
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::SequenceExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    /// ### [13.16.1 Runtime Semantics: Evaluation](https://tc39.es/ecma262/#sec-comma-operator-runtime-semantics-evaluation)
    ///
    /// ```text
    /// Expression : Expression , AssignmentExpression
    /// ```
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // 1. Let lRef be ? Evaluation of Expression.
        // 2. Perform ? GetValue(lRef).
        // 3. Let rRef be ? Evaluation of AssignmentExpression.
        // 4. Return ? GetValue(rRef).
        let (last, rest) = self.expressions.split_last().unwrap();
        for expr in rest {
            if expr.is_literal() {
                // Literals do not have observable side-effects when compiled,
                // we can skip these when they're not the last expression.
                continue;
            }
            // NOTE: GetValue must be called even though its value is not used
            // because it may have observable side-effects.
            expr.compile(ctx)?.get_value(ctx)?;
        }
        last.compile(ctx)?.get_value(ctx)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::Super {
    type Output = ();
    #[inline(always)]
    fn compile(&'s self, _ctx: &mut CompileContext<'_, 's, '_, '_>) -> Self::Output {
        // There's no work to be done here.
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope>
    for ast::TaggedTemplateExpression<'s>
{
    type Output = Result<ValueOutput<'gc>, ExpressionError>;
    /// ### [13.3.11 Tagged Templates](https://tc39.es/ecma262/#sec-tagged-templates)
    ///
    /// > NOTE: A tagged template is a function call where the arguments of the
    /// > call are derived from a TemplateLiteral (13.2.8). The actual
    /// > arguments include a template object (13.2.8.4) and the values
    /// > produced by evaluating the expressions embedded within the
    /// > TemplateLiteral.
    fn compile(&'s self, ctx: &mut CompileContext<'_, 's, '_, '_>) -> Self::Output {
        //  MemberExpression : MemberExpression TemplateLiteral
        //  CallExpression : CallExpression TemplateLiteral

        // 1. Let tagRef be ? Evaluation of MemberExpression/CallExpression.
        let tag_ref = self.tag.compile(ctx)?;
        // 2. Let tagFunc be ? GetValue(tagRef).
        let _tag_func = tag_ref.get_value_keep_reference(ctx)?;
        let need_pop_reference =
            tag_ref.has_reference() && !self.quasi.is_no_substitution_template();
        // Load tagFunc to the stack.
        let tag_func_on_stack = ctx.load_to_stack();

        // 3. Let thisCall be this MemberExpression.
        // 4. Let tailCall be IsInTailPosition(thisCall).
        // 5. Return ? EvaluateCall(tagFunc, tagRef, TemplateLiteral, tailCall).
        //    3. Let argList be ? ArgumentListEvaluation of arguments.

        // ### 13.3.8.1 Runtime Semantics: ArgumentListEvaluation

        if need_pop_reference {
            ctx.add_instruction(Instruction::PushReference);
        }

        //  TemplateLiteral : NoSubstitutionTemplate
        let mut arguments = Vec::with_capacity(self.quasi.expressions.len());
        if self.quasi.is_no_substitution_template() {
            // 1. Let templateLiteral be this TemplateLiteral.
            // 2. Let siteObj be GetTemplateObject(templateLiteral).
            let (agent, gc) = ctx.get_agent_and_gc();
            let site_obj = get_template_object(agent, &self.quasi, gc);
            // 3. Return « siteObj ».
            arguments.push(ctx.load_constant_to_stack(site_obj));
        } else {
            // TemplateLiteral : SubstitutionTemplate

            // 1. Let templateLiteral be this TemplateLiteral.
            // 2. Let siteObj be GetTemplateObject(templateLiteral).
            let (agent, gc) = ctx.get_agent_and_gc();
            let site_obj = get_template_object(agent, &self.quasi, gc);
            arguments.push(ctx.load_constant_to_stack(site_obj));
            // 3. Let remaining be ? ArgumentListEvaluation of SubstitutionTemplate.
            // 4. Return the list-concatenation of « siteObj » and remaining.

            // SubstitutionTemplate : TemplateHead Expression TemplateSpans
            for expression in self.quasi.expressions.iter() {
                // 1. Let firstSubRef be ? Evaluation of Expression.
                // 2. Let firstSub be ? GetValue(firstSubRef).
                if let Err(err) = expression.compile(ctx).and_then(|r| r.get_value(ctx)) {
                    for arg in arguments {
                        arg.forget(ctx);
                    }
                    tag_func_on_stack.forget(ctx);
                    return Err(err);
                }
                // 3. Let restSub be ? SubstitutionEvaluation of TemplateSpans.
                arguments.push(ctx.load_to_stack());
                // 4. Assert: restSub is a possibly empty List.
                // 5. Return the list-concatenation of « firstSub » and restSub.
            }
        }
        if need_pop_reference {
            ctx.add_instruction(Instruction::PopReference);
        }
        let num_arguments = arguments.len();
        // EvaluateCall consumes arguments and tagFunc.
        for arg in arguments {
            arg.forget(ctx);
        }
        tag_func_on_stack.forget(ctx);
        ctx.add_instruction_with_immediate(Instruction::EvaluateCall, num_arguments);
        Ok(ValueOutput::Value)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::TemplateLiteral<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if let Some(quasi) = self.single_quasi() {
            let constant = ctx.create_string(&quasi);
            ctx.add_instruction_with_constant(Instruction::StoreConstant, constant);
            Ok(constant.into())
        } else {
            let mut quasis = self.quasis.as_slice();
            let mut expressions = self.expressions.as_slice();
            let mut parts = Vec::with_capacity(quasis.len());
            while let Some((head, rest)) = quasis.split_first() {
                quasis = rest;
                // 1. Let head be the TV of TemplateHead as defined in 12.9.6.
                let head = ctx.create_string(head.value.cooked.as_ref().unwrap().as_str());
                parts.push(ctx.load_constant_to_stack(head));
                if let Some((expression, rest)) = expressions.split_first() {
                    expressions = rest;
                    // 2. Let subRef be ? Evaluation of Expression.
                    // 3. Let sub be ? GetValue(subRef).
                    if let Err(err) = expression.compile(ctx).and_then(|r| r.get_value(ctx)) {
                        for part in parts {
                            part.forget(ctx);
                        }
                        return Err(err);
                    }
                    // 4. Let middle be ? ToString(sub).
                    // Note: This is done by StringConcat.
                    parts.push(ctx.load_to_stack());
                }
                // 5. Let tail be ? Evaluation of TemplateSpans.
            }
            // 6. Return the string-concatenation of head, middle, and tail.
            let count = parts.len();
            // Note: StringConcat consumes the parts from stack.
            for part in parts {
                part.forget(ctx);
            }
            ctx.add_instruction_with_immediate(Instruction::StringConcat, count);
            Ok(ValueOutput::Value)
        }
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ThisExpression {
    type Output = ();
    #[inline]
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        ctx.add_instruction(Instruction::ResolveThisBinding);
    }
}

/// ### [15.5.5 Runtime Semantics: Evaluation](https://tc39.es/ecma262/#sec-generator-function-definitions-runtime-semantics-evaluation)
///
/// ### YieldExpression : yield * AssignmentExpression
fn compile_delegate_yield_expression<'s>(
    expr: &'s ast::YieldExpression<'s>,
    ctx: &mut CompileContext<'_, 's, '_, '_>,
) -> Result<(), ExpressionError> {
    let assignment_expression = expr
        .argument
        .as_ref()
        .expect("Unhandled SyntaxError: yield * requires an argument");
    // 1. Let generatorKind be GetGeneratorKind().
    let generator_kind_is_async = ctx.is_async_generator();
    // 2. Assert: generatorKind is either sync or async.
    // 3. Let exprRef be ? Evaluation of AssignmentExpression.
    // 4. Let value be ? GetValue(exprRef).
    let _value = assignment_expression.compile(ctx)?.get_value(ctx)?;
    // 5. Let iteratorRecord be ? GetIterator(value, generatorKind).
    // If a ? throw happens after this, we need to pop the iterator before
    // allowing the error to continue onwards.
    let iterator = if generator_kind_is_async {
        ctx.push_async_iterator()
    } else {
        ctx.push_sync_iterator()
    };
    // 6. Let iterator be iteratorRecord.[[Iterator]].
    // 7. Let received be NormalCompletion(undefined).
    ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Undefined);
    let jump_over_repeat = ctx.add_instruction_with_jump_slot(Instruction::Jump);
    // 8. Repeat,
    let jump_to_repeat = ctx.get_jump_index_to_here();
    // We should be +1 try-catch block here.
    // NOTE: this here is the last part of the normal completion handling.
    ctx.add_instruction(Instruction::PopExceptionJumpTarget);
    // We should be +0 try-catch block here.
    ctx.set_jump_target_here(jump_over_repeat);
    // a. If received is a normal completion, then
    let (inner_result_yield_label, inner_result_handling_label, try_catch_block, jump_to_end) = {
        // ### Normal result handling
        // i. Let innerResult be ? Call(
        //        iteratorRecord.[[NextMethod]],
        //        iteratorRecord.[[Iterator]],
        //        « received.[[Value]] »
        //    ).
        ctx.add_instruction(Instruction::IteratorCallNextMethod);
        // We should be +0 try-catch block here.
        let inner_result_handling_label = ctx.get_jump_index_to_here();
        if generator_kind_is_async {
            // ii. If generatorKind is async, set innerResult to
            //     ? Await(innerResult).
            ctx.add_instruction(Instruction::Await);
        }
        let jump_to_end = ctx.add_instruction_with_jump_slot(Instruction::IteratorComplete);
        // iii. If innerResult is not an Object, throw a TypeError exception.
        // iv. Let done be ? IteratorComplete(innerResult).
        // v. If done is true, then
        //     1. Return ? IteratorValue(innerResult).

        let inner_result_yield_label = ctx.get_jump_index_to_here();
        // vi. If generatorKind is async,
        if generator_kind_is_async {
            // set received to Completion(
            //     AsyncGeneratorYield(? IteratorValue(innerResult))
            // ).
            ctx.add_instruction(Instruction::IteratorValue);
        }
        // +1
        let try_catch_block = ctx.enter_try_catch_block();
        // We should be +1 try-catch block here.
        // vii. Else, set received to Completion(GeneratorYield(innerResult)).
        ctx.add_instruction(Instruction::Yield);
        // Note: generators can be resumed with a Return instruction. For those
        // cases we need to generate Return handling here.
        ctx.add_jump_instruction_to_index(Instruction::Jump, jump_to_repeat);
        // Note: We need to observe the index here as the Yield above makes
        // this instruction pointer reachable even by jumping over the above
        // Jump.
        let _ = ctx.get_jump_index_to_here();
        (
            inner_result_yield_label,
            inner_result_handling_label,
            try_catch_block,
            jump_to_end,
        )
    };
    // c. Else, i. Assert: received is a return completion.
    let jump_to_throw_result_handling = {
        // ### Return result handling
        // We should be +1 try-catch block here.
        // +0
        let jump_to_throw_result_handling = try_catch_block.exit(ctx);
        let jump_over_return_call = ctx.add_instruction_with_jump_slot(Instruction::IteratorReturn);
        // ii. Let return be ? GetMethod(iterator, "return").
        // iii. If return is undefined, then ... (jump over return call)
        // iv. Let innerReturnResult be
        //     ? Call(return, iterator, « received.[[Value]] »).
        // v. If generatorKind is async,
        if generator_kind_is_async {
            // set innerReturnResult to ? Await(innerReturnResult).
            ctx.add_instruction(Instruction::Await);
        }
        // vi. If innerReturnResult is not an Object, throw a TypeError exception.
        // vii. Let done be ? IteratorComplete(innerReturnResult).
        // viii. If done is true, then
        //     1. Set value to ? IteratorValue(innerReturnResult).
        //     2. Return ReturnCompletion(value).
        let jump_to_return = ctx.add_instruction_with_jump_slot(Instruction::IteratorComplete);
        // ix. If generatorKind is async,
        //     set received to Completion(
        //         AsyncGeneratorYield(? IteratorValue(innerReturnResult))
        //     ).
        // x. Else, set received to
        //    Completion(GeneratorYield(innerReturnResult)).
        // Note: the above steps are a repeat of steps vi. and vii. from normal
        // completion handling, so we jump there to reduce duplication.
        ctx.add_jump_instruction_to_index(Instruction::Jump, inner_result_yield_label);

        // We should be +0 try-catch block here.
        ctx.set_jump_target_here(jump_over_return_call);
        // 1. Set value to received.[[Value]].
        ctx.set_jump_target_here(jump_to_return);
        // 2. If generatorKind is async, then
        // a. Set value to ? Await(value).
        // Note: compile_return performs await on value in async generators.
        // 3. Return ReturnCompletion(value).
        ctx.compile_return(true);
        jump_to_throw_result_handling
    };
    // b. Else if received is a throw completion, then
    let jump_to_iterator_pop = {
        // ### Throw result handling
        // We should be +0 try-catch block here.
        ctx.set_jump_target_here(jump_to_throw_result_handling);
        // b. Else if received is a throw completion, then
        // i. Let throw be ? GetMethod(iterator, "throw").
        let jump_over_throw_call = ctx.add_instruction_with_jump_slot(Instruction::IteratorThrow);
        // ii. If throw is not undefined, then
        // 1. Let innerResult be ? Call(throw, iterator, « received.[[Value]] »).
        // 2. If generatorKind is async,
        //    set innerResult to ? Await(innerResult).
        // 3. NOTE: Exceptions from the inner iterator throw method are
        //    propagated. Normal completions from an inner throw method are
        //    processed similarly to an inner next.
        // => we jump to normal inner result handling
        ctx.add_jump_instruction_to_index(Instruction::Jump, inner_result_handling_label);
        // 4. If innerResult is not an Object, throw a TypeError exception.
        // 5. Let done be ? IteratorComplete(innerResult).
        // 6. If done is true, then
        //    a. Return ? IteratorValue(innerResult).
        // 7. If generatorKind is async,
        //    set received to Completion(
        //        AsyncGeneratorYield(? IteratorValue(innerResult))
        //    ).
        // 8. Else, set received to Completion(GeneratorYield(innerResult)).

        // iii. Else,
        // We should be +0 try-catch block here.
        ctx.set_jump_target_here(jump_over_throw_call);
        // 1. NOTE: If iterator does not have a throw method, this throw is
        //    going to terminate the yield* loop. But first we need to give
        //    iterator a chance to clean up.
        // 2. Let closeCompletion be NormalCompletion(empty).
        // 3. If generatorKind is async,
        if generator_kind_is_async {
            // perform ? AsyncIteratorClose(iteratorRecord, closeCompletion).
            ctx.add_instruction(Instruction::AsyncIteratorClose);
            // If async iterator close returned a Value, then it'll push the previous
            // result value into the stack and perform an implicit Await.
            // We should verify that the result of the await is an object, and then
            // return the original result.
            let error_message = ctx.create_string("iterator.return() returned a non-object value");
            ctx.add_instruction_with_identifier(
                Instruction::VerifyIsObject,
                error_message.to_property_key(),
            );
            ctx.add_instruction(Instruction::Store);
        } else {
            // 4. Else, perform ? IteratorClose(iteratorRecord, closeCompletion).
            ctx.add_instruction(Instruction::IteratorClose);
        }
        // Pop the overall catch block and pop the iterator.
        let jump_to_iterator_pop = iterator.exit(ctx);
        // 5. NOTE: The next step throws a TypeError to indicate that there was
        //    a yield* protocol violation: iterator does not have a throw
        //    method.
        // 6. Throw a TypeError exception.
        let error_message = ctx.create_string("iterator does not have a throw method");
        ctx.add_instruction_with_constant(Instruction::StoreConstant, error_message);
        ctx.add_instruction_with_immediate(
            Instruction::ThrowError,
            ExceptionType::TypeError as usize,
        );
        jump_to_iterator_pop
    };

    {
        // Overall catch block to pop the iterator and rethrow.
        ctx.set_jump_target_here(jump_to_iterator_pop);
        ctx.add_instruction(Instruction::IteratorPop);
        ctx.add_instruction(Instruction::Throw);
    }

    // We should be +0 try-catch block here.
    ctx.set_jump_target_here(jump_to_end);
    ctx.add_instruction(Instruction::PopExceptionJumpTarget);
    ctx.add_instruction(Instruction::IteratorPop);
    Ok(())
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::YieldExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if self.delegate {
            compile_delegate_yield_expression(self, ctx)?;
            return Ok(ValueOutput::Value);
        }
        let _value = if let Some(arg) = &self.argument {
            // YieldExpression : yield AssignmentExpression
            // 1. Let exprRef be ? Evaluation of AssignmentExpression.
            // 2. Let value be ? GetValue(exprRef).
            arg.compile(ctx)?.get_value(ctx)?
        } else {
            // YieldExpression : yield
            // 1. Return ? Yield(undefined).
            ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Undefined);
            Primitive::Undefined.into()
        };
        // 3. Return ? Yield(value).
        // ### 27.5.3.7 Yield ( value )
        // 1. Let generatorKind be GetGeneratorKind().
        let generator_kind_is_async = ctx.is_async_generator();
        // 2. If generatorKind is async, return ? AsyncGeneratorYield(? Await(value)).
        if generator_kind_is_async {
            ctx.add_instruction(Instruction::Await);
        } else {
            // 3. Otherwise, return ? GeneratorYield(CreateIteratorResultObject(value, false)).
            compile_create_iterator_result_object(ctx, false);
        }
        ctx.add_instruction(Instruction::Yield);
        // Note: generators can be resumed with a Return instruction. For those
        // cases we need to generate Return handling here.
        let jump_over_return = ctx.add_instruction_with_jump_slot(Instruction::Jump);
        ctx.compile_return(true);
        ctx.set_jump_target_here(jump_over_return);
        Ok(ValueOutput::Value)
    }
}

fn compile_create_iterator_result_object(ctx: &mut CompileContext, done: bool) {
    let (agent, gc) = ctx.get_agent_and_gc();
    let prototype = agent
        .current_realm_record()
        .intrinsics()
        .object_prototype()
        .bind(gc);
    let shape = ObjectShape::get_shape_for_prototype(agent, Some(prototype.into()))
        .get_child_shape(agent, BUILTIN_STRING_MEMORY.value.to_property_key())
        .expect("Should perform GC here")
        .get_child_shape(agent, BUILTIN_STRING_MEMORY.done.to_property_key())
        .expect("Should perform GC here");
    // Note: no load_to_stack because ObjectCreateWithShape immediately consumes
    // the stack.
    ctx.add_instruction(Instruction::Load);
    ctx.add_instruction_with_constant(Instruction::LoadConstant, done);
    ctx.add_instruction_with_shape(Instruction::ObjectCreateWithShape, shape);
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::Expression<'s> {
    type Output = Result<PlaceOrValue<'s, 'gc>, ExpressionError>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        match self {
            ast::Expression::ArrayExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::ArrowFunctionExpression(x) => {
                x.compile(ctx);
                Ok(ValueOutput::Value.into())
            }
            ast::Expression::AssignmentExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::AwaitExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::BigIntLiteral(x) => Ok(x.compile(ctx).into()),
            ast::Expression::BinaryExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::BooleanLiteral(x) => Ok(x.compile(ctx).into()),
            ast::Expression::CallExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::ChainExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::ClassExpression(x) => {
                x.compile(ctx)?;
                Ok(ValueOutput::Value.into())
            }
            ast::Expression::ComputedMemberExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::ConditionalExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::FunctionExpression(x) => {
                x.compile(ctx);
                Ok(ValueOutput::Value.into())
            }
            ast::Expression::Identifier(x) => Ok(x.compile(ctx).into()),
            ast::Expression::ImportExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::LogicalExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::MetaProperty(x) => {
                x.compile(ctx);
                Ok(ValueOutput::Value.into())
            }
            ast::Expression::NewExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::NullLiteral(x) => Ok(x.compile(ctx).into()),
            ast::Expression::NumericLiteral(x) => Ok(x.compile(ctx).into()),
            ast::Expression::ObjectExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::ParenthesizedExpression(x) => x.compile(ctx),
            ast::Expression::PrivateFieldExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::PrivateInExpression(x) => x.compile(ctx).map(Into::into),
            #[cfg(feature = "regexp")]
            ast::Expression::RegExpLiteral(x) => {
                x.compile(ctx);
                Ok(ValueOutput::Value.into())
            }
            #[cfg(not(feature = "regexp"))]
            ast::Expression::RegExpLiteral(_) => unreachable!(),
            ast::Expression::SequenceExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::StaticMemberExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::StringLiteral(x) => Ok(x.compile(ctx).into()),
            ast::Expression::Super(x) => {
                x.compile(ctx);
                Ok(ValueOutput::Value.into())
            }
            ast::Expression::TaggedTemplateExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::TemplateLiteral(x) => x.compile(ctx).map(Into::into),
            ast::Expression::ThisExpression(x) => {
                x.compile(ctx);
                Ok(ValueOutput::Value.into())
            }
            ast::Expression::UnaryExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::UpdateExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::YieldExpression(x) => x.compile(ctx).map(Into::into),
            ast::Expression::V8IntrinsicExpression(_) => todo!(),
            #[cfg(feature = "typescript")]
            ast::Expression::TSAsExpression(x) => x.expression.compile(ctx),
            #[cfg(feature = "typescript")]
            ast::Expression::TSSatisfiesExpression(x) => x.expression.compile(ctx),
            #[cfg(feature = "typescript")]
            ast::Expression::TSNonNullExpression(x) => x.expression.compile(ctx),
            #[cfg(feature = "typescript")]
            ast::Expression::TSTypeAssertion(x) => x.expression.compile(ctx),
            #[cfg(feature = "typescript")]
            ast::Expression::TSInstantiationExpression(x) => x.expression.compile(ctx),
            ast::Expression::JSXElement(_) | ast::Expression::JSXFragment(_) => unreachable!(),
            #[cfg(not(feature = "typescript"))]
            ast::Expression::TSTypeAssertion(_)
            | ast::Expression::TSInstantiationExpression(_)
            | ast::Expression::TSAsExpression(_)
            | ast::Expression::TSNonNullExpression(_)
            | ast::Expression::TSSatisfiesExpression(_) => {
                unreachable!()
            }
        }
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::UpdateExpression<'s> {
    type Output = Result<ValueOutput<'gc>, ExpressionError>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        let lref = match &self.argument {
            ast::SimpleAssignmentTarget::AssignmentTargetIdentifier(x) => x.compile(ctx),
            ast::SimpleAssignmentTarget::ComputedMemberExpression(x) => x.compile(ctx)?,
            ast::SimpleAssignmentTarget::PrivateFieldExpression(x) => x.compile(ctx)?,
            ast::SimpleAssignmentTarget::StaticMemberExpression(x) => x.compile(ctx)?,
            #[cfg(feature = "typescript")]
            ast::SimpleAssignmentTarget::TSAsExpression(x) => match x.expression.compile(ctx)? {
                PlaceOrValue::Place(pk) => pk,
                _ => unreachable!(),
            },
            #[cfg(feature = "typescript")]
            ast::SimpleAssignmentTarget::TSNonNullExpression(x) => {
                match x.expression.compile(ctx)? {
                    PlaceOrValue::Place(pk) => pk,
                    _ => unreachable!(),
                }
            }
            #[cfg(feature = "typescript")]
            ast::SimpleAssignmentTarget::TSSatisfiesExpression(x) => {
                match x.expression.compile(ctx)? {
                    PlaceOrValue::Place(pk) => pk,
                    _ => unreachable!(),
                }
            }
            #[cfg(feature = "typescript")]
            ast::SimpleAssignmentTarget::TSTypeAssertion(x) => match x.expression.compile(ctx)? {
                PlaceOrValue::Place(pk) => pk,
                _ => unreachable!(),
            },
            #[cfg(not(feature = "typescript"))]
            ast::SimpleAssignmentTarget::TSNonNullExpression(_)
            | ast::SimpleAssignmentTarget::TSSatisfiesExpression(_)
            | ast::SimpleAssignmentTarget::TSAsExpression(_)
            | ast::SimpleAssignmentTarget::TSTypeAssertion(_) => unreachable!(),
        };
        lref.get_value_keep_reference(ctx)?;
        ctx.add_instruction(Instruction::ToNumeric);
        let value_on_stack = if !self.prefix {
            // The return value of postfix increment/decrement is the value
            // after ToNumeric.
            Some(ctx.load_copy_to_stack())
        } else {
            None
        };
        match self.operator {
            oxc_syntax::operator::UpdateOperator::Increment => {
                ctx.add_instruction(Instruction::Increment);
            }
            oxc_syntax::operator::UpdateOperator::Decrement => {
                ctx.add_instruction(Instruction::Decrement);
            }
        }
        let value_on_stack = value_on_stack.unwrap_or_else(|| ctx.load_copy_to_stack());
        let result = lref.put_value(ctx, ValueOutput::Value);
        value_on_stack.store(ctx);
        result.map(|_| ValueOutput::Value)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ExpressionStatement<'s> {
    type Output = StatementResult<'gc>;
    /// # ['a 14.5.1 Runtime Semantics: Evaluation](https://tc39.es/ecma262/#sec-expression-statement-runtime-semantics-evaluation)
    /// `ExpressionStatement : Expression ;`
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // 1. Let exprRef be ? Evaluation of Expression.
        // 2. Return ? GetValue(exprRef).
        value_result_to_statement_result(
            self.expression.compile(ctx).and_then(|r| r.get_value(ctx)),
        )
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ReturnStatement<'s> {
    type Output = StatementBreak;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if let Some(expr) = &self.argument {
            if let Err(err) = expr.compile(ctx).and_then(|r| r.get_value(ctx)) {
                return err.into();
            }
        } else {
            ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Undefined);
        }
        ctx.compile_return(self.argument.is_some());
        StatementBreak::Return
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::IfStatement<'s> {
    type Output = StatementResult<'gc>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // 1. Let exprRef be ? Evaluation of Expression.
        // 2. Let exprValue be ToBoolean(? GetValue(exprRef)).
        value_result_to_statement_result(self.test.compile(ctx).and_then(|r| r.get_value(ctx)))?;
        // 3. If exprValue is true, then
        let jump_to_else = ctx.add_instruction_with_jump_slot(Instruction::JumpIfNot);
        let st = ctx.enter_if_statement();
        // a. Let stmtCompletion be Completion(Evaluation of the first Statement).
        let consequent_stmt_completion = self.consequent.compile(ctx);
        st.exit(ctx, false);
        // 4. Else,
        let jump_over_else = if consequent_stmt_completion.is_continue() {
            Some(ctx.add_instruction_with_jump_slot(Instruction::Jump))
        } else {
            None
        };
        if let Some(alternate) = &self.alternate {
            ctx.set_jump_target_here(jump_to_else);
            // a. Let stmtCompletion be Completion(Evaluation of the second Statement).
            let st = ctx.enter_if_statement();
            let _stmt_completion = alternate.compile(ctx);
            st.exit(ctx, false);
        } else {
            ctx.set_jump_target_here(jump_to_else);
            // 3. If exprValue is false, then
            // a. Return undefined.
            ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Undefined);
            // 5. Return ? UpdateEmpty(stmtCompletion, undefined).
        }
        if let Some(jump_over_else) = jump_over_else {
            ctx.set_jump_target_here(jump_over_else);
        }
        ControlFlow::Continue(StatementContinue::Value)
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ArrayPattern<'s> {
    type Output = Result<(), ExpressionError>;
    /// ### [8.6.2 Runtime Semantics: BindingInitialization](https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization)
    /// ### BindingPattern : ArrayBindingPattern
    fn compile(&'s self, ctx: &mut CompileContext<'_, 's, '_, '_>) -> Self::Output {
        if self.elements.is_empty() && self.rest.is_none() {
            // ArrayAssignmentPattern : [ ]
            // 1. Let iteratorRecord be ? GetIterator(value, sync).
            // 2. Return ? IteratorClose(iteratorRecord, NormalCompletion(unused)).
            let iterator = ctx.push_sync_iterator();
            ctx.add_instruction(Instruction::IteratorClose);
            let jump_to_catch = iterator.exit(ctx);
            let jump_over_catch = ctx.add_instruction_with_jump_slot(Instruction::Jump);
            {
                // Catch block
                ctx.set_jump_target_here(jump_to_catch);
                ctx.add_instruction(Instruction::IteratorPop);
                ctx.add_instruction(Instruction::Throw);
            }
            ctx.set_jump_target_here(jump_over_catch);
            return Ok(());
        }

        // 1. Let iteratorRecord be ? GetIterator(value, sync).
        let iterator = ctx.push_sync_iterator();
        // 2. Let result be Completion(IteratorBindingInitialization of
        //    ArrayBindingPattern with arguments iteratorRecord and
        //    environment).
        let result = if !self.contains_expression() {
            simple_array_pattern(
                ctx,
                self.elements.iter().map(Option::as_ref),
                self.rest.as_deref(),
                self.elements.len(),
                ctx.lexical_binding_state,
            );
            Ok(())
        } else {
            complex_array_pattern(
                ctx,
                self.elements.iter().map(Option::as_ref),
                self.rest.as_deref(),
                ctx.lexical_binding_state,
            )
        };
        // 3. If iteratorRecord.[[Done]] is false, return
        //    ? IteratorClose(iteratorRecord, result).
        // Note: simple array binding handles IteratorClose at runtime, while
        // complex array binding injects it on its own. We don't need to do
        // anything special here.
        let jump_to_catch = iterator.exit(ctx);
        let jump_over_catch_and_exit = ctx.add_instruction_with_jump_slot(Instruction::Jump);
        {
            // catch handling, we have to call IteratorClose with the error,
            // then pop the iterator and rethrow our error.
            ctx.set_jump_target_here(jump_to_catch);
            ctx.add_instruction(Instruction::IteratorCloseWithError);
            ctx.add_instruction(Instruction::IteratorPop);
            ctx.add_instruction(Instruction::Throw);
        }
        ctx.set_jump_target_here(jump_over_catch_and_exit);
        // 4. Return ? result.
        result
    }
}

fn simple_array_pattern<'s, I>(
    ctx: &mut CompileContext<'_, 's, '_, '_>,
    elements: I,
    rest: Option<&'s ast::BindingRestElement<'s>>,
    num_elements: usize,
    has_environment: bool,
) where
    I: Iterator<Item = Option<&'s ast::BindingPattern<'s>>>,
{
    let lexical_binding_state = ctx.lexical_binding_state;
    ctx.lexical_binding_state = has_environment;
    ctx.add_instruction_with_immediate_and_immediate(
        Instruction::BeginSimpleArrayBindingPattern,
        num_elements,
        has_environment.into(),
    );

    for ele in elements {
        let Some(ele) = ele else {
            ctx.add_instruction(Instruction::BindingPatternSkip);
            continue;
        };
        match &ele {
            ast::BindingPattern::BindingIdentifier(identifier) => {
                let identifier_string = ctx.create_string(identifier.name.as_str());
                if let Some(stack_slot) = ctx.get_variable_stack_index(identifier.symbol_id()) {
                    ctx.add_instruction_with_immediate_and_constant(
                        Instruction::BindingPatternBindToIndex,
                        stack_slot as usize,
                        identifier_string,
                    );
                } else {
                    ctx.add_instruction_with_identifier(
                        Instruction::BindingPatternBind,
                        identifier_string.to_property_key(),
                    )
                }
            }
            ast::BindingPattern::ObjectPattern(pattern) => {
                ctx.add_instruction(Instruction::BindingPatternGetValue);
                simple_object_pattern(pattern, ctx, has_environment);
            }
            ast::BindingPattern::ArrayPattern(pattern) => {
                ctx.add_instruction(Instruction::BindingPatternGetValue);
                simple_array_pattern(
                    ctx,
                    pattern.elements.iter().map(Option::as_ref),
                    pattern.rest.as_deref(),
                    pattern.elements.len(),
                    has_environment,
                );
            }
            ast::BindingPattern::AssignmentPattern(_) => unreachable!(),
        }
    }

    if let Some(rest) = rest {
        match &rest.argument {
            ast::BindingPattern::BindingIdentifier(identifier) => {
                if let Some(stack_slot) = ctx.get_variable_stack_index(identifier.symbol_id()) {
                    ctx.add_instruction_with_immediate(
                        Instruction::BindingPatternBindRestToIndex,
                        stack_slot as usize,
                    );
                } else {
                    let identifier_string = ctx.create_string(identifier.name.as_str());
                    ctx.add_instruction_with_identifier(
                        Instruction::BindingPatternBindRest,
                        identifier_string.to_property_key(),
                    );
                }
            }
            ast::BindingPattern::ObjectPattern(pattern) => {
                ctx.add_instruction(Instruction::BindingPatternGetRestValue);
                simple_object_pattern(pattern, ctx, has_environment);
            }
            ast::BindingPattern::ArrayPattern(pattern) => {
                ctx.add_instruction(Instruction::BindingPatternGetRestValue);
                simple_array_pattern(
                    ctx,
                    pattern.elements.iter().map(Option::as_ref),
                    pattern.rest.as_deref(),
                    pattern.elements.len(),
                    has_environment,
                );
            }
            ast::BindingPattern::AssignmentPattern(_) => unreachable!(),
        }
    } else {
        ctx.add_instruction(Instruction::FinishBindingPattern);
    }
    ctx.lexical_binding_state = lexical_binding_state;
}

fn check_result_is_undefined(ctx: &mut CompileContext) -> JumpIndex {
    // Run the initializer if the result value is undefined.

    // Note: no load_copy_to_stack because Store consumes the copy immediately.
    // That only happens when we go to that branch, but it all shakes out much
    // the same anyway.
    ctx.add_instruction(Instruction::LoadCopy);
    ctx.add_instruction(Instruction::IsUndefined);
    let jump_slot = ctx.add_instruction_with_jump_slot(Instruction::JumpIfNot);
    // Drop the undefined result value and run initializer.
    ctx.add_instruction(Instruction::Store);
    jump_slot
}

/// ### [8.6.3 Runtime Semantics: IteratorBindingInitialization](https://tc39.es/ecma262/#sec-runtime-semantics-iteratorbindinginitialization)
fn complex_array_pattern<'s, I>(
    ctx: &mut CompileContext<'_, 's, '_, '_>,
    elements: I,
    rest: Option<&'s ast::BindingRestElement<'s>>,
    has_environment: bool,
) -> Result<(), ExpressionError>
where
    I: Iterator<Item = Option<&'s ast::BindingPattern<'s>>>,
{
    let lexical_binding_state = ctx.lexical_binding_state;
    ctx.lexical_binding_state = has_environment;
    let result = 'iter: {
        for ele in elements {
            ctx.add_instruction(Instruction::IteratorStepValueOrUndefined);

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

            if let Err(err) = ele.compile(ctx) {
                break 'iter Err(err);
            }
        }

        if let Some(rest) = rest {
            ctx.add_instruction(Instruction::IteratorRestIntoArray);
            if let Err(err) = rest.argument.compile(ctx) {
                break 'iter Err(err);
            }
        } else {
            ctx.add_instruction(Instruction::IteratorClose);
        }
        Ok(())
    };
    ctx.lexical_binding_state = lexical_binding_state;
    result
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::FormalParameters<'s> {
    type Output = Result<(), ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        for ele in self.items.iter() {
            ctx.add_instruction(Instruction::IteratorStepValueOrUndefined);

            ele.compile(ctx)?;
        }

        if let Some(rest) = self.rest.as_deref() {
            ctx.add_instruction(Instruction::IteratorRestIntoArray);
            rest.rest.argument.compile(ctx)?;
        } else {
            ctx.add_instruction(Instruction::IteratorClose);
        }
        Ok(())
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::FormalParameter<'s> {
    type Output = Result<(), ExpressionError>;

    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if let Some(initializer) = self.initializer.as_deref() {
            compile_assignment((&self.pattern, initializer), ctx)
        } else {
            self.pattern.compile(ctx)
        }
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ObjectPattern<'s> {
    type Output = Result<(), ExpressionError>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if !self.contains_expression() {
            simple_object_pattern(self, ctx, ctx.lexical_binding_state);
        } else {
            complex_object_pattern(self, ctx, ctx.lexical_binding_state)?;
        }
        Ok(())
    }
}

fn simple_object_pattern<'s>(
    pattern: &'s ast::ObjectPattern<'s>,
    ctx: &mut CompileContext<'_, 's, '_, '_>,
    has_environment: bool,
) {
    let lexical_binding_state = ctx.lexical_binding_state;
    ctx.lexical_binding_state = has_environment;
    ctx.add_instruction_with_immediate(
        Instruction::BeginSimpleObjectBindingPattern,
        has_environment.into(),
    );

    for ele in &pattern.properties {
        if ele.shorthand {
            debug_assert!(
                matches!(&ele.key, ast::PropertyKey::StaticIdentifier(_))
                    && matches!(&ele.value, ast::BindingPattern::BindingIdentifier(_))
            );
            let ast::BindingPattern::BindingIdentifier(identifier) = &ele.value else {
                unreachable!()
            };
            let identifier = identifier.as_ref();
            let identifier_string = ctx.create_string(identifier.name.as_str());
            if let Some(stack_slot) = ctx.get_variable_stack_index(identifier.symbol_id()) {
                ctx.add_instruction_with_immediate_and_constant(
                    Instruction::BindingPatternBindToIndex,
                    stack_slot as usize,
                    identifier_string,
                );
            } else {
                ctx.add_instruction_with_identifier(
                    Instruction::BindingPatternBind,
                    identifier_string.to_property_key(),
                );
            }
        } else {
            let key_string = match &ele.key {
                ast::PropertyKey::StaticIdentifier(identifier) => {
                    // SAFETY: We'll use this value as a PropertyKey directly later.
                    unsafe {
                        ctx.create_property_key(&identifier.name)
                            .into_value_unchecked()
                    }
                }
                ast::PropertyKey::NumericLiteral(literal) => {
                    if let Ok(Number::Integer(integer)) = Number::try_from(literal.value) {
                        // Literal is an integer, just drop it in as a
                        // PropertyKey integer directly.
                        Value::Integer(integer)
                    } else {
                        // Literal is a float: it needs to be converted into a
                        // String.
                        let mut buffer = ryu_js::Buffer::new();
                        ctx.create_string(buffer.format(literal.value)).into()
                    }
                }
                ast::PropertyKey::StringLiteral(literal) => {
                    // SAFETY: We'll use this value as a PropertyKey directly later.
                    unsafe {
                        ctx.create_property_key(&literal.value)
                            .into_value_unchecked()
                    }
                }
                ast::PropertyKey::BigIntLiteral(lit) => {
                    // Drop out the trailing 'n' from BigInt literals.
                    let raw_str = lit
                        .raw
                        .as_ref()
                        .expect("BigInt literal should have raw text")
                        .as_str();
                    let last_index = raw_str.len() - 1;
                    let (literal, radix) = match lit.base {
                        oxc_syntax::number::BigintBase::Decimal => (&raw_str[..last_index], 10),
                        oxc_syntax::number::BigintBase::Binary => (&raw_str[2..last_index], 2),
                        oxc_syntax::number::BigintBase::Octal => (&raw_str[2..last_index], 8),
                        oxc_syntax::number::BigintBase::Hex => (&raw_str[2..last_index], 16),
                    };
                    if let Ok(result) = i64::from_str_radix(literal, radix) {
                        if let Ok(number) = Number::try_from(result) {
                            number.into()
                        } else {
                            ctx.create_string_from_owned(result.to_string()).into()
                        }
                    } else {
                        let string = num_bigint::BigInt::from_str_radix(literal, radix)
                            .unwrap()
                            .to_string();
                        ctx.create_string_from_owned(string).into()
                    }
                }
                _ => unreachable!(),
            };

            match &ele.value {
                ast::BindingPattern::BindingIdentifier(identifier) => {
                    let value_identifier_string = ctx.create_string(identifier.name.as_str());
                    if let Some(stack_slot) = ctx.get_variable_stack_index(identifier.symbol_id()) {
                        ctx.add_instruction_with_immediate_and_constant(
                            Instruction::BindingPatternBindToIndex,
                            stack_slot as usize,
                            key_string,
                        );
                    } else {
                        ctx.add_instruction_with_identifier_and_constant(
                            Instruction::BindingPatternBindNamed,
                            value_identifier_string,
                            key_string,
                        )
                    }
                }
                ast::BindingPattern::ObjectPattern(pattern) => {
                    ctx.add_instruction_with_constant(
                        Instruction::BindingPatternGetValueNamed,
                        key_string,
                    );
                    simple_object_pattern(pattern, ctx, has_environment);
                }
                ast::BindingPattern::ArrayPattern(pattern) => {
                    ctx.add_instruction_with_constant(
                        Instruction::BindingPatternGetValueNamed,
                        key_string,
                    );
                    simple_array_pattern(
                        ctx,
                        pattern.elements.iter().map(Option::as_ref),
                        pattern.rest.as_deref(),
                        pattern.elements.len(),
                        has_environment,
                    );
                }
                ast::BindingPattern::AssignmentPattern(_) => unreachable!(),
            }
        }
    }

    if let Some(rest) = &pattern.rest {
        match &rest.argument {
            ast::BindingPattern::BindingIdentifier(identifier) => {
                if let Some(stack_slot) = ctx.get_variable_stack_index(identifier.symbol_id()) {
                    ctx.add_instruction_with_immediate(
                        Instruction::BindingPatternBindRestToIndex,
                        stack_slot as usize,
                    );
                } else {
                    let identifier_string = ctx.create_string(identifier.name.as_str());
                    ctx.add_instruction_with_identifier(
                        Instruction::BindingPatternBindRest,
                        identifier_string.to_property_key(),
                    );
                }
            }
            _ => unreachable!(),
        }
    } else {
        ctx.add_instruction(Instruction::FinishBindingPattern);
    }
    ctx.lexical_binding_state = lexical_binding_state;
}

fn complex_object_pattern<'s>(
    object_pattern: &'s ast::ObjectPattern<'s>,
    ctx: &mut CompileContext<'_, 's, '_, '_>,
    has_environment: bool,
) -> Result<(), ExpressionError> {
    let lexical_binding_state = ctx.lexical_binding_state;
    ctx.lexical_binding_state = has_environment;
    // 8.6.2 Runtime Semantics: BindingInitialization
    // BindingPattern : ObjectBindingPattern
    // 1. Perform ? RequireObjectCoercible(value).
    // NOTE: RequireObjectCoercible throws in the same cases as ToObject, and
    // other operations later on (such as GetV) also perform ToObject, so we
    // convert to an object early.
    ctx.add_instruction(Instruction::ToObject);
    let value_on_stack = ctx.load_to_stack();

    let result = 'iter: {
        for property in &object_pattern.properties {
            let place = match &property.key {
                ast::PropertyKey::StaticIdentifier(identifier) => {
                    // Make a copy of the baseValue in the result register;
                    // EvaluatePropertyAccessWithIdentifierKey consumes it.
                    ctx.add_instruction(Instruction::StoreCopy);
                    identifier.compile(ctx)
                }
                // Note: private field aren't valid in this context.
                ast::PropertyKey::PrivateIdentifier(_) => unreachable!(),
                _ => {
                    // Make a copy of the baseValue on the stack;
                    // EvaluatePropertyAccessWithExpressionKey consumes it.
                    ctx.add_instruction(Instruction::StoreCopy);
                    let base_value_copy = ctx.load_to_stack();
                    let expr = property.key.to_expression();
                    let output = expr.compile(ctx).and_then(|r| r.get_value(ctx));
                    base_value_copy.forget(ctx);
                    let output = match output {
                        Ok(r) => r,
                        Err(err) => {
                            break 'iter Err(err);
                        }
                    };
                    ctx.add_instruction(Instruction::EvaluatePropertyAccessWithExpressionKey);
                    output.to_expression_key()
                }
            };
            if let Err(err) =
                place.get_value_maybe_keep_reference(ctx, object_pattern.rest.is_some())
            {
                break 'iter Err(err);
            }
            if object_pattern.rest.is_some() {
                assert!(place.has_reference());
                ctx.add_instruction(Instruction::PushReference);
            }

            if let Err(err) = property.value.compile(ctx) {
                break 'iter Err(err);
            };
        }
        Ok(())
    };

    if let Err(err) = result {
        value_on_stack.forget(ctx);
        ctx.lexical_binding_state = lexical_binding_state;
        return Err(err);
    }

    // Don't keep the object on the stack.
    value_on_stack.store(ctx);

    if let Some(rest) = &object_pattern.rest {
        let ast::BindingPattern::BindingIdentifier(identifier) = &rest.argument else {
            unreachable!()
        };

        // We have kept the references for all of the properties read in the
        // reference stack, so we can now use them to exclude those
        // properties from the rest object.
        ctx.add_instruction_with_immediate(
            Instruction::CopyDataPropertiesIntoObject,
            object_pattern.properties.len(),
        );
        let value = ValueOutput::Value;

        let place = identifier.compile(ctx);
        if !has_environment {
            if let Err(err) = place.put_value(ctx, value) {
                ctx.lexical_binding_state = lexical_binding_state;
                return Err(err);
            }
        } else {
            place.initialise_referenced_binding(ctx, value);
        }
    }
    ctx.lexical_binding_state = lexical_binding_state;
    result
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::BindingPattern<'s> {
    type Output = Result<(), ExpressionError>;
    /// ### [8.6.2 Runtime Semantics: BindingInitialization](https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization)
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        match self {
            // ### BindingIdentifier : Identifier
            // ### BindingIdentifier : yield
            // ### BindingIdentifier : await
            ast::BindingPattern::BindingIdentifier(identifier) => {
                // 1. Let name be the StringValue of Identifier.
                // 2. Return ? InitializeBoundName(name, value, environment).
                let place = identifier.compile(ctx);
                let value = ValueOutput::Value;

                // ### 8.6.2.1 InitializeBoundName ( name, value, environment )
                // 1. If environment is not undefined, then
                if ctx.lexical_binding_state {
                    // a. Perform ! environment.InitializeBinding(name, value).
                    // b. Return unused.
                    place.initialise_referenced_binding(ctx, value);
                    Ok(())
                } else {
                    // 2. Else,
                    // a. Let lhs be ? ResolveBinding(name).
                    // b. Return ? PutValue(lhs, value).
                    place.put_value(ctx, value)
                }
            }
            // ### BindingPattern : ObjectBindingPattern
            ast::BindingPattern::ObjectPattern(object_binding_pattern) => {
                object_binding_pattern.compile(ctx)
            }
            // ### BindingPattern : ArrayBindingPattern
            ast::BindingPattern::ArrayPattern(array_binding_pattern) => {
                array_binding_pattern.compile(ctx)
            }
            // ### SingleNameBinding : BindingIdentifier Initializer
            // ### BindingElement : BindingPattern Initializer
            ast::BindingPattern::AssignmentPattern(pattern) => {
                let p = (&pattern.left, &pattern.right);
                compile_assignment(p, ctx)
            }
        }
    }
}

fn compile_assignment<'a, 's, 'gc, 'scope>(
    (left, right): (&'s ast::BindingPattern<'s>, &'s ast::Expression<'s>),
    ctx: &mut CompileContext<'a, 's, 'gc, 'scope>,
) -> Result<(), ExpressionError> {
    match left {
        // ### SingleNameBinding : BindingIdentifier Initializer
        //
        // * function (a = 1) {}
        // * [a = 1]
        ast::BindingPattern::BindingIdentifier(binding_identifier) => {
            // 1. Let bindingId be the StringValue of BindingIdentifier.
            // 2. Let lhs be ? ResolveBinding(bindingId, environment).
            let lhs = binding_identifier.compile(ctx);
            // Note: v is already in the result register after
            // IteratorStepValueOrUndefined above.
            // 3. Let v be undefined.
            // 4. If iteratorRecord.[[Done]] is false, then
            //         a. Let next be ? IteratorStepValue(iteratorRecord).
            //         b. If next is not done, then
            //                 i. Set v to next.
            // 5. If Initializer is present and v is undefined, then
            let jump_over_initializer = check_result_is_undefined(ctx);
            if is_anonymous_function_definition(right) {
                // a. If IsAnonymousFunctionDefinition(Initializer) is
                //    true, then
                // i. Set v to ? NamedEvaluation of Initializer with
                //    argument bindingId.
                ctx.add_instruction_with_constant(
                    Instruction::StoreConstant,
                    lhs.identifier().unwrap(),
                );
                ctx.name_identifier = Some(NamedEvaluationParameter::Result);
            }
            let do_push_reference = lhs.has_reference() && !right.is_literal();
            if do_push_reference {
                ctx.add_instruction(Instruction::PushReference);
            }
            // b. Else,
            // i. Let defaultValue be ? Evaluation of Initializer.
            let default_value = right.compile(ctx);
            // ii. Set v to ? GetValue(defaultValue).
            if default_value.and_then(|dv| dv.get_value(ctx)).is_ok() {
                // If Initializer evaluation or GetValue call fails,
                // this code becomes unreachable.
                if do_push_reference {
                    ctx.add_instruction(Instruction::PopReference);
                }
                ctx.name_identifier = None;
                // Note: no load_to_stack as Store consumes the
                // value immediately anyway.
                ctx.add_instruction(Instruction::Load);
            }
            ctx.set_jump_target_here(jump_over_initializer);
            // Note: here we either consume a copy of the lhs value
            // or the default value.
            ctx.add_instruction(Instruction::Store);
            // v can either be read from lhs or be the default value
            // compilation.
            let v = ValueOutput::Value;
            // 6. If environment is undefined,
            if !ctx.lexical_binding_state {
                // return ? PutValue(lhs, v).
                lhs.put_value(ctx, v)
            } else {
                // 7. Return ? InitializeReferencedBinding(lhs, v).
                lhs.initialise_referenced_binding(ctx, v);
                Ok(())
            }
        }
        // ### BindingElement : BindingPattern Initializer
        //
        // * function ({} = 1)
        // * [{} = 1]
        // * function ([] = 1)
        // * [[] = 1]
        _ => {
            // Note: v is already in the result register after
            // IteratorStepValueOrUndefined above.
            // 1. Let v be undefined.
            // 2. If iteratorRecord.[[Done]] is false, then
            //         a. Let next be ? IteratorStepValue(iteratorRecord).
            //         b. If next is not done, then
            //                 i. Set v to next.
            // 3. If Initializer is present and v is undefined, then
            let jump_over_initializer = check_result_is_undefined(ctx);
            // a. Let defaultValue be ? Evaluation of Initializer.
            let default_value = right.compile(ctx);
            // b. Set v to ? GetValue(defaultValue).
            // Note: no early exit as this is not an unconditional
            // branch.
            if default_value.and_then(|dv| dv.get_value(ctx)).is_ok() {
                // Note: if Initializer evaluation or GetValue
                // fails, this branch becomes unreachable.
                ctx.add_instruction(Instruction::Load);
            }
            ctx.set_jump_target_here(jump_over_initializer);
            ctx.add_instruction(Instruction::Store);
            // 4. Return ? BindingInitialization of BindingPattern with
            //    arguments v and environment.
            left.compile(ctx)
        }
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::VariableDeclaration<'s> {
    type Output = Result<(), ExpressionError>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // If this is a declare statement, it's a TypeScript ambient declaration
        // and should not generate any runtime code, similar to type declarations
        #[cfg(feature = "typescript")]
        if self.declare {
            return Ok(());
        }

        match self.kind {
            // VariableStatement : var VariableDeclarationList ;
            ast::VariableDeclarationKind::Var => {
                for decl in &self.declarations {
                    // VariableDeclaration : BindingIdentifier
                    let Some(init) = &decl.init else {
                        // 1. Return EMPTY.
                        continue;
                    };
                    // VariableDeclaration : BindingIdentifier Initializer

                    let ast::BindingPattern::BindingIdentifier(identifier) = &decl.id else {
                        //  VariableDeclaration : BindingPattern Initializer
                        // 1. Let rhs be ? Evaluation of Initializer.
                        // 2. Let rval be ? GetValue(rhs).
                        init.compile(ctx)?.get_value(ctx)?;
                        // 3. Return ? BindingInitialization of BidingPattern with arguments rval and undefined.
                        let lexical_binding_state = ctx.lexical_binding_state;
                        ctx.lexical_binding_state = false;
                        let result = decl.id.compile(ctx);
                        ctx.lexical_binding_state = lexical_binding_state;
                        result?;
                        continue;
                    };

                    // 1. Let bindingId be StringValue of BindingIdentifier.
                    // 2. Let lhs be ? ResolveBinding(bindingId).
                    let lhs = identifier.compile(ctx);

                    let push_reference = lhs.has_reference() && !init.is_literal();
                    if push_reference {
                        ctx.add_instruction(Instruction::PushReference);
                    }

                    // 3. If IsAnonymousFunctionDefinition(Initializer) is true, then
                    if let Some(binding_id) = lhs.identifier()
                        && is_anonymous_function_definition(init)
                    {
                        ctx.add_instruction_with_constant(Instruction::StoreConstant, binding_id);
                        // a. Let value be ? NamedEvaluation of Initializer with argument StackId.
                        ctx.name_identifier = Some(NamedEvaluationParameter::Result);
                        // 4. Else,
                    }
                    // a. Let rhs be ? Evaluation of Initializer.
                    let rhs = init.compile(ctx)?;
                    // b. Let value be ? GetValue(rhs).
                    let value = rhs.get_value(ctx)?;
                    // 5. Perform ? PutValue(lhs, value).
                    if push_reference {
                        ctx.add_instruction(Instruction::PopReference);
                    }
                    lhs.put_value(ctx, value)?;

                    // 6. Return EMPTY.
                }
            }
            ast::VariableDeclarationKind::Let | ast::VariableDeclarationKind::Const => {
                for decl in &self.declarations {
                    let ast::BindingPattern::BindingIdentifier(identifier) = &decl.id else {
                        let init = decl.init.as_ref().unwrap();

                        //  LexicalBinding : BindingPattern Initializer
                        // 1. Let rhs be ? Evaluation of Initializer.
                        let rhs = init.compile(ctx)?;
                        // 2. Let value be ? GetValue(rhs).
                        let _value = rhs.get_value(ctx)?;
                        // 3. Let env be the running execution context's LexicalEnvironment.
                        // 4. Return ? BindingInitialization of BindingPattern with arguments value and env.
                        let lexical_binding_state = ctx.lexical_binding_state;
                        ctx.lexical_binding_state = true;
                        let result = decl.id.compile(ctx);
                        ctx.lexical_binding_state = lexical_binding_state;
                        result?;
                        continue;
                    };

                    // 1. Let lhs be ! ResolveBinding(StringValue of BindingIdentifier).
                    let lhs = identifier.compile(ctx);

                    let Some(init) = &decl.init else {
                        // LexicalBinding : BindingIdentifier
                        // 2. Perform ! InitializeReferencedBinding(lhs, undefined).
                        lhs.initialise_referenced_binding_to_undefined(ctx);
                        // 3. Return empty.
                        continue;
                    };

                    let do_push_reference = lhs.has_reference() && !init.is_literal();
                    //  LexicalBinding : BindingIdentifier Initializer
                    if do_push_reference {
                        ctx.add_instruction(Instruction::PushReference);
                    }
                    // 3. If IsAnonymousFunctionDefinition(Initializer) is true, then
                    if is_anonymous_function_definition(init) {
                        // a. Let value be ? NamedEvaluation of Initializer with argument bindingId.
                        ctx.add_instruction_with_constant(
                            Instruction::StoreConstant,
                            lhs.identifier().unwrap(),
                        );
                        ctx.name_identifier = Some(NamedEvaluationParameter::Result);
                        // 4. Else,
                        // a. Let rhs be ? Evaluation of Initializer.
                    }
                    // b. Let value be ? GetValue(rhs).
                    let value = init.compile(ctx)?.get_value(ctx)?;
                    if do_push_reference {
                        ctx.add_instruction(Instruction::PopReference);
                    }

                    // 5. Perform ! InitializeReferencedBinding(lhs, value).
                    lhs.initialise_referenced_binding(ctx, value);
                    // 6. Return empty.
                }
            }
            ast::VariableDeclarationKind::Using => todo!(),
            ast::VariableDeclarationKind::AwaitUsing => todo!(),
        }
        Ok(())
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::BlockStatement<'s> {
    type Output = StatementResult<'gc>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if self.body.is_empty() {
            // Block : {}
            // 1. Return EMPTY.
            return ControlFlow::Continue(StatementContinue::Empty);
        }
        block_declaration_instantiation::instantiation(ctx, self, |ctx| {
            let mut result = StatementContinue::Empty;
            for ele in &self.body {
                result = ele.compile(ctx)?;
            }
            ControlFlow::Continue(result)
        })
    }
}

impl<'a, 's, 'gc, 'scope> CompileLabelledEvaluation<'a, 's, 'gc, 'scope> for ast::ForStatement<'s> {
    type Output = StatementResult<'gc>;

    fn compile_labelled(
        &'s self,
        label_set: Option<&mut Vec<&'s ast::LabelIdentifier<'s>>>,
        ctx: &mut CompileContext<'a, 's, 'gc, 'scope>,
    ) -> Self::Output {
        let mut per_iteration_env_lets: Vec<String<'_>> = vec![];
        let mut block_prep: Vec<BlockEnvPrep> = vec![];

        let result = if let Some(init) = &self.init {
            match init {
                ast::ForStatementInit::VariableDeclaration(init) => {
                    if init.kind.is_lexical() {
                        // 1. Let oldEnv be the running execution context's LexicalEnvironment.
                        // 2. Let loopEnv be NewDeclarativeEnvironment(oldEnv).
                        // 3. Let isConst be IsConstantDeclaration of LexicalDeclaration.
                        let is_const = init.kind.is_const();
                        // 4. Let boundNames be the BoundNames of LexicalDeclaration.
                        // 5. For each element dn of boundNames, do
                        // a. If isConst is true, then
                        if is_const {
                            init.bound_names(&mut |dn| {
                                if variable_escapes_scope(ctx, dn) {
                                    if !block_prep.iter().any(|p| p.is_env()) {
                                        block_prep
                                            .push(BlockEnvPrep::Env(ctx.enter_lexical_scope()));
                                    }
                                    // i. Perform ! loopEnv.CreateImmutableBinding(dn, true).
                                    let identifier = ctx.create_string(dn.name.as_str());
                                    ctx.add_instruction_with_identifier(
                                        Instruction::CreateImmutableBinding,
                                        identifier.to_property_key(),
                                    )
                                } else {
                                    block_prep.push(BlockEnvPrep::Var(
                                        ctx.push_stack_variable(dn.symbol_id(), false),
                                    ));
                                }
                            });
                        } else {
                            // b. Else,
                            // i. Perform ! loopEnv.CreateMutableBinding(dn, false).
                            init.bound_names(&mut |dn| {
                                if variable_escapes_scope(ctx, dn) {
                                    if !block_prep.iter().any(|p| p.is_env()) {
                                        block_prep
                                            .push(BlockEnvPrep::Env(ctx.enter_lexical_scope()));
                                    }
                                    let identifier = ctx.create_string(dn.name.as_str());
                                    // 9. If isConst is false, let perIterationLets
                                    // be boundNames; otherwise let perIterationLets
                                    // be a new empty List.
                                    per_iteration_env_lets.push(identifier);
                                    ctx.add_instruction_with_identifier(
                                        Instruction::CreateMutableBinding,
                                        identifier.to_property_key(),
                                    )
                                } else {
                                    block_prep.push(BlockEnvPrep::Var(
                                        ctx.push_stack_variable(dn.symbol_id(), false),
                                    ));
                                }
                            });
                        }
                        // 6. Set the running execution context's LexicalEnvironment to loopEnv.
                    }
                    init.compile(ctx)
                }
                _ => {
                    let expr = init.as_expression().unwrap();
                    expr.compile(ctx).and_then(|r| r.get_value(ctx)).map(|_| ())
                }
            }
        } else {
            Ok(())
        };

        if let Err(err) = result {
            for block_prep in block_prep.into_iter().rev() {
                block_prep.exit(ctx);
            }
            return ControlFlow::Break(err.into());
        }
        // 2. Perform ? CreatePerIterationEnvironment(perIterationBindings).
        let create_per_iteration_env = !per_iteration_env_lets.is_empty();
        if create_per_iteration_env {
            create_per_iteration_environment(ctx, &per_iteration_env_lets);
        }

        // 1. Let V be undefined.
        ctx.add_instruction(Instruction::Empty);
        let v = ctx.push_stack_result_value(Some(Value::Undefined));
        // 3. Repeat,
        let l = ctx.enter_loop(label_set.cloned());
        let jump_over_continue = ctx.add_instruction_with_jump_slot(Instruction::Jump);
        let continue_label = ctx.get_jump_index_to_here();
        // Note: to save one Jump in continue cases, the LoopContinues work is
        // here.
        // d. If result.[[Value]] is not empty, set V to result.[[Value]].
        ctx.add_instruction(Instruction::LoadReplace);
        // e. Perform ? CreatePerIterationEnvironment(perIterationBindings).
        if create_per_iteration_env {
            create_per_iteration_environment(ctx, &per_iteration_env_lets);
        }
        // f. If increment is not empty, then
        if let Some(update) = &self.update {
            // i. Let incRef be ? Evaluation of increment.
            let inc_ref = update.compile(ctx);
            // ii. Perform ? GetValue(incRef).
            // Note: no early exit, as this path is not guaranteed to run.
            let _ = inc_ref.and_then(|r| r.get_value(ctx));
        }

        ctx.set_jump_target_here(jump_over_continue);

        // a. If test is not empty, then
        let test_result = if let Some(test) = &self.test {
            // i. Let testRef be ? Evaluation of test.
            let test_ref = test.compile(ctx);
            // ii. Let testValue be ? GetValue(testRef).
            let test_value = test_ref.and_then(|r| r.get_value(ctx));
            // iii. If ToBoolean(testValue) is false, return V.
            // jump over consequent if test fails
            test_value.map(|_| Some(ctx.add_instruction_with_jump_slot(Instruction::JumpIfNot)))
        } else {
            Ok(None)
        };

        let result = if let Err(err) = test_result.as_ref() {
            ControlFlow::Break((*err).into())
        } else {
            // b. Let result be Completion(Evaluation of stmt).
            let result = self.body.compile(ctx);
            if result.is_continue() {
                ctx.add_jump_instruction_to_index(Instruction::Jump, continue_label.clone());
            }
            // We cannot know that the loop completes abruptly even if the body
            // says so. Continues and so forth can exit the loop.
            ControlFlow::Continue(StatementContinue::Value)
        };
        // c. If LoopContinues(result, labelSet) is false,
        //    return ? UpdateEmpty(result, V).
        // d. If result.[[Value]] is not empty, set V to result.[[Value]].
        // e. Perform ? CreatePerIterationEnvironment(perIterationBindings).
        // f. If increment is not empty, then

        {
            // ## Catch block
            ctx.set_jump_target_here(l.on_abrupt_exit());
            // Error was thrown: this means loop continues is false:
            // > c. If LoopContinues(result, labelSet) is false,
            // >    return ? UpdateEmpty(result, V).
            ctx.add_instruction(Instruction::UpdateEmpty);
            ctx.add_instruction(Instruction::Throw);
        }

        // iii. If ToBoolean(testValue) is false, return V.
        if let Ok(Some(end_jump)) = test_result {
            ctx.set_jump_target_here(end_jump);
        }
        // Note: exit_loop performs UpdateEmpty; if we jumped here from test
        // failure then result is currently empty and UpdateEmpty will pop V
        // into the result register.
        l.exit(ctx, continue_label);
        v.forget(ctx);

        for block_prep in block_prep.into_iter().rev() {
            block_prep.exit(ctx);
        }
        // c. If LoopContinues(result, labelSet) is false,
        //    return ? UpdateEmpty(result, V).
        result
    }
}

fn create_per_iteration_environment<'gc>(
    ctx: &mut CompileContext<'_, '_, 'gc, '_>,
    per_iteration_env_lets: &[String<'gc>],
) {
    if per_iteration_env_lets.len() == 1 {
        // NOTE: If there's only env let then we do not need to push and pop
        // from the stack in this case but can use the result register directly.
        // There are rather easy further optimizations available as well around
        // creating a sibling environment directly, creating an initialized
        // mutable binding directly.

        let binding = *per_iteration_env_lets.first().unwrap();
        // Get value of binding from lastIterationEnv.
        ctx.add_instruction_with_identifier(Instruction::ResolveBinding, binding.to_property_key());
        ctx.add_instruction(Instruction::GetValue);
        // Note: here we do not use exit & enter lexical
        // environment helpers as we'd just immediately exit again.
        ctx.add_instruction(Instruction::ExitDeclarativeEnvironment);
        ctx.add_instruction(Instruction::EnterDeclarativeEnvironment);
        ctx.add_instruction_with_identifier(
            Instruction::CreateMutableBinding,
            binding.to_property_key(),
        );
        ctx.add_instruction_with_identifier(Instruction::ResolveBinding, binding.to_property_key());
        ctx.add_instruction(Instruction::InitializeReferencedBinding);
    } else {
        for bn in per_iteration_env_lets {
            ctx.add_instruction_with_identifier(Instruction::ResolveBinding, bn.to_property_key());
            ctx.add_instruction(Instruction::GetValue);
            // Note: no load_to_stack as the temporary increase in stack size
            // cannot be seen by users.
            ctx.add_instruction(Instruction::Load);
        }
        // Note: here we do not use exit & enter lexical
        // environment helpers as we'd just immediately exit again.
        ctx.add_instruction(Instruction::ExitDeclarativeEnvironment);
        ctx.add_instruction(Instruction::EnterDeclarativeEnvironment);
        for bn in per_iteration_env_lets.iter().rev() {
            ctx.add_instruction_with_identifier(
                Instruction::CreateMutableBinding,
                bn.to_property_key(),
            );
            ctx.add_instruction_with_identifier(Instruction::ResolveBinding, bn.to_property_key());
            ctx.add_instruction(Instruction::Store);
            ctx.add_instruction(Instruction::InitializeReferencedBinding);
        }
    }
}

impl<'a, 's, 'gc, 'scope> CompileLabelledEvaluation<'a, 's, 'gc, 'scope>
    for ast::SwitchStatement<'s>
{
    type Output = StatementResult<'gc>;

    fn compile_labelled(
        &'s self,
        label_set: Option<&mut Vec<&'s ast::LabelIdentifier<'s>>>,
        ctx: &mut CompileContext<'_, 's, 'gc, '_>,
    ) -> Self::Output {
        // 1. Let exprRef be ? Evaluation of Expression.
        // 2. Let switchValue be ? GetValue(exprRef).
        value_result_to_statement_result(
            self.discriminant
                .compile(ctx)
                .and_then(|r| r.get_value(ctx)),
        )?;
        if self.cases.is_empty() {
            // CaseBlock : { }
            // 1. Return undefined.
            ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Undefined);
            return ControlFlow::Continue(StatementContinue::Literal(Primitive::Undefined));
        }
        let switch_value = ctx.push_stack_result_value(Option::<Value>::None);
        let switch = ctx.enter_switch(label_set.cloned());
        // 3. Let oldEnv be the running execution context's LexicalEnvironment.
        // 4. Let blockEnv be NewDeclarativeEnvironment(oldEnv).
        // 5. Perform BlockDeclarationInstantiation(CaseBlock, blockEnv).
        // 6. Set the running execution context's LexicalEnvironment to blockEnv.
        let r = block_declaration_instantiation::instantiation(ctx, self, |ctx| {
            // 7. Let R be Completion(CaseBlockEvaluation of CaseBlock with argument switchValue).
            let mut default_case_index = None;
            let mut cases = Vec::with_capacity(self.cases.len());
            let mut end_unreachable = false;
            for case in &self.cases {
                let Some(test) = &case.test else {
                    // Default case test does not care about the write order:
                    // After all other cases have been tested, default will be
                    // entered if no other was entered previously. The placement
                    // of the default case only matters for fall-through
                    // behaviour.
                    default_case_index = Some(cases.len() as u32);
                    cases.push((case, None));
                    continue;
                };
                // We have switchValue somewhere on the stack, and we want to
                // compare it to the test value. IsStrictlyEqual consumes one
                // value from the top of the stack and compares that to the
                // result value, so we need to make a copy of the switchValue
                // and put it to the top of the stack before we compile the test
                // expression and get its value into the result register.
                switch_value.read(ctx);
                let switch_value_copy_on_stack = ctx.load_to_stack();
                // 2. Let exprRef be ? Evaluation of the Expression of C.
                let expr_ref = test.compile(ctx);
                // 3. Let clauseSelector be ? GetValue(exprRef).
                let clause_selector = expr_ref.and_then(|r| r.get_value(ctx));
                // The switchValue on the stack is consumed by IsStrictlyEqual
                // or gets forgotten in an error case and is cleared up by a
                // try-catch.
                switch_value_copy_on_stack.forget(ctx);
                if clause_selector.is_ok() {
                    // 4. Return IsStrictlyEqual(input, clauseSelector).
                    ctx.add_instruction(Instruction::IsStrictlyEqual);
                    // b. If found is true then [evaluate case]
                    let jump_to_case_evaluation =
                        ctx.add_instruction_with_jump_slot(Instruction::JumpIfTrue);
                    cases.push((case, Some(jump_to_case_evaluation)));
                } else {
                    // If the evaluation or GetValue of a test expression fails
                    // unconditionally, any remaining test cases become
                    // unreachable.
                    if cases.is_empty() {
                        // The very first case test fails: code after the switch
                        // block is unreachable.
                        return ControlFlow::Break(StatementBreak::Error);
                    }

                    end_unreachable = true;
                    break;
                }
            }

            // Note: switchValue changes to be V now.
            let v = &switch_value;

            let jump_to_end = if end_unreachable {
                None
            } else {
                // If end is not unreachable, we have to add an unconditional
                // jump here. That either takes us to the default case or to the
                // end of the switch block.
                if let Some(default_case_index) = default_case_index {
                    let jump_to_default_case =
                        ctx.add_instruction_with_jump_slot(Instruction::Jump);
                    // 10. If foundInB is true, return V.
                    // 11. Let defaultR be Completion(Evaluation of DefaultClause).
                    let previous_jump = cases[default_case_index as usize]
                        .1
                        .replace(jump_to_default_case);
                    debug_assert!(previous_jump.is_none());
                    None
                } else {
                    // If nothing matched and default case doesn't exist then we
                    // need to set V to undefined here.
                    ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Undefined);
                    v.write(ctx);
                    Some(ctx.add_instruction_with_jump_slot(Instruction::Jump))
                }
            };

            // === THIS LINE IS UNREACHABLE ===

            // Either some case test before the end always fails, or we have a
            // default case to jump to, or we jump to the end of the switch
            // block. Hence, control flow never enters here normally.

            let mut prev_result = ControlFlow::Break(StatementBreak::Break);
            'cases: for (case, jump_index) in cases.into_iter() {
                let fallthrough_jump = if prev_result.is_break() {
                    // OPTIMISATION: if previous case ended with a break or an
                    // otherwise terminal instruction, we don't need a
                    // fallthrough jump at the beginning of the next case.
                    None
                } else {
                    Some(ctx.add_instruction_with_jump_slot(Instruction::Jump))
                };
                // Jump from IsStrictlyEqual comparison to here.
                let Some(jump_index) = jump_index else {
                    // This can only happen if the default case is unreachable
                    // due to some test always failing. In that case we do not
                    // need to generate code for it.
                    continue;
                };
                ctx.set_jump_target_here(jump_index.clone());

                // 1. Let V be undefined.
                ctx.add_instruction_with_constant(Instruction::StoreConstant, Value::Undefined);
                v.write(ctx);

                if let Some(fallthrough_jump) = fallthrough_jump {
                    ctx.set_jump_target_here(fallthrough_jump);
                }

                // i. Let R be Completion(Evaluation of C).
                if case.consequent.is_empty() {
                    // Empty consequents fall through to the next case.
                    prev_result = ControlFlow::Continue(StatementContinue::Empty);
                    continue 'cases;
                }

                v.read(ctx);
                let v_copy = ctx.load_to_stack();

                for ele in &case.consequent {
                    prev_result = ele.compile(ctx);
                    if prev_result.is_break() {
                        // Continue to next case if the rest of the current case
                        // becomes unreachable.
                        v_copy.forget(ctx);
                        continue 'cases;
                    }
                }
                // ii. If R.[[Value]] is not empty, set V to R.[[Value]].
                // iii. If R is an abrupt completion, return ? UpdateEmpty(R, V).
                v_copy.update_empty(ctx);
                v.write(ctx);
            }

            if let Some(jump_to_end) = jump_to_end {
                ctx.set_jump_target_here(jump_to_end);
            }
            ControlFlow::Continue(StatementContinue::Value)
        });

        // 9. Return R.
        switch.exit(ctx);
        switch_value.update_empty(ctx);
        r
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ThrowStatement<'s> {
    type Output = ExpressionError;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        self.argument
            .compile(ctx)
            .and_then(|arg| arg.get_value(ctx))
            .and_then(|_| {
                ctx.add_instruction(Instruction::Throw);
                Result::<Infallible, ExpressionError>::Err(ExpressionError::Error)
            })
            .unwrap_err()
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::TryStatement<'s> {
    type Output = StatementResult<'gc>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        ctx.add_instruction(Instruction::Empty);
        let try_finally_block = self
            .finalizer
            .is_some()
            .then(|| ctx.enter_try_finally_block());
        let try_catch_block = self.handler.is_some().then(|| ctx.enter_try_catch_block());

        // 1. Let B be Completion(Evaluation of Block).
        let b = self.block.compile(ctx);
        // 2. If B is a throw completion,
        let jump_over_catch_blocks = if let Some(catch_clause) = &self.handler {
            let jump_to_catch = try_catch_block.unwrap().exit(ctx);
            // OPTIMISATION: If the end of the try-block is unreachable, we
            // don't need a jump over the catch blocks.
            let jump_over_catch_blocks = if b.is_continue() {
                Some(ctx.add_instruction_with_jump_slot(Instruction::Jump))
            } else {
                None
            };
            ctx.set_jump_target_here(jump_to_catch);

            // let C be Completion(CatchClauseEvaluation of Catch with argument B.[[Value]]).
            let _c = catch_clause_evaluation(catch_clause, ctx);
            // 9. Return ? B.
            jump_over_catch_blocks
        } else {
            // 3. Else, let C be B.
            assert!(try_catch_block.is_none());
            None
        };
        if let Some(finalizer) = &self.finalizer {
            try_finally_block
                .unwrap()
                .exit(ctx, finalizer, jump_over_catch_blocks);
        } else if let Some(jump_over_catch_blocks) = jump_over_catch_blocks {
            // If we have a catch block following the normal execution but no
            // finally block then we'll have to handle the jump out ourselves.
            ctx.set_jump_target_here(jump_over_catch_blocks);
        }
        if !ctx.is_unreachable() {
            // 4. Return ? UpdateEmpty(C, undefined).
            ctx.add_instruction_with_constant(Instruction::LoadConstant, Value::Undefined);
            ctx.add_instruction(Instruction::UpdateEmpty);
        }
        ControlFlow::Continue(StatementContinue::Value)
    }
}

fn catch_clause_evaluation<'s, 'gc>(
    catch_clause: &'s ast::CatchClause<'s>,
    ctx: &mut CompileContext<'_, 's, 'gc, '_>,
) -> StatementResult<'gc> {
    // 14.15.2 Runtime Semantics: CatchClauseEvaluation

    // Before we can start evaluation, we want to reset the stack depth to what
    // it should be here according to our tracking. It's possible that our error
    // was thrown from within an expression that forgot some Values on the
    // stack, and leaving those there would lead to stack variable misalignment.
    ctx.reset_stack_depth();

    let catch_env = if let Some(exception_param) = &catch_clause.param {
        // 1. Let oldEnv be the running execution context's LexicalEnvironment.
        // 2. Let catchEnv be NewDeclarativeEnvironment(oldEnv).
        // 4. Set the running execution context's LexicalEnvironment to catchEnv.
        // Note: We skip the declarative environment if there is no catch
        // param as it's not observable.
        let catch_env = ctx.enter_lexical_scope();

        // 3. For each element argName of the BoundNames of CatchParameter, do
        // a. Perform ! catchEnv.CreateMutableBinding(argName, false).
        exception_param.pattern.bound_names(&mut |arg_name| {
            let arg_name = ctx.create_string(arg_name.name.as_str());
            ctx.add_instruction_with_identifier(
                Instruction::CreateMutableBinding,
                arg_name.to_property_key(),
            );
        });
        // 5. Let status be Completion(BindingInitialization of
        //    CatchParameter with arguments thrownValue and catchEnv).
        let lexical_binding_state = ctx.lexical_binding_state;
        ctx.lexical_binding_state = true;
        let status = exception_param.pattern.compile(ctx);
        ctx.lexical_binding_state = lexical_binding_state;
        // 6. If status is an abrupt completion, then
        if let Err(status) = status {
            // a. Set the running execution context's LexicalEnvironment to
            //    oldEnv.
            catch_env.exit(ctx);
            // b. Return ? status.
            return ControlFlow::Break(status.into());
        }
        Some(catch_env)
    } else {
        None
    };
    // 7. Let B be Completion(Evaluation of Block).
    let b = catch_clause.body.compile(ctx);
    // 8. Set the running execution context's LexicalEnvironment to oldEnv.
    if let Some(catch_env) = catch_env {
        catch_env.exit(ctx);
    }
    // 9. Return ? B.
    b
}

impl<'a, 's, 'gc, 'scope> CompileLabelledEvaluation<'a, 's, 'gc, 'scope>
    for ast::WhileStatement<'s>
{
    type Output = StatementResult<'gc>;

    fn compile_labelled(
        &'s self,
        label_set: Option<&mut Vec<&'s ast::LabelIdentifier<'s>>>,
        ctx: &mut CompileContext<'_, 's, '_, '_>,
    ) -> Self::Output {
        // 1. Let V be undefined.
        ctx.add_instruction(Instruction::Empty);
        let v = ctx.push_stack_result_value(Some(Value::Undefined));
        // 2. Repeat
        let l = ctx.enter_loop(label_set.cloned());
        let jump_over_continue = ctx.add_instruction_with_jump_slot(Instruction::Jump);
        let continue_label = ctx.get_jump_index_to_here();
        // f. If stmtResult.[[Value]] is not EMPTY, set V to
        //    stmtResult.[[Value]].
        ctx.add_instruction(Instruction::LoadReplace);
        ctx.set_jump_target_here(jump_over_continue);

        // a. Let exprRef be ? Evaluation of Expression.
        // OPTIMISATION: while(true) loops are pretty common, skip the test.
        let expr_result = if !is_boolean_literal_true(&self.test) {
            // b. Let exprValue be ? GetValue(exprRef).
            let expr_value = self.test.compile(ctx).and_then(|r| r.get_value(ctx));

            // c. If ToBoolean(exprValue) is false, return V.
            // jump over loop jump if test fails
            expr_value.map(|_| Some(ctx.add_instruction_with_jump_slot(Instruction::JumpIfNot)))
        } else {
            Ok(None)
        };

        // d. Let stmtResult be Completion(Evaluation of Statement).
        let stmt_result = if let Err(err) = expr_result {
            ControlFlow::Break(err.into())
        } else {
            let stmt_result = self.body.compile(ctx);
            if stmt_result.is_continue() {
                ctx.add_jump_instruction_to_index(Instruction::Jump, continue_label.clone());
            }
            // We cannot know how the loop ends.
            ControlFlow::Continue(StatementContinue::Value)
        };
        {
            // ## Catch block
            ctx.set_jump_target_here(l.on_abrupt_exit());
            // Error was thrown: this means loop continues is false:
            // > c. If LoopContinues(result, labelSet) is false,
            // >    return ? UpdateEmpty(result, V).
            ctx.add_instruction(Instruction::UpdateEmpty);
            ctx.add_instruction(Instruction::Throw);
        }
        // f. If stmtResult.[[Value]] is not EMPTY, set V to
        //    stmtResult.[[Value]].

        // c. If ToBoolean(exprValue) is false, return V.
        if let Ok(Some(end_jump)) = expr_result {
            ctx.set_jump_target_here(end_jump);
        }
        // Note: exit_loop performs UpdateEmpty; if we jumped here from test
        // failure then result is currently empty and UpdateEmpty will pop V
        // into the result register.
        l.exit(ctx, continue_label);
        v.forget(ctx);

        stmt_result
    }
}

impl<'a, 's, 'gc, 'scope> CompileLabelledEvaluation<'a, 's, 'gc, 'scope>
    for ast::DoWhileStatement<'s>
{
    type Output = StatementResult<'gc>;

    fn compile_labelled(
        &'s self,
        label_set: Option<&mut Vec<&'s ast::LabelIdentifier<'s>>>,
        ctx: &mut CompileContext<'_, 's, '_, '_>,
    ) -> Self::Output {
        // 1. Let V be undefined.
        ctx.add_instruction(Instruction::Empty);
        let v = ctx.push_stack_result_value(Some(Value::Undefined));
        // 2. Repeat,
        let l = ctx.enter_loop(label_set.cloned());
        let jump_over_continue = ctx.add_instruction_with_jump_slot(Instruction::Jump);
        // Note: to save one Jump in continue cases, the LoopContinues work is
        // here.
        // c. If stmtResult.[[Value]] is not empty, set V to
        //    stmtResult.[[Value]].
        let continue_label = ctx.get_jump_index_to_here();
        ctx.add_instruction(Instruction::LoadReplace);
        let expr_result = if is_boolean_literal_true(&self.test) {
            // OPTIMISATION: do {} while(true) loops are still somewhat common,
            // skip the test.
            // f. If ToBoolean(exprValue) is false, return V.
            Ok(None)
        } else if is_boolean_literal_false(&self.test) {
            // OPTIMISATION: do {} while(false) loops appear in tests; this is
            // a dumb optimisation: continue can never return to the beginning
            // of the loop.
            // f. If ToBoolean(exprValue) is false, return V.
            Ok(Some(ctx.add_instruction_with_jump_slot(Instruction::Jump)))
        } else {
            // d. Let exprRef be ? Evaluation of Expression.
            // e. Let exprValue be ? GetValue(exprRef).
            let expr_value = self.test.compile(ctx).and_then(|r| r.get_value(ctx));

            // f. If ToBoolean(exprValue) is false, return V.
            expr_value.map(|_| Some(ctx.add_instruction_with_jump_slot(Instruction::JumpIfNot)))
        };

        let stmt_result = if let Err(err) = expr_result {
            ControlFlow::Break(err.into())
        } else {
            ctx.set_jump_target_here(jump_over_continue);
            // a. Let stmtResult be Completion(Evaluation of Statement).
            let stmt_result = self.body.compile(ctx);
            // b. If LoopContinues(stmtResult, labelSet) is false,
            //    return ? UpdateEmpty(stmtResult, V).
            if stmt_result.is_continue() {
                ctx.add_jump_instruction_to_index(Instruction::Jump, continue_label.clone());
            }
            // We cannot know how the loop ends.
            ControlFlow::Continue(StatementContinue::Value)
        };

        {
            // ## Catch block
            ctx.set_jump_target_here(l.on_abrupt_exit());
            // Error was thrown: this means loop continues is false:
            // > b. If LoopContinues(stmtResult, labelSet) is false,
            // >    return ? UpdateEmpty(stmtResult, V).
            ctx.add_instruction(Instruction::UpdateEmpty);
            ctx.add_instruction(Instruction::Throw);
        }
        // f. If ToBoolean(exprValue) is false, return V.
        if let Ok(Some(jump_to_end)) = expr_result {
            ctx.set_jump_target_here(jump_to_end.clone());
        }
        // Note: exit_loop performs UpdateEmpty; if we jumped here from test
        // failure then result is currently empty and UpdateEmpty will pop V
        // into the result register.
        l.exit(ctx, continue_label);
        v.forget(ctx);
        stmt_result
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::BreakStatement<'s> {
    type Output = ();
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        ctx.compile_break(self.label.as_ref());
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::ContinueStatement<'s> {
    type Output = ();
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        ctx.compile_continue(self.label.as_ref());
    }
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::Statement<'s> {
    type Output = StatementResult<'gc>;
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        if ctx.is_unreachable() {
            // OPTIMISATION: If the previous statement was terminal, then later
            // statements cannot be executed and do not need to be compiled.
            return StatementBreak::Return.into();
        }
        match self {
            Self::ExpressionStatement(x) => x.compile(ctx),
            Self::ReturnStatement(x) => x.compile(ctx).into(),
            Self::IfStatement(x) => x.compile(ctx),
            Self::VariableDeclaration(x) => {
                if let Err(err) = x.compile(ctx) {
                    ControlFlow::Break(err.into())
                } else {
                    // 6. Return EMPTY.
                    ControlFlow::Continue(StatementContinue::Empty)
                }
            }
            Self::FunctionDeclaration(_) => {
                // Note: Function declaration statements are always hoisted.
                // There is no work left to do here.
                ControlFlow::Continue(StatementContinue::Empty)
            }
            Self::BlockStatement(x) => x.compile(ctx),
            Self::EmptyStatement(_) => ControlFlow::Continue(StatementContinue::Empty),
            Self::ForStatement(x) => x.compile_labelled(None, ctx),
            Self::ThrowStatement(x) => ControlFlow::Break(x.compile(ctx).into()),
            Self::TryStatement(x) => x.compile(ctx),
            Self::BreakStatement(statement) => {
                statement.compile(ctx);
                ControlFlow::Break(StatementBreak::Break)
            }
            Self::ContinueStatement(statement) => {
                statement.compile(ctx);
                ControlFlow::Break(StatementBreak::Continue)
            }
            Self::DebuggerStatement(_) => {
                ctx.add_instruction(Instruction::Debug);
                ControlFlow::Continue(StatementContinue::Empty)
            }
            Self::DoWhileStatement(statement) => statement.compile_labelled(None, ctx),
            Self::ForInStatement(statement) => statement.compile_labelled(None, ctx),
            Self::ForOfStatement(statement) => statement.compile_labelled(None, ctx),
            Self::LabeledStatement(statement) => statement.compile_labelled(None, ctx),
            Self::SwitchStatement(statement) => statement.compile_labelled(None, ctx),
            Self::WhileStatement(statement) => statement.compile_labelled(None, ctx),
            Self::WithStatement(st) => st.compile(ctx),
            Self::ClassDeclaration(x) => {
                // If this is a declare statement, it's a TypeScript ambient declaration
                // and should not generate any runtime code, similar to type declarations
                #[cfg(feature = "typescript")]
                if x.declare {
                    return ControlFlow::Continue(StatementContinue::Empty);
                }
                if let Err(err) = x.compile(ctx) {
                    ControlFlow::Break(err.into())
                } else {
                    ControlFlow::Continue(StatementContinue::Value)
                }
            }
            Self::ImportDeclaration(_) => {
                // Note: Import declarations do not perform any runtime work.
                ControlFlow::Continue(StatementContinue::Empty)
            }
            Self::ExportAllDeclaration(x) => {
                x.compile(ctx);
                ControlFlow::Continue(StatementContinue::Empty)
            }
            Self::ExportDefaultDeclaration(x) => {
                x.compile(ctx)?;
                ControlFlow::Continue(StatementContinue::Empty)
            }
            Self::ExportNamedDeclaration(x) => {
                x.compile(ctx)?;
                ControlFlow::Continue(StatementContinue::Empty)
            }
            #[cfg(feature = "typescript")]
            Self::TSEnumDeclaration(x) => {
                x.compile(ctx);
                ControlFlow::Continue(StatementContinue::Empty)
            }
            #[cfg(feature = "typescript")]
            Self::TSTypeAliasDeclaration(_)
            | Self::TSInterfaceDeclaration(_)
            | Self::TSModuleDeclaration(_)
            | Self::TSGlobalDeclaration(_) => ControlFlow::Continue(StatementContinue::Empty),
            #[cfg(not(feature = "typescript"))]
            Self::TSTypeAliasDeclaration(_)
            | Self::TSInterfaceDeclaration(_)
            | Self::TSModuleDeclaration(_)
            | Self::TSEnumDeclaration(_)
            | Self::TSGlobalDeclaration(_) => {
                unreachable!()
            }
            // TODO: Implement TypeScript-specific statement compilation
            Self::TSExportAssignment(_)
            | Self::TSImportEqualsDeclaration(_)
            | Self::TSNamespaceExportDeclaration(_) => {
                unreachable!()
            }
        }
    }
}

fn is_anonymous_function_definition(expression: &ast::Expression) -> bool {
    match expression {
        ast::Expression::ArrowFunctionExpression(_) => true,
        ast::Expression::FunctionExpression(f) => f.id.is_none(),
        ast::Expression::ClassExpression(f) => f.id.is_none(),
        ast::Expression::ParenthesizedExpression(x) => {
            is_anonymous_function_definition(&x.expression)
        }
        _ => false,
    }
}

#[cfg(feature = "typescript")]
impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::TSEnumDeclaration<'s> {
    type Output = ();
    fn compile(&'s self, ctx: &mut CompileContext<'a, 's, 'gc, 'scope>) -> Self::Output {
        // TODO: Check if this is a const enum when the field is available
        // For now, treat all enums as regular enums

        // 1. Create the enum name binding
        let enum_name = self.id.name.as_str();
        let enum_identifier = ctx.create_string(enum_name);
        ctx.add_instruction_with_identifier(
            Instruction::ResolveBinding,
            enum_identifier.to_property_key(),
        );

        // 2. Analyze enum properties to determine if we can use ObjectCreateWithShape
        let mut is_numeric_enum = true;
        let mut has_computed_members = false;

        // First pass: check if all members are simple (no computed expressions)
        for member in self.body.members.iter() {
            if let Some(ref initializer) = member.initializer {
                match initializer {
                    ast::Expression::StringLiteral(_) => {
                        is_numeric_enum = false;
                    }
                    ast::Expression::NumericLiteral(_) => {}
                    _ => {
                        // Computed expression
                        is_numeric_enum = false;
                        has_computed_members = true;
                        break;
                    }
                }
            }
        }

        // If we have computed members, fall back to the original property-by-property approach
        if has_computed_members {
            compile_enum_with_computed_members(self, ctx);
            return;
        }

        // 3. Create object shape with all enum member keys directly
        let prototype = Some(
            ctx.get_agent()
                .current_realm_record()
                .intrinsics()
                .object_prototype()
                .into(),
        );

        // Collect all property keys upfront for intrinsic shape creation
        let mut property_keys = Vec::new();

        // Add forward mapping keys
        for member in self.body.members.iter() {
            let member_name = match &member.id {
                ast::TSEnumMemberName::Identifier(ident) => ident.name.as_str(),
                _ => "unknown",
            };
            let identifier = ctx.create_property_key(member_name);
            property_keys.push(identifier);
        }

        // Add reverse mapping keys for numeric enums
        if is_numeric_enum {
            let mut current_numeric_value = 0f64;
            for member in self.body.members.iter() {
                let reverse_key_value =
                    if let Some(ast::Expression::NumericLiteral(num_lit)) = &member.initializer {
                        current_numeric_value = num_lit.value + 1.0;
                        num_lit.value
                    } else {
                        let value = current_numeric_value;
                        current_numeric_value += 1.0;
                        value
                    };

                let reverse_key = ctx.create_property_key(&reverse_key_value.to_string());
                property_keys.push(reverse_key);
            }
        }

        // Create intrinsic shape directly with all properties in one shot
        let properties_count = property_keys.len();
        let agent = ctx.get_agent_mut();
        let (cap, index) = agent
            .heap
            .elements
            .allocate_keys_with_capacity(properties_count)
            .expect("Should perform GC here");
        let cap = cap.make_intrinsic();

        let keys_memory = agent.heap.elements.get_keys_uninit_raw(cap, index);
        for (slot, key) in keys_memory.iter_mut().zip(property_keys.iter()) {
            *slot = Some(key.unbind());
        }

        let shape = agent.heap.create(ObjectShapeRecord::create(
            prototype,
            index,
            cap,
            properties_count,
        ));

        // 4. Compile values in correct order (matching the shape)
        let mut current_numeric_value = 0f64;

        // Compile forward mapping values
        for member in self.body.members.iter() {
            if let Some(ref initializer) = member.initializer {
                match initializer {
                    ast::Expression::StringLiteral(string_lit) => {
                        let string_value = ctx.create_string(string_lit.value.as_str());
                        ctx.add_instruction_with_constant(Instruction::StoreConstant, string_value);
                    }
                    ast::Expression::NumericLiteral(num_lit) => {
                        let number_value = ctx.create_number(num_lit.value);
                        ctx.add_instruction_with_constant(Instruction::StoreConstant, number_value);
                        current_numeric_value = num_lit.value + 1.0;
                    }
                    _ => unreachable!("Computed members should have been filtered out"),
                }
            } else {
                let number_value = ctx.create_number(current_numeric_value);
                ctx.add_instruction_with_constant(Instruction::StoreConstant, number_value);
                current_numeric_value += 1.0;
            }
            ctx.add_instruction(Instruction::Load);
        }

        // Compile reverse mapping values for numeric enums
        if is_numeric_enum {
            for member in self.body.members.iter() {
                let member_name = match &member.id {
                    ast::TSEnumMemberName::Identifier(ident) => ident.name.as_str(),
                    _ => "unknown",
                };
                let name_string = ctx.create_string(member_name);
                ctx.add_instruction_with_constant(Instruction::StoreConstant, name_string);
                ctx.add_instruction(Instruction::Load);
            }
        }

        // 5. Create object with pre-computed shape
        ctx.add_instruction_with_shape(Instruction::ObjectCreateWithShape, shape);

        // 6. Initialize the binding with the completed enum object
        ctx.add_instruction(Instruction::InitializeReferencedBinding);
    }
}

#[cfg(feature = "typescript")]
fn compile_enum_with_computed_members<'s>(
    enum_decl: &'s ast::TSEnumDeclaration<'s>,
    ctx: &mut CompileContext<'_, 's, '_, '_>,
) {
    // Fallback to original implementation for enums with computed members
    ctx.add_instruction(Instruction::ObjectCreate);

    let mut current_numeric_value = 0f64;
    let mut is_numeric_enum = true;

    for member in enum_decl.body.members.iter() {
        let member_name = match &member.id {
            ast::TSEnumMemberName::Identifier(ident) => ident.name.as_str(),
            _ => "unknown",
        };

        // Push member name as property key onto stack
        let member_string = ctx.create_string(member_name);
        ctx.add_instruction_with_constant(Instruction::LoadConstant, member_string);

        // Determine the value for this enum member
        if let Some(ref initializer) = member.initializer {
            match initializer {
                ast::Expression::StringLiteral(string_lit) => {
                    is_numeric_enum = false;
                    let string_value = ctx.create_string(string_lit.value.as_str());
                    ctx.add_instruction_with_constant(Instruction::StoreConstant, string_value);
                }
                ast::Expression::NumericLiteral(num_lit) => {
                    let number_value = ctx.create_number(num_lit.value);
                    ctx.add_instruction_with_constant(Instruction::StoreConstant, number_value);
                    current_numeric_value = num_lit.value + 1.0;
                }
                _ => {
                    is_numeric_enum = false;
                    let _ = initializer.compile(ctx).and_then(|r| r.get_value(ctx));
                }
            }
        } else {
            let number_value = ctx.create_number(current_numeric_value);
            ctx.add_instruction_with_constant(Instruction::StoreConstant, number_value);
            current_numeric_value += 1.0;
        }

        ctx.add_instruction(Instruction::ObjectDefineProperty);
    }

    // Add reverse mappings for numeric enums
    if is_numeric_enum {
        current_numeric_value = 0f64;

        for member in enum_decl.body.members.iter() {
            let member_name = match &member.id {
                ast::TSEnumMemberName::Identifier(ident) => ident.name.as_str(),
                _ => "unknown",
            };

            let reverse_key_value = if let Some(ref initializer) = member.initializer {
                if let ast::Expression::NumericLiteral(num_lit) = initializer {
                    current_numeric_value = num_lit.value + 1.0;
                    num_lit.value
                } else {
                    current_numeric_value += 1.0;
                    continue;
                }
            } else {
                let value = current_numeric_value;
                current_numeric_value += 1.0;
                value
            };

            let key_number = ctx.create_number(reverse_key_value);
            ctx.add_instruction_with_constant(Instruction::LoadConstant, key_number);

            let name_string = ctx.create_string(member_name);
            ctx.add_instruction_with_constant(Instruction::StoreConstant, name_string);

            ctx.add_instruction(Instruction::ObjectDefineProperty);
        }
    }

    // Move the enum object from stack to result register
    ctx.add_instruction(Instruction::Store);
    // Now initialize the binding (reference is on stack, value is in result)
    ctx.add_instruction(Instruction::InitializeReferencedBinding);
}