node-js 0.1.12

JavaScript as a fusevm frontend: a lexer/parser and compiler to fusevm::Chunk on a JsHost object heap, with no bespoke VM or JIT
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
//! Lower the JavaScript AST to `fusevm::Chunk`.
//!
//! Native fusevm ops carry arithmetic (`+ - * / % **`), the relational
//! comparisons (`< <= > >=`) and boolean short-circuit so the JIT can trace
//! them; the strict numeric hook (host) supplies JS semantics for non-numeric
//! operands (string concat, coercion). Everything JS-specific — name access,
//! member/index access, calls, object/array construction, iteration — lowers to
//! a `CallBuiltin` that lands in `builtins.rs`.
//!
//! Conditions are normalized through the `TRUTHY` builtin before a native
//! `JumpIfFalse`, because JS truthiness differs from fusevm's default numeric
//! truthiness. Compiler-internal name strings travel as native `Value::Str`
//! constants; JS-level strings are always heap objects built by `MKSTR`.

use crate::ast::*;
use crate::host::{binop as bop, member, ops, unop, unwind, FuncDef, ParamSlot, TryDef};
use fusevm::{Chunk, ChunkBuilder, Op, Value};

/// A compiled program: the top-level chunk plus the function template table and
/// the try-block table.
#[derive(Default)]
pub struct Program {
    pub main: Chunk,
    pub functions: Vec<(String, FuncDef)>,
    pub tries: Vec<TryDef>,
    /// Whether the program's own top level is strict (`'use strict'` as its
    /// first statement). A FUNCTION carries its strictness in its `FuncDef`;
    /// the top level had nowhere to put it, so the module frame stayed sloppy
    /// and a refused write never threw there even though the compiler had
    /// already emitted the strict ASSIGNMENT opcodes.
    pub strict: bool,
    /// The text the program was parsed from, which every function's `span`
    /// indexes. Installed on the host by `load_merged`.
    pub source: Option<std::sync::Arc<str>>,
}

/// Rebase every func-id and try-id reference so its ids sit above those already
/// loaded on the host (needed only for incremental loading; a no-op for a single
/// run).
pub fn rebase_program(prog: &mut Program, func_off: usize, try_off: usize) {
    if func_off == 0 && try_off == 0 {
        return;
    }
    rebase_chunk(&mut prog.main, func_off, try_off);
    for (_, f) in &mut prog.functions {
        rebase_chunk(&mut f.chunk, func_off, try_off);
    }
    for t in &mut prog.tries {
        rebase_chunk(&mut t.block, func_off, try_off);
        if let Some((_, hb)) = &mut t.handler {
            rebase_chunk(hb, func_off, try_off);
        }
        if let Some(f) = &mut t.finalizer {
            rebase_chunk(f, func_off, try_off);
        }
    }
}

fn rebase_chunk(chunk: &mut Chunk, func_off: usize, try_off: usize) {
    for i in 1..chunk.ops.len() {
        let off = match chunk.ops[i] {
            Op::CallBuiltin(id, _) if id == ops::MKFUNC => func_off,
            Op::CallBuiltin(id, 4) if id == ops::MKCLASS => func_off,
            Op::CallBuiltin(id, 1) if id == ops::TRY => try_off,
            _ => continue,
        };
        if off == 0 {
            continue;
        }
        if let Op::LoadInt(v) = &mut chunk.ops[i - 1] {
            *v += off as i64;
        }
    }
    for sub in &mut chunk.sub_chunks {
        rebase_chunk(sub, func_off, try_off);
    }
}

/// The binding scope a declaration keyword introduces.
fn bind_mode(kind: DeclKind) -> BindMode {
    match kind {
        DeclKind::Var => BindMode::Var,
        DeclKind::Let => BindMode::Lexical,
        DeclKind::Const => BindMode::Const,
    }
}

/// How a binding site introduces its name.
#[derive(Clone, Copy, PartialEq, Eq)]
enum BindMode {
    /// Plain assignment to an existing binding (`x = 1`, a for-of head without
    /// `let`/`const`/`var`).
    Assign,
    /// `let`/`class`: bound in the innermost BLOCK scope.
    Lexical,
    /// `const`: block-scoped like `Lexical`, but IMMUTABLE — a later assignment
    /// to the name throws `TypeError: Assignment to constant variable.`
    Const,
    /// `var` / a hoisted function declaration: bound at FUNCTION scope.
    Var,
}

/// Break/continue jump fixups for a loop or switch.
struct LoopCtx {
    breaks: Vec<usize>,
    continues: Vec<usize>,
    /// Block-scope depth the `break` target expects; a `break` from inside nested
    /// blocks pops back down to it first.
    break_depth: usize,
    /// Block-scope depth the `continue` target expects.
    continue_depth: usize,
    /// Number of iterators on the VM stack inside this loop's body.
    iter_depth: usize,
    /// Whether `continue` binds here (true for loops, false for `switch`).
    catches_continue: bool,
    /// The source label attached to this loop/block, if any (`outer: for …`),
    /// so labeled `break outer` / `continue outer` can target it directly.
    label: Option<String>,
}

#[derive(Default)]
pub struct Compiler {
    /// Pending short-circuit jumps for the optional chain being lowered, one
    /// frame per chain.
    ///
    /// `?.` short-circuits the WHOLE chain to its right, not just its own link:
    /// `o.a?.b.c` is `undefined` when `o.a` is nullish, and never reads `.c`
    /// off it. Each `?.` therefore parks its jump here and the chain's ROOT
    /// patches every one of them to the end. An empty stack means no chain is
    /// open, so a `?.` outside one patches itself as before.
    opt_chain: Vec<Vec<usize>>,
    /// Compiling a Script whose COMPLETION VALUE is observable — what `eval`
    /// returns. Every expression statement then stores into `.completion`
    /// instead of discarding its value, which is how the "last non-empty
    /// completion" rule (14.x, `UpdateEmpty`) falls out without threading a
    /// value through each statement form. Cleared inside a nested function
    /// body, whose statements are not the script's.
    completion: bool,
    functions: Vec<(String, FuncDef)>,
    tries: Vec<TryDef>,
    loops: Vec<LoopCtx>,
    tmp: usize,
    /// A label seen immediately before a loop, consumed by that loop's `LoopCtx`
    /// (`outer: for (…)`); `None` once claimed.
    pending_label: Option<String>,
    /// Source text of the expression an object pattern is being destructured
    /// FROM, set by the declaration or assignment site. Node names it in the
    /// error a nullish source raises — `Cannot destructure property 'w' of 'v'
    /// as it is null` — and the pattern compiler only has the VALUE.
    destructure_src: Option<String>,
    /// Whether `destructure_src` came from a DECLARATION's initializer rather
    /// than from an assignment target. Node names the source in a
    /// not-iterable error only for a declaration: `const [x] = o` is `o is not
    /// iterable`, while `[y] = o` reports the TYPE.
    destructure_is_decl: bool,
    /// Emit per-statement `DBG_LINE` markers for the DAP debugger (`node --dap`).
    debug: bool,
    /// Index into `loops` of the first loop opened by the chunk being emitted.
    /// A `break`/`continue` targeting a loop BELOW this index leaves the current
    /// chunk (a `try` body is compiled as its own chunk), so it cannot be a plain
    /// jump and is raised as a signal instead.
    chunk_loop_base: usize,
    /// Whether this chunk contains a signal-raising `break`/`continue`, so loops
    /// in it must re-dispatch a still-pending signal when they exit.
    chunk_signals: bool,
    /// Number of block scopes open at the current emission point, so a jump out of
    /// them can pop exactly the right number.
    scope_depth: usize,
    /// True while compiling an `async function*` body, where `yield*` must drive
    /// the delegate through the ASYNC iteration protocol.
    in_async_generator: bool,
    /// Number of for-of/for-in iterators parked on the VM stack at this point. A
    /// `break`/`continue` that leaves such a loop must close and drop its iterator,
    /// otherwise the enclosing loop's `FORITER` would peek at the wrong one.
    iter_depth: usize,
    /// Whether the code being emitted is in STRICT mode — a `'use strict'`
    /// directive prologue on the program or an enclosing function body, or a
    /// class body (which is strict unconditionally). The only difference it
    /// makes here is `PutValue` on an unresolvable reference: strict code throws
    /// `ReferenceError` where sloppy code creates a global.
    strict: bool,
    /// Callee SOURCE TEXT per call op of the chunk being emitted, handed to the
    /// host when the chunk is built so a failed call can name the callee the way
    /// the source wrote it. Saved and restored around every nested chunk.
    call_sites: Vec<(usize, String)>,
    /// Parked-iterator depth per `yield` op of the chunk being emitted, so an
    /// injected `.return()`/`.throw()` can close the `for…of` / `yield*`
    /// iterators the halt would otherwise abandon.
    yield_sites: Vec<(usize, usize)>,
    /// Locals of the chunk being emitted that live in fusevm frame slots rather
    /// than the host's scope chain — see [`crate::slots`]. Empty for a chunk the
    /// analysis refused, so `slot_of` answering `None` is the old path.
    slots: crate::slots::Plan,
    /// Number of tagged-template sites emitted so far in this compilation, so
    /// each site carries an ordinal the runtime can cache its template object
    /// under. Monotonic across the whole compilation rather than per chunk: two
    /// textually identical arrow bodies are separate chunks, and this operand is
    /// what makes their bytecode — and therefore their chunk hashes — differ.
    tmpl_sites: u64,
}

// ── early errors: duplicate lexical declarations ─────────────────────────────

/// Reject a duplicate lexical declaration before anything runs, as node does.
///
/// `let a = 1; let a = 2;` is a SyntaxError at PARSE time in node, and this
/// engine ran it — the second declaration simply won. That is the gap that lets
/// a genuine double-declaration bug through silently, and it bit three test
/// files in this repo whose collisions node rejected and this accepted.
///
/// Deliberately narrow, since a false positive REJECTS a program that works:
/// only the three collisions the spec is unambiguous about are reported —
/// two lexical declarations of one name in the same statement list, a lexical
/// name that a `var` in the same subtree hoists onto, and a lexical name
/// colliding with a function declaration beside it. Repeated `var`s, and the
/// same name in nested scopes, stay legal.
/// The names strict code may not BIND or ASSIGN to (13.1.1, 14.3.1.1).
const RESERVED_IN_STRICT: [&str; 2] = ["eval", "arguments"];

/// `SyntaxError: Unexpected eval or arguments in strict mode` — raised for a
/// binding, a parameter, an assignment target and an update target alike.
fn strict_reserved_error() -> String {
    "SyntaxError: Unexpected eval or arguments in strict mode".to_string()
}

pub fn check_early_errors(stmts: &[Stmt]) -> Result<(), String> {
    let mut lexical: Vec<String> = Vec::new();
    let mut functions: Vec<String> = Vec::new();
    for st in stmts {
        match &st.kind {
            StmtKind::Decl { kind, decls } if !matches!(kind, DeclKind::Var) => {
                for d in decls {
                    let mut names = Vec::new();
                    pattern_names(&d.target, &mut names);
                    for n in names {
                        if lexical.contains(&n) {
                            return Err(already_declared(&n));
                        }
                        lexical.push(n);
                    }
                }
            }
            StmtKind::ClassDecl(c) => {
                if let Some(n) = &c.name {
                    if lexical.contains(n) {
                        return Err(already_declared(n));
                    }
                    lexical.push(n.clone());
                }
            }
            StmtKind::FuncDecl { name, .. } => functions.push(name.clone()),
            _ => {}
        }
    }
    // A function declaration and a lexical binding of the same name cannot
    // share a scope, whichever order they appear in.
    for f in &functions {
        if lexical.contains(f) {
            return Err(already_declared(f));
        }
    }
    // A `var` anywhere below hoists PAST any block between it and its function
    // scope, so it collides with a lexical name declared here.
    let mut vars: Vec<String> = Vec::new();
    for st in stmts {
        collect_var_names(st, &mut vars);
    }
    for n in &lexical {
        if vars.contains(n) {
            return Err(already_declared(n));
        }
    }
    // Each nested statement list is its own scope.
    for st in stmts {
        check_nested(&st.kind)?;
    }
    Ok(())
}

fn already_declared(name: &str) -> String {
    format!("SyntaxError: Identifier '{name}' has already been declared")
}

/// Recurse into the statement lists that form their own scopes. A function
/// BODY is checked when that function is compiled, so the walk does not
/// descend into one here.
fn check_nested(k: &StmtKind) -> Result<(), String> {
    let one = |s: &Stmt| check_nested(&s.kind);
    match k {
        StmtKind::Block(b) => check_early_errors(b),
        StmtKind::If { cons, alt, .. } => {
            one(cons)?;
            match alt {
                Some(a) => one(a),
                None => Ok(()),
            }
        }
        StmtKind::While { body, .. }
        | StmtKind::DoWhile { body, .. }
        | StmtKind::Labeled { body, .. }
        | StmtKind::ForOf { body, .. }
        | StmtKind::ForIn { body, .. } => one(body),
        StmtKind::For { body, .. } => one(body),
        StmtKind::Try {
            block,
            handler,
            finalizer,
        } => {
            check_early_errors(block)?;
            if let Some((_, h)) = handler {
                check_early_errors(h)?;
            }
            match finalizer {
                Some(f) => check_early_errors(f),
                None => Ok(()),
            }
        }
        StmtKind::Switch { cases, .. } => {
            // Every case shares ONE block scope, so their statements are
            // checked together rather than case by case.
            let all: Vec<Stmt> = cases.iter().flat_map(|c| c.body.clone()).collect();
            check_early_errors(&all)
        }
        _ => Ok(()),
    }
}

/// Compile a parsed program. `debug` enables per-statement DAP line markers.
pub fn compile(stmts: &[Stmt], debug: bool) -> Result<Program, String> {
    let mut c = Compiler {
        opt_chain: Vec::new(),
        debug,
        // Under `--dap` the debugger reads scopes by name out of the host, and a
        // slot has no name, so a debug run keeps every local a binding.
        slots: if debug {
            Default::default()
        } else {
            crate::slots::plan(&[], stmts, true)
        },
        strict: has_use_strict(stmts),
        ..Default::default()
    };
    check_early_errors(stmts)?;
    let mut b = ChunkBuilder::new();
    // Hoist function declarations to the top (JS function hoisting).
    c.hoist_vars(&mut b, stmts)?;
    c.hoist_lexical(&mut b, stmts);
    c.hoist_funcs(&mut b, stmts)?;
    c.compile_stmts(&mut b, stmts)?;
    Ok(Program {
        main: c.finish_chunk(b),
        functions: c.functions,
        tries: c.tries,
        strict: c.strict,
        source: None,
    })
}

/// Compile leaving the value of the final top-level expression statement on the
/// stack (the program's completion value), for `eval`/`vm.runInThisContext`. A
/// non-expression final statement leaves nothing (→ `undefined`).
pub fn compile_completion(stmts: &[Stmt], debug: bool) -> Result<Program, String> {
    compile_completion_strict(stmts, debug, false)
}

/// As [`compile_completion`], but with the CALLER's strictness folded in.
///
/// A direct `eval` inherits it (19.2.1.1 step 10), which decides every strict
/// early error inside the evaluated source: `eval('delete x')` in strict code
/// is a SyntaxError, and compiling the source on its own could not see that.
pub fn compile_completion_strict(
    stmts: &[Stmt],
    debug: bool,
    caller_strict: bool,
) -> Result<Program, String> {
    let mut c = Compiler {
        opt_chain: Vec::new(),
        debug,
        strict: caller_strict || has_use_strict(stmts),
        ..Default::default()
    };
    let mut b = ChunkBuilder::new();
    // The completion register, declared before anything can write it. A name no
    // source text can spell, like the `.param<n>` slots a destructured
    // parameter uses.
    c.name_const(&mut b, COMPLETION_SLOT);
    b.emit(Op::LoadUndef, 0);
    b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
    b.emit(Op::Pop, 0);
    c.completion = true;
    c.hoist_vars(&mut b, stmts)?;
    c.hoist_funcs(&mut b, stmts)?;
    c.compile_stmts(&mut b, stmts)?;
    c.completion = false;
    c.name_const(&mut b, COMPLETION_SLOT);
    b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
    Ok(Program {
        main: c.finish_chunk(b),
        functions: c.functions,
        tries: c.tries,
        strict: c.strict,
        source: None,
    })
}

impl Compiler {
    /// `UpdateEmpty(result, undefined)` — the step `if`, every loop, `try` and
    /// `switch` apply to their own completion (14.6.7, 14.7.x, 14.11.x,
    /// 14.15.3). Each therefore always produces a VALUE: `1; if(0){2}` is
    /// `undefined`, not 1, and a `break` out of a loop body discards what
    /// earlier iterations accumulated. A block, a labelled statement, `;` and
    /// every declaration propagate empty instead and are not reset here.
    fn reset_completion(&mut self, b: &mut ChunkBuilder, line: u32) {
        if !self.completion {
            return;
        }
        self.name_const(b, COMPLETION_SLOT);
        b.emit(Op::LoadUndef, line);
        b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), line);
        b.emit(Op::Pop, line);
    }
}

/// The hidden binding a completion-valued Script accumulates into. Leading dot:
/// no source text can name it, so nothing a script declares can collide.
const COMPLETION_SLOT: &str = ".completion";

/// Does this statement list open with a `"use strict"` directive prologue?
///
/// A directive prologue is the run of leading statements that are nothing but a
/// string literal, so `"use strict"` counts only while every statement before it
/// is also one.
fn has_use_strict(stmts: &[Stmt]) -> bool {
    for s in stmts {
        match &s.kind {
            StmtKind::Expr(e) => match e {
                Expr::Str(v) if v == "use strict" => return true,
                Expr::Str(_) => continue,
                _ => return false,
            },
            _ => return false,
        }
    }
    false
}

/// The callee's source text, re-printed from its AST the way V8's `CallPrinter`
/// does for the `TypeError` a failed call raises: `o.a.b`, `o[k]`, `"s".x`,
/// `3.x`, `o?.a?.zz`. A string-literal computed access normalizes to dot form
/// (`o['a']` prints `o.a`), which is what node reports.
///
/// `None` for any shape this does not print faithfully — the caller then keeps
/// the bare method name it already used, so an unprinted shape is never given
/// invented text.
fn callee_text(e: &Expr) -> Option<String> {
    Some(match e {
        Expr::Ident(n) => n.clone(),
        Expr::This => "this".into(),
        Expr::Number(n) => crate::host::fmt_number(*n),
        Expr::Str(s) => format!("\"{s}\""),
        Expr::True => "true".into(),
        Expr::False => "false".into(),
        Expr::Null => "null".into(),
        Expr::Undefined => "undefined".into(),
        Expr::Array(items) if items.is_empty() => "[]".into(),
        Expr::Object(props) if props.is_empty() => "{}".into(),
        // A non-empty OBJECT literal is the one shape V8 will not render from
        // source: `({a: 1})()` is `{(intermediate value)} is not a function`,
        // where an array literal or a template is printed as written. Without
        // this the message fell back to the VALUE, which renders
        // `[object Object]` — a spelling node never produces here.
        Expr::Object(_) => "{(intermediate value)}".into(),
        Expr::Member {
            object,
            property,
            optional,
        } => {
            let dot = if *optional { "?." } else { "." };
            format!("{}{dot}{property}", callee_text(object)?)
        }
        Expr::Index {
            object,
            index,
            optional,
        } => {
            let obj = callee_text(object)?;
            // A string-literal key that is a plain identifier prints as a dot
            // access, exactly as node reports it.
            if let Expr::Str(k) = &**index {
                if is_identifier(k) {
                    let dot = if *optional { "?." } else { "." };
                    return Some(format!("{obj}{dot}{k}"));
                }
            }
            let idx = callee_text(index)?;
            let open = if *optional { "?.[" } else { "[" };
            format!("{obj}{open}{idx}]")
        }
        // V8 prints a call in a callee position as `f(...)`, whatever its
        // arguments were: `require('fs').nope()` reports `require(...).nope`.
        Expr::Call { func, .. } => format!("{}(...)", callee_text(func)?),
        Expr::Sequence(items) => {
            let parts: Option<Vec<String>> = items.iter().map(callee_text).collect();
            format!("({})", parts?.join(" , "))
        }
        _ => return None,
    })
}

/// Whether `s` can be written after a `.` — the test that decides whether a
/// string-literal computed access prints in dot form.
fn is_identifier(s: &str) -> bool {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$' => {}
        _ => return false,
    }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
}

fn argc(n: usize) -> Result<u8, String> {
    u8::try_from(n).map_err(|_| "too many arguments (>255) for one call".to_string())
}

/// Does this expression already leave a `Value::Bool` on the stack? A condition
/// that does needs no `TRUTHY` call: `JumpIfFalse` reads the boolean directly.
///
/// The gain is one host round-trip per condition evaluation — `for (let i = 0;
/// i < n; i++)` paid it on every iteration — and it also puts the comparison
/// immediately before the jump that consumes it, which is what fusevm's block
/// JIT requires of a bool-producing op (`bool_is_consumed_in_place`).
///
/// Every arm listed here is a lowering that ends in a `Bool`: the relational
/// ops go to `Op::Num{Lt,Le,Gt,Ge}` (the numeric hook's `relational` returns a
/// Rust `bool`), the equality ops to `STRICT_EQ`/`LOOSE_EQ`, `in` to
/// `CONTAINS`, `instanceof` to `INSTANCEOF`, and `!`/`!=`/`!==` end in
/// `Op::LogNot`. Anything else — including `&&`/`||`/`??`, which evaluate to an
/// OPERAND and not to a boolean — keeps the call.
fn yields_bool(e: &Expr) -> bool {
    match e {
        Expr::True | Expr::False => true,
        Expr::Unary(UnOp::Not, _) | Expr::Unary(UnOp::Delete, _) => true,
        Expr::Binary(op, _, _) => matches!(
            op,
            BinOp::Lt
                | BinOp::Le
                | BinOp::Gt
                | BinOp::Ge
                | BinOp::EqEq
                | BinOp::NeEq
                | BinOp::EqEqEq
                | BinOp::NeEqEq
                | BinOp::In
                | BinOp::InstanceOf
        ),
        _ => false,
    }
}

impl Compiler {
    // ── emit helpers ─────────────────────────────────────────────────────
    fn name_const(&self, b: &mut ChunkBuilder, s: &str) {
        let k = b.add_constant(Value::str(s));
        b.emit(Op::LoadConst(k), 0);
    }
    fn strlit(&self, b: &mut ChunkBuilder, s: &str) {
        let k = b.add_constant(Value::str(s));
        b.emit(Op::LoadConst(k), 0);
        b.emit(Op::CallBuiltin(ops::MKSTR, 1), 0);
    }
    fn tmp_name(&mut self, tag: &str) -> String {
        let n = format!(".{tag}{}", self.tmp);
        self.tmp += 1;
        n
    }

    /// Emit MKFUNC for a compiled function template and leave the closure on the
    /// stack.
    fn emit_mkfunc(&self, b: &mut ChunkBuilder, def_id: usize) {
        b.emit(Op::LoadInt(def_id as i64), 0);
        b.emit(Op::CallBuiltin(ops::MKFUNC, 1), 0);
    }

    /// Emit the `var` hoisting for one function (or program) scope.
    ///
    /// A `var` binding exists from the moment its scope is entered, so
    /// `f(){ x; var x = 1 }` reads `undefined` where a `let` would throw. The
    /// walk therefore descends through every block, loop, `switch`, `try` and
    /// label — `var` ignores block scope — but stops at a nested function, which
    /// begins a scope of its own. Only the binding is created here; the
    /// initialiser still runs where it is written.
    ///
    /// Emitted BEFORE [`Self::hoist_funcs`] so a function declaration overwrites
    /// the `undefined` rather than the other way round, which is the order the
    /// spec instantiates them in.
    fn hoist_vars(&mut self, b: &mut ChunkBuilder, stmts: &[Stmt]) -> Result<(), String> {
        let mut names = Vec::new();
        for s in stmts {
            collect_var_names(s, &mut names);
        }
        for n in names {
            // A slotted local is its slot, which already reads `undefined`
            // before its first write, so there is no binding to create.
            if self.slot_of(&n).is_some() {
                continue;
            }
            self.name_const(b, &n);
            b.emit(Op::CallBuiltin(ops::HOIST_VAR, 1), 0);
            b.emit(Op::Pop, 0);
        }
        Ok(())
    }

    /// Declare every `let`/`const`/`class` named DIRECTLY in `stmts` as
    /// uninitialized, at the top of the scope those statements form.
    ///
    /// Without it a lexical binding simply did not exist until its declaration
    /// ran, so a read above it either found an OUTER binding of the same name —
    /// `let x = 1; { x; let x = 2 }` read `1` where node throws — or reported
    /// the name as undefined, which is the message for a typo rather than for
    /// the temporal dead zone. Nested blocks are NOT walked: each opens its own
    /// scope and hoists its own.
    fn hoist_lexical(&mut self, b: &mut ChunkBuilder, stmts: &[Stmt]) {
        for s in stmts {
            match &s.kind {
                StmtKind::Decl {
                    kind: DeclKind::Let | DeclKind::Const,
                    decls,
                } => {
                    for d in decls {
                        for name in binding_names(&d.target) {
                            self.name_const(b, &name);
                            b.emit(Op::CallBuiltin(ops::HOIST_TDZ, 1), 0);
                            b.emit(Op::Pop, 0);
                        }
                    }
                }
                StmtKind::ClassDecl(c) => {
                    if let Some(name) = &c.name {
                        self.name_const(b, name);
                        b.emit(Op::CallBuiltin(ops::HOIST_TDZ, 1), 0);
                        b.emit(Op::Pop, 0);
                    }
                }
                _ => {}
            }
        }
    }

    fn hoist_funcs(&mut self, b: &mut ChunkBuilder, stmts: &[Stmt]) -> Result<(), String> {
        self.hoist_funcs_in(b, stmts, false)
    }

    /// `in_block` marks a declaration that is nested in a BLOCK rather than at
    /// the top of a function body or script. Only that case is affected by
    /// strictness.
    fn hoist_funcs_in(
        &mut self,
        b: &mut ChunkBuilder,
        stmts: &[Stmt],
        in_block: bool,
    ) -> Result<(), String> {
        for s in stmts {
            if let StmtKind::FuncDecl {
                name,
                params,
                body,
                is_generator,
                is_async,
                span,
            } = &s.kind
            {
                let def_id = self.build_function(name, params, body, *is_generator, *is_async)?;
                self.functions[def_id].1.span = *span;
                self.emit_mkfunc(b, def_id);
                // A function declaration in a BLOCK is block-scoped (14.2.x);
                // only Annex B.3.3's sloppy-mode legacy hoists it to the
                // enclosing FUNCTION scope as well. Hoisting unconditionally
                // made `function o() { { function g() {} } return typeof g }`
                // answer `"function"` under `'use strict'`, where node says
                // `"undefined"`.
                let mode = if in_block && self.strict {
                    BindMode::Lexical
                } else {
                    BindMode::Var
                };
                self.declare_as(b, &Expr::Ident(name.clone()), mode);
            }
        }
        Ok(())
    }

    fn compile_stmts(&mut self, b: &mut ChunkBuilder, stmts: &[Stmt]) -> Result<(), String> {
        for s in stmts {
            self.compile_stmt(b, s)?;
        }
        Ok(())
    }

    fn compile_stmt(&mut self, b: &mut ChunkBuilder, s: &Stmt) -> Result<(), String> {
        if self.debug && s.line != 0 {
            b.emit(Op::LoadInt(s.line as i64), s.line);
            b.emit(Op::CallBuiltin(ops::DBG_LINE, 1), s.line);
            b.emit(Op::Pop, s.line);
        }
        let line = s.line;
        match &s.kind {
            StmtKind::Expr(e) => {
                self.compile_expr(b, e)?;
                if self.completion {
                    self.name_const(b, COMPLETION_SLOT);
                    b.emit(Op::Swap, line);
                    b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), line);
                }
                b.emit(Op::Pop, line);
            }
            StmtKind::Empty => {}
            StmtKind::FuncDecl { .. } => {} // hoisted at block entry
            StmtKind::ClassDecl(node) => {
                self.compile_class(b, node)?;
                // Bind the class to its name in the current scope.
                if let Some(name) = &node.name {
                    self.declare(b, &Expr::Ident(name.clone()));
                } else {
                    b.emit(Op::Pop, line);
                }
            }
            StmtKind::Decl { kind, decls } => {
                let mode = bind_mode(*kind);
                for d in decls {
                    // `var x;` with no initialiser names a binding that scope
                    // entry already created, and must NOT reset it — in
                    // `function f(a) { var a; }` the parameter stands.
                    if d.init.is_none() && *kind == DeclKind::Var {
                        continue;
                    }
                    match &d.init {
                        Some(v) => {
                            self.compile_expr(b, v)?;
                            // Name inference: `const f = () => {}` / `= function(){}`
                            // / `= class {}` gives the function/class the name `f`.
                            if let Expr::Ident(name) = &d.target {
                                self.infer_name(b, v, name);
                            }
                        }
                        None => {
                            b.emit(Op::LoadUndef, line);
                        }
                    }
                    // 13.3.1.1: a `var`/`let`/`const` may not BIND `eval` or
                    // `arguments` in strict code.
                    if self.strict {
                        for n in binding_names(&d.target) {
                            if RESERVED_IN_STRICT.contains(&n.as_str()) {
                                return Err(strict_reserved_error());
                            }
                        }
                    }
                    self.destructure_src = d.init.as_ref().and_then(destructure_source_text);
                    self.destructure_is_decl = true;
                    let r = self.compile_bind(b, &d.target, mode);
                    self.destructure_src = None;
                    self.destructure_is_decl = false;
                    r?;
                }
            }
            StmtKind::Block(body) => {
                // A block that declares nothing lexical has nothing to put in a
                // scope, and opening one costs an `EnvData` allocation and free
                // every time control enters the block — once per iteration when
                // the block is a loop body, which is where most of them are.
                let scoped = crate::capture::block_needs_scope(body);
                if scoped {
                    self.emit_push_scope(b);
                }
                self.hoist_lexical(b, body);
                self.hoist_funcs_in(b, body, true)?;
                self.compile_stmts(b, body)?;
                if scoped {
                    self.emit_pop_scope(b);
                }
            }
            StmtKind::If { test, cons, alt } => {
                self.reset_completion(b, line);
                self.compile_if(b, test, cons, alt)?
            }
            StmtKind::While { test, body } => {
                self.reset_completion(b, line);
                self.compile_while(b, test, body)?
            }
            StmtKind::DoWhile { body, test } => {
                self.reset_completion(b, line);
                self.compile_do_while(b, body, test)?
            }
            StmtKind::For {
                init,
                test,
                update,
                body,
            } => {
                self.reset_completion(b, line);
                self.compile_for(b, init, test, update, body)?
            }
            StmtKind::ForOf {
                decl_kind,
                target,
                iter,
                body,
                is_await,
            } => {
                self.reset_completion(b, line);
                let mode = decl_kind.map(bind_mode).unwrap_or(BindMode::Assign);
                if *is_await {
                    self.compile_for_await(b, mode, target, iter, body)?
                } else {
                    self.compile_for_of(b, mode, target, iter, body)?
                }
            }
            StmtKind::ForIn {
                decl_kind,
                target,
                object,
                body,
            } => {
                self.reset_completion(b, line);
                let mode = decl_kind.map(bind_mode).unwrap_or(BindMode::Assign);
                self.compile_for_in(b, mode, target, object, body)?
            }
            StmtKind::Switch { disc, cases } => {
                self.reset_completion(b, line);
                self.compile_switch(b, disc, cases)?
            }
            StmtKind::Return(e) => {
                match e {
                    Some(e) => self.compile_expr(b, e)?,
                    None => {
                        b.emit(Op::LoadUndef, line);
                    }
                }
                // A `return` out of a `for…of` is an abrupt completion, and
                // 7.4.9 `IteratorClose` runs the iterator's `return` for it —
                // which is what makes a generator's `finally` run. `break` and
                // `continue` already closed theirs; a `return` walked away and
                // left the iterator suspended forever.
                self.emit_close_iters_under_value(b);
                b.emit(Op::CallBuiltin(ops::SIG_RETURN, 1), line);
            }
            StmtKind::Labeled { label, body } => self.compile_labeled(b, label, body)?,
            StmtKind::Break(label) => {
                let idx = match label {
                    // `break outer`: the nearest enclosing context carrying that label.
                    Some(name) => self
                        .loops
                        .iter()
                        .rposition(|c| c.label.as_deref() == Some(name.as_str()))
                        .ok_or_else(|| format!("SyntaxError: Undefined label '{name}'"))?,
                    None => self
                        .loops
                        .len()
                        .checked_sub(1)
                        .ok_or("SyntaxError: 'break' outside loop")?,
                };
                if idx >= self.chunk_loop_base {
                    self.emit_unwind_scopes(b, self.loops[idx].break_depth);
                    self.emit_close_iters(b, self.loops[idx].iter_depth);
                    let j = b.emit(Op::Jump(0), line);
                    self.loops[idx].breaks.push(j);
                } else {
                    self.emit_signal_jump(b, ops::SIG_BREAK, label.as_deref(), line);
                }
            }
            StmtKind::Continue(label) => {
                let idx = match label {
                    // `continue outer`: the labeled loop (a label on a non-loop
                    // cannot catch `continue`).
                    Some(name) => self
                        .loops
                        .iter()
                        .rposition(|c| {
                            c.catches_continue && c.label.as_deref() == Some(name.as_str())
                        })
                        .ok_or_else(|| {
                            format!("SyntaxError: Undefined label '{name}' for continue")
                        })?,
                    None => self
                        .loops
                        .iter()
                        .rposition(|c| c.catches_continue)
                        .ok_or("SyntaxError: 'continue' outside loop")?,
                };
                if idx >= self.chunk_loop_base {
                    self.emit_unwind_scopes(b, self.loops[idx].continue_depth);
                    self.emit_close_iters(b, self.loops[idx].iter_depth);
                    let j = b.emit(Op::Jump(0), line);
                    self.loops[idx].continues.push(j);
                } else {
                    self.emit_signal_jump(b, ops::SIG_CONTINUE, label.as_deref(), line);
                }
            }
            StmtKind::Throw(e) => {
                self.compile_expr(b, e)?;
                b.emit(Op::CallBuiltin(ops::THROW, 1), line);
            }
            StmtKind::Try {
                block,
                handler,
                finalizer,
            } => {
                self.reset_completion(b, line);
                self.compile_try(b, block, handler, finalizer)?
            }
        }
        Ok(())
    }

    // ── binding / assignment ─────────────────────────────────────────────
    /// Store the value on top of the stack into `target`. `declare` chooses
    /// `DECLARE` (new binding) vs `SETLOCAL` (existing binding / global).
    fn compile_bind(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        declare: BindMode,
    ) -> Result<(), String> {
        // A DESTRUCTURING target named `eval` or `arguments` is refused in
        // strict code too, with its own wording — `({ a: eval } = {})` slipped
        // past the assignment check because it never builds an `Expr::Assign`.
        if self.strict {
            if let Expr::Ident(n) = target {
                if declare == BindMode::Assign && RESERVED_IN_STRICT.contains(&n.as_str()) {
                    return Err("SyntaxError: Invalid destructuring assignment target".to_string());
                }
            }
        }
        match target {
            Expr::Ident(_) => {
                if declare == BindMode::Assign {
                    self.store_simple(b, target)?;
                } else {
                    self.declare_as(b, target, declare);
                }
            }
            Expr::Member { .. } | Expr::Index { .. } => {
                self.store_simple(b, target)?;
            }
            Expr::Array(items) => self.destructure_array(b, items, declare)?,
            Expr::Object(props) => self.destructure_object(b, props, declare)?,
            Expr::Assign { target, value, .. } => {
                // Pattern element with a default: use it when TOS is undefined.
                b.emit(Op::Dup, 0);
                b.emit(Op::LoadUndef, 0);
                b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
                let jf = b.emit(Op::JumpIfFalse(0), 0);
                b.emit(Op::Pop, 0); // drop the undefined
                self.compile_expr(b, value)?;
                // 8.6.3 / 14.3.3: a destructuring default whose target is a
                // single binding identifier names an anonymous function after
                // it — `const {a = function(){}} = {}` gives `a.name === "a"`.
                if let Expr::Ident(n) = &**target {
                    self.infer_name(b, value, n);
                }
                let end = b.current_pos();
                b.patch_jump(jf, end);
                self.compile_bind(b, target, declare)?;
            }
            _ => return Err("SyntaxError: invalid assignment target".into()),
        }
        Ok(())
    }

    /// Emit a `DECLARE` of a simple name binding, consuming TOS value.
    fn declare(&self, b: &mut ChunkBuilder, target: &Expr) {
        self.declare_as(b, target, BindMode::Lexical);
    }

    /// Emit the declaration op matching `mode`: block-scoped for `let`/`const`,
    /// function-scoped for `var` and hoisted function declarations.
    fn declare_as(&self, b: &mut ChunkBuilder, target: &Expr, mode: BindMode) {
        if let Expr::Ident(n) = target {
            // A slotted local has no scope entry to declare into: the binding IS
            // the store.
            if let Some(slot) = self.slot_of(n) {
                b.emit(Op::SetSlot(slot), 0);
                return;
            }
            let op = match mode {
                BindMode::Var => ops::DECLARE_VAR,
                BindMode::Const => ops::DECLARE_CONST,
                _ => ops::DECLARE,
            };
            self.name_const(b, n);
            b.emit(Op::Swap, 0);
            b.emit(Op::CallBuiltin(op, 2), 0);
            b.emit(Op::Pop, 0);
        }
    }

    /// Emit `throw new TypeError("Assignment to constant variable.")`.
    ///
    /// A store to a `const` is a RUNTIME error, not a parse error — the spec
    /// puts it in SetMutableBinding (8.5.2), so `try { const c=1; c=2 } catch {}`
    /// has to catch it. Emitting the throw in place of the store gives exactly
    /// that, and costs nothing for every store that is not to a const.
    fn throw_const_assignment(&mut self, b: &mut ChunkBuilder) {
        let e = Expr::New {
            callee: Box::new(Expr::Ident("TypeError".into())),
            args: vec![Expr::Str("Assignment to constant variable.".into())],
        };
        // `New` of a known builtin with a literal argument cannot fail to
        // compile, so the error path is unreachable rather than swallowed.
        if self.compile_expr(b, &e).is_ok() {
            b.emit(Op::CallBuiltin(ops::THROW, 1), 0);
        }
    }

    /// Store TOS into an lvalue (Ident/Member/Index), leaving nothing.
    fn store_simple(&mut self, b: &mut ChunkBuilder, target: &Expr) -> Result<(), String> {
        match target {
            Expr::Ident(n) => {
                // A slotted binding never reaches the host's scope chain, so the
                // host's immutable-binding check cannot see it. The slot plan is
                // exact about which names are const (one declaration per name,
                // unreachable from another chunk, simple identifiers only), so
                // the store is rejected here instead — at run time, as the spec
                // requires, since `try { const c=1; c=2 } catch {}` must CATCH
                // this rather than fail to parse.
                if self.slots.consts.contains(n) {
                    b.emit(Op::Pop, 0); // drop the value that will never be stored
                    self.throw_const_assignment(b);
                    return Ok(());
                }
                if let Some(slot) = self.slot_of(n) {
                    b.emit(Op::SetSlot(slot), 0);
                    return Ok(());
                }
                self.name_const(b, n);
                b.emit(Op::Swap, 0);
                // `PutValue` (6.2.5.6) on an unresolvable reference: strict code
                // throws `ReferenceError`, sloppy code creates a global.
                let op = if self.strict {
                    ops::SETLOCAL_STRICT
                } else {
                    ops::SETLOCAL
                };
                b.emit(Op::CallBuiltin(op, 2), 0);
                b.emit(Op::Pop, 0);
            }
            Expr::Member {
                object, property, ..
            } => {
                self.compile_expr(b, object)?; // [value, recv]
                self.name_const(b, property); // [value, recv, name]
                b.emit(Op::Rot, 0); // [recv, name, value]
                b.emit(Op::CallBuiltin(ops::SETATTR, 3), 0);
                b.emit(Op::Pop, 0);
            }
            Expr::Index { object, index, .. } => {
                self.compile_expr(b, object)?; // [value, recv]
                self.compile_expr(b, index)?; // [value, recv, idx]
                b.emit(Op::Rot, 0); // [recv, idx, value]
                b.emit(Op::CallBuiltin(ops::SETITEM, 3), 0);
                b.emit(Op::Pop, 0);
            }
            _ => return Err("SyntaxError: invalid assignment target".into()),
        }
        Ok(())
    }

    fn destructure_array(
        &mut self,
        b: &mut ChunkBuilder,
        items: &[Expr],
        declare: BindMode,
    ) -> Result<(), String> {
        let star_idx = items
            .iter()
            .position(|e| matches!(e, Expr::Spread(_)))
            .map(|i| i as i64)
            .unwrap_or(-1);
        b.emit(Op::LoadInt(items.len() as i64), 0);
        b.emit(Op::LoadInt(star_idx), 0);
        let at = b.current_pos();
        b.emit(Op::CallBuiltin(ops::UNPACK, 3), 0); // pushes items[0]..items[n-1], items[0] on top
                                                    // Destructuring a non-iterable names the SOURCE the same way `for-of`
                                                    // does: `const [x] = a` reports `a is not iterable`. The text is the one
                                                    // the object-pattern error already carries; a synthesized `.param<n>`
                                                    // slot has no source spelling and is skipped.
                                                    // …and only for a plain IDENTIFIER source. Node reports the TYPE for
                                                    // every other shape — a member, an index, a call, a nested pattern —
                                                    // even though the text exists, so recording one there would name an
                                                    // expression node never names.
        if let Some(src) = self
            .destructure_src
            .clone()
            .filter(|_| self.destructure_is_decl)
            .filter(|t| !t.starts_with('.'))
            .filter(|t| {
                t.starts_with('{')
                    || t.chars()
                        .all(|c| c.is_alphanumeric() || c == '_' || c == '$')
            })
        {
            self.call_sites.push((at, src));
        }
        for it in items {
            match it {
                // An elided target position (`const [a, , b] = xs`) still
                // consumes its unpacked value; nothing is bound to it.
                Expr::Hole | Expr::Undefined => {
                    b.emit(Op::Pop, 0);
                }
                Expr::Spread(inner) => self.compile_bind(b, inner, declare)?,
                _ => self.compile_bind(b, it, declare)?,
            }
        }
        Ok(())
    }

    fn destructure_object(
        &mut self,
        b: &mut ChunkBuilder,
        props: &[Prop],
        declare: BindMode,
    ) -> Result<(), String> {
        // A NULLISH source: node names the pattern's first property and the
        // source expression rather than reporting the property read that failed.
        // Which of the two wordings it uses is decided by that first element —
        // a plain property names itself, a rest / computed key / empty pattern
        // does not, and one carrying a DEFAULT falls through to the ordinary
        // read error because the default is what reads it.
        // A leading `.` marks a compiler-generated name (a parameter slot), which
        // is not something the user wrote and must not be quoted back at them.
        if let Some(src) = self.destructure_src.take().filter(|s| !s.starts_with('.')) {
            let first = match props.first() {
                Some(Prop::KeyValue {
                    key: Expr::Str(k),
                    value,
                    computed: false,
                }) if !matches!(value, Expr::Assign { .. }) => Some(k.clone()),
                // A COMPUTED first key names nothing — evaluating it is what
                // would fail — and neither does a rest or an empty pattern.
                None | Some(Prop::Spread(_)) | Some(Prop::KeyValue { computed: true, .. }) => None,
                // A first property carrying a DEFAULT falls through: the default
                // is what performs the read, so node reports the read.
                _ => return self.destructure_object_body(b, props, declare),
            };
            self.emit_destructure_guard(b, &src, first.as_deref());
        }
        self.destructure_object_body(b, props, declare)
    }

    /// `throw new TypeError(…)` when TOS is nullish, leaving TOS untouched
    /// otherwise.
    fn emit_destructure_guard(&mut self, b: &mut ChunkBuilder, src: &str, first: Option<&str>) {
        for (is_null, word) in [(true, "null"), (false, "undefined")] {
            b.emit(Op::Dup, 0);
            if is_null {
                b.emit(Op::CallBuiltin(ops::LOAD_NULL, 0), 0);
            } else {
                b.emit(Op::LoadUndef, 0);
            }
            b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
            let ok = b.emit(Op::JumpIfFalse(0), 0);
            let msg = match first {
                Some(k) => {
                    format!("Cannot destructure property '{k}' of '{src}' as it is {word}.")
                }
                None => format!("Cannot destructure '{src}' as it is {word}."),
            };
            // A real `TypeError` instance, not a bare string — the handler
            // reads `e.constructor.name` and `e.stack`.
            let e = Expr::New {
                callee: Box::new(Expr::Ident("TypeError".into())),
                args: vec![Expr::Str(msg)],
            };
            if self.compile_expr(b, &e).is_ok() {
                b.emit(Op::CallBuiltin(ops::THROW, 1), 0);
            }
            let end = b.current_pos();
            b.patch_jump(ok, end);
        }
    }

    fn destructure_object_body(
        &mut self,
        b: &mut ChunkBuilder,
        props: &[Prop],
        declare: BindMode,
    ) -> Result<(), String> {
        // Object value on TOS; keep it, read each key, bind, then drop.
        let obj_tmp = self.tmp_name("destr");
        self.name_const(b, &obj_tmp);
        b.emit(Op::Swap, 0);
        b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
        b.emit(Op::Pop, 0);
        // The keys a `...rest` must EXCLUDE. A statically-spelled key is known
        // here; a computed one (`{ [k]: v, ...rest }`) is only a value at run
        // time, and only collecting the static ones left every computed key in
        // the rest object — `const { [k]: y, ...r } = { a: 1, b: 2 }` with
        // `k === 'b'` put `b` in BOTH `y` and `r`.
        //
        // A computed key must still be evaluated exactly once, so its value is
        // stashed in a temporary as it is computed and the rest reads that
        // temporary rather than re-running the expression.
        enum Excl {
            Static(String),
            Computed(String),
        }
        let has_rest = props.iter().any(|p| matches!(p, Prop::Spread(_)));
        let mut named: Vec<Excl> = Vec::new();
        for p in props {
            match p {
                Prop::KeyValue { key, value, .. } => {
                    // Load obj, read key.
                    self.load_local(b, &obj_tmp);
                    self.compile_expr(b, key)?; // [obj, key]
                    match key {
                        Expr::Str(s) => named.push(Excl::Static(s.clone())),
                        // Only worth a temporary when a rest will read it.
                        _ if has_rest => {
                            let t = self.tmp_name("destrkey");
                            b.emit(Op::Dup, 0); // [obj, key, key]
                            self.name_const(b, &t); // [obj, key, key, name]
                            b.emit(Op::Swap, 0); // [obj, key, name, key]
                            b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0); // [obj, key, _]
                            b.emit(Op::Pop, 0); // [obj, key]
                            named.push(Excl::Computed(t));
                        }
                        _ => {}
                    }
                    b.emit(Op::CallBuiltin(ops::GETITEM, 2), 0); // [value]
                    self.compile_bind(b, value, declare)?;
                }
                Prop::Spread(target) => {
                    self.load_local(b, &obj_tmp);
                    for k in &named {
                        match k {
                            Excl::Static(s) => self.strlit(b, s),
                            Excl::Computed(t) => self.load_local(b, t),
                        }
                    }
                    b.emit(Op::CallBuiltin(ops::MKARR, argc(named.len())?), 0);
                    b.emit(Op::CallBuiltin(ops::OBJ_REST, 2), 0); // [rest_object]
                    self.compile_bind(b, target, declare)?;
                }
                // Accessors never appear in a destructuring pattern.
                Prop::Accessor { .. } => {}
            }
        }
        Ok(())
    }

    fn load_local(&self, b: &mut ChunkBuilder, name: &str) {
        if let Some(slot) = self.slot_of(name) {
            b.emit(Op::GetSlot(slot), 0);
            return;
        }
        self.name_const(b, name);
        b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
    }

    /// The frame slot holding `name` in the chunk being emitted, if it has one.
    fn slot_of(&self, name: &str) -> Option<u16> {
        self.slots.table.get(name).copied()
    }

    /// The slot for `name` if it also provably holds a Number, so `++`/`--` can
    /// be a native add rather than a `NUM_STEP` round-trip through the host.
    fn numeric_slot_of(&self, name: &str) -> Option<u16> {
        self.slots
            .numeric
            .contains(name)
            .then(|| self.slot_of(name))
            .flatten()
    }

    // ── control flow ─────────────────────────────────────────────────────
    fn compile_condition(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
        self.compile_expr(b, e)?;
        if !yields_bool(e) {
            b.emit(Op::CallBuiltin(ops::TRUTHY, 1), 0);
        }
        Ok(())
    }

    fn compile_if(
        &mut self,
        b: &mut ChunkBuilder,
        test: &Expr,
        cons: &Stmt,
        alt: &Option<Box<Stmt>>,
    ) -> Result<(), String> {
        self.compile_condition(b, test)?;
        let jfalse = b.emit(Op::JumpIfFalse(0), 0);
        self.compile_stmt(b, cons)?;
        if let Some(alt) = alt {
            let jend = b.emit(Op::Jump(0), 0);
            let else_start = b.current_pos();
            b.patch_jump(jfalse, else_start);
            self.compile_stmt(b, alt)?;
            let end = b.current_pos();
            b.patch_jump(jend, end);
        } else {
            let end = b.current_pos();
            b.patch_jump(jfalse, end);
        }
        Ok(())
    }

    /// `label: stmt`. If the body is a loop, the label rides into that loop's
    /// `LoopCtx` (so labeled `break`/`continue` target it); otherwise a break-only
    /// context spans the body so `break label` can jump past it.
    fn compile_labeled(
        &mut self,
        b: &mut ChunkBuilder,
        label: &str,
        body: &Stmt,
    ) -> Result<(), String> {
        if matches!(
            body.kind,
            StmtKind::While { .. }
                | StmtKind::DoWhile { .. }
                | StmtKind::For { .. }
                | StmtKind::ForOf { .. }
                | StmtKind::ForIn { .. }
        ) {
            self.pending_label = Some(label.to_string());
            self.compile_stmt(b, body)?;
            // The loop claimed it; clear any residue defensively.
            self.pending_label = None;
        } else {
            self.loops.push(LoopCtx {
                breaks: Vec::new(),
                continues: Vec::new(),
                break_depth: self.scope_depth,
                continue_depth: self.scope_depth,
                iter_depth: self.iter_depth,
                catches_continue: false,
                label: Some(label.to_string()),
            });
            self.compile_stmt(b, body)?;
            let ctx = self.loops.pop().unwrap();
            let end = b.current_pos();
            for br in ctx.breaks {
                b.patch_jump(br, end);
            }
            self.redispatch_after_loop(b);
        }
        Ok(())
    }

    /// After a loop/switch exits, a signal raised deeper in this chunk may still be
    /// pending (a LABELED `break`/`continue` for an OUTER loop). Re-dispatch it one
    /// level out. Emitted only when this chunk actually raises signals.
    fn redispatch_after_loop(&mut self, b: &mut ChunkBuilder) {
        if self.chunk_signals {
            self.emit_signal_dispatch(b);
        }
    }

    /// `while (test) body`, lowered ROTATED: the test is emitted once as an entry
    /// guard and once at the bottom, so the loop closes with a CONDITIONAL
    /// backward branch rather than an unconditional `Jump` back to a test at the
    /// top.
    ///
    /// That shape is what fusevm's tracing JIT needs — it only closes a trace on
    /// a conditional backward branch. Emitted the other way, `--tiers` reported
    /// `trace-eligible=true traced=false` and `reaches native code false` for
    /// every `for` and `while` this frontend produced, while the same arithmetic
    /// written as `do { … } while (…)` — the one loop form that already ended in
    /// a conditional branch — reported `traced=true`. Measured on a debug build:
    /// `for (let i = 0; i < 3000000; i++) s += i` took 5.76s of user CPU
    /// unrotated and 0.02s rotated.
    ///
    /// Evaluation order and count are unchanged: a top-test loop runs the test
    /// `n + 1` times for `n` iterations, and so does this — one entry test, then
    /// one after each pass. Rotation costs one copy of the condition's code and
    /// saves one jump per iteration.
    fn compile_while(
        &mut self,
        b: &mut ChunkBuilder,
        test: &Expr,
        body: &Stmt,
    ) -> Result<(), String> {
        self.compile_condition(b, test)?;
        let jfalse = b.emit(Op::JumpIfFalse(0), 0);
        let top = b.current_pos();
        self.loops.push(LoopCtx {
            breaks: Vec::new(),
            continues: Vec::new(),
            break_depth: self.scope_depth,
            continue_depth: self.scope_depth,
            iter_depth: self.iter_depth,
            catches_continue: true,
            label: self.pending_label.take(),
        });
        self.compile_stmt(b, body)?;
        // `continue` re-tests the condition, which is now the BOTTOM copy of it.
        let cont_target = b.current_pos();
        self.compile_condition(b, test)?;
        b.emit(Op::JumpIfTrue(top), 0);
        let ctx = self.loops.pop().unwrap();
        for c in ctx.continues {
            b.patch_jump(c, cont_target);
        }
        let end = b.current_pos();
        b.patch_jump(jfalse, end);
        for br in ctx.breaks {
            b.patch_jump(br, end);
        }
        self.redispatch_after_loop(b);
        Ok(())
    }

    fn compile_do_while(
        &mut self,
        b: &mut ChunkBuilder,
        body: &Stmt,
        test: &Expr,
    ) -> Result<(), String> {
        let start = b.current_pos();
        self.loops.push(LoopCtx {
            breaks: Vec::new(),
            continues: Vec::new(),
            break_depth: self.scope_depth,
            continue_depth: self.scope_depth,
            iter_depth: self.iter_depth,
            catches_continue: true,
            label: self.pending_label.take(),
        });
        self.compile_stmt(b, body)?;
        let cont_target = b.current_pos();
        self.compile_condition(b, test)?;
        b.emit(Op::JumpIfTrue(start), 0);
        let ctx = self.loops.pop().unwrap();
        for c in ctx.continues {
            b.patch_jump(c, cont_target);
        }
        let end = b.current_pos();
        for br in ctx.breaks {
            b.patch_jump(br, end);
        }
        self.redispatch_after_loop(b);
        Ok(())
    }

    fn compile_for(
        &mut self,
        b: &mut ChunkBuilder,
        init: &Option<Box<Stmt>>,
        test: &Option<Expr>,
        update: &Option<Expr>,
        body: &Stmt,
    ) -> Result<(), String> {
        // A `let`/`const` head is scoped to the loop AND re-bound per iteration, so
        // a closure made in one pass keeps that pass's value (ForBodyEvaluation's
        // CreatePerIterationEnvironment). A `var` head belongs to the function.
        let lexical_head = matches!(
            init.as_deref(),
            Some(Stmt {
                kind: StmtKind::Decl {
                    kind: DeclKind::Let | DeclKind::Const,
                    ..
                },
                ..
            })
        );
        // The loop's own scope is not optional — it is what keeps `let i` from
        // leaking past the loop or clobbering an outer `i`. The per-iteration
        // COPY of that scope is: only code that can CAPTURE a binding can tell
        // one copy per pass from one binding mutated in place, and the copy is a
        // whole-scope clone every iteration. A 5M-iteration counting loop spent
        // 17% of its samples cloning scopes that nothing could observe.
        let per_iteration = lexical_head;
        let copy_per_iteration = lexical_head
            && (crate::capture::stmt_captures(body)
                || init.as_deref().is_some_and(crate::capture::stmt_captures)
                || test.as_ref().is_some_and(crate::capture::expr_captures)
                || update.as_ref().is_some_and(crate::capture::expr_captures));
        if per_iteration {
            self.emit_push_scope(b);
            // The head's own bindings are in scope — and in their dead zone —
            // for the head itself: `for (let i = i; …)` is a ReferenceError.
            if let Some(init) = init.as_deref() {
                self.hoist_lexical(b, std::slice::from_ref(init));
            }
        }
        if let Some(init) = init {
            self.compile_stmt(b, init)?;
        }
        if copy_per_iteration {
            self.emit_copy_scope(b);
        }
        // Rotated, for the reason `compile_while` documents: the test as an entry
        // guard plus a conditional backward branch at the bottom.
        let jfalse = match test {
            Some(t) => {
                self.compile_condition(b, t)?;
                Some(b.emit(Op::JumpIfFalse(0), 0))
            }
            None => None,
        };
        let top = b.current_pos();
        self.loops.push(LoopCtx {
            breaks: Vec::new(),
            continues: Vec::new(),
            break_depth: self.scope_depth,
            continue_depth: self.scope_depth,
            iter_depth: self.iter_depth,
            catches_continue: true,
            label: self.pending_label.take(),
        });
        self.compile_stmt(b, body)?;
        let cont_target = b.current_pos();
        if copy_per_iteration {
            // Fresh copy BEFORE the update, so the update advances the NEXT pass's
            // binding and the one just captured keeps this pass's value.
            self.emit_copy_scope(b);
        }
        if let Some(u) = update {
            self.compile_expr(b, u)?;
            b.emit(Op::Pop, 0);
        }
        match test {
            Some(t) => {
                self.compile_condition(b, t)?;
                b.emit(Op::JumpIfTrue(top), 0);
            }
            // `for (;;)` has no test to branch on, so the back edge is a
            // constant-true CONDITIONAL branch rather than an unconditional
            // `Jump`. The distinction is not cosmetic: fusevm's trace compiler
            // only ever installs a trace closed by `JumpIfTrue`/`JumpIfFalse`
            // and silently declines an `Op::Jump` close, so `for (;;)` stayed
            // interpreted while the identical `while (true)` — which already
            // emitted `LoadTrue; JumpIfTrue` — reached native code. Measured on
            // a debug build, 3M iterations of `s += i`: 4.26s against 0.02s.
            None => {
                b.emit(Op::LoadTrue, 0);
                b.emit(Op::JumpIfTrue(top), 0);
            }
        }
        let ctx = self.loops.pop().unwrap();
        for c in ctx.continues {
            b.patch_jump(c, cont_target);
        }
        let end = b.current_pos();
        if let Some(jf) = jfalse {
            b.patch_jump(jf, end);
        }
        for br in ctx.breaks {
            b.patch_jump(br, end);
        }
        if per_iteration {
            self.emit_pop_scope(b);
        }
        self.redispatch_after_loop(b);
        Ok(())
    }

    fn compile_for_of(
        &mut self,
        b: &mut ChunkBuilder,
        declare: BindMode,
        target: &Expr,
        iter: &Expr,
        body: &Stmt,
    ) -> Result<(), String> {
        self.compile_expr(b, iter)?;
        let at = b.current_pos();
        b.emit(Op::CallBuiltin(ops::GETITER, 1), 0); // [iterator]
                                                     // A `for-of` over a non-iterable names the SOURCE expression:
                                                     // `for (const x of a)` reports `a is not iterable`, not the rendering
                                                     // of whatever `a` held. Same table the callee-naming uses.
                                                     //
                                                     // A CALL source gets V8's combined wording, since either half could be
                                                     // at fault: `for (const x of f())` is `f is not a function or its
                                                     // return value is not iterable`. Recording the whole subject rather
                                                     // than a marker keeps the runtime side one string substitution.
        match iter {
            Expr::Call { func, .. } => {
                let name = callee_text(func).unwrap_or_else(|| "(intermediate value)".into());
                self.call_sites
                    .push((at, format!("{name} is not a function or its return value")));
            }
            _ => self.note_call_site(at, iter),
        }
        self.iter_depth += 1;
        let r = self.loop_over(b, declare, target, body);
        self.iter_depth -= 1;
        r
    }

    fn compile_for_in(
        &mut self,
        b: &mut ChunkBuilder,
        declare: BindMode,
        target: &Expr,
        object: &Expr,
        body: &Stmt,
    ) -> Result<(), String> {
        // The object is kept in a temp for the whole loop: each key is re-checked
        // against it just before it is visited, because the body can delete one
        // (14.7.5.10 enumerates lazily, so a key deleted before its turn is never
        // visited). Without that, `for (const k in d) delete d.z` still visited
        // `z`.
        let obj_tmp = self.tmp_name("forin");
        self.compile_expr(b, object)?;
        self.name_const(b, &obj_tmp);
        b.emit(Op::Swap, 0);
        b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0); // [obj]
        b.emit(Op::CallBuiltin(ops::FORIN_KEYS, 1), 0); // [keys_array]
        b.emit(Op::CallBuiltin(ops::GETITER, 1), 0); // [iterator]
        self.iter_depth += 1;
        let r = self.loop_over_inner(b, declare, target, body, Some(obj_tmp));
        self.iter_depth -= 1;
        r
    }

    /// `for await (target of iterable) body`. Obtains an async iterator, then each
    /// pass `await`s a `{value, done}` step (a native async iterator's promise, or
    /// the sync fallback's per-value await). The iterator lives in a temp local.
    fn compile_for_await(
        &mut self,
        b: &mut ChunkBuilder,
        declare: BindMode,
        target: &Expr,
        iter: &Expr,
        body: &Stmt,
    ) -> Result<(), String> {
        let iter_tmp = self.tmp_name("aiter");
        self.compile_expr(b, iter)?;
        let at = b.current_pos();
        b.emit(Op::CallBuiltin(ops::GET_ASYNC_ITER, 1), 0); // [iterator]
                                                            // `for await` over a non-iterable names the source AND says ASYNC:
                                                            // `for await (const x of o)` is `o is not async iterable`. Recording
                                                            // the whole subject keeps the runtime side one substitution, as the
                                                            // call-source wording above does.
        self.note_call_site(at, iter);
        self.name_const(b, &iter_tmp);
        b.emit(Op::Swap, 0);
        b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
        b.emit(Op::Pop, 0);
        let start = b.current_pos();
        // step = await ASYNC_STEP(iterator)  -> {value, done}
        self.load_local(b, &iter_tmp);
        b.emit(Op::CallBuiltin(ops::ASYNC_STEP, 1), 0); // [stepPromise]
        b.emit(Op::CallBuiltin(ops::AWAIT, 1), 0); // [step]
        let step_tmp = self.tmp_name("astep");
        self.name_const(b, &step_tmp);
        b.emit(Op::Swap, 0);
        b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
        b.emit(Op::Pop, 0);
        // if (step.done) break
        self.load_local(b, &step_tmp);
        self.name_const(b, "done");
        b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0);
        b.emit(Op::CallBuiltin(ops::TRUTHY, 1), 0);
        let jdone = b.emit(Op::JumpIfTrue(0), 0);
        // target = step.value
        self.load_local(b, &step_tmp);
        self.name_const(b, "value");
        b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [value]
        let per_iteration = matches!(declare, BindMode::Lexical | BindMode::Const);
        if per_iteration {
            self.emit_push_scope(b);
        }
        self.compile_bind(b, target, declare)?;
        self.loops.push(LoopCtx {
            breaks: Vec::new(),
            continues: Vec::new(),
            break_depth: self.scope_depth,
            continue_depth: self.scope_depth,
            iter_depth: self.iter_depth,
            catches_continue: true,
            label: self.pending_label.take(),
        });
        self.compile_stmt(b, body)?;
        let cont_target = b.current_pos();
        if per_iteration {
            self.emit_pop_scope(b);
        }
        b.emit(Op::Jump(start), 0);
        let ctx = self.loops.pop().unwrap();
        for c in ctx.continues {
            b.patch_jump(c, cont_target);
        }
        // `done` arrives before the iteration scope is open; `break` from inside it
        // still has one to close.
        let break_target = b.current_pos();
        if per_iteration {
            b.emit(Op::CallBuiltin(ops::POP_SCOPE, 0), 0);
            b.emit(Op::Pop, 0);
        }
        // Leaving early closes the async iterator, running an async generator's
        // pending `finally` / calling a user iterator's `.return()`.
        self.load_local(b, &iter_tmp);
        b.emit(Op::CallBuiltin(ops::ITER_CLOSE, 1), 0);
        b.emit(Op::Pop, 0);
        let end = b.current_pos();
        b.patch_jump(jdone, end);
        for br in ctx.breaks {
            b.patch_jump(br, break_target);
        }
        self.redispatch_after_loop(b);
        Ok(())
    }

    /// Shared loop tail for for-of / for-in: iterator on TOS.
    fn loop_over(
        &mut self,
        b: &mut ChunkBuilder,
        declare: BindMode,
        target: &Expr,
        body: &Stmt,
    ) -> Result<(), String> {
        self.loop_over_inner(b, declare, target, body, None)
    }

    /// `alive_in` names the local holding a `for-in`'s object. When it is set,
    /// each key is re-checked against that object before it is bound, and a key
    /// the body already deleted is skipped rather than visited.
    fn loop_over_inner(
        &mut self,
        b: &mut ChunkBuilder,
        declare: BindMode,
        target: &Expr,
        body: &Stmt,
        alive_in: Option<String>,
    ) -> Result<(), String> {
        // `for (const v of …)` binds a FRESH `v` each pass, so a closure made in one
        // pass keeps that pass's element.
        let per_iteration = matches!(declare, BindMode::Lexical | BindMode::Const);
        let start = b.current_pos();
        b.emit(Op::CallBuiltin(ops::FORITER, 0), 0); // [iterator, value, has_next]
        let jdone = b.emit(Op::JumpIfFalse(0), 0); // pops has_next
        if let Some(obj_tmp) = &alive_in {
            b.emit(Op::Dup, 0); // [iterator, key, key]
            self.load_local(b, obj_tmp); // [iterator, key, key, obj]
            b.emit(Op::Swap, 0); // [iterator, key, obj, key]
            b.emit(Op::CallBuiltin(ops::FORIN_ALIVE, 2), 0); // [iterator, key, alive]
            let jalive = b.emit(Op::JumpIfTrue(0), 0);
            b.emit(Op::Pop, 0); // drop the dead key -> [iterator]
            b.emit(Op::Jump(start), 0);
            b.patch_jump(jalive, b.current_pos());
        }
        if per_iteration {
            self.emit_push_scope(b);
        }
        self.compile_bind(b, target, declare)?; // consumes value -> [iterator]
        self.loops.push(LoopCtx {
            breaks: Vec::new(),
            continues: Vec::new(),
            break_depth: self.scope_depth,
            continue_depth: self.scope_depth,
            iter_depth: self.iter_depth,
            catches_continue: true,
            label: self.pending_label.take(),
        });
        self.compile_stmt(b, body)?;
        let cont_target = b.current_pos();
        if per_iteration {
            self.emit_pop_scope(b);
        }
        b.emit(Op::Jump(start), 0);
        let ctx = self.loops.pop().unwrap();
        for c in ctx.continues {
            b.patch_jump(c, cont_target);
        }
        let done = b.current_pos();
        b.patch_jump(jdone, done);
        b.emit(Op::Pop, 0); // drop iterator
        let jafter = b.emit(Op::Jump(0), 0);
        let break_target = b.current_pos();
        // `break` out of a for-of closes the iterator (runs a generator's pending
        // `finally` / calls a user iterator's `.return()`), then drops it.
        if per_iteration {
            b.emit(Op::CallBuiltin(ops::POP_SCOPE, 0), 0);
            b.emit(Op::Pop, 0);
        }
        b.emit(Op::CallBuiltin(ops::ITER_CLOSE, 1), 0);
        b.emit(Op::Pop, 0); // ITER_CLOSE leaves its result; the `done` path popped
        let end = b.current_pos();
        b.patch_jump(jafter, end);
        for br in ctx.breaks {
            b.patch_jump(br, break_target);
        }
        // Every exit path above has already closed and dropped THIS loop's
        // iterator, so a signal re-dispatched here must not count it as live.
        self.iter_depth -= 1;
        self.redispatch_after_loop(b);
        self.iter_depth += 1;
        Ok(())
    }

    fn compile_switch(
        &mut self,
        b: &mut ChunkBuilder,
        disc: &Expr,
        cases: &[SwitchCase],
    ) -> Result<(), String> {
        let disc_tmp = self.tmp_name("switch");
        self.compile_expr(b, disc)?;
        self.name_const(b, &disc_tmp);
        b.emit(Op::Swap, 0);
        b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
        b.emit(Op::Pop, 0);
        // All cases share ONE block scope, so `case 1: let x = …` is visible to the
        // later cases but dies with the switch. It opens BEFORE the test chain
        // because each case test jumps straight into its body.
        self.emit_push_scope(b);
        // …and every case's lexical names are hoisted into that one scope, so a
        // read from an EARLIER case is a dead-zone error rather than a lookup
        // that escapes to an outer binding.
        let all: Vec<Stmt> = cases.iter().flat_map(|c| c.body.iter().cloned()).collect();
        self.hoist_lexical(b, &all);
        // Emit the test chain: `if (disc === caseTest) goto bodyN`.
        let mut body_jumps: Vec<Option<usize>> = Vec::new();
        let mut default_idx: Option<usize> = None;
        for (i, case) in cases.iter().enumerate() {
            match &case.test {
                Some(t) => {
                    self.load_local(b, &disc_tmp);
                    self.compile_expr(b, t)?;
                    b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
                    let j = b.emit(Op::JumpIfTrue(0), 0);
                    body_jumps.push(Some(j));
                }
                None => {
                    default_idx = Some(i);
                    body_jumps.push(None);
                }
            }
        }
        // No test matched: jump to default (if any) or end.
        let no_match_jump = b.emit(Op::Jump(0), 0);
        self.loops.push(LoopCtx {
            breaks: Vec::new(),
            continues: Vec::new(),
            break_depth: self.scope_depth,
            continue_depth: self.scope_depth,
            iter_depth: self.iter_depth,
            catches_continue: false,
            label: None,
        });
        let mut body_starts: Vec<usize> = Vec::new();
        for case in cases {
            body_starts.push(b.current_pos());
            self.compile_stmts(b, &case.body)?;
        }
        let end = b.current_pos();
        // Patch each case test-jump to its body start.
        for (i, j) in body_jumps.iter().enumerate() {
            if let Some(j) = j {
                b.patch_jump(*j, body_starts[i]);
            }
        }
        match default_idx {
            Some(i) => b.patch_jump(no_match_jump, body_starts[i]),
            None => b.patch_jump(no_match_jump, end),
        }
        let ctx = self.loops.pop().unwrap();
        for br in ctx.breaks {
            b.patch_jump(br, end);
        }
        self.emit_pop_scope(b);
        self.redispatch_after_loop(b);
        Ok(())
    }

    fn compile_try(
        &mut self,
        b: &mut ChunkBuilder,
        block: &[Stmt],
        handler: &Option<(Option<Expr>, Vec<Stmt>)>,
        finalizer: &Option<Vec<Stmt>>,
    ) -> Result<(), String> {
        let block_chunk = self.compile_block_chunk(block)?;
        let handler_def = match handler {
            Some((param, body)) => match param {
                Some(Expr::Ident(n)) => {
                    let hbody = self.compile_block_chunk(body)?;
                    Some((Some(n.clone()), hbody))
                }
                // `catch ({ code })` / `catch ([a, b])`. The handler receives
                // ONE value under a name, so a pattern binds a temp and is
                // destructured out of it before the body runs. Only a bare
                // identifier was handled, so the pattern bound nothing at all
                // and the body saw a ReferenceError for every name in it.
                Some(pattern) => {
                    let tmp = self.tmp_name("catch");
                    let pattern = pattern.clone();
                    let name = tmp.clone();
                    let hbody = self.compile_chunk_with(body, move |s, cb| {
                        s.load_local(cb, &name);
                        s.compile_bind(cb, &pattern, BindMode::Lexical)
                    })?;
                    Some((Some(tmp), hbody))
                }
                None => {
                    let hbody = self.compile_block_chunk(body)?;
                    Some((None, hbody))
                }
            },
            None => None,
        };
        let final_chunk = match finalizer {
            Some(f) => {
                // 14.15.3: a `finally` that completes NORMALLY has its
                // completion DISCARDED — the try/catch value is what the
                // statement produces. `eval('try{5}finally{6}')` is 5, and was
                // 6 while the block updated the completion register like any
                // other.
                let saved = std::mem::take(&mut self.completion);
                let chunk = self.compile_block_chunk(f);
                self.completion = saved;
                Some(chunk?)
            }
            None => None,
        };
        let id = self.tries.len();
        self.tries.push(TryDef {
            block: block_chunk,
            handler: handler_def,
            finalizer: final_chunk,
        });
        b.emit(Op::LoadInt(id as i64), 0);
        b.emit(Op::CallBuiltin(ops::TRY, 1), 0);
        b.emit(Op::Pop, 0);
        // The try/catch/finally bodies ran as their own chunks, so a `return` or
        // a `break`/`continue` inside them left a signal instead of jumping.
        self.emit_signal_dispatch(b);
        Ok(())
    }

    /// Compile statements into a SEPARATE chunk (a try/catch/finally body). Loops
    /// opened outside it are unreachable by a plain jump, so `chunk_loop_base`
    /// moves up for the duration.
    fn compile_block_chunk(&mut self, stmts: &[Stmt]) -> Result<Chunk, String> {
        self.compile_chunk_with(stmts, |_, _| Ok(()))
    }

    /// A try/catch/finally body chunk, with `prelude` emitted ahead of the
    /// statements. Used to destructure a `catch ({ code })` parameter, which has
    /// to bind before the handler's first statement runs.
    fn compile_chunk_with(
        &mut self,
        stmts: &[Stmt],
        prelude: impl FnOnce(&mut Self, &mut ChunkBuilder) -> Result<(), String>,
    ) -> Result<Chunk, String> {
        let mut cb = ChunkBuilder::new();
        // A nested chunk runs on its OWN VM frame, so the enclosing chunk's
        // slots are not reachable from it — everything here goes by name. (The
        // slot analysis already refuses any chunk containing a `try`, which is
        // what builds these; this keeps that true if another one appears.)
        let saved_slot_table = std::mem::take(&mut self.slots);
        let base = std::mem::replace(&mut self.chunk_loop_base, self.loops.len());
        let signals = std::mem::take(&mut self.chunk_signals);
        let depth = std::mem::take(&mut self.scope_depth);
        let iters = std::mem::take(&mut self.iter_depth);
        let sites = std::mem::take(&mut self.call_sites);
        let yields = std::mem::take(&mut self.yield_sites);
        let r = (|| {
            prelude(self, &mut cb)?;
            self.hoist_lexical(&mut cb, stmts);
            self.hoist_funcs(&mut cb, stmts)?;
            self.compile_stmts(&mut cb, stmts)
        })();
        self.chunk_loop_base = base;
        self.scope_depth = depth;
        self.iter_depth = iters;
        self.slots = saved_slot_table;
        // A signal raised inside the nested chunk still has to be dispatched by a
        // loop in THIS chunk, so the flag propagates outward.
        self.chunk_signals |= signals;
        r?;
        let chunk = self.finish_chunk(cb);
        self.call_sites = sites;
        self.yield_sites = yields;
        Ok(chunk)
    }

    // ── functions ────────────────────────────────────────────────────────
    fn build_function(
        &mut self,
        name: &str,
        params: &[Param],
        body: &[Stmt],
        is_generator: bool,
        is_async: bool,
    ) -> Result<usize, String> {
        let (param_slots, prologue) = self.lower_params(params)?;
        let mut fb = ChunkBuilder::new();
        // Each function body is its own frame, so it gets its own slot table.
        // The analysis sees the parameter prologue (defaults, destructuring)
        // ahead of the body, which is the order they are emitted in.
        let mut planned: Vec<Stmt> = prologue.clone();
        planned.extend_from_slice(body);
        let saved_slot_table = std::mem::replace(
            &mut self.slots,
            if self.debug || is_generator || is_async {
                Default::default()
            } else {
                crate::slots::plan(params, &planned, false)
            },
        );
        // Prologue: a parameter arrives in the call environment (`bind_params`
        // ran before this chunk), so copy each slotted one into its slot once,
        // and everything after it is a bare `GetSlot`.
        for name in crate::slots::param_names(params) {
            if let Some(slot) = self.slot_of(&name) {
                self.name_const(&mut fb, &name);
                fb.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
                fb.emit(Op::SetSlot(slot), 0);
            }
        }
        // A function body is its own control-flow universe: `break`/`continue` can
        // never target a loop in the enclosing function.
        let saved_loops = std::mem::take(&mut self.loops);
        let saved_base = std::mem::replace(&mut self.chunk_loop_base, 0);
        let saved_signals = std::mem::take(&mut self.chunk_signals);
        let saved_depth = std::mem::take(&mut self.scope_depth);
        let saved_iters = std::mem::take(&mut self.iter_depth);
        let saved_agen = std::mem::replace(&mut self.in_async_generator, is_generator && is_async);
        // Strictness is inherited by every nested function and can only be
        // ADDED by a body's own directive prologue — never dropped.
        let saved_strict = self.strict;
        self.strict = self.strict || has_use_strict(body);
        // A nested function's statements are not the SCRIPT's, so none of them
        // may touch the completion register.
        let saved_completion = std::mem::take(&mut self.completion);
        // Captured before the restore below, since the FuncDef is built after
        // `self.strict` has been put back to the enclosing value.
        let body_strict = self.strict;
        // The body is a chunk of its own, so its call sites are keyed to ITS
        // `op_hash`; the enclosing chunk's pending ones must not be swept in.
        let saved_sites = std::mem::take(&mut self.call_sites);
        let saved_yields = std::mem::take(&mut self.yield_sites);
        let r = (|| {
            // Function-body hoisting: `var` bindings first, so a same-named
            // function declaration below overwrites the `undefined` rather than
            // being overwritten by it. Parameters are already bound, and
            // `hoist_var_name` leaves an existing binding alone.
            self.hoist_vars(&mut fb, body)?;
            self.hoist_funcs(&mut fb, &prologue)?;
            self.hoist_lexical(&mut fb, body);
            self.hoist_funcs(&mut fb, body)?;
            self.compile_stmts(&mut fb, &prologue)?;
            self.compile_stmts(&mut fb, body)
        })();
        self.loops = saved_loops;
        self.chunk_loop_base = saved_base;
        self.chunk_signals = saved_signals;
        self.scope_depth = saved_depth;
        self.iter_depth = saved_iters;
        self.in_async_generator = saved_agen;
        self.strict = saved_strict;
        self.completion = saved_completion;
        self.slots = saved_slot_table;
        r?;
        let def = FuncDef {
            name: name.to_string(),
            params: param_slots,
            chunk: self.finish_chunk(fb),
            is_arrow: false,
            is_generator,
            is_async,
            is_method: false,
            self_name: false,
            strict: body_strict,
            span: (0, 0),
            script: None,
        };
        self.call_sites = saved_sites;
        self.yield_sites = saved_yields;
        self.functions.push((name.to_string(), def));
        Ok(self.functions.len() - 1)
    }

    /// A FuncDef that only carries `span`: the source of a `class`, which has
    /// no function of its own when it declares no constructor.
    fn source_record(&mut self, name: &str, span: Span) -> usize {
        let def = FuncDef {
            name: name.to_string(),
            params: Vec::new(),
            chunk: ChunkBuilder::new().build(),
            is_arrow: false,
            is_generator: false,
            is_async: false,
            is_method: true,
            self_name: false,
            strict: true,
            span,
            script: None,
        };
        self.functions.push((name.to_string(), def));
        self.functions.len() - 1
    }

    fn build_arrow(
        &mut self,
        params: &[Param],
        body: &FnBody,
        is_async: bool,
    ) -> Result<usize, String> {
        let stmts = match body {
            FnBody::Block(b) => b.clone(),
            FnBody::Expr(e) => vec![Stmt::from(StmtKind::Return(Some((**e).clone())))],
        };
        let id = self.build_function("", params, &stmts, false, is_async)?;
        // Mark the template as an arrow so `this` is captured lexically.
        self.functions[id].1.is_arrow = true;
        Ok(id)
    }

    // ── classes ──────────────────────────────────────────────────────────
    /// Lower a `class` to runtime builder ops, leaving the class value on the
    /// stack: `MKCLASS` (name, parent, ctor) then `DEF_MEMBER`/`DEF_FIELD` for
    /// each member (each keeps the class on the stack).
    fn compile_class(&mut self, b: &mut ChunkBuilder, node: &ClassNode) -> Result<(), String> {
        // A class body is strict code unconditionally (10.2.4), directive or not.
        let saved_strict = std::mem::replace(&mut self.strict, true);
        let r = self.compile_class_body(b, node);
        self.strict = saved_strict;
        r
    }

    /// `#name` when this member's key is a literal private name, else `None`. A
    /// private name is never computed, so a computed key is never one.
    fn private_key(m: &ClassMember) -> Option<String> {
        match &m.key {
            Expr::Str(s) if !m.computed && s.starts_with('#') => Some(s.clone()),
            Expr::Ident(s) if !m.computed && s.starts_with('#') => Some(s.clone()),
            _ => None,
        }
    }

    fn compile_class_body(&mut self, b: &mut ChunkBuilder, node: &ClassNode) -> Result<(), String> {
        let cname = node.name.clone().unwrap_or_default();
        // Push name, parent (or undefined), constructor (or undefined).
        self.name_const(b, &cname);
        match &node.parent {
            Some(p) => self.compile_expr(b, p)?,
            None => {
                b.emit(Op::LoadUndef, 0);
            }
        }
        let ctor = node
            .members
            .iter()
            .find(|m| m.kind == MemberKind::Constructor);
        match ctor {
            Some(m) => {
                let def_id = self.build_function(&cname, &m.params, &m.body, false, false)?;
                self.emit_mkfunc(b, def_id);
            }
            None => {
                b.emit(Op::LoadUndef, 0);
            }
        }
        // The class's source text (`String(C)`) rides on a FuncDef that is
        // never called, so its span is script-relative like any function's
        // and its id is rebased with the rest.
        let record = self.source_record(&cname, node.span);
        b.emit(Op::LoadInt(record as i64), 0);
        b.emit(Op::CallBuiltin(ops::MKCLASS, 4), 0); // -> [class]

        // 15.7.14 steps 8-17: the class body runs inside its OWN environment,
        // holding one immutable binding for the class name, initialized to the
        // class itself at step 17 — before the static-field initializers of step
        // 32. So `class C { static x = C.m(); static m(){return 5} }` is 5, and a
        // class EXPRESSION's name (`const K = class Inner { static s = Inner.name }`)
        // is reachable from inside the body even though it is never a binding
        // outside it. node-js had no such scope: both threw `ReferenceError: C is
        // not defined`, because the only binding was the outer one the class
        // DECLARATION installs afterwards. An instance method's body already
        // worked, but only by accident — it runs late enough for the outer
        // binding to exist, which a class expression never gets.
        let body_scope = node.name.is_some();
        if let Some(name) = &node.name {
            self.emit_push_scope(b);
            b.emit(Op::Dup, 0); // [class, class]
            self.declare_as(b, &Expr::Ident(name.clone()), BindMode::Const); // [class]
        }

        // `ClassDefinitionEvaluation` (15.7.14) installs every method and
        // accessor while evaluating the class body, and only then runs the
        // static-field initializers (step 32). So a static field may call a
        // static method declared after it, and `getOwnPropertyNames(C)` lists
        // the methods before the fields regardless of source order.
        // A `static { … }` block is a static ELEMENT, not a method: it belongs in
        // the deferred group with the field initializers and runs interleaved
        // with them in source order (both filters are stable over `members`).
        let deferred = |k: &MemberKind| matches!(k, MemberKind::Field | MemberKind::StaticBlock);
        let ordered = node
            .members
            .iter()
            .filter(|m| !deferred(&m.kind))
            .chain(node.members.iter().filter(|m| deferred(&m.kind)));
        let mut static_block_n = 0usize;
        for m in ordered {
            match m.kind {
                MemberKind::Constructor => {}
                // A PRIVATE static field declares a private element, so it
                // cannot be an ordinary write: `C.#s = 5` through `SETATTR`
                // trips the brand check that exists to reject exactly that write
                // on an object that has not declared `#s`. `DEF_MEMBER` installs
                // it directly, which is what a declaration is.
                MemberKind::Field if m.is_static && Self::private_key(m).is_some() => {
                    let key = Self::private_key(m).expect("guarded above");
                    self.name_const(b, &key); // [class, name]
                    b.emit(Op::LoadInt(member::STATIC_FIELD), 0);
                    b.emit(Op::LoadTrue, 0); // is_static
                    match &m.field_init {
                        Some(e) => self.emit_keyed_value(b, &m.key, e, false, member::METHOD)?,
                        None => {
                            b.emit(Op::LoadUndef, 0);
                        }
                    }
                    b.emit(Op::CallBuiltin(ops::DEF_MEMBER, 5), 0); // -> [class]
                }
                MemberKind::Field if m.is_static => {
                    // A static field is evaluated once at class-definition time and
                    // set as an own property of the constructor: `[class]` stays on
                    // the stack, `Dup` it as the SETATTR receiver.
                    b.emit(Op::Dup, 0); // [class, class]
                    self.emit_member_key(b, m)?; // [class, class, name]
                    match &m.field_init {
                        // 15.7.10: a static field's initializer is named after
                        // the field (`static s = function(){}` → `s`).
                        Some(e) => {
                            self.emit_keyed_value(b, &m.key, e, m.computed, member::METHOD)?
                        }
                        None => {
                            b.emit(Op::LoadUndef, 0);
                        }
                    }
                    // [class, class, name, val] -> SETATTR sets on the class -> [class, val]
                    b.emit(Op::CallBuiltin(ops::SETATTR, 3), 0);
                    b.emit(Op::Pop, 0); // drop the returned value -> [class]
                }
                MemberKind::Field => {
                    // [class] name thunk name_anon -> DEF_FIELD -> [class]
                    self.emit_member_key(b, m)?;
                    let init = m.field_init.clone().unwrap_or(Expr::Undefined);
                    // 15.7.10: `class C { f = function(){} }` names the function
                    // `f`. An instance field's initializer runs per-instance from
                    // a thunk, and under a computed key the key is only known at
                    // class-definition time, so the decision travels to the host
                    // as a flag rather than as an emitted rename.
                    let name_anon = Self::is_anon_fn_def(&init);
                    let stmts = vec![Stmt::from(StmtKind::Return(Some(init)))];
                    let def_id = self.build_function("", &[], &stmts, false, false)?;
                    self.emit_mkfunc(b, def_id);
                    b.emit(
                        if name_anon {
                            Op::LoadTrue
                        } else {
                            Op::LoadFalse
                        },
                        0,
                    );
                    b.emit(Op::CallBuiltin(ops::DEF_FIELD, 4), 0);
                }
                MemberKind::StaticBlock => {
                    // `static { … }` runs ONCE at class-definition time with
                    // `this` bound to the constructor — exactly what a static
                    // method called as `C.m()` gets. So it is compiled as a
                    // static method under a HIDDEN key, invoked, and removed
                    // again; the `@@` prefix keeps it out of every enumeration
                    // (`Object.getOwnPropertyNames(C)` and friends filter
                    // internal slots) for the window in which it exists, and the
                    // counter keeps sibling blocks from colliding.
                    static_block_n += 1;
                    let slot = format!("@@staticBlock:{static_block_n}");
                    // [class] name kind static fn -> DEF_MEMBER -> [class]
                    self.name_const(b, &slot);
                    b.emit(Op::LoadInt(member::METHOD), 0);
                    b.emit(Op::LoadTrue, 0);
                    let def_id = self.build_function("", &[], &m.body, false, false)?;
                    self.functions[def_id].1.is_method = true;
                    self.emit_mkfunc(b, def_id);
                    b.emit(Op::CallBuiltin(ops::DEF_MEMBER, 5), 0);
                    // [class] -> C[slot]() -> discard the result
                    b.emit(Op::Dup, 0);
                    self.name_const(b, &slot);
                    b.emit(Op::CallBuiltin(ops::CALL_METHOD, 2), 0);
                    b.emit(Op::Pop, 0);
                    // [class] -> delete C[slot] -> discard the Bool
                    b.emit(Op::Dup, 0);
                    self.name_const(b, &slot);
                    self.emit_bool(b, false);
                    b.emit(Op::CallBuiltin(ops::DELPROP_NAME, 3), 0);
                    b.emit(Op::Pop, 0);
                }
                MemberKind::Method | MemberKind::Get | MemberKind::Set => {
                    // [class] name kind static fn -> DEF_MEMBER -> [class]
                    self.emit_member_key(b, m)?;
                    let kind = match m.kind {
                        MemberKind::Get => member::GET,
                        MemberKind::Set => member::SET,
                        _ => member::METHOD,
                    };
                    b.emit(Op::LoadInt(kind), 0);
                    b.emit(
                        if m.is_static {
                            Op::LoadTrue
                        } else {
                            Op::LoadFalse
                        },
                        0,
                    );
                    // 10.2.9 step 4: an accessor's function name carries the
                    // `get `/`set ` prefix — `class C { get gg(){} }` gives
                    // `get gg`, not `gg`.
                    let mname = match &m.key {
                        Expr::Str(s) if !m.computed => match m.kind {
                            MemberKind::Get => format!("get {s}"),
                            MemberKind::Set => format!("set {s}"),
                            _ => s.clone(),
                        },
                        _ => String::new(),
                    };
                    let def_id = self.build_function(
                        &mname,
                        &m.params,
                        &m.body,
                        m.is_generator,
                        m.is_async,
                    )?;
                    // A class method/accessor is a MethodDefinition: not a
                    // constructor, so it owns no `prototype` property.
                    self.functions[def_id].1.is_method = true;
                    self.functions[def_id].1.span = m.span;
                    self.emit_mkfunc(b, def_id);
                    b.emit(Op::CallBuiltin(ops::DEF_MEMBER, 5), 0);
                }
            }
        }
        if body_scope {
            self.emit_pop_scope(b);
        }
        Ok(())
    }

    /// `IsAnonymousFunctionDefinition(expr)` — the SYNTACTIC predicate that
    /// decides whether NamedEvaluation applies. It is deliberately not a runtime
    /// "does this function have an empty name" test: measured against node
    /// v26.7.0, `const anon = (0, function(){}); ({ m: anon }).m.name` is `""`,
    /// because the property definition's right-hand side is an
    /// IdentifierReference, not a function definition. Renaming by value would
    /// also mutate a function the program still holds under another binding.
    fn is_anon_fn_def(init: &Expr) -> bool {
        match init {
            Expr::Function { name: None, .. } => true,
            Expr::Class(node) => node.name.is_none(),
            _ => false,
        }
    }

    /// If `init` is an anonymous function/arrow/class (value already on TOS), set
    /// its `.name` to `name` (JS binding name-inference). No-op otherwise.
    fn infer_name(&mut self, b: &mut ChunkBuilder, init: &Expr, name: &str) {
        if !Self::is_anon_fn_def(init) {
            return;
        }
        // [fn] Dup; .name = name; drop the SETATTR result.
        b.emit(Op::Dup, 0);
        self.name_const(b, "name");
        self.strlit(b, name);
        b.emit(Op::CallBuiltin(ops::SETATTR, 3), 0);
        b.emit(Op::Pop, 0);
    }

    /// Compile a member's VALUE with the key already on the stack, applying
    /// NamedEvaluation (10.2.9 SetFunctionName) when the value is an anonymous
    /// function definition — `{ m: function(){} }`, `{ m(){} }`, `{ [k]: () => {} }`,
    /// `class C { static [k] = function(){} }`.
    ///
    /// A literal key resolves at compile time; a computed one is only known at
    /// run time, so the key already on the stack is duplicated and handed to
    /// `NAMED_EVAL` along with `kind` (which supplies the `get `/`set ` prefix).
    /// Leaves exactly one value on the stack either way, so every caller's
    /// arity is unchanged.
    fn emit_keyed_value(
        &mut self,
        b: &mut ChunkBuilder,
        key: &Expr,
        value: &Expr,
        computed: bool,
        kind: i64,
    ) -> Result<(), String> {
        match (Self::is_anon_fn_def(value), computed, key) {
            (true, false, Expr::Str(s)) => {
                self.compile_expr(b, value)?;
                let name = match kind {
                    member::GET => format!("get {s}"),
                    member::SET => format!("set {s}"),
                    _ => s.clone(),
                };
                self.infer_name(b, value, &name);
            }
            // [.., key] -> [.., key, key, kind, fn] -> NAMED_EVAL -> [.., key, fn]
            (true, true, _) => {
                b.emit(Op::Dup, 0);
                b.emit(Op::LoadInt(kind), 0);
                self.compile_expr(b, value)?;
                b.emit(Op::CallBuiltin(ops::NAMED_EVAL, 3), 0);
            }
            _ => self.compile_expr(b, value)?,
        }
        Ok(())
    }

    /// Push a class/object member's property key: a computed expression coerced
    /// via `PROPKEY` (Symbol-aware), or a static name constant.
    fn emit_member_key(&mut self, b: &mut ChunkBuilder, m: &ClassMember) -> Result<(), String> {
        if m.computed {
            self.compile_expr(b, &m.key)?;
            b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
        } else if let Expr::Str(s) = &m.key {
            self.name_const(b, s);
        } else {
            self.compile_expr(b, &m.key)?;
            b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
        }
        Ok(())
    }

    // ── generators / yield ───────────────────────────────────────────────
    fn compile_yield(
        &mut self,
        b: &mut ChunkBuilder,
        arg: &Option<Box<Expr>>,
        delegate: bool,
    ) -> Result<(), String> {
        if delegate && self.in_async_generator {
            // `yield* x` inside an `async function*` delegates over the ASYNC
            // iterator: await each step, re-yield its value, and evaluate to the
            // delegate's return value.
            match arg {
                Some(e) => self.compile_expr(b, e)?,
                None => {
                    b.emit(Op::LoadUndef, 0);
                }
            }
            b.emit(Op::CallBuiltin(ops::GET_ASYNC_ITER, 1), 0); // [aiter]
            let start = b.current_pos();
            b.emit(Op::Dup, 0); // [aiter, aiter]
            b.emit(Op::CallBuiltin(ops::ASYNC_STEP, 1), 0); // [aiter, stepPromise]
            b.emit(Op::CallBuiltin(ops::AWAIT, 1), 0); // [aiter, step]
            b.emit(Op::Dup, 0); // [aiter, step, step]
            self.name_const(b, "done");
            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0);
            b.emit(Op::CallBuiltin(ops::TRUTHY, 1), 0);
            let jdone = b.emit(Op::JumpIfTrue(0), 0); // [aiter, step]
            self.name_const(b, "value");
            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [aiter, value]
            let at = b.emit(Op::CallBuiltin(ops::YIELD, 1), 0); // [aiter, sent]
            self.yield_sites.push((at, self.iter_depth));
            b.emit(Op::Pop, 0); // [aiter]
            b.emit(Op::Jump(start), 0);
            let done = b.current_pos();
            b.patch_jump(jdone, done);
            self.name_const(b, "value"); // [aiter, step, "value"]
            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [aiter, returnValue]
            b.emit(Op::Swap, 0); // [returnValue, aiter]
            b.emit(Op::Pop, 0); // [returnValue]
        } else if delegate {
            // `yield* iterable`: step the delegate through the iterator protocol,
            // re-yielding each value and FORWARDING whatever `.next(x)` sent in.
            // The expression's value is the delegate's RETURN value, which
            // `FORITER` discards — hence the explicit `.next()` calls.
            let sent_tmp = self.tmp_name("delegated");
            match arg {
                Some(e) => self.compile_expr(b, e)?,
                None => {
                    b.emit(Op::LoadUndef, 0);
                }
            }
            b.emit(Op::CallBuiltin(ops::GETITER, 1), 0); // [iterator]
                                                         // The delegate is parked on the stack for the whole delegation, so
                                                         // it counts as a live iterator: a `.return()`/`.throw()` injected
                                                         // into the OUTER generator has to close it (7.4.9 IteratorClose),
                                                         // which is what runs the delegate's pending `finally`.
            self.iter_depth += 1;
            self.name_const(b, &sent_tmp);
            b.emit(Op::LoadUndef, 0);
            b.emit(Op::CallBuiltin(ops::DECLARE, 2), 0);
            b.emit(Op::Pop, 0);
            let start = b.current_pos();
            b.emit(Op::Dup, 0); // [iterator, iterator]
            self.name_const(b, "next");
            self.load_local(b, &sent_tmp);
            b.emit(Op::CallBuiltin(ops::CALL_METHOD, 3), 0); // [iterator, step]
            b.emit(Op::Dup, 0);
            self.name_const(b, "done");
            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0);
            b.emit(Op::CallBuiltin(ops::TRUTHY, 1), 0);
            let jdone = b.emit(Op::JumpIfTrue(0), 0); // [iterator, step]
            self.name_const(b, "value");
            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [iterator, value]
            let at = b.emit(Op::CallBuiltin(ops::YIELD, 1), 0); // [iterator, sent]
            self.yield_sites.push((at, self.iter_depth));
            self.name_const(b, &sent_tmp);
            b.emit(Op::Swap, 0);
            b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
            b.emit(Op::Pop, 0);
            b.emit(Op::Jump(start), 0);
            let done = b.current_pos();
            b.patch_jump(jdone, done);
            self.name_const(b, "value"); // [iterator, step, "value"]
            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [iterator, returnValue]
            b.emit(Op::Swap, 0);
            b.emit(Op::Pop, 0); // [returnValue]
            self.iter_depth -= 1;
        } else {
            match arg {
                Some(e) => self.compile_expr(b, e)?,
                None => {
                    b.emit(Op::LoadUndef, 0);
                }
            }
            // YIELD suspends and leaves the value sent by `.next(x)` on the stack.
            let at = b.emit(Op::CallBuiltin(ops::YIELD, 1), 0);
            self.yield_sites.push((at, self.iter_depth));
        }
        Ok(())
    }

    /// Lower a formal-parameter list into simple slots plus prologue statements
    /// (defaults + destructuring), executed at the top of the body.
    fn lower_params(&mut self, params: &[Param]) -> Result<(Vec<ParamSlot>, Vec<Stmt>), String> {
        // Strict code refuses a DUPLICATE parameter name, and refuses `eval` or
        // `arguments` as one. Both are early errors, so they fire before the
        // body runs — sloppy code still allows the duplicate, where the LAST
        // one wins.
        if self.strict {
            let mut seen: Vec<String> = Vec::new();
            for p in params {
                for n in binding_names(&p.pattern) {
                    if RESERVED_IN_STRICT.contains(&n.as_str()) {
                        return Err(strict_reserved_error());
                    }
                    if seen.contains(&n) {
                        return Err(
                            "SyntaxError: Duplicate parameter name not allowed in this context"
                                .to_string(),
                        );
                    }
                    seen.push(n);
                }
            }
        }
        let mut slots = Vec::new();
        let mut prologue: Vec<Stmt> = Vec::new();
        for (i, p) in params.iter().enumerate() {
            if p.rest {
                let name = match &p.pattern {
                    Expr::Ident(n) => n.clone(),
                    _ => return Err("SyntaxError: rest parameter must be an identifier".into()),
                };
                slots.push(ParamSlot {
                    name,
                    rest: true,
                    has_default: false,
                });
                continue;
            }
            match &p.pattern {
                Expr::Ident(name) => {
                    slots.push(ParamSlot {
                        name: name.clone(),
                        rest: false,
                        has_default: p.default.is_some(),
                    });
                    if let Some(d) = &p.default {
                        prologue.push(default_stmt(name, d));
                    }
                }
                pattern => {
                    let synth = format!(".param{i}");
                    slots.push(ParamSlot {
                        name: synth.clone(),
                        rest: false,
                        has_default: p.default.is_some(),
                    });
                    if let Some(d) = &p.default {
                        prologue.push(default_stmt(&synth, d));
                    }
                    prologue.push(Stmt::from(StmtKind::Decl {
                        kind: DeclKind::Let,
                        decls: vec![Declarator {
                            target: pattern.clone(),
                            init: Some(Expr::Ident(synth)),
                        }],
                    }));
                }
            }
        }
        Ok((slots, prologue))
    }

    // ── expressions ──────────────────────────────────────────────────────
    fn compile_expr(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
        match e {
            Expr::Undefined => {
                b.emit(Op::LoadUndef, 0);
            }
            // A hole only carries its extra meaning INSIDE an array literal
            // (`compile_array` records it); evaluated anywhere else it is just
            // the `undefined` an elided read produces.
            Expr::Hole => {
                b.emit(Op::LoadUndef, 0);
            }
            Expr::Null => {
                b.emit(Op::CallBuiltin(ops::LOAD_NULL, 0), 0);
            }
            Expr::True => {
                b.emit(Op::LoadTrue, 0);
            }
            Expr::False => {
                b.emit(Op::LoadFalse, 0);
            }
            Expr::Number(n) => {
                b.emit(Op::LoadFloat(*n), 0);
            }
            Expr::BigInt(digits) => {
                // The canonical decimal digit string travels as a native constant;
                // MKBIGINT parses it into a heap BigInt at runtime.
                let k = b.add_constant(Value::str(digits));
                b.emit(Op::LoadConst(k), 0);
                b.emit(Op::CallBuiltin(ops::MKBIGINT, 1), 0);
            }
            Expr::Regex(pat, flags) => {
                let kp = b.add_constant(Value::str(pat));
                b.emit(Op::LoadConst(kp), 0);
                let kf = b.add_constant(Value::str(flags));
                b.emit(Op::LoadConst(kf), 0);
                b.emit(Op::CallBuiltin(ops::MKREGEX, 2), 0);
            }
            Expr::Str(s) => self.strlit(b, s),
            Expr::Template { quasis, exprs } => self.compile_template(b, quasis, exprs)?,
            Expr::TaggedTemplate {
                tag,
                quasis,
                raws,
                exprs,
            } => self.compile_tagged_template(b, tag, quasis, raws, exprs)?,
            Expr::Ident(n) => self.load_local(b, n),
            Expr::This => {
                b.emit(Op::CallBuiltin(ops::THIS, 0), 0);
            }
            Expr::Array(items) => self.compile_array(b, items)?,
            Expr::Object(props) => self.compile_object(b, props)?,
            Expr::Spread(inner) => self.compile_expr(b, inner)?,
            Expr::Logical(op, l, r) => self.compile_logical(b, *op, l, r)?,
            Expr::Unary(op, e) => self.compile_unary(b, *op, e)?,
            Expr::Binary(op, l, r) => self.compile_binary(b, *op, l, r)?,
            Expr::Conditional { test, cons, alt } => {
                self.compile_condition(b, test)?;
                let jf = b.emit(Op::JumpIfFalse(0), 0);
                self.compile_expr(b, cons)?;
                let je = b.emit(Op::Jump(0), 0);
                let els = b.current_pos();
                b.patch_jump(jf, els);
                self.compile_expr(b, alt)?;
                let end = b.current_pos();
                b.patch_jump(je, end);
            }
            // A COMPOUND assignment (`o[k()] += 1`) evaluates the target
            // reference once. Handled ahead of the plain-`=` arms below because
            // it must keep that reference on the stack across the read, the
            // computation and the write, which a plain assignment never does.
            Expr::Assign {
                target,
                op: Some(aop),
                value,
            } => self.compile_compound_assign(b, target, *aop, value)?,
            // 13.15.1 / 13.4.1: strict code may not assign to, or update,
            // `eval` or `arguments`. Both are early errors.
            Expr::Assign { target, .. } | Expr::Update { target, .. }
                if self.strict
                    && matches!(&**target, Expr::Ident(n)
                        if RESERVED_IN_STRICT.contains(&n.as_str())) =>
            {
                return Err(strict_reserved_error());
            }
            Expr::Assign { target, value, .. } => match &**target {
                // 13.15.2 steps 1.a-1.f: for a PROPERTY target the reference is
                // evaluated first — the object, then the key — and only then the
                // right-hand side. Routing these through `compile_bind` emitted
                // the value first and the reference after, so every side effect
                // in the target ran in the wrong order: `o[k()] = v()` called
                // `v` before `k`, and `a[i++] = f()` passed `f` the
                // already-incremented index. Both builtins return the value they
                // stored, which is also the value of the assignment expression,
                // so the `Dup`/`Rot`/`Pop` the generic path needed all fall away.
                Expr::Member {
                    object, property, ..
                } => {
                    self.compile_expr(b, object)?; // [recv]
                    self.name_const(b, property); // [recv, name]
                    self.compile_expr(b, value)?; // [recv, name, value]
                    b.emit(Op::CallBuiltin(ops::SETATTR, 3), 0); // [value]
                }
                Expr::Index { object, index, .. } => {
                    self.compile_expr(b, object)?; // [recv]
                    self.compile_expr(b, index)?; // [recv, idx]
                    self.compile_expr(b, value)?; // [recv, idx, value]
                    b.emit(Op::CallBuiltin(ops::SETITEM, 3), 0); // [value]
                }
                _ => {
                    self.compile_expr(b, value)?;
                    // 13.15.2 step 1.e: `h = function(){}` names the function `h`.
                    // Only an IdentifierReference target counts — `o.p = function(){}`
                    // leaves the name empty in node too.
                    if let Expr::Ident(n) = &**target {
                        self.infer_name(b, value, n);
                    }
                    b.emit(Op::Dup, 0); // assignment yields the value
                    self.destructure_src = destructure_source_text(value);
                    let r = self.compile_bind(b, target, BindMode::Assign);
                    self.destructure_src = None;
                    r?;
                }
            },
            Expr::Update { op, prefix, target } => self.compile_update(b, *op, *prefix, target)?,
            // A chain's ROOT opens the frame its `?.` links park their jumps
            // in; nested links see it already open and add to it.
            Expr::Call { .. } | Expr::Member { .. } | Expr::Index { .. }
                if self.opt_chain.is_empty() && Self::spine_has_optional(e) =>
            {
                self.compile_chain_root(b, e)?
            }
            Expr::Call {
                func,
                args,
                optional,
            } => self.compile_call(b, func, args, *optional)?,
            Expr::New { callee, args } => self.compile_new(b, callee, args)?,
            Expr::Member {
                object,
                property,
                optional,
            } => self.compile_member(b, object, property, *optional)?,
            Expr::Index {
                object,
                index,
                optional,
            } => self.compile_index(b, object, index, *optional)?,
            Expr::Function {
                params,
                body,
                is_arrow,
                name,
                is_generator,
                is_async,
                is_method,
                span,
            } => {
                let def_id = if *is_arrow {
                    self.build_arrow(params, body, *is_async)?
                } else {
                    let n = name.clone().unwrap_or_default();
                    let stmts = match body {
                        FnBody::Block(b) => b.clone(),
                        FnBody::Expr(e) => vec![Stmt::from(StmtKind::Return(Some((**e).clone())))],
                    };
                    let id = self.build_function(&n, params, &stmts, *is_generator, *is_async)?;
                    // A NAMED function expression binds its own name inside the body
                    // (object/class methods parse with `name: None`, so this only
                    // fires for `function name(…) {…}` in expression position).
                    if name.is_some() {
                        self.functions[id].1.self_name = true;
                    }
                    self.functions[id].1.is_method = *is_method;
                    id
                };
                self.functions[def_id].1.span = *span;
                self.emit_mkfunc(b, def_id);
            }
            Expr::Class(node) => self.compile_class(b, node)?,
            Expr::Super => {
                // Bare `super` only appears as a call/member callee, handled by
                // compile_call / compile_member; a stray `super` yields undefined.
                b.emit(Op::LoadUndef, 0);
            }
            Expr::NewTarget => {
                b.emit(Op::CallBuiltin(ops::NEW_TARGET, 0), 0);
            }
            Expr::Yield { arg, delegate } => self.compile_yield(b, arg, *delegate)?,
            Expr::Await(inner) => {
                self.compile_expr(b, inner)?;
                b.emit(Op::CallBuiltin(ops::AWAIT, 1), 0);
            }
            Expr::Sequence(items) => {
                for (i, it) in items.iter().enumerate() {
                    self.compile_expr(b, it)?;
                    if i + 1 < items.len() {
                        b.emit(Op::Pop, 0);
                    }
                }
            }
        }
        Ok(())
    }

    fn compile_template(
        &mut self,
        b: &mut ChunkBuilder,
        quasis: &[String],
        exprs: &[Expr],
    ) -> Result<(), String> {
        let mut n = 0;
        for (i, q) in quasis.iter().enumerate() {
            let k = b.add_constant(Value::str(q));
            b.emit(Op::LoadConst(k), 0);
            n += 1;
            if i < exprs.len() {
                self.compile_expr(b, &exprs[i])?;
                b.emit(Op::CallBuiltin(ops::TOSTR, 1), 0);
                n += 1;
            }
        }
        b.emit(Op::CallBuiltin(ops::MKSTR, argc(n)?), 0);
        Ok(())
    }

    /// Lower a tagged template to `TAG_TMPL`. Operand layout (matching
    /// `builtins::b_tag_tmpl`): `[this, tag, n, m, site, cooked×n, raw×n,
    /// values×m]`, where `n = quasis.len()` and `m = exprs.len()`
    /// (`n == m + 1`).
    ///
    /// `this` is the tag's receiver. A tagged template IS a call (13.3.11.1
    /// evaluates the tag as a MemberExpression and passes its reference's base
    /// as the `this` argument), so ``o.m`a` `` runs `m` with `this === o` — it
    /// ran with `this` undefined, which broke every tag written as a method.
    /// `undefined` for a tag that is not a property reference.
    ///
    /// `site` is this site's ordinal in the compilation; the runtime caches the
    /// template object under it so a site evaluated twice hands back the same
    /// object.
    fn compile_tagged_template(
        &mut self,
        b: &mut ChunkBuilder,
        tag: &Expr,
        quasis: &[String],
        raws: &[String],
        exprs: &[Expr],
    ) -> Result<(), String> {
        match tag {
            // `o.m`…`` / `o?.m`…`` — the receiver stays on the stack under the
            // method, so both are evaluated exactly once.
            Expr::Member {
                object,
                property,
                optional: false,
            } if !matches!(**object, Expr::Super) => {
                self.compile_expr(b, object)?; // [o]
                b.emit(Op::Dup, 0); // [o, o]
                self.name_const(b, property);
                b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [o, f]
            }
            _ => {
                b.emit(Op::LoadUndef, 0);
                self.compile_expr(b, tag)?;
            }
        }
        let n = quasis.len();
        let m = exprs.len();
        let site = self.tmpl_sites;
        self.tmpl_sites += 1;
        b.emit(Op::LoadInt(n as i64), 0);
        b.emit(Op::LoadInt(m as i64), 0);
        b.emit(Op::LoadInt(site as i64), 0);
        for q in quasis {
            self.strlit(b, q); // cooked strings (heap)
        }
        for r in raws {
            self.strlit(b, r); // raw strings (heap)
        }
        for e in exprs {
            self.compile_expr(b, e)?; // substitution values
        }
        b.emit(Op::CallBuiltin(ops::TAG_TMPL, argc(5 + 2 * n + m)?), 0);
        Ok(())
    }

    fn compile_array(&mut self, b: &mut ChunkBuilder, items: &[Expr]) -> Result<(), String> {
        if items.iter().any(|e| matches!(e, Expr::Spread(_))) {
            // (tag, value) pairs; tag 1 = spread, tag 2 = elision. A spread
            // makes every later element's index a RUN-TIME quantity, so the
            // holes cannot be recorded from here — the tag carries the fact and
            // `BUILD_ARGS` marks them as it walks.
            for it in items {
                match it {
                    Expr::Spread(inner) => {
                        b.emit(Op::LoadInt(1), 0);
                        self.compile_expr(b, inner)?;
                    }
                    Expr::Hole => {
                        b.emit(Op::LoadInt(2), 0);
                        b.emit(Op::LoadUndef, 0);
                    }
                    _ => {
                        b.emit(Op::LoadInt(0), 0);
                        self.compile_expr(b, it)?;
                    }
                }
            }
            let at = b.current_pos();
            b.emit(Op::CallBuiltin(ops::BUILD_ARGS, argc(items.len() * 2)?), 0);
            // A spread over a non-iterable names the SOURCE: `[...o]` reports
            // `o is not iterable`. One op covers the whole literal, so the text
            // is recorded only when a SINGLE spread could have raised it —
            // with two, this cannot say which one did, and naming the wrong
            // expression is worse than rendering the value.
            let texts: Vec<Option<String>> = items
                .iter()
                .filter_map(|e| match e {
                    Expr::Spread(inner) => Some(callee_text(inner)),
                    _ => None,
                })
                .collect();
            // One op covers the whole literal, so a name can be recorded only
            // when every spread would produce the SAME one — with one spread
            // trivially, and with `[...o, ...o]` because either is the answer.
            // Two DIFFERENT sources cannot be told apart here, and naming the
            // wrong expression is worse than rendering the value.
            if let Some(first) = texts.first().cloned().flatten() {
                if texts.iter().all(|t| t.as_deref() == Some(first.as_str())) {
                    self.call_sites.push((at, first));
                }
            }
        } else if items.len() <= u8::MAX as usize {
            for it in items {
                self.compile_expr(b, it)?;
            }
            b.emit(Op::CallBuiltin(ops::MKARR, argc(items.len())?), 0);
            self.mark_literal_holes(b, items);
        } else {
            // A literal larger than one CallBuiltin's u8 arg count can hold (the
            // generated data tables in iconv-lite hit this): start from an empty
            // array and append each element with an indexed store, keeping the
            // array on the stack across iterations.
            b.emit(Op::CallBuiltin(ops::MKARR, 0), 0); // [arr]
            for (i, it) in items.iter().enumerate() {
                b.emit(Op::Dup, 0); // [arr, arr]
                b.emit(Op::LoadInt(i as i64), 0); // [arr, arr, i]
                self.compile_expr(b, it)?; // [arr, arr, i, val]
                b.emit(Op::CallBuiltin(ops::SETITEM, 3), 0); // -> [arr, val]
                b.emit(Op::Pop, 0); // [arr]
            }
            // After the writes: a `SETITEM` CLEARS the hole at the index it
            // writes, so marking has to come last.
            self.mark_literal_holes(b, items);
        }
        Ok(())
    }

    /// Emit a `MARK_HOLE` per elided position of a spread-free array literal,
    /// with the finished array on top of the stack. Emits nothing at all for the
    /// dense literals that are essentially every literal in real code.
    fn mark_literal_holes(&mut self, b: &mut ChunkBuilder, items: &[Expr]) {
        for (i, it) in items.iter().enumerate() {
            if !matches!(it, Expr::Hole) {
                continue;
            }
            b.emit(Op::Dup, 0); // [arr, arr]
            b.emit(Op::LoadInt(i as i64), 0); // [arr, arr, i]
            b.emit(Op::CallBuiltin(ops::MARK_HOLE, 2), 0); // [arr, undefined]
            b.emit(Op::Pop, 0); // [arr]
        }
    }

    fn compile_object(&mut self, b: &mut ChunkBuilder, props: &[Prop]) -> Result<(), String> {
        // (tag, key, val) triples for the data/spread props; tag 1 = ...spread.
        // Accessors are installed afterward via DEF_ACCESSOR.
        // An ACCESSOR keeps its slot in this list — with a tag of its own — so
        // the object enumerates it where the source declared it. The pair
        // `get`/`set` for one key contributes ONE slot.
        let mut seen_accessor: Vec<String> = Vec::new();
        let data: Vec<&Prop> = props
            .iter()
            .filter(|p| match p {
                Prop::Accessor { key, computed, .. } => {
                    // Only a literal key can be de-duplicated at compile time; a
                    // computed one is settled by `b_mkobj`'s `or_insert`.
                    let literal = match (key, computed) {
                        (Expr::Str(s), false) => Some(s.clone()),
                        _ => None,
                    };
                    match literal {
                        Some(k) if seen_accessor.contains(&k) => false,
                        Some(k) => {
                            seen_accessor.push(k);
                            true
                        }
                        None => true,
                    }
                }
                _ => true,
            })
            .collect();
        let has_spread = data.iter().any(|p| matches!(p, Prop::Spread(_)));
        // A spread-free literal with more triples than one CallBuiltin's u8 arg
        // count can hold (iconv-lite's generated codepage tables are 150+ keys)
        // is built incrementally: start empty, store each key, keeping the object
        // on the stack. Spread merges need the single-shot MKOBJ tag path, so
        // large-with-spread stays on it (a rare, genuine limitation).
        if data.len() * 3 > u8::MAX as usize && !has_spread {
            b.emit(Op::CallBuiltin(ops::MKOBJ, 0), 0); // [obj]
            for p in &data {
                if let Prop::KeyValue {
                    key,
                    value,
                    computed,
                } = p
                {
                    b.emit(Op::Dup, 0); // [obj, obj]
                    self.compile_expr(b, key)?;
                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0); // [obj, obj, key]
                    self.emit_keyed_value(b, key, value, *computed, member::METHOD)?;
                    b.emit(Op::CallBuiltin(ops::SETITEM, 3), 0); // -> [obj, val]
                    b.emit(Op::Pop, 0); // [obj]
                }
            }
            // The incremental path's accessors keep their trailing order: a
            // literal that large is a generated data table, and none carry one.
            return self.compile_object_accessors(b, props);
        }
        for p in &data {
            match p {
                Prop::KeyValue {
                    key,
                    value,
                    computed,
                } => {
                    // Tag 3 marks a METHOD DEFINITION, so `MKOBJ` can give it
                    // the literal as its `[[HomeObject]]`. It has to be decided
                    // HERE: a method assigned from elsewhere (`{ m: other.m }`)
                    // is an ordinary value whose home object was fixed where it
                    // was defined, and the runtime cannot tell the two apart
                    // from the value alone.
                    let defines_method = matches!(
                        value,
                        Expr::Function {
                            is_method: true,
                            ..
                        }
                    );
                    b.emit(Op::LoadInt(if defines_method { 3 } else { 0 }), 0);
                    // Key coerces to a property key (Symbol-aware: a Symbol maps to
                    // its internal `@@…` key rather than a `String()` coercion).
                    self.compile_expr(b, key)?;
                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
                    self.emit_keyed_value(b, key, value, *computed, member::METHOD)?;
                }
                Prop::Spread(src) => {
                    b.emit(Op::LoadInt(1), 0);
                    self.compile_expr(b, src)?;
                    b.emit(Op::LoadUndef, 0);
                }
                // Reserve the accessor's enumeration slot; `DEF_ACCESSOR` below
                // installs the functions themselves.
                Prop::Accessor { key, computed, .. } => {
                    let _ = computed; // the key expression covers both forms
                    b.emit(Op::LoadInt(2), 0);
                    self.compile_expr(b, key)?;
                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
                    b.emit(Op::LoadUndef, 0);
                }
            }
        }
        b.emit(Op::CallBuiltin(ops::MKOBJ, argc(data.len() * 3)?), 0); // [obj]
        self.compile_object_accessors(b, props)
    }

    /// Install any getter/setter accessors of an object literal onto the object
    /// left on the stack (shared by the single-shot and incremental build paths).
    fn compile_object_accessors(
        &mut self,
        b: &mut ChunkBuilder,
        props: &[Prop],
    ) -> Result<(), String> {
        for p in props {
            if let Prop::Accessor {
                key,
                computed,
                is_getter,
                func,
            } = p
            {
                if *computed {
                    self.compile_expr(b, key)?;
                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
                } else if let Expr::Str(s) = key {
                    self.name_const(b, s);
                } else {
                    self.compile_expr(b, key)?;
                    b.emit(Op::CallBuiltin(ops::PROPKEY, 1), 0);
                }
                let kind = if *is_getter { member::GET } else { member::SET };
                b.emit(Op::LoadInt(kind), 0);
                // `{ get g(){} }` names the getter `get g` (10.2.9 step 4 via
                // 13.2.5.5). A COMPUTED accessor key is the one member position
                // whose key is not still reachable on the stack here — `kind`
                // sits between it and the function — so it keeps the empty name.
                if *computed {
                    self.compile_expr(b, func)?;
                } else if let Expr::Str(s) = key {
                    self.compile_expr(b, func)?;
                    let prefix = if *is_getter { "get" } else { "set" };
                    self.infer_name(b, func, &format!("{prefix} {s}"));
                } else {
                    self.compile_expr(b, func)?;
                }
                b.emit(Op::CallBuiltin(ops::DEF_ACCESSOR, 4), 0);
            }
        }
        Ok(())
    }

    fn compile_logical(
        &mut self,
        b: &mut ChunkBuilder,
        op: LogicalOp,
        l: &Expr,
        r: &Expr,
    ) -> Result<(), String> {
        self.compile_expr(b, l)?;
        b.emit(Op::Dup, 0);
        let test_op = match op {
            LogicalOp::And | LogicalOp::Or => ops::TRUTHY,
            LogicalOp::Nullish => ops::NULLISH,
        };
        b.emit(Op::CallBuiltin(test_op, 1), 0);
        let jump = match op {
            LogicalOp::And => b.emit(Op::JumpIfFalse(0), 0), // false -> keep left
            LogicalOp::Or => b.emit(Op::JumpIfTrue(0), 0),   // true -> keep left
            LogicalOp::Nullish => b.emit(Op::JumpIfFalse(0), 0), // not-nullish -> keep left
        };
        b.emit(Op::Pop, 0); // drop left, evaluate right
        self.compile_expr(b, r)?;
        let end = b.current_pos();
        b.patch_jump(jump, end);
        Ok(())
    }

    /// `target op= value` with the target reference evaluated exactly ONCE.
    ///
    /// The parser hands the operator over instead of rewriting `a op= b` into
    /// `a = a op b`; that rewrite duplicated the target subtree, so every side
    /// effect in it ran twice (`o[k()] += 1` called `k` twice, and the logical
    /// forms called it twice even when they short-circuited and never wrote).
    /// The duplication could not be repaired downstream: after the rewrite,
    /// `o[k()] += 1` and the genuinely-twice-calling `o[k()] = o[k()] + 1` are
    /// the same tree.
    ///
    /// For a property target the reference is the pair `[recv, key]`, which
    /// `Dup2` copies for the read while the originals serve for the write. An
    /// identifier target has no reference to preserve — reading a name twice
    /// has no observable effect — so it keeps the simple lowering.
    fn compile_compound_assign(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        aop: AssignOp,
        value: &Expr,
    ) -> Result<(), String> {
        // The reference: leave `[recv, key]` on the stack, and report which
        // builtin pair reads and writes through it.
        let (get, set) = match target {
            Expr::Member {
                object, property, ..
            } => {
                self.compile_expr(b, object)?; // [recv]
                self.name_const(b, property); // [recv, name]
                (ops::GETATTR, ops::SETATTR)
            }
            Expr::Index { object, index, .. } => {
                self.compile_expr(b, object)?; // [recv]
                self.compile_expr(b, index)?; // [recv, idx]
                (ops::GETITEM, ops::SETITEM)
            }
            // An identifier (or anything else `compile_bind` accepts): no
            // reference to preserve, so read it, combine, and bind the result.
            _ => return self.compile_compound_ident(b, target, aop, value),
        };
        b.emit(Op::Dup2, 0); // [recv, key, recv, key]
        b.emit(Op::CallBuiltin(get, 2), 0); // [recv, key, old]
        match aop {
            AssignOp::Binary(op) => {
                self.emit_compound_binop(b, op, value)?; // [recv, key, new]
                b.emit(Op::CallBuiltin(set, 3), 0); // [new]
            }
            AssignOp::Logical(lop) => {
                // Short-circuit: the write is skipped entirely when the old
                // value already decides the result. That is the case the
                // duplicating desugaring got most visibly wrong — it evaluated
                // the target a second time to perform a write that the spec
                // says never happens.
                b.emit(Op::Dup, 0); // [recv, key, old, old]
                let test_op = match lop {
                    LogicalOp::And | LogicalOp::Or => ops::TRUTHY,
                    LogicalOp::Nullish => ops::NULLISH,
                };
                b.emit(Op::CallBuiltin(test_op, 1), 0); // [recv, key, old, cond]
                let skip = match lop {
                    LogicalOp::And => b.emit(Op::JumpIfFalse(0), 0), // falsy -> keep old
                    LogicalOp::Or => b.emit(Op::JumpIfTrue(0), 0),   // truthy -> keep old
                    LogicalOp::Nullish => b.emit(Op::JumpIfFalse(0), 0), // non-nullish -> keep old
                };
                b.emit(Op::Pop, 0); // drop old: [recv, key]
                self.compile_expr(b, value)?; // [recv, key, rhs]
                b.emit(Op::CallBuiltin(set, 3), 0); // [rhs]
                let done = b.emit(Op::Jump(0), 0);
                // Short-circuit landing: `[recv, key, old]` has to become
                // `[old]` with no write. There is no "drop the two below the
                // top", so the old value is rotated under and the reference
                // popped out from beneath it.
                let short = b.current_pos();
                b.patch_jump(skip, short);
                b.emit(Op::Rot, 0); // [key, old, recv]
                b.emit(Op::Pop, 0); // [key, old]
                b.emit(Op::Swap, 0); // [old, key]
                b.emit(Op::Pop, 0); // [old]
                let end = b.current_pos();
                b.patch_jump(done, end);
            }
        }
        Ok(())
    }

    /// `x op= value` for an identifier target: the name may be read twice with
    /// no observable difference, so this keeps the pre-existing desugaring.
    fn compile_compound_ident(
        &mut self,
        b: &mut ChunkBuilder,
        target: &Expr,
        aop: AssignOp,
        value: &Expr,
    ) -> Result<(), String> {
        let rebuilt = match aop {
            AssignOp::Binary(op) => {
                Expr::Binary(op, Box::new(target.clone()), Box::new(value.clone()))
            }
            AssignOp::Logical(lop) => {
                Expr::Logical(lop, Box::new(target.clone()), Box::new(value.clone()))
            }
        };
        self.compile_expr(
            b,
            &Expr::Assign {
                target: Box::new(target.clone()),
                op: None,
                value: Box::new(rebuilt),
            },
        )
    }

    /// The old value is already on the stack; compile `rhs` and combine the two
    /// with `op`, leaving one value in their place.
    ///
    /// This mirrors [`Self::compile_binary`], which cannot be reused because it
    /// compiles both operands itself — and for the bitwise family it pushes an
    /// operator TAG *below* them, which is why those arms slide the tag under
    /// the already-present old value rather than simply emitting it.
    fn emit_compound_binop(
        &mut self,
        b: &mut ChunkBuilder,
        op: BinOp,
        rhs: &Expr,
    ) -> Result<(), String> {
        let bitwise = match op {
            BinOp::BitAnd => Some(bop::BITAND),
            BinOp::BitOr => Some(bop::BITOR),
            BinOp::BitXor => Some(bop::BITXOR),
            BinOp::Shl => Some(bop::SHL),
            BinOp::Shr => Some(bop::SHR),
            BinOp::UShr => Some(bop::USHR),
            _ => None,
        };
        if let Some(tag) = bitwise {
            b.emit(Op::LoadInt(tag), 0); // [old, tag]
            b.emit(Op::Swap, 0); // [tag, old]
            self.compile_expr(b, rhs)?; // [tag, old, rhs]
            b.emit(Op::CallBuiltin(ops::BINOP, 3), 0);
            return Ok(());
        }
        self.compile_expr(b, rhs)?; // [old, rhs]
        match op {
            BinOp::Add => b.emit(Op::Add, 0),
            BinOp::Sub => b.emit(Op::Sub, 0),
            BinOp::Mul => b.emit(Op::Mul, 0),
            BinOp::Mod => b.emit(Op::Mod, 0),
            // `/` and `**` are builtins rather than the native ops, for the same
            // reason `compile_binary` routes them that way: fusevm's division
            // answers `Undef` on a zero divisor and its `pow` is IEEE-754.
            BinOp::Div => b.emit(Op::CallBuiltin(ops::DIV, 2), 0),
            BinOp::Pow => b.emit(Op::CallBuiltin(ops::POW, 2), 0),
            // No other operator has an `op=` spelling.
            _ => return Err(format!("unsupported compound assignment operator {op:?}")),
        };
        Ok(())
    }

    fn compile_unary(&mut self, b: &mut ChunkBuilder, op: UnOp, e: &Expr) -> Result<(), String> {
        match op {
            UnOp::Neg => {
                self.compile_expr(b, e)?;
                b.emit(Op::Negate, 0);
            }
            UnOp::Not => {
                self.compile_condition(b, e)?;
                b.emit(Op::LogNot, 0);
            }
            UnOp::Pos => {
                b.emit(Op::LoadInt(unop::POS), 0);
                self.compile_expr(b, e)?;
                b.emit(Op::CallBuiltin(ops::UNARY, 2), 0);
            }
            UnOp::BitNot => {
                b.emit(Op::LoadInt(unop::BITNOT), 0);
                self.compile_expr(b, e)?;
                b.emit(Op::CallBuiltin(ops::UNARY, 2), 0);
            }
            UnOp::TypeOf => {
                // `typeof <bare ident>` must NOT throw when the name is unbound —
                // JS returns "undefined". Route a plain identifier through a
                // non-throwing name read; any other operand evaluates normally.
                if let Expr::Ident(n) = e {
                    // A slotted local is always bound by the time it is read
                    // (that is rule 3 of the slot analysis), so there is no
                    // unbound case for `TYPEOF_NAME` to absorb.
                    if let Some(slot) = self.slot_of(n) {
                        b.emit(Op::GetSlot(slot), 0);
                        b.emit(Op::CallBuiltin(ops::TYPEOF, 1), 0);
                        return Ok(());
                    }
                    self.name_const(b, n);
                    b.emit(Op::CallBuiltin(ops::TYPEOF_NAME, 1), 0);
                } else {
                    self.compile_expr(b, e)?;
                    b.emit(Op::CallBuiltin(ops::TYPEOF, 1), 0);
                }
            }
            UnOp::Void => {
                self.compile_expr(b, e)?;
                b.emit(Op::Pop, 0);
                b.emit(Op::LoadUndef, 0);
            }
            // STRICT mode turns a refused delete into a TypeError (13.5.1.2
            // step 5.b). Strictness is static, so it rides along as a third
            // operand rather than being looked up at run time — and the error
            // is raised where the key and the receiver are both still in hand,
            // which a compiler-side check after the Bool could not manage.
            UnOp::Delete if self.strict && matches!(e, Expr::Ident(_)) => {
                // 13.5.1.1: `delete x` on a plain name is an early error in
                // strict code, whatever `x` is bound to.
                return Err(
                    "SyntaxError: Delete of an unqualified identifier in strict mode.".to_string(),
                );
            }
            UnOp::Delete => match e {
                Expr::Member {
                    object, property, ..
                } => {
                    self.compile_expr(b, object)?;
                    self.name_const(b, property);
                    self.emit_bool(b, self.strict);
                    b.emit(Op::CallBuiltin(ops::DELPROP_NAME, 3), 0);
                }
                Expr::Index { object, index, .. } => {
                    self.compile_expr(b, object)?;
                    self.compile_expr(b, index)?;
                    self.emit_bool(b, self.strict);
                    b.emit(Op::CallBuiltin(ops::DELITEM, 3), 0);
                }
                _ => {
                    b.emit(Op::LoadTrue, 0);
                }
            },
        }
        Ok(())
    }

    fn compile_binary(
        &mut self,
        b: &mut ChunkBuilder,
        op: BinOp,
        l: &Expr,
        r: &Expr,
    ) -> Result<(), String> {
        // Native fast path (JIT-traceable); the numeric hook supplies JS
        // semantics for non-number operands.
        macro_rules! native {
            ($opc:expr) => {{
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                b.emit($opc, 0);
                return Ok(());
            }};
        }
        match op {
            BinOp::Add => native!(Op::Add),
            BinOp::Sub => native!(Op::Sub),
            BinOp::Mul => native!(Op::Mul),
            BinOp::Div => {
                // NOT native `Op::Div`: fusevm returns `Undef` for a zero divisor,
                // but JS needs `x/0 === ±Infinity` / `0/0 === NaN`, so `/` is a
                // builtin (fusevm's own documented pattern for non-default `/`).
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                b.emit(Op::CallBuiltin(ops::DIV, 2), 0);
                return Ok(());
            }
            BinOp::Mod => native!(Op::Mod),
            // NOT native `Op::Pow`, for the same reason `/` is a builtin above:
            // fusevm's is IEEE-754 `pow`, where `(-1) ** Infinity` and `1 ** NaN`
            // come back 1 rather than the spec's NaN.
            BinOp::Pow => {
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                b.emit(Op::CallBuiltin(ops::POW, 2), 0);
                return Ok(());
            }
            BinOp::Lt => native!(Op::NumLt),
            BinOp::Le => native!(Op::NumLe),
            BinOp::Gt => native!(Op::NumGt),
            BinOp::Ge => native!(Op::NumGe),
            BinOp::EqEqEq => {
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
            }
            BinOp::NeEqEq => {
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
                b.emit(Op::LogNot, 0);
            }
            BinOp::EqEq => {
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                b.emit(Op::CallBuiltin(ops::LOOSE_EQ, 2), 0);
            }
            BinOp::NeEq => {
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                b.emit(Op::CallBuiltin(ops::LOOSE_EQ, 2), 0);
                b.emit(Op::LogNot, 0);
            }
            BinOp::In => {
                // `#field in obj` is the private-brand check: the left operand is a
                // private NAME, not a variable read, so it lowers to the key string
                // (private fields live as `#`-prefixed properties on the instance).
                match l {
                    Expr::Ident(n) if n.starts_with('#') => self.name_const(b, n),
                    _ => self.compile_expr(b, l)?,
                }
                self.compile_expr(b, r)?;
                b.emit(Op::CallBuiltin(ops::CONTAINS, 2), 0);
            }
            BinOp::InstanceOf => {
                self.compile_expr(b, l)?;
                self.compile_expr(b, r)?;
                b.emit(Op::CallBuiltin(ops::INSTANCEOF, 2), 0);
            }
            BinOp::BitAnd => self.emit_bitwise(b, bop::BITAND, l, r)?,
            BinOp::BitOr => self.emit_bitwise(b, bop::BITOR, l, r)?,
            BinOp::BitXor => self.emit_bitwise(b, bop::BITXOR, l, r)?,
            BinOp::Shl => self.emit_bitwise(b, bop::SHL, l, r)?,
            BinOp::Shr => self.emit_bitwise(b, bop::SHR, l, r)?,
            BinOp::UShr => self.emit_bitwise(b, bop::USHR, l, r)?,
        }
        Ok(())
    }

    fn emit_bitwise(
        &mut self,
        b: &mut ChunkBuilder,
        tag: i64,
        l: &Expr,
        r: &Expr,
    ) -> Result<(), String> {
        b.emit(Op::LoadInt(tag), 0);
        self.compile_expr(b, l)?;
        self.compile_expr(b, r)?;
        b.emit(Op::CallBuiltin(ops::BINOP, 3), 0);
        Ok(())
    }

    fn compile_update(
        &mut self,
        b: &mut ChunkBuilder,
        op: UpdateOp,
        prefix: bool,
        target: &Expr,
    ) -> Result<(), String> {
        // `NUM_STEP(tag, old)` computes `ToNumeric(old)` and `old ± 1` preserving
        // the operand's numeric type — so `x++` on a BigInt stays a BigInt
        // (`+old`/`old + 1` would throw the mix error). It pushes the coerced old
        // value and returns the new value: stack `[tag, old]` → `[oldN, new]`.
        let tag = if matches!(op, UpdateOp::Inc) { 1 } else { -1 };
        // A slot that provably holds a Number needs none of that: `ToNumeric`
        // is the identity on it and `Number ± 1` is a Number, so the whole
        // update is `GetSlot`, a native `Add`, and `SetSlot`. This is what takes
        // the last `CallBuiltin` out of a counting loop's body — and with it the
        // reason fusevm's tiers decline the loop.
        if let Expr::Ident(n) = target {
            // `c++` on a `const` is an assignment and throws like one. The
            // numeric fast path below writes the slot directly, and the general
            // path reaches the check through `compile_bind`, so this has to come
            // before both — otherwise `const c = 1; c++` silently incremented a
            // constant while `c = 2` correctly threw.
            if self.slots.consts.contains(n) {
                self.throw_const_assignment(b);
                return Ok(());
            }
            if let Some(slot) = self.numeric_slot_of(n) {
                b.emit(Op::GetSlot(slot), 0); // [old]
                if !prefix {
                    b.emit(Op::Dup, 0); // [old, old]
                }
                b.emit(Op::LoadFloat(tag as f64), 0);
                b.emit(Op::Add, 0); // [ (old,) new ]
                if prefix {
                    b.emit(Op::Dup, 0); // [new, new]
                }
                b.emit(Op::SetSlot(slot), 0); // stores, leaves the yielded value
                return Ok(());
            }
        }
        b.emit(Op::LoadInt(tag), 0);
        self.compile_expr(b, target)?; // [tag, old]
        b.emit(Op::CallBuiltin(ops::NUM_STEP, 2), 0); // [oldN, new]
        if prefix {
            // ++x: discard oldN, store new, yield new.
            b.emit(Op::Swap, 0); // [new, oldN]
            b.emit(Op::Pop, 0); // [new]
            b.emit(Op::Dup, 0); // [new, new]
            self.compile_bind(b, target, BindMode::Assign)?; // stores new -> [new]
        } else {
            // x++: store new, yield oldN.
            self.compile_bind(b, target, BindMode::Assign)?; // stores new -> [oldN]
        }
        Ok(())
    }

    fn compile_member(
        &mut self,
        b: &mut ChunkBuilder,
        object: &Expr,
        property: &str,
        optional: bool,
    ) -> Result<(), String> {
        // `super.prop` — read a data/accessor property off the parent prototype.
        if matches!(object, Expr::Super) {
            self.name_const(b, property);
            b.emit(Op::CallBuiltin(ops::SUPER_GET, 1), 0);
            return Ok(());
        }
        self.compile_expr(b, object)?;
        if optional {
            let jshort = self.emit_optional_guard(b);
            self.name_const(b, property);
            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0);
            // Inside a chain the jump belongs to the chain's end, not to this
            // link's — otherwise the rest of the chain runs on the `undefined`
            // the short-circuit just produced.
            match self.opt_chain.last_mut() {
                Some(frame) => frame.push(jshort),
                None => {
                    let end = b.current_pos();
                    b.patch_jump(jshort, end);
                }
            }
        } else {
            self.name_const(b, property);
            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0);
        }
        Ok(())
    }

    fn compile_index(
        &mut self,
        b: &mut ChunkBuilder,
        object: &Expr,
        index: &Expr,
        optional: bool,
    ) -> Result<(), String> {
        // `super[expr]` READ — the computed twin of `super.prop`, which
        // `compile_member` handles. Without it `super` compiled as a value and
        // the read went against `undefined`.
        if matches!(object, Expr::Super) {
            self.compile_expr(b, index)?;
            b.emit(Op::CallBuiltin(ops::SUPER_GET, 1), 0);
            return Ok(());
        }
        self.compile_expr(b, object)?;
        if optional {
            let jshort = self.emit_optional_guard(b);
            self.compile_off_spine(b, index)?;
            b.emit(Op::CallBuiltin(ops::GETITEM, 2), 0);
            match self.opt_chain.last_mut() {
                Some(frame) => frame.push(jshort),
                None => {
                    let end = b.current_pos();
                    b.patch_jump(jshort, end);
                }
            }
        } else {
            self.compile_off_spine(b, index)?;
            b.emit(Op::CallBuiltin(ops::GETITEM, 2), 0);
        }
        Ok(())
    }

    /// For an optional access: object on TOS. If nullish, replace with undefined
    /// and jump over the access. Returns the jump index to patch to the end.
    // ── block scopes ─────────────────────────────────────────────────────
    /// Enter a block scope: `let`/`const` declared after this point die at the
    /// matching [`Self::emit_pop_scope`].
    /// Push a literal boolean.
    fn emit_bool(&self, b: &mut ChunkBuilder, v: bool) {
        b.emit(if v { Op::LoadTrue } else { Op::LoadFalse }, 0);
    }

    fn emit_push_scope(&mut self, b: &mut ChunkBuilder) {
        b.emit(Op::CallBuiltin(ops::PUSH_SCOPE, 0), 0);
        b.emit(Op::Pop, 0);
        self.scope_depth += 1;
    }

    fn emit_pop_scope(&mut self, b: &mut ChunkBuilder) {
        b.emit(Op::CallBuiltin(ops::POP_SCOPE, 0), 0);
        b.emit(Op::Pop, 0);
        self.scope_depth -= 1;
    }

    /// Replace the innermost scope with a copy of its bindings — the per-iteration
    /// environment that makes each `for (let i …)` pass capture its own `i`.
    fn emit_copy_scope(&self, b: &mut ChunkBuilder) {
        b.emit(Op::CallBuiltin(ops::COPY_SCOPE, 0), 0);
        b.emit(Op::Pop, 0);
    }

    /// Close and drop every for-of/for-in iterator between here and `target`
    /// depth. A jump to an OUTER loop abandons the inner loops, and their
    /// iterators are parked on the VM stack, so they must be popped (running a
    /// generator's `finally` / the iterator protocol's `.return()`) or the outer
    /// `FORITER` would read the wrong stack slot.
    /// Close every iterator this chunk has parked, with a value already on top
    /// of the stack that must survive: the iterators sit UNDER it, so each one
    /// is swapped up, closed, and its result dropped.
    /// Build the chunk being emitted and hand the host its call-site table. Every
    /// chunk goes through here so a site is registered exactly once, under the
    /// `op_hash` `build()` computes.
    fn finish_chunk(&mut self, b: ChunkBuilder) -> Chunk {
        let sites = std::mem::take(&mut self.call_sites);
        let yields = std::mem::take(&mut self.yield_sites);
        let chunk = b.build();
        crate::host::register_call_sites(chunk.op_hash, sites);
        crate::host::register_yield_sites(chunk.op_hash, yields);
        chunk
    }

    /// Record the callee's source text for the call op just emitted at `at`, so
    /// a `TypeError` raised there can name the callee the way V8 does. Nothing
    /// is recorded for a shape `callee_text` declines to print.
    fn note_call_site(&mut self, at: usize, callee: &Expr) {
        if let Some(text) = callee_text(callee) {
            self.call_sites.push((at, text));
        }
    }

    fn emit_close_iters_under_value(&self, b: &mut ChunkBuilder) {
        for _ in 0..self.iter_depth {
            b.emit(Op::Swap, 0); // [.., iter, val] -> [.., val, iter]
            b.emit(Op::CallBuiltin(ops::ITER_CLOSE, 1), 0); // -> [.., val, result]
            b.emit(Op::Pop, 0); // -> [.., val]
        }
    }

    fn emit_close_iters(&self, b: &mut ChunkBuilder, target: usize) {
        for _ in target..self.iter_depth {
            b.emit(Op::CallBuiltin(ops::ITER_CLOSE, 1), 0);
            b.emit(Op::Pop, 0);
        }
    }

    /// Close every block scope between here and `target` depth, without changing
    /// the compile-time depth (the jump that follows leaves this code path).
    fn emit_unwind_scopes(&self, b: &mut ChunkBuilder, target: usize) {
        for _ in target..self.scope_depth {
            b.emit(Op::CallBuiltin(ops::POP_SCOPE, 0), 0);
            b.emit(Op::Pop, 0);
        }
    }

    /// Raise a `break`/`continue` whose target loop is outside this chunk.
    fn emit_signal_jump(&mut self, b: &mut ChunkBuilder, op: u16, label: Option<&str>, line: u32) {
        self.name_const(b, label.unwrap_or(""));
        b.emit(Op::CallBuiltin(op, 1), line);
        b.emit(Op::Pop, line);
        self.chunk_signals = true;
    }

    /// Emit the `SIG_UNWIND` dispatch that runs right after a `TRY` (or after a
    /// loop that may still hold a signal for an outer labeled loop): route a
    /// pending `break`/`continue` to the enclosing loop's exit/continue target, or
    /// halt the chunk so a `return` (or a signal for a loop further out) keeps
    /// propagating.
    fn emit_signal_dispatch(&mut self, b: &mut ChunkBuilder) {
        // `break` lands on the innermost enclosing context, `continue` on the
        // innermost one that CATCHES it — a `switch` catches `break` but not
        // `continue`, so the two targets are resolved INDEPENDENTLY. Either may be
        // absent from this chunk, in which case a signal of that kind keeps
        // travelling outward. (`cont` implies `brk`: a continue-catching loop is
        // itself breakable, so it can never sit above the innermost context.)
        let brk = self
            .loops
            .len()
            .checked_sub(1)
            .filter(|i| *i >= self.chunk_loop_base);
        let cont = self
            .loops
            .iter()
            .rposition(|c| c.catches_continue)
            .filter(|i| *i >= self.chunk_loop_base);
        let tag_of = |i: Option<usize>, loops: &[LoopCtx]| match i {
            Some(i) => loops[i]
                .label
                .clone()
                .unwrap_or_else(|| unwind::PLAIN_LOOP.to_string()),
            None => unwind::NO_LOOP.to_string(),
        };
        let brk_tag = tag_of(brk, &self.loops);
        let cont_tag = tag_of(cont, &self.loops);
        self.name_const(b, &brk_tag);
        self.name_const(b, &cont_tag);
        b.emit(Op::CallBuiltin(ops::SIG_UNWIND, 2), 0); // [code]
        let Some(idx) = brk else {
            // Nothing in this chunk can catch the signal; `SIG_UNWIND` already
            // halted the chunk, so just drop its code.
            b.emit(Op::Pop, 0);
            return;
        };
        b.emit(Op::Dup, 0);
        b.emit(Op::LoadInt(unwind::BREAK), 0);
        b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
        let jb = b.emit(Op::JumpIfTrue(0), 0);
        let jc = cont.map(|_| {
            b.emit(Op::Dup, 0);
            b.emit(Op::LoadInt(unwind::CONTINUE), 0);
            b.emit(Op::CallBuiltin(ops::STRICT_EQ, 2), 0);
            b.emit(Op::JumpIfTrue(0), 0)
        });
        b.emit(Op::Pop, 0); // no signal: drop the code and fall through
        let jafter = b.emit(Op::Jump(0), 0);
        // The landing pads leave every block scope and iterator opened between
        // here and the target, exactly as the plain compiler-resolved `break` /
        // `continue` does. Skipping this leaked a scope onto the frame, so the
        // NEXT `let`/`const` at that level bound in a dead child env and became
        // invisible to any closure created afterwards.
        let (brk_scope, brk_iter) = (self.loops[idx].break_depth, self.loops[idx].iter_depth);
        let brk_land = b.current_pos();
        b.emit(Op::Pop, 0);
        self.emit_unwind_scopes(b, brk_scope);
        self.emit_close_iters(b, brk_iter);
        let brk_jump = b.emit(Op::Jump(0), 0);
        let cont_jump = jc.map(|_| {
            let (cs, ci) = cont
                .map(|i| (self.loops[i].continue_depth, self.loops[i].iter_depth))
                .unwrap_or((self.scope_depth, self.iter_depth));
            let cont_land = b.current_pos();
            b.emit(Op::Pop, 0);
            self.emit_unwind_scopes(b, cs);
            self.emit_close_iters(b, ci);
            (cont_land, b.emit(Op::Jump(0), 0))
        });
        let after = b.current_pos();
        b.patch_jump(jb, brk_land);
        if let (Some(jc), Some((cont_land, _))) = (jc, cont_jump) {
            b.patch_jump(jc, cont_land);
        }
        b.patch_jump(jafter, after);
        self.loops[idx].breaks.push(brk_jump);
        if let (Some(cont_idx), Some((_, cj))) = (cont, cont_jump) {
            self.loops[cont_idx].continues.push(cj);
        }
    }

    /// Whether `e` is a link in an optional chain that short-circuits — i.e.
    /// walking the SPINE (a member's object, an index's object, a call's
    /// callee) reaches a `?.`. An argument or a computed index is not on the
    /// spine: `a?.b[c?.d]` is two chains, not one.
    fn spine_has_optional(e: &Expr) -> bool {
        match e {
            Expr::Member {
                object, optional, ..
            } => *optional || Self::spine_has_optional(object),
            Expr::Index {
                object, optional, ..
            } => *optional || Self::spine_has_optional(object),
            Expr::Call { func, optional, .. } => *optional || Self::spine_has_optional(func),
            _ => false,
        }
    }

    /// Lower `e` as the ROOT of an optional chain: every `?.` inside its spine
    /// parks a jump, and all of them land here, past the whole chain.
    fn compile_chain_root(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
        self.opt_chain.push(Vec::new());
        let r = self.compile_expr(b, e);
        let pending = self.opt_chain.pop().unwrap_or_default();
        r?;
        let end = b.current_pos();
        for j in pending {
            b.patch_jump(j, end);
        }
        Ok(())
    }

    /// Lower `e` with the enclosing chain SUSPENDED, so a `?.` inside it forms
    /// its own chain. Used for the parts that are not on the spine — call
    /// arguments and a computed index.
    fn compile_off_spine(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
        let saved = std::mem::take(&mut self.opt_chain);
        let r = self.compile_expr(b, e);
        self.opt_chain = saved;
        r
    }

    fn emit_optional_guard(&mut self, b: &mut ChunkBuilder) -> usize {
        b.emit(Op::Dup, 0);
        b.emit(Op::CallBuiltin(ops::NULLISH, 1), 0);
        let jnull = b.emit(Op::JumpIfFalse(0), 0); // not nullish -> continue access
                                                   // nullish: drop object, push undefined, jump to end.
        b.emit(Op::Pop, 0);
        b.emit(Op::LoadUndef, 0);
        let jend = b.emit(Op::Jump(0), 0);
        let cont = b.current_pos();
        b.patch_jump(jnull, cont);
        jend
    }

    /// `callee?.(args)` — the CALLEE itself may be nullish, in which case the whole
    /// call short-circuits to `undefined` without evaluating the arguments. A
    /// method callee (`obj.m?.()`) must still be invoked with `this === obj`, so it
    /// is dispatched through `m.call(obj, …)` / `m.apply(obj, …)`.
    fn compile_optional_call(
        &mut self,
        b: &mut ChunkBuilder,
        func: &Expr,
        args: &[Expr],
    ) -> Result<(), String> {
        let has_spread = args.iter().any(|a| matches!(a, Expr::Spread(_)));
        if let Expr::Member {
            object,
            property,
            optional: obj_optional,
        } = func
        {
            self.compile_expr(b, object)?; // [recv]
            let jobj = if *obj_optional {
                Some(self.emit_optional_guard(b))
            } else {
                None
            };
            b.emit(Op::Dup, 0); // [recv, recv]
            self.name_const(b, property); // [recv, recv, name]
            b.emit(Op::CallBuiltin(ops::GETATTR, 2), 0); // [recv, fn]
                                                         // Nullish callee: drop both the method and the receiver.
            b.emit(Op::Dup, 0);
            b.emit(Op::CallBuiltin(ops::NULLISH, 1), 0);
            let jlive = b.emit(Op::JumpIfFalse(0), 0);
            b.emit(Op::Pop, 0);
            b.emit(Op::Pop, 0);
            b.emit(Op::LoadUndef, 0);
            let jend = b.emit(Op::Jump(0), 0);
            let live = b.current_pos();
            b.patch_jump(jlive, live);
            // [recv, fn] -> fn.call(recv, …) / fn.apply(recv, argsArray)
            let via = if has_spread { "apply" } else { "call" };
            self.name_const(b, via); // [recv, fn, via]
            b.emit(Op::Rot, 0); // [fn, via, recv]
            let extra = if has_spread {
                self.compile_spread_args(b, args)?; // [fn, via, recv, argsArray]
                1
            } else {
                for a in args {
                    self.compile_expr(b, a)?;
                }
                args.len()
            };
            b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(3 + extra)?), 0);
            match self.opt_chain.last_mut() {
                Some(frame) => {
                    frame.push(jend);
                    if let Some(j) = jobj {
                        frame.push(j);
                    }
                }
                None => {
                    let end = b.current_pos();
                    b.patch_jump(jend, end);
                    if let Some(j) = jobj {
                        b.patch_jump(j, end);
                    }
                }
            }
            return Ok(());
        }
        // `recv[expr]?.(…)` — the optional-call form of a COMPUTED member. Same
        // receiver rule as `recv.name?.(…)` above; only the key differs, being
        // known at run time rather than compile time. This used to fall through
        // to the plain-callee path below and lose `this`, so `o['self']?.()`
        // threw where `o.self?.()` worked.
        if let Expr::Index {
            object,
            index,
            optional: obj_optional,
        } = func
        {
            self.compile_expr(b, object)?; // [recv]
            let jobj = if *obj_optional {
                Some(self.emit_optional_guard(b))
            } else {
                None
            };
            b.emit(Op::Dup, 0); // [recv, recv]
            self.compile_expr(b, index)?; // [recv, recv, key]
            b.emit(Op::CallBuiltin(ops::GETITEM, 2), 0); // [recv, fn]
            b.emit(Op::Dup, 0);
            b.emit(Op::CallBuiltin(ops::NULLISH, 1), 0);
            let jlive = b.emit(Op::JumpIfFalse(0), 0);
            b.emit(Op::Pop, 0);
            b.emit(Op::Pop, 0);
            b.emit(Op::LoadUndef, 0);
            let jend = b.emit(Op::Jump(0), 0);
            let live = b.current_pos();
            b.patch_jump(jlive, live);
            let via = if has_spread { "apply" } else { "call" };
            self.name_const(b, via); // [recv, fn, via]
            b.emit(Op::Rot, 0); // [fn, via, recv]
            let extra = if has_spread {
                self.compile_spread_args(b, args)?;
                1
            } else {
                for a in args {
                    self.compile_expr(b, a)?;
                }
                args.len()
            };
            b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(3 + extra)?), 0);
            match self.opt_chain.last_mut() {
                Some(frame) => {
                    frame.push(jend);
                    if let Some(j) = jobj {
                        frame.push(j);
                    }
                }
                None => {
                    let end = b.current_pos();
                    b.patch_jump(jend, end);
                    if let Some(j) = jobj {
                        b.patch_jump(j, end);
                    }
                }
            }
            return Ok(());
        }
        // Plain callee (`f?.()`): evaluate it, guard, then call with no
        // receiver — a bare expression has none to keep.
        self.compile_expr(b, func)?;
        let jend = self.emit_optional_guard(b);
        if has_spread {
            self.compile_spread_args(b, args)?;
            b.emit(Op::CallBuiltin(ops::APPLY, 2), 0);
        } else {
            for a in args {
                self.compile_expr(b, a)?;
            }
            b.emit(Op::CallBuiltin(ops::CALL_VALUE, argc(1 + args.len())?), 0);
        }
        let end = b.current_pos();
        b.patch_jump(jend, end);
        Ok(())
    }

    fn compile_call(
        &mut self,
        b: &mut ChunkBuilder,
        func: &Expr,
        args: &[Expr],
        optional: bool,
    ) -> Result<(), String> {
        if optional {
            return self.compile_optional_call(b, func, args);
        }
        let has_spread = args.iter().any(|a| matches!(a, Expr::Spread(_)));
        match func {
            // `super(...args)` — invoke the parent constructor on the current
            // `this` (SUPER_CALL runs the parent ctor + this class's field inits).
            Expr::Super => {
                // A `...spread` has to be EXPANDED here as it is at every other
                // call site: compiling it as an ordinary expression passed the
                // spread OBJECT as one argument, so `super(...[1, 2])` gave the
                // parent the array and left its second parameter undefined.
                if has_spread {
                    self.compile_spread_args(b, args)?;
                    b.emit(Op::CallBuiltin(ops::SUPER_CALL_SPREAD, 1), 0);
                    return Ok(());
                }
                for a in args {
                    self.compile_expr(b, a)?;
                }
                b.emit(Op::CallBuiltin(ops::SUPER_CALL, argc(args.len())?), 0);
                return Ok(());
            }
            // `super.method(...args)` — resolve the parent method, call it bound to
            // the current `this` via `method.call(this, ...args)`.
            Expr::Member {
                object, property, ..
            } if matches!(**object, Expr::Super) => {
                self.name_const(b, property);
                b.emit(Op::CallBuiltin(ops::SUPER_GET, 1), 0); // [method]
                                                               // With a spread the argument count is not static, so the call
                                                               // goes through `apply` with a run-time array rather than `call`
                                                               // with a fixed run. Compiling the spread as an ordinary
                                                               // argument handed the parent method the array itself.
                if has_spread {
                    self.name_const(b, "apply"); // [method, "apply"]
                    b.emit(Op::CallBuiltin(ops::THIS, 0), 0); // [method, "apply", this]
                    self.compile_spread_args(b, args)?; // [..., argsArray]
                    b.emit(Op::CallBuiltin(ops::CALL_METHOD, 4), 0);
                    return Ok(());
                }
                self.name_const(b, "call"); // [method, "call"]
                b.emit(Op::CallBuiltin(ops::THIS, 0), 0); // [method, "call", this]
                                                          // `method.call(this, ...args)`: compile args and dispatch as a
                                                          // method call named "call".
                for a in args {
                    self.compile_expr(b, a)?;
                }
                b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(3 + args.len())?), 0);
                return Ok(());
            }
            Expr::Member {
                object,
                property,
                optional,
            } => {
                self.compile_expr(b, object)?;
                // `obj?.method(...)`: if `obj` is nullish, short-circuit the whole
                // call to `undefined` (skip the method name, args, and dispatch).
                let jshort = if *optional {
                    Some(self.emit_optional_guard(b))
                } else {
                    None
                };
                self.name_const(b, property);
                if has_spread {
                    self.compile_spread_args(b, args)?; // [recv, name, argsArray]
                    b.emit(Op::CallBuiltin(ops::APPLY_METHOD, 3), 0);
                } else {
                    // Arguments are not on the chain's spine: a `?.` inside one
                    // is its own chain and must not jump past this call.
                    for a in args {
                        self.compile_off_spine(b, a)?;
                    }
                    let at = b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(2 + args.len())?), 0);
                    self.note_call_site(at, func);
                }
                if let Some(j) = jshort {
                    match self.opt_chain.last_mut() {
                        Some(frame) => frame.push(j),
                        None => {
                            let end = b.current_pos();
                            b.patch_jump(j, end);
                        }
                    }
                }
            }
            // `super[expr](args)` — the computed twin of `super.m(args)` above.
            // The dotted form was handled and this was not, so it fell through
            // to the ordinary computed-call path, which compiled `super` as a
            // value and dispatched on that.
            Expr::Index { object, index, .. } if matches!(**object, Expr::Super) => {
                self.compile_expr(b, index)?; // [name]
                b.emit(Op::CallBuiltin(ops::SUPER_GET, 1), 0); // [method]
                self.name_const(b, "call"); // [method, "call"]
                b.emit(Op::CallBuiltin(ops::THIS, 0), 0); // [method, "call", this]
                for a in args {
                    self.compile_expr(b, a)?;
                }
                b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(3 + args.len())?), 0);
                return Ok(());
            }
            Expr::Index {
                object,
                index,
                optional,
            } => {
                // recv[expr](args) — evaluate as a method via computed name.
                self.compile_expr(b, object)?; // [recv]
                                               // `recv?.[expr](...)`: short-circuit to `undefined` when nullish.
                let jshort = if *optional {
                    Some(self.emit_optional_guard(b))
                } else {
                    None
                };
                // 13.3.6 EvaluateCall: the receiver of `recv[expr](...)` is
                // `recv`, exactly as for `recv.name(...)`. This used to read the
                // function with GETITEM, DROP the receiver, and call the value
                // with no `this` — the comment called it "approximated", and it
                // silently produced wrong answers rather than errors:
                //
                //     const o = {x: 42, f() { return this.x }};
                //     o.f()      // 42
                //     o['f']()   // undefined      <- was
                //     c['m']()   // TypeError      <- on a class instance
                //
                // CALL_METHOD/APPLY_METHOD take the name off the STACK, so a
                // computed key dispatches through the same path a static one
                // does and keeps the receiver.
                self.compile_expr(b, index)?; // [recv, name]
                if has_spread {
                    self.compile_spread_args(b, args)?; // [recv, name, argsArray]
                    b.emit(Op::CallBuiltin(ops::APPLY_METHOD, 3), 0);
                } else {
                    for a in args {
                        self.compile_off_spine(b, a)?;
                    }
                    let at = b.emit(Op::CallBuiltin(ops::CALL_METHOD, argc(2 + args.len())?), 0);
                    self.note_call_site(at, func);
                }
                if let Some(j) = jshort {
                    let end = b.current_pos();
                    b.patch_jump(j, end);
                }
            }
            // A slotted callee has no name to resolve at run time: it falls
            // through to the value path below, which reads the slot and calls
            // through `CALL_VALUE`.
            Expr::Ident(n) if self.slot_of(n).is_none() => {
                self.name_const(b, n);
                if has_spread {
                    self.compile_spread_args(b, args)?; // [name, argsArray]
                                                        // Resolve name to a value, then APPLY.
                    b.emit(Op::Swap, 0); // [argsArray, name]
                    b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0); // [argsArray, fn]
                    b.emit(Op::Swap, 0); // [fn, argsArray]
                    b.emit(Op::CallBuiltin(ops::APPLY, 2), 0);
                } else {
                    for a in args {
                        self.compile_expr(b, a)?;
                    }
                    let at = b.emit(Op::CallBuiltin(ops::CALL, argc(1 + args.len())?), 0);
                    self.note_call_site(at, func);
                }
            }
            _ => {
                self.compile_expr(b, func)?;
                if has_spread {
                    self.compile_spread_args(b, args)?;
                    b.emit(Op::CallBuiltin(ops::APPLY, 2), 0);
                } else {
                    for a in args {
                        self.compile_expr(b, a)?;
                    }
                    let at = b.emit(Op::CallBuiltin(ops::CALL_VALUE, argc(1 + args.len())?), 0);
                    self.note_call_site(at, func);
                }
            }
        }
        Ok(())
    }

    /// Build a flat args array from a mix of plain args and `...spread` args.
    fn compile_spread_args(&mut self, b: &mut ChunkBuilder, args: &[Expr]) -> Result<(), String> {
        for a in args {
            match a {
                // Tag 3, not 1: a spread in a CALL argument list reports a
                // non-iterable differently from one in an ARRAY LITERAL, and
                // `BUILD_ARGS` serves both. Node names the missing protocol
                // here (`Spread syntax requires ...`) and the VALUE there.
                Expr::Spread(inner) => {
                    b.emit(Op::LoadInt(3), 0);
                    self.compile_expr(b, inner)?;
                }
                _ => {
                    b.emit(Op::LoadInt(0), 0);
                    self.compile_expr(b, a)?;
                }
            }
        }
        b.emit(Op::CallBuiltin(ops::BUILD_ARGS, argc(args.len() * 2)?), 0);
        Ok(())
    }

    fn compile_new(
        &mut self,
        b: &mut ChunkBuilder,
        callee: &Expr,
        args: &[Expr],
    ) -> Result<(), String> {
        self.compile_expr(b, callee)?;
        // A `...spread` argument has to be EXPANDED into the argument list. A
        // plain `compile_expr` of one yields the spread object itself, so
        // `new C(...[1, 2])` passed the array as a single argument.
        if args.iter().any(|a| matches!(a, Expr::Spread(_))) {
            // `compile_spread_args` emits its own `BUILD_ARGS`, leaving the flat
            // argument array on the stack above the constructor.
            self.compile_spread_args(b, args)?;
            let at = b.emit(Op::CallBuiltin(ops::NEW_SPREAD, 2), 0);
            self.note_call_site(at, callee);
            return Ok(());
        }
        for a in args {
            self.compile_expr(b, a)?;
        }
        let at = b.emit(Op::CallBuiltin(ops::NEW, argc(1 + args.len())?), 0);
        self.note_call_site(at, callee);
        Ok(())
    }
}

/// A prologue statement applying a parameter default: `if (name === undefined)
/// name = default;`.
fn default_stmt(name: &str, default: &Expr) -> Stmt {
    Stmt::from(StmtKind::If {
        test: Expr::Binary(
            BinOp::EqEqEq,
            Box::new(Expr::Ident(name.to_string())),
            Box::new(Expr::Undefined),
        ),
        cons: Box::new(Stmt::from(StmtKind::Expr(Expr::Assign {
            target: Box::new(Expr::Ident(name.to_string())),
            op: None,
            value: Box::new(default.clone()),
        }))),
        alt: None,
    })
}

/// Every name a `var` binds inside one function scope, in source order.
///
/// Descends through block-scoped constructs, because `var` is not block-scoped,
/// and stops at a nested `function` declaration, whose body is its own scope.
/// Function *expressions* and arrows are inside `Expr`, which is not walked at
/// all: a `var` can only be introduced by a statement.
fn collect_var_names(s: &Stmt, out: &mut Vec<String>) {
    match &s.kind {
        StmtKind::Decl {
            kind: DeclKind::Var,
            decls,
        } => {
            for d in decls {
                pattern_names(&d.target, out);
            }
        }
        StmtKind::Block(body) => body.iter().for_each(|s| collect_var_names(s, out)),
        StmtKind::If { cons, alt, .. } => {
            collect_var_names(cons, out);
            if let Some(a) = alt {
                collect_var_names(a, out);
            }
        }
        StmtKind::While { body, .. }
        | StmtKind::DoWhile { body, .. }
        | StmtKind::Labeled { body, .. } => collect_var_names(body, out),
        StmtKind::For { init, body, .. } => {
            if let Some(i) = init {
                collect_var_names(i, out);
            }
            collect_var_names(body, out);
        }
        StmtKind::ForOf {
            decl_kind,
            target,
            body,
            ..
        }
        | StmtKind::ForIn {
            decl_kind,
            target,
            body,
            ..
        } => {
            if *decl_kind == Some(DeclKind::Var) {
                pattern_names(target, out);
            }
            collect_var_names(body, out);
        }
        StmtKind::Switch { cases, .. } => {
            for c in cases {
                c.body.iter().for_each(|s| collect_var_names(s, out));
            }
        }
        StmtKind::Try {
            block,
            handler,
            finalizer,
        } => {
            block.iter().for_each(|s| collect_var_names(s, out));
            if let Some((_, body)) = handler {
                // The catch PARAMETER is block-scoped to the handler, so it is
                // not collected; a `var` in the handler body still hoists.
                body.iter().for_each(|s| collect_var_names(s, out));
            }
            if let Some(f) = finalizer {
                f.iter().for_each(|s| collect_var_names(s, out));
            }
        }
        _ => {}
    }
}

/// The binding names a declaration target introduces, destructuring included.
fn pattern_names(target: &Expr, out: &mut Vec<String>) {
    match target {
        Expr::Ident(n) => {
            if !out.iter().any(|x| x == n) {
                out.push(n.clone());
            }
        }
        Expr::Array(items) => items.iter().for_each(|i| pattern_names(i, out)),
        Expr::Object(props) => {
            for p in props {
                match p {
                    Prop::KeyValue { value, .. } => pattern_names(value, out),
                    Prop::Spread(e) => pattern_names(e, out),
                    Prop::Accessor { .. } => {}
                }
            }
        }
        // `[a = 1]` / `{a: b = 1}` — the binding is the target, not the default.
        Expr::Assign { target, .. } => pattern_names(target, out),
        Expr::Spread(inner) => pattern_names(inner, out),
        // A member target (`[obj.x] = …`) assigns a property, binding nothing.
        _ => {}
    }
}

/// How node renders the SOURCE of a failed object destructuring: `const {w} =
/// v` names `v`. Only the forms whose text can be reproduced exactly are
/// rendered; anything else answers `None` and the caller falls back to the
/// ordinary property-read error rather than inventing a rendering.
fn destructure_source_text(e: &Expr) -> Option<String> {
    Some(match e {
        Expr::Null => "null".into(),
        Expr::Undefined => "undefined".into(),
        Expr::Ident(n) => n.clone(),
        // A LITERAL names itself: `const [x] = 5` is `5 is not iterable`. An
        // OBJECT literal is named too, but by shape rather than by text — empty
        // renders `{}` and anything else `{(intermediate value)}`, which is
        // what V8 calls a value with no source name.
        Expr::Number(n) => crate::host::fmt_number(*n),
        Expr::True => "true".into(),
        Expr::False => "false".into(),
        Expr::Object(props) if props.is_empty() => "{}".into(),
        Expr::Object(_) => "{(intermediate value)}".into(),
        Expr::Member {
            object,
            property,
            optional: false,
        } => format!("{}.{property}", destructure_source_text(object)?),
        _ => return None,
    })
}

/// Every name a binding pattern introduces, in source order — one for a plain
/// identifier, and the leaves of an object or array pattern otherwise.
fn binding_names(target: &Expr) -> Vec<String> {
    let mut out = Vec::new();
    fn walk(e: &Expr, out: &mut Vec<String>) {
        match e {
            Expr::Ident(n) => out.push(n.clone()),
            Expr::Assign { target, .. } => walk(target, out),
            Expr::Spread(inner) => walk(inner, out),
            Expr::Array(items) => items.iter().for_each(|i| walk(i, out)),
            Expr::Object(props) => {
                for p in props {
                    match p {
                        Prop::KeyValue { value, .. } => walk(value, out),
                        Prop::Spread(inner) => walk(inner, out),
                        Prop::Accessor { .. } => {}
                    }
                }
            }
            _ => {}
        }
    }
    walk(target, &mut out);
    out
}