tsrun 0.1.23

A TypeScript interpreter designed for embedding in applications
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
//! Statement compilation
//!
//! Compiles AST statements to bytecode instructions.

use super::Compiler;
use super::bytecode::{ConstantIndex, Op, Register};
use crate::ast::{
    BlockStatement, BreakStatement, ClassConstructor, ClassDeclaration, ClassMember, ClassMethod,
    ClassProperty, ContinueStatement, DoWhileStatement, ExportDeclaration, ForInOfLeft,
    ForInStatement, ForInit, ForOfStatement, ForStatement, IfStatement, LabeledStatement,
    MethodKind, ObjectPatternProperty, ObjectPropertyKey, Pattern, ReturnStatement, Statement,
    SwitchStatement, ThrowStatement, TryStatement, VariableDeclaration, VariableKind,
    WhileStatement,
};
use crate::error::JsError;
use crate::prelude::*;
use crate::value::{CheapClone, JsString};

impl Compiler {
    /// Compile a statement
    pub fn compile_statement_impl(&mut self, stmt: &Statement) -> Result<(), JsError> {
        match stmt {
            Statement::Expression(expr_stmt) => {
                self.builder.set_span(expr_stmt.span);
                if self.track_completion {
                    // When tracking completion, compile directly to register 0
                    self.compile_expression(&expr_stmt.expression, 0)?;
                } else {
                    let dst = self.builder.alloc_register()?;
                    self.compile_expression(&expr_stmt.expression, dst)?;
                    // Discard the result
                    self.builder.free_register(dst);
                }
                Ok(())
            }

            Statement::VariableDeclaration(decl) => self.compile_variable_declaration(decl),

            Statement::Block(block) => self.compile_block(block),

            Statement::If(if_stmt) => self.compile_if(if_stmt),

            Statement::While(while_stmt) => self.compile_while(while_stmt),

            Statement::DoWhile(do_while) => self.compile_do_while(do_while),

            Statement::For(for_stmt) => self.compile_for(for_stmt),

            Statement::ForIn(for_in) => self.compile_for_in(for_in),

            Statement::ForOf(for_of) => self.compile_for_of(for_of),

            Statement::Switch(switch_stmt) => self.compile_switch(switch_stmt),

            Statement::Return(return_stmt) => self.compile_return(return_stmt),

            Statement::Break(break_stmt) => self.compile_break(break_stmt),

            Statement::Continue(continue_stmt) => self.compile_continue(continue_stmt),

            Statement::Throw(throw_stmt) => self.compile_throw(throw_stmt),

            Statement::Try(try_stmt) => self.compile_try(try_stmt),

            Statement::Labeled(labeled) => self.compile_labeled(labeled),

            Statement::FunctionDeclaration(func) => self.compile_function_declaration(func),

            Statement::ClassDeclaration(class) => self.compile_class_declaration(class),

            Statement::Empty => {
                // No-op
                Ok(())
            }

            Statement::Debugger => {
                self.builder.emit(Op::Debugger);
                Ok(())
            }

            // TypeScript declarations - no-ops at runtime (except enum)
            Statement::TypeAlias(_) | Statement::InterfaceDeclaration(_) => Ok(()),

            // Enum declarations create runtime objects
            Statement::EnumDeclaration(decl) => self.compile_enum_declaration(decl),

            // Namespace declarations
            Statement::NamespaceDeclaration(decl) => self.compile_namespace_declaration(decl),

            // Module declarations
            Statement::Import(_) => {
                // Import bindings are set up before bytecode execution by setup_import_bindings()
                // so imports compile to no-ops
                Ok(())
            }

            // Export declaration - compile the inner declaration and emit export bindings
            Statement::Export(export) => self.compile_export_declaration(export),
        }
    }

    /// Compile a variable declaration
    fn compile_variable_declaration(&mut self, decl: &VariableDeclaration) -> Result<(), JsError> {
        self.builder.set_span(decl.span);

        let mutable = decl.kind != VariableKind::Const;
        let is_var = decl.kind == VariableKind::Var;

        for declarator in decl.declarations.iter() {
            self.builder.set_span(declarator.span);

            // Get the inferred name from simple identifier patterns
            let inferred_name = match &declarator.id {
                Pattern::Identifier(id) => Some(id.name.cheap_clone()),
                _ => None,
            };

            // Compile initializer (or undefined)
            let init_reg = self.builder.alloc_register()?;
            if let Some(init) = &declarator.init {
                // Check if this is an anonymous function being assigned to an identifier
                // If so, pass the inferred name for function.name property
                self.compile_expression_with_inferred_name(init, init_reg, inferred_name)?;
            } else {
                self.builder.emit(Op::LoadUndefined { dst: init_reg });
            }

            // Bind to pattern
            self.compile_pattern_binding(&declarator.id, init_reg, mutable, is_var)?;

            self.builder.free_register(init_reg);
        }

        Ok(())
    }

    /// Compile a block statement
    fn compile_block(&mut self, block: &BlockStatement) -> Result<(), JsError> {
        self.builder.set_span(block.span);

        // Push a new scope
        self.emit_push_scope();

        if block.body.is_empty() && self.track_completion {
            // Empty block has completion value undefined
            self.builder.emit(Op::LoadUndefined { dst: 0 });
        } else {
            // Compile statements
            for stmt in block.body.iter() {
                self.compile_statement_impl(stmt)?;
            }
        }

        // Pop scope
        self.emit_pop_scope();

        Ok(())
    }

    /// Compile an if statement
    fn compile_if(&mut self, if_stmt: &IfStatement) -> Result<(), JsError> {
        self.builder.set_span(if_stmt.span);

        // Compile test
        let test_reg = self.builder.alloc_register()?;
        self.compile_expression(&if_stmt.test, test_reg)?;

        // Jump to else/end if test is falsy
        let jump_to_else = self.builder.emit_jump_if_false(test_reg);
        self.builder.free_register(test_reg);

        // Compile consequent
        self.compile_statement_impl(&if_stmt.consequent)?;

        if let Some(alternate) = &if_stmt.alternate {
            // Jump over else block
            let jump_to_end = self.builder.emit_jump();

            // Patch jump to else
            self.builder.patch_jump(jump_to_else);

            // Compile alternate
            self.compile_statement_impl(alternate)?;

            // Patch jump to end
            self.builder.patch_jump(jump_to_end);
        } else {
            // Patch jump to end (no else block)
            self.builder.patch_jump(jump_to_else);
        }

        Ok(())
    }

    /// Compile a while statement
    fn compile_while(&mut self, while_stmt: &WhileStatement) -> Result<(), JsError> {
        self.builder.set_span(while_stmt.span);

        // Loop start (for continue)
        let loop_start = self.builder.current_offset();

        // Push loop context
        self.push_loop(None);
        self.set_continue_target(loop_start);

        // Compile test
        let test_reg = self.builder.alloc_register()?;
        self.compile_expression(&while_stmt.test, test_reg)?;

        // Jump to end if test is falsy
        let jump_to_end = self.builder.emit_jump_if_false(test_reg);
        self.builder.free_register(test_reg);

        // Compile body
        self.compile_statement_impl(&while_stmt.body)?;

        // Jump back to start
        self.builder.emit_jump_to(loop_start);

        // Patch end jump
        self.builder.patch_jump(jump_to_end);

        // Pop loop context (patches break jumps)
        self.pop_loop();

        Ok(())
    }

    /// Compile a do-while statement
    fn compile_do_while(&mut self, do_while: &DoWhileStatement) -> Result<(), JsError> {
        self.builder.set_span(do_while.span);

        // Loop start
        let loop_start = self.builder.current_offset();

        // Push loop context
        self.push_loop(None);

        // Compile body first
        self.compile_statement_impl(&do_while.body)?;

        // Continue target is here (after body, before test)
        let continue_target = self.builder.current_offset();
        self.set_continue_target(continue_target);

        // Compile test
        let test_reg = self.builder.alloc_register()?;
        self.compile_expression(&do_while.test, test_reg)?;

        // Jump back to start if test is truthy
        self.builder.emit(Op::JumpIfTrue {
            cond: test_reg,
            target: loop_start as u32,
        });
        self.builder.free_register(test_reg);

        // Pop loop context
        self.pop_loop();

        Ok(())
    }

    /// Compile a for statement
    fn compile_for(&mut self, for_stmt: &ForStatement) -> Result<(), JsError> {
        self.builder.set_span(for_stmt.span);

        // Check if this is a for loop with let/const declaration (needs per-iteration binding)
        let per_iteration_vars = self.get_per_iteration_vars(&for_stmt.init);

        if per_iteration_vars.is_empty() {
            // No let/const vars: use simple compilation
            self.compile_for_simple(for_stmt)
        } else {
            // Has let/const vars: use per-iteration binding semantics
            self.compile_for_per_iteration(for_stmt, &per_iteration_vars)
        }
    }

    /// Get variable names that need per-iteration binding (let/const in for init)
    fn get_per_iteration_vars(&self, init: &Option<ForInit>) -> Vec<JsString> {
        if let Some(ForInit::Variable(decl)) = init
            && (decl.kind == VariableKind::Let || decl.kind == VariableKind::Const)
        {
            // Extract variable names from declarations
            let mut names = Vec::new();
            for declarator in decl.declarations.iter() {
                Self::collect_pattern_names(&declarator.id, &mut names);
            }
            return names;
        }
        Vec::new()
    }

    /// Collect variable names from a pattern
    fn collect_pattern_names(pattern: &Pattern, names: &mut Vec<JsString>) {
        match pattern {
            Pattern::Identifier(id) => names.push(id.name.cheap_clone()),
            Pattern::Object(obj) => {
                for prop in &obj.properties {
                    match prop {
                        ObjectPatternProperty::KeyValue { value, .. } => {
                            Self::collect_pattern_names(value, names);
                        }
                        ObjectPatternProperty::Rest(rest) => {
                            Self::collect_pattern_names(&rest.argument, names);
                        }
                    }
                }
            }
            Pattern::Array(arr) => {
                for elem in arr.elements.iter().flatten() {
                    Self::collect_pattern_names(elem, names);
                }
            }
            Pattern::Rest(rest) => {
                Self::collect_pattern_names(&rest.argument, names);
            }
            Pattern::Assignment(assign) => {
                Self::collect_pattern_names(&assign.left, names);
            }
        }
    }

    /// Compile for loop without per-iteration bindings (var or expression init)
    fn compile_for_simple(&mut self, for_stmt: &ForStatement) -> Result<(), JsError> {
        // Push scope for loop variable
        self.emit_push_scope();

        // Compile init
        if let Some(init) = &for_stmt.init {
            match init {
                ForInit::Variable(decl) => {
                    self.compile_variable_declaration(decl)?;
                }
                ForInit::Expression(expr) => {
                    let tmp = self.builder.alloc_register()?;
                    self.compile_expression(expr, tmp)?;
                    self.builder.free_register(tmp);
                }
            }
        }

        // Loop test position
        let loop_test = self.builder.current_offset();

        // Push loop context
        self.push_loop(None);

        // Compile test (if any)
        let jump_to_end = if let Some(test) = &for_stmt.test {
            let test_reg = self.builder.alloc_register()?;
            self.compile_expression(test, test_reg)?;
            let jump = self.builder.emit_jump_if_false(test_reg);
            self.builder.free_register(test_reg);
            Some(jump)
        } else {
            None
        };

        // Compile body
        self.compile_statement_impl(&for_stmt.body)?;

        // Continue target (before update)
        let continue_target = self.builder.current_offset();
        self.set_continue_target(continue_target);

        // Compile update (if any)
        if let Some(update) = &for_stmt.update {
            let tmp = self.builder.alloc_register()?;
            self.compile_expression(update, tmp)?;
            self.builder.free_register(tmp);
        }

        // Jump back to test
        self.builder.emit_jump_to(loop_test);

        // Patch end jump
        if let Some(jump) = jump_to_end {
            self.builder.patch_jump(jump);
        }

        // Pop loop context
        self.pop_loop();

        // Pop scope
        self.emit_pop_scope();

        Ok(())
    }

    /// Compile for loop with per-iteration bindings for let/const vars
    /// Each iteration gets a fresh binding, with values copied between iterations.
    ///
    /// Key insight: closures must capture the PRE-update value. To achieve this,
    /// we don't modify the per-iteration bindings during update. Instead, we
    /// compile the update to compute the new value into a register, then use
    /// that register to initialize the NEXT iteration's bindings.
    fn compile_for_per_iteration(
        &mut self,
        for_stmt: &ForStatement,
        var_names: &[JsString],
    ) -> Result<(), JsError> {
        // Allocate registers to hold values between iterations
        let mut var_regs: Vec<(JsString, Register)> = Vec::new();
        for name in var_names {
            let reg = self.builder.alloc_register()?;
            var_regs.push((name.cheap_clone(), reg));
        }

        // Push outer scope for the init
        self.emit_push_scope();

        // Compile init (first iteration's values)
        if let Some(ForInit::Variable(decl)) = &for_stmt.init {
            self.compile_variable_declaration(decl)?;
        }

        // Copy initial values to registers
        for (name, reg) in &var_regs {
            let name_idx = self.builder.add_string(name.cheap_clone())?;
            self.builder.emit(Op::GetVar {
                dst: *reg,
                name: name_idx,
            });
        }

        // Pop the init scope (we'll create per-iteration scopes in the loop)
        self.emit_pop_scope();

        // Loop start - push per-iteration scope and copy values from registers
        let loop_start = self.builder.current_offset();

        // Push per-iteration scope
        self.emit_push_scope();

        // Declare and initialize vars from registers (these are the values closures will capture)
        for (name, reg) in &var_regs {
            let name_idx = self.builder.add_string(name.cheap_clone())?;
            self.builder.emit(Op::DeclareVar {
                name: name_idx,
                init: *reg,
                mutable: true, // let vars are mutable
            });
        }

        // Push loop context
        self.push_loop(None);

        // Compile test (if any)
        let jump_to_end = if let Some(test) = &for_stmt.test {
            let test_reg = self.builder.alloc_register()?;
            self.compile_expression(test, test_reg)?;
            let jump = self.builder.emit_jump_if_false(test_reg);
            self.builder.free_register(test_reg);
            Some(jump)
        } else {
            None
        };

        // Compile body (closures capture the per-iteration scope's bindings)
        self.compile_statement_impl(&for_stmt.body)?;

        // Continue target
        let continue_target = self.builder.current_offset();
        self.set_continue_target(continue_target);

        // Compile update with special handling for loop variables:
        // Instead of modifying the scope's bindings (which closures captured),
        // we evaluate the update and store results to registers for the next iteration.
        if let Some(update) = &for_stmt.update {
            // Enable loop variable redirection: any assignment to loop vars
            // will be redirected to their corresponding registers
            self.set_loop_var_redirects(var_regs.clone());

            let tmp = self.builder.alloc_register()?;
            self.compile_expression(update, tmp)?;
            self.builder.free_register(tmp);

            // Disable redirection
            self.clear_loop_var_redirects();
        } else {
            // No update expression, but body may have modified loop variables.
            // Copy current scope values back to registers for next iteration.
            for (name, reg) in &var_regs {
                let name_idx = self.builder.add_string(name.cheap_clone())?;
                self.builder.emit(Op::GetVar {
                    dst: *reg,
                    name: name_idx,
                });
            }
        }

        // Pop per-iteration scope
        self.emit_pop_scope();

        // Jump back to loop start
        self.builder.emit_jump_to(loop_start);

        // Patch end jump (jump here when test fails)
        if let Some(jump) = jump_to_end {
            self.builder.patch_jump(jump);
        }

        // If jumping out due to test failure, need to pop scope
        self.emit_pop_scope();

        // Pop loop context
        self.pop_loop();

        // Free registers
        for (_, reg) in var_regs {
            self.builder.free_register(reg);
        }

        Ok(())
    }

    /// Compile a for-in statement
    fn compile_for_in(&mut self, for_in: &ForInStatement) -> Result<(), JsError> {
        self.builder.set_span(for_in.span);

        // Push scope
        self.emit_push_scope();

        // Compile the right side (object to iterate)
        let obj_reg = self.builder.alloc_register()?;
        self.compile_expression(&for_in.right, obj_reg)?;

        // Get keys iterator for for-in (iterates over enumerable property keys)
        let iter_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::GetKeysIterator {
            dst: iter_reg,
            obj: obj_reg,
        });

        // Loop start
        let loop_start = self.builder.current_offset();

        // Push loop context
        self.push_loop(None);
        self.set_continue_target(loop_start);

        // Get next key
        let result_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::IteratorNext {
            dst: result_reg,
            iterator: iter_reg,
        });

        // Check if done
        let jump_to_end = self.builder.emit(Op::IteratorDone {
            result: result_reg,
            target: 0,
        });
        let jump_placeholder = super::JumpPlaceholder {
            instruction_index: jump_to_end,
        };

        // Get the value
        let value_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::IteratorValue {
            dst: value_reg,
            result: result_reg,
        });

        // Bind to left side
        self.compile_for_in_of_left(&for_in.left, value_reg)?;

        // Compile body
        self.compile_statement_impl(&for_in.body)?;

        // Jump back to start
        self.builder.emit_jump_to(loop_start);

        // Patch end jump
        self.builder.patch_jump(jump_placeholder);

        // Pop loop context
        self.pop_loop();

        // Free registers
        self.builder.free_register(value_reg);
        self.builder.free_register(result_reg);
        self.builder.free_register(iter_reg);
        self.builder.free_register(obj_reg);

        // Pop scope
        self.emit_pop_scope();

        Ok(())
    }

    /// Compile a for-of statement
    fn compile_for_of(&mut self, for_of: &ForOfStatement) -> Result<(), JsError> {
        self.builder.set_span(for_of.span);

        // Push scope
        self.emit_push_scope();

        // Compile the right side (iterable)
        let obj_reg = self.builder.alloc_register()?;
        self.compile_expression(&for_of.right, obj_reg)?;

        // Get iterator
        let iter_reg = self.builder.alloc_register()?;
        if for_of.await_ {
            self.builder.emit(Op::GetAsyncIterator {
                dst: iter_reg,
                obj: obj_reg,
            });
        } else {
            self.builder.emit(Op::GetIterator {
                dst: iter_reg,
                obj: obj_reg,
            });
        }

        // Loop start
        let loop_start = self.builder.current_offset();

        // Push loop context with iterator register (for iterator close protocol)
        self.push_loop_with_iterator(None, Some(iter_reg));
        self.set_continue_target(loop_start);

        // Get next value
        let result_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::IteratorNext {
            dst: result_reg,
            iterator: iter_reg,
        });

        // For await...of, await the result (for true async iterators, next() returns a promise)
        if for_of.await_ {
            self.builder.emit(Op::Await {
                dst: result_reg,
                promise: result_reg,
            });
        }

        // Check if done
        let jump_to_end = self.builder.emit(Op::IteratorDone {
            result: result_reg,
            target: 0,
        });
        let jump_placeholder = super::JumpPlaceholder {
            instruction_index: jump_to_end,
        };

        // Get the value
        let value_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::IteratorValue {
            dst: value_reg,
            result: result_reg,
        });

        // For await...of, also await the value (for sync iterables with promise values)
        if for_of.await_ {
            self.builder.emit(Op::Await {
                dst: value_reg,
                promise: value_reg,
            });
        }

        // Bind to left side
        self.compile_for_in_of_left(&for_of.left, value_reg)?;

        // Push iterator try handler to catch exceptions and close iterator
        // The catch target will be patched after we emit the body
        let push_iter_try_idx = self.builder.emit(Op::PushIterTry {
            iterator: iter_reg,
            catch_target: 0, // Will be patched
        });

        // Compile body
        self.compile_statement_impl(&for_of.body)?;

        // Pop iterator try handler (normal completion, no exception)
        self.builder.emit(Op::PopIterTry);

        // Jump back to start
        self.builder.emit_jump_to(loop_start);

        // Exception handler: close iterator and rethrow
        // This is where PushIterTry will jump on exception
        let catch_target = self.builder.current_offset();

        // Close the iterator
        self.builder.emit(Op::IteratorClose { iterator: iter_reg });

        // Rethrow the exception
        self.builder.emit(Op::Rethrow);

        // Patch the PushIterTry catch target
        self.builder
            .patch_iter_try_target(push_iter_try_idx, catch_target as u32);

        // Patch end jump (this is where IteratorDone jumps when done)
        self.builder.patch_jump(jump_placeholder);

        // Pop loop context
        self.pop_loop();

        // Free registers
        self.builder.free_register(value_reg);
        self.builder.free_register(result_reg);
        self.builder.free_register(iter_reg);
        self.builder.free_register(obj_reg);

        // Pop scope
        self.emit_pop_scope();

        Ok(())
    }

    /// Compile the left side of a for-in/for-of
    fn compile_for_in_of_left(
        &mut self,
        left: &ForInOfLeft,
        value_reg: super::Register,
    ) -> Result<(), JsError> {
        match left {
            ForInOfLeft::Variable(decl) => {
                // Should have exactly one declarator
                if let Some(declarator) = decl.declarations.first() {
                    let mutable = decl.kind != VariableKind::Const;
                    let is_var = decl.kind == VariableKind::Var;
                    self.compile_pattern_binding(&declarator.id, value_reg, mutable, is_var)?;
                }
            }
            ForInOfLeft::Pattern(pattern) => {
                // Assignment to existing binding
                self.compile_pattern_assignment(pattern, value_reg)?;
            }
        }
        Ok(())
    }

    /// Compile a switch statement
    fn compile_switch(&mut self, switch_stmt: &SwitchStatement) -> Result<(), JsError> {
        self.builder.set_span(switch_stmt.span);

        // Compile discriminant
        let disc_reg = self.builder.alloc_register()?;
        self.compile_expression(&switch_stmt.discriminant, disc_reg)?;

        // Push loop context for break (switch uses the same break mechanism)
        self.push_loop(None);

        // Collect case targets
        let mut case_jumps: Vec<super::JumpPlaceholder> = Vec::new();
        let mut default_jump: Option<super::JumpPlaceholder> = None;

        // First pass: emit comparison and jumps
        for case in switch_stmt.cases.iter() {
            if let Some(test) = &case.test {
                // Regular case
                let test_reg = self.builder.alloc_register()?;
                self.compile_expression(test, test_reg)?;

                // Compare with discriminant (strict equality)
                let cmp_reg = self.builder.alloc_register()?;
                self.builder.emit(Op::StrictEq {
                    dst: cmp_reg,
                    left: disc_reg,
                    right: test_reg,
                });

                // Jump to case body if equal
                case_jumps.push(self.builder.emit_jump_if_true(cmp_reg));

                self.builder.free_register(cmp_reg);
                self.builder.free_register(test_reg);
            } else {
                // Default case - save for later
                default_jump = Some(self.builder.emit_jump());
            }
        }

        // Jump to end if no case matched (and no default)
        let jump_to_end = if default_jump.is_none() {
            Some(self.builder.emit_jump())
        } else {
            None
        };

        // Second pass: emit case bodies
        let mut case_jumps_iter = case_jumps.into_iter();
        for case in switch_stmt.cases.iter() {
            if case.test.is_some() {
                // Patch case jump to here
                if let Some(jump) = case_jumps_iter.next() {
                    self.builder.patch_jump(jump);
                }
            } else {
                // Patch default jump to here
                if let Some(jump) = default_jump.take() {
                    self.builder.patch_jump(jump);
                }
            }

            // Compile case statements
            for stmt in case.consequent.iter() {
                self.compile_statement_impl(stmt)?;
            }
        }

        // Patch jump to end
        if let Some(jump) = jump_to_end {
            self.builder.patch_jump(jump);
        }

        // Pop loop context (patches break jumps)
        self.pop_loop();

        self.builder.free_register(disc_reg);

        Ok(())
    }

    /// Compile a return statement
    fn compile_return(&mut self, return_stmt: &ReturnStatement) -> Result<(), JsError> {
        self.builder.set_span(return_stmt.span);

        // Emit IteratorClose for all enclosing for-of loops before returning
        // (iterate from innermost to outermost)
        for i in (0..self.loop_stack.len()).rev() {
            if let Some(iter_reg) = self.loop_stack.get(i).and_then(|ctx| ctx.iterator_reg) {
                self.builder.emit(Op::IteratorClose { iterator: iter_reg });
            }
        }

        if let Some(argument) = &return_stmt.argument {
            let reg = self.builder.alloc_register()?;

            // Mark as tail position for TCO only if the return argument is a direct call expression
            // (not a binary expression like `n * f()`, which is NOT a tail call)
            let is_direct_call = match argument.as_ref() {
                crate::ast::Expression::Call(_) => true,
                crate::ast::Expression::Parenthesized(inner, _) => {
                    matches!(inner.as_ref(), crate::ast::Expression::Call(_))
                }
                _ => false,
            };

            // Check for async TCO pattern: `return await directCall()` in async function
            let is_return_await_direct_call = self.is_async_function
                && self.try_depth == 0
                && match argument.as_ref() {
                    crate::ast::Expression::Await(await_expr) => {
                        match await_expr.argument.as_ref() {
                            crate::ast::Expression::Call(_) => true,
                            crate::ast::Expression::Parenthesized(inner, _) => {
                                matches!(inner.as_ref(), crate::ast::Expression::Call(_))
                            }
                            _ => false,
                        }
                    }
                    _ => false,
                };

            if is_direct_call && self.tco_eligible && self.try_depth == 0 {
                self.in_tail_position = true;
            }
            if is_return_await_direct_call {
                self.in_async_tail_position = true;
            }

            self.compile_expression(argument, reg)?;
            self.in_tail_position = false;
            self.in_async_tail_position = false;

            self.builder.emit(Op::Return { value: reg });
            self.builder.free_register(reg);
        } else {
            self.builder.emit(Op::ReturnUndefined);
        }

        Ok(())
    }

    /// Compile a break statement
    fn compile_break(&mut self, break_stmt: &BreakStatement) -> Result<(), JsError> {
        self.builder.set_span(break_stmt.span);

        // Per ES spec, break has "empty" completion value, which UpdateEmpty converts to undefined
        if self.track_completion {
            self.builder.emit(Op::LoadUndefined { dst: 0 });
        }

        let label = break_stmt.label.as_ref().map(|id| &id.name);
        self.add_break_jump(label)?;

        Ok(())
    }

    /// Compile a continue statement
    fn compile_continue(&mut self, continue_stmt: &ContinueStatement) -> Result<(), JsError> {
        self.builder.set_span(continue_stmt.span);

        // Per ES spec, continue has "empty" completion value, which UpdateEmpty converts to undefined
        if self.track_completion {
            self.builder.emit(Op::LoadUndefined { dst: 0 });
        }

        let label = continue_stmt.label.as_ref().map(|id| &id.name);
        self.add_continue_jump(label)?;

        Ok(())
    }

    /// Compile a throw statement
    fn compile_throw(&mut self, throw_stmt: &ThrowStatement) -> Result<(), JsError> {
        self.builder.set_span(throw_stmt.span);

        let reg = self.builder.alloc_register()?;
        self.compile_expression(&throw_stmt.argument, reg)?;
        self.builder.emit(Op::Throw { value: reg });
        self.builder.free_register(reg);

        Ok(())
    }

    /// Compile a try statement
    fn compile_try(&mut self, try_stmt: &TryStatement) -> Result<(), JsError> {
        self.builder.set_span(try_stmt.span);

        self.try_depth += 1;

        // Emit PushTry - targets will be patched
        let push_try_idx = self.builder.emit(Op::PushTry {
            catch_target: 0,
            finally_target: 0,
        });

        // Compile try block
        self.compile_block(&try_stmt.block)?;

        // Pop try handler after successful completion
        self.builder.emit(Op::PopTry);

        // Jump to finally (if exists) or end
        let jump_after_try = self.builder.emit_jump();

        // Catch handler
        let catch_start = self.builder.current_offset();
        if let Some(handler) = &try_stmt.handler {
            self.builder.set_span(handler.span);

            // Push scope for catch variable
            self.emit_push_scope();

            // Bind exception to parameter
            if let Some(param) = &handler.param {
                let exc_reg = self.builder.alloc_register()?;
                self.builder.emit(Op::GetException { dst: exc_reg });
                self.compile_pattern_binding(param, exc_reg, true, false)?;
                self.builder.free_register(exc_reg);
            }

            // Compile catch body
            if handler.body.body.is_empty() && self.track_completion {
                // Empty catch block has completion value undefined
                self.builder.emit(Op::LoadUndefined { dst: 0 });
            } else {
                for stmt in handler.body.body.iter() {
                    self.compile_statement_impl(stmt)?;
                }
            }

            // Pop scope
            self.emit_pop_scope();
        }

        // Jump to finally (if exists) or end
        let jump_after_catch = self.builder.emit_jump();

        // Finally handler
        let finally_start = self.builder.current_offset();
        if let Some(finalizer) = &try_stmt.finalizer {
            self.builder.set_span(finalizer.span);

            // Compile finally block
            for stmt in finalizer.body.iter() {
                self.compile_statement_impl(stmt)?;
            }

            // FinallyEnd completes any pending return/throw
            self.builder.emit(Op::FinallyEnd);
        }

        // End of try-catch-finally
        let end_offset = self.builder.current_offset();

        // Patch jumps: if there's a finally block, jump TO it, otherwise jump past everything
        if try_stmt.finalizer.is_some() {
            // Jump to finally block (which will naturally fall through to end)
            self.builder
                .patch_jump_to(jump_after_try, finally_start as super::JumpTarget);
            self.builder
                .patch_jump_to(jump_after_catch, finally_start as super::JumpTarget);
        } else {
            // No finally, jump to end
            self.builder
                .patch_jump_to(jump_after_try, end_offset as super::JumpTarget);
            self.builder
                .patch_jump_to(jump_after_catch, end_offset as super::JumpTarget);
        }

        // Patch PushTry targets
        self.builder.patch_try_targets(
            push_try_idx,
            if try_stmt.handler.is_some() {
                catch_start as u32
            } else {
                0
            },
            if try_stmt.finalizer.is_some() {
                finally_start as u32
            } else {
                0
            },
        );

        self.try_depth -= 1;

        Ok(())
    }

    /// Compile a labeled statement
    fn compile_labeled(&mut self, labeled: &LabeledStatement) -> Result<(), JsError> {
        self.builder.set_span(labeled.span);

        // Push loop context with label
        self.push_loop(Some(labeled.label.name.cheap_clone()));

        // Compile the body
        self.compile_statement_impl(&labeled.body)?;

        // Pop loop context
        self.pop_loop();

        Ok(())
    }

    /// Compile a function declaration
    fn compile_function_declaration(
        &mut self,
        func: &crate::ast::FunctionDeclaration,
    ) -> Result<(), JsError> {
        self.builder.set_span(func.span);

        // Get function name
        let name = func.id.as_ref().map(|id| id.name.cheap_clone());

        // Compile the function body to a nested chunk
        let chunk = self.compile_function_body(
            &func.params,
            &func.body.body,
            name.clone(),
            func.generator,
            func.async_,
            false, // not an arrow function
        )?;

        // Add the chunk to constants
        let chunk_idx = self.builder.add_chunk(chunk)?;

        // Allocate register for the function object
        let dst = self.builder.alloc_register()?;

        // Emit CreateClosure instruction
        if func.generator && func.async_ {
            self.builder
                .emit(Op::CreateAsyncGenerator { dst, chunk_idx });
        } else if func.generator {
            self.builder.emit(Op::CreateGenerator { dst, chunk_idx });
        } else if func.async_ {
            self.builder.emit(Op::CreateAsync { dst, chunk_idx });
        } else {
            self.builder.emit(Op::CreateClosure { dst, chunk_idx });
        }

        // If the function has a name, declare it as a variable
        if let Some(ref fn_name) = name {
            let name_idx = self.builder.add_string(fn_name.cheap_clone())?;
            self.builder.emit(Op::DeclareVarHoisted {
                name: name_idx,
                init: dst,
            });
        }

        self.builder.free_register(dst);

        Ok(())
    }

    /// Compile function body to a nested BytecodeChunk
    pub fn compile_function_body(
        &mut self,
        params: &[crate::ast::FunctionParam],
        body: &[Statement],
        name: Option<JsString>,
        is_generator: bool,
        is_async: bool,
        is_arrow: bool,
    ) -> Result<super::BytecodeChunk, JsError> {
        use super::FunctionInfo;

        // Create a new compiler for the function body
        let mut func_compiler = Compiler::new();

        // Disable regular TCO for generators and async functions
        // (generators yield mid-function, async functions have implicit promise wrapping)
        // But async functions can use async-specific TCO for `return await fn()` pattern
        if is_generator || is_async {
            func_compiler.tco_eligible = false;
        }
        if is_async {
            func_compiler.is_async_function = true;
        }

        // Propagate source file for stack traces
        func_compiler.source_file = self.source_file.clone();
        if let Some(ref path) = self.source_file {
            func_compiler.builder.set_source_file(path.clone());
        }

        // Copy class context so private members can be accessed inside nested functions
        func_compiler.class_context_stack = self.class_context_stack.clone();

        // Reserve registers for parameters - they are passed in registers 0, 1, 2...
        // We must reserve these before any other register allocation
        if !params.is_empty() {
            func_compiler
                .builder
                .reserve_registers(params.len() as u8)?;
        }

        // Compile parameter declarations
        // Parameters will be passed via registers and need to be bound to the environment
        let mut param_names = Vec::with_capacity(params.len());
        let mut rest_param = None;

        for (idx, param) in params.iter().enumerate() {
            let arg_reg = idx as u8;

            match &param.pattern {
                crate::ast::Pattern::Identifier(id) => {
                    // In strict mode, 'eval' and 'arguments' cannot be parameter names
                    if id.name.as_ref() == "eval" || id.name.as_ref() == "arguments" {
                        return Err(JsError::syntax_error_simple(
                            "Unexpected eval or arguments in strict mode",
                        ));
                    }
                    // In strict mode, duplicate parameter names are not allowed
                    if param_names.contains(&id.name) {
                        return Err(JsError::syntax_error_simple(format!(
                            "Duplicate parameter name '{}' not allowed in strict mode",
                            id.name
                        )));
                    }
                    param_names.push(id.name.cheap_clone());

                    // Load argument from register and declare variable
                    let name_idx = func_compiler.builder.add_string(id.name.cheap_clone())?;
                    func_compiler.builder.emit(Op::DeclareVar {
                        name: name_idx,
                        init: arg_reg,
                        mutable: true,
                    });
                }
                crate::ast::Pattern::Rest(rest) => {
                    rest_param = Some(idx);
                    if let crate::ast::Pattern::Identifier(id) = &*rest.argument {
                        // In strict mode, 'eval' and 'arguments' cannot be parameter names
                        if id.name.as_ref() == "eval" || id.name.as_ref() == "arguments" {
                            return Err(JsError::syntax_error_simple(
                                "Unexpected eval or arguments in strict mode",
                            ));
                        }
                        // In strict mode, duplicate parameter names are not allowed
                        if param_names.contains(&id.name) {
                            return Err(JsError::syntax_error_simple(format!(
                                "Duplicate parameter name '{}' not allowed in strict mode",
                                id.name
                            )));
                        }
                        param_names.push(id.name.cheap_clone());

                        // For rest params, we'll need special handling (not fully implemented)
                        let name_idx = func_compiler.builder.add_string(id.name.cheap_clone())?;
                        func_compiler.builder.emit(Op::DeclareVar {
                            name: name_idx,
                            init: arg_reg,
                            mutable: true,
                        });
                    }
                }
                crate::ast::Pattern::Object(_) | crate::ast::Pattern::Array(_) => {
                    // Handle destructuring patterns in function parameters
                    // The argument is in arg_reg, compile the pattern binding
                    param_names.push(JsString::from(format!("__param{}__", idx)));
                    func_compiler.compile_pattern_binding(&param.pattern, arg_reg, true, false)?;
                }
                crate::ast::Pattern::Assignment(assign_pat) => {
                    // Parameter with default value: param = defaultValue
                    // If argument is undefined, use default value
                    let actual_value = func_compiler.builder.alloc_register()?;

                    // Check if arg is undefined
                    let is_undefined = func_compiler.builder.alloc_register()?;
                    func_compiler
                        .builder
                        .emit(Op::LoadUndefined { dst: is_undefined });
                    func_compiler.builder.emit(Op::StrictEq {
                        dst: is_undefined,
                        left: arg_reg,
                        right: is_undefined,
                    });

                    let skip_default = func_compiler.builder.emit_jump_if_false(is_undefined);
                    func_compiler.builder.free_register(is_undefined);

                    // Use default value
                    func_compiler.compile_expression(&assign_pat.right, actual_value)?;
                    let skip_arg = func_compiler.builder.emit_jump();

                    // Use provided argument
                    func_compiler.builder.patch_jump(skip_default);
                    func_compiler.builder.emit(Op::Move {
                        dst: actual_value,
                        src: arg_reg,
                    });

                    func_compiler.builder.patch_jump(skip_arg);

                    // Bind the inner pattern
                    func_compiler.compile_pattern_binding(
                        &assign_pat.left,
                        actual_value,
                        true,
                        false,
                    )?;

                    // Extract name for param_names
                    if let crate::ast::Pattern::Identifier(id) = assign_pat.left.as_ref() {
                        param_names.push(id.name.cheap_clone());
                    } else {
                        param_names.push(JsString::from(format!("__param{}__", idx)));
                    }

                    func_compiler.builder.free_register(actual_value);
                }
            }
        }

        // Hoist var declarations in the function body
        func_compiler.emit_hoisted_declarations(body)?;

        // Compile the body statements
        for stmt in body {
            func_compiler.compile_statement_impl(stmt)?;
        }

        // Emit implicit return undefined at end
        let undefined_reg = func_compiler.builder.alloc_register()?;
        func_compiler
            .builder
            .emit(Op::LoadUndefined { dst: undefined_reg });
        func_compiler.builder.emit(Op::Return {
            value: undefined_reg,
        });

        // Count bindings for environment pre-sizing
        let binding_count = super::hoist::count_function_bindings(params, body, is_arrow);

        // Build the chunk with function info
        let mut chunk = func_compiler.builder.finish();
        chunk.function_info = Some(FunctionInfo {
            name,
            param_count: params.len(),
            is_generator,
            is_async,
            is_arrow,
            uses_arguments: false, // TODO: analyze function body
            uses_this: !is_arrow,
            param_names,
            rest_param,
            binding_count,
        });

        // Make sure we have enough registers for parameters
        if chunk.register_count < params.len() as u8 {
            chunk.register_count = params.len() as u8;
        }

        Ok(chunk)
    }

    /// Compile a class declaration
    fn compile_class_declaration(&mut self, class: &ClassDeclaration) -> Result<(), JsError> {
        self.builder.set_span(class.span);

        // Allocate register for the class constructor
        let class_reg = self.builder.alloc_register()?;

        // Compile class body to register
        // Note: compile_class_body now also declares the class variable (if named)
        // so that static blocks can reference the class by name
        self.compile_class_body(class, class_reg)?;

        self.builder.free_register(class_reg);
        Ok(())
    }

    /// Compile class body - shared by class declarations and expressions
    ///
    /// `inferred_name`: Optional inferred name for anonymous class expressions.
    /// This is used only for the `.name` property, NOT for creating a scope binding.
    pub fn compile_class_body(
        &mut self,
        class: &ClassDeclaration,
        dst: super::bytecode::Register,
    ) -> Result<(), JsError> {
        self.compile_class_body_with_name(class, dst, None)
    }

    /// Compile class body with optional inferred name (for anonymous class expressions)
    pub fn compile_class_body_with_name(
        &mut self,
        class: &ClassDeclaration,
        dst: super::bytecode::Register,
        inferred_name: Option<JsString>,
    ) -> Result<(), JsError> {
        // Get class name for constructor - prefer explicit id, fallback to inferred name
        let class_name = class
            .id
            .as_ref()
            .map(|id| id.name.cheap_clone())
            .or(inferred_name);
        // Only create inner binding if class has explicit id (not inferred name)
        let has_explicit_name = class.id.is_some();

        // Compile class decorators first - they are evaluated before the class is created
        // Evaluation order: top-to-bottom (forward iteration)
        // Application order: bottom-to-top (reverse iteration when applying)
        let mut decorator_regs: Vec<super::bytecode::Register> = Vec::new();
        for decorator in &class.decorators {
            let dec_reg = self.builder.alloc_register()?;
            self.compile_expression(&decorator.expression, dec_reg)?;
            decorator_regs.push(dec_reg);
        }

        // Generate a unique class brand for private field access
        let class_brand = self.new_class_brand();

        // Collect class members and build private member info
        let mut constructor: Option<&ClassConstructor> = None;
        let mut instance_methods: Vec<&ClassMethod> = Vec::new();
        let mut static_methods: Vec<&ClassMethod> = Vec::new();
        let mut instance_fields: Vec<&ClassProperty> = Vec::new();
        let mut static_fields: Vec<&ClassProperty> = Vec::new();
        let mut instance_auto_accessors: Vec<&ClassProperty> = Vec::new();
        let mut static_auto_accessors: Vec<&ClassProperty> = Vec::new();
        let mut static_blocks: Vec<&crate::ast::BlockStatement> = Vec::new();
        let mut instance_private_fields: Vec<&ClassProperty> = Vec::new();
        let mut static_private_fields: Vec<&ClassProperty> = Vec::new();
        let mut instance_private_methods: Vec<&ClassMethod> = Vec::new();
        let mut static_private_methods: Vec<&ClassMethod> = Vec::new();
        let mut private_members = FxHashMap::default();

        for member in &class.body.members {
            match member {
                ClassMember::Constructor(ctor) => {
                    constructor = Some(ctor);
                }
                ClassMember::Method(method) => {
                    if let ObjectPropertyKey::PrivateIdentifier(id) = &method.key {
                        // This is a private method
                        private_members.insert(
                            id.name.cheap_clone(),
                            super::PrivateMemberInfo {
                                is_method: true,
                                is_static: method.static_,
                            },
                        );
                        if method.static_ {
                            static_private_methods.push(method);
                        } else {
                            instance_private_methods.push(method);
                        }
                    } else {
                        // Regular public method
                        if method.static_ {
                            static_methods.push(method);
                        } else {
                            instance_methods.push(method);
                        }
                    }
                }
                ClassMember::Property(prop) => {
                    if let ObjectPropertyKey::PrivateIdentifier(id) = &prop.key {
                        // This is a private field
                        private_members.insert(
                            id.name.cheap_clone(),
                            super::PrivateMemberInfo {
                                is_method: false,
                                is_static: prop.static_,
                            },
                        );
                        if prop.static_ {
                            static_private_fields.push(prop);
                        } else {
                            instance_private_fields.push(prop);
                        }
                    } else if prop.accessor {
                        // Auto-accessor property (accessor keyword)
                        if prop.static_ {
                            static_auto_accessors.push(prop);
                        } else {
                            instance_auto_accessors.push(prop);
                        }
                    } else {
                        // Regular public field
                        if prop.static_ {
                            static_fields.push(prop);
                        } else {
                            instance_fields.push(prop);
                        }
                    }
                }
                ClassMember::StaticBlock(block) => {
                    static_blocks.push(block);
                }
            }
        }

        // Push class context for private member access
        self.class_context_stack.push(super::ClassContext {
            brand: class_brand,
            private_members,
        });

        // Compile constructor (or create default one)
        let has_super = class.super_class.is_some();
        let ctor_chunk = if let Some(ctor) = constructor {
            self.compile_constructor_body(
                ctor,
                &instance_fields,
                &instance_private_fields,
                &instance_private_methods,
                class_brand,
                class_name.clone(),
            )?
        } else {
            self.compile_default_constructor(
                &instance_fields,
                &instance_private_fields,
                &instance_private_methods,
                class_brand,
                class_name.clone(),
                has_super,
            )?
        };

        let ctor_chunk_idx = self.builder.add_chunk(ctor_chunk)?;

        // Create constructor register and emit CreateClosure
        let ctor_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::CreateClosure {
            dst: ctor_reg,
            chunk_idx: ctor_chunk_idx,
        });

        // Compile superclass if present
        let super_reg = self.builder.alloc_register()?;
        if let Some(super_class) = &class.super_class {
            self.compile_expression(super_class, super_reg)?;
        } else {
            self.builder.emit(Op::LoadUndefined { dst: super_reg });
        }

        // Create the class
        self.builder.emit(Op::CreateClass {
            dst,
            constructor: ctor_reg,
            super_class: super_reg,
        });

        self.builder.free_register(ctor_reg);
        self.builder.free_register(super_reg);

        // Apply constructor parameter decorators (target = the class, not the constructor)
        if let Some(ctor) = constructor {
            let ctor_name_idx = self.builder.add_string(JsString::from("constructor"))?;

            for (param_index, param) in ctor.params.iter().enumerate() {
                if param.decorators.is_empty() {
                    continue;
                }

                // Get parameter name if it's a simple identifier
                let param_name_idx = match &param.pattern {
                    crate::ast::Pattern::Identifier(id) => {
                        self.builder.add_string(id.name.cheap_clone())?
                    }
                    _ => self.builder.add_string(JsString::from(""))?,
                };

                // Evaluate and apply decorators for this parameter (bottom-to-top)
                let mut dec_regs: Vec<super::bytecode::Register> = Vec::new();
                for decorator in &param.decorators {
                    let dec_reg = self.builder.alloc_register()?;
                    self.compile_expression(&decorator.expression, dec_reg)?;
                    dec_regs.push(dec_reg);
                }

                for dec_reg in dec_regs.into_iter().rev() {
                    self.builder.emit(Op::ApplyParameterDecorator {
                        target: dst, // target is the class
                        decorator: dec_reg,
                        method_name: ctor_name_idx,
                        param_name: param_name_idx,
                        param_index: param_index as u8,
                        is_static: false,
                    });
                    self.builder.free_register(dec_reg);
                }
            }
        }

        // Define instance methods (decorators are applied in compile_class_method)
        for method in &instance_methods {
            self.compile_class_method(dst, method, false)?;
        }

        // Define static methods (decorators are applied in compile_class_method)
        for method in &static_methods {
            self.compile_class_method(dst, method, true)?;
        }

        // Process instance field decorators (store initializers on class)
        // Field decorators are called after method decorators but before class decorator
        for field in &instance_fields {
            self.compile_field_decorators(dst, field, false)?;
        }

        // Process instance private field decorators
        for field in &instance_private_fields {
            self.compile_field_decorators(dst, field, false)?;
        }

        // Process static field decorators
        for field in &static_fields {
            self.compile_field_decorators(dst, field, true)?;
        }

        // Process static private field decorators
        for field in &static_private_fields {
            self.compile_field_decorators(dst, field, true)?;
        }

        // Initialize static fields (on the class constructor itself)
        for field in &static_fields {
            self.compile_static_field_initializer(dst, field)?;
        }

        // Define instance auto-accessors (on prototype)
        for accessor in &instance_auto_accessors {
            self.compile_auto_accessor(dst, accessor, false)?;
        }

        // Define static auto-accessors (on class constructor)
        for accessor in &static_auto_accessors {
            self.compile_auto_accessor(dst, accessor, true)?;
        }

        // Before running static blocks, bind the class name so code in static blocks
        // can reference the class by name (e.g., `Config.value = 42`)
        // Only create inner binding for explicit class names, not inferred names.
        // For `var C = class {}`, the binding is handled by the var declaration.
        // For `class C {}` or `var x = class C {}`, C needs an inner immutable binding.
        // If decorators are present, the binding must be mutable so we can update it
        // after decorators are applied (since decorators can replace the class).
        let has_decorators = !decorator_regs.is_empty();
        if has_explicit_name && let Some(ref name) = class_name {
            let name_idx = self.builder.add_string(name.cheap_clone())?;
            self.builder.emit(Op::DeclareVar {
                name: name_idx,
                init: dst,
                mutable: has_decorators, // mutable if decorators might replace the class
            });
        }

        // Execute static blocks with `this` bound to the class constructor
        for block in &static_blocks {
            self.compile_static_block(dst, block)?;
        }

        // Initialize static private fields (on the class constructor itself)
        for field in &static_private_fields {
            self.compile_static_private_field_initializer(dst, field, class_brand)?;
        }

        // Define static private methods
        for method in &static_private_methods {
            self.compile_private_method(dst, method, true, class_brand)?;
        }

        // Define instance private methods (store on class for later installation on instances)
        for method in &instance_private_methods {
            self.compile_private_method(dst, method, false, class_brand)?;
        }

        // Pop class context
        self.class_context_stack.pop();

        // Apply class decorators in reverse order (bottom-to-top)
        // Decorators were evaluated top-to-bottom, now apply them bottom-to-top
        if !decorator_regs.is_empty() {
            // Get class name constant index (or MAX for no name)
            let class_name_idx = if let Some(ref name) = class_name {
                self.builder.add_string(name.cheap_clone())?
            } else {
                super::bytecode::ConstantIndex::MAX
            };

            // Create an empty array to collect initializers from addInitializer calls
            let initializers_reg = self.builder.alloc_register()?;
            self.builder.emit(Op::CreateArray {
                dst: initializers_reg,
                start: 0, // Unused when count is 0
                count: 0,
            });

            for dec_reg in decorator_regs.into_iter().rev() {
                self.builder.emit(Op::ApplyClassDecorator {
                    class: dst,
                    decorator: dec_reg,
                    class_name: class_name_idx,
                    initializers: initializers_reg,
                });
                self.builder.free_register(dec_reg);
            }

            // Run all collected initializers with `this` bound to the class
            self.builder.emit(Op::RunClassInitializers {
                class: dst,
                initializers: initializers_reg,
            });
            self.builder.free_register(initializers_reg);

            // Update the class name binding with the final decorated class
            // (decorators may have replaced the class)
            if has_explicit_name && let Some(ref name) = class_name {
                let name_idx = self.builder.add_string(name.cheap_clone())?;
                self.builder.emit(Op::SetVar {
                    name: name_idx,
                    src: dst,
                });
            }
        }

        Ok(())
    }

    /// Compile a class method and emit DefineMethod/DefineAccessor
    fn compile_class_method(
        &mut self,
        class_reg: super::bytecode::Register,
        method: &ClassMethod,
        is_static: bool,
    ) -> Result<(), JsError> {
        // Get method name and check if it's private or computed
        enum MethodKey {
            Const(ConstantIndex, JsString),
            Computed(super::bytecode::Register),
            Private(ConstantIndex, JsString),
        }

        let key = match &method.key {
            ObjectPropertyKey::Identifier(id) => {
                let name = id.name.cheap_clone();
                let name_idx = self.builder.add_string(name.cheap_clone())?;
                MethodKey::Const(name_idx, name)
            }
            ObjectPropertyKey::String(s) => {
                let name = s.value.cheap_clone();
                let name_idx = self.builder.add_string(name.cheap_clone())?;
                MethodKey::Const(name_idx, name)
            }
            ObjectPropertyKey::Number(lit) => {
                // Convert number to string for method name
                use crate::ast::LiteralValue;
                match &lit.value {
                    LiteralValue::Number(n) => {
                        let name = JsString::from(crate::value::number_to_string(*n));
                        let name_idx = self.builder.add_string(name.cheap_clone())?;
                        MethodKey::Const(name_idx, name)
                    }
                    _ => return Err(JsError::syntax_error_simple("Invalid method key")),
                }
            }
            ObjectPropertyKey::Computed(expr) => {
                // Compile computed key expression to a register
                let key_reg = self.builder.alloc_register()?;
                self.compile_expression(expr, key_reg)?;
                MethodKey::Computed(key_reg)
            }
            ObjectPropertyKey::PrivateIdentifier(id) => {
                let name = id.name.cheap_clone();
                let name_idx = self.builder.add_string(name.cheap_clone())?;
                MethodKey::Private(name_idx, name)
            }
        };

        // Get method name for function naming (use None for computed)
        let method_name = match &key {
            MethodKey::Const(_, name) | MethodKey::Private(_, name) => Some(name.cheap_clone()),
            MethodKey::Computed(_) => None,
        };

        // Compile method body
        let func = &method.value;
        let method_chunk = self.compile_function_body(
            &func.params,
            &func.body.body,
            method_name,
            func.generator,
            func.async_,
            false,
        )?;

        let chunk_idx = self.builder.add_chunk(method_chunk)?;

        // Allocate register for method function
        let method_reg = self.builder.alloc_register()?;

        // Create the method function
        if func.generator && func.async_ {
            self.builder.emit(Op::CreateAsyncGenerator {
                dst: method_reg,
                chunk_idx,
            });
        } else if func.generator {
            self.builder.emit(Op::CreateGenerator {
                dst: method_reg,
                chunk_idx,
            });
        } else if func.async_ {
            self.builder.emit(Op::CreateAsync {
                dst: method_reg,
                chunk_idx,
            });
        } else {
            self.builder.emit(Op::CreateClosure {
                dst: method_reg,
                chunk_idx,
            });
        }

        // Apply parameter decorators first (before method decorators)
        // Parameter decorators are called for side effects (like metadata registration)
        let func = &method.value;
        let method_name_idx = match &key {
            MethodKey::Const(idx, _) | MethodKey::Private(idx, _) => *idx,
            MethodKey::Computed(_) => self.builder.add_string(JsString::from(""))?,
        };

        for (param_index, param) in func.params.iter().enumerate() {
            if param.decorators.is_empty() {
                continue;
            }

            // Get parameter name if it's a simple identifier
            let param_name_idx = match &param.pattern {
                crate::ast::Pattern::Identifier(id) => {
                    self.builder.add_string(id.name.cheap_clone())?
                }
                _ => self.builder.add_string(JsString::from(""))?,
            };

            // Evaluate and apply decorators for this parameter (bottom-to-top)
            let mut dec_regs: Vec<super::bytecode::Register> = Vec::new();
            for decorator in &param.decorators {
                let dec_reg = self.builder.alloc_register()?;
                self.compile_expression(&decorator.expression, dec_reg)?;
                dec_regs.push(dec_reg);
            }

            for dec_reg in dec_regs.into_iter().rev() {
                self.builder.emit(Op::ApplyParameterDecorator {
                    target: method_reg,
                    decorator: dec_reg,
                    method_name: method_name_idx,
                    param_name: param_name_idx,
                    param_index: param_index as u8,
                    is_static,
                });
                self.builder.free_register(dec_reg);
            }
        }

        // Apply method decorators
        // Evaluation order: top-to-bottom (forward iteration)
        // Application order: bottom-to-top (reverse iteration when applying)
        if !method.decorators.is_empty() {
            // Determine kind byte: 0 = method, 1 = getter, 2 = setter
            let kind: u8 = match method.kind {
                MethodKind::Method => 0,
                MethodKind::Get => 1,
                MethodKind::Set => 2,
            };

            let is_private = matches!(&key, MethodKey::Private(_, _));

            // First, evaluate all decorator expressions (top-to-bottom)
            let mut dec_regs: Vec<super::bytecode::Register> = Vec::new();
            for decorator in &method.decorators {
                let dec_reg = self.builder.alloc_register()?;
                self.compile_expression(&decorator.expression, dec_reg)?;
                dec_regs.push(dec_reg);
            }

            // Then apply decorators (bottom-to-top)
            for dec_reg in dec_regs.into_iter().rev() {
                self.builder.emit(Op::ApplyMethodDecorator {
                    method: method_reg,
                    decorator: dec_reg,
                    name: method_name_idx,
                    kind,
                    is_static,
                    is_private,
                });

                self.builder.free_register(dec_reg);
            }
        }

        // Emit DefineMethod or DefineAccessor based on method kind
        match (&key, &method.kind) {
            (
                MethodKey::Const(name_idx, _) | MethodKey::Private(name_idx, _),
                MethodKind::Method,
            ) => {
                self.builder.emit(Op::DefineMethod {
                    class: class_reg,
                    name: *name_idx,
                    method: method_reg,
                    is_static,
                });
            }
            (MethodKey::Computed(key_reg), MethodKind::Method) => {
                self.builder.emit(Op::DefineMethodComputed {
                    class: class_reg,
                    key: *key_reg,
                    method: method_reg,
                    is_static,
                });
                self.builder.free_register(*key_reg);
            }
            (MethodKey::Const(name_idx, _) | MethodKey::Private(name_idx, _), MethodKind::Get) => {
                // Getter only - pass undefined for setter
                let undefined_reg = self.builder.alloc_register()?;
                self.builder.emit(Op::LoadUndefined { dst: undefined_reg });

                self.builder.emit(Op::DefineAccessor {
                    class: class_reg,
                    name: *name_idx,
                    getter: method_reg,
                    setter: undefined_reg,
                    is_static,
                });

                self.builder.free_register(undefined_reg);
            }
            (MethodKey::Computed(key_reg), MethodKind::Get) => {
                // Getter only - pass undefined for setter
                let undefined_reg = self.builder.alloc_register()?;
                self.builder.emit(Op::LoadUndefined { dst: undefined_reg });

                self.builder.emit(Op::DefineAccessorComputed {
                    class: class_reg,
                    key: *key_reg,
                    getter: method_reg,
                    setter: undefined_reg,
                    is_static,
                });

                self.builder.free_register(undefined_reg);
                self.builder.free_register(*key_reg);
            }
            (MethodKey::Const(name_idx, _) | MethodKey::Private(name_idx, _), MethodKind::Set) => {
                // Setter only - pass undefined for getter
                let undefined_reg = self.builder.alloc_register()?;
                self.builder.emit(Op::LoadUndefined { dst: undefined_reg });

                self.builder.emit(Op::DefineAccessor {
                    class: class_reg,
                    name: *name_idx,
                    getter: undefined_reg,
                    setter: method_reg,
                    is_static,
                });

                self.builder.free_register(undefined_reg);
            }
            (MethodKey::Computed(key_reg), MethodKind::Set) => {
                // Setter only - pass undefined for getter
                let undefined_reg = self.builder.alloc_register()?;
                self.builder.emit(Op::LoadUndefined { dst: undefined_reg });

                self.builder.emit(Op::DefineAccessorComputed {
                    class: class_reg,
                    key: *key_reg,
                    getter: undefined_reg,
                    setter: method_reg,
                    is_static,
                });

                self.builder.free_register(undefined_reg);
                self.builder.free_register(*key_reg);
            }
        }

        self.builder.free_register(method_reg);
        Ok(())
    }

    /// Compile field decorators and store initializers on class
    fn compile_field_decorators(
        &mut self,
        class_reg: super::bytecode::Register,
        field: &ClassProperty,
        is_static: bool,
    ) -> Result<(), JsError> {
        // Skip if no decorators
        if field.decorators.is_empty() {
            return Ok(());
        }

        // Get field name
        let (field_name, is_private): (JsString, bool) = match &field.key {
            ObjectPropertyKey::Identifier(id) => (id.name.cheap_clone(), false),
            ObjectPropertyKey::String(s) => (s.value.cheap_clone(), false),
            ObjectPropertyKey::PrivateIdentifier(id) => (id.name.cheap_clone(), true),
            _ => return Ok(()), // Skip computed keys for now
        };

        let name_idx = self.builder.add_string(field_name)?;

        // Process decorators
        // Evaluation order: top-to-bottom (forward iteration)
        // Application order: bottom-to-top (reverse iteration when applying)
        // Each decorator is called with (undefined, context) and may return an initializer
        // We chain the initializers: if decorator A returns init_A and B returns init_B,
        // the final initializer is value => init_B(init_A(value))
        // For simplicity, we store only the last non-undefined initializer for now

        // First, evaluate all decorator expressions (top-to-bottom)
        let mut dec_regs: Vec<super::bytecode::Register> = Vec::new();
        for decorator in &field.decorators {
            let dec_reg = self.builder.alloc_register()?;
            self.compile_expression(&decorator.expression, dec_reg)?;
            dec_regs.push(dec_reg);
        }

        let init_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::LoadUndefined { dst: init_reg });

        // Then apply decorators (bottom-to-top)
        for dec_reg in dec_regs.into_iter().rev() {
            // Call decorator and get potential initializer
            self.builder.emit(Op::ApplyFieldDecorator {
                dst: init_reg,
                decorator: dec_reg,
                name: name_idx,
                is_static,
                is_private,
                is_accessor: field.accessor,
            });

            self.builder.free_register(dec_reg);
        }

        // Store the initializer on the class (only if not undefined)
        // We'll handle this in the VM - StoreFieldInitializer only stores if not undefined
        self.builder.emit(Op::StoreFieldInitializer {
            class: class_reg,
            name: name_idx,
            initializer: init_reg,
        });

        self.builder.free_register(init_reg);
        Ok(())
    }

    /// Compile an auto-accessor property (accessor keyword)
    /// Creates getter/setter and applies decorators if any
    fn compile_auto_accessor(
        &mut self,
        class_reg: super::bytecode::Register,
        accessor: &ClassProperty,
        is_static: bool,
    ) -> Result<(), JsError> {
        // Get accessor name
        let accessor_name: JsString = match &accessor.key {
            ObjectPropertyKey::Identifier(id) => id.name.cheap_clone(),
            ObjectPropertyKey::String(s) => s.value.cheap_clone(),
            _ => return Ok(()), // Skip computed keys for now
        };

        let name_idx = self.builder.add_string(accessor_name)?;

        // Compile initial value (or undefined)
        let init_value_reg = self.builder.alloc_register()?;
        if let Some(init) = &accessor.value {
            self.compile_expression(init, init_value_reg)?;
        } else {
            self.builder.emit(Op::LoadUndefined {
                dst: init_value_reg,
            });
        }

        // Create target { get, set } object for decorators
        let target_reg = self.builder.alloc_register()?;

        // Emit DefineAutoAccessor - creates getter/setter and returns { get, set } target
        self.builder.emit(Op::DefineAutoAccessor {
            class: class_reg,
            name: name_idx,
            init_value: init_value_reg,
            target_dst: target_reg,
            is_static,
        });

        self.builder.free_register(init_value_reg);

        // If there are decorators, apply them
        if !accessor.decorators.is_empty() {
            // Evaluate all decorator expressions (top-to-bottom)
            let mut dec_regs: Vec<super::bytecode::Register> = Vec::new();
            for decorator in &accessor.decorators {
                let dec_reg = self.builder.alloc_register()?;
                self.compile_expression(&decorator.expression, dec_reg)?;
                dec_regs.push(dec_reg);
            }

            // Apply decorators (bottom-to-top)
            // Each decorator receives target and returns potentially modified { get, set }
            for dec_reg in dec_regs.into_iter().rev() {
                self.builder.emit(Op::ApplyAutoAccessorDecorator {
                    target: target_reg,
                    decorator: dec_reg,
                    name: name_idx,
                    is_static,
                });
                self.builder.free_register(dec_reg);
            }

            // Store the final decorated accessor
            self.builder.emit(Op::StoreAutoAccessor {
                class: class_reg,
                name: name_idx,
                accessor_obj: target_reg,
                is_static,
            });
        }

        self.builder.free_register(target_reg);
        Ok(())
    }

    /// Compile constructor body
    fn compile_constructor_body(
        &mut self,
        ctor: &ClassConstructor,
        instance_fields: &[&ClassProperty],
        instance_private_fields: &[&ClassProperty],
        instance_private_methods: &[&ClassMethod],
        class_brand: u32,
        name: Option<JsString>,
    ) -> Result<super::BytecodeChunk, JsError> {
        use super::FunctionInfo;

        let mut func_compiler = Compiler::new();

        // Copy the class context so private field access works inside the constructor
        func_compiler.class_context_stack = self.class_context_stack.clone();

        // Reserve registers for parameters
        if !ctor.params.is_empty() {
            func_compiler
                .builder
                .reserve_registers(ctor.params.len() as u8)?;
        }

        // Compile parameter declarations inline (same as compile_function_body)
        // Also collect parameter properties (public/private/protected) to assign to this
        let mut param_names = Vec::with_capacity(ctor.params.len());
        // Param properties: (name, value_reg, needs_free)
        // needs_free is true for registers allocated for default values
        let mut param_properties: Vec<(JsString, u8, bool)> = Vec::new();

        for (idx, param) in ctor.params.iter().enumerate() {
            let arg_reg = idx as u8;

            match &param.pattern {
                crate::ast::Pattern::Identifier(id) => {
                    param_names.push(id.name.cheap_clone());
                    let name_idx = func_compiler.builder.add_string(id.name.cheap_clone())?;
                    func_compiler.builder.emit(Op::DeclareVar {
                        name: name_idx,
                        init: arg_reg,
                        mutable: true,
                    });

                    // If this is a parameter property (has accessibility or readonly), record it
                    // arg_reg is a fixed argument register, doesn't need freeing
                    if param.accessibility.is_some() || param.readonly {
                        param_properties.push((id.name.cheap_clone(), arg_reg, false));
                    }
                }
                crate::ast::Pattern::Rest(rest) => {
                    if let crate::ast::Pattern::Identifier(id) = &*rest.argument {
                        param_names.push(id.name.cheap_clone());
                        let name_idx = func_compiler.builder.add_string(id.name.cheap_clone())?;
                        func_compiler.builder.emit(Op::DeclareVar {
                            name: name_idx,
                            init: arg_reg,
                            mutable: true,
                        });
                    }
                }
                crate::ast::Pattern::Object(_) | crate::ast::Pattern::Array(_) => {
                    param_names.push(JsString::from(format!("__param{}__", idx)));
                    func_compiler.compile_pattern_binding(&param.pattern, arg_reg, true, false)?;
                }
                crate::ast::Pattern::Assignment(assign_pat) => {
                    let actual_value = func_compiler.builder.alloc_register()?;
                    let is_undefined = func_compiler.builder.alloc_register()?;
                    func_compiler
                        .builder
                        .emit(Op::LoadUndefined { dst: is_undefined });
                    func_compiler.builder.emit(Op::StrictEq {
                        dst: is_undefined,
                        left: arg_reg,
                        right: is_undefined,
                    });

                    let skip_default = func_compiler.builder.emit_jump_if_false(is_undefined);
                    func_compiler.builder.free_register(is_undefined);

                    func_compiler.compile_expression(&assign_pat.right, actual_value)?;
                    let skip_arg = func_compiler.builder.emit_jump();

                    func_compiler.builder.patch_jump(skip_default);
                    func_compiler.builder.emit(Op::Move {
                        dst: actual_value,
                        src: arg_reg,
                    });

                    func_compiler.builder.patch_jump(skip_arg);
                    func_compiler.compile_pattern_binding(
                        &assign_pat.left,
                        actual_value,
                        true,
                        false,
                    )?;

                    if let crate::ast::Pattern::Identifier(id) = assign_pat.left.as_ref() {
                        param_names.push(id.name.cheap_clone());
                        // If this is a parameter property, record it
                        // Note: we DON'T free actual_value here if it's a param property,
                        // because it's needed later in the param_properties loop
                        if param.accessibility.is_some() || param.readonly {
                            param_properties.push((id.name.cheap_clone(), actual_value, true));
                        } else {
                            func_compiler.builder.free_register(actual_value);
                        }
                    } else {
                        param_names.push(JsString::from(format!("__param{}__", idx)));
                        func_compiler.builder.free_register(actual_value);
                    }
                }
            }
        }

        // Emit parameter property assignments: this.x = x
        // These happen before instance field initializers
        for (prop_name, value_reg, needs_free) in &param_properties {
            let this_reg = func_compiler.builder.alloc_register()?;
            func_compiler.builder.emit(Op::LoadThis { dst: this_reg });
            let prop_idx = func_compiler.builder.add_string(prop_name.cheap_clone())?;
            func_compiler.builder.emit(Op::SetPropertyConst {
                obj: this_reg,
                key: prop_idx,
                value: *value_reg,
            });
            func_compiler.builder.free_register(this_reg);
            // Free registers allocated for default values after they've been used
            if *needs_free {
                func_compiler.builder.free_register(*value_reg);
            }
        }

        // Compile instance field initializers at the start of constructor
        // These run before the user's constructor body (after super() call if extending)
        for field in instance_fields {
            func_compiler.compile_instance_field_initializer(field)?;
        }

        // Initialize instance private fields
        for field in instance_private_fields {
            func_compiler.compile_instance_private_field_initializer(field, class_brand)?;
        }

        // Install instance private methods on 'this'
        for method in instance_private_methods {
            func_compiler.compile_instance_private_method_initializer(method, class_brand)?;
        }

        // Hoist var declarations in constructor body
        func_compiler.emit_hoisted_declarations(&ctor.body.body)?;

        // Compile constructor body
        for stmt in ctor.body.body.iter() {
            func_compiler.compile_statement_impl(stmt)?;
        }

        // Return this implicitly (constructor returns `this`)
        let this_reg = func_compiler.builder.alloc_register()?;
        func_compiler.builder.emit(Op::LoadThis { dst: this_reg });
        func_compiler.builder.emit(Op::Return { value: this_reg });

        // Count bindings for environment pre-sizing
        let binding_count =
            super::hoist::count_function_bindings(&ctor.params, &ctor.body.body, false);

        let mut chunk = func_compiler.builder.finish();
        chunk.function_info = Some(FunctionInfo {
            name,
            param_count: ctor.params.len(),
            param_names,
            rest_param: None,
            is_generator: false,
            is_async: false,
            is_arrow: false,
            uses_arguments: false,
            uses_this: true, // constructors use this
            binding_count,
        });

        Ok(chunk)
    }

    /// Compile default constructor (for classes without explicit constructor)
    /// For derived classes, this generates: constructor(...args) { super(...args); }
    fn compile_default_constructor(
        &mut self,
        instance_fields: &[&ClassProperty],
        instance_private_fields: &[&ClassProperty],
        instance_private_methods: &[&ClassMethod],
        class_brand: u32,
        name: Option<JsString>,
        has_super: bool,
    ) -> Result<super::BytecodeChunk, JsError> {
        use super::FunctionInfo;

        let mut func_compiler = Compiler::new();

        // Copy the class context so private field access works inside the constructor
        func_compiler.class_context_stack = self.class_context_stack.clone();

        // For derived classes, call super(...args) first to forward all arguments
        if has_super {
            // Load arguments as an array and call super with spread
            let args_reg = func_compiler.builder.alloc_register()?;
            func_compiler
                .builder
                .emit(Op::LoadArguments { dst: args_reg });

            let result_reg = func_compiler.builder.alloc_register()?;
            func_compiler.builder.emit(Op::SuperCallSpread {
                dst: result_reg,
                args_array: args_reg,
            });

            func_compiler.builder.free_register(result_reg);
            func_compiler.builder.free_register(args_reg);
        }

        // Compile instance field initializers (these run AFTER super() call)
        for field in instance_fields {
            func_compiler.compile_instance_field_initializer(field)?;
        }

        // Initialize instance private fields
        for field in instance_private_fields {
            func_compiler.compile_instance_private_field_initializer(field, class_brand)?;
        }

        // Install instance private methods on 'this'
        for method in instance_private_methods {
            func_compiler.compile_instance_private_method_initializer(method, class_brand)?;
        }

        // Return this
        let this_reg = func_compiler.builder.alloc_register()?;
        func_compiler.builder.emit(Op::LoadThis { dst: this_reg });
        func_compiler.builder.emit(Op::Return { value: this_reg });

        let mut chunk = func_compiler.builder.finish();
        chunk.function_info = Some(FunctionInfo {
            name,
            param_count: 0,
            param_names: vec![],
            rest_param: Some(0), // Rest parameter at index 0 to collect all args
            is_generator: false,
            is_async: false,
            is_arrow: false,
            uses_arguments: has_super, // Uses arguments if we have a super call
            uses_this: true,           // constructors use this
            binding_count: 3,          // this + slack
        });

        Ok(chunk)
    }

    /// Compile instance field initializer (this.field = value)
    fn compile_instance_field_initializer(&mut self, field: &ClassProperty) -> Result<(), JsError> {
        // Get field name
        let field_name: JsString = match &field.key {
            ObjectPropertyKey::Identifier(id) => id.name.cheap_clone(),
            ObjectPropertyKey::String(s) => s.value.cheap_clone(),
            _ => return Ok(()), // Skip computed/private for now
        };

        let name_idx = self.builder.add_string(field_name)?;

        // Get this
        let this_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::LoadThis { dst: this_reg });

        // Compile field initializer or use undefined
        let value_reg = self.builder.alloc_register()?;
        if let Some(init) = &field.value {
            self.compile_expression(init, value_reg)?;
        } else {
            self.builder.emit(Op::LoadUndefined { dst: value_reg });
        }

        // Check if there's a field initializer from decorators
        if !field.decorators.is_empty() {
            // Get new.target (the constructor)
            let class_reg = self.builder.alloc_register()?;
            self.builder.emit(Op::LoadNewTarget { dst: class_reg });

            // Get the stored initializer
            let init_reg = self.builder.alloc_register()?;
            self.builder.emit(Op::GetFieldInitializer {
                dst: init_reg,
                class: class_reg,
                name: name_idx,
            });

            // Apply the initializer to the value (if it exists)
            self.builder.emit(Op::ApplyFieldInitializer {
                value: value_reg,
                initializer: init_reg,
            });

            self.builder.free_register(init_reg);
            self.builder.free_register(class_reg);
        }

        // Set property on this
        self.builder.emit(Op::SetPropertyConst {
            obj: this_reg,
            key: name_idx,
            value: value_reg,
        });

        self.builder.free_register(value_reg);
        self.builder.free_register(this_reg);
        Ok(())
    }

    /// Compile a static field initializer (sets property on class constructor)
    fn compile_static_field_initializer(
        &mut self,
        class_reg: super::bytecode::Register,
        field: &ClassProperty,
    ) -> Result<(), JsError> {
        // Get field name
        let field_name: JsString = match &field.key {
            ObjectPropertyKey::Identifier(id) => id.name.cheap_clone(),
            ObjectPropertyKey::String(s) => s.value.cheap_clone(),
            _ => return Ok(()), // Skip computed/private for now
        };

        let name_idx = self.builder.add_string(field_name)?;

        // Compile field initializer or use undefined
        let value_reg = self.builder.alloc_register()?;
        if let Some(init) = &field.value {
            self.compile_expression(init, value_reg)?;
        } else {
            self.builder.emit(Op::LoadUndefined { dst: value_reg });
        }

        // Apply field initializer from decorator if present
        if !field.decorators.is_empty() {
            let init_reg = self.builder.alloc_register()?;
            self.builder.emit(Op::GetFieldInitializer {
                dst: init_reg,
                class: class_reg,
                name: name_idx,
            });

            self.builder.emit(Op::ApplyFieldInitializer {
                value: value_reg,
                initializer: init_reg,
            });

            self.builder.free_register(init_reg);
        }

        // Set property on class constructor
        self.builder.emit(Op::SetPropertyConst {
            obj: class_reg,
            key: name_idx,
            value: value_reg,
        });

        self.builder.free_register(value_reg);
        Ok(())
    }

    /// Compile an instance private field initializer (this.#field = value)
    fn compile_instance_private_field_initializer(
        &mut self,
        field: &ClassProperty,
        class_brand: u32,
    ) -> Result<(), JsError> {
        // Get field name
        let field_name: JsString = match &field.key {
            ObjectPropertyKey::PrivateIdentifier(id) => id.name.cheap_clone(),
            _ => return Ok(()), // Should only be called for private fields
        };

        let name_idx = self.builder.add_string(field_name)?;

        // Get this
        let this_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::LoadThis { dst: this_reg });

        // Compile field initializer or use undefined
        let value_reg = self.builder.alloc_register()?;
        if let Some(init) = &field.value {
            self.compile_expression(init, value_reg)?;
        } else {
            self.builder.emit(Op::LoadUndefined { dst: value_reg });
        }

        // Check if there's a field initializer from decorators
        if !field.decorators.is_empty() {
            // Get new.target (the constructor)
            let class_reg = self.builder.alloc_register()?;
            self.builder.emit(Op::LoadNewTarget { dst: class_reg });

            // Get the stored initializer
            let init_reg = self.builder.alloc_register()?;
            self.builder.emit(Op::GetFieldInitializer {
                dst: init_reg,
                class: class_reg,
                name: name_idx,
            });

            // Apply the initializer to the value (if it exists)
            self.builder.emit(Op::ApplyFieldInitializer {
                value: value_reg,
                initializer: init_reg,
            });

            self.builder.free_register(init_reg);
            self.builder.free_register(class_reg);
        }

        // Define private field on this
        self.builder.emit(Op::DefinePrivateField {
            obj: this_reg,
            class_brand,
            field_name: name_idx,
            value: value_reg,
        });

        self.builder.free_register(value_reg);
        self.builder.free_register(this_reg);
        Ok(())
    }

    /// Install an instance private method on 'this' during construction
    fn compile_instance_private_method_initializer(
        &mut self,
        method: &ClassMethod,
        class_brand: u32,
    ) -> Result<(), JsError> {
        // Get method name
        let method_name: JsString = match &method.key {
            ObjectPropertyKey::PrivateIdentifier(id) => id.name.cheap_clone(),
            _ => return Ok(()), // Should only be called for private methods
        };

        let name_idx = self.builder.add_string(method_name)?;

        // Emit instruction to install the stored private method on this
        // The method was already compiled and stored on the class during class definition
        self.builder.emit(Op::InstallPrivateMethod {
            class_brand,
            method_name: name_idx,
        });

        Ok(())
    }

    /// Compile a static private field initializer
    fn compile_static_private_field_initializer(
        &mut self,
        class_reg: super::bytecode::Register,
        field: &ClassProperty,
        class_brand: u32,
    ) -> Result<(), JsError> {
        // Get field name
        let field_name: JsString = match &field.key {
            ObjectPropertyKey::PrivateIdentifier(id) => id.name.cheap_clone(),
            _ => return Ok(()), // Should only be called for private fields
        };

        let name_idx = self.builder.add_string(field_name)?;

        // Compile field initializer or use undefined
        let value_reg = self.builder.alloc_register()?;
        if let Some(init) = &field.value {
            self.compile_expression(init, value_reg)?;
        } else {
            self.builder.emit(Op::LoadUndefined { dst: value_reg });
        }

        // Define private field on class constructor
        self.builder.emit(Op::DefinePrivateField {
            obj: class_reg,
            class_brand,
            field_name: name_idx,
            value: value_reg,
        });

        self.builder.free_register(value_reg);
        Ok(())
    }

    /// Compile a private method
    fn compile_private_method(
        &mut self,
        class_reg: super::bytecode::Register,
        method: &ClassMethod,
        is_static: bool,
        class_brand: u32,
    ) -> Result<(), JsError> {
        // Get method name
        let method_name: JsString = match &method.key {
            ObjectPropertyKey::PrivateIdentifier(id) => id.name.cheap_clone(),
            _ => return Ok(()), // Should only be called for private methods
        };

        let name_idx = self.builder.add_string(method_name.cheap_clone())?;

        // Compile method body
        let func = &method.value;
        let method_chunk = self.compile_function_body(
            &func.params,
            &func.body.body,
            Some(method_name),
            func.generator,
            func.async_,
            false,
        )?;

        let chunk_idx = self.builder.add_chunk(method_chunk)?;

        // Create method function
        let method_reg = self.builder.alloc_register()?;
        if func.generator && func.async_ {
            self.builder.emit(Op::CreateAsyncGenerator {
                dst: method_reg,
                chunk_idx,
            });
        } else if func.generator {
            self.builder.emit(Op::CreateGenerator {
                dst: method_reg,
                chunk_idx,
            });
        } else if func.async_ {
            self.builder.emit(Op::CreateAsync {
                dst: method_reg,
                chunk_idx,
            });
        } else {
            self.builder.emit(Op::CreateClosure {
                dst: method_reg,
                chunk_idx,
            });
        }

        // Apply method decorators (if any)
        // Evaluation order: top-to-bottom (forward iteration)
        // Application order: bottom-to-top (reverse iteration when applying)
        if !method.decorators.is_empty() {
            // Determine kind byte: 0 = method, 1 = getter, 2 = setter
            let kind: u8 = match method.kind {
                MethodKind::Method => 0,
                MethodKind::Get => 1,
                MethodKind::Set => 2,
            };

            // First, evaluate all decorator expressions (top-to-bottom)
            let mut dec_regs: Vec<super::bytecode::Register> = Vec::new();
            for decorator in &method.decorators {
                let dec_reg = self.builder.alloc_register()?;
                self.compile_expression(&decorator.expression, dec_reg)?;
                dec_regs.push(dec_reg);
            }

            // Then apply decorators (bottom-to-top)
            for dec_reg in dec_regs.into_iter().rev() {
                self.builder.emit(Op::ApplyMethodDecorator {
                    method: method_reg,
                    decorator: dec_reg,
                    name: name_idx,
                    kind,
                    is_static,
                    is_private: true,
                });

                self.builder.free_register(dec_reg);
            }
        }

        if is_static {
            // Define on class constructor directly
            self.builder.emit(Op::DefinePrivateField {
                obj: class_reg,
                class_brand,
                field_name: name_idx,
                value: method_reg,
            });
        } else {
            // Store for later installation on instances
            self.builder.emit(Op::DefinePrivateMethod {
                class: class_reg,
                class_brand,
                method_name: name_idx,
                method: method_reg,
                is_static,
            });
        }

        self.builder.free_register(method_reg);
        Ok(())
    }

    /// Compile a static block - compiles the block body as a function and calls it with `this` = class
    fn compile_static_block(
        &mut self,
        class_reg: super::bytecode::Register,
        block: &crate::ast::BlockStatement,
    ) -> Result<(), JsError> {
        // Compile the static block body as an anonymous function
        // The function will be called immediately with `this` bound to the class constructor
        let empty_params: [crate::ast::FunctionParam; 0] = [];
        let block_chunk =
            self.compile_function_body(&empty_params, &block.body, None, false, false, false)?;
        let chunk_idx = self.builder.add_chunk(block_chunk)?;

        // Create a closure for the static block
        let block_fn_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::CreateClosure {
            dst: block_fn_reg,
            chunk_idx,
        });

        // Call the static block with `this` = class constructor
        // No arguments needed, so we use a dummy register for args_start
        let result_reg = self.builder.alloc_register()?;
        self.builder.emit(Op::Call {
            dst: result_reg,
            callee: block_fn_reg,
            this: class_reg,
            args_start: 0, // Register is u8
            argc: 0,
        });

        self.builder.free_register(result_reg);
        self.builder.free_register(block_fn_reg);
        Ok(())
    }

    /// Compile an enum declaration
    /// TypeScript enums compile to an object with forward and reverse mappings
    fn compile_enum_declaration(
        &mut self,
        decl: &crate::ast::EnumDeclaration,
    ) -> Result<(), JsError> {
        self.builder.set_span(decl.span);

        // Create the enum object
        let enum_obj = self.builder.alloc_register()?;
        self.builder.emit(Op::CreateObject { dst: enum_obj });

        // Declare the enum variable FIRST so member initializers can reference prior members
        // via EnumName.MemberName or just MemberName (for const enums)
        let enum_name_idx = self.builder.add_string(decl.id.name.cheap_clone())?;
        self.builder.emit(Op::DeclareVar {
            name: enum_name_idx,
            init: enum_obj,
            mutable: true, // Enums are mutable like objects
        });

        // Track the current numeric value for auto-increment
        let mut current_value: i64 = 0;
        let value_reg = self.builder.alloc_register()?;
        let key_reg = self.builder.alloc_register()?;

        // Track prior member names for rewriting identifier references
        let mut prior_members: Vec<JsString> = Vec::new();

        for member in &decl.members {
            let member_name = member.id.name.cheap_clone();
            let name_idx = self.builder.add_string(member_name.cheap_clone())?;

            if let Some(ref init) = member.initializer {
                // Compile the initializer expression, rewriting references to prior enum members
                self.compile_enum_init_expression(init, value_reg, enum_obj, &prior_members)?;

                // Try to compute the numeric value for auto-increment
                // This is a simplified version - in reality, we'd need const evaluation
                if let crate::ast::Expression::Literal(lit) = init
                    && let crate::ast::LiteralValue::Number(n) = &lit.value
                {
                    current_value = *n as i64 + 1;
                }
            } else {
                // Use auto-increment value
                self.builder.emit(Op::LoadInt {
                    dst: value_reg,
                    value: current_value as i32,
                });
                current_value += 1;
            }

            // Add this member to prior members for subsequent initializers
            prior_members.push(member_name.cheap_clone());

            // Set forward mapping: EnumName.MemberName = value
            self.builder.emit(Op::SetPropertyConst {
                obj: enum_obj,
                key: name_idx,
                value: value_reg,
            });

            // Set reverse mapping for numeric values: EnumName[value] = MemberName
            // Only for numeric values (not string enums)
            // We need to check if value is numeric at runtime for mixed enums
            let is_numeric = match &member.initializer {
                None => true,
                Some(init) => {
                    // Check for numeric literal
                    matches!(
                        init,
                        crate::ast::Expression::Literal(lit) if matches!(lit.as_ref(), crate::ast::Literal { value: crate::ast::LiteralValue::Number(_), .. })
                    ) ||
                    // Check for unary minus of numeric literal (e.g., -10)
                    matches!(
                        init,
                        crate::ast::Expression::Unary(unary)
                            if unary.operator == crate::ast::UnaryOp::Minus
                            && matches!(
                                unary.argument.as_ref(),
                                crate::ast::Expression::Literal(lit) if matches!(lit.as_ref(), crate::ast::Literal { value: crate::ast::LiteralValue::Number(_), .. })
                            )
                    )
                }
            };
            if is_numeric {
                // Load the member name as a string value
                self.builder.emit_load_string(key_reg, member_name)?;

                // Set reverse mapping: EnumName[value] = "MemberName"
                self.builder.emit(Op::SetProperty {
                    obj: enum_obj,
                    key: value_reg,
                    value: key_reg,
                });
            }
        }

        self.builder.free_register(key_reg);
        self.builder.free_register(value_reg);
        self.builder.free_register(enum_obj);
        Ok(())
    }

    /// Compile a namespace declaration
    fn compile_namespace_declaration(
        &mut self,
        decl: &crate::ast::NamespaceDeclaration,
    ) -> Result<(), JsError> {
        self.builder.set_span(decl.span);

        let name_idx = self.builder.add_string(decl.id.name.cheap_clone())?;
        let ns_obj = self.builder.alloc_register()?;

        // Check if namespace already exists (for merging)
        // Try to get existing namespace, use it if found, otherwise create new
        let existing_reg = self.builder.alloc_register()?;

        // Try to get the existing namespace variable (returns undefined if not found)
        self.builder.emit(Op::TryGetVar {
            dst: existing_reg,
            name: name_idx,
        });

        // Check if existing is undefined - use JumpIfNullish since undefined is nullish
        // If undefined/null, jump to create new object, else use existing
        let jump_to_create = self.builder.emit_jump_if_nullish(existing_reg);

        // Use existing namespace
        self.builder.emit(Op::Move {
            dst: ns_obj,
            src: existing_reg,
        });
        let jump_to_end = self.builder.emit_jump();

        // Create new namespace object
        self.builder.patch_jump(jump_to_create);
        self.builder.emit(Op::CreateObject { dst: ns_obj });
        self.builder.emit(Op::DeclareVar {
            name: name_idx,
            init: ns_obj,
            mutable: true,
        });

        self.builder.patch_jump(jump_to_end);

        // Free temporary registers
        self.builder.free_register(existing_reg);

        // Push a new scope for the namespace body
        self.emit_push_scope();

        // Compile the namespace body statements
        for stmt in decl.body.iter() {
            self.compile_statement_impl(stmt)?;

            // If the statement exports something, add it to the namespace object
            // For now, we handle exported declarations by adding them to the namespace
            if let Statement::Export(export) = stmt
                && let Some(ref decl) = export.declaration
            {
                self.add_export_to_namespace(ns_obj, decl)?;
            }
        }

        // Pop the namespace scope
        self.emit_pop_scope();

        self.builder.free_register(ns_obj);
        Ok(())
    }

    /// Add an exported declaration to a namespace object
    fn add_export_to_namespace(
        &mut self,
        ns_obj: super::Register,
        decl: &Statement,
    ) -> Result<(), JsError> {
        match decl {
            Statement::VariableDeclaration(var_decl) => {
                for declarator in var_decl.declarations.iter() {
                    if let crate::ast::Pattern::Identifier(id) = &declarator.id {
                        let value_reg = self.builder.alloc_register()?;
                        let name_idx = self.builder.add_string(id.name.cheap_clone())?;
                        self.builder.emit(Op::GetVar {
                            dst: value_reg,
                            name: name_idx,
                        });
                        self.builder.emit(Op::SetPropertyConst {
                            obj: ns_obj,
                            key: name_idx,
                            value: value_reg,
                        });
                        self.builder.free_register(value_reg);
                    }
                }
            }
            Statement::FunctionDeclaration(func_decl) => {
                if let Some(ref id) = func_decl.id {
                    let value_reg = self.builder.alloc_register()?;
                    let name_idx = self.builder.add_string(id.name.cheap_clone())?;
                    self.builder.emit(Op::GetVar {
                        dst: value_reg,
                        name: name_idx,
                    });
                    self.builder.emit(Op::SetPropertyConst {
                        obj: ns_obj,
                        key: name_idx,
                        value: value_reg,
                    });
                    self.builder.free_register(value_reg);
                }
            }
            Statement::ClassDeclaration(class_decl) => {
                if let Some(ref id) = class_decl.id {
                    let value_reg = self.builder.alloc_register()?;
                    let name_idx = self.builder.add_string(id.name.cheap_clone())?;
                    self.builder.emit(Op::GetVar {
                        dst: value_reg,
                        name: name_idx,
                    });
                    self.builder.emit(Op::SetPropertyConst {
                        obj: ns_obj,
                        key: name_idx,
                        value: value_reg,
                    });
                    self.builder.free_register(value_reg);
                }
            }
            Statement::EnumDeclaration(enum_decl) => {
                let value_reg = self.builder.alloc_register()?;
                let name_idx = self.builder.add_string(enum_decl.id.name.cheap_clone())?;
                self.builder.emit(Op::GetVar {
                    dst: value_reg,
                    name: name_idx,
                });
                self.builder.emit(Op::SetPropertyConst {
                    obj: ns_obj,
                    key: name_idx,
                    value: value_reg,
                });
                self.builder.free_register(value_reg);
            }
            Statement::NamespaceDeclaration(nested_ns) => {
                // Add nested namespace to parent namespace
                let value_reg = self.builder.alloc_register()?;
                let name_idx = self.builder.add_string(nested_ns.id.name.cheap_clone())?;
                self.builder.emit(Op::GetVar {
                    dst: value_reg,
                    name: name_idx,
                });
                self.builder.emit(Op::SetPropertyConst {
                    obj: ns_obj,
                    key: name_idx,
                    value: value_reg,
                });
                self.builder.free_register(value_reg);
            }
            _ => {}
        }
        Ok(())
    }

    /// Compile an enum initializer expression, rewriting references to prior enum members
    /// as property accesses on the enum object.
    fn compile_enum_init_expression(
        &mut self,
        expr: &crate::ast::Expression,
        dst: super::Register,
        enum_obj: super::Register,
        prior_members: &[JsString],
    ) -> Result<(), JsError> {
        use crate::ast::Expression;

        match expr {
            // Check if this is an identifier that matches a prior enum member
            Expression::Identifier(id) => {
                if prior_members.iter().any(|m| m.as_str() == id.name.as_str()) {
                    // This is a reference to a prior member - load from enum object
                    let name_idx = self.builder.add_string(id.name.cheap_clone())?;
                    self.builder.emit(Op::GetPropertyConst {
                        dst,
                        obj: enum_obj,
                        key: name_idx,
                    });
                    Ok(())
                } else {
                    // Not a prior member - compile normally
                    self.compile_expression(expr, dst)
                }
            }

            // For binary expressions, recursively handle operands
            Expression::Binary(bin) => {
                let left_reg = self.builder.alloc_register()?;
                let right_reg = self.builder.alloc_register()?;

                self.compile_enum_init_expression(&bin.left, left_reg, enum_obj, prior_members)?;
                self.compile_enum_init_expression(&bin.right, right_reg, enum_obj, prior_members)?;

                // Now emit the binary operation
                self.compile_binary_op(bin.operator, dst, left_reg, right_reg)?;

                self.builder.free_register(right_reg);
                self.builder.free_register(left_reg);
                Ok(())
            }

            // For unary expressions, recursively handle operand
            Expression::Unary(unary) => {
                let arg_reg = self.builder.alloc_register()?;
                self.compile_enum_init_expression(
                    &unary.argument,
                    arg_reg,
                    enum_obj,
                    prior_members,
                )?;

                // Emit the unary operation
                match unary.operator {
                    crate::ast::UnaryOp::Minus => {
                        self.builder.emit(Op::Neg { dst, src: arg_reg });
                    }
                    crate::ast::UnaryOp::Plus => {
                        self.builder.emit(Op::Plus { dst, src: arg_reg });
                    }
                    crate::ast::UnaryOp::Not => {
                        self.builder.emit(Op::Not { dst, src: arg_reg });
                    }
                    crate::ast::UnaryOp::BitNot => {
                        self.builder.emit(Op::BitNot { dst, src: arg_reg });
                    }
                    _ => {
                        // Fall back to normal compilation for other unary ops
                        self.builder.free_register(arg_reg);
                        return self.compile_expression(expr, dst);
                    }
                }

                self.builder.free_register(arg_reg);
                Ok(())
            }

            // For parenthesized expressions, handle the inner expression
            Expression::Parenthesized(expr, _) => {
                self.compile_enum_init_expression(expr, dst, enum_obj, prior_members)
            }

            // For other expressions (literals, etc.), compile normally
            _ => self.compile_expression(expr, dst),
        }
    }

    /// Compile a binary operator
    fn compile_binary_op(
        &mut self,
        operator: crate::ast::BinaryOp,
        dst: super::Register,
        left: super::Register,
        right: super::Register,
    ) -> Result<(), JsError> {
        use crate::ast::BinaryOp;
        match operator {
            BinaryOp::BitOr => self.builder.emit(Op::BitOr { dst, left, right }),
            BinaryOp::BitAnd => self.builder.emit(Op::BitAnd { dst, left, right }),
            BinaryOp::BitXor => self.builder.emit(Op::BitXor { dst, left, right }),
            BinaryOp::Add => self.builder.emit(Op::Add { dst, left, right }),
            BinaryOp::Sub => self.builder.emit(Op::Sub { dst, left, right }),
            BinaryOp::Mul => self.builder.emit(Op::Mul { dst, left, right }),
            BinaryOp::Div => self.builder.emit(Op::Div { dst, left, right }),
            BinaryOp::Mod => self.builder.emit(Op::Mod { dst, left, right }),
            BinaryOp::Exp => self.builder.emit(Op::Exp { dst, left, right }),
            BinaryOp::LShift => self.builder.emit(Op::LShift { dst, left, right }),
            BinaryOp::RShift => self.builder.emit(Op::RShift { dst, left, right }),
            BinaryOp::URShift => self.builder.emit(Op::URShift { dst, left, right }),
            _ => {
                return Err(JsError::internal_error(format!(
                    "Unsupported binary operator in enum initializer: {:?}",
                    operator
                )));
            }
        };
        Ok(())
    }

    /// Compile an export declaration
    fn compile_export_declaration(&mut self, export: &ExportDeclaration) -> Result<(), JsError> {
        self.builder.set_span(export.span);

        // Skip type-only exports
        if export.type_only {
            return Ok(());
        }

        // Handle re-exports: export { foo } from "./bar" or export * as ns from "./bar"
        if let Some(source) = &export.source {
            let source_idx = self.builder.add_string(source.value.cheap_clone())?;

            // Handle namespace re-export: export * as ns from "./bar"
            if let Some(ns) = &export.namespace_export {
                let export_name_idx = self.builder.add_string(ns.name.cheap_clone())?;
                self.builder.emit(Op::ExportNamespace {
                    export_name: export_name_idx,
                    module_specifier: source_idx,
                });
                return Ok(());
            }

            // Handle named re-exports: export { foo, bar as baz } from "./bar"
            for spec in &export.specifiers {
                let export_name_idx = self.builder.add_string(spec.exported.name.cheap_clone())?;
                let source_key_idx = self.builder.add_string(spec.local.name.cheap_clone())?;
                self.builder.emit(Op::ReExport {
                    export_name: export_name_idx,
                    source_module: source_idx,
                    source_key: source_key_idx,
                });
            }
            return Ok(());
        }

        // Handle default export: export default expr
        if export.default
            && let Some(ref decl) = export.declaration
        {
            // export default function/class/expression
            // First compile the declaration to get the value
            let value_reg = self.builder.alloc_register()?;

            match decl.as_ref() {
                Statement::FunctionDeclaration(func) => {
                    // Compile function and store in value_reg
                    self.compile_function_expression_for_export(func, value_reg)?;
                }
                Statement::ClassDeclaration(class) => {
                    // Compile class and store in value_reg
                    self.compile_class_expression_for_export(class, value_reg)?;
                }
                Statement::Expression(expr_stmt) => {
                    // Compile expression
                    self.compile_expression(&expr_stmt.expression, value_reg)?;
                }
                _ => {
                    // Shouldn't happen - other statements can't be default exported
                    return Err(JsError::syntax_error_simple(
                        "Unexpected declaration in default export",
                    ));
                }
            }

            // Emit export binding for "default"
            let default_str = self.builder.add_string(JsString::from("default"))?;
            self.builder.emit(Op::ExportBinding {
                export_name: default_str,
                binding_name: default_str,
                value: value_reg,
            });

            self.builder.free_register(value_reg);
            return Ok(());
        }

        // Handle named export declaration: export const/let/var/function/class
        if let Some(ref decl) = export.declaration {
            // First compile the declaration
            self.compile_statement_impl(decl)?;

            // Then emit export bindings for all names defined
            match decl.as_ref() {
                Statement::FunctionDeclaration(func) => {
                    if let Some(id) = &func.id {
                        // Get the function value and export it
                        let value_reg = self.builder.alloc_register()?;
                        let name_idx = self.builder.add_string(id.name.cheap_clone())?;
                        self.builder.emit(Op::GetVar {
                            dst: value_reg,
                            name: name_idx,
                        });
                        self.builder.emit(Op::ExportBinding {
                            export_name: name_idx,
                            binding_name: name_idx,
                            value: value_reg,
                        });
                        self.builder.free_register(value_reg);
                    }
                }
                Statement::ClassDeclaration(class) => {
                    if let Some(id) = &class.id {
                        // Get the class value and export it
                        let value_reg = self.builder.alloc_register()?;
                        let name_idx = self.builder.add_string(id.name.cheap_clone())?;
                        self.builder.emit(Op::GetVar {
                            dst: value_reg,
                            name: name_idx,
                        });
                        self.builder.emit(Op::ExportBinding {
                            export_name: name_idx,
                            binding_name: name_idx,
                            value: value_reg,
                        });
                        self.builder.free_register(value_reg);
                    }
                }
                Statement::VariableDeclaration(var_decl) => {
                    // Export each variable in the declaration
                    for declarator in var_decl.declarations.iter() {
                        self.emit_export_for_pattern(&declarator.id)?;
                    }
                }
                Statement::EnumDeclaration(enum_decl) => {
                    // Export the enum
                    let value_reg = self.builder.alloc_register()?;
                    let name_idx = self.builder.add_string(enum_decl.id.name.cheap_clone())?;
                    self.builder.emit(Op::GetVar {
                        dst: value_reg,
                        name: name_idx,
                    });
                    self.builder.emit(Op::ExportBinding {
                        export_name: name_idx,
                        binding_name: name_idx,
                        value: value_reg,
                    });
                    self.builder.free_register(value_reg);
                }
                Statement::NamespaceDeclaration(ns_decl) => {
                    // Export the namespace
                    let value_reg = self.builder.alloc_register()?;
                    let name_idx = self.builder.add_string(ns_decl.id.name.cheap_clone())?;
                    self.builder.emit(Op::GetVar {
                        dst: value_reg,
                        name: name_idx,
                    });
                    self.builder.emit(Op::ExportBinding {
                        export_name: name_idx,
                        binding_name: name_idx,
                        value: value_reg,
                    });
                    self.builder.free_register(value_reg);
                }
                _ => {}
            }
            return Ok(());
        }

        // Handle named export specifiers: export { foo, bar as baz }
        for spec in &export.specifiers {
            let value_reg = self.builder.alloc_register()?;
            let local_name_idx = self.builder.add_string(spec.local.name.cheap_clone())?;
            let export_name_idx = self.builder.add_string(spec.exported.name.cheap_clone())?;

            // Get the local variable value
            self.builder.emit(Op::GetVar {
                dst: value_reg,
                name: local_name_idx,
            });

            // Export it
            self.builder.emit(Op::ExportBinding {
                export_name: export_name_idx,
                binding_name: local_name_idx,
                value: value_reg,
            });

            self.builder.free_register(value_reg);
        }

        Ok(())
    }

    /// Emit export bindings for a pattern (handles destructuring)
    fn emit_export_for_pattern(&mut self, pattern: &Pattern) -> Result<(), JsError> {
        match pattern {
            Pattern::Identifier(id) => {
                let value_reg = self.builder.alloc_register()?;
                let name_idx = self.builder.add_string(id.name.cheap_clone())?;
                self.builder.emit(Op::GetVar {
                    dst: value_reg,
                    name: name_idx,
                });
                self.builder.emit(Op::ExportBinding {
                    export_name: name_idx,
                    binding_name: name_idx,
                    value: value_reg,
                });
                self.builder.free_register(value_reg);
            }
            Pattern::Object(obj_pattern) => {
                for prop in &obj_pattern.properties {
                    match prop {
                        ObjectPatternProperty::KeyValue { value, .. } => {
                            self.emit_export_for_pattern(value)?;
                        }
                        ObjectPatternProperty::Rest(rest_elem) => {
                            self.emit_export_for_pattern(&rest_elem.argument)?;
                        }
                    }
                }
            }
            Pattern::Array(arr_pattern) => {
                for p in arr_pattern.elements.iter().flatten() {
                    self.emit_export_for_pattern(p)?;
                }
            }
            Pattern::Rest(rest_elem) => {
                self.emit_export_for_pattern(&rest_elem.argument)?;
            }
            Pattern::Assignment(assign_pattern) => {
                self.emit_export_for_pattern(&assign_pattern.left)?;
            }
        }
        Ok(())
    }

    /// Compile a function for export default (returns value in register)
    fn compile_function_expression_for_export(
        &mut self,
        func: &crate::ast::FunctionDeclaration,
        dst: Register,
    ) -> Result<(), JsError> {
        use crate::ast::FunctionExpression;

        // Convert FunctionDeclaration to a FunctionExpression-like structure for compilation
        let func_expr = FunctionExpression {
            id: func.id.clone(),
            params: func.params.clone(),
            body: func.body.clone(),
            generator: func.generator,
            async_: func.async_,
            span: func.span,
            return_type: None,
            type_parameters: None,
        };

        self.compile_function_expression(&func_expr, dst)?;
        Ok(())
    }

    /// Compile a class for export default (returns value in register)
    fn compile_class_expression_for_export(
        &mut self,
        class: &ClassDeclaration,
        dst: Register,
    ) -> Result<(), JsError> {
        use crate::ast::ClassExpression;

        // Convert ClassDeclaration to ClassExpression for compilation
        let class_expr = ClassExpression {
            id: class.id.clone(),
            super_class: class.super_class.clone(),
            body: class.body.clone(),
            implements: class.implements.clone(),
            type_parameters: None,
            decorators: class.decorators.clone(),
            span: class.span,
        };

        self.compile_class_expression(&class_expr, dst)?;
        Ok(())
    }
}