quickjs-compile 0.9.0

Bytecode compiler for the pure-Rust QuickJS port
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
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
//! The bytecode compiler.
//!
//! Compilation is a single walk over the AST that emits *symbolic* instructions
//! (jump targets are label ids, variable references are names), followed by a
//! resolution pass that turns them into final bytecode. Splitting it this way
//! keeps the emitter readable: nothing has to know slot indices or byte offsets
//! while it is still discovering them.
//!
//! Variable resolution follows the reference implementation's model:
//!
//! * every function has a flat table of arguments and locals;
//! * block scopes form a chain through [`VarDef::scope_next`], which is what makes
//!   `let`/`const` bindings visible only inside their block and lets the runtime
//!   put them back into the temporal dead zone on entry;
//! * a name that is not in the current function is looked up in the enclosing
//!   ones; if found, the variable is marked captured and reached through a
//!   closure reference;
//! * a name found nowhere is a global, reached through a closure entry as well.
//!
//! Emission order and instruction choice deliberately mirror `quickjs.c`: the
//! differential test compares disassembly with the reference opcode by opcode, so
//! an unnecessary `dup` or a differently chosen short form shows up immediately.

use crate::bytecode::LineCol;
use crate::bytecode::{
    ANONYMOUS_BINDING, Atom, ClosureType, ClosureVar, Constant, EvalSite, EvalVisible, ExportEntry,
    Function as CompiledFunction, FunctionKind, ImportEntry, ModuleMeta, ModuleRequest, VarDef,
    VarKind,
};
use crate::disasm;
use crate::opcode::Opcode;
use js_parse::Position;
use js_parse::Span;
use js_parse::SyntaxError;
use js_parse::ast::{self, *};

/// A label id, local to the function being compiled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Label(u32);

/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
///
/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
/// is why the brackets are part of the name; nothing a program writes can collide with it.
const HOME_OBJECT: &str = "<home_object>";

/// The local holding the function `super()` constructs from.
///
/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
const ACTIVE_FUNC: &str = "this.active_func";

/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
const NEW_TARGET: &str = "new.target";

/// Stand-in for a constant-pool index that is only known later in the instruction stream.
///
/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
/// billion members is not a thing — and the compiler patches it before resolution runs, so a
/// missed patch is a panic-free compiler error rather than a wrong jump.
const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;

/// One step of a class's initialisation, in source order.
///
/// A static block is not a member the class keeps — it is a run of statements that executes
/// at the point the class definition reaches it — so it belongs *inside* the initialiser
/// function rather than alongside the fields as a separate pass. Merging the two is what
/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
/// same way the reference is.
enum StaticInitItem<'a> {
    /// `static x = value`, or `x = value` for the instance half.
    Field(FieldKey<'a>, Option<&'a Expr>),
    /// `static { … }`
    Block {
        body: &'a [Stmt],
        /// Position of the `{`, which is where the reference puts the function.
        body_start: Position,
    },
}

/// How one field names its property.
///
/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
/// is fixed when the class is created. Keeping the expression here instead made
/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
/// `{1: "a"}`.
enum FieldKey<'a> {
    /// `x`, `"x"`, `0` — the property name is static text.
    Literal(&'a PropKey),
    /// `#x`: the class-scope binding that holds the private symbol.
    Private(String),
    /// `[expr]`: the class-scope binding that holds the evaluated key.
    Computed(String),
}

/// The `var_block` sentinel for a binding that lives at function scope.
///
/// It has to be a value a *real* block key can never take. Block keys are source
/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
/// sentinel takes the slot below it.
const FUNCTION_SCOPE: u64 = u64::MAX - 3;

/// The `var_block` sentinel for a binding of the parameter list.
///
/// A function whose parameter list contains a default expression gets *two* variable
/// environments: one for the parameters and one for the body, so a `var` in the body
/// that shares a name with a parameter is a different binding. The parameter bindings
/// therefore need a scope key of their own: reachable while the defaults are
/// evaluated, invisible to the body, and never merged with a body `var` of the same
/// name.
///
/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
/// the closure and the body shared one slot, when only the parameters were in scope
/// when it was created.
const PARAM_SCOPE: u64 = u64::MAX - 4;

/// The name of the hidden local a `using` declaration caches its dispose method in.
///
/// It has to be a name no source can produce, because a script may declare anything: the
/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
fn using_method_name(name: &str) -> String {
    format!("<using.method {name}>")
}

/// The `blocks` parent sentinel for "this block has no enclosing block".
///
/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
/// also the terminator the chain walk from the script body reached the file's
/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
/// leaked into the body scope.
const NO_PARENT: u64 = u64::MAX - 2;

/// The block key for a script body. Distinct from both sentinels and unreachable from
/// any source offset.
const SCRIPT_BODY: u64 = u64::MAX - 1;

/// An operand of a symbolic instruction.
#[derive(Debug, Clone, PartialEq)]
enum Op {
    /// An immediate integer.
    Int(i32),
    /// A jump target.
    Label(Label),
    /// A constant pool index.
    Const(u32),
    /// An atom, before interning.
    Atom(Atom),
    /// An interned atom, as an index into [`Function::atoms`].
    AtomId(u32),
    /// A resolved slot.
    Slot(Slot),
}

/// Where a resolved variable lives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Slot {
    Arg(u32),
    Loc(u32),
    VarRef(u32),
    /// A global, by closure-var index.
    Global(u32),
    /// A global *declared* in this script. The reference keeps these bindings in
    /// reference cells so that the script and any closure share one variable, so
    /// a store goes through `put_var_ref` while a read uses `get_var`.
    GlobalDecl(u32),
}

/// What a symbolic variable access does, which decides the final opcode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum VarAction {
    /// Read the value.
    Get,
    /// Read the value, yielding `undefined` for an undeclared global.
    GetUndef,
    /// Write, leaving nothing on the stack.
    Put,
    /// Write and initialise, leaving the value on the stack.
    PutInit,
    /// Write, leaving the value on the stack.
    Set,
    /// Initialise a binding that may only be initialised once, such as a derived
    /// constructor's `this`.
    PutInitChecked,
    /// Initialise, leaving the value on the stack and without the `const` check.
    ///
    /// A class's own scope binding is a `const` that has to be initialised in the middle
    /// of the definition — after the constructor exists but before the static fields run
    /// — and the value has to survive for the outer store to use.
    SetInit,
    /// Write a binding that lives in a reference cell.
    PutRef,
}

#[derive(Debug, Clone)]
enum Insn {
    /// A fully determined instruction.
    Fixed { op: Opcode, operands: Vec<Op> },
    /// A variable access, resolved in the second pass.
    ///
    /// `block` is the lexical block the access appears in, which is what makes
    /// shadowing work: two bindings can share a name, and the one that wins is
    /// whichever scope encloses the access.
    Var {
        action: VarAction,
        name: String,
        block: u64,
        /// Whether the access was written in the parameter list; see
        /// [`FnState::in_params`].
        in_params: bool,
    },
    /// Close a binding *if* it turned out to be captured.
    ///
    /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
    /// only known once the body has been compiled — a closure created there is the
    /// thing that makes it necessary. The reference emits `close_loc` exactly in that
    /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
    /// of emitted blind.
    CloseCaptured { name: String, block: u64 },
    /// `delete name`, which can only answer `false` once the binding is known.
    ///
    /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
    /// looks the name up on the global object, which is what distinguishes an implicit
    /// global (configurable, deletable) from a declared one (a binding, always `false`).
    DeleteVar { name: String },
    /// An instruction that dead-code elimination removed. It keeps its slot so
    /// that label indices stay valid, and resolves to no bytecode.
    Dead,
}

/// Where `break` and `continue` jump to.
///
/// Targets are stacked as the compiler enters loops and labelled statements, so a
/// bare `break` needs no analysis: it is simply the innermost target. A labelled
/// one searches outward by name.
#[derive(Debug, Clone)]
struct JumpTarget {
    /// The labels attached to this target. `l: for(;;)` gives one name; a bare
    /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
    /// same statement and `break a` must reach the same place as `break b`.
    names: Vec<String>,
    /// Where `break` lands. `None` for a construct `break` may only leave, not
    /// target — a `try`, whose entry exists purely to unwind.
    break_label: Option<Label>,
    /// Where `continue` lands. `None` for anything that is not a loop.
    continue_label: Option<Label>,
    /// Stack slots to discard when control leaves this construct by a jump.
    ///
    /// Both `switch` and `try` leave something on the value stack for the duration
    /// of the construct — the discriminant, or the `catch` offset — and a jump out
    /// has to take it with it. A loop leaves nothing.
    drop_count: u32,
    /// The finalizer to run when control leaves this construct.
    ///
    /// Set on a `try` even when it has no `finally`: the label is always emitted and
    /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
    /// does not have to know whether a finalizer exists.
    finally_label: Option<Label>,
    /// Whether this is a labelled non-loop statement, which an unlabelled `break`
    /// does not reach.
    is_regular_stmt: bool,
    /// Whether leaving this construct has to close an iterator.
    ///
    /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
    /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
    /// is dropped rather than closed.
    has_iterator: bool,
    /// Whether that iterator speaks the *async* protocol.
    ///
    /// An async close has to `await` the inner `return`, so it is an inline instruction
    /// sequence rather than one opcode — the reference's `emit_iterator_close`.
    is_async_iterator: bool,
}

/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
///
/// Both leave `source value` on the stack, so this is purely which spelling the reference
/// picked, and it picked it by whether it had to build a *reference* for the target:
///
/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
///   consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
///   destructures);
/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
/// * a `var`, and any assignment target, go through `dup; get_field`, because the
///   reference builds a reference for them — which is what `with` needs.
fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
    nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
}

/// Whether binding this pattern starts by boxing the value it was handed.
fn nests_a_pattern(pattern: &Pattern) -> bool {
    match &pattern.kind {
        PatternKind::Array { .. } | PatternKind::Object { .. } => true,
        PatternKind::Assign { target, .. } => nests_a_pattern(target),
        _ => false,
    }
}

/// `copy_data_properties` flags for an object-literal spread.
///
/// The byte packs three fields: the low bits are the stack offset of the source,
/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
/// as well as string keys. A spread passes a literal `null` exclusion list right
/// below the source, so that field stays zero and only the source offset and the
/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);

/// The expression a `...` introduces.
///
/// The parser marks the spread in two places — the element/property variant and an
/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
/// stepped through before the argument can be compiled.
fn spread_argument(spread: &Expr) -> &Expr {
    match &spread.kind {
        ExprKind::Spread(inner) => inner,
        _ => spread,
    }
}

/// The flag byte `define_method` takes.
///
/// The low two bits pick value/getter/setter; bit 2 marks the property
/// enumerable, which every object-literal method is.
/// What kind of class constructor a function is being compiled as.
///
/// A constructor is not an ordinary method: a base one materialises `this` and refuses
/// to run without `new`, and a derived one starts with `this` in the dead zone until
/// `super()` produces it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CtorKind {
    /// Not a class constructor.
    None,
    /// A constructor of a class without `extends`.
    Base,
    /// A constructor of a class with `extends`.
    Derived,
}

/// The flag byte `define_method` takes for a class member.
///
/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
/// a class method is *not* — that is the whole difference from an object-literal method,
/// and the reason `Object.keys(C.prototype)` stays empty.
fn class_method_flags(kind: MethodKind) -> i32 {
    match kind {
        MethodKind::Constructor | MethodKind::Method => 0,
        MethodKind::Get => 1,
        MethodKind::Set => 2,
    }
}

fn define_method_flags(kind: PropertyKind) -> i32 {
    let base = match kind {
        PropertyKind::Value | PropertyKind::Method => 0,
        PropertyKind::Get => 1,
        PropertyKind::Set => 2,
    };
    base | 4
}

/// Convert a numeric property key to the text an atom would be made from.
///
/// Only the range where Rust and JavaScript agree on the spelling is accepted.
/// Both print the shortest representation that round-trips, so plain decimal
/// digits match; they diverge at the extremes, where JavaScript switches to an
/// exponent (`1e-7`, `1e+21`) and Rust does not. Rather than emit an atom that
/// differs from the reference, those keys are rejected.
fn numeric_key_text(value: f64, span: Span) -> Result<String, SyntaxError> {
    if !value.is_finite() {
        return Err(SyntaxError::new(
            "a non-finite numeric property key is not supported by the compiler yet",
            span,
        ));
    }
    if value == value.trunc() && value.abs() < 1e21 {
        return Ok(format!("{}", value as i64));
    }
    if value.abs() >= 1e-6 && value.abs() < 1e21 {
        return Ok(format!("{value}"));
    }
    Err(SyntaxError::new(
        "a numeric property key outside [1e-6, 1e21) is not supported by the compiler yet",
        span,
    ))
}

/// Collect the operands of a same-operator logical run, in source order.
///
/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
/// the caller appends `c`. A node with a different operator is one operand.
fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
    if let ExprKind::Logical {
        op: inner_op,
        left,
        right,
    } = &expr.kind
        && *inner_op == op
    {
        collect_same_operator(op, left, out);
        out.push(right);
        return;
    }
    out.push(expr);
}

/// The jump a logical assignment or `??` takes when the value is kept.
///
/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
/// the value when it is *not* null-ish, so it is the `if_false` side.
fn logical_jump(op: AssignOp) -> Opcode {
    match op {
        AssignOp::Or => Opcode::IfTrue,
        AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
        _ => Opcode::IfFalse,
    }
}

/// Whether a loop enumerates keys or values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ForLoopKind {
    /// `for (x in o)` — the keys of an object.
    In,
    /// `for (x of o)` — the values of an iterable.
    Of,
    /// `for await (x of o)` — the values of an async iterable, or of a sync one.
    AwaitOf,
}

/// Which part of a `try` statement a block key refers to.
#[derive(Debug, Clone, Copy)]
enum TryPart {
    /// The guarded block.
    Block = 0,
    /// The handler body, excluding the catch parameter.
    Catch = 1,
    /// The finalizer block.
    Finally = 2,
    /// The catch parameter's own scope.
    Param = 3,
}

/// A lexical scope, identified while hoisting and numbered at the end.
///
/// Scope identity is needed in two passes that must agree: declarations are
/// hoisted in source order (so slots come out in source order, as in the
/// reference), but a binding belongs to the block it was written in, which is only
/// entered later. Blocks are therefore keyed by the source position of their
/// opening brace, which is stable across both walks.
#[derive(Debug, Clone, Copy)]
struct Block {
    /// Source position of the block.
    key: u64,
    /// The block this one is nested in; `0` for the function scope.
    parent: u64,
}

/// One function under construction.
struct FnState {
    name: String,
    kind: FunctionKind,
    strict: bool,
    args: Vec<VarDef>,
    vars: Vec<VarDef>,
    closure_vars: Vec<ClosureVar>,
    cpool: Vec<Constant>,
    atoms: Vec<Atom>,
    /// Every lexical scope, in creation order.
    blocks: Vec<Block>,
    /// The block currently being parsed or compiled.
    current_block: u64,
    /// The block a *nested* function was created in, so a capture made from here can be
    /// resolved against the enclosing function's lexical scopes rather than against a
    /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
    /// function's own `let S` instead of the class body's `const S`.
    created_in_block: u64,
    /// The block each local was declared in, parallel to `vars`. `0` means the
    /// function scope, where `var` bindings live.
    var_block: Vec<u64>,
    /// Set when the expression just compiled left no value on the stack.
    ///
    /// Only a store can do that: `put_field` consumes the object and the value, so
    /// an assignment whose result is unused emits nothing extra. The expression
    /// statement then has nothing to drop.
    no_value: bool,
    /// Whether a label was placed since the last instruction was emitted.
    ///
    /// The `put`/`get` fold is only valid when the two are adjacent in the final
    /// stream; a label in between means a jump can land on the read, so the store has
    /// to keep consuming its value. A flag is enough and avoids having to reason about
    /// which index a label recorded.
    label_since_insn: bool,
    /// Whether the value of the expression being compiled is thrown away.
    ///
    /// Only an expression *statement* discards its value, and only the outermost
    /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
    /// still has to produce a value. Consumed by [`Compiler::assign`], which is
    /// the one construct whose bytecode depends on it.
    discard_value: bool,
    /// The block that holds the function body.
    body_block: u64,
    /// Head of each scope's binding chain, indexed by level. Filled in by
    /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
    block_heads: Vec<i32>,
    /// Enclosing `break`/`continue` targets, innermost last.
    jump_targets: Vec<JumpTarget>,
    insns: Vec<Insn>,
    labels: Vec<Option<usize>>,
    /// Captured locals, which need a reference cell.
    var_ref_count: u32,
    line: u32,
    column: u32,
    /// Whether this is a script body. A script's top-level declarations create
    /// global properties rather than locals, which is why they show up as
    /// closure variables with `[global_decl]`.
    is_script: bool,
    /// Whether this is a module body.
    ///
    /// A module body is a script in every respect that matters here — no `arguments`,
    /// no `this` of its own — but its top-level declarations are *module*-scoped
    /// instead of global, which is what this flag changes.
    is_module: bool,
    /// Whether the function is an arrow, which never gets its own `arguments`.
    is_arrow: bool,
    /// The name a *named function expression* binds inside its own body.
    /// How many parameters count towards `.length`.
    defined_args: u32,
    /// Parameters that are not a plain name, with the argument slot each came from.
    param_prologue: Vec<(usize, Pattern)>,
    /// What kind of class constructor this function is, if any.
    ctor_kind: CtorKind,
    /// Whether the class has instance fields, so the constructor has to run their
    /// initialiser before it returns.
    /// What the nested function about to be compiled should be told about its class.
    class_ctor_pending: Option<CtorKind>,
    /// Whether this function needs the hidden `this` local, because an arrow inside it
    /// refers to `this`.
    ///
    /// An arrow has no `this` of its own, so the reference materialises the enclosing
    /// function's receiver into a local and lets the arrow capture it as an ordinary
    /// closure variable. Declaring the local is not enough on its own: the store that
    /// fills it has to be prepended to the body, which is what this flag arranges.
    needs_this_local: bool,
    /// The same, for `arguments`.
    needs_arguments_local: bool,
    /// The same, for `new.target`.
    needs_new_target_local: bool,
    /// Whether the body already opens by filling a `this` local, which
    /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
    has_this_prologue: bool,
    /// The same, for `<home_object>`: the object `super` resolves against.
    ///
    /// An arrow and a static block have no home object of their own — only the method or
    /// initialiser they were written in does — so `super.x` inside one is a read of the
    /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
    /// by `special_object 4`, the same way `this` is.
    needs_home_object_local: bool,
    /// The same, for `this.active_func`: the function `super()` constructs from.
    ///
    /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
    /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
    /// as a local of the enclosing function; an arrow that escaped the constructor
    /// (`iter.return = () => super()`) then finds it in its closure even with the
    /// constructor nowhere on the call stack.
    needs_active_func_local: bool,
    /// Hidden locals of the `with` blocks currently open, innermost last.
    with_names: Vec<String>,
    /// Set while a with-guard is being emitted, so the guard's own accesses are not
    /// wrapped in another guard.
    emitting_with_guard: bool,
    self_name: Option<String>,
    /// Where the function body starts, in source order; see [`Function::body_start`].
    body_start: (u32, u32),
    /// Whether the body contains a *direct* `eval(...)` call.
    ///
    /// A direct eval sees every binding of the function that called it, including ones
    /// no other code mentions. It also hands those bindings to any closure it creates,
    /// which can outlive the function. Both need the bindings to live in cells, so this
    /// flag makes the function treat all of them as captured.
    has_direct_eval: bool,
    /// Whether the parameter list contains a default expression, which is what gives
    /// the function a second variable environment (see [`PARAM_SCOPE`]).
    has_parameter_expressions: bool,
    /// Whether the instructions being emitted belong to the parameter list.
    ///
    /// References made here must not see the body's `var`s: the body has not run yet,
    /// and the reference's own model keeps the two scopes apart.
    in_params: bool,
    /// Whether an arrow created in this function's parameter list needs the parameter
    /// scope's `arguments` binding.
    needs_param_arguments: bool,
    /// Whether this function was *created* inside a parameter list.
    ///
    /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
    /// arrow too. The name reference is the arrow's, but the scope it must not see
    /// belongs to the function the arrow was born in.
    created_in_params: bool,
    /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
    ///
    /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
    /// final while the body is still being compiled: a named function expression declares
    /// its own name binding *after* the body, and that binding is exactly what
    /// `eval("myfunc = 1")` has to find.
    eval_sites: Vec<EvalSite>,
    /// Direct `eval` call sites seen so far: where, and the block that was current.
    pending_eval_sites: Vec<(Span, u64, bool)>,
    /// Whether this body contains `await`.
    ///
    /// For a *module* this decides whether its body is an async function: top-level
    /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
    /// to survive to the compiled function rather than being a local of the compiler.
    has_await: bool,
    /// The module tables, when this body is a module.
    ///
    /// Only the top-level state ever has one: `export` and `import` are top-level
    /// statements, so nothing nested can add to these tables.
    module: Option<ModuleMeta>,
    /// Whether the self-name prologue (`special_object 2` then the store) has been
    /// emitted for this function.
    ///
    /// A *nested* function's lookup declares the binding early (see
    /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
    /// prologue is still needed — the binding existing is not the same as it being
    /// initialised.
    self_name_initialized: bool,
    /// Whether the code emitted so far leaves the program's result on the stack.
    /// The reference tracks this for the hidden `<ret>` local of an eval script.
    leaves_value: bool,
    /// Statement nesting depth, used to tell top-level statements apart.
    stmt_depth: u32,
    /// Function declarations waiting to be instantiated at scope entry, as
    /// (target slot, constant pool index). The reference emits these from
    /// `instantiate_hoisted_definitions` rather than at the statement, because a
    /// declaration is visible before it is reached.
    hoisted: Vec<(u64, HoistTarget, u32)>,
    /// Function declarations whose bodies are compiled only once the enclosing scope
    /// has finished hoisting, as (owning block, declaration).
    ///
    /// Compiling a body at the declaration makes the result depend on source order: in
    /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
    /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
    /// names first and the bodies second is what removes that dependence.
    deferred_funcs: Vec<(u64, Box<ast::Function>)>,
    /// The source position of the node being compiled. Every instruction emitted
    /// takes it, which is how the position table that feeds stack traces is built.
    cur_pos: Option<Position>,
    /// One position per entry in `insns`, index-aligned.
    insn_pos: Vec<Option<Position>>,
}

/// Where a hoisted function declaration is stored.
#[derive(Debug, Clone)]
enum HoistTarget {
    Arg(u32),
    Loc(u32),
    /// A global, which the resolver looks up by name.
    Global(String),
}

impl FnState {
    /// Whether this function suspends: a generator or an async function.
    ///
    /// A suspending function's `return` is a `return_async` and its body starts with an
    /// `initial_yield`, so almost every statement that touches control flow asks this.
    fn is_suspending(&self) -> bool {
        self.kind.is_generator() || self.kind.is_async()
    }

    fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
        FnState {
            name: name.into(),
            kind,
            strict: false,
            args: Vec::new(),
            vars: Vec::new(),
            closure_vars: Vec::new(),
            cpool: Vec::new(),
            atoms: Vec::new(),
            blocks: Vec::new(),
            current_block: 0,
            created_in_block: NO_PARENT,
            var_block: Vec::new(),
            no_value: false,
            label_since_insn: false,
            discard_value: false,
            body_block: 0,
            block_heads: Vec::new(),
            jump_targets: Vec::new(),
            insns: Vec::new(),
            labels: Vec::new(),
            var_ref_count: 0,
            line: 1,
            column: 1,
            is_script: false,
            is_module: false,
            is_arrow: false,
            defined_args: 0,
            param_prologue: Vec::new(),
            ctor_kind: CtorKind::None,
            class_ctor_pending: None,
            needs_this_local: false,
            needs_arguments_local: false,
            needs_new_target_local: false,
            has_this_prologue: false,
            needs_home_object_local: false,
            needs_active_func_local: false,
            with_names: Vec::new(),
            emitting_with_guard: false,
            self_name: None,
            has_direct_eval: false,
            body_start: (0, 0),
            has_parameter_expressions: false,
            in_params: false,
            needs_param_arguments: false,
            created_in_params: false,
            eval_sites: Vec::new(),
            pending_eval_sites: Vec::new(),
            has_await: false,
            module: None,
            self_name_initialized: false,
            leaves_value: false,
            stmt_depth: 0,
            hoisted: Vec::new(),
            deferred_funcs: Vec::new(),
            cur_pos: None,
            insn_pos: Vec::new(),
        }
    }

    /// The scope a declaration lands in: a script's top-level declarations are
    /// globals, everything else gets a slot.
    /// Whether a binding declared *now* becomes a property of the global object.
    ///
    /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
    /// The `var` case is decided by the keyword rather than by the cursor position:
    /// `var` is function-scoped, so a `var i` in a `for` head is still the same
    /// binding as a `var i` in the body, even though the head has its own block.
    fn declares_globally(&self, def: &VarDef) -> bool {
        // A module's top-level declarations are *module*-scoped: they live in the module
        // record, never on the global object. Two modules can both declare `var x`
        // without seeing each other, which is the whole point.
        if self.is_module {
            return false;
        }
        self.is_script && (!def.is_lexical || self.current_block == self.body_block)
    }
}

/// The compiler's entry point.
pub struct Compiler {
    module: bool,
    /// Whether the program itself is the body of an `async` function.
    ///
    /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
    /// completion value is wrapped so a returned promise is not adopted.
    async_body: bool,
    /// Enclosing functions, outermost first. The last entry is the current one.
    stack: Vec<FnState>,
    /// The private names visible at this point, innermost class body last.
    ///
    /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
    /// to the class body: a method, an arrow inside it and a class nested inside that arrow
    /// all resolve against the same entries, and the parser accepts exactly that set
    /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
    /// class's names the moment a method started.
    private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
}

/// How a use site of a private name compiles.
///
/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
/// of a setter-only accessor pair.
#[derive(Clone, Copy, PartialEq, Eq)]
enum PrivateKind {
    /// `#x = 1`: an own property keyed by the symbol in the binding.
    Field,
    /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
    Method,
    /// `get #a() {}`: the binding holds the getter, and a read calls it.
    Getter,
    /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
    /// the same `TypeError` as reading an uninitialised `const`.
    Setter,
}

/// What the compiler knows about one `#name` where it is used.
#[derive(Clone)]
struct PrivateUse {
    kind: PrivateKind,
    /// `#a<set>` when the class defines a setter for this name.
    ///
    /// A second binding, not a second field of the first: the reference stores the setter
    /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
    setter: Option<String>,
}

/// The class-scope bindings one class body needs, in declaration order.
#[derive(Default)]
struct ClassPlan {
    /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
    /// at class entry, in member order.
    bindings: Vec<String>,
    /// The private names, for the use sites inside the body.
    uses: std::collections::HashMap<String, PrivateUse>,
    /// Computed field keys, by element index, so the emission pass does not have to redo the
    /// per-half counter that names them.
    computed: std::collections::HashMap<usize, String>,
    /// Whether the instance initialiser has to add the brand to `this`.
    instance_brand: bool,
    /// Whether the constructor itself has to carry the brand.
    static_brand: bool,
}

impl ClassPlan {
    /// Walk a class body once and decide every class-scope binding it needs.
    ///
    /// Order is the reference's: a member's binding is created when the member is parsed, so
    /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
    /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
    /// the disassembly stops matching even when every instruction is right.
    fn build(class: &Class) -> ClassPlan {
        let mut plan = ClassPlan::default();
        let mut instance_keys = 0usize;
        let mut static_keys = 0usize;
        for (index, element) in class.elements.iter().enumerate() {
            match element {
                ClassElement::Method {
                    key: PropName::Private(ident),
                    kind,
                    is_static,
                    ..
                } => {
                    let name = format!("#{}", ident.name);
                    let first = !plan.uses.contains_key(&name);
                    if first {
                        plan.bindings.push(name.clone());
                        plan.uses.insert(
                            name.clone(),
                            PrivateUse {
                                kind: match kind {
                                    MethodKind::Get => PrivateKind::Getter,
                                    MethodKind::Set => PrivateKind::Setter,
                                    _ => PrivateKind::Method,
                                },
                                setter: None,
                            },
                        );
                    }
                    match kind {
                        MethodKind::Set => {
                            let binding = format!("{name}<set>");
                            plan.bindings.push(binding.clone());
                            if let Some(use_) = plan.uses.get_mut(&name) {
                                use_.setter = Some(binding);
                            }
                        }
                        // A getter is what makes the name readable, so a pair that started
                        // as a setter becomes readable once the getter arrives.
                        MethodKind::Get => {
                            if let Some(use_) = plan.uses.get_mut(&name) {
                                use_.kind = PrivateKind::Getter;
                            }
                        }
                        _ => {}
                    }
                    if *is_static {
                        plan.static_brand = true;
                    } else {
                        plan.instance_brand = true;
                    }
                }
                ClassElement::Method {
                    key: PropName::Computed(_),
                    ..
                } => {}
                ClassElement::Method { .. } => {}
                ClassElement::Field {
                    key: PropName::Private(ident),
                    ..
                } => {
                    let name = format!("#{}", ident.name);
                    if !plan.uses.contains_key(&name) {
                        plan.bindings.push(name.clone());
                        plan.uses.insert(
                            name,
                            PrivateUse {
                                kind: PrivateKind::Field,
                                setter: None,
                            },
                        );
                    }
                }
                ClassElement::Field {
                    key: PropName::Computed(_),
                    is_static,
                    ..
                } => {
                    let index_in_half = if *is_static {
                        static_keys += 1;
                        static_keys - 1
                    } else {
                        instance_keys += 1;
                        instance_keys - 1
                    };
                    let binding = computed_field_binding(index_in_half, *is_static);
                    plan.bindings.push(binding.clone());
                    plan.computed.insert(index, binding);
                }
                ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
            }
        }
        plan
    }

    /// How a private name used inside the body compiles, or `None` if no enclosing class
    /// declares it.
    fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
        compiler
            .private_scopes
            .iter()
            .rev()
            .find_map(|scope| scope.get(name))
    }
}

/// Compile a script.
pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
    Compiler::new(false).compile(program)
}

/// Compile a script whose top level is the body of an `async` function.
///
/// The body is an ordinary script in every other way — it still reports a completion value
/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
/// it answers a promise instead of a value. The wrapper is what keeps that promise from
/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
/// documents.
pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
    Compiler::for_suspensible_script().compile(program)
}

/// Compile a module.
pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
    Compiler::new(true).compile(program)
}

impl Compiler {
    /// Create a compiler.
    pub fn new(module: bool) -> Compiler {
        Compiler {
            module,
            async_body: false,
            stack: Vec::new(),
            private_scopes: Vec::new(),
        }
    }

    /// Create a compiler for a script whose top level is an `async` function body.
    fn for_suspensible_script() -> Compiler {
        Compiler {
            module: false,
            async_body: true,
            stack: Vec::new(),
            private_scopes: Vec::new(),
        }
    }

    /// Compile a whole program into its top-level function.
    pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
        let mut state = FnState::new("<eval>", FunctionKind::Normal);
        // A module body is *not* a script: it has no completion value, so no hidden
        // `<ret>` local and no `put_loc0` before each statement. What it shares with one
        // is having no `arguments` of its own and no receiver — see `is_module`.
        state.is_script = !self.module;
        state.is_module = self.module;
        if self.module {
            state.module = Some(ModuleMeta::default());
        }
        state.strict = program.strict || self.module;
        state.line = program.span.start.line;
        state.column = program.span.start.column;
        // Locals are numbered in declaration order; `<ret>` is always slot 0.
        //
        // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
        // slot that only appears in one of the two arrays shifts every later
        // binding's block and silently loses the temporal-dead-zone marking for
        // the script's own blocks. A function frame has no `<ret>`, which is why
        // the misalignment only showed up at the top level.
        if !self.module {
            state.vars.push(VarDef::var("<ret>"));
            state.var_block.push(FUNCTION_SCOPE);
        }
        self.stack.push(state);
        // The body is its own scope, keyed by the position of the program.
        // The script body needs a key no statement can produce. Statement keys are
        // source offsets, and the program's own start offset is `0` — which is also
        // the offset of the first statement, so a top-level `{ let x }` or
        // `for (let i …)` used to share the body's block and lose its scope.
        let body_key = SCRIPT_BODY;
        self.push_block(body_key, NO_PARENT);
        self.state().body_block = body_key;
        // A module body opens with a re-entry guard. The host evaluates a module exactly
        // once, so the guard never fires in practice — but the reference emits it, and a
        // module function called a second time (through `eval` of its own source, say)
        // must not run its body again.
        let module_guard = self.module.then(|| self.new_label());
        if let Some(body) = module_guard {
            // The guard wraps the *hoisting* too: a second evaluation of the same module
            // body must not even re-create its function declarations.
            self.emit(Opcode::PushThis, &[]);
            self.emit_jump(Opcode::IfFalse, body, &[]);
        }
        self.hoist(&program.body, body_key)?;
        // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
        // come before the guard's `return_undef`: the reference's jump target sits past
        // both, and a second evaluation therefore re-creates nothing.
        self.emit_scope_enter(body_key);
        if let Some(body) = module_guard {
            self.emit(Opcode::ReturnUndef, &[]);
            self.place_label(body);
        }
        // Through `stmts` rather than the loop, so a `using` region at the top level of an
        // eval'd body or a module gets its disposal epilogue like any other block.
        self.stmts(&program.body)?;
        if self.module {
            // A module has no completion value; its body simply ends.
            self.emit(Opcode::Undefined, &[]);
            self.emit(Opcode::ReturnAsync, &[]);
            // Top-level `await` makes the body an async function, so the host runs it as
            // a coroutine and waits. Without this the `await` opcode would suspend in a
            // body that nothing knows how to resume — which is what "a generator body ran
            // as an ordinary call" was reporting.
            if self.cur().has_await {
                self.state().kind = FunctionKind::Async;
            }
        } else if self.async_body {
            // An async body reports its completion value the same way, but through an
            // object: the function answers a promise, and resolving that promise *with*
            // the completion value would adopt a promise completion instead of reporting
            // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
            // resolve to `{value: <promise>}` rather than to `7`.
            //
            // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
            // value in an object so that promises can be safely returned").
            self.emit(Opcode::Object, &[]);
            self.emit(Opcode::Dup, &[]);
            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
            self.emit(Opcode::Return, &[]);
            self.state().kind = FunctionKind::Async;
        } else {
            // The program's value is whatever the last expression statement stored in
            // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
            // case into a single `set_loc0`.
            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
            self.emit(Opcode::Return, &[]);
        }
        Ok(self.finish_current())
    }

    // -- emitting ----------------------------------------------------------

    fn state(&mut self) -> &mut FnState {
        self.stack.last_mut().expect("a function is being compiled")
    }

    fn cur(&self) -> &FnState {
        self.stack.last().expect("a function is being compiled")
    }

    fn emit(&mut self, op: Opcode, operands: &[Op]) {
        self.state().label_since_insn = false;
        let pos = self.cur().cur_pos;
        self.state().insns.push(Insn::Fixed {
            op,
            operands: operands.to_vec(),
        });
        self.state().insn_pos.push(pos);
    }

    /// Reset the script's hidden return value to `undefined`.
    ///
    /// Called at the start of every statement that does not itself produce the
    /// program's value, which is how the reference keeps `if`/loop results from
    /// leaking into an eval result.
    fn reset_value(&mut self) {
        if !self.cur().is_script {
            return;
        }
        self.emit(Opcode::Undefined, &[]);
        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
        self.state().leaves_value = false;
    }

    /// Whether `name` is a local or argument slot rather than a global.
    fn is_slot(&self, name: &str) -> bool {
        self.cur().vars.iter().any(|v| v.name == name)
            || self.cur().args.iter().any(|a| a.name == name)
    }

    /// `with (object) body`
    ///
    /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
    /// what makes the object reachable from a closure created inside the block, and it
    /// is also what lets an `eval` find it: the runtime collects the active `With`
    /// locals of every frame and resolves names against them before the realm.
    ///
    /// Inside the block every name reference is spelled as "look in the with objects
    /// first", innermost outwards, and falls through to the ordinary access. The test is
    /// `in`, which is `HasProperty` — the same question the spec's Object Environment
    /// Record asks.
    fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
        let name = self.next_with_name();
        // The object expression is evaluated *outside* the scope it introduces, so no
        // wrapper may be emitted for the names it mentions.
        let saved = std::mem::take(&mut self.state().with_names);
        self.expr(object)?;
        self.state().with_names = saved;
        self.emit(Opcode::ToObject, &[]);
        self.declare_hidden_local(&name, VarKind::With);
        // Pushed before the store so the store itself is not guarded by an *outer*
        // `with` — the object being stored is the new one, not something to look up.
        self.state().with_names.push(name.clone());
        self.emit_var(VarAction::Put, &name);
        let result = self.stmt(body);
        self.state().with_names.pop();
        result
    }

    /// A hidden-local name for one `with` block, distinct from every enclosing one.
    fn next_with_name(&self) -> String {
        let depth = self.cur().with_names.len();
        if depth == 0 {
            "<with>".to_string()
        } else {
            format!("<with{depth}>")
        }
    }

    /// Declare a hidden local that must stay a *local* even in a script.
    ///
    /// A script's `var` is a property of the global object, but the `with` object is not
    /// part of the source program's name space at all — it only exists for the compiler
    /// and the runtime — so it goes straight into the frame's slot list.
    fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
        let state = self.state();
        if state.vars.iter().any(|v| v.name == name) {
            return;
        }
        state.var_block.push(FUNCTION_SCOPE);
        state.vars.push(VarDef {
            kind,
            ..VarDef::var(name)
        });
    }

    /// Emit a name access, guarded by every active `with` object.
    ///
    /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
    /// the read itself; the outer guards and the plain access are what the `if_false`
    /// jumps to, so the innermost object wins.
    fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
        let names = self.cur().with_names.clone();
        let done = self.new_label();
        let mut starts = Vec::new();
        // Innermost object first: the last `with` opened is the one that shadows the
        // others, so its guard has to be the first chance to satisfy the name.
        for with_name in names.iter().rev() {
            let next = self.new_label();
            // `in` takes the key then the object.
            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
            self.emit_var(VarAction::Get, with_name);
            self.emit(Opcode::In, &[]);
            self.emit_jump(Opcode::IfFalse, next, &[]);
            starts.push(next);
            match action {
                // A store keeps the value under the receiver, which is where
                // `put_field` expects it.
                VarAction::Put | VarAction::PutInit => {
                    self.emit_var(VarAction::Get, with_name);
                    self.emit(Opcode::Swap, &[]);
                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
                }
                _ => {
                    self.emit_var(VarAction::Get, with_name);
                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
                    self.emit(Opcode::GetArrayEl, &[]);
                }
            }
            self.emit_jump(Opcode::Goto, done, &[]);
            self.place_label(next);
        }
        self.emit_var(action, name);
        self.place_label(done);
    }

    fn emit_var(&mut self, action: VarAction, name: &str) {
        // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
        // stores and keeps the value in one instruction. The reference does this
        // in a post-pass; folding it at emit time keeps instruction indices
        // stable, which matters because labels are recorded as indices.
        //
        // Only slots have a `set_` form: a global is stored with `put_var` and
        // read with `get_var`, and the reference does not fold those.
        //
        // A label between the two cancels the fold. `set_x v` leaves the value on
        // the stack, which is only equivalent when the read immediately follows the
        // store; when a jump target sits in between, the store must *consume* the
        // value and the read must fetch it afresh. A loop head is exactly that
        // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
        // condition re-reads it — and folding across the label would make the
        // condition compare whatever the previous iteration left on the stack.
        if action == VarAction::Get {
            let is_slot = self.is_slot(name);
            let at_label = std::mem::take(&mut self.state().label_since_insn);
            //
            // `arguments` is excluded because the reference treats it as a special
            // binding: it is initialised once and read many times, and folding its
            // initialisation into a `set_` would leave the object on the stack where
            // the reference leaves nothing.
            if is_slot
                && name != "arguments"
                && !at_label
                && let Some(Insn::Var {
                    action: previous,
                    name: previous_name,
                    ..
                }) = self.state().insns.last_mut()
                && *previous == VarAction::Put
                && previous_name == name
            {
                *previous = VarAction::Set;
                return;
            }
        }
        // Inside a `with`, every name lookup consults the with objects first. The
        // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
        let guarded = !self.cur().with_names.is_empty()
            && !self.cur().with_names.iter().any(|hidden| hidden == name)
            && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
            && !self.state().emitting_with_guard;
        if guarded {
            self.state().emitting_with_guard = true;
            self.emit_with_guarded(action, name);
            self.state().emitting_with_guard = false;
            return;
        }
        let block = self.cur().current_block;
        self.state().label_since_insn = false;
        let pos = self.cur().cur_pos;
        let in_params = self.cur().in_params;
        self.state().insns.push(Insn::Var {
            action,
            name: name.to_string(),
            block,
            in_params,
        });
        self.state().insn_pos.push(pos);
    }

    fn new_label(&mut self) -> Label {
        let state = self.state();
        state.labels.push(None);
        Label(state.labels.len() as u32 - 1)
    }

    fn place_label(&mut self, label: Label) {
        let index = self.cur().insns.len();
        self.state().label_since_insn = true;
        self.state().labels[label.0 as usize] = Some(index);
    }

    fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
        let mut operands = vec![Op::Label(label)];
        operands.extend_from_slice(extra);
        self.emit(op, &operands);
    }

    // -- scopes ------------------------------------------------------------

    /// Start a new lexical scope inside `parent`.
    fn push_block(&mut self, key: u64, parent: u64) {
        let state = self.state();
        if !state.blocks.iter().any(|b| b.key == key) {
            state.blocks.push(Block { key, parent });
        }
        state.current_block = key;
    }

    /// Emit the code that runs when a lexical scope is entered.
    ///
    /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
    /// so entering its block marks it uninitialised. Hoisted function
    /// declarations are created here instead, which is why a call before the
    /// declaration still works.
    ///
    /// The order is not obvious: bindings are emitted in *reverse* declaration
    /// order, because the reference walks its scope chain, which is built by
    /// prepending.
    fn emit_scope_enter(&mut self, block: u64) {
        let hoisted = std::mem::take(&mut self.state().hoisted);
        let mut mine: Vec<(HoistTarget, u32)> = hoisted
            .into_iter()
            .filter(|(owner, _, _)| *owner == block)
            .map(|(_, target, pool_index)| (target, pool_index))
            .collect();
        mine.sort_by_key(|(target, _)| match target {
            HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
            HoistTarget::Global(_) => u32::MAX,
        });
        for (target, pool_index) in mine {
            self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
            match target {
                HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
                HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
                HoistTarget::Global(name) => {
                    // A global binding lives in a reference cell, so the store
                    // goes through `put_var_ref` while reads use `get_var`.
                    let block = self.cur().current_block;
                    let pos = self.cur().cur_pos;
                    let in_params = self.cur().in_params;
                    self.state().insns.push(Insn::Var {
                        action: VarAction::PutRef,
                        name,
                        block,
                        in_params,
                    });
                    self.state().insn_pos.push(pos);
                }
            }
        }
        for index in self.block_vars_reversed(block) {
            self.emit(
                Opcode::SetLocUninitialized,
                &[Op::Slot(Slot::Loc(index as u32))],
            );
        }
    }

    /// Emit the code that runs when a lexical scope is exited.
    ///
    /// A captured binding has to be closed: detaching its reference cell freezes
    /// the value the binding had when the block ended, which is what a closure
    /// created inside the block must keep seeing.
    fn emit_scope_leave(&mut self, block: u64) {
        for index in self.block_vars_reversed(block) {
            if self.cur().vars[index].is_captured {
                self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
            }
        }
    }

    /// Locals declared in `block`, in reverse declaration order.
    fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
        let state = self.cur();
        let mut out: Vec<usize> = (0..state.vars.len())
            .filter(|index| {
                state.var_block.get(*index).copied() == Some(block)
                    && state.vars[*index].is_lexical
                    // A derived constructor's `this` is lexical but is not initialised by
                    // entering the scope: `check_ctor` proves it, so its dead-zone marker
                    // was emitted with the constructor's own prologue.
                    && state.vars[*index].name != "this"
            })
            .collect();
        out.reverse();
        out
    }

    /// Declare a local, even at the top level of a script.
    ///
    /// A `catch` parameter is always a local: the reference puts it in the
    /// function's own variable list (`1: catch e`), never in the global object,
    /// because it only exists while the handler runs.
    fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
        let state = self.state();
        let index = state.vars.len() as u32;
        // A `catch` parameter belongs to a scope even though it is not lexical: the
        // runtime instantiates it per handler entry, but it never sits in the
        // temporal dead zone.
        let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
            state.current_block
        } else {
            0
        };
        state.var_block.push(block);
        state.vars.push(def);
        index
    }

    fn declare(&mut self, name: &str, def: VarDef) -> u32 {
        if self.cur().is_module
            && self.cur().current_block == self.cur().body_block
            && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
        {
            // Only the body's own block: a `let` inside a module-level `{}` is still an
            // ordinary local of that block, not a module variable.
            //
            // A `using` binding is excluded on purpose, and the reference excludes it in
            // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
            // "'using' variables are currently not exported in modules"): a module-level
            // `using` is an ordinary *local* of the module body function, not a module
            // cell. Two things follow, and both are what the reference does — `export {a}`
            // of a `using` binding is "exported variable 'a' does not exist", and
            // disposal works, because the disposal epilogue addresses locals by slot.
            //
            // The hidden dispose-method variable is excluded for a stronger reason: it is
            // *always* a local (`add_scope_var` in the reference), and it must sit
            // immediately after its value so `using_dispose` can find it at `slot + 1`.
            return self.declare_module(name, &def);
        }
        if self.cur().declares_globally(&def) {
            self.declare_global(name, &def);
            return 0;
        }
        let state = self.state();
        let index = state.vars.len() as u32;
        let block = if def.is_lexical {
            state.current_block
        } else {
            0
        };
        state.var_block.push(block);
        state.vars.push(def);
        index
    }

    /// Declare a `using` binding and its cached dispose method, returning both slots.
    ///
    /// The two are adjacent by construction, because `using_dispose` addresses the pair as
    /// `(value, value + 1)` — the reference does the same and documents the constraint.
    fn declare_using(&mut self, name: &str) -> (u32, u32) {
        let mut def = VarDef::lexical(name);
        def.kind = VarKind::Using;
        let value = self.declare(name, def);
        let mut method = VarDef::lexical(using_method_name(name));
        method.kind = VarKind::UsingMethod;
        let method_slot = self.declare(&using_method_name(name), method);
        (value, method_slot)
    }

    /// The slot a `using` binding's dispose method lives in.
    fn using_method_slot(&self, name: &str) -> Option<u32> {
        let hidden = using_method_name(name);
        self.cur()
            .vars
            .iter()
            .position(|var| var.name == hidden)
            .map(|index| index as u32)
    }

    // -- statements --------------------------------------------------------

    fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
        self.stmt_labelled(stmt, &[])
    }

    /// Compile a statement that a chain of labels names.
    ///
    /// Only a loop consumes `labels`; every other statement ignores them (the
    /// parser has already rejected a label on a statement that cannot use it).
    fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
        // Only a *top-level* expression statement supplies the program's value.
        let saved = self.cur().leaves_value;
        self.state().leaves_value =
            matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
        self.state().stmt_depth += 1;
        let result = self.stmt_inner(stmt, labels);
        self.state().stmt_depth -= 1;
        // A nested statement never contributes the program's value, so the flag
        // the wrapper set above is what survives.
        let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
        self.state().leaves_value = produced;
        let _ = saved;
        result
    }

    fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
        match &stmt.kind {
            StmtKind::Empty | StmtKind::Debugger => {}
            StmtKind::Expr(expr) => {
                // The statement's first token is a position the reference records: an
                // expression statement is the `hasexpr:` arm of `js_parse_statement`,
                // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
                // is why an error from a construct with no position of its own (`[...it]`
                // with a throwing iterator, `` `${x}` ``) reports the statement's start.
                let saved = self.cur().cur_pos;
                self.state().cur_pos = Some(expr.span.start);
                // An expression statement's value is thrown away — except in a
                // script, where it becomes the program's result. `assign` reads this
                // and clears it, so a nested assignment still produces a value.
                self.state().discard_value = !self.cur().is_script;
                let result = self.expr(expr);
                self.state().discard_value = false;
                result?;
                if std::mem::take(&mut self.state().no_value) {
                    // A store whose value was discarded left nothing to drop.
                } else if self.cur().is_script {
                    // The program's value lands in the hidden `<ret>` local.
                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
                } else {
                    self.emit(Opcode::Drop, &[]);
                }
                // Restored last: the trailing `drop` is part of the statement, and in the
                // reference it simply inherits whatever the expression last recorded.
                self.state().cur_pos = saved;
            }
            StmtKind::Block(body) => {
                // The block's declarations were hoisted with its enclosing
                // statement list, so there is nothing left to declare here.
                let key = stmt.span.start.offset as u64;
                let parent = self.cur().current_block;
                self.push_block(key, parent);
                self.emit_scope_enter(key);
                // A block is where a `using` region lives, so its statements have to go
                // through `stmts`: that is what emits the disposal epilogue.
                self.stmts(body)?;
                self.emit_scope_leave(key);
                self.state().current_block = parent;
            }
            StmtKind::VarDecl(decl) => self.var_decl(decl)?,
            // A function declaration was already instantiated when its scope was
            // entered, so the statement itself emits nothing.
            StmtKind::FuncDecl(_) => {}
            StmtKind::If { test, cons, alt } => {
                self.reset_value();
                let else_label = self.new_label();
                let end_label = self.new_label();
                self.expr(test)?;
                self.emit_jump(Opcode::IfFalse, else_label, &[]);
                self.stmt(cons)?;
                if alt.is_some() {
                    self.emit_jump(Opcode::Goto, end_label, &[]);
                }
                self.place_label(else_label);
                if let Some(alt) = alt {
                    self.stmt(alt)?;
                    self.place_label(end_label);
                }
            }
            StmtKind::While { test, body } => {
                self.reset_value();
                let top = self.new_label();
                let end = self.new_label();
                self.place_label(top);
                self.expr(test)?;
                // The condition's false branch and `break` share one target,
                // which is why a `while` loop needs only one end label.
                self.emit_jump(Opcode::IfFalse, end, &[]);
                self.loop_body(body, labels, top, end)?;
                self.emit_jump(Opcode::Goto, top, &[]);
                self.place_label(end);
            }
            StmtKind::DoWhile { body, test } => {
                self.reset_value();
                let top = self.new_label();
                let cont = self.new_label();
                let end = self.new_label();
                self.place_label(top);
                // `continue` in a `do…while` runs the test, so it lands on `cont`
                // rather than on the loop head.
                self.loop_body(body, labels, cont, end)?;
                self.place_label(cont);
                self.expr(test)?;
                self.emit_jump(Opcode::IfTrue, top, &[]);
                self.place_label(end);
            }
            StmtKind::For {
                init,
                test,
                update,
                body,
            } => {
                self.reset_value();
                let for_key = stmt.span.start.offset as u64;
                let for_parent = self.cur().current_block;
                self.push_block(for_key, for_parent);
                self.emit_scope_enter(for_key);
                if let Some(init) = init {
                    match init {
                        ForInit::VarDecl(decl) => {
                            self.var_decl(decl)?;
                        }
                        ForInit::Expr(expr) => {
                            // The head's value is discarded. Saying so lets an
                            // assignment store with `put` instead of `dup`+`put`, which
                            // is what the reference emits — and the difference matters:
                            // a `dup`/`drop` pair around the store gives the peephole a
                            // chance to fold the store into the *condition's* read.
                            self.state().discard_value = true;
                            let result = self.expr(expr);
                            self.state().discard_value = false;
                            result?;
                            if !std::mem::take(&mut self.state().no_value) {
                                self.emit(Opcode::Drop, &[]);
                            }
                        }
                    }
                }
                // A `let`/`const` in the head gets a *fresh binding per iteration*,
                // so a closure made in the body captures that iteration's value
                // instead of sharing one. The reference expresses this with
                // `close_loc`, which swaps in a new reference cell holding the
                // current value; the three points below are the ones it uses — after
                // the initialiser, before the update, and after the loop.
                let loop_bindings = match init {
                    Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
                        let mut names: Vec<String> = Vec::new();
                        for declarator in &decl.declarators {
                            let mut idents = Vec::new();
                            declarator.target.bound_names(&mut idents);
                            names.extend(idents.into_iter().map(|ident| ident.name));
                        }
                        names
                    }
                    _ => Vec::new(),
                };
                // The reference also closes right after the initialiser, so the first
                // iteration's closures get their own cell rather than sharing the one
                // the initialiser wrote into.
                for name in &loop_bindings {
                    let pos = self.cur().cur_pos;
                    self.state().insns.push(Insn::CloseCaptured {
                        name: name.clone(),
                        block: for_key,
                    });
                    self.state().insn_pos.push(pos);
                }
                let top = self.new_label();
                let cont = self.new_label();
                let end = self.new_label();
                self.place_label(top);
                if let Some(test) = test {
                    self.expr(test)?;
                    self.emit_jump(Opcode::IfFalse, end, &[]);
                }
                // `continue` runs the update expression first, so it lands on
                // `cont`, which sits just before the update.
                self.loop_body(body, labels, cont, end)?;
                self.place_label(cont);
                // Each iteration ends with a fresh cell, so the closures the body just
                // created keep the cell they captured and the update writes to a new
                // one. Without this every closure in the loop shares one binding.
                let binding_block = for_key;
                for name in &loop_bindings {
                    let pos = self.cur().cur_pos;
                    self.state().insns.push(Insn::CloseCaptured {
                        name: name.clone(),
                        block: binding_block,
                    });
                    self.state().insn_pos.push(pos);
                }
                if let Some(update) = update {
                    self.state().discard_value = true;
                    let result = self.expr(update);
                    self.state().discard_value = false;
                    result?;
                    if !std::mem::take(&mut self.state().no_value) {
                        self.emit(Opcode::Drop, &[]);
                    }
                }
                self.emit_jump(Opcode::Goto, top, &[]);
                self.place_label(end);
                self.emit_scope_leave(for_key);
                self.state().current_block = for_parent;
            }
            StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
            StmtKind::Throw(expr) => {
                self.expr(expr)?;
                self.emit(Opcode::Throw, &[]);
            }
            StmtKind::Break(_) | StmtKind::Continue(_) => {
                // Labels and loops are wired up in a later milestone; a bare
                // break/continue jumps to the innermost enclosing target, which
                // the loop helpers register.
                self.control_transfer(stmt)?;
            }
            StmtKind::Labeled { label, body } => {
                self.labeled(label, body, stmt)?;
            }
            StmtKind::Switch {
                discriminant,
                cases,
            } => {
                self.switch(discriminant, cases, stmt)?;
            }
            StmtKind::Try {
                block,
                handler,
                finalizer,
            } => {
                self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
            }
            StmtKind::ForIn { left, right, body } => {
                self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
            }
            StmtKind::ForOf {
                left,
                right,
                body,
                is_await,
            } => {
                let kind = if *is_await {
                    ForLoopKind::AwaitOf
                } else {
                    ForLoopKind::Of
                };
                self.for_in_of(stmt, left, right, body, kind, labels)?;
            }
            StmtKind::With { object, body } => self.with_stmt(object, body)?,
            StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
            // `import` emits nothing: hoisting already bound its names, and the host
            // fills their cells before the body runs.
            StmtKind::Import(_) => {}
            StmtKind::Export(decl) => self.export_stmt(decl)?,
        }
        Ok(())
    }

    /// Compile `return`, running every enclosing finalizer on the way out.
    ///
    /// `nip_catch` is what makes this possible: it discards everything on the stack
    /// down to and including the `catch` offset while keeping the return value on
    /// top, so the frame the finalizer sees has the same shape as on the normal
    /// path.
    fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
        let mut has_value = value.is_some();
        if let Some(expr) = value {
            // `return f(x)` is a tail call *only* when nothing has to happen to the
            // value afterwards. A `finally` or an open iterator in scope forces the
            // normal path, because the cleanup has to run after the call returns —
            // which is exactly what a tail call refuses to do.
            let plain = self
                .cur()
                .jump_targets
                .iter()
                .all(|target| target.finally_label.is_none() && !target.has_iterator);
            if plain && self.expr_if_tail_call(expr)? {
                return Ok(());
            }
            self.expr(expr)?;
        }
        // `return v` in an *async generator* awaits `v` before anything else happens —
        // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
        // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
        // exactly that reason ("the await must be done before handling the finally in case
        // it raises an exception").
        if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
            self.emit(Opcode::Await, &[]);
            self.state().has_await = true;
        }
        has_value = self.emit_unwind_for_return(has_value);
        // A generator or async function does not return to its caller: it either
        // finishes, and the value becomes `{value, done: true}`, or it suspends.
        // `return_async` is the "finished" half, and it reads the value off the stack
        // rather than carrying it, which is what the resume machinery expects.
        if self.cur().is_suspending() {
            if !has_value {
                self.emit(Opcode::Undefined, &[]);
            }
            self.emit(Opcode::ReturnAsync, &[]);
            return Ok(());
        }
        if has_value {
            self.emit(Opcode::Return, &[]);
        } else {
            self.emit(Opcode::ReturnUndef, &[]);
        }
        Ok(())
    }

    /// Close an iterator: the reference's `emit_iterator_close`.
    ///
    /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
    /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
    /// sequence, and three details in it are load-bearing:
    ///
    /// * the iterator object is compared against `undefined` first, because a loop that
    ///   ran to completion clears that slot rather than closing an exhausted iterator;
    /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
    /// * `preserve_completion` keeps whatever was underneath (the return value of the
    ///   function being left), which is why one branch ends on `nip` and the other on `drop`.
    fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
        if !is_async {
            if preserve_completion {
                self.emit(Opcode::Rot3r, &[]);
                self.emit(Opcode::Undefined, &[]);
            }
            self.emit(Opcode::IteratorClose, &[]);
            return;
        }
        if preserve_completion {
            // `iter next completion -> completion iter`
            self.emit(Opcode::Nip, &[]);
            self.emit(Opcode::Swap, &[]);
        } else {
            // `iter next catch_offset -> iter`
            self.emit(Opcode::Drop, &[]);
            self.emit(Opcode::Drop, &[]);
        }
        let done = self.new_label();
        let no_return = self.new_label();
        self.emit(Opcode::Dup, &[]);
        self.emit(Opcode::IsUndefined, &[]);
        self.emit_jump(Opcode::IfTrue, done, &[]);
        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
        self.emit(Opcode::Dup, &[]);
        self.emit(Opcode::IsUndefinedOrNull, &[]);
        self.emit_jump(Opcode::IfTrue, no_return, &[]);
        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
        self.emit(Opcode::Await, &[]);
        self.state().has_await = true;
        self.emit_jump(Opcode::Goto, done, &[]);
        self.place_label(no_return);
        self.emit(Opcode::Drop, &[]);
        self.place_label(done);
        self.emit(Opcode::Drop, &[]);
    }

    /// Emit the finalizer/iterator cleanup for leaving the current position with a
    /// return, and report whether a value is now on the stack for it to carry.
    ///
    /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
    /// enclosing `finally` at once, and the two used to be separate — the `yield` path
    /// simply emitted `return_async`, so `it.return()` ended the generator without ever
    /// running `finally` blocks the body was sitting inside.
    fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
        let targets = self.cur().jump_targets.clone();
        for target in targets.iter().rev() {
            if target.finally_label.is_none() && !target.has_iterator {
                continue;
            }
            if !has_value {
                // The cleanup expects a value to pass through; with nothing to
                // return, `undefined` stands in.
                self.emit(Opcode::Undefined, &[]);
                has_value = true;
            }
            self.emit(Opcode::NipCatch, &[]);
            if target.has_iterator {
                // Rewind to the loop's own slots and hand the close a dummy catch offset:
                // the loop is being abandoned, so there is nothing left to catch.
                self.emit_iterator_close(target.is_async_iterator, true);
            } else if let Some(finally) = target.finally_label {
                self.emit_jump(Opcode::Gosub, finally, &[]);
            }
        }
        has_value
    }

    /// Compile a statement list, stopping at the first statement that cannot
    /// fall through.
    fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
        for (index, stmt) in body.iter().enumerate() {
            // A `using` declaration is not just a binding: everything after it, to the end
            // of the list, runs inside its disposal region. Compiling the rest of the list
            // recursively is what gives nested regions their innermost-first order.
            if Self::using_declaration(stmt).is_some() {
                return self.using_region(stmt, &body[index + 1..]);
            }
            self.stmt(stmt)?;
            if Self::terminates(stmt) {
                break;
            }
        }
        Ok(())
    }

    /// The declaration a `using` statement carries, if it is one.
    fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
        match &stmt.kind {
            StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
            _ => None,
        }
    }

    /// Compile `decl` and then the rest of its block, disposing when the block ends.
    ///
    /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
    /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
    /// exception — and this engine already funnels all of those through `catch` plus
    /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
    /// `return` and `break` dispose without knowing anything about `using`.
    ///
    /// ```text
    ///   <declaration>              value -> x, method -> x+1
    ///   catch CATCH                <- an exception in the rest lands here
    /// REST:
    ///   <the rest of the block>
    ///   drop                       <- the catch offset, on the fall-through path
    ///   undefined; gosub DISPOSE; drop
    ///   goto END
    /// CATCH:
    ///   using_dispose x            <- merges the failure into the pending exception
    ///   throw
    /// DISPOSE:
    ///   using_dispose_init
    ///   using_dispose x
    ///   using_dispose_end          <- rethrows if a dispose failed
    ///   ret
    /// END:
    /// ```
    fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
        let Some(decl) = Self::using_declaration(stmt) else {
            unreachable!("using_region is only called for a using declaration");
        };
        // `using` binds exactly one name and has no pattern form, which the parser
        // enforces; the region still has to know *which* slot to dispose.
        let name = decl
            .declarators
            .first()
            .and_then(|declarator| match &declarator.target.kind {
                PatternKind::Ident(ident) => Some(ident.name.clone()),
                _ => None,
            });
        self.stmt(stmt)?;
        let Some(name) = name else {
            // Unreachable for a well-formed `using`, but a bare `using` with no declarator
            // must not make the compiler panic.
            return self.stmts(rest);
        };
        let Some(value_slot) = self.using_value_slot(&name) else {
            // Declared globally, which the parser rules out for a script; a module's
            // top level is a scope, and there the disposal stays a known gap.
            return self.stmts(rest);
        };
        // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
        // exit path already disposed.
        let live = !rest.last().is_some_and(Self::terminates);
        self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
    }

    /// The slot a `using` binding's value lives in.
    fn using_value_slot(&self, name: &str) -> Option<u32> {
        self.cur()
            .vars
            .iter()
            .position(|var| var.name == name && var.kind == VarKind::Using)
            .map(|index| index as u32)
    }

    /// Wrap `inside` in a disposal region for the resource in `value_slot`.
    ///
    /// Shared between a `using` statement — which owns the rest of its block — and a
    /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
    /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
    /// the end, `return`, `break`, `continue`, and an exception — and this engine already
    /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
    /// target with a `finally_label` is what makes `return` and `break` dispose without
    /// knowing anything about `using`.
    ///
    /// ```text
    ///   catch CATCH                <- an exception inside lands here
    ///   <inside>
    ///   drop                       <- the catch offset, on the fall-through path
    ///   undefined; gosub DISPOSE; drop
    ///   goto END
    /// CATCH:
    ///   using_dispose slot         <- merges the failure into the pending exception
    ///   throw
    /// DISPOSE:
    ///   using_dispose_init
    ///   using_dispose slot
    ///   using_dispose_end          <- rethrows if a dispose failed
    ///   ret
    /// END:
    /// ```
    fn using_region_around(
        &mut self,
        value_slot: u32,
        live: bool,
        inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
    ) -> Result<(), SyntaxError> {
        let catch_label = self.new_label();
        let end_label = self.new_label();
        let dispose_label = self.new_label();

        self.emit_jump(Opcode::Catch, catch_label, &[]);
        self.push_jump_target(JumpTarget {
            names: Vec::new(),
            break_label: None,
            continue_label: None,
            // The catch offset is the one thing on the stack that leaving has to remove.
            drop_count: 1,
            finally_label: Some(dispose_label),
            is_regular_stmt: false,
            has_iterator: false,
            is_async_iterator: false,
        });
        inside(self)?;
        self.pop_jump_target();

        if live {
            self.emit(Opcode::Drop, &[]);
            self.emit(Opcode::Undefined, &[]);
            self.emit_jump(Opcode::Gosub, dispose_label, &[]);
            self.emit(Opcode::Drop, &[]);
            self.emit_jump(Opcode::Goto, end_label, &[]);
        }

        // An exception unwinds to here with the thrown value on the stack, which is exactly
        // the shape `using_dispose` expects as its error state.
        self.place_label(catch_label);
        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
        self.emit(Opcode::Throw, &[]);

        self.place_label(dispose_label);
        // Inside the subroutine the return value and the `gosub` return address are both
        // live, and neither an outer finalizer nor another region may run before this one
        // has finished.
        self.push_jump_target(JumpTarget {
            names: Vec::new(),
            break_label: None,
            continue_label: None,
            drop_count: 2,
            finally_label: None,
            is_regular_stmt: false,
            has_iterator: false,
            is_async_iterator: false,
        });
        self.emit(Opcode::UsingDisposeInit, &[]);
        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
        self.emit(Opcode::UsingDisposeEnd, &[]);
        self.pop_jump_target();
        self.emit(Opcode::Ret, &[]);
        self.place_label(end_label);
        Ok(())
    }

    /// Declare every name a statement list introduces, before compiling any of
    /// it, so a reference that appears textually before a declaration still
    /// resolves.
    ///
    /// Declarations are walked in source order because that is the order the
    /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
    /// slot 1, while `var b; let a;` gives the opposite. `var` and function
    /// declarations hoist out to the function scope; lexical names belong to the
    /// block they were written in, which `block` records.
    fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
        let saved = self.cur().current_block;
        self.state().current_block = block;
        let result = self.hoist_list(body);
        // Only now is every binding of this scope known, so the deferred function
        // bodies can be compiled against the finished list. Compiled at its own
        // declaration instead, a body that names a `var` written further down would
        // have resolved that name as a global.
        if result.is_ok() {
            let deferred = std::mem::take(&mut self.state().deferred_funcs);
            let mut outcome = Ok(());
            for (owner, func) in deferred {
                let previous = self.cur().current_block;
                self.state().current_block = owner;
                outcome = self.func_decl(&func);
                self.state().current_block = previous;
                if outcome.is_err() {
                    break;
                }
            }
            self.state().current_block = saved;
            return outcome;
        }
        // `current_block` is restored by the caller for a block statement, since
        // it needs it set while compiling; only clean up on the hoist path.
        self.state().current_block = saved;
        result
    }

    fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
        for stmt in body {
            self.hoist_stmt(stmt)?;
        }
        Ok(())
    }

    /// Whether a statement always transfers control away, making everything after
    /// it in the same list unreachable.
    ///
    /// The reference drops such statements in `skip_dead_code`, so `return 1;
    /// let x = 2;` compiles to the same bytecode as `return 1;`.
    fn terminates(stmt: &Stmt) -> bool {
        matches!(
            stmt.kind,
            StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
        )
    }

    fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
        match &stmt.kind {
            StmtKind::VarDecl(decl) => {
                for declarator in &decl.declarators {
                    let mut names = Vec::new();
                    declarator.target.bound_names(&mut names);
                    for name in names {
                        let text = name.name.clone();
                        if decl.kind == VarDeclKind::Var {
                            let def = VarDef::var(text.clone());
                            self.declare_var(&text, def);
                        } else if decl.kind.is_using() {
                            // Two adjacent slots: the resource, then the dispose method
                            // snapshotted at declaration. `using_dispose` reads them as a
                            // pair `(slot, slot + 1)`, so nothing may be declared between
                            // them — which is why both are declared here, in one step,
                            // rather than the method being added at emission time.
                            self.declare_using(&text);
                        } else {
                            let def = if decl.kind == VarDeclKind::Const {
                                VarDef::constant(text.clone())
                            } else {
                                VarDef::lexical(text.clone())
                            };
                            self.declare(&text, def);
                        }
                    }
                }
            }
            StmtKind::FuncDecl(func) => {
                if let Some(name) = &func.name {
                    // A function declaration is a `var` binding that happens to
                    // hold a function, not a lexical one.
                    let def = VarDef::var(name.name.clone());
                    self.declare_var(&name.name.clone(), def);
                }
                // The function object is created when the scope is entered, so it
                // exists before the declaration is reached. Its body is compiled
                // *after* this scope's hoisting finishes, so a name it uses resolves
                // even when the `var` that declares it comes later in the source.
                let owner = self.cur().current_block;
                self.state().deferred_funcs.push((owner, func.clone()));
            }
            StmtKind::ClassDecl(class) => {
                if let Some(name) = &class.name {
                    self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
                }
            }
            // A module's imports are bound before any of its code runs, and its exports
            // declare the very bindings they export — so both hoist the declarations
            // their `StmtKind` arm will later emit code for.
            StmtKind::Import(decl) => self.hoist_import(decl)?,
            StmtKind::Export(decl) => self.hoist_export(decl)?,
            StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
            StmtKind::If { cons, alt, .. } => {
                self.hoist_stmt(cons)?;
                if let Some(alt) = alt {
                    self.hoist_stmt(alt)?;
                }
            }
            StmtKind::While { body, .. }
            | StmtKind::DoWhile { body, .. }
            | StmtKind::Labeled { body, .. }
            | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
            StmtKind::For { init, body, .. } => {
                // A `for` head gets its own scope even when it declares nothing,
                // because `let` in the head is scoped to the loop.
                let key = stmt.span.start.offset as u64;
                let parent = self.cur().current_block;
                self.push_block(key, parent);
                if let Some(init) = init
                    && let ForInit::VarDecl(decl) = init
                {
                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
                }
                self.hoist_stmt(body)?;
                self.state().current_block = parent;
            }
            StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
                let key = stmt.span.start.offset as u64;
                let parent = self.cur().current_block;
                self.push_block(key, parent);
                if let ForHead::VarDecl(decl) = left {
                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
                }
                self.hoist_stmt(body)?;
                self.state().current_block = parent;
            }
            StmtKind::Try {
                block,
                handler,
                finalizer,
            } => {
                self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
                let try_parent = self.cur().current_block;
                if let Some(handler) = handler {
                    // The catch parameter belongs to the function scope, not to a
                    // block: it is a `catch` binding rather than a `let`, so it is
                    // never in the temporal dead zone and `emit_scope_enter` must
                    // not mark it uninitialised. It still has to be declared before
                    // the handler body is hoisted, so it takes the slot the
                    // reference gives it (bindings are numbered in source order).
                    if let Some(pattern) = &handler.param {
                        // The parameter gets its own scope, so entering the handler
                        // does not have to re-declare it. It is not lexical, so it
                        // is never marked uninitialised.
                        let key = Self::try_block_key(stmt, TryPart::Param);
                        let parent = self.cur().current_block;
                        self.push_block(key, parent);
                        // A destructuring parameter binds several names, one slot each,
                        // in the order they are written. The reference declares those as
                        // `let`s rather than as one `catch` binding — its dump prints
                        // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
                        // so the kind follows the shape of the parameter.
                        //
                        // Neither form is in the dead zone: the stores run as the handler
                        // is entered, so both use the unchecked `put_loc`.
                        let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
                        let mut names = Vec::new();
                        pattern.bound_names(&mut names);
                        for name in names {
                            let def = VarDef {
                                name: name.name.clone(),
                                is_const: false,
                                is_lexical: destructures,
                                kind: if destructures {
                                    crate::bytecode::VarKind::LexicalCatch
                                } else {
                                    crate::bytecode::VarKind::Catch
                                },
                                is_captured: false,
                                scope_level: 0,
                                scope_next: None,
                            };
                            self.declare_local(&name.name.clone(), def);
                        }
                        // The handler body nests inside the parameter's scope, so the
                        // body's bindings chain on to the parameter (the reference
                        // prints `let y [next:1]`, pointing at `e`).
                        self.state().current_block = key;
                    }
                    self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
                    // Back to the block the `try` itself lives in, so the finalizer
                    // is a sibling of the handler rather than nested in it.
                    self.state().current_block = try_parent;
                }
                if let Some(finalizer) = finalizer {
                    self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
                }
            }
            StmtKind::Switch { cases, .. } => {
                let key = stmt.span.start.offset as u64;
                let parent = self.cur().current_block;
                self.push_block(key, parent);
                for case in cases {
                    self.hoist_list(&case.body)?;
                }
                self.state().current_block = parent;
            }
            _ => {}
        }
        Ok(())
    }

    /// Hoist a nested statement list, which is its own lexical scope.
    fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
        let parent = self.cur().current_block;
        self.push_block(key, parent);
        self.hoist_list(body)?;
        self.state().current_block = parent;
        Ok(())
    }

    /// A block key for one part of a `try` statement.
    ///
    /// The three parts are three separate scopes, so they cannot share the key a
    /// statement's own offset would give them: the try block, the handler body and
    /// the finalizer would then look like one scope, and their `let` bindings would
    /// be marked uninitialised only on entering the first of them.
    fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
        (stmt.span.start.offset as u64) * 4 + part as u64
    }

    /// Declare a `var`: it lives in the function's own scope, not the block's.
    fn declare_var(&mut self, name: &str, def: VarDef) {
        if self.cur().is_module {
            self.declare_module(name, &def);
            return;
        }
        if self.cur().declares_globally(&def) {
            self.declare_global(name, &def);
            return;
        }
        let state = self.state();
        // A binding of the *parameter* scope does not count: the body's `var` of the
        // same name is a different binding and needs a slot of its own.
        if state.vars.iter().enumerate().any(|(index, v)| {
            v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
        }) {
            return;
        }
        // A `var` belongs to the function scope, never to the enclosing block.
        state.var_block.push(FUNCTION_SCOPE);
        state.vars.push(def);
    }

    /// Declare `name` as a binding of the parameter scope, returning its slot.
    fn declare_param_var(&mut self, name: &str) -> u32 {
        declare_param_var_at(self.state(), name)
    }

    /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
    ///
    /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
    /// so each points at the one declared before it and the oldest ends the chain with
    /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
    /// runtime walks when it instantiates them.
    fn declare_param_binding(&mut self, name: &str) -> u32 {
        let state = self.state();
        let previous = state
            .vars
            .iter()
            .enumerate()
            .rev()
            .find(|(index, var)| {
                state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
            })
            .map(|(index, _)| index as i32);
        let index = state.vars.len() as u32;
        state.var_block.push(PARAM_SCOPE);
        let mut def = VarDef::lexical(name);
        // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
        // the function's, and its bindings are initialised one by one rather than all at
        // once — which is exactly what the dead zone needs.
        def.scope_level = 1;
        def.scope_next = Some(previous.unwrap_or(-2));
        state.vars.push(def);
        index
    }

    /// The slot of a parameter-list binding, if the list has one by that name.
    fn param_binding_slot(&self, name: &str) -> Option<u32> {
        let state = self.cur();
        state
            .vars
            .iter()
            .enumerate()
            .position(|(index, var)| {
                var.name == name
                    && var.is_lexical
                    && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
            })
            .map(|index| index as u32)
    }

    /// Every parameter-list binding, in declaration order.
    fn param_binding_names(&self) -> Vec<String> {
        let state = self.cur();
        state
            .vars
            .iter()
            .enumerate()
            .filter(|(index, var)| {
                var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
            })
            .map(|(_, var)| var.name.clone())
            .collect()
    }

    /// The body's own binding for `name`, as opposed to the parameter's copy of it.
    fn body_var_slot(&self, name: &str) -> Option<u32> {
        let state = self.cur();
        state
            .vars
            .iter()
            .enumerate()
            .find(|(index, var)| {
                var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
            })
            .map(|(index, _)| index as u32)
    }

    /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
    /// one.
    ///
    /// With parameter expressions the reference creates two: an unmapped one in the
    /// argument scope, for the defaults and anything they close over, and the body's own.
    /// They are separate bindings, which is what makes
    /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
    /// report 1 from `p` and 2 from the body.
    fn provide_param_arguments(&mut self) {
        if !self.cur().has_parameter_expressions {
            return;
        }
        let mentioned = self.cur().needs_param_arguments
            || self
                .cur()
                .insns
                .iter()
                .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
        if !mentioned {
            return;
        }
        let slot = self.declare_param_var("arguments");
        let magic = if self.cur().strict { 0 } else { 1 };
        self.prepend_initialiser_to(
            slot,
            Insn::Fixed {
                op: Opcode::SpecialObject,
                operands: vec![Op::Int(magic)],
            },
        );
    }

    /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
    fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
        let current = self.stack.len() - 1;
        let init = [
            producer,
            Insn::Fixed {
                op: Opcode::PutLoc,
                operands: vec![Op::Slot(Slot::Loc(slot))],
            },
        ];
        let inserted = init.len();
        for (index, instruction) in init.into_iter().enumerate() {
            self.stack[current].insns.insert(index, instruction);
        }
        for placed in self.stack[current].labels.iter_mut().flatten() {
            *placed += inserted;
        }
        self.state().label_since_insn = false;
    }

    /// Give the function an `arguments` binding if its body mentions one.
    ///
    /// The check runs on the *instruction* stream rather than the AST: by this point
    /// every reference has become an `Insn::Var`, so scanning is exact and needs no
    /// AST walker. Declaring lazily matters for more than tidiness — always declaring
    /// would renumber every later local slot and stop the bytecode matching the
    /// reference, which only adds the binding when the body uses it.
    ///
    /// `arguments` is a local, initialised at the top of the body by
    /// `special_object`; that is the reference's shape, so the disassembly agrees.
    fn provide_arguments(&mut self) {
        let current = self.stack.len() - 1;
        if self.stack[current].is_script || self.stack[current].is_module {
            // A module has no `arguments` binding; referring to it is a ReferenceError,
            // which is exactly what an unbound name produces.
            return;
        }
        // An arrow has no `arguments` of its own: the binding belongs to the enclosing
        // function, which is why `() => arguments` sees the caller's arguments.
        if self.stack[current].is_arrow {
            if self.mentions("arguments") {
                self.ensure_enclosing_arguments();
            }
            return;
        }
        // Only a *body* mention needs the body's binding: the parameter list has one of
        // its own (see [`Compiler::provide_param_arguments`]).
        let mentioned = self.cur().insns.iter().any(|insn| {
            matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params)
        });
        if !mentioned && !self.cur().needs_arguments_local {
            return;
        }
        // The request may have come only from a parameter-list arrow, in which case the
        // parameter scope's binding already answers for it and the body needs none.
        if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
            return;
        }
        // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`. The mapping itself is
        // not implemented, so the two behave alike for now.
        //
        // With parameter expressions the list and the body are separate environments, so
        // an assignment to a parameter cannot be reflected into `arguments` at all — the
        // arguments object is unmapped whatever the mode, which is why the reference emits
        // `special_object 0` here even in sloppy code.
        let magic = if self.stack[current].strict || self.stack[current].has_parameter_expressions {
            0
        } else {
            1
        };
        self.prepend_binding("arguments", magic);
    }

    /// Whether a *body* instruction refers to `arguments`.
    fn body_mentions_arguments(&self) -> bool {
        self.cur()
            .insns
            .iter()
            .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
    }

    /// Whether the function body's instruction stream refers to `name`.
    fn mentions(&self, name: &str) -> bool {
        let current = self.stack.len() - 1;
        // A binding of the parameter scope does not answer for the body: the body's own
        // `arguments` (or self-name) still has to be provided for it.
        if self.stack[current]
            .vars
            .iter()
            .enumerate()
            .any(|(index, v)| {
                v.name == name
                    && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
            })
        {
            return false;
        }
        self.stack[current]
            .insns
            .iter()
            .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
    }

    /// Bind the name a named function expression uses to refer to itself.
    ///
    /// The value is `special_object 2`, the function currently running, so the binding
    /// is the closure itself and not a copy. It is a local of this function, which is
    /// what keeps `g` out of the enclosing scope.
    /// Give the function a local `this`, for an arrow inside it to capture.
    fn provide_this_local(&mut self) {
        let current = self.stack.len() - 1;
        if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
            return;
        }
        if !self.stack[current]
            .vars
            .iter()
            .any(|var| var.name == "this")
        {
            self.declare_hidden_local("this", VarKind::Normal);
        }
        self.prepend_initialiser(
            "this",
            Insn::Fixed {
                op: Opcode::PushThis,
                operands: vec![],
            },
        );
    }

    /// Give the function a local `<home_object>`, for an arrow or a static block inside it
    /// to read through `super`.
    fn provide_home_object_local(&mut self) {
        let current = self.stack.len() - 1;
        if !self.stack[current].needs_home_object_local {
            return;
        }
        if !self.stack[current]
            .vars
            .iter()
            .any(|var| var.name == HOME_OBJECT)
        {
            self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
        }
        self.prepend_initialiser(
            HOME_OBJECT,
            Insn::Fixed {
                op: Opcode::SpecialObject,
                operands: vec![Op::Int(4)],
            },
        );
    }

    fn provide_self_name(&mut self) {
        let current = self.stack.len() - 1;
        let Some(name) = self.stack[current].self_name.clone() else {
            return;
        };
        if self.stack[current].self_name_initialized {
            return;
        }
        // Either the body refers to the name, or a nested function already forced the
        // binding into existence while being resolved. A direct `eval` can name it
        // without mentioning it, so its presence is a third reason: in strict mode
        // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
        // that only happens if the binding exists.
        let declared = self.stack[current].vars.iter().any(|v| v.name == name);
        if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
            return;
        }
        self.stack[current].self_name_initialized = true;
        self.prepend_binding_with(&name, 2, VarKind::FunctionName);
    }

    /// Insert `special_object magic` plus the store to `name` at the top of the body.
    ///
    /// Prepending shifts every label that has been placed, so they are all moved by
    /// the number of instructions inserted.
    fn prepend_binding(&mut self, name: &str, magic: i32) {
        self.prepend_binding_with(name, magic, VarKind::Normal);
    }

    /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
    fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
        let current = self.stack.len() - 1;
        // A function-expression's own name is immutable in strict mode, which is what
        // makes `f = 1` inside a strict body throw instead of being dropped.
        let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
        self.declare_var(
            name,
            VarDef {
                kind,
                is_const,
                ..VarDef::var(name)
            },
        );
        let init = [
            Insn::Fixed {
                op: Opcode::SpecialObject,
                operands: vec![Op::Int(magic)],
            },
            Insn::Var {
                // An initialisation, not an assignment: sloppy mode drops stores to a
                // function-expression's own name, and the prologue is what puts the
                // value there in the first place.
                action: if kind == VarKind::FunctionName {
                    VarAction::PutInit
                } else {
                    VarAction::Put
                },
                name: name.to_string(),
                block: 0,
                in_params: false,
            },
        ];
        let inserted = init.len();
        for (index, instruction) in init.into_iter().enumerate() {
            self.stack[current].insns.insert(index, instruction);
        }
        for placed in self.stack[current].labels.iter_mut().flatten() {
            *placed += inserted;
        }
        // A store sits at the insertion point now, so the `put`/`get` fold must not
        // reach across it.
        self.stack[current].label_since_insn = true;
    }

    /// Record a top-level script declaration as a global.
    ///
    /// A script's top-level `var`/`let`/`function` create properties of the
    /// global object, not slots in the script's frame, so they show up as closure
    /// variables instead.
    fn declare_global(&mut self, name: &str, def: &VarDef) {
        let state = self.state();
        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
            // The name was already referenced, from a function compiled before this
            // declaration was reached — `function a(){ b() } function b(){}` resolves
            // `b` while `b` is still unknown, and that guess has to be corrected here.
            // Leaving it as a plain global meant the declaration was never registered,
            // so the binding did not exist at run time and `a()` threw
            // `b is not defined`.
            if matches!(existing.closure_type, ClosureType::Global) {
                existing.closure_type = ClosureType::GlobalDecl;
                existing.is_const = def.is_const;
                existing.is_lexical = def.is_lexical;
            }
            return;
        }
        state.closure_vars.push(ClosureVar {
            name: name.to_string(),
            is_const: def.is_const,
            is_lexical: def.is_lexical,
            closure_type: ClosureType::GlobalDecl,
            var_idx: 0,
        });
    }

    /// Record a module-level declaration as a module variable.
    ///
    /// The binding is a closure variable of the module body, so reads and writes are
    /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
    /// *who fills the cell*: the module record does, before the body runs, and an import
    /// points its cell at the exporting module's, which is what makes bindings live and
    /// cycles work.
    fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
        let state = self.state();
        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
            // The name may have been referenced before this declaration was hoisted,
            // which resolved it as a plain global. Correct that here, the way
            // `declare_global` does.
            if matches!(existing.closure_type, ClosureType::Global) {
                existing.closure_type = ClosureType::ModuleDecl;
                existing.is_const = def.is_const;
                existing.is_lexical = def.is_lexical;
            }
            return 0;
        }
        state.closure_vars.push(ClosureVar {
            name: name.to_string(),
            is_const: def.is_const,
            is_lexical: def.is_lexical,
            closure_type: ClosureType::ModuleDecl,
            var_idx: 0,
        });
        0
    }

    /// Declare a module variable and answer its closure-variable index.
    ///
    /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
    /// module variable is not one. The import table needs the real index instead, because
    /// that is the position the host writes the cell into.
    fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
        self.declare_module(name, def);
        self.cur()
            .closure_vars
            .iter()
            .position(|c| c.name == name)
            .map(|index| index as u32)
            .unwrap_or(0)
    }

    /// Declare one imported binding as a module variable.
    ///
    /// Returns the closure-variable index, which is what the import table records: the
    /// host writes the exporter's cell into that slot before the body runs.
    fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
        let state = self.state();
        if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
            // Keep the slot, fix the kind: the name may already have been referenced.
            state.closure_vars[index].closure_type = ClosureType::ModuleImport;
            state.closure_vars[index].is_const = is_const;
            return index as u32;
        }
        state.closure_vars.push(ClosureVar {
            name: name.to_string(),
            // An imported binding cannot be assigned: `x = 1` on an import is a
            // `TypeError` at run time, which the const flag is what produces.
            is_const: true,
            // Lexical, so reads go through `get_var_ref_check`: before linking has filled
            // the cell an import is in its dead zone, and reading it there must say so
            // rather than answer `undefined`.
            is_lexical: true,
            closure_type: ClosureType::ModuleImport,
            var_idx: 0,
        });
        state.closure_vars.len() as u32 - 1
    }

    /// Emit the code an `export` needs.
    ///
    /// Only `export default <expr>` has any: everything else is a table entry whose
    /// binding is declared elsewhere. The expression is stored into the hidden
    /// `*default*` variable rather than returned, because the module body has no value
    /// to speak of.
    fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
        match &decl.kind {
            ExportKind::Declaration(stmt) => self.stmt(stmt),
            ExportKind::Default(expr) => {
                // A named default function/class is already a module binding; the export
                // points at it and there is nothing to evaluate.
                if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some())
                    || matches!(&expr.kind, ExprKind::Class(class) if class.name.is_some())
                {
                    return Ok(());
                }
                self.expr(expr)?;
                let index = self.declare_export_default();
                self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
                Ok(())
            }
            ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
        }
    }

    /// A module name as the string it denotes.
    fn module_name_text(name: &ModuleName) -> &str {
        match name {
            ModuleName::Ident(ident) => &ident.name,
            ModuleName::Str(text) => text,
        }
    }

    /// Bind `import`'s local names and record where each one comes from.
    ///
    /// Nothing is emitted: an import is not an instruction, it is a promise that the
    /// binding's cell will be filled before the body runs. The cell lands in the module's
    /// environment at a fixed index, and the host fills it from the exporter's cell —
    /// which is why a cyclic import can bind before the other module has evaluated.
    fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
        let request = self.module_request(&decl.source, &decl.attributes);
        for specifier in &decl.specifiers {
            let (local, name, is_star) = match specifier {
                ImportSpecifier::Default(ident) => {
                    (ident.name.clone(), "default".to_string(), false)
                }
                ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
                ImportSpecifier::Named { imported, local } => (
                    local.name.clone(),
                    Self::module_name_text(imported).to_string(),
                    false,
                ),
            };
            // `import * as ns` is *not* a live binding of another module's variable —
            // it is a value of its own, which is why the reference declares it like a
            // module variable and the host stores the namespace object in that cell.
            let var_idx = if is_star {
                // `const`: a namespace object is a value, and the binding is immutable.
                self.declare_module_var(&local, &VarDef::constant(local.clone()))
            } else {
                self.declare_import(&local, true)
            };
            self.module_meta().imports.push(ImportEntry {
                module: request,
                name,
                var_idx,
                is_star,
            });
        }
        Ok(())
    }

    /// Record what an `export` offers, declaring the binding it exports.
    ///
    /// `export var x = 1` is a declaration like any other; only the table entry is extra.
    fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
        match &decl.kind {
            ExportKind::Declaration(stmt) => {
                // The inner declaration keeps its own hoisting, then every name it binds
                // becomes an export of the same name.
                self.hoist_stmt(stmt)?;
                let mut names = Vec::new();
                Self::declared_names(stmt, &mut names);
                for name in names {
                    let var_idx = self.module_binding_index(&name);
                    self.exports_local(&name, var_idx);
                }
            }
            ExportKind::Default(expr) => {
                // The reference puts a default export in a hidden `*default*` variable,
                // so `export default function f(){}` can export a *value* while `f` stays
                // a binding of the module.
                if let ExprKind::Function(func) = &expr.kind
                    && let Some(name) = &func.name
                {
                    let text = name.name.clone();
                    self.hoist_stmt(&Stmt {
                        kind: StmtKind::FuncDecl(func.clone()),
                        span: expr.span,
                    })?;
                    let var_idx = self.module_binding_index(&text);
                    self.module_meta().exports.push(ExportEntry::Local {
                        export_name: "default".to_string(),
                        var_idx,
                    });
                    return Ok(());
                }
                if let ExprKind::Class(class) = &expr.kind
                    && let Some(name) = &class.name
                {
                    let text = name.name.clone();
                    self.hoist_stmt(&Stmt {
                        kind: StmtKind::ClassDecl(class.clone()),
                        span: expr.span,
                    })?;
                    let var_idx = self.module_binding_index(&text);
                    let _ = var_idx;
                }
                let var_idx = self.declare_export_default();
                self.module_meta().exports.push(ExportEntry::Local {
                    export_name: "default".to_string(),
                    var_idx,
                });
            }
            ExportKind::Named {
                specifiers,
                source,
                attributes,
            } => match source {
                Some(source) => {
                    let request = self.module_request(source, attributes);
                    for specifier in specifiers {
                        self.module_meta().exports.push(ExportEntry::Indirect {
                            export_name: Self::module_name_text(&specifier.exported).to_string(),
                            module: request,
                            import_name: Self::module_name_text(&specifier.local).to_string(),
                        });
                    }
                }
                None => {
                    for specifier in specifiers {
                        let local = Self::module_name_text(&specifier.local).to_string();
                        let var_idx = self.module_binding_index(&local);
                        let export_name = Self::module_name_text(&specifier.exported).to_string();
                        self.module_meta().exports.push(ExportEntry::Local {
                            export_name,
                            var_idx,
                        });
                    }
                }
            },
            ExportKind::All {
                source,
                exported,
                attributes,
            } => {
                let request = self.module_request(source, attributes);
                match exported {
                    Some(name) => {
                        self.module_meta().exports.push(ExportEntry::StarAs {
                            export_name: Self::module_name_text(name).to_string(),
                            module: request,
                        });
                    }
                    None => {
                        self.module_meta()
                            .exports
                            .push(ExportEntry::Star { module: request });
                    }
                }
            }
        }
        Ok(())
    }

    /// The names a declaration binds, which is what `export <decl>` exports.
    fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
        match &stmt.kind {
            StmtKind::VarDecl(decl) => {
                for declarator in &decl.declarators {
                    let mut names = Vec::new();
                    declarator.target.bound_names(&mut names);
                    out.extend(names.into_iter().map(|name| name.name));
                }
            }
            StmtKind::FuncDecl(func) => {
                if let Some(name) = &func.name {
                    out.push(name.name.clone());
                }
            }
            StmtKind::ClassDecl(class) => {
                if let Some(name) = &class.name {
                    out.push(name.name.clone());
                }
            }
            _ => {}
        }
    }

    /// The closure-variable index of a module binding, declaring it if the name was
    /// exported without being declared here.
    ///
    /// `export { x }` where `x` is not declared in the module is a link-time
    /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
    fn module_binding_index(&mut self, name: &str) -> u32 {
        if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
            return index as u32;
        }
        self.declare_module_var(name, &VarDef::lexical(name.to_string()))
    }

    fn exports_local(&mut self, export_name: &str, var_idx: u32) {
        self.module_meta().exports.push(ExportEntry::Local {
            export_name: export_name.to_string(),
            var_idx,
        });
    }

    /// The hidden `*default*` binding `export default <expr>` stores into.
    fn declare_export_default(&mut self) -> u32 {
        const DEFAULT: &str = "*default*";
        if let Some(index) = self
            .cur()
            .closure_vars
            .iter()
            .position(|c| c.name == DEFAULT)
        {
            return index as u32;
        }
        self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
    }

    /// The module tables, which only the top-level state has.
    fn module_meta(&mut self) -> &mut ModuleMeta {
        self.state()
            .module
            .as_mut()
            .expect("module tables are only touched while compiling a module")
    }

    /// The index of `specifier`'s request, adding it if it is new.
    ///
    /// Deduplicated on the specifier *and* its attributes: the same file imported once as
    /// JSON and once as text is two modules with two different contents, which is exactly
    /// what `hello_module.js` does.
    fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
        let attributes: Vec<(String, String)> = attributes
            .iter()
            .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
            .collect();
        let meta = self.module_meta();
        if let Some(index) = meta
            .requests
            .iter()
            .position(|request| request.specifier == specifier && request.attributes == attributes)
        {
            return index as u32;
        }
        meta.requests.push(ModuleRequest {
            specifier: specifier.to_string(),
            attributes,
        });
        meta.requests.len() as u32 - 1
    }

    /// Compile a loop body with a `break`/`continue` target pushed for it.
    fn loop_body(
        &mut self,
        body: &Stmt,
        labels: &[String],
        continue_label: Label,
        break_label: Label,
    ) -> Result<(), SyntaxError> {
        self.push_jump_target(JumpTarget {
            names: labels.to_vec(),
            break_label: Some(break_label),
            continue_label: Some(continue_label),
            // A loop leaves nothing of its own on the value stack.
            drop_count: 0,
            finally_label: None,
            is_regular_stmt: false,
            has_iterator: false,
            is_async_iterator: false,
        });
        let result = self.stmt(body);
        self.pop_jump_target();
        result
    }

    fn push_jump_target(&mut self, target: JumpTarget) {
        self.state().jump_targets.push(target);
    }

    fn pop_jump_target(&mut self) {
        self.state().jump_targets.pop();
    }

    fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
        let (label, is_break) = match &stmt.kind {
            StmtKind::Break(label) => (label.as_ref(), true),
            StmtKind::Continue(label) => (label.as_ref(), false),
            _ => unreachable!("control_transfer is only called for break and continue"),
        };

        // Walk outward from the innermost construct. Everything considered before
        // the match is a construct control is leaving, and leaving it has a cost:
        // its stack slots go, and its finalizer runs.
        let targets = self.cur().jump_targets.clone();
        for target in targets.iter().rev() {
            let destination = match (label, is_break) {
                // An unlabelled `break` skips a labelled non-loop statement: `break`
                // may name one, but the bare form only means "leave the loop".
                (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
                (None, false) => target.continue_label,
                (Some(name), true) => target
                    .break_label
                    .filter(|_| target.names.contains(&name.name)),
                (Some(name), false) => target
                    .continue_label
                    .filter(|_| target.names.contains(&name.name)),
            };

            if let Some(destination) = destination {
                self.emit_jump(Opcode::Goto, destination, &[]);
                return Ok(());
            }

            // Closing the iterator consumes the three slots the loop keeps on the
            // stack (iterator, next method, catch offset), so those are not dropped
            // again below.
            let mut remaining = target.drop_count;
            if target.has_iterator {
                self.emit_iterator_close(target.is_async_iterator, false);
                remaining = remaining.saturating_sub(3);
            }
            for _ in 0..remaining {
                self.emit(Opcode::Drop, &[]);
            }
            if let Some(finally) = target.finally_label {
                // The finalizer runs as a subroutine and is handed a dummy return
                // value, which is dropped afterwards to keep the stack the depth it
                // had before.
                self.emit(Opcode::Undefined, &[]);
                self.emit_jump(Opcode::Gosub, finally, &[]);
                self.emit(Opcode::Drop, &[]);
            }
        }

        // The parser rejects a break/continue with no target, so reaching here
        // means the compiler's own bookkeeping is wrong.
        Err(SyntaxError::new(
            if is_break {
                "break has no enclosing loop or switch"
            } else {
                "continue has no enclosing loop"
            },
            stmt.span,
        ))
    }

    /// Compile a labelled statement.
    ///
    /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
    /// that loop's targets, so the chain is collected and handed to the loop. A
    /// label on a non-loop statement only provides a `break` target, because
    /// `continue` may not target it.
    fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
        let mut names = vec![label.name.clone()];
        let mut inner = body;
        while let StmtKind::Labeled {
            label: next,
            body: deeper,
        } = &inner.kind
        {
            names.push(next.name.clone());
            inner = deeper;
        }
        if Self::is_loop(inner) {
            return self.stmt_labelled(inner, &names);
        }
        let end = self.new_label();
        self.push_jump_target(JumpTarget {
            names,
            break_label: Some(end),
            continue_label: None,
            drop_count: 0,
            finally_label: None,
            is_regular_stmt: true,
            has_iterator: false,
            is_async_iterator: false,
        });
        let result = self.stmt(inner);
        self.pop_jump_target();
        result?;
        self.place_label(end);
        let _ = stmt;
        Ok(())
    }

    /// Whether a statement is a loop, i.e. a valid target for `continue`.
    fn is_loop(stmt: &Stmt) -> bool {
        matches!(
            stmt.kind,
            StmtKind::While { .. }
                | StmtKind::DoWhile { .. }
                | StmtKind::For { .. }
                | StmtKind::ForIn { .. }
                | StmtKind::ForOf { .. }
        )
    }

    /// Compile `switch`.
    ///
    /// The discriminant is evaluated once and stays on the value stack while the
    /// clauses compare against copies of it, so it is dropped at the end — which is
    /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
    /// clause's body jumps over the *next* clause's tests straight into its body.
    ///
    /// The tests form a chain: each `case` run compares and, on a miss, hands over to
    /// the next run's tests. Only the last run's miss reaches the `default` body, or
    /// the end of the switch when there is no `default`. That failure path can point
    /// backwards (`default` written first), so the runs and their labels are worked
    /// out before any code is emitted.
    fn switch(
        &mut self,
        discriminant: &Expr,
        cases: &[SwitchCase],
        stmt: &Stmt,
    ) -> Result<(), SyntaxError> {
        self.reset_value();
        // The discriminant is evaluated outside the switch's block scope, before
        // any `case` clause exists.
        self.expr(discriminant)?;

        let switch_key = stmt.span.start.offset as u64;
        let switch_parent = self.cur().current_block;
        self.push_block(switch_key, switch_parent);
        self.emit_scope_enter(switch_key);

        let break_label = self.new_label();
        self.push_jump_target(JumpTarget {
            names: Vec::new(),
            break_label: Some(break_label),
            // `switch` is a valid `break` target but not a `continue` target.
            continue_label: None,
            // The discriminant stays on the value stack for the whole statement, so
            // a `break` aimed further out has to discard it.
            drop_count: 1,
            finally_label: None,
            is_regular_stmt: false,
            has_iterator: false,
            is_async_iterator: false,
        });

        // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
        // its label to the clause after it, so both tests reach the same body.
        let mut runs: Vec<(usize, usize)> = Vec::new();
        let mut scan = 0;
        while scan < cases.len() {
            if cases[scan].test.is_some() {
                let mut last = scan;
                while last + 1 < cases.len()
                    && cases[last].test.is_some()
                    && cases[last].body.is_empty()
                    && cases[last + 1].test.is_some()
                {
                    last += 1;
                }
                runs.push((scan, last));
                scan = last + 1;
            } else {
                scan += 1;
            }
        }

        let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
        let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
        let default_at = cases.iter().position(|case| case.test.is_none());
        // Where the last run sends control when nothing matched.
        let miss_target = match default_at {
            Some(index) => body_labels[index],
            None => break_label,
        };

        // When `default` comes first, control has to jump over it to reach the
        // tests. It only needs to when some clause actually has a test; otherwise
        // the default body is the entry point.
        let mut entry = None;
        if default_at == Some(0) && !runs.is_empty() {
            self.emit_jump(Opcode::Goto, run_labels[0], &[]);
            entry = Some(run_labels[0]);
        }

        let mut index = 0;
        let mut run = 0;
        let result = (|| -> Result<(), SyntaxError> {
            while index < cases.len() {
                if cases[index].test.is_some() {
                    let (first, last) = runs[run];
                    // Reaching these tests from the preceding body is a
                    // fallthrough, which continues inside the body and skips them.
                    if index > 0 {
                        self.emit_jump(Opcode::Goto, body_labels[index], &[]);
                    }
                    if let Some(label) = entry.take() {
                        self.place_label(label);
                    }
                    self.place_label(run_labels[run]);

                    for (offset, case) in cases[first..=last].iter().enumerate() {
                        let test = case.test.as_ref().unwrap();
                        self.emit(Opcode::Dup, &[]);
                        self.expr(test)?;
                        self.emit(Opcode::StrictEq, &[]);
                        if first + offset < last {
                            self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
                        } else {
                            // Hand over to the next run's tests, or give up.
                            let next = match runs.get(run + 1) {
                                Some(_) => run_labels[run + 1],
                                None => miss_target,
                            };
                            self.emit_jump(Opcode::IfFalse, next, &[]);
                        }
                    }

                    self.place_label(body_labels[index]);
                    for case in &cases[first..=last] {
                        self.stmts(&case.body)?;
                    }
                    index = last + 1;
                    run += 1;
                } else {
                    // `default`: control arrives here either by falling through or
                    // because every test missed.
                    self.place_label(body_labels[index]);
                    self.stmts(&cases[index].body)?;
                    index += 1;
                }
            }
            Ok(())
        })();

        if result.is_ok() {
            self.place_label(break_label);
            // Discard the discriminant now that no test needs it.
            self.emit(Opcode::Drop, &[]);
        }

        self.pop_jump_target();
        self.emit_scope_leave(switch_key);
        self.state().current_block = switch_parent;
        result
    }

    /// Compile `try`/`catch`/`finally`.
    ///
    /// The shape is an exception table built out of `catch` instructions, each of
    /// which records where control goes if the instructions that follow raise:
    ///
    /// ```text
    /// catch HANDLER            <- if the guarded block throws, jump to HANDLER
    ///   <guarded block>
    ///   drop                   <- discard the catch offset
    ///   undefined; gosub FINALLY; drop
    ///   goto END
    /// HANDLER:
    ///   <bind the catch parameter>
    ///   catch CATCH2           <- if the handler itself throws, go to CATCH2
    ///   <handler body>
    ///   drop; undefined; gosub FINALLY; drop; goto END
    /// CATCH2:
    ///   gosub FINALLY; throw   <- run the finalizer, then let the error out
    /// FINALLY:
    ///   <finalizer>
    ///   ret                    <- return to the `gosub`
    /// END:
    /// ```
    ///
    /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
    /// of the finalizer serves the normal path, the handler path and the
    /// propagating-exception path.
    ///
    /// The `undefined` before each `gosub` is a dummy return value: the finalizer
    /// runs with `ret_value` on the stack, and the normal path has no value to
    /// keep, so it pushes one to keep the stack depth identical on every path.
    fn try_stmt(
        &mut self,
        stmt: &Stmt,
        block: &[Stmt],
        handler: &Option<CatchClause>,
        finalizer: Option<&[Stmt]>,
    ) -> Result<(), SyntaxError> {
        self.reset_value();

        let catch_label = self.new_label();
        let catch2_label = self.new_label();
        let finally_label = self.new_label();
        let end_label = self.new_label();

        self.emit_jump(Opcode::Catch, catch_label, &[]);

        // The guarded block. `break` may not target it, so its entry exists purely
        // to unwind: a jump out has to discard the catch offset and run the
        // finalizer.
        self.push_jump_target(JumpTarget {
            names: Vec::new(),
            break_label: None,
            continue_label: None,
            drop_count: 1,
            finally_label: Some(finally_label),
            is_regular_stmt: false,
            has_iterator: false,
            is_async_iterator: false,
        });

        let block_key = Self::try_block_key(stmt, TryPart::Block);
        let block_parent = self.cur().current_block;
        self.push_block(block_key, block_parent);
        self.emit_scope_enter(block_key);
        self.stmts(block)?;
        self.emit_scope_leave(block_key);
        self.state().current_block = block_parent;
        // A guarded block that ends in a `return`/`throw` never reaches the
        // epilogue, so the reference does not emit one.
        self.pop_jump_target();
        let block_live = !block.last().is_some_and(Self::terminates);

        if block_live {
            self.emit(Opcode::Drop, &[]);
            self.emit(Opcode::Undefined, &[]);
            self.emit_jump(Opcode::Gosub, finally_label, &[]);
            self.emit(Opcode::Drop, &[]);
            self.emit_jump(Opcode::Goto, end_label, &[]);
        }

        if let Some(handler) = handler {
            self.place_label(catch_label);
            // The thrown value is on top of the stack: bind it, or discard it for
            // `catch { }`.
            match &handler.param {
                Some(pattern) => {
                    // The stores resolve the names, so they have to run inside the
                    // parameter's own scope; otherwise a same-named `catch` further out
                    // could win. A `catch` binding is never in the dead zone, so the store
                    // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
                    let param_key = Self::try_block_key(stmt, TryPart::Param);
                    let param_parent = self.cur().current_block;
                    self.push_block(param_key, param_parent);
                    self.destructure(pattern, Some(VarDeclKind::Var))?;
                    self.state().current_block = param_parent;
                }
                None => self.emit(Opcode::Drop, &[]),
            }
            self.emit_jump(Opcode::Catch, catch2_label, &[]);

            self.push_jump_target(JumpTarget {
                names: Vec::new(),
                break_label: None,
                continue_label: None,
                drop_count: 1,
                finally_label: Some(finally_label),
                is_regular_stmt: false,
                has_iterator: false,
                is_async_iterator: false,
            });
            let catch_key = Self::try_block_key(stmt, TryPart::Catch);
            let catch_parent = self.cur().current_block;
            self.push_block(catch_key, catch_parent);
            self.emit_scope_enter(catch_key);
            self.stmts(&handler.body)?;
            self.emit_scope_leave(catch_key);
            self.state().current_block = catch_parent;
            self.pop_jump_target();
            let handler_live = !handler.body.last().is_some_and(Self::terminates);

            if handler_live {
                self.emit(Opcode::Drop, &[]);
                self.emit(Opcode::Undefined, &[]);
                self.emit_jump(Opcode::Gosub, finally_label, &[]);
                self.emit(Opcode::Drop, &[]);
                self.emit_jump(Opcode::Goto, end_label, &[]);
            }

            // An error raised inside the handler still has to run the finalizer.
            self.place_label(catch2_label);
            self.emit_jump(Opcode::Gosub, finally_label, &[]);
            self.emit(Opcode::Throw, &[]);
        } else {
            // `try`/`finally` with no handler: the finalizer runs, then the error
            // keeps propagating.
            self.place_label(catch_label);
            self.emit_jump(Opcode::Gosub, finally_label, &[]);
            self.emit(Opcode::Throw, &[]);
        }

        self.place_label(finally_label);
        // Inside the finalizer, leaving has a different cost: the return value and
        // the `gosub` return address are both on the stack, and neither finalizer nor
        // any outer one may run before the block has finished.
        self.push_jump_target(JumpTarget {
            names: Vec::new(),
            break_label: None,
            continue_label: None,
            drop_count: 2,
            finally_label: None,
            is_regular_stmt: false,
            has_iterator: false,
            is_async_iterator: false,
        });
        if let Some(finalizer) = finalizer {
            let finally_key = Self::try_block_key(stmt, TryPart::Finally);
            let finally_parent = self.cur().current_block;
            self.push_block(finally_key, finally_parent);
            self.emit_scope_enter(finally_key);
            self.stmts(finalizer)?;
            self.emit_scope_leave(finally_key);
            self.state().current_block = finally_parent;
        }
        self.pop_jump_target();
        self.emit(Opcode::Ret, &[]);
        self.place_label(end_label);
        Ok(())
    }

    /// Compile `for`/`in` and `for`/`of`.
    ///
    /// Both keep an enumeration record on the value stack for the whole loop, which
    /// is what makes leaving early expensive: the record has to be dropped, or the
    /// iterator closed. The layout is
    ///
    /// ```text
    ///   <iterated expression>
    ///   for_in_start | for_of_start      <- pushes the record
    ///   goto TEST
    /// NEXT:
    ///   <bind the loop variable>
    ///   <body>
    /// TEST:
    ///   for_in_next | for_of_next 0
    ///   if_false NEXT                    <- not finished: next iteration
    ///   drop                             <- finished: discard the leftover value
    /// BREAK:
    ///   drop | iterator_close            <- the one cleanup `break` also uses
    /// ```
    ///
    /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
    /// normal exit share one copy — which is why `break` inside the loop emits nothing
    /// of its own, and only a jump that passes *through* the loop pays for its record.
    fn for_in_of(
        &mut self,
        stmt: &Stmt,
        left: &ForHead,
        right: &Expr,
        body: &Stmt,
        kind: ForLoopKind,
        labels: &[String],
    ) -> Result<(), SyntaxError> {
        self.reset_value();

        let loop_key = stmt.span.start.offset as u64;
        let loop_parent = self.cur().current_block;
        self.push_block(loop_key, loop_parent);
        self.emit_scope_enter(loop_key);

        // The iterated expression is evaluated inside the loop's scope, after the
        // bindings exist in the temporal dead zone.
        self.expr(right)?;

        let next = self.new_label();
        let test = self.new_label();
        let break_target = self.new_label();

        let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
        match kind {
            ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
            ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
            ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
        }
        self.emit_jump(Opcode::Goto, test, &[]);

        self.push_jump_target(JumpTarget {
            // `outer: for (x of xs) … break outer` needs the name here. Without it the
            // loop had no label to break to, and the compiler reported "break has no
            // enclosing loop" for a loop that was plainly enclosing it.
            names: labels.to_vec(),
            break_label: Some(break_target),
            continue_label: Some(test),
            // Passing through the loop has to dispose of its record. A `for`/`of`
            // record is three slots, and closing the iterator consumes all of them.
            drop_count: if has_iterator { 3 } else { 1 },
            finally_label: None,
            is_regular_stmt: false,
            has_iterator,
            is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
        });

        self.place_label(next);
        self.bind_loop_variable(left)?;
        // The reference marks the body with its own label here. Nothing jumps to it
        // once the loop is laid out, but it is not decoration: a label between the
        // store and the body is why `put_loc v; get_loc v` does *not* fold into
        // `set_loc v` when the body starts by reading the loop variable.
        let body_label = self.new_label();
        self.place_label(body_label);
        // `for (using x of …)` disposes once per iteration, so the body is a disposal
        // region rather than the whole loop: the resource is the element that this
        // iteration produced.
        let using_slot = match left {
            ForHead::VarDecl(decl) if decl.kind.is_using() => {
                decl.declarators
                    .first()
                    .and_then(|declarator| match &declarator.target.kind {
                        PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
                        _ => None,
                    })
            }
            _ => None,
        };
        match using_slot {
            Some(slot) => {
                let live = !Self::terminates(body);
                self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
            }
            None => self.stmt(body)?,
        }

        self.place_label(test);
        match kind {
            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
            ForLoopKind::AwaitOf => {
                // The reference's shape: step, `await` the result, then unpack it.
                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
                self.emit(Opcode::Await, &[]);
                self.state().has_await = true;
                self.emit(Opcode::IteratorGetValueDone, &[]);
            }
        }
        self.emit_jump(Opcode::IfFalse, next, &[]);
        // The loop is finished; `for_xx_next` left an `undefined` behind.
        self.emit(Opcode::Drop, &[]);

        self.pop_jump_target();
        self.place_label(break_target);
        if has_iterator {
            // A loop that ran to completion finds its iterator slot already cleared (see
            // `iterator_get_value_done`), so this closes only an iterator abandoned by a
            // `break` that jumped here.
            self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
        } else {
            self.emit(Opcode::Drop, &[]);
        }

        self.emit_scope_leave(loop_key);
        self.state().current_block = loop_parent;
        Ok(())
    }

    /// Store the value `for_xx_next` left on the stack into the loop variable.
    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
        // A declaration *initialises* the binding, which is what takes a `let` out of
        // the temporal dead zone, so the store is the unchecked form. Assigning to a
        // binding declared elsewhere is an ordinary write and keeps its check.
        let (pattern, action) = match left {
            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
        };
        match &pattern.kind {
            PatternKind::Ident(name) => {
                // `for (using x of …)` validates and snapshots each iteration's value
                // before the body runs, which is what makes a non-disposable element fail
                // on the iteration that produced it rather than at the end of the loop.
                if let ForHead::VarDecl(decl) = left
                    && decl.kind.is_using()
                {
                    let method_slot = self
                        .using_method_slot(&name.name)
                        .expect("a using binding was declared during hoisting");
                    self.emit(
                        Opcode::UsingCheck,
                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
                    );
                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
                }
                self.emit_var(action, &name.name);
                Ok(())
            }
            // Every other target stores through the same path an assignment pattern
            // uses, which is what makes `for (a[0] in obj)` write each key into the
            // property instead of refusing the loop outright.
            _ => self.destructure(
                pattern,
                match left {
                    ForHead::VarDecl(decl) => Some(decl.kind),
                    ForHead::Assign(_) => None,
                },
            ),
        }
    }

    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
        for declarator in &decl.declarators {
            let Some(init) = &declarator.init else {
                // `var x;` stays `undefined`. A lexical binding is different: it
                // has to be *initialised* to leave the temporal dead zone, so the
                // compiler supplies an explicit `undefined`.
                if decl.kind.is_lexical() {
                    // A lexical binding has to be *initialised* to leave the temporal
                    // dead zone, and a destructuring one is no different — `let {a}`
                    // with no initialiser is a syntax error, but `let [a] = []` still
                    // needs `a` to be initialised from an empty source, which the
                    // pattern does on its own.
                    self.emit(Opcode::Undefined, &[]);
                    self.destructure(&declarator.target, Some(decl.kind))?;
                }
                continue;
            };
            match &declarator.target.kind {
                PatternKind::Ident(name) => {
                    self.expr(init)?;
                    self.set_name_if_anonymous(init, &name.name);
                    if decl.kind.is_using() {
                        // `using_check` validates the value and snapshots its dispose
                        // method: `value -> value, method`. The snapshot is what makes a
                        // later change to `Symbol.dispose` irrelevant, and validating here
                        // is what keeps the body from running at all when the value is not
                        // disposable.
                        let method_slot = self
                            .using_method_slot(&name.name)
                            .expect("a using binding was declared during hoisting");
                        self.emit(
                            Opcode::UsingCheck,
                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
                        );
                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
                        self.emit_var(VarAction::PutInit, &name.name);
                        continue;
                    }
                    // A declaration statement produces no value, so nothing is
                    // duplicated onto the stack.
                    match decl.kind {
                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
                        _ => self.emit_var(VarAction::PutInit, &name.name),
                    }
                }
                _ => {
                    // A destructuring declaration keeps nothing on the stack: the
                    // pattern consumes the initialiser.
                    self.expr(init)?;
                    self.destructure(&declarator.target, Some(decl.kind))?;
                }
            }
        }
        Ok(())
    }

    /// Bind a destructuring pattern from the value on top of the stack.
    ///
    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
    /// *assignment*, where a member expression is a legal target and the store is an
    /// ordinary property write.
    ///
    /// The value is consumed. An assignment expression's own result is the right-hand
    /// side, which the caller keeps separately — the spec does not make the pattern's
    /// last store produce it.
    fn destructure(
        &mut self,
        pattern: &Pattern,
        decl: Option<VarDeclKind>,
    ) -> Result<(), SyntaxError> {
        match &pattern.kind {
            PatternKind::Ident(name) => {
                match decl {
                    Some(VarDeclKind::Var) | None => {
                        self.emit_var(VarAction::Put, &name.name);
                    }
                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
                }
                Ok(())
            }
            PatternKind::Assign { target, default } => {
                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
                // keeps `null`.
                //
                // The shape is the reference's: test for `undefined`, and when the value is
                // present fall **through** to a single store both paths share. The
                // alternatives — branching to the store on each side — need a second store
                // and a jump between them, which is what the dump used to show.
                let has_value = self.new_label();
                self.emit(Opcode::Dup, &[]);
                self.emit(Opcode::IsUndefined, &[]);
                self.emit_jump(Opcode::IfFalse, has_value, &[]);
                self.emit(Opcode::Drop, &[]);
                self.expr(default)?;
                // `var {f = function(){}} = {}` names the function `f`, like a plain
                // `var f = function(){}` does. Both pattern forms do it:
                // `BindingInitialization` names the value for a *binding* target, and since
                // ES2018 `DestructuringAssignmentEvaluation` does the same, so
                // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
                // no name to give, which is why only an identifier qualifies.
                if let PatternKind::Ident(name) = &target.kind {
                    self.set_name_if_anonymous(default, &name.name);
                }
                self.place_label(has_value);
                self.destructure(target, decl)
            }
            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
            PatternKind::Object { properties, rest } => {
                self.destructure_object(properties, rest, decl, pattern)
            }
            PatternKind::Member(member) if decl.is_none() => {
                // An assignment pattern may store into a property. The value is on the
                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
                // put the three in the order `put_array_el`/`put_field` expect.
                self.expr(&member.object)?;
                match &member.property {
                    MemberProp::Ident(name) => {
                        // `value obj` -> `obj value`, the order `put_field` takes.
                        // Nothing needs to be left behind: a pattern element's value is
                        // consumed by its own store.
                        self.emit(Opcode::Swap, &[]);
                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
                    }
                    MemberProp::Computed(index) => {
                        self.expr(index)?;
                        // `value obj key` -> `obj key value`.
                        self.emit(Opcode::Rot3l, &[]);
                        self.emit(Opcode::PutArrayEl, &[]);
                    }
                    MemberProp::Private(name) => {
                        // `value obj` -> `obj value`, and the store half of the assignment is
                        // the same one `obj.#x = value` uses — only without `insert2`,
                        // because a pattern element's value is not wanted back.
                        let binding = format!("#{}", name.name);
                        let (kind, setter) = self.private_use(&binding, member.span)?;
                        self.emit(Opcode::Swap, &[]);
                        self.private_store(&binding, kind, setter.as_deref())?;
                    }
                }
                Ok(())
            }
            PatternKind::Rest(inner) => self.destructure(inner, decl),
            PatternKind::Invalid(expr) => {
                Err(SyntaxError::new("invalid assignment target", expr.span))
            }
            _ => Err(SyntaxError::new(
                "this destructuring target is not supported by the compiler yet",
                pattern.span,
            )),
        }
    }

    /// `[…]` on the left: drain an iterator, binding one target per element.
    fn destructure_array(
        &mut self,
        elements: &[Option<PatternElement>],
        rest: &Option<Box<RestElement>>,
        decl: Option<VarDeclKind>,
    ) -> Result<(), SyntaxError> {
        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
        // pattern accepts any iterable and closes the iterator when the pattern ends
        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
        // first because it is on top.
        self.emit(Opcode::ForOfStart, &[]);
        for element in elements {
            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
            self.emit(Opcode::Drop, &[]);
            match element {
                Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
                Some(PatternElement::Property { span, .. }) => {
                    return Err(SyntaxError::new(
                        "a property pattern is not a valid array element",
                        *span,
                    ));
                }
                // An elision skips the value, which is already on the stack.
                None => self.emit(Opcode::Drop, &[]),
            }
        }
        if let Some(rest) = rest {
            // The remaining values go into a fresh array. The target and its running
            // index stay on the stack above the iterator, which is what the operand of
            // `for_of_next` accounts for: two values sit above the iterator triple.
            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
            self.emit(Opcode::Push0, &[]);
            let top = self.new_label();
            self.place_label(top);
            self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
            let done = self.new_label();
            self.emit_jump(Opcode::IfTrue, done, &[]);
            self.emit(Opcode::DefineArrayEl, &[]);
            self.emit(Opcode::Inc, &[]);
            self.emit_jump(Opcode::Goto, top, &[]);
            self.place_label(done);
            self.emit(Opcode::Drop, &[]);
            self.emit(Opcode::Drop, &[]);
            self.destructure_rest(rest, decl)?;
        }
        self.emit(Opcode::IteratorClose, &[]);
        Ok(())
    }

    /// `{…}` on the left: read properties off one boxed source object.
    fn destructure_object(
        &mut self,
        properties: &[Option<PatternElement>],
        rest: &Option<Box<RestElement>>,
        decl: Option<VarDeclKind>,
        pattern: &Pattern,
    ) -> Result<(), SyntaxError> {
        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
        // aside for the rest element below.
        self.emit(Opcode::ToObject, &[]);
        let mut taken: Vec<String> = Vec::new();
        // Whether any key was computed, which a rest element cannot exclude.
        let mut computed = false;
        for property in properties {
            let Some(PatternElement::Property {
                key, value, span, ..
            }) = property
            else {
                return Err(SyntaxError::new(
                    "a bare pattern is not a valid object property",
                    properties
                        .iter()
                        .flatten()
                        .map(|element| match element {
                            PatternElement::Pattern(pattern) => pattern.span,
                            PatternElement::Property { span, .. } => *span,
                        })
                        .next()
                        .unwrap_or(pattern.span),
                ));
            };
            // Every read needs the source twice: to read from, and to keep for the next
            // property. `get_field2` is that duplicate-and-read in one instruction, but it
            // leaves the copy *under* the value, so it is only usable when whatever
            // consumes the value tolerates that. See [`reads_with_get_field2`].
            let nested = reads_with_get_field2(decl, value);
            if !nested {
                self.emit(Opcode::Dup, &[]);
            }
            match key {
                PropName::Literal(literal) => {
                    let name = self.property_key_text(literal, *span)?;
                    taken.push(name.clone());
                    self.emit(
                        if nested {
                            Opcode::GetField2
                        } else {
                            Opcode::GetField
                        },
                        &[Op::Atom(Atom::from_text(&name))],
                    );
                }
                PropName::Computed(index) => {
                    // A computed key has no name to exclude ahead of time, so a rest
                    // element that has to skip it is refused below rather than silently
                    // copying the property into the rest object.
                    computed = true;
                    self.expr(index)?;
                    self.emit(Opcode::GetArrayEl, &[]);
                }
                PropName::Private(_) => {
                    return Err(SyntaxError::new(
                        "private fields are not supported by the compiler yet",
                        value.span,
                    ));
                }
            }
            self.destructure(value, decl)?;
        }
        match rest {
            Some(rest) => {
                if computed {
                    return Err(SyntaxError::new(
                        "a computed key with a rest element is not supported by the compiler yet",
                        Self::rest_span(rest),
                    ));
                }
                // `target src exclude`: the exclusion list is an array of the keys the
                // literal part already took, so the rest object gets only the others.
                self.emit(Opcode::Object, &[]);
                self.emit(Opcode::Swap, &[]);
                for name in &taken {
                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
                }
                self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
                self.emit(Opcode::Drop, &[]);
                self.emit(Opcode::Drop, &[]);
                self.destructure_rest(rest, decl)?;
            }
            // The source was only kept for a rest element.
            None => self.emit(Opcode::Drop, &[]),
        }
        Ok(())
    }

    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
    fn destructure_rest(
        &mut self,
        rest: &RestElement,
        decl: Option<VarDeclKind>,
    ) -> Result<(), SyntaxError> {
        match rest {
            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
            // `[...a.b] = c` stores into a property.
            RestElement::Member(member) => {
                let pattern = Pattern {
                    kind: PatternKind::Member(member.clone()),
                    span: member.span,
                };
                self.destructure(&pattern, decl)
            }
        }
    }

    /// The source range of a rest element, for error messages.
    fn rest_span(rest: &RestElement) -> Span {
        match rest {
            RestElement::Pattern(pattern) => pattern.span,
            RestElement::Member(member) => member.span,
        }
    }

    /// Compile a function declaration and queue it for instantiation at scope
    /// entry.
    ///
    /// A declaration is visible before the statement that declares it, so the
    /// code that creates the function object belongs at the top of the enclosing
    /// scope, not at the declaration.
    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
        let name = func.name.as_ref().expect("a declaration has a name");
        let function = self.compile_function(func)?;
        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
        let target = self.hoist_target(&name.name);
        let block = self.cur().current_block;
        self.state().hoisted.push((block, target, pool_index));
        Ok(())
    }

    /// Where a name lives, for a hoisted declaration.
    fn hoist_target(&self, name: &str) -> HoistTarget {
        let state = self.cur();
        if let Some(index) = state.args.iter().position(|a| a.name == name) {
            return HoistTarget::Arg(index as u32);
        }
        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
            return HoistTarget::Loc(index as u32);
        }
        // A global function declaration is not a slot at all.
        HoistTarget::Global(name.to_string())
    }

    // -- expressions -------------------------------------------------------

    /// Compile one expression, recording where its instructions sit.
    ///
    /// The position is the node's operator when it has one and its first token
    /// otherwise, and it is restored on the way out so a parent's own instructions —
    /// which are emitted *after* its children — are blamed on the parent. Without the
    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
        let saved = self.cur().cur_pos;
        // Only the node kinds the reference calls `emit_source_pos` for record a position:
        // the operator a node exists for, and a variable *read*, which the reference
        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
        // start, a parenthesised group, an anonymous function expression — leaves the
        // previous position in place, because a table entry the reference never writes is
        // one we must not write either: the instruction that inherits a position (the
        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
        // report a more recent token than the reference does.
        let pos = expr.op_pos.or(match &expr.kind {
            ExprKind::Ident(ident) => Some(ident.span.start),
            _ => None,
        });
        match pos {
            Some(pos) => self.state().cur_pos = Some(pos),
            // A node the reference records nothing for: its own instructions stay
            // unpositioned, so they inherit whatever was written last — which is what an
            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
            // enclosing position instead would blame them on a token the reference has not
            // reached yet: a spread's `iterator_open` reports the expression it follows, and
            // a template's `to_propkey` the interpolation.
            None => self.state().cur_pos = None,
        }
        // Note a direct `eval` call before compiling it, because the *whole* function
        // is affected: an eval can name any binding the function declares, so every one
        // of them has to live in a cell for a closure it creates to capture it.
        if Self::is_direct_eval(expr) {
            // Every enclosing function is affected too: the eval sees the whole scope
            // chain, and a closure it creates can capture a binding of any of them.
            // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
            // cell, because the closure the eval builds outlives the loop iteration.
            for state in &mut self.stack {
                state.has_direct_eval = true;
            }
            let block = self.cur().current_block;
            let in_params = self.cur().in_params;
            self.state()
                .pending_eval_sites
                .push((expr.span, block, in_params));
        }
        let result = self.expr_inner(expr);
        self.state().cur_pos = saved;
        result
    }

    /// Record which bindings are in scope at a direct `eval` call.
    ///
    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
    /// resolves names from a string at run time, so the only chance to pin down *which*
    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
    /// its block is the current block, an enclosing one, or the function scope.
    fn materialize_eval_sites(&mut self) {
        let pending = std::mem::take(&mut self.state().pending_eval_sites);
        for (span, site_block, in_params) in pending {
            self.resolve_eval_site(span, site_block, in_params);
        }
    }

    /// Resolve the bindings visible at one `eval` call.
    fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
        /// How near a binding is: function distance first, then block depth, then the
        /// later declaration (which shadows the earlier one in the same block).
        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);

        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
        // walked, innermost function first: a direct `eval` sees every enclosing
        // function's bindings, and none of them can be resolved at run time because the
        // runtime only has names to go on.
        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
        let deepest = self.stack.len() - 1;
        for (level, state) in self.stack.iter().enumerate().rev() {
            let owner = (deepest - level) as u32;
            // The innermost function's block is the one the call sat in, which is not
            // the block the compiler is in now; the enclosing functions are still at
            // the point where this one was created.
            let here = if level == deepest {
                site_block
            } else {
                state.current_block
            };
            // The chain of live blocks, innermost first, with a depth for each. The walk
            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
            // block can start at source offset zero.
            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
            let mut block = here;
            while let Some(parent) = state
                .blocks
                .iter()
                .find(|candidate| candidate.key == block)
                .map(|candidate| candidate.parent)
                .filter(|parent| *parent != NO_PARENT)
                .filter(|parent| parent != &block)
            {
                live.push((parent, live.len()));
                block = parent;
            }
            let depth_of = |key: u64| {
                live.iter()
                    .find(|(candidate, _)| *candidate == key)
                    .map(|(_, depth)| *depth)
                    // The function scope is the outermost depth there is. A binding of a
                    // block this site is not inside lands here too, which pushes it
                    // behind every live one — the right answer: it is out of scope.
                    .unwrap_or(live.len())
            };
            for (index, arg) in state.args.iter().enumerate() {
                bindings.push((
                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
                    EvalVisible {
                        name: arg.name.clone(),
                        is_arg: true,
                        index: index as u32,
                        owner,
                    },
                ));
            }
            // A parameter list cannot see the body, so a body `var` is not a binding the
            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
            // not let that eval write the body's `c`.
            let hides_body = if level == deepest {
                site_in_params
            } else {
                state.created_in_params
            };
            for (index, var) in state.vars.iter().enumerate() {
                let block = state
                    .var_block
                    .get(index)
                    .copied()
                    .unwrap_or(FUNCTION_SCOPE);
                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
                    continue;
                }
                bindings.push((
                    (
                        owner as usize,
                        depth_of(block),
                        std::cmp::Reverse(index as u32),
                    ),
                    EvalVisible {
                        name: var.name.clone(),
                        is_arg: false,
                        index: index as u32,
                        owner,
                    },
                ));
            }
        }
        // Innermost function first, then innermost block, then the later declaration
        // (which shadows the earlier one within a block).
        bindings.sort_by_key(|(priority, _)| *priority);
        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
        self.state().eval_sites.push(EvalSite {
            line: span.start.line,
            column: span.start.column,
            bindings,
        });
    }

    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
    ///
    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
    /// a bare identifier callee counts.
    fn is_direct_eval(expr: &Expr) -> bool {
        matches!(
            &expr.kind,
            ExprKind::Call { callee, .. }
                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
        )
    }

    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
        match &expr.kind {
            ExprKind::Number(value) => self.push_number(*value),
            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
            ExprKind::Null => self.emit(Opcode::Null, &[]),
            ExprKind::String(text) => self.push_string(text),
            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
            ExprKind::This => self.this_expression(),
            ExprKind::NewTarget => self.new_target_expression(),
            ExprKind::Paren(inner) => self.expr(inner)?,
            ExprKind::Binary { op, left, right } => {
                self.expr(left)?;
                self.expr(right)?;
                self.emit(binary_opcode(*op), &[]);
            }
            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
            ExprKind::Unary {
                op: UnaryOp::Minus,
                argument,
            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
                let ExprKind::Number(value) = argument.unparen().kind else {
                    unreachable!("matched above")
                };
                // The reference folds a negative literal only when the negation is
                // exact in the integer range: `-1` becomes `push_minus1` and
                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
                // `-Infinity`, not `Infinity` — and folding a fraction would change
                // which instruction the reference emits.
                let negated = -value;
                // `-2147483648` is deliberately excluded: its magnitude is one past
                // `i32::MAX`, so the reference sends it through the constant pool and
                // negates at run time instead.
                if value > 0.0
                    && negated == negated.trunc()
                    && negated >= -(i32::MAX as f64)
                    && negated < 0.0
                {
                    self.push_number(negated);
                } else {
                    self.push_number(value);
                    self.emit(Opcode::Neg, &[]);
                }
            }
            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
            ExprKind::Conditional { test, cons, alt } => {
                let else_label = self.new_label();
                let end_label = self.new_label();
                self.expr(test)?;
                self.emit_jump(Opcode::IfFalse, else_label, &[]);
                self.expr(cons)?;
                self.emit_jump(Opcode::Goto, end_label, &[]);
                self.place_label(else_label);
                self.expr(alt)?;
                self.place_label(end_label);
            }
            ExprKind::Assign { op, target, value } => self.assign(*op, target, value)?,
            ExprKind::Update {
                op,
                argument,
                prefix,
            } => self.update(*op, argument, *prefix)?,
            ExprKind::Sequence(items) => {
                for (index, item) in items.iter().enumerate() {
                    self.expr(item)?;
                    if index + 1 != items.len() {
                        self.emit(Opcode::Drop, &[]);
                    }
                }
            }
            ExprKind::Call { .. } => self.chain_link_top(expr)?,
            ExprKind::Member { .. } => self.chain_link_top(expr)?,
            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
            ExprKind::Template(template) => self.template_literal(template)?,
            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
            ExprKind::New { callee, arguments } => {
                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
                // The `dup` is not redundant: `call_constructor` takes the
                // constructor twice, once as the target and once as `new.target`,
                // which is what makes `new.target === C` inside the body.
                self.expr(callee)?;
                self.emit(Opcode::Dup, &[]);
                let args = arguments.as_deref().unwrap_or(&[]);
                if Self::has_spread(args) {
                    // `C C array`: the duplicated callee is already both the target
                    // and `new.target`, so no reordering is needed before `apply 1`.
                    self.argument_array(args)?;
                    self.emit(Opcode::Apply, &[Op::Int(1)]);
                    return Ok(());
                }
                for argument in args {
                    self.expr(argument)?;
                }
                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
            }
            ExprKind::Class(class) => self.class_definition(class, true)?,
            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
            ExprKind::Yield { argument, delegate } => {
                self.yield_expression(argument.as_deref(), *delegate)?
            }
            ExprKind::Await(argument) => self.await_expression(argument)?,
            ExprKind::RegExp { pattern, flags } => {
                // A literal is compiled *here*, at parse time, not when the line runs. The
                // spec is explicit that an invalid pattern is an early error (§12.9.4:
                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
                // also validates `\p{…}` names: 163 conformance cases are patterns that have
                // to be rejected before any code runs.
                //
                // This is the whole reason the engine lives in its own crate rather than
                // inside `quickjs-pure`: the compiler could not depend on the interpreter
                // (`pure` depends on `compile`), but both need this.
                // The lexer already rejected an unknown or repeated flag, so an unparsable
                // flag string here would be a bug in the lexer rather than in the script;
                // fall back to the default flags instead of inventing a second message.
                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
                    SyntaxError::new(
                        format!("invalid regular expression: {}", error.message),
                        expr.span,
                    )
                })?;
                // The tree is thrown away and rebuilt when the literal first runs: keeping it
                // would mean serialising the syntax tree into the function's constant pool,
                // and a literal is created once per evaluation of its expression anyway.
                let _ = parsed;
                // The pattern and its flags travel as two string constants; `regexp` builds
                // the object. A dedicated opcode (rather than a call to the constructor) is
                // what the reference does too, so that a literal never goes through the
                // public `RegExp` function and its string-coercion rules.
                self.push_string(pattern);
                self.push_string(flags);
                self.emit(Opcode::Regexp, &[]);
            }
            ExprKind::Arrow(func) => {
                let function = self.compile_function(func)?;
                let index = self.push_constant(Constant::Function(Box::new(function)));
                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
            }
            ExprKind::Function(func) => {
                let function = self.compile_function_with_name(func, true)?;
                let index = self.push_constant(Constant::Function(Box::new(function)));
                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
            }
            // `import.meta`: the host fills a per-module object at link time.
            ExprKind::ImportMeta => {
                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
            }
            // `import("x")` compiles to a two-slot push followed by one opcode: the
            // specifier, then the options object (`undefined` here, since this compiler
            // does not accept the second argument yet).
            ExprKind::ImportCall(specifier) => {
                self.expr(specifier)?;
                self.emit(Opcode::Undefined, &[]);
                self.emit(Opcode::Import, &[]);
            }
            ExprKind::PrivateIn { name, object } => {
                // `#x in o`: the object, then the binding, then one opcode which decides what
                // to do with the second operand. A field's binding holds a symbol and the
                // answer is an own-property test; a method's holds a function and the answer
                // is a brand check — both live in `private_in`, so the compiler emits the
                // same instruction for either.
                self.expr(object)?;
                self.emit_var(VarAction::Get, &format!("#{}", name.name));
                self.emit(Opcode::PrivateIn, &[]);
            }
            _ => {
                return Err(SyntaxError::new(
                    "this expression form is not supported by the compiler yet",
                    expr.span,
                ));
            }
        }
        Ok(())
    }

    /// Build one array holding the evaluated call arguments, which is how a call
    /// containing a spread is compiled: the reference does the same, building the
    /// list on the stack and handing it to `apply`.
    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
        let elements: Vec<Option<ArrayElement>> = arguments
            .iter()
            .map(|argument| match &argument.unparen().kind {
                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
            })
            .collect();
        self.array_literal(&elements, Span::default())
    }

    /// Whether any argument is a spread, which is what selects the `apply` form.
    fn has_spread(arguments: &[Expr]) -> bool {
        arguments
            .iter()
            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
    }

    /// Compile `a${x}b`.
    ///
    /// A template is a `+` chain built left to right: the leading chunk (or an empty
    /// string when the template starts with a substitution), then for each
    /// substitution its value, `to_propkey` and `add`, then the following chunk when
    /// it is not empty. `to_propkey` is what makes a number or object substitute the
    /// way `ToString` would while leaving the result a string for `add` to
    /// concatenate.
    ///
    /// The chunk is an atom rather than a constant-pool string, because a non-empty
    /// chunk always lands where a value is pushed and `push_atom_value` is the
    /// instruction the reference uses for it; the empty first chunk has its own
    /// zero-byte form.
    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
        let first = template.quasis.first();
        match first.and_then(|quasi| quasi.cooked.clone()) {
            Some(text) if !text.is_empty() => {
                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(&text))]);
            }
            // Either the template begins with a substitution, or the chunk is
            // empty — in both cases the chain needs a string to start from.
            _ => self.emit(Opcode::PushEmptyString, &[]),
        }
        for (index, expression) in template.expressions.iter().enumerate() {
            self.expr(expression)?;
            self.emit(Opcode::ToPropkey, &[]);
            self.emit(Opcode::Add, &[]);
            if let Some(text) = template
                .quasis
                .get(index + 1)
                .and_then(|quasi| quasi.cooked.clone())
                && !text.is_empty()
            {
                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(&text))]);
                self.emit(Opcode::Add, &[]);
            }
        }
        Ok(())
    }

    /// Compile an object literal.
    ///
    /// The object is built in place: `object` pushes it, and each property leaves it
    /// on the stack with one field more, so no temporary is needed and later
    /// properties can overwrite earlier ones.
    ///
    /// The instruction depends on *how* the property was written, not on what kind
    /// of value it holds:
    ///
    /// | source | instruction |
    /// |---|---|
    /// | `{ a: v }` | `define_field a` |
    /// | `{ __proto__: v }` | `set_proto` |
    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
    /// | `{ m() {} }` | `define_method m,4` |
    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
    /// | `{ [k]() {} }` | `define_method_computed 4` |
    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
    ///
    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
    /// key itself, which is why the trailing `drop` is absent there too.
    /// `tag`…``: a call whose first argument is the call site's template object.
    ///
    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
    /// array beside it, so `String.raw` can read the source text back. It is a constant
    /// because its contents never change; the reference builds one per call site and
    /// reuses it, while this builds one per evaluation, which only `tag` code that
    /// compares template objects across calls could tell apart.
    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
        let cooked = quasi
            .quasis
            .iter()
            .map(|chunk| chunk.cooked.clone())
            .collect();
        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
        let index = self.push_constant(Constant::Template { cooked, raw });
        let count = quasi.expressions.len() + 1;
        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
        if let ExprKind::Member {
            object, property, ..
        } = &tag.unparen().kind
        {
            self.expr(object)?;
            match property {
                MemberProp::Ident(name) => {
                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
                }
                MemberProp::Computed(key) => {
                    self.expr(key)?;
                    self.emit(Opcode::GetArrayEl2, &[]);
                }
                MemberProp::Private(name) => {
                    let binding = format!("#{}", name.name);
                    let (kind, _) = self.private_use(&binding, tag.span)?;
                    self.private_callee(&binding, kind)?;
                }
            }
            self.emit(Opcode::PushConst, &[Op::Const(index)]);
            for expression in &quasi.expressions {
                self.expr(expression)?;
            }
            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
            return Ok(());
        }
        self.expr(tag)?;
        self.emit(Opcode::PushConst, &[Op::Const(index)]);
        for expression in &quasi.expressions {
            self.expr(expression)?;
        }
        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
        Ok(())
    }

    fn object_literal(
        &mut self,
        properties: &[ObjectProperty],
        span: Span,
    ) -> Result<(), SyntaxError> {
        self.emit(Opcode::Object, &[]);
        for property in properties {
            match property {
                ObjectProperty::Spread(value) => {
                    // `copy_data_properties` takes the target, the source and an
                    // exclusion list; a literal `null` means "exclude nothing".
                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
                    // exclusion list by stack offset.
                    self.expr(spread_argument(value))?;
                    self.emit(Opcode::Null, &[]);
                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
                    self.emit(Opcode::Drop, &[]);
                    self.emit(Opcode::Drop, &[]);
                }
                ObjectProperty::Property {
                    key,
                    value,
                    kind,
                    shorthand,
                    span: property_span,
                } => match key {
                    PropName::Computed(key_expr) => {
                        self.expr(key_expr)?;
                        match kind {
                            PropertyKind::Value => {
                                self.emit(Opcode::ToPropkey, &[]);
                                self.expr(value)?;
                                self.set_name_if_anonymous_computed(value);
                                self.emit(Opcode::DefineArrayEl, &[]);
                                // `define_array_el` leaves the object and the key;
                                // the key is no longer needed.
                                self.emit(Opcode::Drop, &[]);
                            }
                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
                                self.emit_method_function(value)?;
                                self.emit(
                                    Opcode::DefineMethodComputed,
                                    &[Op::Int(define_method_flags(*kind))],
                                );
                            }
                        }
                    }
                    PropName::Literal(key) => {
                        let name = self.property_key_text(key, *property_span)?;
                        match kind {
                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
                                self.emit_method_function(value)?;
                                self.emit(
                                    Opcode::DefineMethod,
                                    &[
                                        Op::Atom(Atom::from_text(&name)),
                                        Op::Int(define_method_flags(*kind)),
                                    ],
                                );
                            }
                            PropertyKind::Value => {
                                self.expr(value)?;
                                // `{__proto__: x}` sets the prototype instead of
                                // creating a property; the shorthand `{__proto__}`
                                // is an ordinary property and does not.
                                if name == "__proto__" && !shorthand {
                                    self.emit(Opcode::SetProto, &[]);
                                } else {
                                    self.set_name_if_anonymous(value, &name);
                                    self.emit(
                                        Opcode::DefineField,
                                        &[Op::Atom(Atom::from_text(&name))],
                                    );
                                }
                            }
                        }
                    }
                    PropName::Private(_) => {
                        return Err(SyntaxError::new(
                            "private names are not valid in object literals",
                            *property_span,
                        ));
                    }
                },
            }
        }
        let _ = span;
        Ok(())
    }

    /// Emit the function a method/accessor property defines.
    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
        self.expr(value)
    }

    /// The name a literal property key contributes.
    ///
    /// String keys are used as written. A numeric key is converted the way
    /// `ToString` would convert it, because the atom is made from that spelling:
    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<String, SyntaxError> {
        match key {
            PropKey::Str(text) => Ok(text.clone()),
            PropKey::Num(value) => numeric_key_text(*value, span),
        }
    }

    /// Compile an optional chain.
    ///
    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
    /// `undefined`. So the chain is compiled with one end label and every guard
    /// jumps to it. The parser hands us the extent of that spine as an
    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
    /// exactly the scope the label has to cover.
    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
        let end = self.new_label();
        self.chain_link(inner, end)?;
        self.place_label(end);
        Ok(())
    }

    /// A member access or call reached from outside any optional chain.
    ///
    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
    /// still created because [`Self::chain_link`] takes it, and placing it at the
    /// end is a no-op that keeps a single code path.
    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
        let end = self.new_label();
        self.chain_link(expr, end)?;
        self.place_label(end);
        Ok(())
    }

    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
        match &expr.kind {
            ExprKind::Member {
                object,
                property,
                optional,
            } => {
                // `super.x` is not a lookup on a value: it starts at the home object's
                // prototype and keeps `this` as the receiver, so it cannot go through
                // `chain_link` and the ordinary field read.
                if matches!(object.unparen().kind, ExprKind::SuperProp) {
                    self.super_base();
                    match property {
                        MemberProp::Ident(name) => self.emit(
                            Opcode::PushAtomValue,
                            &[Op::Atom(Atom::from_text(&name.name))],
                        ),
                        MemberProp::Computed(index) => self.expr(index)?,
                        MemberProp::Private(_) => {
                            return Err(SyntaxError::new(
                                "private fields are not supported by the compiler yet",
                                expr.span,
                            ));
                        }
                    }
                    self.emit(Opcode::GetSuperValue, &[]);
                    return Ok(());
                }
                self.chain_link(object, end)?;
                if *optional {
                    self.optional_guard(end);
                }
                match property {
                    // `.length` has its own opcode. The reference emits it for every
                    // object, not just arrays, so a name-based rule is right and
                    // cheaper than the generic field read.
                    MemberProp::Ident(name) if name.name == "length" => {
                        self.emit(Opcode::GetLength, &[]);
                    }
                    MemberProp::Ident(name) => {
                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
                    }
                    MemberProp::Computed(index) => {
                        self.expr(index)?;
                        self.emit(Opcode::GetArrayEl, &[]);
                    }
                    MemberProp::Private(name) => {
                        // The binding comes from the class scope, so a read from outside the
                        // class cannot name it at all. `?.` checks the object, not the field:
                        // `o?.#x` guards on `o` being nullish.
                        let binding = format!("#{}", name.name);
                        let (kind, _) = self.private_use(&binding, expr.span)?;
                        self.private_load(&binding, kind, expr.span)?;
                    }
                }
                Ok(())
            }
            ExprKind::Call {
                callee,
                arguments,
                optional,
            } => {
                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
                // cannot: it reads the function and then calls it with no
                // receiver at all. The reference's answer is to keep the object
                // under the function value — `get_field2` reads a field and leaves
                // its base in place — and to use `call_method`, which takes the
                // receiver from the stack. Missing this does not just cost an
                // instruction, it loses the `this` binding.
                if let ExprKind::Member {
                    object,
                    property,
                    optional: member_optional,
                } = &callee.unparen().kind
                {
                    // `super.m()` reads the method off the home object's prototype but
                    // calls it with `this`, so the receiver goes under the read instead of
                    // being replaced by it.
                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
                        self.super_base();
                        match property {
                            MemberProp::Ident(name) => self.emit(
                                Opcode::PushAtomValue,
                                &[Op::Atom(Atom::from_text(&name.name))],
                            ),
                            MemberProp::Computed(index) => self.expr(index)?,
                            MemberProp::Private(_) => {
                                return Err(SyntaxError::new(
                                    "private fields are not supported by the compiler yet",
                                    expr.span,
                                ));
                            }
                        }
                        // The two-output form would drop the receiver; this one replaces
                        // the prototype and the key, leaving `this` underneath.
                        self.emit(Opcode::GetArrayEl, &[]);
                        if Self::has_spread(arguments) {
                            self.argument_array(arguments)?;
                            self.emit(Opcode::Perm3, &[]);
                            self.emit(Opcode::Apply, &[Op::Int(0)]);
                            return Ok(());
                        }
                        for argument in arguments {
                            self.expr(argument)?;
                        }
                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
                        return Ok(());
                    }
                    self.chain_link(object, end)?;
                    if *member_optional {
                        self.optional_guard(end);
                    }
                    match property {
                        MemberProp::Ident(name) => {
                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
                        }
                        MemberProp::Computed(index) => {
                            self.expr(index)?;
                            // The key is not needed after the read, so this is the
                            // two-output form: object, value.
                            self.emit(Opcode::GetArrayEl2, &[]);
                        }
                        MemberProp::Private(name) => {
                            // The receiver is already under the callee, which is exactly the
                            // shape `call_method` and `apply` want — so nothing is dropped.
                            let binding = format!("#{}", name.name);
                            let (kind, _) = self.private_use(&binding, expr.span)?;
                            self.private_callee(&binding, kind)?;
                        }
                    }
                    if Self::has_spread(arguments) {
                        // Stack is `obj func`; the array goes on top, then `perm3`
                        // reorders to the `func this array` that `apply` wants.
                        self.argument_array(arguments)?;
                        self.emit(Opcode::Perm3, &[]);
                        self.emit(Opcode::Apply, &[Op::Int(0)]);
                        return Ok(());
                    }
                    for argument in arguments {
                        self.expr(argument)?;
                    }
                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
                    return Ok(());
                }
                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
                // with `get_field2` so the base stays under it, and on the short-circuit
                // path pushes an extra `undefined` as a placeholder receiver — the call
                // then throws, which is what calling a missing optional chain should do.
                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
                    && let ExprKind::Member {
                        object,
                        property,
                        optional: member_optional,
                    } = &inner.unparen().kind
                {
                    let call = self.new_label();
                    // A guard target of its own: the outer `end` skips the whole
                    // expression, and a short-circuited receiver still has to reach the
                    // call so that calling it throws.
                    let short = self.new_label();
                    self.chain_link(object, end)?;
                    if *member_optional {
                        self.optional_guard(short);
                    }
                    match property {
                        MemberProp::Ident(name) => {
                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
                        }
                        MemberProp::Computed(index) => {
                            self.expr(index)?;
                            self.emit(Opcode::GetArrayEl2, &[]);
                        }
                        MemberProp::Private(name) => {
                            let binding = format!("#{}", name.name);
                            let (kind, _) = self.private_use(&binding, expr.span)?;
                            self.private_callee(&binding, kind)?;
                        }
                    }
                    self.emit_jump(Opcode::Goto, call, &[]);
                    self.place_label(short);
                    self.emit(Opcode::Undefined, &[]);
                    self.place_label(call);
                    if Self::has_spread(arguments) {
                        self.argument_array(arguments)?;
                        self.emit(Opcode::Perm3, &[]);
                        self.emit(Opcode::Apply, &[Op::Int(0)]);
                        return Ok(());
                    }
                    for argument in arguments {
                        self.expr(argument)?;
                    }
                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
                    return Ok(());
                }
                self.chain_link(callee, end)?;
                if *optional {
                    self.optional_guard(end);
                }
                if Self::has_spread(arguments) {
                    // `func array -> func undefined array`, which is the plain-call
                    // form of `apply`: the receiver is `undefined`.
                    self.argument_array(arguments)?;
                    self.emit(Opcode::Undefined, &[]);
                    self.emit(Opcode::Swap, &[]);
                    self.emit(Opcode::Apply, &[Op::Int(0)]);
                    return Ok(());
                }
                for argument in arguments {
                    self.expr(argument)?;
                }
                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
                Ok(())
            }
            _ => self.expr(expr),
        }
    }

    /// Compile `expr` as a tail call when it is one, reporting whether it was.
    ///
    /// `tail_call` reuses the current frame instead of pushing a new one, so a
    /// tail-recursive function runs in constant stack space. It also has to be the
    /// *last* thing the function does, which is why only a `return` reaches here.
    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
        let ExprKind::Call {
            callee,
            arguments,
            optional: false,
        } = &expr.unparen().kind
        else {
            return Ok(false);
        };
        let end = self.new_label();
        if let ExprKind::Member {
            object,
            property,
            optional: false,
        } = &callee.unparen().kind
        {
            // `super.m()` in tail position is still an ordinary method call with `this`
            // as the receiver; only the read of the method differs.
            if matches!(object.unparen().kind, ExprKind::SuperProp) {
                self.super_base();
                match property {
                    MemberProp::Ident(name) => self.emit(
                        Opcode::PushAtomValue,
                        &[Op::Atom(Atom::from_text(&name.name))],
                    ),
                    MemberProp::Computed(index) => self.expr(index)?,
                    MemberProp::Private(_) => return Ok(false),
                }
                self.emit(Opcode::GetArrayEl, &[]);
                for argument in arguments {
                    self.expr(argument)?;
                }
                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
                self.place_label(end);
                return Ok(true);
            }
            self.chain_link(object, end)?;
            match property {
                MemberProp::Ident(name) => {
                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
                }
                MemberProp::Computed(index) => {
                    self.expr(index)?;
                    self.emit(Opcode::GetArrayEl2, &[]);
                }
                MemberProp::Private(_) => return Ok(false),
            }
            for argument in arguments {
                self.expr(argument)?;
            }
            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
            self.place_label(end);
            return Ok(true);
        }
        self.chain_link(callee, end)?;
        for argument in arguments {
            self.expr(argument)?;
        }
        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
        self.place_label(end);
        Ok(true)
    }

    /// The `?.` guard: keep the value if it is neither null nor undefined,
    /// otherwise replace it with `undefined` and leave the whole chain.
    fn optional_guard(&mut self, end: Label) {
        let cont = self.new_label();
        self.emit(Opcode::Dup, &[]);
        self.emit(Opcode::IsUndefinedOrNull, &[]);
        self.emit_jump(Opcode::IfFalse, cont, &[]);
        self.emit(Opcode::Drop, &[]);
        self.emit(Opcode::Undefined, &[]);
        self.emit_jump(Opcode::Goto, end, &[]);
        self.place_label(cont);
    }

    fn push_number(&mut self, value: f64) {
        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
        // goes into the constant pool.
        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
            let int = value as i32;
            if (-1..=7).contains(&int) {
                self.emit(Opcode::PushI32, &[Op::Int(int)]);
                return;
            }
            if (-128..=127).contains(&int) {
                self.emit(Opcode::PushI8, &[Op::Int(int)]);
                return;
            }
            if (-32768..=32767).contains(&int) {
                self.emit(Opcode::PushI16, &[Op::Int(int)]);
                return;
            }
            self.emit(Opcode::PushI32, &[Op::Int(int)]);
            return;
        }
        let index = self.push_constant(Constant::Number(value));
        self.emit(Opcode::PushConst, &[Op::Const(index)]);
    }

    /// Push a `BigInt` literal.
    ///
    /// A value that fits an `i32` uses the immediate form, which is what the reference
    /// emits too; anything larger goes into the constant pool, because the operand of
    /// `push_bigint` is only four bytes wide.
    fn push_bigint(&mut self, digits: &str, radix: u32) {
        if radix == 10
            && let Ok(value) = digits.parse::<i64>()
            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
        {
            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
            return;
        }
        let index = self.push_constant(Constant::BigInt {
            digits: digits.to_string(),
            radix,
        });
        self.emit(Opcode::PushConst, &[Op::Const(index)]);
    }

    fn push_string(&mut self, text: &str) {
        if text.is_empty() {
            self.emit(Opcode::PushEmptyString, &[]);
            return;
        }
        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(text))]);
    }

    /// Name an anonymous function from the binding it is assigned to.
    ///
    /// `var f = function(){}` produces a function whose `name` is `f`, which the
    /// runtime cannot know without being told: the function object is created
    /// before the store. `set_name` carries the name across.
    fn set_name_if_anonymous(&mut self, value: &Expr, name: &str) {
        if value.is_anonymous_function_definition() {
            self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(name))]);
        }
    }

    /// The same, for a computed key: the name comes from the value on the stack
    /// rather than from an atom, so a different instruction carries it.
    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
        if value.is_anonymous_function_definition() {
            self.emit(Opcode::SetNameComputed, &[]);
        }
    }

    /// Compile a function body that exists only in the compiler's head — a class's
    /// implicit constructor or its field initialiser.
    ///
    /// Everything structural is the same as a written function: a fresh `FnState`, its
    /// own body block, and resolution while the frame is still on the stack. Only the
    /// statements differ.
    fn compile_synthetic_function(
        &mut self,
        name: &str,
        strict: bool,
        span: Span,
        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
    ) -> Result<CompiledFunction, SyntaxError> {
        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
        state.strict = strict;
        state.created_in_block = self.cur().current_block;
        state.with_names = self.cur().with_names.clone();
        state.line = span.start.line;
        state.column = span.start.column;
        let depth = self.stack.len();
        self.stack.push(state);
        let body_key = span.start.offset as u64;
        self.push_block(body_key, NO_PARENT);
        self.state().body_block = body_key;
        let result = (|| {
            self.emit_scope_enter(body_key);
            body(self)?;
            if self.end_is_reachable() {
                self.emit(Opcode::ReturnUndef, &[]);
            }
            Ok(())
        })();
        if result.is_err() {
            self.stack.truncate(depth);
            return result.map(|()| unreachable!());
        }
        Ok(self.finish_current())
    }

    /// The implicit return of a class constructor.
    ///
    /// A constructor that falls off the end initialises its instance fields first, and a
    /// derived one returns `this` — which is what makes `new D()` the object `super()`
    /// built rather than `undefined`.
    fn emit_class_constructor_tail(&mut self) {
        match self.cur().ctor_kind {
            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
            // Nothing to install: a base constructor did it in its prologue and a derived
            // one at each `super()` site, which is where `this` first exists.
            CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
            CtorKind::Derived => {
                // `get_loc_check` rather than `get_loc`: reaching the end without ever
                // running `super()` is a ReferenceError, not `undefined`.
                self.emit_var(VarAction::Get, "this");
                self.emit(Opcode::Return, &[]);
            }
        }
    }

    /// `yield expr` / `yield* expr`.
    ///
    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
    /// it to the caller and parks the frame. On resume the stack holds the value the
    /// caller passed *and* a "magic" number saying which method resumed it — `next`
    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
    /// `if_false <continue>` asks whether this was an ordinary `next`:
    ///
    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
    ///   and uses the value sitting under the magic number.
    ///
    /// A `throw` never reaches here: the interpreter unwinds instead (see
    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
    fn yield_expression(
        &mut self,
        argument: Option<&Expr>,
        delegate: bool,
    ) -> Result<(), SyntaxError> {
        if delegate {
            return self.yield_star(argument);
        }
        // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
        // does the same for the `return(v)` that can resume it — which is why an async
        // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
        // generator's is just `yield`.
        let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
        match argument {
            Some(value) => self.expr(value)?,
            None => self.emit(Opcode::Undefined, &[]),
        }
        if is_async {
            self.emit(Opcode::Await, &[]);
            self.state().has_await = true;
        }
        self.emit(Opcode::Yield, &[]);
        let resume = self.new_label();
        self.emit_jump(Opcode::IfFalse, resume, &[]);
        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
        // finished the generator and never ran the `finally`.
        if is_async {
            self.emit(Opcode::Await, &[]);
        }
        self.emit_unwind_for_return(true);
        self.emit(Opcode::ReturnAsync, &[]);
        self.place_label(resume);
        // Nothing is emitted here: the value the caller passed to `next` *is* the value
        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
        // it through the ordinary expression-statement discard.
        Ok(())
    }

    /// `yield* iterable`.
    ///
    /// The shape is the reference's, and it is a fall-through chain rather than a
    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
    /// the inner iterator and finishes, `throw` forwards the exception into it and
    /// continues only if it has a `throw` method.
    ///
    /// The stack is `iter next catch value` throughout, `catch` being the offset
    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
        match argument {
            Some(value) => self.expr(value)?,
            // The parser rejects a bare `yield*`, so this is unreachable in practice.
            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
        }
        // `for await of` is the same protocol as `for of` with two differences that matter
        // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
        // every `next()` result is a promise the delegate has to await.
        let is_async = self.cur().kind.is_async();
        self.emit(
            if is_async {
                Opcode::ForAwaitOfStart
            } else {
                Opcode::ForOfStart
            },
            &[],
        );
        self.emit(Opcode::Drop, &[]);
        self.emit(Opcode::Undefined, &[]);
        self.emit(Opcode::Undefined, &[]);
        let next = self.new_label();
        let resume = self.new_label();
        let finished = self.new_label();
        let rethrow = self.new_label();
        let throw_no_method = self.new_label();
        let done = self.new_label();
        self.place_label(next);
        self.emit(Opcode::IteratorNext, &[]);
        if is_async {
            self.emit(Opcode::Await, &[]);
            self.state().has_await = true;
        }
        self.emit(Opcode::IteratorCheckObject, &[]);
        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
        self.emit_jump(Opcode::IfTrue, done, &[]);
        // The suspension. `resume` is both the label the return path jumps back to in order
        // to yield one more value and where the caller's answer arrives, as the value
        // followed by the magic number.
        //
        // The two forms differ in what they hand the suspension: `yield_star` takes the
        // result object itself, `async_yield_star` takes `.value`, because an async
        // generator awaits and re-wraps whatever it yields.
        self.place_label(resume);
        if is_async {
            self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
            self.emit(Opcode::AsyncYieldStar, &[]);
        } else {
            self.emit(Opcode::YieldStar, &[]);
        }
        self.emit(Opcode::Dup, &[]);
        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
        self.emit(Opcode::Drop, &[]);
        self.emit_jump(Opcode::Goto, next, &[]);

        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
        self.place_label(rethrow);
        self.emit(Opcode::PushI32, &[Op::Int(2)]);
        self.emit(Opcode::StrictEq, &[]);
        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
        // A `return` closes the inner iterator; if it had none, the delegate simply
        // finishes with the requested value. In an async generator both the call and its
        // result are awaited, because the inner `return` may itself be async.
        if is_async {
            self.emit(Opcode::Await, &[]);
        }
        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
        self.emit_jump(Opcode::IfTrue, finished, &[]);
        if is_async {
            self.emit(Opcode::Await, &[]);
        }
        self.emit(Opcode::IteratorCheckObject, &[]);
        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
        self.emit_jump(Opcode::IfFalse, resume, &[]);
        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
        self.place_label(finished);
        self.emit(Opcode::Nip, &[]);
        self.emit(Opcode::Nip, &[]);
        self.emit(Opcode::Nip, &[]);
        // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
        // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
        // awaits the value in an async generator and then runs the same `finally`/iterator
        // unwinding a written `return` would. Skipping the unwinding made
        // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
        if is_async {
            self.emit(Opcode::Await, &[]);
        }
        self.emit_unwind_for_return(true);
        self.emit(Opcode::ReturnAsync, &[]);

        // `throw(e)`: forward it into the inner iterator.
        self.place_label(throw_no_method);
        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
        let no_throw = self.new_label();
        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
        if is_async {
            self.emit(Opcode::Await, &[]);
        }
        self.emit(Opcode::IteratorCheckObject, &[]);
        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
        self.emit_jump(Opcode::IfFalse, resume, &[]);
        self.emit_jump(Opcode::Goto, done, &[]);
        // No `throw` method: close the iterator, then report the spec's TypeError. The
        // `if_true` before the `await` is the reference's shape — the flag it consumes is
        // what `iterator_call` leaves behind, and a close that *did* find no `return`
        // method has nothing to await.
        self.place_label(no_throw);
        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
        let no_close = self.new_label();
        self.emit_jump(Opcode::IfTrue, no_close, &[]);
        if is_async {
            self.emit(Opcode::Await, &[]);
        }
        self.place_label(no_close);
        self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);

        // The inner iterator finished: the delegate's value is the `yield*` expression's
        // value, so it is left on the stack for whatever consumes it.
        self.place_label(done);
        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
        self.emit(Opcode::Nip, &[]);
        self.emit(Opcode::Nip, &[]);
        self.emit(Opcode::Nip, &[]);
        Ok(())
    }

    /// `await expr`: exactly one instruction.
    ///
    /// No resume-magic branch follows it. The reference's `await` leaves a single value
    /// on the stack and completion is signalled by the `return_async` at the end of the
    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
    /// reference never emits, and a `for await` loop — which reaches `await` through the
    /// same opcode — would then spill a value the loop's unpacking does not expect.
    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
        self.expr(argument)?;
        self.emit(Opcode::Await, &[]);
        self.state().has_await = true;
        Ok(())
    }

    /// The `super` base: the receiver followed by the home object's prototype.
    ///
    /// Everything `super` does needs both. A *read* starts at the prototype but reports
    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
    /// prototype but calls it with the receiver.
    fn super_base(&mut self) {
        self.this_expression();
        self.home_object();
        self.emit(Opcode::GetSuper, &[]);
    }

    /// `[[HomeObject]]` as `super` sees it.
    ///
    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
    /// put it there — so for them the special object *is* the answer. An arrow and a
    /// static block have none: they read the enclosing function's, which has to be
    /// materialised into a local, exactly as `this` is for an arrow.
    ///
    /// The name matches what the reference stores, so the disassembly agrees; it is not a
    /// name any program can write.
    fn home_object(&mut self) {
        if !self.cur().is_arrow {
            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
            return;
        }
        if let Some(target) = self.enclosing_function() {
            self.state_at(target).needs_home_object_local = true;
            self.declare_at(target, HOME_OBJECT);
        }
        self.emit_var(VarAction::Get, HOME_OBJECT);
    }

    /// `super(args)`: construct the parent class and adopt the result as `this`.
    ///
    /// The parent is the prototype of the constructor that is running, which is exactly
    /// what `extends` set up. `new.target` is passed through unchanged so that
    /// `new.target` inside the parent is the class actually being constructed.
    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
        self.active_func_expression();
        self.emit(Opcode::GetSuper, &[]);
        self.new_target_expression();
        if Self::has_spread(arguments) {
            self.argument_array(arguments)?;
            self.emit(Opcode::Apply, &[Op::Int(1)]);
        } else {
            for argument in arguments {
                self.expr(argument)?;
            }
            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
        }
        // The value stays on the stack: `super()` is an expression, and a derived
        // constructor's `this` may only be initialised once.
        self.emit(Opcode::Dup, &[]);
        self.emit_var(VarAction::PutInitChecked, "this");
        // Instance fields are installed here, not at the top of the body: a derived
        // constructor has no `this` to install them on until `super()` returns. The
        // reference emits the same call at every `super()` site.
        self.call_field_initialiser();
        Ok(())
    }

    /// `this` as a local, which every class constructor and field initialiser needs.
    ///
    /// The reference materialises the receiver into a local rather than reading
    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
    /// and a field initialiser has to see the final value.
    fn begin_this_local(&mut self) {
        self.declare_hidden_local("this", VarKind::Normal);
        self.emit(Opcode::PushThis, &[]);
        self.emit_var(VarAction::Put, "this");
        // The store is already at the top of the body, so `provide_this_local` has
        // nothing left to prepend. Without this the initialiser ended up with
        // `push_this; put_loc0 this` twice whenever the class also held a field
        // initialiser whose body read `this` through an arrow.
        self.state().has_this_prologue = true;
    }

    /// Compile a constructor the class wrote.
    ///
    /// The flags have to be in place before the body is compiled, but
    /// `compile_function_with_name` creates its own state — so the caller's state is
    /// marked instead and the new one inherits it. That is the same trick the parameter
    /// prologue uses, and it keeps one code path for both.
    fn compile_class_constructor(
        &mut self,
        func: &ast::Function,
        has_heritage: bool,
    ) -> Result<CompiledFunction, SyntaxError> {
        let saved = self.cur().ctor_kind;
        self.state().class_ctor_pending = Some(if has_heritage {
            CtorKind::Derived
        } else {
            CtorKind::Base
        });
        let result = self.compile_function_with_name(func, false);
        self.state().ctor_kind = saved;
        self.state().class_ctor_pending = None;
        result
    }

    /// The constructor a class gets when it does not declare one.
    ///
    /// A base class's is empty; a derived class's forwards every argument to the parent
    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
    /// instance field initialiser afterwards when the class has fields, which is why the
    /// initialiser is captured rather than inlined.
    fn compile_implicit_constructor(
        &mut self,
        class: &Class,
        has_heritage: bool,
    ) -> Result<CompiledFunction, SyntaxError> {
        self.compile_synthetic_function(
            "",
            true,
            Span::new(class.body_end, class.body_end),
            |compiler| {
                if has_heritage {
                    // A derived constructor's `this` does not exist until `super()` returns,
                    // so it starts in the dead zone and `init_ctor` fills it.
                    compiler.declare("this", VarDef::lexical("this"));
                    compiler.emit(
                        Opcode::SetLocUninitialized,
                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
                    );
                    compiler.emit(Opcode::InitCtor, &[]);
                    compiler.emit(
                        Opcode::PutLocCheckInit,
                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
                    );
                } else {
                    compiler.begin_this_local();
                    compiler.emit(Opcode::CheckCtor, &[]);
                }
                compiler.call_field_initialiser();
                // A derived constructor returns `this`, the object `super()` built. Without
                // this the implicit constructor fell through to `return_undef`, and `new B()`
                // handed back the empty object `construct` had made instead of the one the
                // parent constructor initialised.
                if has_heritage {
                    compiler.emit_var(VarAction::Get, "this");
                    compiler.emit(Opcode::Return, &[]);
                }
                Ok(())
            },
        )
    }

    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
    ///
    /// A class with no instance fields leaves the binding `undefined`, and calling it
    /// would throw; the reference emits the same guard rather than branching at compile
    /// time because a class can be extended by a subclass whose fields still have to run.
    fn call_field_initialiser(&mut self) {
        let skip = self.new_label();
        self.emit_var(VarAction::Get, "<class_fields_init>");
        self.emit(Opcode::Dup, &[]);
        self.emit_jump(Opcode::IfFalse, skip, &[]);
        self.emit_var(VarAction::Get, "this");
        self.emit(Opcode::Swap, &[]);
        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
        self.place_label(skip);
        self.emit(Opcode::Drop, &[]);
    }

    /// The function that defines one class's fields on `this`, and runs its static blocks.
    ///
    /// `define_field` rather than `put_field`: a field is an own property created
    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
    /// `x = 1` field must not call the setter.
    ///
    /// One function serves the whole class: it is called once per instance (or once, for
    /// the static half) and walks the members in source order. Static blocks are compiled
    /// into the same function because they *are* part of the same sequence — `static a =
    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
    /// different values, so the two kinds cannot be split apart.
    fn compile_field_initialiser(
        &mut self,
        items: &[StaticInitItem<'_>],
        span: Span,
        instance: bool,
        add_brand: bool,
    ) -> Result<CompiledFunction, SyntaxError> {
        self.compile_synthetic_function("", true, span, |compiler| {
            if instance {
                // An instance initialiser always carries a `<home_object>` local, because the
                // brand block below reads it — even when that block turns out to be dead. The
                // reference has the same artefact, and the store is visible in its dump.
                let current = compiler.stack.len() - 1;
                compiler.stack[current].needs_home_object_local = true;
            }
            compiler.begin_this_local();
            if instance {
                // `this` gets the brand the prototype created, before any field is defined —
                // which is what makes `#m()` usable from inside a field initialiser.
                //
                // The reference always emits `push_false; if_false L; this; home; add_brand;
                // L:` and patches the `push_false` to `push_true` from the class parse when
                // the class has private methods; either way the branch folds, but the *mark*
                // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
                // `this` local from being fused into a `set_loc`.
                let skip = compiler.new_label();
                if add_brand {
                    compiler.emit(Opcode::PushTrue, &[]);
                } else {
                    compiler.emit(Opcode::PushFalse, &[]);
                }
                compiler.emit_jump(Opcode::IfFalse, skip, &[]);
                compiler.emit_var(VarAction::Get, "this");
                compiler.emit_var(VarAction::Get, HOME_OBJECT);
                compiler.emit(Opcode::AddBrand, &[]);
                compiler.place_label(skip);
            }
            for item in items {
                match item {
                    StaticInitItem::Field(key, value) => {
                        // A private field is *defined*, not assigned: `define_private_field`
                        // reads `obj symbol value`, and its point is that it fails on a
                        // receiver that is not this class's — which `put_field` would not.
                        //
                        // The three shapes are the reference's: `define_field <atom>` for a
                        // static name, `define_array_el` for a key that is only known at run
                        // time (`obj key value`), `define_private_field` for `#x`, and a
                        // computed key is read from its binding rather than recomputed.
                        compiler.emit_var(VarAction::Get, "this");
                        match key {
                            FieldKey::Private(binding) | FieldKey::Computed(binding) => {
                                compiler.emit_var(VarAction::Get, binding);
                            }
                            FieldKey::Literal(_) => {}
                        }
                        match value {
                            Some(value) => compiler.expr(value)?,
                            None => compiler.emit(Opcode::Undefined, &[]),
                        }
                        match key {
                            FieldKey::Literal(literal) => {
                                let text = compiler.property_key_text(literal, span)?;
                                compiler
                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_text(&text))]);
                            }
                            FieldKey::Computed(_) => {
                                compiler.emit(Opcode::DefineArrayEl, &[]);
                                // `define_array_el` leaves `obj key`; the key is consumed by
                                // the copy the pattern machinery wants, so both go.
                                compiler.emit(Opcode::Drop, &[]);
                            }
                            FieldKey::Private(_) => {
                                compiler.emit(Opcode::DefinePrivateField, &[]);
                            }
                        }
                        compiler.emit(Opcode::Drop, &[]);
                    }
                    StaticInitItem::Block { body, body_start } => {
                        let block = compiler.compile_static_block(body, *body_start)?;
                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
                        // `this fclosure`, so `call_method` finds the receiver below the
                        // callee: the block runs with `this` bound to the class.
                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
                        compiler.emit_var(VarAction::Get, "this");
                        compiler.emit(Opcode::Swap, &[]);
                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
                        // Nothing the block evaluates is wanted; its effects are the point.
                        compiler.emit(Opcode::Drop, &[]);
                    }
                }
            }
            Ok(())
        })
    }

    /// Compile a `static { … }` body into the function the class calls for it.
    ///
    /// Shaped like an arrow, because that is the one function form with no `this`,
    /// `new.target` or `arguments` of its own: all three reach the enclosing static
    /// initialiser, and through it the class. `arguments` never gets that far — the parser
    /// rejects the reference — but `this` and `super` both depend on it.
    ///
    /// The body is hoisted like a function body's, because the reference parses it as one:
    /// `var` inside a block is a local of the block's function, not of whatever encloses
    /// the class.
    fn compile_static_block(
        &mut self,
        body: &[Stmt],
        body_start: Position,
    ) -> Result<CompiledFunction, SyntaxError> {
        let mut state = FnState::new(String::new(), FunctionKind::Normal);
        // Class bodies are strict, so a static block is too.
        state.strict = true;
        // The one property that makes this an arrow: nothing of its own to bind `this` to,
        // so `this` and `super` come from the initialiser that calls it.
        state.is_arrow = true;
        state.created_in_block = self.cur().current_block;
        state.with_names = self.cur().with_names.clone();
        state.line = body_start.line;
        state.column = body_start.column;
        let depth = self.stack.len();
        self.stack.push(state);
        let body_key = body_start.offset as u64;
        self.push_block(body_key, NO_PARENT);
        self.state().body_block = body_key;
        let result = (|| {
            self.hoist(body, body_key)?;
            self.emit_scope_enter(body_key);
            for statement in body {
                self.stmt(statement)?;
            }
            if self.end_is_reachable() {
                self.emit(Opcode::ReturnUndef, &[]);
            }
            Ok(())
        })();
        if result.is_err() {
            self.stack.truncate(depth);
            return result.map(|()| unreachable!());
        }
        Ok(self.finish_current())
    }

    /// Compile a class, leaving the constructor on the stack when `keep`.
    ///
    /// The shape follows the reference: the class body is its own scope holding the
    /// class's *inner* name as a `const` — which is what lets a method refer to the
    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
    /// on the top of the stack: the prototype for instance members, the constructor
    /// itself for `static` ones, which is why a static member costs an extra `swap`.
    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
        let parent_block = self.cur().current_block;
        let key = class.span.start.offset as u64;
        self.push_block(key, parent_block);
        let name = class.name.as_ref().map(|ident| ident.name.clone());
        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
        // resolves `E` without a global lookup. An *unnamed* class expression has no such
        // binding, and `define_class` is handed the empty name.
        if let Some(name) = &name {
            self.declare(name, VarDef::constant(name.clone()));
        }
        self.emit_scope_enter(key);

        // The heritage clause is evaluated outside the class's own scope: it cannot see
        // the class binding it is about to initialise.
        let saved_block = self.cur().current_block;
        self.state().current_block = parent_block;
        match &class.super_class {
            Some(parent) => self.expr(parent)?,
            None => self.emit(Opcode::Undefined, &[]),
        }
        self.state().current_block = saved_block;
        let has_heritage = class.super_class.is_some();

        // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
        // lands after the heritage's code — which is where the reference puts it, because it
        // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
        // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
        // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
        // came out in the opposite order from the reference's.
        //
        // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
        // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
        // a const accepts — so the old comment's worry ("a const would refuse the second
        // store") did not apply: there is no second store.
        // Every `#name` the class declares gets a `const` binding in the class scope, and so
        // does every computed field key. That is how the reference does it
        // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
        // what makes a private name resolve like any other class-scope variable — including
        // through a nested function's closure — while remaining invisible outside.
        //
        // All of them are declared *before* `<class_fields_init>`, in member order, because
        // that is when the reference's parser creates them.
        let plan = ClassPlan::build(class);
        // The body's private names are visible from here to the end of the class, and shadow
        // any outer class's of the same spelling. Pushed *before* the constructor is compiled
        // — it is compiled first because `define_class` consumes it, but its body can name
        // `#x` like any other member's.
        self.private_scopes.push(plan.uses.clone());
        let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
        for binding in &plan.bindings {
            class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
        }
        let fci = self.declare(
            "<class_fields_init>",
            VarDef::constant("<class_fields_init>"),
        );
        // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
        // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
        // members' bindings follow in reverse.
        self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
        for slot in class_slots.iter().rev() {
            self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
        }

        // The constructor is compiled before `define_class` because that instruction
        // consumes it; a class without one gets the implicit version.
        let constructor = class.elements.iter().find_map(|element| match element {
            ClassElement::Method {
                kind: MethodKind::Constructor,
                func,
                ..
            } => Some(&**func),
            _ => None,
        });
        // A constructor is compiled differently from a method: it owns `this`. The flags
        // go on the *enclosing* state because a constructor is a nested function and
        // `compile_function_with_name` starts a fresh one.
        let ctor = match constructor {
            Some(func) => self.compile_class_constructor(func, has_heritage)?,
            None => self.compile_implicit_constructor(class, has_heritage)?,
        };
        // A closure, not the bare constant: the constructor captures
        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
        // has to hold the cell rather than a copy of its value.
        //
        // The pool slot is left unassigned for now, because the reference gives the
        // constructor the *last* index of the members' range: `js_parse_class` emits a
        // `push_const` whose operand is patched at the end of the class parse, after every
        // method has taken a slot. Emitting the members first and the constant second is how
        // the numbering comes out the same; the instruction itself stays where it is.
        let ctor_insn = self.cur().insns.len();
        self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
        let flags = if has_heritage { 1 } else { 0 };
        self.emit(
            Opcode::DefineClass,
            &[
                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
                Op::Int(flags),
            ],
        );

        // Instance fields and static fields are two different functions: the first runs
        // per instance from the constructor, the second runs once, here.
        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
        for (index, element) in class.elements.iter().enumerate() {
            match element {
                ClassElement::Method {
                    key: member_key,
                    is_static,
                    kind,
                    func,
                    span,
                } => {
                    if *kind == MethodKind::Constructor {
                        continue;
                    }
                    // `static(x)` is a *method* named `static`, not a static method; the
                    // parser already decided which by putting it in `kind`.
                    if *is_static {
                        self.emit(Opcode::Swap, &[]);
                    }
                    let function = self.compile_function_with_name(func, true)?;
                    let index = self.push_constant(Constant::Function(Box::new(function)));
                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
                    match member_key {
                        // A private method is not a property of the prototype: it is a
                        // closure in the class scope, which is why nothing outside can reach
                        // it and why a use site has to brand-check. `set_name` gives the
                        // function its `name` (`#m`), which an accessor does not get — the
                        // reference leaves that commented out.
                        PropName::Private(ident) => {
                            let name = format!("#{}", ident.name);
                            // `set_home_object` first: the brand check reads the function's
                            // home object, and for a method that is the prototype.
                            self.emit(Opcode::SetHomeObject, &[]);
                            let binding = if *kind == MethodKind::Set {
                                format!("{name}<set>")
                            } else {
                                name.clone()
                            };
                            if *kind == MethodKind::Method {
                                self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
                            }
                            self.emit_var(VarAction::PutInit, &binding);
                        }
                        PropName::Computed(key) => {
                            self.emit(Opcode::Swap, &[]);
                            self.expr(key)?;
                            self.emit(
                                Opcode::DefineMethodComputed,
                                &[Op::Int(class_method_flags(*kind))],
                            );
                            // `define_method_computed` leaves the key; drop it.
                            self.emit(Opcode::Drop, &[]);
                        }
                        PropName::Literal(literal) => {
                            let text = self.property_key_text(literal, *span)?;
                            self.emit(
                                Opcode::DefineMethod,
                                &[
                                    Op::Atom(Atom::from_text(&text)),
                                    Op::Int(class_method_flags(*kind)),
                                ],
                            );
                        }
                    }
                    if *is_static {
                        self.emit(Opcode::Swap, &[]);
                    }
                }
                ClassElement::Field {
                    key: field_key,
                    is_static,
                    value,
                    ..
                } => {
                    // A private field's *symbol* is created here, at the member, and stored
                    // in its binding: the field's property is keyed by it, so it has to exist
                    // before any initialiser runs, and a fresh one per class body is what
                    // makes two classes that both write `#x` independent.
                    //
                    // A computed key is evaluated once, here, and `to_propkey`'d once — a key
                    // whose `toString` has a side effect must not run again per instance.
                    let key = match field_key {
                        PropName::Private(ident) => {
                            let binding = format!("#{}", ident.name);
                            if *is_static {
                                self.emit(Opcode::Swap, &[]);
                            }
                            self.emit(
                                Opcode::PrivateSymbol,
                                &[Op::Atom(Atom::from_text(&binding))],
                            );
                            self.emit_var(VarAction::PutInit, &binding);
                            if *is_static {
                                self.emit(Opcode::Swap, &[]);
                            }
                            FieldKey::Private(binding)
                        }
                        PropName::Computed(expression) => {
                            let binding = plan
                                .computed
                                .get(&index)
                                .cloned()
                                .expect("every computed key got a binding");
                            if *is_static {
                                self.emit(Opcode::Swap, &[]);
                            }
                            self.expr(expression)?;
                            self.emit(Opcode::ToPropkey, &[]);
                            self.emit_var(VarAction::PutInit, &binding);
                            if *is_static {
                                self.emit(Opcode::Swap, &[]);
                            }
                            FieldKey::Computed(binding)
                        }
                        PropName::Literal(literal) => FieldKey::Literal(literal),
                    };
                    if *is_static {
                        static_items.push(StaticInitItem::Field(key, value.as_deref()));
                    } else {
                        instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
                    }
                }
                ClassElement::StaticBlock {
                    body, body_start, ..
                } => static_items.push(StaticInitItem::Block {
                    body,
                    body_start: *body_start,
                }),
            }
        }

        // Now that every member has its slot, the constructor can have the next one and the
        // `fclosure` above can name it.
        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
        match self.state().insns.get_mut(ctor_insn) {
            Some(Insn::Fixed { operands, .. }) => {
                operands[0] = Op::Const(ctor_index);
            }
            // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
            // loudly beats emitting a `fclosure` of slot 4294967295.
            _ => {
                return Err(SyntaxError::new(
                    "the class constructor's fclosure went missing",
                    class.span,
                ));
            }
        }

        // The instance brand: a symbol created once on the prototype, which every instance
        // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
        // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
        // copy is created. The prototype is on top of the stack at this point.
        if plan.instance_brand {
            self.emit(Opcode::Dup, &[]);
            self.emit(Opcode::Null, &[]);
            self.emit(Opcode::Swap, &[]);
            self.emit(Opcode::AddBrand, &[]);
        }

        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
        // class has no instance fields. The constructor calls it only when it is defined.
        //
        // A class with private *methods* but no fields still needs one, because adding the
        // brand to each new instance is the initialiser's job.
        if instance_fields.is_empty() && !plan.instance_brand {
            self.emit(Opcode::Undefined, &[]);
        } else {
            let initialiser = self.compile_field_initialiser(
                &instance_fields,
                class.span,
                true,
                plan.instance_brand,
            )?;
            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
            // `set_home_object` reads `obj func`, so the prototype stays where it is.
            self.emit(Opcode::SetHomeObject, &[]);
        }
        self.emit_var(VarAction::PutInit, "<class_fields_init>");
        // The prototype has done its job: every instance member is defined on it. What
        // is left under it is the constructor.
        self.emit(Opcode::Drop, &[]);

        // The static brand, for `static #m() {}`: same opcode, but the home object is the
        // constructor itself, so the symbol lands on the class and the class carries it.
        if plan.static_brand {
            self.emit(Opcode::Dup, &[]);
            self.emit(Opcode::Dup, &[]);
            self.emit(Opcode::AddBrand, &[]);
        }

        // The class binding is initialised *before* static fields run, so a static field
        // can refer to the class by name (`static y = S.x`).
        // `set_loc` leaves the constructor on the stack, which is what the static field
        // call and the outer store both consume.
        //
        // Only when there *is* such a binding: an anonymous class expression declares no
        // class-scope name, and asking for one by the empty string resolved to nothing —
        // which made `var x = class {}` assign `undefined` and put a bogus global store in
        // the instruction stream.
        if let Some(name) = &name {
            self.emit_var(VarAction::SetInit, name);
        }
        if !static_items.is_empty() {
            // The static half has no brand prologue of its own: the constructor got its
            // brand above, before this runs.
            let initialiser =
                self.compile_field_initialiser(&static_items, class.span, false, false)?;
            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
            self.emit(Opcode::Dup, &[]);
            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
            self.emit(Opcode::SetHomeObject, &[]);
            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
            self.emit(Opcode::Drop, &[]);
        }
        // The body is over, and with it this class's private names.
        let _ = self.private_scopes.pop();
        self.emit_scope_leave(key);
        self.state().current_block = parent_block;
        if keep {
            // A class *expression* is its own value; the class-scope binding was only
            // ever an alias for it.
            return Ok(());
        }
        // A declaration stores into the binding the enclosing statement declared.
        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
        Ok(())
    }

    fn push_this(&mut self) {
        self.emit(Opcode::PushThis, &[]);
    }

    /// `this`, which an arrow does not have of its own.
    ///
    /// The reference gives the enclosing function a local named `this`, initialised from
    /// `push_this` at the top of its body, and the arrow then reads it as a captured
    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
    /// the arrow is called with none.
    fn this_expression(&mut self) {
        // In a class constructor `this` is a local: a derived constructor only gets one
        // when `super()` returns, and reading the raw receiver would give the *outer*
        // one instead.
        if self.cur().ctor_kind != CtorKind::None {
            self.emit_var(VarAction::Get, "this");
            return;
        }
        if !self.cur().is_arrow {
            self.push_this();
            return;
        }
        if let Some(target) = self.enclosing_function() {
            self.state_at(target).needs_this_local = true;
            self.declare_at(target, "this");
        }
        self.emit_var(VarAction::Get, "this");
    }

    /// `new.target`, which an arrow likewise does not own.
    fn new_target_expression(&mut self) {
        if !self.cur().is_arrow {
            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
            return;
        }
        if let Some(target) = self.enclosing_function() {
            self.state_at(target).needs_new_target_local = true;
            self.declare_at(target, NEW_TARGET);
        }
        self.emit_var(VarAction::Get, NEW_TARGET);
    }

    /// `this.active_func`: the function `super()` resolves against.
    ///
    /// In a constructor or a method that is the function being run, so the special object
    /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
    /// a closure variable — see [`FnState::needs_active_func_local`].
    fn active_func_expression(&mut self) {
        if !self.cur().is_arrow {
            self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
            return;
        }
        if let Some(target) = self.enclosing_function() {
            self.state_at(target).needs_active_func_local = true;
            self.declare_at(target, ACTIVE_FUNC);
        }
        self.emit_var(VarAction::Get, ACTIVE_FUNC);
    }

    /// Give the function a local `<active_func>`, for an arrow inside it to capture.
    fn provide_active_func_local(&mut self) {
        let current = self.stack.len() - 1;
        if !self.stack[current].needs_active_func_local {
            return;
        }
        if !self.stack[current]
            .vars
            .iter()
            .any(|var| var.name == ACTIVE_FUNC)
        {
            self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
        }
        self.prepend_initialiser(
            ACTIVE_FUNC,
            Insn::Fixed {
                op: Opcode::SpecialObject,
                operands: vec![Op::Int(2)],
            },
        );
    }

    /// Give the function a local `new.target`, for an arrow inside it to capture.
    fn provide_new_target_local(&mut self) {
        let current = self.stack.len() - 1;
        if !self.stack[current].needs_new_target_local {
            return;
        }
        if !self.stack[current]
            .vars
            .iter()
            .any(|var| var.name == NEW_TARGET)
        {
            self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
        }
        self.prepend_initialiser(
            NEW_TARGET,
            Insn::Fixed {
                op: Opcode::SpecialObject,
                operands: vec![Op::Int(3)],
            },
        );
    }

    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
    /// function.
    fn ensure_enclosing_arguments(&mut self) {
        // An arrow created in a parameter list needs the *parameter* scope's
        // `arguments`, not the body's: the two are separate bindings and the arrow was
        // born before the body existed.
        let from_params = self.cur().created_in_params;
        if let Some(target) = self.enclosing_function() {
            self.state_at(target).needs_arguments_local = true;
            if from_params {
                self.state_at(target).needs_param_arguments = true;
                // Declare it now, not at the enclosing function's `finish_current`: the
                // arrow resolves its own `arguments` before that runs, and a binding that
                // does not exist yet resolves as a global.
                declare_param_var_at(&mut self.stack[target], "arguments");
            }
            self.declare_at(target, "arguments");
        }
    }

    /// The innermost enclosing frame that is a real function — an arrow inherits from it
    /// rather than starting a scope of its own.
    fn enclosing_function(&self) -> Option<usize> {
        (0..self.stack.len())
            .rev()
            .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
    }

    fn state_at(&mut self, index: usize) -> &mut FnState {
        &mut self.stack[index]
    }

    /// Declare a `var` binding directly in a specific frame.
    fn declare_at(&mut self, index: usize, name: &str) {
        let state = &mut self.stack[index];
        if state.vars.iter().any(|var| var.name == name) {
            return;
        }
        state.var_block.push(FUNCTION_SCOPE);
        state.vars.push(VarDef::var(name));
    }

    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
    /// the reference calls a `special_object` gets initialised on entry.
    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
        let current = self.stack.len() - 1;
        let init = [
            producer,
            Insn::Var {
                action: VarAction::Put,
                name: name.to_string(),
                block: 0,
                // A prologue initialiser runs before the body proper, but it is body
                // code: `this` and `arguments` are provided for it, not by it.
                in_params: false,
            },
        ];
        let inserted = init.len();
        for (index, instruction) in init.into_iter().enumerate() {
            self.stack[current].insns.insert(index, instruction);
        }
        for placed in self.stack[current].labels.iter_mut().flatten() {
            *placed += inserted;
        }
        self.stack[current].label_since_insn = true;
    }

    fn push_constant(&mut self, constant: Constant) -> u32 {
        let state = self.state();
        let index = state.cpool.len() as u32;
        state.cpool.push(constant);
        index
    }

    /// Compile `a && b`, `a || b`, `a ?? b`.
    ///
    /// A run of the *same* operator shares one end label, so `a || b || c` tests
    /// `a` once and jumps past everything when it is truthy, instead of falling
    /// into `b`'s test. The parser builds such a run left-associated —
    /// `((a || b) || c)` — so the operands are collected off the left spine.
    ///
    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
    /// `||`'s label, because the inner chain really does end before `&&` begins.
    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
        let mut operands = Vec::new();
        collect_same_operator(op, left, &mut operands);
        operands.push(right);

        let end = self.new_label();
        // Every operand but the last decides whether the chain stops here.
        let last = operands.pop().expect("the right operand is always present");
        for operand in operands {
            self.expr(operand)?;
            self.emit(Opcode::Dup, &[]);
            match op {
                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
                // `0 || b` is `b`. The dedicated test keeps the value unless it is
                // null-ish, so the jump is taken on `false`.
                LogicalOp::Coalesce => {
                    self.emit(Opcode::IsUndefinedOrNull, &[]);
                    self.emit_jump(Opcode::IfFalse, end, &[]);
                }
            }
            self.emit(Opcode::Drop, &[]);
        }
        self.expr(last)?;
        self.place_label(end);
        Ok(())
    }

    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
        match op {
            UnaryOp::Typeof => {
                // `typeof x` must not throw on an undeclared name.
                if let ExprKind::Ident(name) = &argument.kind {
                    self.emit_var(VarAction::GetUndef, &name.name);
                } else {
                    self.expr(argument)?;
                }
                self.emit(Opcode::Typeof, &[]);
            }
            UnaryOp::Delete => {
                // `delete obj.prop` really deletes, and answers whether it could.
                // Deleting a *binding* is always `false`: a local, an argument and a
                // declared global are all non-configurable, which the reference encodes
                // as a constant `push_false` rather than a runtime check. Only a
                // property access has anything to do at run time.
                // `delete super.x` is not a delete at all: the spec refuses it, and the
                // reference encodes the refusal as a `throw_error`. The receiver and the
                // key are still evaluated first, which is what keeps the evaluation order
                // of the operand intact.
                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
                // nothing to delete, and a failed delete is not the same as a skipped
                // one. The reference emits the guards so they land on a `drop; push_true`
                // tail, which is what this reproduces.
                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
                    && let ExprKind::Member {
                        object, property, ..
                    } = &inner.unparen().kind
                {
                    let end = self.new_label();
                    let done = self.new_label();
                    self.chain_link(object, end)?;
                    match property {
                        MemberProp::Ident(name) => self.emit(
                            Opcode::PushAtomValue,
                            &[Op::Atom(Atom::from_text(&name.name))],
                        ),
                        MemberProp::Computed(index) => self.expr(index)?,
                        MemberProp::Private(_) => {
                            return Err(SyntaxError::new(
                                "deleting a private field is not allowed",
                                argument.span,
                            ));
                        }
                    }
                    self.emit(Opcode::Delete, &[]);
                    self.emit_jump(Opcode::Goto, done, &[]);
                    self.place_label(end);
                    self.emit(Opcode::Drop, &[]);
                    self.emit(Opcode::PushTrue, &[]);
                    self.place_label(done);
                    return Ok(());
                }
                if let ExprKind::Member { object, .. } = &argument.unparen().kind
                    && matches!(object.unparen().kind, ExprKind::SuperProp)
                {
                    self.super_base();
                    self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
                    return Ok(());
                }
                match &argument.kind {
                    ExprKind::Member {
                        object, property, ..
                    } => {
                        self.expr(object)?;
                        match property {
                            MemberProp::Ident(name) => {
                                self.emit(
                                    Opcode::PushAtomValue,
                                    &[Op::Atom(Atom::from_text(&name.name))],
                                );
                            }
                            MemberProp::Computed(index) => self.expr(index)?,
                            MemberProp::Private(_) => {
                                return Err(SyntaxError::new(
                                    "deleting a private field is not allowed",
                                    argument.span,
                                ));
                            }
                        }
                        self.emit(Opcode::Delete, &[]);
                    }
                    ExprKind::Ident(name) => {
                        // `delete name`: a declared global, a local and an argument all
                        // answer `false`, but an *implicit* global (`x = 1` with no
                        // declaration) is a configurable property of the global object
                        // and really goes away. Which of those a name is only the
                        // resolver knows, so the decision waits for it.
                        let pos = self.cur().cur_pos;
                        self.state().insns.push(Insn::DeleteVar {
                            name: name.name.clone(),
                        });
                        self.state().insn_pos.push(pos);
                    }
                    _ => self.emit(Opcode::PushFalse, &[]),
                }
            }
            UnaryOp::Void => {
                self.expr(argument)?;
                self.emit(Opcode::Drop, &[]);
                self.emit(Opcode::Undefined, &[]);
            }
            UnaryOp::Minus => {
                self.expr(argument)?;
                self.emit(Opcode::Neg, &[]);
            }
            UnaryOp::Plus => {
                self.expr(argument)?;
                self.emit(Opcode::Plus, &[]);
            }
            UnaryOp::Not => {
                self.expr(argument)?;
                self.emit(Opcode::Lnot, &[]);
            }
            UnaryOp::BitNot => {
                self.expr(argument)?;
                self.emit(Opcode::Not, &[]);
            }
        }
        Ok(())
    }

    /// Compile an assignment.
    ///
    /// Three operator families, three shapes:
    ///
    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
    ///   the value is kept, because `put_field`/`put_array_el` consume both the
    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
    ///   the pair it wants and leaves a copy on top.
    /// * **compound** `+=` … — read the place, apply the operator, store. A member
    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
    ///   index) underneath the value precisely so the store can follow.
    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
    ///   right-hand side. The test *keeps* the current value and skips the store
    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
    ///   `a` is already truthy.
    fn assign(&mut self, op: AssignOp, target: &Pattern, value: &Expr) -> Result<(), SyntaxError> {
        // Reading the flag clears it: only the outermost assignment of an
        // expression statement may drop its value.
        let keep = !std::mem::take(&mut self.state().discard_value);
        match &target.kind {
            PatternKind::Ident(name) => {
                // A *simple* store is blamed on the identifier, not on the `=`: a
                // strict-mode `not_def = 1` raises when the name is written, which the
                // reference reports at the name's column. A compound store is blamed on
                // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
                // which the reference reports at the `+=`), so only the simple case
                // moves the position.
                let saved = self.cur().cur_pos;
                let name_pos = Some(name.span.start);
                if matches!(op, AssignOp::Assign) {
                    self.state().cur_pos = name_pos;
                }
                // A *compound* store reads the binding before it combines, and that read
                // is blamed on the identifier: `not_def += 2` fails while reading
                // `not_def`, so the position is the name's, not the `+=`'s. The
                // combination that follows is blamed on the operator, which is why
                // `cur_pos` is put back to the operator position before it is emitted.
                self.state().cur_pos = name_pos;
                match op {
                    AssignOp::Assign => {
                        self.expr(value)?;
                        self.set_name_if_anonymous(value, &name.name);
                        // A discarded store to a *slot* consumes its value, so no copy
                        // is needed. A global store goes through `put_var`, which the
                        // reference always pairs with a `dup` — matching it keeps the
                        // bytecode identical. Getting this wrong is not only an extra
                        // instruction: a stray copy gives the peephole a chance to fold
                        // the store into an unrelated later read.
                        let slot = self.is_slot(&name.name);
                        if keep || !slot {
                            self.emit(Opcode::Dup, &[]);
                        }
                        self.state().no_value = !keep && slot;
                        self.emit_var(VarAction::Put, &name.name);
                    }
                    AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
                        let end = self.new_label();
                        self.emit_var(VarAction::Get, &name.name);
                        self.state().cur_pos = saved;
                        self.emit(Opcode::Dup, &[]);
                        self.emit_logical_test(op);
                        self.emit_jump(logical_jump(op), end, &[]);
                        self.emit(Opcode::Drop, &[]);
                        self.expr(value)?;
                        self.emit(Opcode::Dup, &[]);
                        self.emit_var(VarAction::Put, &name.name);
                        self.place_label(end);
                    }
                    _ => {
                        self.emit_var(VarAction::Get, &name.name);
                        self.expr(value)?;
                        self.state().cur_pos = saved;
                        self.emit(compound_opcode(op), &[]);
                        self.emit(Opcode::Dup, &[]);
                        self.emit_var(VarAction::Put, &name.name);
                    }
                }
                self.state().cur_pos = saved;
                Ok(())
            }
            PatternKind::Member(member) => {
                // `super.x = v` is not a store through a value: it starts at the home
                // object's prototype but writes to `this`, so it goes through
                // `put_super_value` rather than `put_field`. The receiver, prototype, key
                // and value are handed over together.
                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
                    return self.assign_super(member, op, value);
                }
                // A store is blamed on the selector punctuator (`.` or `[`), the same
                // token a load is blamed on — the reference records `put_field obj.a`
                // at the `.`, so a setter that throws reports that column and not the
                // `=` of the assignment it sits in. The inner expressions restore their
                // own positions, so the selector's sticks for the store instructions.
                let saved = self.cur().cur_pos;
                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
                self.expr(&member.object)?;
                match &member.property {
                    MemberProp::Ident(property) => {
                        let atom = Atom::from_text(&property.name);
                        match op {
                            AssignOp::Assign => {
                                self.expr(value)?;
                                // `put_field` consumes the object and the value, so
                                // without `insert2` nothing is left over for the
                                // statement to drop.
                                self.state().no_value = !keep;
                                if keep {
                                    self.emit(Opcode::Insert2, &[]);
                                }
                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
                            }
                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
                                // `get_field2` leaves the object under the value, so
                                // the keep path has an object to dispose of. The store
                                // path must jump *over* that cleanup: falling into it
                                // would `nip` a stack that only holds the value.
                                let (keep_label, end) = (self.new_label(), self.new_label());
                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
                                self.emit(Opcode::Dup, &[]);
                                self.emit_logical_test(op);
                                self.emit_jump(logical_jump(op), keep_label, &[]);
                                self.emit(Opcode::Drop, &[]);
                                self.expr(value)?;
                                self.emit(Opcode::Insert2, &[]);
                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
                                self.emit_jump(Opcode::Goto, end, &[]);
                                self.place_label(keep_label);
                                self.emit(Opcode::Nip, &[]);
                                self.place_label(end);
                            }
                            _ => {
                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
                                self.expr(value)?;
                                self.emit(compound_opcode(op), &[]);
                                self.state().no_value = !keep;
                                if keep {
                                    self.emit(Opcode::Insert2, &[]);
                                }
                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
                            }
                        }
                    }
                    MemberProp::Computed(index) => {
                        self.expr(index)?;
                        match op {
                            AssignOp::Assign => {
                                self.expr(value)?;
                                self.state().no_value = !keep;
                                if keep {
                                    self.emit(Opcode::Insert3, &[]);
                                }
                                self.emit(Opcode::PutArrayEl, &[]);
                            }
                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
                                let (keep_label, end) = (self.new_label(), self.new_label());
                                self.emit(Opcode::GetArrayEl3, &[]);
                                self.emit(Opcode::Dup, &[]);
                                self.emit_logical_test(op);
                                self.emit_jump(logical_jump(op), keep_label, &[]);
                                self.emit(Opcode::Drop, &[]);
                                self.expr(value)?;
                                self.emit(Opcode::Insert3, &[]);
                                self.emit(Opcode::PutArrayEl, &[]);
                                self.emit_jump(Opcode::Goto, end, &[]);
                                self.place_label(keep_label);
                                // Both the object and the index are left over.
                                self.emit(Opcode::Nip, &[]);
                                self.emit(Opcode::Nip, &[]);
                                self.place_label(end);
                            }
                            _ => {
                                self.emit(Opcode::GetArrayEl3, &[]);
                                self.expr(value)?;
                                self.emit(compound_opcode(op), &[]);
                                self.state().no_value = !keep;
                                if keep {
                                    self.emit(Opcode::Insert3, &[]);
                                }
                                self.emit(Opcode::PutArrayEl, &[]);
                            }
                        }
                    }
                    MemberProp::Private(name) => {
                        // `obj value` is on the stack, and every private store wants exactly
                        // that. A top-level private name cannot be assigned (the parser rejects
                        // `#x = 1`), so the only way here is `this.#x = …` inside the class.
                        //
                        // The reference emits `insert2` whether or not the value is wanted,
                        // so this does too: the copy left behind is the assignment expression's
                        // value, and a discarded one is simply never read.
                        let binding = format!("#{}", name.name);
                        let (kind, setter) = self.private_use(&binding, member.span)?;
                        match op {
                            AssignOp::Assign => {
                                self.expr(value)?;
                                if keep {
                                    self.emit(Opcode::Insert2, &[]);
                                }
                                self.private_store(&binding, kind, setter.as_deref())?;
                                self.state().no_value = !keep;
                            }
                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
                                let (keep_label, end) = (self.new_label(), self.new_label());
                                self.emit(Opcode::Dup, &[]);
                                self.private_load(&binding, kind, member.span)?;
                                self.emit(Opcode::Dup, &[]);
                                self.emit_logical_test(op);
                                self.emit_jump(logical_jump(op), keep_label, &[]);
                                self.emit(Opcode::Drop, &[]);
                                self.expr(value)?;
                                self.emit(Opcode::Insert2, &[]);
                                self.private_store(&binding, kind, setter.as_deref())?;
                                self.emit_jump(Opcode::Goto, end, &[]);
                                self.place_label(keep_label);
                                self.emit(Opcode::Nip, &[]);
                                self.place_label(end);
                            }
                            _ => {
                                self.emit(Opcode::Dup, &[]);
                                self.private_load(&binding, kind, member.span)?;
                                self.expr(value)?;
                                self.emit(compound_opcode(op), &[]);
                                self.emit(Opcode::Insert2, &[]);
                                self.private_store(&binding, kind, setter.as_deref())?;
                            }
                        }
                    }
                }
                self.state().cur_pos = saved;
                Ok(())
            }
            // A destructuring assignment: the right-hand side is the expression's own
            // value, so it is evaluated once and kept under the pattern's stores.
            PatternKind::Array { .. } | PatternKind::Object { .. } => {
                self.expr(value)?;
                if keep {
                    self.emit(Opcode::Dup, &[]);
                }
                self.destructure(target, None)?;
                self.state().no_value = !keep;
                Ok(())
            }
            _ => Err(SyntaxError::new(
                "this assignment target is not supported by the compiler yet",
                target.span,
            )),
        }
    }

    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
    ///
    /// The stack has to carry four values — receiver, prototype, key, value — because
    /// `put_super_value` takes them together; the receiver is what makes a setter found on
    /// the prototype run with `this`, and the key has to survive until the store, which is
    /// why a compound form converts it to a property key once and `dup3`s rather than
    /// evaluating it twice.
    fn assign_super(
        &mut self,
        member: &MemberPattern,
        op: AssignOp,
        value: &Expr,
    ) -> Result<(), SyntaxError> {
        let saved = self.cur().cur_pos;
        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
        self.super_base();
        match &member.property {
            MemberProp::Ident(property) => self.emit(
                Opcode::PushAtomValue,
                &[Op::Atom(Atom::from_text(&property.name))],
            ),
            MemberProp::Computed(index) => self.expr(index)?,
            MemberProp::Private(_) => {
                return Err(SyntaxError::new(
                    "private fields are not supported by the compiler yet",
                    member.span,
                ));
            }
        }
        match op {
            AssignOp::Assign => {
                // The key is only converted once, by `put_super_value` itself, so a
                // computed key's `toString` runs exactly once.
                self.expr(value)?;
                self.emit(Opcode::Insert4, &[]);
                self.emit(Opcode::PutSuperValue, &[]);
            }
            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
                let (keep_label, end) = (self.new_label(), self.new_label());
                self.emit(Opcode::ToPropkey, &[]);
                self.emit(Opcode::Dup3, &[]);
                self.emit(Opcode::GetSuperValue, &[]);
                self.emit(Opcode::Dup, &[]);
                self.emit_logical_test(op);
                self.emit_jump(logical_jump(op), keep_label, &[]);
                self.emit(Opcode::Drop, &[]);
                self.expr(value)?;
                self.emit(Opcode::Insert4, &[]);
                self.emit(Opcode::PutSuperValue, &[]);
                self.emit_jump(Opcode::Goto, end, &[]);
                self.place_label(keep_label);
                // The prototype and the key are still under the value that was read.
                self.emit(Opcode::Nip, &[]);
                self.emit(Opcode::Nip, &[]);
                self.emit(Opcode::Nip, &[]);
                self.place_label(end);
            }
            _ => {
                self.emit(Opcode::ToPropkey, &[]);
                self.emit(Opcode::Dup3, &[]);
                self.emit(Opcode::GetSuperValue, &[]);
                self.expr(value)?;
                self.emit(compound_opcode(op), &[]);
                self.emit(Opcode::Insert4, &[]);
                self.emit(Opcode::PutSuperValue, &[]);
            }
        }
        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
        // is still on the stack when the store finishes, and the expression statement is
        // what disposes of it — the same arrangement as `put_field`, reached from the other
        // side: there the store consumes the value (`no_value`), here it leaves it
        // (`keep` already false, so nothing tells the statement otherwise).
        self.state().cur_pos = saved;
        Ok(())
    }

    /// The test a logical assignment applies to the current value.
    ///
    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
    /// assign, while `0 ||= b` must not.
    fn emit_logical_test(&mut self, op: AssignOp) {
        if op == AssignOp::Coalesce {
            self.emit(Opcode::IsUndefinedOrNull, &[]);
        }
    }

    /// The private name `#name` this use site resolves against.
    ///
    /// The parser has already rejected a name no enclosing class declares, so a miss here
    /// means the compiler lost track of a class scope — which is worth a real error rather
    /// than an `unwrap`.
    fn private_use(
        &self,
        binding: &str,
        span: Span,
    ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
        ClassPlan::find(self, binding)
            .map(|use_| (use_.kind, use_.setter.clone()))
            .ok_or_else(|| {
                SyntaxError::new(
                    format!("the private name '{binding}' is out of scope here"),
                    span,
                )
            })
    }

    /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
    ///
    /// The three readable kinds take three different instructions, because a private name
    /// holds three different things — a symbol, a method function, a getter function — and
    /// only the first one is a property read at all.
    fn private_load(
        &mut self,
        binding: &str,
        kind: PrivateKind,
        span: Span,
    ) -> Result<(), SyntaxError> {
        match kind {
            PrivateKind::Field => {
                self.emit_var(VarAction::Get, binding);
                self.emit(Opcode::GetPrivateField, &[]);
            }
            PrivateKind::Method => {
                self.emit_var(VarAction::Get, binding);
                self.emit(Opcode::CheckBrand, &[]);
                // `check_brand` reads `obj func` and leaves both; the method itself is what
                // `this.#m` evaluates to.
                self.emit(Opcode::Nip, &[]);
            }
            PrivateKind::Getter => {
                self.emit_var(VarAction::Get, binding);
                self.emit(Opcode::CheckBrand, &[]);
                self.emit(Opcode::CallMethod, &[Op::Int(0)]);
            }
            // `#a` is declared but never filled when only a setter exists, so reading it is
            // the same refusal as assigning to a `const`. The reference reports it with the
            // generic read-only wording and leaves the better message as a `XXX`.
            PrivateKind::Setter => self.emit(
                Opcode::ThrowError,
                &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
            ),
        }
        let _ = span;
        Ok(())
    }

    /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
    fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
        match kind {
            // A method *is* the callee, so only the check goes in between.
            PrivateKind::Method => {
                self.emit_var(VarAction::Get, binding);
                self.emit(Opcode::CheckBrand, &[]);
            }
            _ => self.private_load(binding, kind, Span::default())?,
        }
        Ok(())
    }

    /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
    /// wanted back.
    ///
    /// A getter/setter pair is a *method call*, not a property store: the reference reads
    /// the setter out of its own binding and calls it with the receiver, which is why the
    /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
    /// keeps the assignment's value for an expression context.
    fn private_store(
        &mut self,
        binding: &str,
        kind: PrivateKind,
        setter: Option<&str>,
    ) -> Result<(), SyntaxError> {
        match kind {
            PrivateKind::Field => {
                self.emit_var(VarAction::Get, binding);
                self.emit(Opcode::PutPrivateField, &[]);
            }
            PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
                Some(setter) => {
                    self.emit_var(VarAction::Get, setter);
                    // `obj func value` -> `value obj func` for the check, and back again for
                    // the call, which wants `obj func arg`.
                    self.emit(Opcode::Swap, &[]);
                    self.emit(Opcode::Rot3r, &[]);
                    self.emit(Opcode::CheckBrand, &[]);
                    self.emit(Opcode::Rot3l, &[]);
                    self.emit(Opcode::CallMethod, &[Op::Int(1)]);
                    // The setter's return value is discarded; the assignment's own value is
                    // whatever the caller left underneath.
                    self.emit(Opcode::Drop, &[]);
                }
                None => self.emit(
                    Opcode::ThrowError,
                    &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
                ),
            },
        }
        Ok(())
    }

    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
        let instruction = match (op, prefix) {
            (UpdateOp::Increment, true) => Opcode::Inc,
            (UpdateOp::Increment, false) => Opcode::PostInc,
            (UpdateOp::Decrement, true) => Opcode::Dec,
            (UpdateOp::Decrement, false) => Opcode::PostDec,
        };
        if let ExprKind::Member {
            object,
            property,
            optional: _,
        } = &argument.kind
        {
            // `o.x++` needs the receiver twice, so the last link is read with the
            // `get_*2`/`get_*3` form that keeps it, and the update is written back
            // with `put_field`/`put_array_el`. The reordering in between is what puts
            // the old value below the receiver for a postfix update and the new one
            // above it for a prefix one:
            //
            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
            //
            // This mirrors the reference instruction for instruction.
            self.expr(object)?;
            match property {
                MemberProp::Ident(name) => {
                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
                    self.emit(instruction, &[]);
                    self.emit(
                        if prefix {
                            Opcode::Insert2
                        } else {
                            Opcode::Perm3
                        },
                        &[],
                    );
                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
                }
                MemberProp::Computed(index) => {
                    self.expr(index)?;
                    self.emit(Opcode::GetArrayEl3, &[]);
                    self.emit(instruction, &[]);
                    self.emit(
                        if prefix {
                            Opcode::Insert3
                        } else {
                            Opcode::Perm4
                        },
                        &[],
                    );
                    self.emit(Opcode::PutArrayEl, &[]);
                }
                MemberProp::Private(name) => {
                    // The receiver is duplicated and the read keeps it, exactly as `get_field2`
                    // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
                    // `perm3` -> `old obj new` -> store.
                    let binding = format!("#{}", name.name);
                    let (kind, setter) = self.private_use(&binding, argument.span)?;
                    self.emit(Opcode::Dup, &[]);
                    self.private_load(&binding, kind, argument.span)?;
                    self.emit(instruction, &[]);
                    self.emit(
                        if prefix {
                            Opcode::Insert2
                        } else {
                            Opcode::Perm3
                        },
                        &[],
                    );
                    self.private_store(&binding, kind, setter.as_deref())?;
                }
            }
            return Ok(());
        }
        let ExprKind::Ident(name) = &argument.kind else {
            return Err(SyntaxError::new(
                "increment of a non-variable is not supported by the compiler yet",
                argument.span,
            ));
        };
        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
        // reference's `inc_loc` folds those three into one, but it does so only in some
        // positions (a `for` update and not a bare statement, and never for a lexical
        // binding), so emitting it unconditionally would move *away* from its output.
        // The instruction is equivalent either way; matching the reference matters more
        // than saving two instructions.
        let _ = !std::mem::take(&mut self.state().discard_value);
        self.emit_var(VarAction::Get, &name.name);
        self.emit(instruction, &[]);
        if prefix {
            self.emit(Opcode::Dup, &[]);
        }
        self.emit_var(VarAction::Put, &name.name);
        Ok(())
    }

    /// Compile an array literal.
    ///
    /// The reference splits this into three phases, and the split is load-bearing
    /// rather than an optimisation detail:
    ///
    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
    ///    the array in one instruction.
    /// 2. **Everything up to the first spread** is appended with explicit indices
    ///    (`define_field <index>`), because a hole has no element to pass to
    ///    `array_from`. A hole here is what makes `length` need fixing up: an
    ///    explicit index does not extend the array the way a pushed element does.
    /// 3. **From the first spread on** the index lives on the stack, so `append` and
    ///    `define_array_el` can consume it and `inc` advances it.
    ///
    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
    /// forces phase 2, and `[...a]` forces phase 3.
    fn array_literal(
        &mut self,
        elements: &[Option<ArrayElement>],
        span: Span,
    ) -> Result<(), SyntaxError> {
        let _ = span;
        let mut index: u32 = 0;
        let mut cursor = 0usize;

        // Phase 1: a leading run of plain elements, at most 32 of them.
        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
            if index >= 32 {
                break;
            }
            self.expr(element)?;
            index += 1;
            cursor += 1;
        }
        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);

        // Phase 2: explicit indices, up to the first spread.
        let mut need_length = false;
        while let Some(element) = elements.get(cursor) {
            if matches!(element, Some(ArrayElement::Spread(_))) {
                break;
            }
            need_length = true;
            if let Some(ArrayElement::Expr(expression)) = element {
                self.expr(expression)?;
                self.emit_define_index(index);
                need_length = false;
            }
            index += 1;
            cursor += 1;
        }

        if cursor >= elements.len() {
            if need_length {
                // `define_field` cannot set `length`, which is not configurable.
                self.emit(Opcode::Dup, &[]);
                self.push_number(index as f64);
                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
            }
            return Ok(());
        }

        // Phase 3: the index moves onto the stack for the spreading tail.
        //
        // `need_length` deliberately carries over from phase 2: a hole before the
        // first spread still has to be reflected in `length`, and only the final
        // check can do it because the array is not finished until the tail is
        // appended.
        self.push_number(index as f64);
        while let Some(element) = elements.get(cursor) {
            match element {
                Some(ArrayElement::Spread(expression)) => {
                    // `append` copies an iterable and leaves the next index behind,
                    // so no `inc` is needed here.
                    self.expr(spread_argument(expression))?;
                    self.emit(Opcode::Append, &[]);
                }
                None | Some(ArrayElement::Expr(_)) => {
                    need_length = true;
                    if let Some(ArrayElement::Expr(expression)) = element {
                        self.expr(expression)?;
                        self.emit(Opcode::DefineArrayEl, &[]);
                        need_length = false;
                    }
                    self.emit(Opcode::Inc, &[]);
                }
            }
            cursor += 1;
        }
        if need_length {
            self.emit(Opcode::Dup1, &[]);
            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
        } else {
            self.emit(Opcode::Drop, &[]);
        }
        Ok(())
    }

    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
    fn emit_define_index(&mut self, index: u32) {
        self.emit(
            Opcode::DefineField,
            &[Op::Atom(Atom::from_text(&index.to_string()))],
        );
    }

    // -- functions ---------------------------------------------------------

    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
        self.compile_function_with_name(func, false)
    }

    /// Compile a function, recording whether it is a *named function expression*.
    ///
    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
    /// must not leak outside. The reference does that by declaring `g` as a local of
    /// the function itself and initialising it with `special_object 2` (the current
    /// function), which is why this has to be known at compile time.
    fn compile_function_with_name(
        &mut self,
        func: &ast::Function,
        is_expression: bool,
    ) -> Result<CompiledFunction, SyntaxError> {
        let kind = match (func.is_generator, func.is_async) {
            (false, false) => FunctionKind::Normal,
            (true, false) => FunctionKind::Generator,
            (false, true) => FunctionKind::Async,
            (true, true) => FunctionKind::AsyncGenerator,
        };
        let mut state = FnState::new(
            func.name
                .as_ref()
                .map(|n| n.name.clone())
                .unwrap_or_default(),
            kind,
        );
        // The function's own mode, recorded by the parser. Inheriting the enclosing
        // function's instead let a nested `"use strict"` directive be ignored, so the
        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
        state.strict = func.strict;
        // A function defined inside a `with` block keeps seeing that object: the guard
        // chain names the enclosing `<with>` locals, which resolve outward into closure
        // variables exactly like any other captured binding.
        state.with_names = self.cur().with_names.clone();
        state.is_arrow = func.is_arrow;
        state.created_in_block = self.cur().current_block;
        // A default anywhere in the parameter list is what gives the function two
        // variable environments. The reference decides this the same way: it scans the
        // parenthesis for a top-level `=`, so a destructured name without a default
        // stays a plain function-scope binding.
        state.in_params = false;
        // The reference scans the parenthesis for *any* `=`, including one nested inside
        // a pattern, so `function f({a = 1})` has parameter expressions even though the
        // parameter itself carries no initialiser.
        state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
        // A function born inside a parameter list inherits the prohibition: it must not
        // see the body bindings of the function it was created in.
        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
        // A class constructor knows what it is only because the class told it.
        if let Some(kind) = self.cur().class_ctor_pending {
            state.ctor_kind = kind;
        }
        // A named *expression* binds its own name; a declaration's name is already
        // bound in the enclosing scope.
        state.self_name = if is_expression && !func.is_arrow {
            func.name.as_ref().map(|n| n.name.clone())
        } else {
            None
        };
        state.line = func.span.start.line;
        state.column = func.span.start.column;
        // A function body has no hidden `<ret>` local; the value comes back on
        // the stack. Only a script keeps one.
        // Parameters are positional, so even a pattern occupies one argument slot. A
        // simple name is that slot itself; anything else (a pattern, a default, a rest
        // parameter) takes an anonymous slot and is unpicked into locals at the top of
        // the body, which is the only way one argument can bind several names.
        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
        // `.length` stops at the first parameter that can be substituted: a default
        // fills a missing argument in, and a rest parameter absorbs the rest.
        let mut defined_args = func.params.len() as u32;
        for (index, param) in func.params.iter().enumerate() {
            match simple_parameter(param) {
                Some(name) => state.args.push(VarDef::var(name.name.clone())),
                None => {
                    state.args.push(VarDef::var(ANONYMOUS_BINDING));
                    prologue.push((index, param.clone()));
                }
            }
        }
        // A default anywhere before the end also ends the count, which the loop above
        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
        for (position, param) in func.params.iter().enumerate() {
            if matches!(
                param.kind,
                PatternKind::Assign { .. } | PatternKind::Rest(_)
            ) {
                defined_args = position as u32;
                break;
            }
        }
        state.defined_args = defined_args;
        state.param_prologue = prologue;
        let depth = self.stack.len();
        self.stack.push(state);
        let result = self.compile_function_body(func);
        if result.is_err() {
            // A failed compile must not leave its `FnState` behind. Every caller
            // reads `self.state()` as "the function being compiled", so a leftover
            // frame silently retargets all later bookkeeping at a dead function.
            self.stack.truncate(depth);
        }
        result
    }

    /// The body of a function, with its frame already pushed.
    fn compile_function_body(
        &mut self,
        func: &ast::Function,
    ) -> Result<CompiledFunction, SyntaxError> {
        let body_key = func.params_span.end.offset as u64;
        // Where the body begins, in source order. The runtime needs this to tell a
        // closure created by a default expression from one the body creates — the two see
        // different variable environments — and a bytecode offset would not survive the
        // instruction shuffling that building the frame does. Positions are in source
        // order, so a comparison answers it.
        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
        self.push_block(body_key, NO_PARENT);
        self.state().body_block = body_key;
        // An arrow with an expression body has no statements; the expression is
        // its `return`. Building the statement here keeps one code path below, and
        // matters for correctness beyond convenience: returning early with the new
        // `FnState` still on the stack would leave the compiler looking at the
        // wrong function, which surfaces as an unrelated underflow later.
        let concise = match &func.body {
            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
                StmtKind::Return(Some(Box::new((**value).clone()))),
                value.span,
            )),
            js_parse::ast::FunctionBody::Block(_) => None,
        };
        let body: &[Stmt] = match &concise {
            Some(stmt) => std::slice::from_ref(stmt),
            None => func
                .body
                .statements()
                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
        };
        let prologue = std::mem::take(&mut self.state().param_prologue);
        let has_param_scope = self.cur().has_parameter_expressions;
        // The parameter scope's own bindings, declared in source order.
        //
        // With parameter expressions the list gets a variable environment of its own, and
        // every name it binds is a `let` there. That is what puts the *list* in the
        // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
        // and `function f(x = y, y){}` does the same, where a single shared environment
        // would answer `undefined` to both.
        if has_param_scope {
            let mut declared: Vec<String> = Vec::new();
            for param in &func.params {
                let mut names = Vec::new();
                param.bound_names(&mut names);
                for name in names {
                    if declared.contains(&name.name) {
                        continue;
                    }
                    declared.push(name.name.clone());
                    self.declare_param_binding(&name.name);
                }
            }
        }
        // A pattern parameter binds its names as function-scope locals, so they have to
        // exist — and be unpicked from the argument — before the body runs. With a
        // parameter scope these are the *second* environment: the pattern fills the
        // parameter's copy, and the body's binding is filled from it afterwards.
        for (_, pattern) in &prologue {
            let mut names = Vec::new();
            pattern.bound_names(&mut names);
            for name in names {
                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
            }
        }
        self.hoist(body, body_key)?;
        // A constructor's prologue is not a parameter unpacking but the `this` binding:
        // a base constructor takes the receiver, a derived one starts in the dead zone
        // because only `super()` may produce it.
        match self.cur().ctor_kind {
            CtorKind::None => {}
            CtorKind::Base => {
                self.begin_this_local();
                self.emit(Opcode::CheckCtor, &[]);
                // Instance fields are installed at the top of a base constructor's body,
                // before any statement — `class C { x = 1; constructor() { this.x } }` sees
                // `1`. This used to be emitted at the *tail*, which made every field read
                // `undefined` inside the constructor that declared it.
                self.call_field_initialiser();
            }
            CtorKind::Derived => {
                self.declare("this", VarDef::lexical("this"));
                let slot = self.cur().vars.len() as u32 - 1;
                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
                self.emit(Opcode::CheckCtor, &[]);
            }
        }
        // Entering the parameter list: everything it binds starts in the dead zone.
        // The order is the reference's — it walks the scope chain, which is prepended, so
        // the bindings come out newest first.
        for name in self.param_binding_names().into_iter().rev() {
            if let Some(slot) = self.param_binding_slot(&name) {
                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
            }
        }
        // The whole parameter list is one scope, and nothing in the body exists yet, so
        // every name it mentions resolves against the parameter bindings and outward.
        self.state().in_params = has_param_scope;
        for (index, param) in func.params.iter().enumerate() {
            if let Some(pattern) = prologue_pattern(&prologue, index) {
                // A destructuring parameter *initialises* its bindings: with a parameter
                // scope they are the list's own `let`s, which is why the stores skip the
                // dead-zone check, and why the reference reads their properties with
                // `get_field2` — a `let` needs no reference.
                let kind = if has_param_scope {
                    VarDeclKind::Let
                } else {
                    VarDeclKind::Var
                };
                match &pattern.kind {
                    // `...rest` collects what is left rather than reading one slot.
                    PatternKind::Rest(inner) => {
                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
                        self.destructure(inner, Some(kind))?;
                    }
                    _ => {
                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
                        self.destructure(pattern, Some(kind))?;
                    }
                }
                continue;
            }
            // A plain name binds straight from its argument slot. With a parameter scope
            // the slot is also copied into the parameter binding, which is what a later
            // default (or a closure made among the defaults) reads.
            let Some(name) = simple_parameter(param) else {
                continue;
            };
            let target = self.param_binding_slot(&name.name);
            if matches!(param.kind, PatternKind::Rest(_)) {
                self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
                if let Some(slot) = target {
                    self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
                }
                // `put_arg` rather than `set_arg`: the array is the last thing on the
                // stack and nothing keeps it. Named by hand because a name in the
                // parameter list resolves to the parameter binding, and this store has to
                // reach the *argument* — that is what the body reads.
                self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
                continue;
            }
            if let PatternKind::Assign { default, .. } = &param.kind {
                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
                let has_value = self.new_label();
                self.emit(Opcode::Dup, &[]);
                self.emit(Opcode::IsUndefined, &[]);
                self.emit_jump(Opcode::IfFalse, has_value, &[]);
                self.emit(Opcode::Drop, &[]);
                self.expr(default)?;
                self.set_name_if_anonymous(default, &name.name);
                // The argument slot keeps the substituted value, because the *body* reads
                // the slot rather than the parameter binding — so this store is named
                // explicitly, like the rest parameter's.
                self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
                self.place_label(has_value);
                if let Some(slot) = target {
                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
                }
                continue;
            }
            if let Some(slot) = target {
                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
            }
        }
        // Copy the parameter scope into the body. A plain parameter needs nothing: the
        // body reads its argument slot, and the list kept the two in step. A name a
        // pattern bound has no argument slot of its own, so the body gets a `var` filled
        // from the parameter's copy — and *that* is why an assignment inside a default
        // does not reach the body.
        if has_param_scope {
            for (_, pattern) in &prologue {
                let mut names = Vec::new();
                pattern.bound_names(&mut names);
                for name in names {
                    let Some(slot) = self.param_binding_slot(&name.name) else {
                        continue;
                    };
                    let Some(body) = self.body_var_slot(&name.name) else {
                        continue;
                    };
                    self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
                }
            }
        }
        // The parameter list is over; from here on a direct `eval` belongs to the body.
        self.state().in_params = false;
        // Entering the body's own scope comes *after* the parameter list: the body's
        // `let`s are not in existence while the defaults run, and the reference emits
        // their `set_loc_uninitialized` only once the parameters are bound.
        self.emit_scope_enter(body_key);
        // A generator starts suspended: `initial_yield` parks the body so that creating one
        // runs no body code until the first `next()`.
        //
        // It comes *after* the parameter unpacking, not before, because a parameter
        // initialiser is not body code — `function* g(a = sideEffect())` must run
        // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
        // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
        // until the first `next()` and 29 test262 cases that check for a synchronous throw
        // saw none at all.
        //
        // An async function does **not** get one. Its body runs synchronously up to the
        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
        // before its caller's next statement — so an `initial_yield` here would park the
        // body before it started, which is not fixable at run time: the suspension looks
        // exactly like a real `await`.
        if self.cur().kind.is_generator() {
            self.emit(Opcode::InitialYield, &[]);
        }
        // Through `stmts`: the body is a block, and a `using` declaration in it is a
        // disposal region.
        self.stmts(body)?;
        // The implicit return only exists if control can actually get here: an
        // infinite loop never falls off the end.
        if self.end_is_reachable() {
            if self.cur().is_suspending() {
                // Falling off the end finishes the generator with `undefined`, and the
                // value is what tells the resume machinery "completed" rather than
                // "suspended".
                self.emit(Opcode::Undefined, &[]);
                self.emit(Opcode::ReturnAsync, &[]);
            } else {
                self.emit_class_constructor_tail();
            }
        }
        // Resolution runs while this function is still on the stack: capturing a
        // variable from an enclosing function means reaching into that
        // function's state, which requires the whole chain to be present.
        Ok(self.finish_current())
    }

    /// Put every binding of a function that contains a direct `eval` into a cell.
    ///
    /// A direct eval can name any binding in scope, and any closure it creates has to
    /// keep sharing that binding after the function returns — `for (let i …)
    /// eval("push(() => i)")` collects one closure per iteration and each must read its
    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
    /// a cell. Doing this unconditionally for such functions is the cheap, honest
    /// answer: the alternative is knowing at compile time which names a string will
    /// mention.
    fn capture_everything_for_eval(&mut self) {
        let current = self.stack.len() - 1;
        if !self.stack[current].has_direct_eval {
            return;
        }
        for arg in &mut self.stack[current].args {
            arg.is_captured = true;
        }
        for var in &mut self.stack[current].vars {
            var.is_captured = true;
        }
    }

    /// Whether the current position in the instruction stream can be reached.
    ///
    /// A walk over the control-flow graph, using labels as instruction indices.
    /// The reference does the same thing to decide whether an implicit
    /// `return_undef` is needed.
    fn end_is_reachable(&self) -> bool {
        let state = self.cur();
        reachable_instructions(state, state.insns.len())[state.insns.len()]
    }

    /// Resolve and assemble the function on top of the compiler stack, then pop
    /// it.
    fn finish_current(&mut self) -> CompiledFunction {
        self.provide_param_arguments();
        self.provide_arguments();
        self.provide_this_local();
        self.provide_new_target_local();
        self.provide_home_object_local();
        self.provide_active_func_local();
        self.provide_self_name();
        self.materialize_eval_sites();
        self.capture_everything_for_eval();
        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
        // Captured bindings need a reference cell; the count goes in the header so
        // the runtime knows how many cells to allocate on entry.
        let current = self.stack.len() - 1;
        let captured = self.stack[current]
            .args
            .iter()
            .filter(|a| a.is_captured)
            .count()
            + self.stack[current]
                .vars
                .iter()
                .filter(|v| v.is_captured)
                .count();
        self.stack[current].var_ref_count = captured as u32;
        // The scope chain is only final now that every binding is known.
        rebuild_scope_chain(&mut self.stack[current]);
        let (code, stack_size, positions) =
            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
        let _ = &mut resolved;
        let mut state = self.stack.pop().expect("a function is being compiled");
        CompiledFunction {
            name: state.name,
            kind: state.kind,
            strict: state.strict,
            is_arrow: state.is_arrow,
            has_parameter_expressions: state.has_parameter_expressions,
            body_start: state.body_start,
            args: state.args,
            defined_args: state.defined_args,
            vars: state.vars,
            closure_vars: state.closure_vars,
            cpool: state.cpool,
            atoms: state.atoms,
            code,
            stack_size,
            var_ref_count: state.var_ref_count,
            positions,
            source: None,
            line: state.line,
            column: state.column,
            filename: None,
            eval_sites: state.eval_sites,
            module: state.module.take().map(Box::new),
        }
    }
}

/// Assign each binding a scope level and rebuild the scope chains.
///
/// Levels are numbered in the order the blocks appear, with 0 reserved for the
/// function scope where `var` and hoisted functions live. Every binding outside
/// level 0 gets a `scope_next` link to the next binding visible from the same
/// point, so walking a block's chain enumerates exactly the bindings live there.
///
/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
/// point at `b`, which is declared later in the source but earlier in the chain.
fn rebuild_scope_chain(state: &mut FnState) {
    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
    // real block that happens to start at offset zero keeps its own level instead of
    // being merged into the function scope.
    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
    for block in &state.blocks {
        if !levels.contains(&block.key) {
            levels.push(block.key);
        }
    }
    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
    let parent_level = |level: usize| -> usize {
        if level == 0 {
            return 0;
        }
        let key = levels[level];
        let parent = state
            .blocks
            .iter()
            .find(|b| b.key == key)
            .map(|b| b.parent)
            .unwrap_or(FUNCTION_SCOPE);
        level_of(parent)
    };

    // Own bindings per level, in declaration order.
    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
    let keys: Vec<u64> = (0..state.vars.len())
        .map(|index| {
            state
                .var_block
                .get(index)
                .copied()
                .unwrap_or(FUNCTION_SCOPE)
        })
        .collect();
    for (index, key) in keys.into_iter().enumerate() {
        // The parameter scope is not a block: it is a level of its own with no parent,
        // assigned below. Letting it land in level 0 would chain the body's bindings onto
        // it, which the reference does not do — the two environments are siblings.
        if key == PARAM_SCOPE {
            continue;
        }
        let level = level_of(key);
        state.vars[index].scope_level = level as u32;
        // A `catch` parameter is part of the runtime scope chain even though it is
        // not lexical: the handler's own bindings chain on to it, which is why the
        // reference prints `let y [next:1]` with `e` at 1.
        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
        {
            own[level].push(index);
        }
    }

    // A scope's chain is its own bindings in reverse declaration order followed
    // by the enclosing scope's chain.
    let mut head = vec![-1i32; levels.len()];
    for level in 0..levels.len() {
        let inherited = if level == 0 {
            -1
        } else {
            head[parent_level(level)]
        };
        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
        head[level] = chain.first().map_or(inherited, |first| *first as i32);
        for (position, &index) in chain.iter().enumerate() {
            let next = chain
                .get(position + 1)
                .map_or(inherited, |next| *next as i32);
            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
        }
    }
    state.block_heads = head;

    // The parameter list is a scope of its own, and it has no parent: the reference pops
    // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
    // the `-1` a block uses. A level past every real block keeps it out of the walk above
    // — nothing but the dump reads it — and the links run newest-to-oldest through the
    // bindings themselves, which is the order `set_loc_uninitialized` walks.
    let param_level = levels.len() as u32;
    let mut previous: Option<usize> = None;
    for index in 0..state.vars.len() {
        if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
        {
            continue;
        }
        state.vars[index].scope_level = param_level;
        state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
        previous = Some(index);
    }
}

/// This is where names become slots and where the temporal dead zone shows up in
/// the instruction stream: a read of a `let`/`const` binding compiles to
/// `get_loc_check`, which throws if the binding is still uninitialised.
///
/// The peephole pass from the reference implementation is applied at the end,
/// for the same reason it is applied to resolved bytecode there: the patterns are
/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
/// resolution. Deleted instructions stay in the list as `None` so that label
/// indices remain valid; [`Assembler`] maps them to byte offsets.
/// A resolved instruction and the source position it came from.
type ResolvedInsn = Option<(Opcode, Vec<Op>)>;

/// A resolved instruction paired with its position, which is what `assemble` consumes.
type PositionedInsn = (Opcode, Vec<Op>);

fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
    let current = stack.len() - 1;
    // Dead-code elimination, on the symbolic form where labels are still
    // instruction indices. A `break` inside a loop leaves the trailing `goto`
    // unreachable, and a `return` leaves everything after it unreachable; the
    // reference drops both. Doing it here means the emitter never has to think
    // about reachability.
    strip_empty_gosubs(stack, current);
    eliminate_dead_code(stack, current);
    let insns = std::mem::take(&mut stack[current].insns);
    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
    // `insns`, and every arm below pushes exactly one instruction, so the positions
    // stay aligned with `out`.
    let positions = std::mem::take(&mut stack[current].insn_pos);
    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
    for (index, insn) in insns.iter().enumerate() {
        let pos = positions.get(index).copied().flatten();
        out_pos.push(pos);
        match insn {
            Insn::Fixed { op, operands } => {
                let operands = operands
                    .iter()
                    .map(|operand| match operand {
                        Op::Atom(atom) => {
                            Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
                        }
                        other => other.clone(),
                    })
                    .collect();
                out.push(Some((*op, operands)));
            }
            Insn::Var {
                action,
                name,
                block,
                in_params,
            } => {
                // Both reads and writes in the parameter list address the parameter
                // scope. That is what puts the list in the temporal dead zone — a read of
                // a later parameter is `get_loc_check` on an uninitialised slot — and it
                // is also what keeps an assignment made inside a default away from the
                // body, which sees a separate environment.
                let slot = resolve_slot(stack, current, name, *block, *in_params);
                // A store to the name of a named function expression is special: the
                // reference drops it in sloppy mode and throws in strict mode, because
                // the binding is immutable but only *checked* when the body is strict.
                // The same rule applies when the name is reached through a closure:
                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
                // the store in the arrow too, not just in the function that owns the
                // binding. Reaching the owner means walking the chain of closure
                // entries, which is what `self_name_binding` does.
                let self_name = matches!(action, VarAction::Put | VarAction::Set)
                    .then(|| {
                        // A local of this function is the common case and needs no
                        // chain walk; only an access that resolves elsewhere can be
                        // pointing at an enclosing function's name binding.
                        if let Slot::Loc(index) = slot {
                            stack[current]
                                .vars
                                .get(index as usize)
                                .filter(|var| var.kind == VarKind::FunctionName)
                                .map(|var| var.is_const)
                        } else {
                            self_name_binding(stack, current, name, *block)
                        }
                    })
                    .flatten();
                if let Some(is_const) = self_name {
                    out.push(Some(if is_const {
                        (
                            Opcode::ThrowError,
                            vec![
                                Op::AtomId(intern_atom(&mut stack[current], name)),
                                Op::Int(0),
                            ],
                        )
                    } else {
                        (Opcode::Drop, Vec::new())
                    }));
                    continue;
                }
                out.push(Some(variable_instruction(stack, current, *action, slot)));
            }
            Insn::CloseCaptured { name, block } => {
                // The block matters: a loop variable is scoped to the `for` head's own
                // block, so resolving it against block 0 would miss it entirely and
                // silently emit nothing.
                let slot = resolve_slot(stack, current, name, *block, false);
                // Only a local with a reference cell has anything to close. A global
                // or a never-captured local resolves to no instruction at all, which
                // keeps the bytecode identical to the reference's.
                if let Slot::Loc(index) = slot
                    && stack[current]
                        .vars
                        .get(index as usize)
                        .is_some_and(|v| v.is_captured)
                {
                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
                } else {
                    out.push(None);
                }
            }
            Insn::DeleteVar { name } => {
                // A binding — a local, an argument, or a declared global — cannot be
                // deleted, and the reference encodes that as a constant `push_false`.
                // Only an implicit global needs the runtime lookup.
                if matches!(
                    resolve_slot(stack, current, name, 0, false),
                    Slot::Global(_)
                ) {
                    let atom = intern_atom(&mut stack[current], name);
                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
                } else {
                    out.push(Some((Opcode::PushFalse, Vec::new())));
                }
            }
            Insn::Dead => out.push(None),
        }
    }
    // Which label (if any) sits on each instruction, so the jump patterns can
    // tell whether they would cross a jump target.
    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
    for (id, placed) in stack[current].labels.iter().enumerate() {
        if let Some(index) = *placed
            && index < label_at.len()
            && label_at[index].is_none()
        {
            label_at[index] = Some(id as u32);
        }
    }
    if std::env::var_os("QJS_DEBUG").is_some() {
        eprintln!("--- peephole entry ---");
        for (i, e) in out.iter().enumerate() {
            eprintln!("{i}: {e:?}");
        }
        eprintln!("label_at: {label_at:?}");
    }
    peephole(&mut out, &label_at, &stack[current].labels);
    (out, out_pos)
}

/// Find where `name` lives, capturing it in an enclosing function when needed.
///
/// The search runs outward through the enclosing functions' states, which are
/// still on the compiler stack while a nested function is resolved. Finding the
/// name in an enclosing function is what creates a closure reference, and every
/// function in between has to forward it — a function can only reach its own
/// parent's frame.
///
/// A name declared nowhere is a global. The reference does *not* look it up by
/// name from the inner function: the top-level function gets one `[global]`
/// entry and every nested function gets a `[global_ref<n>]` pointing at its
/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
/// rather than `[global]`.
/// The lexical blocks enclosing `block`, innermost first.
fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
    let mut chain = Vec::new();
    let mut current = Some(block);
    while let Some(key) = current {
        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
        // explicitly (rather than on "no block with this key") is what keeps a block
        // that happens to sit at offset zero from being mistaken for the terminator.
        if key == NO_PARENT || chain.contains(&key) {
            break;
        }
        chain.push(key);
        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
    }
    chain
}

/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
///
/// The binding may be several functions away: an arrow nested in `function myfunc`
/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
/// means following `Ref` entries down and then reading the owning function's var table.
fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
    let state = stack.get(current)?;
    // A parameter shadows everything and is never a function-expression name.
    if state.args.iter().any(|arg| arg.name == name) {
        return None;
    }
    // A local of this very function: the answer is in its var table.
    if let Some(index) = local_slot_index(state, name, block) {
        let var = state.vars.get(index)?;
        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
    }
    // Otherwise the name lives further out, and the closure entry says how to get
    // there. `Local` names the owner's slot directly; `Ref` names the next level's
    // closure entry, so the walk continues downwards.
    let mut level = current;
    let mut index = state
        .closure_vars
        .iter()
        .position(|closure| closure.name == name)?;
    loop {
        let state = stack.get(level)?;
        let closure = state.closure_vars.get(index)?;
        match closure.closure_type {
            ClosureType::Local => {
                let owner = stack.get(level.checked_sub(1)?)?;
                let var = owner.vars.get(closure.var_idx as usize)?;
                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
            }
            ClosureType::Arg => return None,
            ClosureType::Ref => {
                level -= 1;
                index = closure.var_idx as usize;
            }
            // A global is never a function-expression name.
            ClosureType::Global
            | ClosureType::GlobalDecl
            | ClosureType::GlobalRef
            | ClosureType::ModuleDecl
            | ClosureType::ModuleImport => return None,
        }
    }
}

/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
    block_chain(state, block).into_iter().find_map(|scope| {
        state.vars.iter().enumerate().find_map(|(index, var)| {
            (var.name == name && state.var_block.get(index).copied() == Some(scope))
                .then_some(index)
        })
    })
}

/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
    }) {
        return index as u32;
    }
    state.var_block.push(PARAM_SCOPE);
    state.vars.push(VarDef::var(name));
    state.vars.len() as u32 - 1
}

/// The name a parameter binds straight from its argument slot, if it has one.
///
/// A plain name does — with or without a default, and with or without `...`. Everything
/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
/// reference names the argument in the first case and leaves it `<null>` in the second,
/// so both the dump and the closures that capture the argument depend on this.
fn simple_parameter(param: &Pattern) -> Option<&Ident> {
    match &param.kind {
        PatternKind::Ident(name) => Some(name),
        PatternKind::Assign { target, .. } => match &target.kind {
            PatternKind::Ident(name) => Some(name),
            _ => None,
        },
        PatternKind::Rest(inner) => match &inner.kind {
            PatternKind::Ident(name) => Some(name),
            _ => None,
        },
        _ => None,
    }
}

/// The pattern a parameter list has to unpick, if `index` is one of them.
fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
    prologue
        .iter()
        .find(|(at, _)| *at == index)
        .map(|(_, pattern)| pattern)
}

/// Whether a parameter pattern contains a default anywhere, at any depth.
///
/// The reference decides "this function has parameter expressions" by scanning the
/// parenthesis for a top-level `=`, which a default buried in a pattern still counts as —
/// `function f({a = 1})` has a parameter scope just like `function f(a = 1)`.
fn pattern_has_default(pattern: &Pattern) -> bool {
    match &pattern.kind {
        PatternKind::Assign { .. } => true,
        PatternKind::Rest(inner) => pattern_has_default(inner),
        PatternKind::Array { elements, rest } => {
            elements.iter().flatten().any(element_has_default)
                || rest.as_deref().is_some_and(rest_has_default)
        }
        PatternKind::Object { properties, rest } => {
            properties.iter().flatten().any(element_has_default)
                || rest.as_deref().is_some_and(rest_has_default)
        }
        _ => false,
    }
}

fn element_has_default(element: &PatternElement) -> bool {
    match element {
        PatternElement::Pattern(pattern) => pattern_has_default(pattern),
        PatternElement::Property { value, .. } => pattern_has_default(value),
    }
}

fn rest_has_default(rest: &RestElement) -> bool {
    match rest {
        RestElement::Pattern(pattern) => pattern_has_default(pattern),
        RestElement::Member(_) => false,
    }
}

/// Whether a function-scope binding is visible to the parameter list.
///
/// The parameter list runs before the body, so the body's `var`s and function
/// declarations do not exist yet — a name that only the body declares has to resolve
/// outward instead. What *does* exist by then is the compiler's own prologue: the
/// self-name of a named function expression (bound by `special_object 2` before anything
/// else), `this` and `new.target`. Those stay visible, which is what makes
/// `function f(a = this)` and `var f = function f(a = f)` work.
///
/// `arguments` is handled separately, as a binding of the parameter scope itself: with
/// parameter expressions the reference creates two of them, and the one the parameter
/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
fn visible_in_params(var: &VarDef) -> bool {
    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
}

fn resolve_slot(
    stack: &mut [FnState],
    current: usize,
    name: &str,
    block: u64,
    in_params: bool,
) -> Slot {
    // The parameter list's own bindings. They are consulted first because they shadow
    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
    // `a` in the parameter scope, so a closure made there reads the parameter even after
    // the body assigns to its own `a`.
    if in_params
        && let Some(index) = stack[current]
            .vars
            .iter()
            .enumerate()
            .position(|(index, var)| {
                var.name == name
                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
            })
    {
        return Slot::Loc(index as u32);
    }
    // A name can be bound more than once: two `catch` parameters in nested
    // handlers are two slots. The binding that wins is the one whose scope encloses
    // the access, and among those the innermost — so the blocks are walked outward
    // and the first binding found on the way is the one that counts. A binding in
    // no block (`var`) is reachable from anywhere, which is why the function scope
    // is the end of the walk.
    //
    // The block walk comes *before* the argument slots, because a block may shadow a
    // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
    // slot is only the answer once nothing nearer claims the name.
    let chain = block_chain(&stack[current], block);
    for scope in &chain {
        let found = stack[current]
            .vars
            .iter()
            .enumerate()
            .find(|(index, var)| {
                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
            })
            .map(|(index, _)| index);
        if let Some(index) = found {
            return Slot::Loc(index as u32);
        }
    }
    // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
    // its own slot, and `var` of the same name in the body is the same binding.
    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
        return Slot::Arg(index as u32);
    }
    // Function-scope bindings — `var` and function declarations — are recorded with
    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
    // them. They are reachable from anywhere in the function, which is exactly what
    // the sentinel means.
    //
    // This pass is *only* for those. A lexical binding has to be found through the
    // chain or not at all, and looking a name up without its block is precisely how
    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
    // block leaked out of it.
    let function_scoped = stack[current]
        .vars
        .iter()
        .enumerate()
        .find(|(index, var)| {
            var.name == name
                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
                && (!in_params || visible_in_params(var))
        })
        .map(|(index, _)| index);
    if let Some(index) = function_scoped {
        return Slot::Loc(index as u32);
    }
    if let Some(index) = stack[current]
        .closure_vars
        .iter()
        .position(|c| c.name == name)
    {
        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
    }

    for owner in (0..current).rev() {
        // The nested function was created inside one of this frame's blocks, and the
        // outermost visible binding is the innermost block on that chain — not whatever
        // comes first in the variable table. `function f(){ class S{} }` has two `S`
        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
        // the class body is the one a method may see.
        let entry = stack
            .get(owner + 1)
            .map(|s| s.created_in_block)
            .unwrap_or(0);
        let lexical = block_chain(&stack[owner], entry)
            .into_iter()
            .find_map(|scope| {
                stack[owner]
                    .vars
                    .iter()
                    .enumerate()
                    .find(|(index, var)| {
                        var.name == name
                            && stack[owner].var_block.get(*index).copied() == Some(scope)
                    })
                    .map(|(index, _)| index)
            });
        // A function born in a parameter list sees that list's bindings, not the body's:
        // the parameter scope is the environment it was created in.
        let in_param_scope = stack
            .get(owner + 1)
            .is_some_and(|child| child.created_in_params)
            .then(|| {
                stack[owner]
                    .vars
                    .iter()
                    .enumerate()
                    .position(|(index, var)| {
                        var.name == name
                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
                    })
            })
            .flatten();
        let found = if let Some(index) = in_param_scope {
            let var = &stack[owner].vars[index];
            Some(Found::Local(
                ClosureType::Local,
                index as u32,
                var.is_const,
                var.needs_check(),
            ))
        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
        } else if let Some(index) = lexical {
            let var = &stack[owner].vars[index];
            Some(Found::Local(
                ClosureType::Local,
                index as u32,
                var.is_const,
                var.needs_check(),
            ))
        } else if let Some(index) = stack[owner]
            .vars
            .iter()
            .enumerate()
            .find_map(|(index, var)| {
                // A function created inside a parameter list must not see the body of the
                // function it was born in; see [`FnState::created_in_params`].
                let hidden = stack
                    .get(owner + 1)
                    .is_some_and(|child| child.created_in_params);
                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
            })
        {
            let var = &stack[owner].vars[index];
            Some(Found::Local(
                ClosureType::Local,
                index as u32,
                var.is_const,
                var.needs_check(),
            ))
        } else if stack[owner].self_name.as_deref() == Some(name) {
            // A named function expression's own name. The reference declares it here,
            // on the first lookup that fails, rather than up front — and that is what
            // makes it reachable from a *nested* function: the nested lookup is what
            // walks out and creates the binding. A direct reference in the body is
            // caught the same way, which is why `provide_self_name` only has to add
            // the prologue.
            let strict = stack[owner].strict;
            stack[owner].var_block.push(FUNCTION_SCOPE);
            stack[owner].vars.push(VarDef {
                kind: VarKind::FunctionName,
                // In strict mode the name is immutable, so a store raises; sloppy
                // mode drops the store instead (see `variable_instruction`).
                is_const: strict,
                ..VarDef::var(name)
            });
            let index = stack[owner].vars.len() as u32 - 1;
            Some(Found::Local(ClosureType::Local, index, strict, false))
        } else if let Some(index) = stack[owner]
            .closure_vars
            .iter()
            .position(|c| c.name == name)
        {
            let closure = &stack[owner].closure_vars[index];
            Some(match closure.closure_type {
                // `GlobalRef` belongs here too: it is a *global* reached through this
                // frame's reference table, so treating it as a `Ref` to a local cell makes
                // the reader look for a cell no frame ever fills. That is how a second
                // function using `eval` in its parameter list read `undefined` after a
                // sibling had already made `eval` a closure entry.
                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
                    Found::Global(index as u32)
                }
                // A module variable is a cell in the *module's* environment, which is
                // the module body's parent as far as a nested function is concerned — so
                // it is captured as a plain reference, not looked up as a global.
                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
                    ClosureType::Ref,
                    index as u32,
                    closure.is_const,
                    closure.is_lexical,
                ),
                _ => Found::Local(
                    ClosureType::Ref,
                    index as u32,
                    closure.is_const,
                    closure.is_lexical,
                ),
            })
        } else {
            None
        };
        let Some(found) = found else { continue };

        let (is_const, is_lexical) = match found {
            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
            Found::Global(_) => (false, false),
        };
        // Mark the owner's binding as captured so it moves into a reference cell.
        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
            let slot = match found {
                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
                _ => &mut stack[owner].vars[index as usize],
            };
            slot.is_captured = true;
        }
        // Forward the reference through every function in between.
        let mut previous = match found {
            Found::Local(kind, index, _, _) => (kind, index),
            Found::Global(index) => (ClosureType::Global, index),
        };
        for level in owner + 1..=current {
            let kind = match (previous.0, level) {
                // A global stays a global at *every* level. Without `GlobalRef` in
                // this arm the second nested function over the same global got a
                // `Ref` to a cell no frame ever held, so the innermost closure read
                // `undefined` — which is how a two-deep getter lost its outer
                // variable.
                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
                    ClosureType::GlobalRef
                }
                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
                _ => ClosureType::Ref,
            };
            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
            previous = (kind, index);
        }
        let index = previous.1;
        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
    }

    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
    // creating a property. The top-level function holds the entry.
    let mut previous = (
        ClosureType::Global,
        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
    );
    for level in 1..=current {
        let index = ensure_closure(
            stack,
            level,
            name,
            false,
            false,
            ClosureType::GlobalRef,
            previous.1,
        );
        previous = (ClosureType::GlobalRef, index);
    }
    Slot::Global(previous.1)
}

/// What an outward search turned up.
#[derive(Debug, Clone, Copy)]
enum Found {
    /// A binding in an enclosing function, reachable through a closure of this
    /// type, with its const/lexical flags.
    Local(ClosureType, u32, bool, bool),
    /// A global, reached through the enclosing function's closure entry.
    Global(u32),
}

/// Add a closure entry to `level` if it is not there yet.
fn ensure_closure(
    stack: &mut [FnState],
    level: usize,
    name: &str,
    is_const: bool,
    is_lexical: bool,
    closure_type: ClosureType,
    var_idx: u32,
) -> u32 {
    if let Some(index) = stack[level]
        .closure_vars
        .iter()
        .position(|c| c.name == name)
    {
        return index as u32;
    }
    stack[level].closure_vars.push(ClosureVar {
        name: name.to_string(),
        is_const,
        is_lexical,
        closure_type,
        var_idx: var_idx as u16,
    });
    stack[level].closure_vars.len() as u32 - 1
}

fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
    match closure.closure_type {
        // A `global_ref` only says *how* the binding is found (through the
        // parent's closure table); the access itself is an ordinary global one.
        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
        // A module variable is a real cell in the module's environment, so it is reached
        // exactly like a captured local — the host, not the global object, is what fills
        // the slot.
        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
        _ => Slot::VarRef(index),
    }
}

/// Pick the opcode for one variable access.
///
/// The `_check` variants are what enforce the temporal dead zone. They are used
/// for every access to a `let`/`const` binding except its own initialisation —
/// which is exactly the operation that takes the binding out of the dead zone.
fn variable_instruction(
    stack: &[FnState],
    current: usize,
    action: VarAction,
    slot: Slot,
) -> (Opcode, Vec<Op>) {
    let lexical = match slot {
        Slot::Loc(index) => stack[current]
            .vars
            .get(index as usize)
            .is_some_and(|v| v.needs_check()),
        Slot::VarRef(index) => stack[current]
            .closure_vars
            .get(index as usize)
            .is_some_and(|c| c.is_lexical),
        _ => false,
    };
    let operand = vec![Op::Slot(slot)];
    match (action, slot) {
        (VarAction::Get, Slot::Loc(index)) => (
            if lexical {
                Opcode::GetLocCheck
            } else {
                Opcode::GetLoc
            },
            vec![Op::Slot(Slot::Loc(index))],
        ),
        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
        (VarAction::Get, Slot::VarRef(index)) => (
            if lexical {
                Opcode::GetVarRefCheck
            } else {
                Opcode::GetVarRef
            },
            vec![Op::Slot(Slot::VarRef(index))],
        ),
        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
        (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
        (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
            (Opcode::GetVarUndef, operand)
        }

        (VarAction::Put, Slot::Loc(_)) => (
            if lexical {
                Opcode::PutLocCheck
            } else {
                Opcode::PutLoc
            },
            operand,
        ),
        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
        (VarAction::Put, Slot::VarRef(_)) => (
            if lexical {
                Opcode::PutVarRefCheck
            } else {
                Opcode::PutVarRef
            },
            operand,
        ),
        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
        // Initialisation is what ends the dead zone, so it never checks.
        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
        // `this` in a derived constructor is always a local, so these cannot happen;
        // routing them to the ordinary forms keeps the match total without inventing
        // opcodes the reference does not have.
        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
            (Opcode::PutVarInit, operand)
        }
        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
            (Opcode::PutVarInit, operand)
        }
        (VarAction::Set, Slot::Loc(_)) => (
            if lexical {
                Opcode::SetLocCheck
            } else {
                Opcode::SetLoc
            },
            operand,
        ),
        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
    }
}

/// The instruction-rewriting pass.
///
/// These are the reference implementation's patterns, restricted to the ones the
/// constructs this compiler supports can produce. Each entry is a comment on the
/// bytecode it removes, because the whole point is that the result is one
/// instruction shorter than the literal translation of the AST.
fn peephole(
    insns: &mut [Option<(Opcode, Vec<Op>)>],
    label_at: &[Option<u32>],
    placed: &[Option<usize>],
) {
    fold_dup_patterns(insns, label_at);

    // `drop` before `return_undef` is dead: the return discards the whole frame
    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
    // consumes its own `drop`; removing the drop first would leave the `dup` and
    // produce a `set_` where the reference has a `put_`.
    for index in 0..insns.len() {
        if opcode_at(insns, index) != Some(Opcode::Drop) {
            continue;
        }
        // Skip over a run of drops, but stop at a jump target: removing code on
        // one side of a label would silently retarget the jump.
        let mut next = index + 1;
        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
            next += 1;
        }
        if is_label_at(label_at, next) {
            continue;
        }
        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
            for entry in &mut insns[index..next] {
                *entry = None;
            }
        }
    }

    // The rewrites below all decide against one fixed snapshot, which is what the
    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
    // the pass, so a rule never observes what an earlier rule removed. Gathering
    // every deletion first and applying them together reproduces that.
    let snapshot: Vec<Option<Opcode>> = insns
        .iter()
        .map(|entry| entry.as_ref().map(|(op, _)| *op))
        .collect();
    // The next instruction that is still there. Holes left by dead-code
    // elimination are not instructions, so a rule looks past them.
    let next_op = |index: usize| -> Option<usize> {
        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
    };

    let mut doomed = vec![false; insns.len()];
    for index in 0..insns.len() {
        // A constant pushed only to be dropped does nothing at all. This is what a
        // comma expression with a literal left operand compiles to — `(0, f)()` — and
        // the reference removes the pair rather than making the reader step over it.
        let constant = matches!(
            snapshot[index],
            Some(
                Opcode::Undefined
                    | Opcode::Null
                    | Opcode::PushMinus1
                    | Opcode::Push0
                    | Opcode::Push1
                    | Opcode::Push2
                    | Opcode::Push3
                    | Opcode::Push4
                    | Opcode::Push5
                    | Opcode::Push6
                    | Opcode::Push7
                    | Opcode::PushTrue
                    | Opcode::PushFalse
                    | Opcode::PushI32
            )
        );
        if constant
            && let Some(next) = next_op(index)
            && snapshot[next] == Some(Opcode::Drop)
        {
            doomed[index] = true;
            doomed[next] = true;
        }
    }
    for (index, entry) in insns.iter_mut().enumerate() {
        if doomed[index] {
            *entry = None;
        }
    }

    // A conditional whose destination is the very next instruction just pops its
    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
    // compiles to.
    //
    // Order matters, and it is the reference's order: this runs *before* the
    // folding below, on the instruction the conditional originally had. Folding
    // moves a conditional's destination, and the reference never re-examines it
    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
    // a conditional even though folding leaves it pointing at the next
    // instruction.
    for (index, entry) in insns.iter_mut().enumerate() {
        let Some((op, operands)) = entry.clone() else {
            continue;
        };
        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
            continue;
        }
        let Some(id) = label_id(&operands) else {
            continue;
        };
        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
            *entry = Some((Opcode::Drop, Vec::new()));
        }
    }

    // A constant condition is decided here rather than at run time.
    fold_constant_conditions(insns);
    // The conditional folding below is about pairs of *real* branches, so it runs
    // before a jump to the next instruction is dropped: `do { … if (c) continue }
    // while (t)` puts `continue` exactly on the condition, and the reference inverts
    // the branch first and only then notices the jump goes nowhere.
    fold_conditional_jumps(insns, label_at, placed);

    // A jump whose destination is the very next instruction does nothing, which is
    // what constant folding leaves behind for `while (1) { … }`.
    remove_jump_to_next(insns, placed);

    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
    // a use of the same variable boils down to.
    for index in 0..insns.len() {
        let Some((put_op, _)) = insns[index].clone() else {
            continue;
        };
        if !is_foldable_put(put_op) {
            continue;
        }
        if is_label_at(label_at, index + 1) {
            continue;
        }
        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
            continue;
        };
        if get_op != get_form_of(put_op) {
            continue;
        }
        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
            continue;
        }
        insns[index] = Some((set_form_of(put_op), get_operands));
        insns[index + 1] = None;
    }
}

/// Drop `gosub`s that call an empty subroutine.
///
/// A `gosub` whose target starts with `ret` returns immediately, so the reference
/// drops the call. This is how `try`/`catch` without a `finally` loses its
/// finalizer plumbing: the finalizer block is empty, its first instruction is
/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
/// [`eliminate_dead_code`] then removes.
fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
    let state = &stack[current];
    let mut targets = Vec::new();
    for insn in &state.insns {
        if let Insn::Fixed { op, operands } = insn
            && *op == Opcode::Gosub
            && let Some(id) = label_id(operands)
            && let Some(target) = state.labels.get(id as usize).copied().flatten()
        {
            targets.push(target);
        }
    }
    let empty: Vec<usize> = targets
        .into_iter()
        .filter(|target| {
            stack[current]
                .insns
                .get(*target)
                .map(|insn| {
                    matches!(
                        insn,
                        Insn::Fixed {
                            op: Opcode::Ret,
                            ..
                        }
                    )
                })
                .unwrap_or(false)
        })
        .collect();
    if empty.is_empty() {
        return;
    }
    for insn in stack[current].insns.iter_mut() {
        if let Insn::Fixed { op, operands } = insn
            && *op == Opcode::Gosub
            && let Some(id) = label_id(operands)
            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
            && empty.contains(&target)
        {
            *insn = Insn::Dead;
        }
    }
}

/// Replace unreachable instructions with [`Insn::Dead`].
fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
        if !reachable[index] {
            *insn = Insn::Dead;
        }
    }
}

/// Mark every instruction index reachable from the entry, plus the index one past
/// the last instruction.
///
/// `seen[len]` answers "can control reach the end of this function", and the
/// entries before it identify dead code. Both DCE and the implicit-return decision
/// read the same result, which keeps them from disagreeing.
fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
    let mut seen = vec![false; count + 1];
    let mut worklist = vec![0usize];
    while let Some(index) = worklist.pop() {
        if index > count || seen[index] {
            continue;
        }
        seen[index] = true;
        if index == count {
            continue;
        }
        let (op, operands) = match &state.insns[index] {
            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
            // A variable access never transfers control, and a removed
            // instruction is only reachable if it is already marked.
            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
                worklist.push(index + 1);
                continue;
            }
        };
        match op {
            // A return, a throw and a `ret` all leave this instruction stream: the
            // first two give control to the caller or the handler, and `ret`
            // returns to a `gosub` elsewhere.
            // A tail call leaves the function too: the callee's result becomes this
            // function's result, so nothing after it runs.
            Opcode::Return
            | Opcode::ReturnUndef
            | Opcode::ReturnAsync
            | Opcode::TailCall
            | Opcode::TailCallMethod
            | Opcode::Throw
            | Opcode::ThrowError
            | Opcode::Ret => {}
            // A `catch` records where exceptions from the code that follows go.
            // That code is not reachable through normal control flow, but it is
            // reachable — through the exception edge — so the walk has to follow
            // it, or dead-code elimination would delete every handler.
            Opcode::Catch => {
                if let Some(target) = placed_label(state, operands) {
                    worklist.push(target);
                }
                worklist.push(index + 1);
            }
            // A `gosub` calls a subroutine and then continues, so both edges count.
            Opcode::Gosub => {
                if let Some(target) = placed_label(state, operands) {
                    worklist.push(target);
                }
                worklist.push(index + 1);
            }
            Opcode::Goto => {
                if let Some(target) = placed_label(state, operands) {
                    worklist.push(target);
                }
            }
            Opcode::IfTrue | Opcode::IfFalse => {
                if let Some(target) = placed_label(state, operands) {
                    worklist.push(target);
                }
                worklist.push(index + 1);
            }
            _ => worklist.push(index + 1),
        }
    }
    seen
}

/// The instruction index a jump operand points at, resolved through the label
/// placement table.
fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
    let id = label_id(operands)?;
    state.labels.get(id as usize).copied().flatten()
}

/// The label an instruction refers to.
fn label_id(operands: &[Op]) -> Option<u32> {
    operands.iter().find_map(|operand| match operand {
        Op::Label(label) => Some(label.0),
        _ => None,
    })
}

/// Turn `if_false L; goto M; L:` into `if_true M`.
///
/// A conditional whose alternate branch is an unconditional jump needs one jump,
/// not two. This is the shape `if (c) break;` produces, so folding it removes an
/// instruction and a label from every conditional `break`.
/// The boolean a constant-push instruction produces, or `None` if it is not one.
///
/// Only the operators whose truthiness is decided by the opcode are covered; a
/// constant that needs the constant pool (a string) is left alone, because reading it
/// would mean threading the pool through the peephole for a case the reference also
/// skips.
fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
    match op {
        // `push_0` returns -1 for zero, `push_1` 1, and so on.
        Opcode::PushMinus1 => Some(true),
        Opcode::Push0 => Some(false),
        Opcode::Push1
        | Opcode::Push2
        | Opcode::Push3
        | Opcode::Push4
        | Opcode::Push5
        | Opcode::Push6
        | Opcode::Push7 => Some(true),
        Opcode::PushTrue => Some(true),
        Opcode::PushFalse => Some(false),
        Opcode::Undefined | Opcode::Null => Some(false),
        Opcode::PushI32 => match operands.first() {
            Some(Op::Int(value)) => Some(*value != 0),
            _ => None,
        },
        _ => None,
    }
}

/// Fold a branch on a constant condition.
///
/// `if (0) a() else b()` must not test anything at run time, and the reference
/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
/// which is why the bytecode for a `while (1)` loop has no condition at all.
///
/// Two instructions become one, so the slot the test occupied is left empty rather
/// than shifting everything after it: labels have already been resolved to indices.
fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
    for index in 0..insns.len() {
        let Some((push_op, push_operands)) = insns[index].clone() else {
            continue;
        };
        let Some(truth) = constant_truth(push_op, &push_operands) else {
            continue;
        };
        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
            continue;
        };
        let (destination, taken) = match branch_op {
            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
            _ => continue,
        };
        let Some(destination) = destination else {
            continue;
        };
        insns[index] = if taken {
            // The branch is always taken, so it becomes an unconditional jump.
            Some((Opcode::Goto, vec![destination]))
        } else {
            // The branch never runs: both instructions disappear and control falls
            // through to what came after.
            None
        };
        insns[index + 1] = None;
    }
}

/// Remove a jump whose destination is the instruction right after it.
///
/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
/// its test into nothing, and the loop-end jump then points at the following
/// instruction. The reference drops them, so `stack_size` and the listing agree.
fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
    for index in 0..insns.len() {
        let Some((op, operands)) = insns[index].clone() else {
            continue;
        };
        if !is_goto(op) {
            continue;
        }
        let Some(id) = label_id(&operands) else {
            continue;
        };
        // The next instruction that still exists, which is what "the instruction
        // after this jump" means once earlier folds have punched holes.
        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
        if placed.get(id as usize).copied().flatten() == next {
            insns[index] = None;
        }
    }
}

fn fold_conditional_jumps(
    insns: &mut [Option<(Opcode, Vec<Op>)>],
    label_at: &[Option<u32>],
    placed: &[Option<usize>],
) {
    for index in 0..insns.len() {
        let Some((op, operands)) = insns[index].clone() else {
            continue;
        };
        let inverted = match op {
            Opcode::IfFalse => Opcode::IfTrue,
            Opcode::IfTrue => Opcode::IfFalse,
            _ => continue,
        };
        // Next must be an unconditional jump that is not itself a target, and the
        // instruction after it must be exactly where the conditional goes.
        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
            continue;
        };
        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
            continue;
        }
        // The conditional must land on the instruction *after* the jump. Several
        // labels can share a position, so this asks where *this* label was put
        // rather than what label happens to sit there.
        let Some(taken) = label_id(&operands) else {
            continue;
        };
        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
            continue;
        }
        let Some(destination) = next_operands.first().cloned() else {
            continue;
        };
        insns[index] = Some((inverted, vec![destination]));
        insns[index + 1] = None;
    }
}

/// Whether a jump target is placed at this instruction index.
fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
    label_at.get(index).copied().flatten().is_some()
}

fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
    // `dup put_x(n)` -> `set_x(n)`
    // `dup put_x(n) drop` -> `put_x(n)`
    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
    for index in 0..insns.len() {
        if opcode_at(insns, index) != Some(Opcode::Dup) {
            continue;
        }
        if is_label_at(label_at, index + 1) {
            continue;
        }
        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
            continue;
        };
        if !is_foldable_put(put_op) {
            continue;
        }
        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
            continue;
        };
        let mut new_op = set_form_of(put_op);
        let mut end = index + 2;
        if is_label_at(label_at, end) {
            // The `put` has to stay as it is; only the `dup` can be folded.
            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
            insns[index + 1] = None;
            continue;
        }
        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
        // Deleting it moves the label's target onto whatever follows, and the code that
        // jumps there arrives with a different stack than the fall-through path: that is
        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
        // an empty stack. The store had already consumed the value it was supposed to
        // leave behind.
        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
            new_op = put_op;
            end += 1;
            if opcode_at(insns, end) == Some(get_form_of(put_op))
                && !is_label_at(label_at, end)
                && insns[end]
                    .as_ref()
                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
            {
                new_op = set_form_of(put_op);
                end += 1;
            }
        }
        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
        for entry in &mut insns[index + 1..end] {
            *entry = None;
        }
    }
}

fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
    insns
        .get(index)
        .and_then(|entry| entry.as_ref())
        .map(|(op, _)| *op)
}

/// The four `put_` families that have a `set_` twin. Deliberately not including
/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
/// these, and folding the others would produce instructions that do not exist.
fn is_foldable_put(op: Opcode) -> bool {
    matches!(
        op,
        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
    )
}

fn set_form_of(op: Opcode) -> Opcode {
    match op {
        Opcode::PutLoc => Opcode::SetLoc,
        Opcode::PutLocCheck => Opcode::SetLocCheck,
        Opcode::PutArg => Opcode::SetArg,
        Opcode::PutVarRef => Opcode::SetVarRef,
        other => other,
    }
}

fn get_form_of(op: Opcode) -> Opcode {
    match op {
        Opcode::PutLoc => Opcode::GetLoc,
        Opcode::PutLocCheck => Opcode::GetLocCheck,
        Opcode::PutArg => Opcode::GetArg,
        Opcode::PutVarRef => Opcode::GetVarRef,
        other => other,
    }
}

/// Atom interning, per function.
///
/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
/// identifiers, so the array-index rule applies here rather than at the handful of
/// call sites that build property keys.
fn intern_atom(state: &mut FnState, name: &str) -> u32 {
    intern_atom_value(state, Atom::from_text(name))
}

/// [`intern_atom`] for an operand that is already an [`Atom`].
///
/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
/// would have looked up.
fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
        return index as u32;
    }
    state.atoms.push(atom);
    state.atoms.len() as u32 - 1
}

fn binary_opcode(op: BinaryOp) -> Opcode {
    match op {
        BinaryOp::Add => Opcode::Add,
        BinaryOp::Sub => Opcode::Sub,
        BinaryOp::Mul => Opcode::Mul,
        BinaryOp::Div => Opcode::Div,
        BinaryOp::Mod => Opcode::Mod,
        BinaryOp::Pow => Opcode::Pow,
        BinaryOp::BitOr => Opcode::Or,
        BinaryOp::BitXor => Opcode::Xor,
        BinaryOp::BitAnd => Opcode::And,
        BinaryOp::Shl => Opcode::Shl,
        BinaryOp::Shr => Opcode::Sar,
        BinaryOp::UShr => Opcode::Shr,
        BinaryOp::Lt => Opcode::Lt,
        BinaryOp::LtEq => Opcode::Lte,
        BinaryOp::Gt => Opcode::Gt,
        BinaryOp::GtEq => Opcode::Gte,
        BinaryOp::Eq => Opcode::Eq,
        BinaryOp::NotEq => Opcode::Neq,
        BinaryOp::StrictEq => Opcode::StrictEq,
        BinaryOp::StrictNotEq => Opcode::StrictNeq,
        BinaryOp::In => Opcode::In,
        BinaryOp::Instanceof => Opcode::Instanceof,
    }
}

fn compound_opcode(op: AssignOp) -> Opcode {
    match op {
        AssignOp::Add => Opcode::Add,
        AssignOp::Sub => Opcode::Sub,
        AssignOp::Mul => Opcode::Mul,
        AssignOp::Div => Opcode::Div,
        AssignOp::Mod => Opcode::Mod,
        AssignOp::Pow => Opcode::Pow,
        AssignOp::Shl => Opcode::Shl,
        AssignOp::Shr => Opcode::Sar,
        AssignOp::UShr => Opcode::Shr,
        AssignOp::BitOr => Opcode::Or,
        AssignOp::BitXor => Opcode::Xor,
        AssignOp::BitAnd => Opcode::And,
        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
    }
}

/// Encode the resolved instruction stream, choosing short forms where possible.
///
/// The peephole pass leaves holes in the instruction list so that label indices
/// stay valid. A label names an *instruction index*, and an index that was
/// deleted has to resolve to the next surviving instruction, which is what
/// [`resolve_label`] does before the byte offsets are known.
fn assemble(
    insns: &mut [Option<(Opcode, Vec<Op>)>],
    insn_pos: &[Option<Position>],
    state: &mut FnState,
) -> (Vec<u8>, u32, Vec<LineCol>) {
    // Compaction: surviving instructions in order, plus the index mapping.
    //
    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
    // point below where instructions are removed — otherwise a stack trace would point
    // at the wrong source line as soon as dead-code elimination kicked in.
    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
    for (original, entry) in insns.iter_mut().enumerate() {
        if let Some((op, operands)) = entry.take() {
            original_to_kept[original] = Some(kept.len());
            kept.push((op, operands));
            spans.push(insn_pos.get(original).copied().flatten());
        }
    }

    if std::env::var_os("QJS_DEBUG").is_some() {
        eprintln!("--- assemble entry --- {kept:?}");
    }
    // How many labels are real, as opposed to the per-instruction ones allocated
    // just below. Only a real label marks a spot in the source program.
    let real_labels = state.labels.len();

    // Give every surviving instruction a label of its own. Jump cleanup below
    // redirects jumps to arbitrary instructions, and a jump target has to be a
    // label; pre-allocating one per index means a redirect never has to invent
    // anything.
    let existing = state.labels.len();
    let base = kept.len();
    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
    for offset in 0..=kept.len() {
        state.labels.push(Some(0));
        index_label.push(Label((existing + offset) as u32));
    }
    // Point each pre-allocated label at its instruction, reusing the count from
    // `original_to_kept` so the mapping survives compaction.
    let place_index_labels = |state: &mut FnState,
                              original_to_kept: &[Option<usize>],
                              kept_len: usize,
                              index_label: &[Label]| {
        for (original, mapped) in original_to_kept.iter().enumerate() {
            if let Some(kept_index) = mapped {
                let label = index_label[*kept_index].0 as usize;
                state.labels[label] = Some(original);
            }
        }
        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
    };
    place_index_labels(state, &original_to_kept, base, &index_label);

    // Resolve every label to a kept index once; the placement table maps labels
    // to original indices, so a second hop lands in kept space.
    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
    for (id, placed) in state.labels.iter().enumerate() {
        let Some(original) = placed else { continue };
        label_kept[id] = if *original == usize::MAX {
            Some(base)
        } else {
            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
        };
    }

    // Code after an unconditional transfer is unreachable, and the reference drops it
    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
    // scans forward until it finds a label something still jumps to, so a run of
    // dead instructions between a `throw` and the next live target disappears.
    //
    // The scan repeats because dropping a jump lowers the reference count of the
    // label it pointed at, which can strand what follows. Only a real label keeps an
    // instruction alive here; the per-instruction labels allocated above belong to
    // this pass, not to the program.
    loop {
        let mut references = vec![false; kept.len() + 1];
        for (_, operands) in &kept {
            if let Some(target) = target_kept_index(operands, &label_kept)
                && target < references.len()
            {
                references[target] = true;
            }
        }
        let mut doomed = vec![false; kept.len()];
        let mut any = false;
        for (index, (op, _)) in kept.iter().enumerate() {
            if !is_transfer(*op) {
                continue;
            }
            for next in index + 1..kept.len() {
                if references[next] {
                    break;
                }
                doomed[next] = true;
                any = true;
            }
        }
        if !any {
            break;
        }
        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
    }

    // A label that lands on an unconditional jump stands for wherever that jump
    // goes, so retarget it once and every jump to the label follows for free.
    // This is what makes `continue` in a `for` head reach the loop top instead of
    // stopping at the update's trailing jump.
    let folded: Vec<Option<usize>> = label_kept
        .iter()
        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
        .collect();
    label_kept = folded;

    // Jump cleanup, in compacted index space. Two rewrites the reference also
    // applies while it resolves labels:
    //   * a jump whose destination is the very next instruction does nothing;
    //   * a jump to a jump is redirected to its final destination.
    // The second can expose the first, so this repeats until it settles.
    loop {
        let mut delete = vec![false; kept.len()];
        let mut changed = false;
        for index in 0..kept.len() {
            let (op, operands) = &kept[index];
            if !is_goto(*op) {
                continue;
            }
            let Some(immediate) = target_kept_index(operands, &label_kept) else {
                continue;
            };
            let target = follow_jump_chain(&kept, &label_kept, immediate);
            if target == index + 1 {
                delete[index] = true;
                changed = true;
            } else if matches!(
                kept.get(target).map(|(op, _)| *op),
                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
            ) {
                // Jumping straight to a return or throw is the same as doing it
                // here, so the jump becomes that instruction.
                kept[index] = (kept[target].0, Vec::new());
                changed = true;
            } else if target != immediate {
                // Redirect to the end of the chain.
                let label = index_label[target];
                kept[index].1 = vec![Op::Label(label)];
                changed = true;
            }
        }
        if !changed {
            break;
        }
        if !delete.iter().any(|deleted| *deleted) {
            break;
        }
        // Drop the deleted instructions and renumber everything.
        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
        for (old, entry) in kept.into_iter().enumerate() {
            if delete[old] {
                continue;
            }
            moved[old] = Some(next.len());
            next.push(entry);
            next_spans.push(spans[old]);
        }
        for (id, slot) in label_kept.iter_mut().enumerate() {
            let Some(old) = *slot else { continue };
            *slot = match moved.get(old).copied().flatten() {
                Some(new) => Some(new),
                // The target was deleted: the jump now lands on whatever follows.
                None => (old..moved.len())
                    .find_map(|i| moved[i])
                    .or(Some(next.len())),
            };
            let _ = id;
        }
        kept = next;
        spans = next_spans;
    }

    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
    // jump to the next instruction and is deleted, leaving the label at the end with
    // nothing pointing at it. If that also strands the last instruction, it goes
    // too — which is how a `try` whose body always returns ends on its `ret` rather
    // than an implicit `return_undef`.
    // Which instructions something still jumps to. Reading the surviving jumps is
    // what the reference's reference counts amount to: once a jump has been folded
    // away the label it named is unreferenced, even though the program still has a
    // label there.
    let mut references = vec![false; kept.len() + 1];
    let _ = real_labels;
    for (_, operands) in &kept {
        if let Some(target) = target_kept_index(operands, &label_kept)
            && target < references.len()
        {
            references[target] = true;
        }
    }
    let mut end = kept.len();
    while end > 0 {
        let last = end - 1;
        let reachable = references[last] || end < kept.len();
        if reachable {
            break;
        }
        let after_transfer = last
            .checked_sub(1)
            .map(|previous| {
                matches!(
                    kept[previous].0,
                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
                )
            })
            .unwrap_or(false);
        if !after_transfer {
            break;
        }
        end = last;
    }
    kept.truncate(end);
    spans.truncate(end);

    // Choose an opcode for each instruction and its size, so label offsets can be
    // computed.
    let chosen = choose_opcodes(&kept, &label_kept);
    let offsets = instruction_offsets(&chosen);
    let offset = *offsets.last().unwrap_or(&0);

    let mut code = Vec::with_capacity(offset);
    for (position, (_, operands)) in kept.iter().enumerate() {
        let op = chosen[position];
        code.push(op as u8);
        let operands = retarget_labels(operands, &label_kept, kept.len());
        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
    }
    let stack_size = compute_stack_size(&code);
    // Keep only the offsets where the position actually changes: a run of
    // instructions on one line is one table entry, and the runtime binary searches
    // the table for the frame's pc.
    //
    // The table always starts at pc 0 with the *function's own* position, because the
    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
    // (`function`, `async`, a method's property name). An instruction before the first
    // recorded operator therefore reports the function's own start, which is what makes a
    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
    let mut positions: Vec<LineCol> = vec![LineCol {
        pc: 0,
        line: state.line,
        column: state.column,
    }];
    let mut last: Option<Position> = None;
    for (index, span) in spans.iter().enumerate() {
        let Some(pos) = *span else { continue };
        if last == Some(pos) {
            continue;
        }
        last = Some(pos);
        if pos.line == state.line && pos.column == state.column {
            // Already the seed entry above.
            continue;
        }
        positions.push(LineCol {
            pc: offsets[index] as u32,
            line: pos.line,
            column: pos.column,
        });
    }
    (code, stack_size, positions)
}

/// Whether an instruction always transfers control away, so anything after it in the
/// same stream is unreachable.
fn is_transfer(op: Opcode) -> bool {
    matches!(
        op,
        Opcode::Goto
            | Opcode::Goto8
            | Opcode::Goto16
            | Opcode::Return
            | Opcode::ReturnUndef
            | Opcode::Throw
            | Opcode::ThrowError
            | Opcode::Ret
    )
}

/// Remove the marked instructions and renumber the label table so it keeps pointing
/// at the same instructions. A label whose instruction went away moves to whatever
/// follows it, since a jump is never left with nowhere to land.
fn drop_instructions(
    kept: Vec<(Opcode, Vec<Op>)>,
    spans: Vec<Option<Position>>,
    label_kept: &mut [Option<usize>],
    doomed: &[bool],
) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
    for (old, entry) in kept.into_iter().enumerate() {
        if doomed.get(old).copied().unwrap_or(false) {
            continue;
        }
        moved[old] = Some(result.len());
        result.push(entry);
        result_spans.push(spans[old]);
    }
    for slot in label_kept.iter_mut() {
        let Some(old) = *slot else { continue };
        *slot = match moved.get(old).copied().flatten() {
            Some(new) => Some(new),
            None => (old..moved.len())
                .find_map(|i| moved[i])
                .or(Some(result.len())),
        };
    }
    (result, result_spans)
}

fn is_goto(op: Opcode) -> bool {
    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
}

/// The kept index a jump operand points at.
fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
    let id = label_id(operands)?;
    label_kept.get(id as usize).copied().flatten()
}

/// Follow a chain of unconditional jumps to its first real destination.
fn follow_jump_chain(
    kept: &[(Opcode, Vec<Op>)],
    label_kept: &[Option<usize>],
    start: usize,
) -> usize {
    let mut current = start;
    // `for(;;)` jumps to itself, so the walk has to be bounded.
    for _ in 0..kept.len() {
        let Some((op, operands)) = kept.get(current) else {
            return current;
        };
        if !is_goto(*op) {
            return current;
        }
        let Some(next) = target_kept_index(operands, label_kept) else {
            return current;
        };
        if next == current {
            return current;
        }
        current = next;
    }
    current
}

/// Rewrite label operands from label ids to kept instruction indices.
fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
    operands
        .iter()
        .map(|operand| match operand {
            Op::Label(label) => {
                let target = label_kept
                    .get(label.0 as usize)
                    .copied()
                    .flatten()
                    .unwrap_or(kept_len);
                Op::Label(Label(target as u32))
            }
            other => other.clone(),
        })
        .collect()
}

/// Encode the resolved instruction stream, choosing short forms where possible.
///
/// Compute the maximum value-stack depth by exploring the control-flow graph.
///
/// This is a breadth-first walk from the first instruction, tracking the stack
/// depth on entry to each instruction. Every instruction has at most two
/// successors (fall through, and a jump target), so a worklist over byte offsets
/// is enough. The reference does the same thing in `compute_stack_size`, which is
/// why the resulting numbers match exactly.
///
/// Instructions that pop a variable number of values (`call`, `array_from`, …)
/// encode that count in their operand, which is added to the static `n_pop`.
fn compute_stack_size(code: &[u8]) -> u32 {
    let mut depth_at = vec![u16::MAX; code.len()];
    // Each entry carries the enclosing `catch` levels, innermost last, because
    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
    // offset and forgets that level.
    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
    let mut max_depth = 0u32;

    while let Some((pc, depth, catch_levels)) = worklist.pop() {
        if pc >= code.len() {
            continue;
        }
        if depth_at[pc] != u16::MAX {
            continue;
        }
        force_depth(&mut depth_at, pc, depth);

        let Some(op) = Opcode::from_u8(code[pc]) else {
            break;
        };
        let info = op.info();
        let next = pc + info.size as usize;
        if next > code.len() {
            break;
        }
        let mut n_pop = info.n_pop as u32;
        let mut n_push = info.n_push as u32;
        // Variable-length forms carry their count in the operand.
        match info.format {
            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
                n_pop += read_u16(code, pc + 1) as u32;
            }
            crate::opcode::OpFormat::Npopx => {
                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
            }
            _ => {}
        }
        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
        // are the `set_` variant; the table already records that, so nothing to
        // adjust here.
        let _ = &mut n_push;

        // The depth before this instruction's own push, which is what a `catch`
        // records as its level.
        let depth_before = depth;
        let mut depth = depth.saturating_sub(n_pop) + n_push;
        let mut catch_levels = catch_levels;
        if op == Opcode::NipCatch {
            // Discard everything above the innermost catch offset, keeping the value
            // on top: the frame the code after this sees is the same shape it would
            // have had if the `try` were not there.
            if let Some(base) = catch_levels.pop() {
                depth = base + 1;
            }
        }
        max_depth = max_depth.max(depth);

        // Successors.
        let target = jump_target_of(code, pc, op);
        match op {
            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
                if let Some(target) = target {
                    worklist.push((target, depth, catch_levels));
                }
            }
            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
                if let Some(target) = target {
                    worklist.push((target, depth, catch_levels.clone()));
                }
                worklist.push((next, depth, catch_levels));
            }
            // A `catch` records an exception edge to the handler. The handler is
            // entered with the thrown value on top of the stack, in the slot the
            // catch offset occupies on the normal path — which is why the handler's
            // first instruction can `put_loc` the exception away, and why the depth
            // is the same on both paths.
            Opcode::Catch => {
                if let Some(target) = target {
                    // The handler is protected by the *enclosing* catch, not by this
                    // one: an error raised inside it is what the handler's own
                    // `catch` catches.
                    worklist.push((target, depth, catch_levels.clone()));
                }
                catch_levels.push(depth_before);
                worklist.push((next, depth, catch_levels));
            }
            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
            // rewind past it too. Its level sits one slot higher than a `catch`'s:
            // the iterator and next-method slots occupy the offset's place.
            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
                if let Some(target) = target {
                    worklist.push((target, depth, catch_levels.clone()));
                }
                catch_levels.push(depth_before + 1);
                worklist.push((next, depth, catch_levels));
            }
            // `gosub` calls a subroutine with the return address on top. The opcode
            // table records no push for it — `ret` is what pops the slot — so the
            // extra one is added here, where the depth of the subroutine's first
            // instruction is being computed.
            Opcode::Gosub => {
                if let Some(target) = target {
                    worklist.push((target, depth + 1, catch_levels.clone()));
                }
                worklist.push((next, depth, catch_levels));
            }
            // `ret` goes back to a `gosub`; nothing here follows it.
            Opcode::Ret
            | Opcode::Return
            | Opcode::ReturnUndef
            | Opcode::Throw
            | Opcode::ThrowError => {}
            _ => worklist.push((next, depth, catch_levels)),
        }
    }
    max_depth
}

/// Record the stack depth on entry to `pc`, keeping the deeper value if the
/// instruction is reachable more than once.
fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
        depth_at[pc] = clamped;
    }
}

fn read_u16(code: &[u8], at: usize) -> u16 {
    let mut value = 0u16;
    for i in 0..2 {
        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
    }
    value
}

/// The absolute target of a jump instruction, if it has one.
fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
    let info = op.info();
    let position = pc + 1;
    match info.format {
        crate::opcode::OpFormat::Label8 => {
            let offset = *code.get(position)? as i8 as i64;
            Some((position as i64 + offset) as usize)
        }
        crate::opcode::OpFormat::Label16 => {
            let offset = read_u16(code, position) as i16 as i64;
            Some((position as i64 + offset) as usize)
        }
        crate::opcode::OpFormat::Label => {
            let mut offset = 0i32;
            for i in 0..4 {
                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
            }
            Some((position as i64 + offset as i64) as usize)
        }
        _ => None,
    }
}

fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
    use Opcode::*;
    match (op, operands.first()) {
        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
            op.short_form(*value as u32).unwrap_or(op)
        }
        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
        // A declared global is reached through its reference cell, so it shares
        // the `var_ref` encodings, short forms included.
        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
            op.short_form(*index).unwrap_or(op)
        }
        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
            op.short_form(*count as u32).unwrap_or(op)
        }
        _ => op,
    }
}

/// The byte offset each instruction will start at, plus the total code size.
fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
    let mut offsets = Vec::with_capacity(chosen.len() + 1);
    let mut offset = 0usize;
    for op in chosen {
        offsets.push(offset);
        offset += op.size() as usize;
    }
    offsets.push(offset);
    offsets
}

/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
/// the offset actually fits.
///
/// The choice is circular: an instruction's size decides the offsets of everything after
/// it, and the offsets decide whether a jump may be short. So this starts with every jump
/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
/// Shrinking only ever *shortens* distances, so the loop converges.
///
/// Doing it in one pass instead — which is what this used to do — silently truncated any
/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
/// with four closures in its body simply stopped, with no error and no output past the
/// first iteration.
fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
    let mut chosen: Vec<Opcode> = kept
        .iter()
        .map(|(op, operands)| choose_short_form(*op, operands))
        .collect();
    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
    let candidates = |op: Opcode| match op {
        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
        _ => None,
    };
    loop {
        let offsets = instruction_offsets(&chosen);
        let mut changed = false;
        for index in 0..kept.len() {
            let (op, operands) = &kept[index];
            let Some((short, medium, has_medium)) = candidates(*op) else {
                continue;
            };
            if chosen[index] == short {
                continue;
            }
            let Some(target) = target_kept_index(operands, label_kept) else {
                continue;
            };
            let Some(&target_offset) = offsets.get(target) else {
                continue;
            };
            // A jump is relative to the byte after its opcode, which is the convention
            // `jump_target_of` decodes with.
            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
            if (-128..=127).contains(&relative) {
                chosen[index] = short;
                changed = true;
            } else if has_medium
                && chosen[index] == Opcode::Goto
                && (-32_768..=32_767).contains(&relative)
            {
                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
                // the reference encodes them.
                chosen[index] = medium;
                changed = true;
            }
        }
        if !changed {
            return chosen;
        }
    }
}

fn encode_operands(
    code: &mut Vec<u8>,
    op: Opcode,
    operands: &[Op],
    position: usize,
    offsets: &[usize],
) {
    use crate::opcode::OpFormat::*;
    let info = op.info();
    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
        let index = match slot {
            Slot::Arg(i)
            | Slot::Loc(i)
            | Slot::VarRef(i)
            | Slot::Global(i)
            | Slot::GlobalDecl(i) => i,
        };
        code.extend_from_slice(&(index as u16).to_be_bytes());
    };
    match info.format {
        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
        U8 | Const8 => {
            if let Some(value) = operands.first().and_then(operand_uint) {
                code.push(value as u8);
            }
        }
        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
        // like their wide counterparts, only one byte wide.
        Loc8 => {
            if let Some(Op::Slot(slot)) = operands.first() {
                let index = match slot {
                    Slot::Arg(i)
                    | Slot::Loc(i)
                    | Slot::VarRef(i)
                    | Slot::Global(i)
                    | Slot::GlobalDecl(i) => *i,
                };
                code.push(index as u8);
            }
        }
        I8 => {
            if let Some(value) = operands.first().and_then(operand_int) {
                code.push(value as i8 as u8);
            }
        }
        U16 | Npop => {
            if let Some(value) = operands.first().and_then(operand_int) {
                code.extend_from_slice(&(value as u16).to_be_bytes());
            }
        }
        I16 => {
            if let Some(value) = operands.first().and_then(operand_int) {
                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
            }
        }
        I32 => {
            if let Some(value) = operands.first().and_then(operand_int) {
                code.extend_from_slice(&value.to_be_bytes());
            }
        }
        U32 | Const => {
            if let Some(value) = operands.first().and_then(operand_uint) {
                code.extend_from_slice(&value.to_be_bytes());
            }
        }
        Loc | Arg | VarRef => {
            if let Some(Op::Slot(slot)) = operands.first() {
                write_slot(code, *slot);
            }
        }
        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
            if let Some(Op::AtomId(index)) = operands.first() {
                code.extend_from_slice(&index.to_be_bytes());
            }
            // The trailing immediate means different things per format, and the
            // atom forms that carry a *label* have to resolve it like any other
            // jump, so they cannot share the `U8`/`U16` arms above.
            match info.format {
                AtomU8 | AtomLabelU8 => {
                    if let Some(value) = operands.get(1).and_then(operand_uint) {
                        code.push(value as u8);
                    }
                }
                AtomU16 | AtomLabelU16 => {
                    if let Some(value) = operands.get(1).and_then(operand_uint) {
                        code.extend_from_slice(&(value as u16).to_be_bytes());
                    }
                }
                _ => {}
            }
        }
        NpopU16 => {
            for operand in operands.iter().take(2) {
                if let Some(value) = operand_uint(operand) {
                    code.extend_from_slice(&(value as u16).to_be_bytes());
                }
            }
        }
        Label | Label8 | Label16 | LabelU16 => {
            if let Some(Op::Label(label)) = operands.first() {
                // Labels were already remapped to kept-instruction indices.
                let Some(&target) = offsets.get(label.0 as usize) else {
                    debug_assert!(false, "label {} is past the end", label.0);
                    return;
                };
                let relative = target as i64 - (position as i64 + 1);
                match info.format {
                    Label8 => code.push(relative as i8 as u8),
                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
                    // `label_u16` stores the target followed by an unrelated u16.
                    LabelU16 => {
                        code.extend_from_slice(&(relative as i32).to_be_bytes());
                        if let Some(value) = operands.get(1).and_then(operand_uint) {
                            code.extend_from_slice(&(value as u16).to_be_bytes());
                        }
                    }
                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
                }
            }
        }
    }
}

fn operand_int(op: &Op) -> Option<i32> {
    match op {
        Op::Int(value) => Some(*value),
        _ => None,
    }
}

fn operand_uint(op: &Op) -> Option<u32> {
    match op {
        Op::Const(value) | Op::AtomId(value) => Some(*value),
        Op::Int(value) => Some(*value as u32),
        _ => None,
    }
}

/// Disassemble a compiled function.
pub fn disassemble(function: &CompiledFunction) -> String {
    disasm::disassemble_program(function)
}