1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
//! Bytecode Virtual Machine
//!
//! This module implements the bytecode interpreter that executes compiled bytecode.
//! It uses a register-based design with up to 256 virtual registers per call frame.
use crate::compiler::{BytecodeChunk, Constant, Op, Register};
use crate::error::{JsError, StackFrame};
use crate::gc::{Gc, Guard};
use crate::prelude::{math, *};
use crate::value::{
BytecodeFunction, CheapClone, ExoticObject, Guarded, JsFunction, JsObject, JsString, JsValue,
Property, PropertyKey,
};
use super::Interpreter;
/// Parameters for a trampoline function call
struct CallParams {
callee: JsValue,
this_value: JsValue,
args: Vec<JsValue>,
return_register: Register,
new_target: JsValue,
is_super_call: bool,
}
/// Result of VM execution
pub enum VmResult {
/// Execution completed with a value
Complete(Guarded),
/// Need to suspend for await/yield on a Promise
Suspend(VmSuspension),
/// Suspended waiting for order fulfillment from host
SuspendForOrder(VmOrderSuspension),
/// Generator yielded a value
Yield(GeneratorYield),
/// Generator yielded via yield*
YieldStar(GeneratorYieldStar),
/// Error occurred
Error(JsError),
}
/// Result of a single VM step
pub enum VmStepResult {
/// Executed one instruction, more to go
Continue,
/// Reached a terminal state
Terminal(Box<VmResult>),
}
/// Generator yield result
pub struct GeneratorYield {
/// The yielded value (guarded to keep alive during suspension)
pub value: Guarded,
/// Register to store the value passed to next() when resumed
pub resume_register: Register,
/// Saved VM state for resumption
pub state: SavedVmState,
}
/// Generator yield* result
pub struct GeneratorYieldStar {
/// The iterable to delegate to (guarded to keep alive during suspension)
pub iterable: Guarded,
/// Register to store the final value when delegation completes
pub resume_register: Register,
/// Saved VM state for resumption
pub state: SavedVmState,
}
/// Suspension state for async/generator (waiting on a Promise)
pub struct VmSuspension {
/// The promise we're waiting on
pub waiting_on: Gc<JsObject>,
/// Saved VM state for resumption
pub state: SavedVmState,
/// Register to store the resume value (for await)
pub resume_register: Register,
}
/// Suspension state for awaiting order fulfillment from host
pub struct VmOrderSuspension {
/// The order ID we're waiting for
pub order_id: crate::OrderId,
/// Saved VM state for resumption
pub state: SavedVmState,
/// Register to store the response value
pub resume_register: Register,
}
/// Saved VM state for suspension/resumption
pub struct SavedVmState {
/// Saved call frames
pub frames: Vec<CallFrame>,
/// Current instruction pointer
pub ip: usize,
/// Current bytecode chunk
pub chunk: Rc<BytecodeChunk>,
/// Register values
pub registers: Vec<JsValue>,
/// Exception handlers
pub try_stack: Vec<TryHandler>,
/// Guard to keep all objects in registers alive during suspension.
/// The field is never read but exists for its drop semantics.
#[allow(dead_code)]
pub guard: Option<Guard<JsObject>>,
/// Original arguments for `arguments` object
pub arguments: Vec<JsValue>,
/// new.target value
pub new_target: JsValue,
/// Trampoline call stack (for nested function calls)
pub trampoline_stack: Vec<SavedTrampolineFrame>,
}
/// A call frame in the VM
#[derive(Debug, Clone)]
pub struct CallFrame {
/// Return instruction pointer
pub return_ip: usize,
/// Return bytecode chunk
pub return_chunk: Rc<BytecodeChunk>,
/// Base register index in the register file
pub registers_base: usize,
/// Register to store return value
pub return_register: Register,
/// Saved environment for restoration on return
pub saved_env: Option<Gc<JsObject>>,
}
/// Exception handler for try/catch/finally
#[derive(Debug, Clone)]
pub struct TryHandler {
/// Instruction pointer for catch block
pub catch_ip: usize,
/// Instruction pointer for finally block (0 = no finally)
pub finally_ip: usize,
/// Register count at time of push (for stack unwinding)
pub registers_snapshot: usize,
/// Call frame depth at time of push
pub frame_depth: usize,
/// Scope depth at time of push (saved_env_stack.len())
/// Used to pop any scopes that were entered in the try block when catching
pub scope_depth: usize,
/// Iterator register for for-of iterator close (None for regular try)
/// When set, this is a PushIterTry handler that should close the iterator on exception
pub iterator_reg: Option<Register>,
}
/// Pending completion to be executed after finally block
pub enum PendingCompletion {
/// Return this value after finally completes
Return(Guarded),
/// Rethrow this exception after finally completes
Throw(Guarded),
/// Break to target after finally completes
Break {
target: usize,
try_depth: u8,
scope_depth: u32,
},
/// Continue to target after finally completes
Continue {
target: usize,
try_depth: u8,
scope_depth: u32,
},
}
/// A saved trampoline frame for suspension (Clone-able version without Guard)
/// The SavedVmState.guard keeps all objects alive during suspension
#[derive(Clone)]
pub struct SavedTrampolineFrame {
/// Saved instruction pointer
pub ip: usize,
/// Saved bytecode chunk
pub chunk: Rc<BytecodeChunk>,
/// Saved registers
pub registers: Vec<JsValue>,
/// Saved this value
pub this_value: JsValue,
/// Saved VM call stack
pub vm_call_stack: Vec<CallFrame>,
/// Saved try handlers
pub try_stack: Vec<TryHandler>,
/// Saved environment stack
pub saved_env_stack: Vec<Gc<JsObject>>,
/// Saved arguments
pub arguments: Vec<JsValue>,
/// Saved new.target
pub new_target: JsValue,
/// Saved current constructor
pub current_constructor: Option<Gc<JsObject>>,
/// Register to store the return value in
pub return_register: Register,
/// Saved interpreter environment
pub saved_interp_env: Gc<JsObject>,
/// For construct calls: the new object to fall back to if constructor doesn't return an object
pub construct_new_obj: Option<Gc<JsObject>>,
/// For async function calls: wrap result in a Promise when returning
pub is_async: bool,
}
/// A saved VM frame for the trampoline call stack
/// This replaces Rust call stack recursion with an explicit stack
pub struct TrampolineFrame {
/// Saved instruction pointer
pub ip: usize,
/// Saved bytecode chunk
pub chunk: Rc<BytecodeChunk>,
/// Saved registers
pub registers: Vec<JsValue>,
/// Saved this value
pub this_value: JsValue,
/// Saved VM call stack
pub vm_call_stack: Vec<CallFrame>,
/// Saved try handlers
pub try_stack: Vec<TryHandler>,
/// Saved exception value (guarded to keep it alive during finally block execution)
pub exception_value: Option<Guarded>,
/// Saved environment stack
pub saved_env_stack: Vec<Gc<JsObject>>,
/// Saved arguments
pub arguments: Vec<JsValue>,
/// Saved new.target
pub new_target: JsValue,
/// Saved current constructor
pub current_constructor: Option<Gc<JsObject>>,
/// Saved pending completion
pub pending_completion: Option<PendingCompletion>,
/// Register to store the return value in
pub return_register: Register,
/// Saved interpreter environment
pub saved_interp_env: Gc<JsObject>,
/// Guard that was protecting this frame's register values.
/// This is ONLY for the saved `registers` - not for exception_value or other fields.
pub register_guard: Guard<JsObject>,
/// For construct calls: the new object to fall back to if constructor doesn't return an object
pub construct_new_obj: Option<Gc<JsObject>>,
/// For async function calls: wrap result in a Promise when returning
pub is_async: bool,
}
/// The bytecode virtual machine
pub struct BytecodeVM {
/// Current instruction pointer
pub ip: usize,
/// Current bytecode chunk being executed
pub chunk: Rc<BytecodeChunk>,
/// Register file
pub registers: Vec<JsValue>,
/// Guard keeping all register values alive.
///
/// IMPORTANT: This guard is ONLY for values stored in `registers`.
/// Do NOT use it for exception_value, OpResult values, PendingCompletion,
/// or any other non-register storage. Those must have their own dedicated guards.
register_guard: Guard<JsObject>,
/// Call stack (return addresses)
pub call_stack: Vec<CallFrame>,
/// Exception handler stack
pub try_stack: Vec<TryHandler>,
/// Current `this` value
this_value: JsValue,
/// Current exception value (for catch blocks)
/// Guarded to keep the exception alive during finally block execution
exception_value: Option<Guarded>,
/// Stack of saved environments for nested scope restoration
saved_env_stack: Vec<Gc<JsObject>>,
/// Original arguments array (for `arguments` object)
pub arguments: Vec<JsValue>,
/// `new.target` value (constructor if called with new, undefined otherwise)
pub new_target: JsValue,
/// Current constructor being executed (for super() lookups in derived classes)
current_constructor: Option<Gc<JsObject>>,
/// Pending completion to execute after finally block
pending_completion: Option<PendingCompletion>,
/// Trampoline call stack - replaces Rust recursion with explicit stack
trampoline_stack: Vec<TrampolineFrame>,
/// Pool of reusable register files to reduce allocation overhead
register_pool: Vec<Vec<JsValue>>,
/// Pool of reusable argument vectors to reduce allocation overhead
arguments_pool: Vec<Vec<JsValue>>,
}
impl BytecodeVM {
/// Create a new VM with a guard for keeping objects alive
pub fn with_guard(
chunk: Rc<BytecodeChunk>,
this_value: JsValue,
guard: Guard<JsObject>,
) -> Self {
let register_count = chunk.register_count as usize;
// Guard this_value if it's an object
if let JsValue::Object(obj) = &this_value {
guard.guard(obj.cheap_clone());
}
Self {
ip: 0,
chunk,
registers: vec![JsValue::Undefined; register_count.max(1)],
register_guard: guard,
call_stack: Vec::new(),
try_stack: Vec::new(),
this_value,
exception_value: None,
saved_env_stack: Vec::new(),
arguments: Vec::new(),
new_target: JsValue::Undefined,
current_constructor: None,
pending_completion: None,
trampoline_stack: Vec::new(),
register_pool: Vec::new(),
arguments_pool: Vec::new(),
}
}
/// Get the current trampoline call depth (number of pending function calls)
pub fn trampoline_depth(&self) -> usize {
self.trampoline_stack.len()
}
/// Create a new VM with a guard and pre-populated function arguments.
/// Arguments are placed in registers 0, 1, 2, ... before execution starts.
/// The bytecode's DeclareVar ops will read from these registers.
pub fn with_guard_and_args(
chunk: Rc<BytecodeChunk>,
this_value: JsValue,
guard: Guard<JsObject>,
args: &[JsValue],
) -> Self {
let register_count = chunk.register_count as usize;
let mut registers = vec![JsValue::Undefined; register_count.max(1)];
// Guard this_value if it's an object
if let JsValue::Object(obj) = &this_value {
guard.guard(obj.cheap_clone());
}
// Pre-populate registers with arguments
for (i, arg) in args.iter().enumerate() {
if i < registers.len()
&& let Some(slot) = registers.get_mut(i)
{
if let JsValue::Object(obj) = arg {
guard.guard(obj.cheap_clone());
}
*slot = arg.clone();
}
}
Self {
ip: 0,
chunk,
registers,
register_guard: guard,
call_stack: Vec::new(),
try_stack: Vec::new(),
this_value,
exception_value: None,
saved_env_stack: Vec::new(),
arguments: args.to_vec(),
new_target: JsValue::Undefined,
current_constructor: None,
pending_completion: None,
trampoline_stack: Vec::new(),
register_pool: Vec::new(),
arguments_pool: Vec::new(),
}
}
/// Create a new VM with a guard, arguments, and new.target value.
pub fn with_guard_args_and_new_target(
chunk: Rc<BytecodeChunk>,
this_value: JsValue,
guard: Guard<JsObject>,
args: &[JsValue],
new_target: JsValue,
) -> Self {
let register_count = chunk.register_count as usize;
let mut registers = vec![JsValue::Undefined; register_count.max(1)];
// Guard this_value if it's an object
if let JsValue::Object(obj) = &this_value {
guard.guard(obj.cheap_clone());
}
// Guard new_target if it's an object
if let JsValue::Object(obj) = &new_target {
guard.guard(obj.cheap_clone());
}
// Pre-populate registers with arguments
for (i, arg) in args.iter().enumerate() {
if i < registers.len()
&& let Some(slot) = registers.get_mut(i)
{
if let JsValue::Object(obj) = arg {
guard.guard(obj.cheap_clone());
}
*slot = arg.clone();
}
}
Self {
ip: 0,
chunk,
registers,
register_guard: guard,
call_stack: Vec::new(),
try_stack: Vec::new(),
this_value,
exception_value: None,
saved_env_stack: Vec::new(),
arguments: args.to_vec(),
new_target,
current_constructor: None,
pending_completion: None,
trampoline_stack: Vec::new(),
register_pool: Vec::new(),
arguments_pool: Vec::new(),
}
}
/// Acquire a register file from the pool, or allocate a new one
#[inline]
fn acquire_registers(&mut self, size: usize) -> Vec<JsValue> {
let size = size.max(1);
// Try to find an existing frame of sufficient size
if let Some(pos) = self.register_pool.iter().position(|f| f.capacity() >= size) {
let mut frame = self.register_pool.swap_remove(pos);
frame.clear();
frame.resize(size, JsValue::Undefined);
return frame;
}
// Allocate new frame
vec![JsValue::Undefined; size]
}
/// Return a register file to the pool for reuse.
/// Also clears the register_guard to remove stale roots that could waste
/// GC cycles iterating over now-pooled objects.
#[inline]
fn release_registers(&mut self, mut registers: Vec<JsValue>) {
// Clear register_guard BEFORE clearing registers - this removes the guard's
// roots while the objects still have valid ref_counts from the registers Vec.
// If we cleared registers first, the guard would have stale roots pointing
// to potentially-pooled GcBoxes.
self.register_guard.clear();
// Clear the registers to drop any references
registers.clear();
// Keep pool size reasonable (e.g., max 16 frames)
if self.register_pool.len() < 16 {
self.register_pool.push(registers);
}
}
/// Acquire an empty arguments vector with given capacity from pool
#[inline]
fn acquire_arguments_vec(&mut self, capacity: usize) -> Vec<JsValue> {
if let Some(pos) = self
.arguments_pool
.iter()
.position(|v| v.capacity() >= capacity)
{
let mut vec = self.arguments_pool.swap_remove(pos);
vec.clear();
return vec;
}
Vec::with_capacity(capacity)
}
/// Return an arguments vector to the pool for reuse
#[inline]
fn release_arguments(&mut self, mut args: Vec<JsValue>) {
args.clear();
// Keep pool size reasonable (max 16)
if self.arguments_pool.len() < 16 {
self.arguments_pool.push(args);
}
}
/// Build a stack trace from the current VM state.
/// Returns a vector of StackFrame entries from innermost to outermost.
pub fn build_stack_trace(&self) -> Vec<StackFrame> {
let mut frames = Vec::new();
// Current frame (where the error occurred)
let current_ip = if self.ip > 0 { self.ip - 1 } else { 0 };
if let Some(span) = self.chunk.get_source_location(current_ip) {
let function_name = self
.chunk
.function_info
.as_ref()
.and_then(|info| info.name.as_ref().map(|s| s.to_string()));
frames.push(StackFrame {
function_name,
file: self.chunk.source_file.clone(),
line: span.line,
column: span.column,
});
}
// Frames from the trampoline stack (outer call frames)
for tramp_frame in self.trampoline_stack.iter().rev() {
let frame_ip = if tramp_frame.ip > 0 {
tramp_frame.ip - 1
} else {
0
};
if let Some(span) = tramp_frame.chunk.get_source_location(frame_ip) {
let function_name = tramp_frame
.chunk
.function_info
.as_ref()
.and_then(|info| info.name.as_ref().map(|s| s.to_string()));
frames.push(StackFrame {
function_name,
file: tramp_frame.chunk.source_file.clone(),
line: span.line,
column: span.column,
});
}
}
frames
}
/// Wrap a JsError with stack trace information.
/// Converts simple errors (TypeError, ReferenceError, etc.) into RuntimeError with backtrace.
pub fn wrap_error_with_trace(&self, error: JsError) -> JsError {
// Only wrap errors that don't already have a stack trace
match &error {
JsError::RuntimeError { .. } => error, // Already has stack
JsError::Thrown | JsError::ThrownValue { .. } => error, // User-thrown, handled separately
JsError::GeneratorYield { .. } => error, // Not a real error
JsError::OptionalChainShortCircuit => error, // Not a real error
_ => {
let stack = self.build_stack_trace();
let (kind, message) = match &error {
JsError::TypeError { message, .. } => {
("TypeError".to_string(), message.clone())
}
JsError::ReferenceError { name } => (
"ReferenceError".to_string(),
format!("{} is not defined", name),
),
JsError::RangeError { message } => ("RangeError".to_string(), message.clone()),
JsError::SyntaxError { message, .. } => {
("SyntaxError".to_string(), message.clone())
}
JsError::ModuleError { message } => {
("ModuleError".to_string(), message.clone())
}
JsError::Internal(msg) => ("InternalError".to_string(), msg.clone()),
// Already handled above
_ => return error,
};
JsError::RuntimeError {
kind,
message,
stack,
}
}
}
}
/// Get register value
#[inline]
fn get_reg(&self, r: Register) -> &JsValue {
self.registers
.get(r as usize)
.unwrap_or(&JsValue::Undefined)
}
/// Set register value
#[inline]
pub fn set_reg(&mut self, r: Register, value: JsValue) {
let idx = r as usize;
debug_assert!(
idx < self.registers.len(),
"Register index {} out of bounds (max {})",
idx,
self.registers.len()
);
if idx < self.registers.len()
&& let Some(slot) = self.registers.get_mut(idx)
{
if let JsValue::Object(obj) = &value {
self.register_guard.guard(obj.clone());
}
if let JsValue::Object(obj) = &slot {
self.register_guard.unguard(obj);
}
*slot = value;
}
}
/// Fetch the next instruction and advance IP
#[inline]
fn fetch(&mut self) -> Option<Op> {
let op = *self.chunk.get(self.ip)?;
self.ip += 1;
Some(op)
}
/// Get a constant from the pool
#[inline]
fn get_constant(&self, idx: u16) -> Option<&Constant> {
self.chunk.get_constant(idx)
}
/// Get a string constant from the pool
#[inline]
fn get_string_constant(&self, idx: u16) -> Option<JsString> {
match self.get_constant(idx)? {
Constant::String(s) => Some(s.cheap_clone()),
_ => None,
}
}
/// Get the super constructor from the current function's __super__ property
fn get_super_constructor(&self, interp: &mut Interpreter) -> Result<JsValue, JsError> {
// Look up __super__ in the current function's properties
let super_key = PropertyKey::String(interp.intern("__super__"));
// First, check if we have a current_constructor set (for construct calls)
// This is the most reliable way to find super() in derived class constructors
if let Some(ref ctor) = self.current_constructor
&& let Some(super_val) = ctor.borrow().get_property(&super_key)
{
return Ok(super_val);
}
if let JsValue::Object(this_obj) = &self.this_value {
// For static methods: `this` IS the class constructor, check directly on it
if let Some(super_val) = this_obj.borrow().get_property(&super_key) {
return Ok(super_val);
}
// For instance methods: look up constructor from prototype chain
if let Some(proto) = &this_obj.borrow().prototype
&& let Some(JsValue::Object(ctor_obj)) = proto
.borrow()
.get_property(&PropertyKey::String(interp.intern("constructor")))
&& let Some(super_val) = ctor_obj.borrow().get_property(&super_key)
{
return Ok(super_val);
}
}
Err(JsError::syntax_error_simple(
"'super' keyword is only valid inside a class method",
))
}
/// Get the super target object for super.x property access
fn get_super_target(&self, interp: &mut Interpreter) -> Result<JsValue, JsError> {
// First, try to look up __super_target__ from the current environment
// This is set when entering a method via the trampoline
let super_target_name = interp.intern("__super_target__");
if let Ok(target) = interp.env_get(&super_target_name) {
return Ok(target);
}
// Fallback: look up from this value's prototype chain (old behavior)
let super_key = PropertyKey::String(interp.intern("__super__"));
let super_target_key = PropertyKey::String(super_target_name);
if let JsValue::Object(this_obj) = &self.this_value {
// For static methods: `this` IS the class constructor
// If `this` has __super__ directly, use __super__ (parent constructor)
// as the target for looking up static methods
if this_obj.borrow().get_property(&super_key).is_some() {
// Static method context: super.x looks up on parent constructor
if let Some(target) = this_obj.borrow().get_property(&super_key) {
return Ok(target);
}
}
// For instance methods: look up constructor from prototype chain
// and use __super_target__ (parent prototype) for property access
if let Some(proto) = &this_obj.borrow().prototype
&& let Some(JsValue::Object(ctor_obj)) = proto
.borrow()
.get_property(&PropertyKey::String(interp.intern("constructor")))
&& let Some(target) = ctor_obj.borrow().get_property(&super_target_key)
{
return Ok(target);
}
}
Err(JsError::syntax_error_simple(
"'super' keyword is only valid inside a class method",
))
}
/// Execute a single bytecode instruction.
///
/// Returns `VmStepResult::Continue` if more instructions remain,
/// or `VmStepResult::Terminal(result)` if execution reached a terminal state.
///
/// This method enables step-by-step execution for host-controlled interruption.
#[inline]
pub fn step(&mut self, interp: &mut Interpreter) -> VmStepResult {
let Some(op) = self.fetch() else {
// End of bytecode - return last result or undefined
let result = self
.registers
.first()
.cloned()
.unwrap_or(JsValue::Undefined);
// Check if we have a trampoline frame to return to
if let Some(frame) = self.trampoline_stack.pop() {
// Restore state from trampoline frame
self.restore_from_trampoline_frame(interp, frame, result);
return VmStepResult::Continue;
}
let guard = interp.heap.create_guard();
if let JsValue::Object(obj) = &result {
guard.guard(obj.cheap_clone());
}
return VmStepResult::Terminal(Box::new(VmResult::Complete(Guarded {
value: result,
guard: Some(guard),
})));
};
match self.execute_op(interp, op) {
Ok(OpResult::Continue) => VmStepResult::Continue,
Ok(OpResult::Halt(value)) => {
// Check if we have a trampoline frame to return to
if let Some(frame) = self.trampoline_stack.pop() {
// Restore state from trampoline frame
self.restore_from_trampoline_frame(interp, frame, value.value);
return VmStepResult::Continue;
}
VmStepResult::Terminal(Box::new(VmResult::Complete(value)))
}
Ok(OpResult::Suspend {
promise,
resume_register,
}) => {
// Extract the object from the guarded value
if let JsValue::Object(obj) = promise.value {
VmStepResult::Terminal(Box::new(VmResult::Suspend(VmSuspension {
waiting_on: obj,
state: self.save_state(interp),
resume_register,
})))
} else {
VmStepResult::Terminal(Box::new(VmResult::Error(self.wrap_error_with_trace(
JsError::internal_error("Suspend expects an object"),
))))
}
}
Ok(OpResult::SuspendForOrder {
order_id,
resume_register,
}) => {
// Suspend waiting for host to provide order response
VmStepResult::Terminal(Box::new(VmResult::SuspendForOrder(VmOrderSuspension {
order_id,
state: self.save_state(interp),
resume_register,
})))
}
Ok(OpResult::Yield {
value,
resume_register,
}) => VmStepResult::Terminal(Box::new(VmResult::Yield(GeneratorYield {
value,
resume_register,
state: self.save_state(interp),
}))),
Ok(OpResult::YieldStar {
iterable,
resume_register,
}) => VmStepResult::Terminal(Box::new(VmResult::YieldStar(GeneratorYieldStar {
iterable,
resume_register,
state: self.save_state(interp),
}))),
Ok(OpResult::Call {
callee,
this_value,
args,
return_register,
new_target,
is_super_call,
guard: _guard, // Guard keeps values alive until trampoline frame is pushed
}) => {
// Trampoline: save current state and switch to called function
match self.setup_trampoline_call(
interp,
CallParams {
callee,
this_value,
args,
return_register,
new_target,
is_super_call,
},
) {
Ok(None) => VmStepResult::Continue,
Ok(Some(vm_result)) => VmStepResult::Terminal(Box::new(vm_result)),
Err(e) => {
// Try to find an exception handler, unwinding trampoline if needed
if let Err(e) = self.handle_error_with_trampoline_unwind(interp, e) {
return VmStepResult::Terminal(Box::new(VmResult::Error(e)));
}
VmStepResult::Continue
}
}
}
Ok(OpResult::Construct {
callee,
this_value,
args,
return_register,
new_target,
new_obj,
guard: _guard, // Guard keeps values alive until trampoline frame is pushed
}) => {
// Trampoline for construct: save current state and switch to constructor
match self.setup_trampoline_construct(
interp,
callee,
this_value,
args,
return_register,
new_target,
new_obj,
) {
Ok(()) => VmStepResult::Continue,
Err(e) => {
// Try to find an exception handler, unwinding trampoline if needed
if let Err(e) = self.handle_error_with_trampoline_unwind(interp, e) {
return VmStepResult::Terminal(Box::new(VmResult::Error(e)));
}
VmStepResult::Continue
}
}
}
Err(e) => {
// Try to find an exception handler, unwinding trampoline if needed
if let Err(e) = self.handle_error_with_trampoline_unwind(interp, e) {
return VmStepResult::Terminal(Box::new(VmResult::Error(e)));
}
VmStepResult::Continue
}
}
}
/// Execute bytecode until completion, suspension, or error.
/// Uses a trampoline pattern to avoid Rust stack overflow on deep JS call chains.
///
/// This method runs until a terminal state is reached. For step-by-step control,
/// use the `step()` method instead.
pub fn run(&mut self, interp: &mut Interpreter) -> VmResult {
loop {
match self.step(interp) {
VmStepResult::Continue => continue,
VmStepResult::Terminal(result) => return *result,
}
}
}
/// Set up a trampoline call - save current state and switch to the called function
/// If `is_super_call` is true, the callee will be set as the current constructor for proper super() lookup
///
/// Returns:
/// - `Ok(None)` - continue execution (trampoline set up or native function completed)
/// - `Ok(Some(VmResult))` - return this VmResult immediately (e.g., for suspension)
/// - `Err(e)` - error occurred
fn setup_trampoline_call(
&mut self,
interp: &mut Interpreter,
params: CallParams,
) -> Result<Option<VmResult>, JsError> {
use crate::value::{ExoticObject, JsFunction};
let CallParams {
callee,
this_value,
args,
return_register,
new_target,
is_super_call,
} = params;
let JsValue::Object(func_obj) = &callee else {
return Err(JsError::type_error("Not a function"));
};
// Check if this is a proxy
let is_proxy = matches!(func_obj.borrow().exotic, ExoticObject::Proxy(_));
if is_proxy {
// For proxies, fall back to recursive call (they're rare)
let result = crate::interpreter::builtins::proxy::proxy_apply(
interp,
func_obj.cheap_clone(),
this_value,
args,
)?;
self.set_reg(return_register, result.value);
return Ok(None);
}
let func = {
let obj_ref = func_obj.borrow();
match &obj_ref.exotic {
ExoticObject::Function(f) => f.clone(),
_ => return Err(JsError::type_error("Not a function")),
}
};
match func {
JsFunction::Bytecode(bc_func) => {
// This is what we want to trampoline!
self.push_trampoline_frame_and_call_bytecode(
interp,
func_obj.cheap_clone(),
bc_func,
this_value,
args,
return_register,
new_target,
false, // not async
is_super_call,
)?;
Ok(None)
}
JsFunction::Native(native) => {
// Native functions are quick, call directly
// Set FFI callback ID if this is an FFI-registered function
let prev_ffi_id = interp.current_ffi_id;
interp.current_ffi_id = native.ffi_id;
let result = (native.func)(interp, this_value, &args);
interp.current_ffi_id = prev_ffi_id;
let result = result?;
// Check if result is a PendingOrder - if so, suspend immediately.
// This makes order() a blocking syscall - each call suspends
// execution until the host fulfills the order with a value.
// For parallel operations, the host can return unresolved Promises
// that are later resolved concurrently.
if let JsValue::Object(ref obj) = result.value
&& let ExoticObject::PendingOrder { id, .. } = &obj.borrow().exotic
{
let order_id = crate::OrderId(*id);
let state = self.save_state(interp);
return Ok(Some(VmResult::SuspendForOrder(VmOrderSuspension {
order_id,
state,
resume_register: return_register,
})));
}
self.set_reg(return_register, result.value);
Ok(None)
}
JsFunction::Bound(bound) => {
// Unwrap bound function and trampoline to target
let target = JsValue::Object(bound.target.cheap_clone());
let bound_this = bound.this_arg.clone();
let mut full_args = bound.bound_args.clone();
full_args.extend(args);
self.setup_trampoline_call(
interp,
CallParams {
callee: target,
this_value: bound_this,
args: full_args,
return_register,
new_target,
is_super_call,
},
)
}
JsFunction::BytecodeGenerator(bc_func) => {
// Generators just create a generator object without running the body.
// The body runs when .next() is called. Handle directly without recursion.
use crate::value::{BytecodeGeneratorState, GeneratorStatus};
let gen_id = interp.next_generator_id;
interp.next_generator_id = interp.next_generator_id.wrapping_add(1);
let state = BytecodeGeneratorState {
chunk: bc_func.chunk,
closure: bc_func.closure,
args: args.to_vec(),
this_value,
status: GeneratorStatus::Suspended,
sent_value: JsValue::Undefined,
id: gen_id,
started: false,
saved_ip: 0,
saved_registers: Vec::new(),
saved_call_stack: Vec::new(),
saved_try_stack: Vec::new(),
yield_result_register: None,
func_env: None,
current_env: None,
delegated_iterator: None,
is_async: false,
throw_value: None,
};
let gen_obj = super::builtins::generator::create_bytecode_generator_object(
interp,
&self.register_guard,
state,
);
self.set_reg(return_register, JsValue::Object(gen_obj));
Ok(None)
}
JsFunction::BytecodeAsyncGenerator(bc_func) => {
// Async generators just create an async generator object without running the body.
// The body runs when .next() is called. Handle directly without recursion.
use crate::value::{BytecodeGeneratorState, GeneratorStatus};
let gen_id = interp.next_generator_id;
interp.next_generator_id = interp.next_generator_id.wrapping_add(1);
let state = BytecodeGeneratorState {
chunk: bc_func.chunk,
closure: bc_func.closure,
args: args.to_vec(),
this_value,
status: GeneratorStatus::Suspended,
sent_value: JsValue::Undefined,
id: gen_id,
started: false,
saved_ip: 0,
saved_registers: Vec::new(),
saved_call_stack: Vec::new(),
saved_try_stack: Vec::new(),
yield_result_register: None,
func_env: None,
current_env: None,
delegated_iterator: None,
is_async: true, // Async generator
throw_value: None,
};
let gen_obj = super::builtins::generator::create_bytecode_generator_object(
interp,
&self.register_guard,
state,
);
self.set_reg(return_register, JsValue::Object(gen_obj));
Ok(None)
}
JsFunction::BytecodeAsync(bc_func) => {
// Async functions run their body and wrap result in Promise.
// Use trampoline to run the body - the is_async flag causes the result
// to be wrapped in a Promise when the frame is popped.
self.push_trampoline_frame_and_call_bytecode(
interp,
func_obj.cheap_clone(),
bc_func,
this_value,
args,
return_register,
new_target,
true, // is_async - wrap result in Promise
is_super_call, // pass through super call flag
)?;
Ok(None)
}
// For all other function types, fall back to the interpreter's call_function
// This includes PromiseResolve, PromiseReject, PromiseAllFulfill, AccessorGetter, etc.
_ => {
let result =
interp.call_function_with_new_target(callee, this_value, &args, new_target)?;
self.set_reg(return_register, result.value);
Ok(None)
}
}
}
/// Set up a trampoline construct call - save current state and switch to the constructor
/// This is similar to setup_trampoline_call but stores the new_obj in the frame
/// so that if the constructor doesn't return an object, we can use the new_obj
#[allow(clippy::too_many_arguments)]
fn setup_trampoline_construct(
&mut self,
interp: &mut Interpreter,
callee: JsValue,
this_value: JsValue,
args: Vec<JsValue>,
return_register: Register,
new_target: JsValue,
new_obj: Gc<JsObject>,
) -> Result<(), JsError> {
use crate::value::{ExoticObject, JsFunction};
let JsValue::Object(func_obj) = &callee else {
return Err(JsError::type_error("Not a constructor"));
};
let func = {
let obj_ref = func_obj.borrow();
match &obj_ref.exotic {
ExoticObject::Function(f) => f.clone(),
_ => return Err(JsError::type_error("Not a constructor")),
}
};
match func {
JsFunction::Bytecode(bc_func) => {
// This is what we want to trampoline!
self.push_trampoline_frame_and_call_bytecode_construct(
interp,
func_obj.cheap_clone(),
bc_func,
this_value,
args,
return_register,
new_target,
new_obj,
)?;
Ok(())
}
JsFunction::Bound(bound) => {
// Unwrap bound function and trampoline to target
let target = JsValue::Object(bound.target.cheap_clone());
let mut full_args = bound.bound_args.clone();
full_args.extend(args);
self.setup_trampoline_construct(
interp,
target,
this_value,
full_args,
return_register,
new_target,
new_obj,
)
}
// For all other function types, fall back to the interpreter's call_function
// and handle the object/non-object return value
_ => {
let result =
interp.call_function_with_new_target(callee, this_value, &args, new_target)?;
// If constructor returned an object, use that; otherwise use the new_obj
let final_val = match result.value {
JsValue::Object(obj) => JsValue::Object(obj),
_ => JsValue::Object(new_obj),
};
self.set_reg(return_register, final_val);
Ok(())
}
}
}
/// Push current state onto trampoline stack and set up for bytecode function call
/// If is_async is true, the result will be wrapped in a Promise when the frame is popped
#[allow(clippy::too_many_arguments)]
fn push_trampoline_frame_and_call_bytecode(
&mut self,
interp: &mut Interpreter,
func_obj: Gc<JsObject>,
bc_func: BytecodeFunction,
this_value: JsValue,
args: Vec<JsValue>,
return_register: Register,
new_target: JsValue,
is_async: bool,
is_super_call: bool,
) -> Result<(), JsError> {
use crate::interpreter::{Binding, VarKey, create_environment_unrooted_with_capacity};
// Get function info from the chunk
let func_info = bc_func.chunk.function_info.as_ref();
// Push call stack frame for stack traces
let func_name = func_info
.and_then(|info| info.name.as_ref())
.map(|s| s.to_string())
.unwrap_or_else(|| "<anonymous>".to_string());
interp.call_stack.push(crate::interpreter::StackFrame {
function_name: func_name,
location: None,
});
// Calculate environment capacity: params + this + potential arguments + some slack
// Use binding_count if available, otherwise estimate from param_count
let env_capacity = func_info
.map(|info| {
if info.binding_count > 0 {
info.binding_count
} else {
// Estimate: params + this + arguments + a few locals
info.param_count + 4
}
})
.unwrap_or(8);
// Create new environment for the function, with closure as parent
let (func_env, func_guard) = create_environment_unrooted_with_capacity(
&interp.heap,
Some(bc_func.closure.cheap_clone()),
env_capacity,
);
// Bind `this` in the function environment
let effective_this = if let Some(captured) = bc_func.captured_this {
*captured
} else {
this_value.clone()
};
{
let this_name = interp.intern("this");
if let Some(data) = func_env.borrow_mut().as_environment_mut() {
data.bindings.insert(
VarKey(this_name),
Binding {
value: effective_this.clone(),
mutable: false,
initialized: true,
import_binding: None,
},
);
}
}
// Bind `__super__` if this function has it (for class methods with super)
{
let super_name = interp.intern("__super__");
let super_key = PropertyKey::String(super_name.cheap_clone());
if let Some(super_val) = func_obj.borrow().get_property(&super_key)
&& let Some(data) = func_env.borrow_mut().as_environment_mut()
{
data.bindings.insert(
VarKey(super_name),
Binding {
value: super_val,
mutable: false,
initialized: true,
import_binding: None,
},
);
}
}
// Bind `__super_target__` for super.x property access
{
let super_target_name = interp.intern("__super_target__");
let super_target_key = PropertyKey::String(super_target_name.cheap_clone());
if let Some(super_target_val) = func_obj.borrow().get_property(&super_target_key)
&& let Some(data) = func_env.borrow_mut().as_environment_mut()
{
data.bindings.insert(
VarKey(super_target_name),
Binding {
value: super_target_val,
mutable: false,
initialized: true,
import_binding: None,
},
);
}
}
// Save current interpreter environment
let saved_interp_env = interp.env.cheap_clone();
interp.env = func_env;
interp.push_env_guard(func_guard);
// Handle rest parameters - separate args for registers vs arguments object
let new_guard = interp.heap.create_guard();
let (processed_args, new_arguments): (Option<Vec<JsValue>>, Vec<JsValue>) =
if let Some(rest_idx) = func_info.and_then(|info| info.rest_param) {
// Rest param case: create processed version for registers
let mut result_args = Vec::with_capacity(rest_idx + 1);
for i in 0..rest_idx {
result_args.push(args.get(i).cloned().unwrap_or(JsValue::Undefined));
}
let rest_elements: Vec<JsValue> = args.get(rest_idx..).unwrap_or_default().to_vec();
let rest_array = interp.create_array_from(&new_guard, rest_elements);
result_args.push(JsValue::Object(rest_array));
(Some(result_args), args)
} else {
// No rest params: use args directly (no clone needed!)
(None, args)
};
// Use processed args for registers if available, otherwise use original args
let register_args = processed_args.as_ref().unwrap_or(&new_arguments);
// Guard all values for the new frame
if let JsValue::Object(obj) = &effective_this {
new_guard.guard(obj.cheap_clone());
}
if let JsValue::Object(obj) = &new_target {
new_guard.guard(obj.cheap_clone());
}
for arg in register_args {
if let JsValue::Object(obj) = arg {
new_guard.guard(obj.cheap_clone());
}
}
// Create the new register file for the called function (from pool if available)
let register_count = bc_func.chunk.register_count as usize;
let mut new_registers = self.acquire_registers(register_count);
for (i, arg) in register_args.iter().enumerate() {
if i < new_registers.len()
&& let Some(slot) = new_registers.get_mut(i)
{
*slot = arg.clone();
}
}
// Save current VM state to trampoline stack
let old_guard = mem::replace(&mut self.register_guard, new_guard);
// new_arguments already set from rest parameter handling above - no extra allocation needed
let frame = TrampolineFrame {
ip: self.ip,
chunk: self.chunk.cheap_clone(),
registers: mem::replace(&mut self.registers, new_registers),
this_value: mem::replace(&mut self.this_value, effective_this),
vm_call_stack: mem::take(&mut self.call_stack),
try_stack: mem::take(&mut self.try_stack),
exception_value: self.exception_value.take(),
saved_env_stack: mem::take(&mut self.saved_env_stack),
arguments: mem::replace(&mut self.arguments, new_arguments),
new_target: mem::replace(&mut self.new_target, new_target),
current_constructor: self.current_constructor.take(),
pending_completion: self.pending_completion.take(),
return_register,
saved_interp_env,
register_guard: old_guard,
construct_new_obj: None,
is_async,
};
self.trampoline_stack.push(frame);
// For super() calls, set the current constructor so super() lookups work correctly
if is_super_call {
self.current_constructor = Some(func_obj);
}
// Set up VM for the called function
self.ip = 0;
self.chunk = bc_func.chunk;
Ok(())
}
/// Execute a tail call with frame reuse for bytecode functions.
/// For non-bytecode callees (native, proxy, etc.), falls back to regular call behavior.
fn execute_tail_call(
&mut self,
interp: &mut Interpreter,
callee: JsValue,
this_value: JsValue,
args: Vec<JsValue>,
) -> Result<OpResult, JsError> {
use crate::value::{
BoundFunctionData, BytecodeFunction, ExoticObject, JsFunction, NativeFunction,
};
let func_obj = match &callee {
JsValue::Object(obj) => obj.cheap_clone(),
_ => return Err(JsError::type_error("Not a function")),
};
// Check if this is a bytecode function - only those can be tail-call optimized
// We need to get the function type before matching to avoid borrow issues
enum FuncType {
Bytecode(BytecodeFunction),
Native(NativeFunction),
Bound(Box<BoundFunctionData>),
FallbackToCall, // For proxy, generators, async, etc.
NotAFunction,
}
let func_type = {
let obj_ref = func_obj.borrow();
match &obj_ref.exotic {
ExoticObject::Function(f) => match f {
JsFunction::Bytecode(bc) => FuncType::Bytecode(bc.clone()),
JsFunction::Native(n) => FuncType::Native(n.clone()),
JsFunction::Bound(b) => FuncType::Bound(b.clone()),
_ => FuncType::FallbackToCall,
},
ExoticObject::Proxy(_) => FuncType::FallbackToCall,
_ => FuncType::NotAFunction,
}
};
match func_type {
FuncType::Bytecode(bc_func) => {
// Tail call optimization: replace current frame with called function
self.tail_call_bytecode(interp, func_obj, bc_func, this_value, args)?;
Ok(OpResult::Continue)
}
FuncType::Native(native) => {
// Native functions: call directly and store result
// The following Return instruction will return this value
let prev_ffi_id = interp.current_ffi_id;
interp.current_ffi_id = native.ffi_id;
let result = (native.func)(interp, this_value, &args);
interp.current_ffi_id = prev_ffi_id;
let result = result?;
// For native tail calls, store result in register 0 (Return will read it)
// Note: This register may not be the actual return_register from the TailCall
// instruction, but since TailCall doesn't have a dst, we use the VM's return path
if let JsValue::Object(obj) = &result.value {
self.register_guard.guard(obj.cheap_clone());
}
// Return OpResult::Halt with the result - the caller's Return instruction
// is never reached, and this value is returned directly
Ok(OpResult::Halt(result))
}
FuncType::Bound(bound) => {
// Unwrap bound function and recurse
let target = JsValue::Object(bound.target.cheap_clone());
let bound_this = bound.this_arg.clone();
let mut full_args = bound.bound_args.clone();
full_args.extend(args);
self.execute_tail_call(interp, target, bound_this, full_args)
}
FuncType::FallbackToCall => {
// Fall back to regular call for proxies, generators, async, etc.
let guard = interp.heap.create_guard();
callee.guard_by(&guard);
this_value.guard_by(&guard);
for arg in &args {
arg.guard_by(&guard);
}
Ok(OpResult::Call {
callee,
this_value,
args,
return_register: 0,
new_target: JsValue::Undefined,
is_super_call: false,
guard,
})
}
FuncType::NotAFunction => Err(JsError::type_error("Not a function")),
}
}
/// Execute an async tail call for `return await fn()` pattern.
/// Similar to execute_tail_call but for async functions.
/// The dst register is used when falling back to non-optimized path (native functions).
fn execute_async_tail_call(
&mut self,
interp: &mut Interpreter,
callee: JsValue,
this_value: JsValue,
args: Vec<JsValue>,
dst: Register,
) -> Result<OpResult, JsError> {
use crate::value::{
BoundFunctionData, BytecodeFunction, ExoticObject, JsFunction, NativeFunction,
};
let func_obj = match &callee {
JsValue::Object(obj) => obj.cheap_clone(),
_ => return Err(JsError::type_error("Not a function")),
};
enum FuncType {
Bytecode(BytecodeFunction),
BytecodeAsync(BytecodeFunction),
Native(NativeFunction),
Bound(Box<BoundFunctionData>),
FallbackToCall,
NotAFunction,
}
let func_type = {
let obj_ref = func_obj.borrow();
match &obj_ref.exotic {
ExoticObject::Function(f) => match f {
JsFunction::Bytecode(bc) => FuncType::Bytecode(bc.clone()),
JsFunction::BytecodeAsync(bc) => FuncType::BytecodeAsync(bc.clone()),
JsFunction::Native(n) => FuncType::Native(n.clone()),
JsFunction::Bound(b) => FuncType::Bound(b.clone()),
_ => FuncType::FallbackToCall,
},
ExoticObject::Proxy(_) => FuncType::FallbackToCall,
_ => FuncType::NotAFunction,
}
};
match func_type {
FuncType::Bytecode(bc_func) | FuncType::BytecodeAsync(bc_func) => {
// Async tail call optimization: replace current frame with called function
// For async functions (BytecodeAsync), we extract the bytecode and run it
// in the current frame. The is_async flag from the original trampoline frame
// ensures the final result is promise-wrapped correctly.
self.tail_call_bytecode(interp, func_obj, bc_func, this_value, args)?;
Ok(OpResult::Continue)
}
FuncType::Native(native) => {
// For native functions, we can't tail-call optimize by reusing the frame,
// but we can still call directly and handle the result here.
// This avoids an extra frame push for the call.
use crate::value::{ExoticObject, PromiseStatus};
let prev_ffi_id = interp.current_ffi_id;
interp.current_ffi_id = native.ffi_id;
let result = (native.func)(interp, this_value, &args);
interp.current_ffi_id = prev_ffi_id;
let result = result?;
// Now we need to "await" the result - handle PendingOrder, Promise, and plain values
let result_val = result.value;
if let JsValue::Object(obj) = &result_val {
let obj_ref = obj.borrow();
// Check for PendingOrder - suspend for host response
if let ExoticObject::PendingOrder { id, .. } = &obj_ref.exotic {
let order_id = crate::OrderId(*id);
drop(obj_ref);
// When suspended, the result will be stored in dst register
// and the Return instruction will return it
return Ok(OpResult::SuspendForOrder {
order_id,
resume_register: dst,
});
}
// Check for Promise
if let ExoticObject::Promise(state) = &obj_ref.exotic {
let state_ref = state.borrow();
match state_ref.status {
PromiseStatus::Fulfilled => {
// Extract the resolved value, store in dst, and continue
let val = state_ref.result.clone().unwrap_or(JsValue::Undefined);
drop(state_ref);
drop(obj_ref);
self.set_reg(dst, val);
return Ok(OpResult::Continue);
}
PromiseStatus::Rejected => {
// Throw the rejection reason
let reason = state_ref.result.clone().unwrap_or(JsValue::Undefined);
drop(state_ref);
drop(obj_ref);
let guarded = Guarded::from_value(reason, &interp.heap);
return Err(JsError::thrown(guarded));
}
PromiseStatus::Pending => {
// Suspend and wait for promise resolution
drop(state_ref);
drop(obj_ref);
return Ok(OpResult::Suspend {
promise: Guarded::from_value(result_val, &interp.heap),
resume_register: dst,
});
}
}
}
}
// Plain value - store in dst and continue to Return instruction
self.set_reg(dst, result_val);
Ok(OpResult::Continue)
}
FuncType::Bound(bound) => {
// Unwrap bound function and recurse
let target = JsValue::Object(bound.target.cheap_clone());
let bound_this = bound.this_arg.clone();
let mut full_args = bound.bound_args.clone();
full_args.extend(args);
self.execute_async_tail_call(interp, target, bound_this, full_args, dst)
}
FuncType::FallbackToCall => {
// Fall back to regular call for proxies, generators, etc.
// Note: This won't properly await the result since there's no Await instruction
// after TailCallAwait. For proxies and generators, consider using regular
// call + await pattern in the source code.
let guard = interp.heap.create_guard();
callee.guard_by(&guard);
this_value.guard_by(&guard);
for arg in &args {
arg.guard_by(&guard);
}
Ok(OpResult::Call {
callee,
this_value,
args,
return_register: dst,
new_target: JsValue::Undefined,
is_super_call: false,
guard,
})
}
FuncType::NotAFunction => Err(JsError::type_error("Not a function")),
}
}
/// Perform a tail call to a bytecode function by reusing the current frame.
/// This replaces the current VM state without pushing to trampoline_stack.
fn tail_call_bytecode(
&mut self,
interp: &mut Interpreter,
func_obj: Gc<JsObject>,
bc_func: BytecodeFunction,
this_value: JsValue,
args: Vec<JsValue>,
) -> Result<(), JsError> {
use crate::interpreter::{Binding, VarKey, create_environment_unrooted_with_capacity};
// Get function info from the chunk
let func_info = bc_func.chunk.function_info.as_ref();
// Update call stack for stack traces (replace current entry, not push)
let func_name = func_info
.and_then(|info| info.name.as_ref())
.map(|s| s.to_string())
.unwrap_or_else(|| "<anonymous>".to_string());
// Replace the current stack frame instead of pushing a new one
if let Some(frame) = interp.call_stack.last_mut() {
frame.function_name = func_name;
frame.location = None;
}
// Pop current function's environment
interp.pop_env_guard();
// Calculate environment capacity
let env_capacity = func_info
.map(|info| {
if info.binding_count > 0 {
info.binding_count
} else {
info.param_count + 4
}
})
.unwrap_or(8);
// Create new environment for the called function
let (func_env, func_guard) = create_environment_unrooted_with_capacity(
&interp.heap,
Some(bc_func.closure.cheap_clone()),
env_capacity,
);
// Bind `this` in the function environment
let effective_this = if let Some(captured) = bc_func.captured_this {
*captured
} else {
this_value.clone()
};
{
let this_name = interp.intern("this");
if let Some(data) = func_env.borrow_mut().as_environment_mut() {
data.bindings.insert(
VarKey(this_name),
Binding {
value: effective_this.clone(),
mutable: false,
initialized: true,
import_binding: None,
},
);
}
}
// Bind `__super__` if present
{
let super_name = interp.intern("__super__");
let super_key = PropertyKey::String(super_name.cheap_clone());
if let Some(super_val) = func_obj.borrow().get_property(&super_key)
&& let Some(data) = func_env.borrow_mut().as_environment_mut()
{
data.bindings.insert(
VarKey(super_name),
Binding {
value: super_val,
mutable: false,
initialized: true,
import_binding: None,
},
);
}
}
// Bind `__super_target__` if present
{
let super_target_name = interp.intern("__super_target__");
let super_target_key = PropertyKey::String(super_target_name.cheap_clone());
if let Some(super_target_val) = func_obj.borrow().get_property(&super_target_key)
&& let Some(data) = func_env.borrow_mut().as_environment_mut()
{
data.bindings.insert(
VarKey(super_target_name),
Binding {
value: super_target_val,
mutable: false,
initialized: true,
import_binding: None,
},
);
}
}
// Set up new interpreter environment
interp.env = func_env;
interp.push_env_guard(func_guard);
// Handle rest parameters
let new_guard = interp.heap.create_guard();
let (processed_args, new_arguments): (Option<Vec<JsValue>>, Vec<JsValue>) =
if let Some(rest_idx) = func_info.and_then(|info| info.rest_param) {
let mut result_args = Vec::with_capacity(rest_idx + 1);
for i in 0..rest_idx {
result_args.push(args.get(i).cloned().unwrap_or(JsValue::Undefined));
}
let rest_elements: Vec<JsValue> = args.get(rest_idx..).unwrap_or_default().to_vec();
let rest_array = interp.create_array_from(&new_guard, rest_elements);
result_args.push(JsValue::Object(rest_array));
(Some(result_args), args)
} else {
(None, args)
};
let register_args = processed_args.as_ref().unwrap_or(&new_arguments);
// Guard all values
if let JsValue::Object(obj) = &effective_this {
new_guard.guard(obj.cheap_clone());
}
for arg in register_args {
if let JsValue::Object(obj) = arg {
new_guard.guard(obj.cheap_clone());
}
}
// Release old registers and arguments back to pool
let old_registers = mem::take(&mut self.registers);
self.release_registers(old_registers);
let old_arguments = mem::take(&mut self.arguments);
self.release_arguments(old_arguments);
// Create new register file
let register_count = bc_func.chunk.register_count as usize;
let mut new_registers = self.acquire_registers(register_count);
for (i, arg) in register_args.iter().enumerate() {
if i < new_registers.len()
&& let Some(slot) = new_registers.get_mut(i)
{
*slot = arg.clone();
}
}
// Update VM state (no trampoline push!)
self.register_guard = new_guard;
self.registers = new_registers;
self.this_value = effective_this;
self.arguments = new_arguments;
self.new_target = JsValue::Undefined;
self.ip = 0;
self.chunk = bc_func.chunk;
// Clear state that shouldn't carry over
self.call_stack.clear();
self.try_stack.clear();
self.exception_value = None;
self.saved_env_stack.clear();
self.current_constructor = None;
self.pending_completion = None;
Ok(())
}
/// Push current state onto trampoline stack for a construct call
/// This is like push_trampoline_frame_and_call_bytecode but stores the new_obj
/// in the frame so it can be used if the constructor doesn't return an object
#[allow(clippy::too_many_arguments)]
fn push_trampoline_frame_and_call_bytecode_construct(
&mut self,
interp: &mut Interpreter,
func_obj: Gc<JsObject>,
bc_func: BytecodeFunction,
this_value: JsValue,
args: Vec<JsValue>,
return_register: Register,
new_target: JsValue,
construct_new_obj: Gc<JsObject>,
) -> Result<(), JsError> {
use crate::interpreter::{Binding, VarKey, create_environment_unrooted_with_capacity};
// Get function info from the chunk
let func_info = bc_func.chunk.function_info.as_ref();
// Push call stack frame for stack traces
let func_name = func_info
.and_then(|info| info.name.as_ref())
.map(|s| s.to_string())
.unwrap_or_else(|| "<anonymous>".to_string());
interp.call_stack.push(crate::interpreter::StackFrame {
function_name: func_name,
location: None,
});
// Calculate environment capacity: params + this + potential arguments + some slack
// Use binding_count if available, otherwise estimate from param_count
let env_capacity = func_info
.map(|info| {
if info.binding_count > 0 {
info.binding_count
} else {
// Estimate: params + this + arguments + a few locals
info.param_count + 4
}
})
.unwrap_or(8);
// Create new environment for the function, with closure as parent
let (func_env, func_guard) = create_environment_unrooted_with_capacity(
&interp.heap,
Some(bc_func.closure.cheap_clone()),
env_capacity,
);
// Bind `this` in the function environment
let effective_this = if let Some(captured) = bc_func.captured_this {
*captured
} else {
this_value.clone()
};
{
let this_name = interp.intern("this");
if let Some(data) = func_env.borrow_mut().as_environment_mut() {
data.bindings.insert(
VarKey(this_name),
Binding {
value: effective_this.clone(),
mutable: false,
initialized: true,
import_binding: None,
},
);
}
}
// Bind `__super__` if this function has it (for class methods with super)
{
let super_name = interp.intern("__super__");
let super_key = PropertyKey::String(super_name.cheap_clone());
if let Some(super_val) = func_obj.borrow().get_property(&super_key)
&& let Some(data) = func_env.borrow_mut().as_environment_mut()
{
data.bindings.insert(
VarKey(super_name),
Binding {
value: super_val,
mutable: false,
initialized: true,
import_binding: None,
},
);
}
}
// Bind `__super_target__` for super.x property access
{
let super_target_name = interp.intern("__super_target__");
let super_target_key = PropertyKey::String(super_target_name.cheap_clone());
if let Some(super_target_val) = func_obj.borrow().get_property(&super_target_key)
&& let Some(data) = func_env.borrow_mut().as_environment_mut()
{
data.bindings.insert(
VarKey(super_target_name),
Binding {
value: super_target_val,
mutable: false,
initialized: true,
import_binding: None,
},
);
}
}
// Save current interpreter environment
let saved_interp_env = interp.env.cheap_clone();
interp.env = func_env;
interp.push_env_guard(func_guard);
// Handle rest parameters - separate args for registers vs arguments object
let new_guard = interp.heap.create_guard();
let (processed_args, new_arguments): (Option<Vec<JsValue>>, Vec<JsValue>) =
if let Some(rest_idx) = func_info.and_then(|info| info.rest_param) {
// Rest param case: create processed version for registers
let mut result_args = Vec::with_capacity(rest_idx + 1);
for i in 0..rest_idx {
result_args.push(args.get(i).cloned().unwrap_or(JsValue::Undefined));
}
let rest_elements: Vec<JsValue> = args.get(rest_idx..).unwrap_or_default().to_vec();
let rest_array = interp.create_array_from(&new_guard, rest_elements);
result_args.push(JsValue::Object(rest_array));
(Some(result_args), args)
} else {
// No rest params: use args directly (no clone needed!)
(None, args)
};
// Use processed args for registers if available, otherwise use original args
let register_args = processed_args.as_ref().unwrap_or(&new_arguments);
// Guard all values for the new frame
if let JsValue::Object(obj) = &effective_this {
new_guard.guard(obj.cheap_clone());
}
if let JsValue::Object(obj) = &new_target {
new_guard.guard(obj.cheap_clone());
}
for arg in register_args {
if let JsValue::Object(obj) = arg {
new_guard.guard(obj.cheap_clone());
}
}
// Also guard the construct_new_obj
new_guard.guard(construct_new_obj.cheap_clone());
// Create the new register file for the called function (from pool if available)
let register_count = bc_func.chunk.register_count as usize;
let mut new_registers = self.acquire_registers(register_count);
for (i, arg) in register_args.iter().enumerate() {
if i < new_registers.len()
&& let Some(slot) = new_registers.get_mut(i)
{
*slot = arg.clone();
}
}
// Save current VM state to trampoline stack
let old_guard = mem::replace(&mut self.register_guard, new_guard);
// new_arguments already set from rest parameter handling above - no extra allocation needed
let frame = TrampolineFrame {
ip: self.ip,
chunk: self.chunk.cheap_clone(),
registers: mem::replace(&mut self.registers, new_registers),
this_value: mem::replace(&mut self.this_value, effective_this),
vm_call_stack: mem::take(&mut self.call_stack),
try_stack: mem::take(&mut self.try_stack),
exception_value: self.exception_value.take(),
saved_env_stack: mem::take(&mut self.saved_env_stack),
arguments: mem::replace(&mut self.arguments, new_arguments),
new_target: mem::replace(&mut self.new_target, new_target),
current_constructor: self.current_constructor.take(),
pending_completion: self.pending_completion.take(),
return_register,
saved_interp_env,
register_guard: old_guard,
construct_new_obj: Some(construct_new_obj),
is_async: false, // Construct calls are never async
};
self.trampoline_stack.push(frame);
// Set up the current constructor for super() lookups
self.current_constructor = Some(func_obj);
// Set up VM for the called function
self.ip = 0;
self.chunk = bc_func.chunk;
Ok(())
}
/// Restore VM state from a trampoline frame after a function returns
fn restore_from_trampoline_frame(
&mut self,
interp: &mut Interpreter,
frame: TrampolineFrame,
return_value: JsValue,
) {
// Release current registers back to pool before restoring
let current_registers = mem::take(&mut self.registers);
self.release_registers(current_registers);
// Release current arguments back to pool before restoring
let current_arguments = mem::take(&mut self.arguments);
self.release_arguments(current_arguments);
// Restore VM state
self.ip = frame.ip;
self.chunk = frame.chunk;
self.registers = frame.registers;
self.register_guard = frame.register_guard;
self.this_value = frame.this_value;
self.call_stack = frame.vm_call_stack;
self.try_stack = frame.try_stack;
self.exception_value = frame.exception_value;
self.saved_env_stack = frame.saved_env_stack;
self.arguments = frame.arguments;
self.new_target = frame.new_target;
self.current_constructor = frame.current_constructor;
self.pending_completion = frame.pending_completion;
// Restore interpreter environment
interp.pop_env_guard();
interp.env = frame.saved_interp_env;
interp.call_stack.pop();
// For construct calls: if constructor didn't return an object, use the new object
let intermediate_value = if let Some(new_obj) = frame.construct_new_obj {
match return_value {
JsValue::Object(obj) => JsValue::Object(obj),
_ => JsValue::Object(new_obj),
}
} else {
return_value
};
// For async calls: wrap result in a Promise
let final_value = if frame.is_async {
use crate::value::ExoticObject;
// Promise assimilation: if result is already a Promise, return it directly
if let JsValue::Object(obj) = &intermediate_value {
if matches!(obj.borrow().exotic, ExoticObject::Promise(_)) {
intermediate_value
} else {
// Wrap non-Promise value in a fulfilled Promise
let promise = super::builtins::promise::create_fulfilled_promise(
interp,
&self.register_guard,
intermediate_value,
);
JsValue::Object(promise)
}
} else {
// Wrap primitive value in a fulfilled Promise
let promise = super::builtins::promise::create_fulfilled_promise(
interp,
&self.register_guard,
intermediate_value,
);
JsValue::Object(promise)
}
} else {
intermediate_value
};
// Store return value in the designated register
// Guard it with the restored frame's guard
if let JsValue::Object(obj) = &final_value {
self.register_guard.guard(obj.cheap_clone());
}
self.set_reg(frame.return_register, final_value);
}
/// Convert an error to a guarded JS value (takes ownership to avoid re-guarding)
fn error_to_guarded(&self, interp: &mut Interpreter, error: JsError) -> Guarded {
match error {
JsError::ThrownValue { guarded } => guarded,
other => {
// Create an error object using the proper error type
use crate::interpreter::builtins::error::create_error_object;
let (value, guard) = create_error_object(interp, &other);
Guarded { value, guard }
}
}
}
/// Find an exception handler for the current position.
/// Returns `Some((handler_ip, is_catch))` where:
/// - `is_catch = true`: handler_ip is a catch block (store error in exception_value)
/// - `is_catch = false`: handler_ip is a finally-only block (store error in pending_completion)
fn find_exception_handler(&mut self, interp: &mut Interpreter) -> Option<(usize, bool)> {
while let Some(handler) = self.try_stack.pop() {
// Unwind to this handler's frame depth
while self.call_stack.len() > handler.frame_depth {
self.call_stack.pop();
}
if handler.catch_ip > 0 {
// If there's also a finally, push a handler for it
// so break/continue in catch will still run finally
if handler.finally_ip > 0 {
self.try_stack.push(TryHandler {
catch_ip: 0, // Clear catch so it won't re-catch
finally_ip: handler.finally_ip,
registers_snapshot: handler.registers_snapshot,
frame_depth: handler.frame_depth,
scope_depth: handler.scope_depth,
iterator_reg: handler.iterator_reg,
});
}
// Unwind any scopes that were entered in the try block
// This is like executing PopScope for each scope that was entered
while self.saved_env_stack.len() > handler.scope_depth {
if let Some(saved_env) = self.saved_env_stack.pop() {
interp.pop_scope(saved_env);
}
}
return Some((handler.catch_ip, true));
}
if handler.finally_ip > 0 {
// Also unwind scopes for finally handlers
while self.saved_env_stack.len() > handler.scope_depth {
if let Some(saved_env) = self.saved_env_stack.pop() {
interp.pop_scope(saved_env);
}
}
return Some((handler.finally_ip, false));
}
}
None
}
/// Handle an error, including unwinding the trampoline stack to find handlers.
/// Returns Ok(()) if a handler was found and execution should continue,
/// or Err(e) if no handler was found (caller should return the error).
fn handle_error_with_trampoline_unwind(
&mut self,
interp: &mut Interpreter,
e: JsError,
) -> Result<(), JsError> {
// Capture stack trace BEFORE unwinding the trampoline stack
// This gives us the full call stack at the point of error
let wrapped_error = self.wrap_error_with_trace(e);
// First check for handler in current frame
if let Some((handler_ip, is_catch)) = self.find_exception_handler(interp) {
self.ip = handler_ip;
let guarded = self.error_to_guarded(interp, wrapped_error);
if is_catch {
// Catch handler: store in exception_value for GetException opcode
self.exception_value = Some(guarded);
} else {
// Finally-only handler: store in pending_completion for FinallyEnd to rethrow
self.pending_completion = Some(PendingCompletion::Throw(guarded));
}
return Ok(());
}
// Unwind trampoline stack to find a handler in parent frames
while let Some(frame) = self.trampoline_stack.pop() {
let is_async_frame = frame.is_async;
let return_register = frame.return_register;
// Release current registers back to pool before restoring
let current_registers = mem::take(&mut self.registers);
self.release_registers(current_registers);
// Release current arguments back to pool before restoring
let current_arguments = mem::take(&mut self.arguments);
self.release_arguments(current_arguments);
// Unwind current frame's scopes before restoring - if the called function
// had any scopes pushed (e.g., from PushScope in its body), we need to pop
// them and their guards before switching to the caller's saved_env_stack
while let Some(saved_env) = self.saved_env_stack.pop() {
interp.pop_scope(saved_env);
}
// Restore state from frame
self.ip = frame.ip;
self.chunk = frame.chunk;
self.registers = frame.registers;
self.register_guard = frame.register_guard;
self.this_value = frame.this_value;
self.call_stack = frame.vm_call_stack;
self.try_stack = frame.try_stack;
self.exception_value = frame.exception_value;
self.saved_env_stack = frame.saved_env_stack;
self.arguments = frame.arguments;
self.new_target = frame.new_target;
self.pending_completion = frame.pending_completion;
// Restore interpreter environment
interp.pop_env_guard();
interp.env = frame.saved_interp_env;
interp.call_stack.pop();
// For async frames: convert error to rejected Promise instead of propagating
if is_async_frame {
let error_guarded = self.error_to_guarded(interp, wrapped_error);
let promise = super::builtins::promise::create_rejected_promise(
interp,
&self.register_guard,
error_guarded.value,
);
// error_guarded.guard keeps the reason alive until promise is created
drop(error_guarded.guard);
self.register_guard.guard(promise.cheap_clone());
self.set_reg(return_register, JsValue::Object(promise));
return Ok(());
}
// Check for exception handler in this frame
if let Some((handler_ip, is_catch)) = self.find_exception_handler(interp) {
self.ip = handler_ip;
let guarded = self.error_to_guarded(interp, wrapped_error);
if is_catch {
self.exception_value = Some(guarded);
} else {
self.pending_completion = Some(PendingCompletion::Throw(guarded));
}
return Ok(());
}
}
// No handler found - return the error back to caller with stack trace
Err(wrapped_error)
}
/// Save VM state for suspension
/// Creates a guard to keep all objects in registers alive during suspension
fn save_state(&self, interp: &Interpreter) -> SavedVmState {
let guard = interp.heap.create_guard();
// Guard all objects in registers
for val in &self.registers {
if let JsValue::Object(obj) = val {
guard.guard(obj.cheap_clone());
}
}
// Guard saved environments in call frames
for frame in &self.call_stack {
if let Some(ref env) = frame.saved_env {
guard.guard(env.cheap_clone());
}
}
// Guard this_value if it's an object
if let JsValue::Object(obj) = &self.this_value {
guard.guard(obj.cheap_clone());
}
// Guard exception_value if it's an object
// (exception_value is already Guarded, but we also add it to the saved state guard
// for consistency when the saved state is restored)
if let Some(Guarded {
value: JsValue::Object(obj),
..
}) = &self.exception_value
{
guard.guard(obj.cheap_clone());
}
// Guard saved_env_stack entries
for env in &self.saved_env_stack {
guard.guard(env.cheap_clone());
}
// Guard all objects in trampoline stack and convert to SavedTrampolineFrame
let saved_trampoline_stack: Vec<SavedTrampolineFrame> = self
.trampoline_stack
.iter()
.map(|frame| {
// Guard all objects in this frame
for val in &frame.registers {
if let JsValue::Object(obj) = val {
guard.guard(obj.cheap_clone());
}
}
if let JsValue::Object(obj) = &frame.this_value {
guard.guard(obj.cheap_clone());
}
for env in &frame.saved_env_stack {
guard.guard(env.cheap_clone());
}
guard.guard(frame.saved_interp_env.cheap_clone());
if let Some(ref ctor) = frame.current_constructor {
guard.guard(ctor.cheap_clone());
}
if let Some(ref obj) = frame.construct_new_obj {
guard.guard(obj.cheap_clone());
}
SavedTrampolineFrame {
ip: frame.ip,
chunk: frame.chunk.clone(),
registers: frame.registers.clone(),
this_value: frame.this_value.clone(),
vm_call_stack: frame.vm_call_stack.clone(),
try_stack: frame.try_stack.clone(),
saved_env_stack: frame.saved_env_stack.clone(),
arguments: frame.arguments.clone(),
new_target: frame.new_target.clone(),
current_constructor: frame.current_constructor.clone(),
return_register: frame.return_register,
saved_interp_env: frame.saved_interp_env.cheap_clone(),
construct_new_obj: frame.construct_new_obj.clone(),
is_async: frame.is_async,
}
})
.collect();
SavedVmState {
frames: self.call_stack.clone(),
ip: self.ip,
chunk: self.chunk.clone(),
registers: self.registers.clone(),
try_stack: self.try_stack.clone(),
guard: Some(guard),
arguments: self.arguments.clone(),
new_target: self.new_target.clone(),
trampoline_stack: saved_trampoline_stack,
}
}
/// Create a new VM from saved state (for generator resumption)
/// The guard must protect all objects in the saved registers
pub fn from_saved_state(
state: SavedVmState,
this_value: JsValue,
guard: Guard<JsObject>,
heap: &crate::gc::Heap<JsObject>,
) -> Self {
// Guard this_value if it's an object
if let JsValue::Object(obj) = &this_value {
guard.guard(obj.cheap_clone());
}
// Guard all objects in the restored registers
for val in &state.registers {
if let JsValue::Object(obj) = val {
guard.guard(obj.cheap_clone());
}
}
// Guard saved environments in call frames
for frame in &state.frames {
if let Some(ref env) = frame.saved_env {
guard.guard(env.cheap_clone());
}
}
// Guard all objects in trampoline stack
for frame in &state.trampoline_stack {
for val in &frame.registers {
if let JsValue::Object(obj) = val {
guard.guard(obj.cheap_clone());
}
}
if let JsValue::Object(obj) = &frame.this_value {
guard.guard(obj.cheap_clone());
}
for env in &frame.saved_env_stack {
guard.guard(env.cheap_clone());
}
guard.guard(frame.saved_interp_env.cheap_clone());
if let Some(ref ctor) = frame.current_constructor {
guard.guard(ctor.cheap_clone());
}
}
// Convert SavedTrampolineFrame back to TrampolineFrame with new guards
let trampoline_stack: Vec<TrampolineFrame> = state
.trampoline_stack
.into_iter()
.map(|saved| {
let frame_guard = heap.create_guard();
// Guard all objects in this frame
for val in &saved.registers {
if let JsValue::Object(obj) = val {
frame_guard.guard(obj.cheap_clone());
}
}
TrampolineFrame {
ip: saved.ip,
chunk: saved.chunk,
registers: saved.registers,
this_value: saved.this_value,
vm_call_stack: saved.vm_call_stack,
try_stack: saved.try_stack,
exception_value: None, // Lost during save, but we handle exceptions differently on resume
saved_env_stack: saved.saved_env_stack,
arguments: saved.arguments,
new_target: saved.new_target,
current_constructor: saved.current_constructor,
pending_completion: None, // Lost during save
return_register: saved.return_register,
saved_interp_env: saved.saved_interp_env,
register_guard: frame_guard,
construct_new_obj: saved.construct_new_obj,
is_async: saved.is_async,
}
})
.collect();
Self {
ip: state.ip,
chunk: state.chunk,
registers: state.registers,
register_guard: guard,
call_stack: state.frames,
try_stack: state.try_stack,
this_value,
exception_value: None,
saved_env_stack: Vec::new(),
arguments: state.arguments,
new_target: state.new_target,
current_constructor: None,
pending_completion: None,
trampoline_stack,
register_pool: Vec::new(),
arguments_pool: Vec::new(),
}
}
/// Set the resume value for await resumption
/// This stores the resolved promise value in the specified register
pub fn set_resume_value(&mut self, register: Register, value: JsValue) {
// Guard the value if it's an object
if let JsValue::Object(ref obj) = value {
self.register_guard.guard(obj.cheap_clone());
}
self.set_reg(register, value);
}
/// Inject an exception into the VM for generator.throw()
/// This sets up the VM to handle the exception as if it was thrown at the current position.
/// Returns true if an exception handler was found, false if the exception should propagate.
pub fn inject_exception(&mut self, interp: &mut Interpreter, exception: JsValue) -> bool {
// Create guarded exception value
let guarded = Guarded::from_value(exception, &interp.heap);
// Try to find an exception handler
if let Some((handler_ip, is_catch)) = self.find_exception_handler(interp) {
self.ip = handler_ip;
if is_catch {
self.exception_value = Some(guarded);
} else {
self.pending_completion = Some(PendingCompletion::Throw(guarded));
}
true
} else {
// No handler found - store exception for propagation
self.exception_value = Some(guarded);
false
}
}
/// Execute a single opcode
fn execute_op(&mut self, interp: &mut Interpreter, op: Op) -> Result<OpResult, JsError> {
match op {
// ═══════════════════════════════════════════════════════════════════════════
// Constants & Register Operations
// ═══════════════════════════════════════════════════════════════════════════
Op::LoadConst { dst, idx } => {
let (value, _guard) = match self.get_constant(idx) {
Some(Constant::String(s)) => {
(JsValue::String(s.cheap_clone()), None::<Guard<JsObject>>)
}
Some(Constant::Number(n)) => (JsValue::Number(*n), None::<Guard<JsObject>>),
Some(Constant::RegExp { pattern, flags }) => {
let guard = interp.heap.create_guard();
let obj =
interp.create_regexp_literal(&guard, pattern.as_str(), flags.as_str());
(JsValue::Object(obj), Some(guard))
}
Some(Constant::Chunk(_)) => {
return Err(JsError::internal_error("Cannot load chunk as value"));
}
Some(Constant::TemplateStrings { .. }) => {
return Err(JsError::internal_error(
"Cannot load template strings as value",
));
}
Some(Constant::ExcludedKeys(_)) => {
return Err(JsError::internal_error(
"Cannot load excluded keys as value",
));
}
Some(Constant::JsValue(val)) => {
// For JsValue constants, we need to guard objects
let value = val.clone();
if let Some(obj) = value.as_object() {
self.register_guard.guard(obj.cheap_clone());
}
(value, None::<Guard<JsObject>>)
}
None => return Err(JsError::internal_error("Invalid constant index")),
};
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::LoadUndefined { dst } => {
self.set_reg(dst, JsValue::Undefined);
Ok(OpResult::Continue)
}
Op::LoadNull { dst } => {
self.set_reg(dst, JsValue::Null);
Ok(OpResult::Continue)
}
Op::LoadBool { dst, value } => {
self.set_reg(dst, JsValue::Boolean(value));
Ok(OpResult::Continue)
}
Op::LoadInt { dst, value } => {
self.set_reg(dst, JsValue::Number(value as f64));
Ok(OpResult::Continue)
}
Op::Move { dst, src } => {
let value = self.get_reg(src).clone();
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Binary Arithmetic Operations
// ═══════════════════════════════════════════════════════════════════════════
Op::Add { dst, left, right } => {
let left_val = self.get_reg(left);
let right_val = self.get_reg(right);
// First convert objects to primitives with "default" hint
let left_prim = interp.coerce_to_primitive(left_val, "default")?;
let right_prim = interp.coerce_to_primitive(right_val, "default")?;
let result = match (&left_prim, &right_prim) {
(JsValue::String(a), _) => {
let right_str = interp.to_js_string(&right_prim);
JsValue::String(a.cheap_clone() + right_str.as_str())
}
(_, JsValue::String(b)) => {
let left_str = interp.to_js_string(&left_prim);
JsValue::String(left_str + b.as_str())
}
_ => JsValue::Number(left_prim.to_number() + right_prim.to_number()),
};
self.set_reg(dst, result);
Ok(OpResult::Continue)
}
Op::Sub { dst, left, right } => {
let left_val = interp.coerce_to_number(self.get_reg(left))?;
let right_val = interp.coerce_to_number(self.get_reg(right))?;
self.set_reg(dst, JsValue::Number(left_val - right_val));
Ok(OpResult::Continue)
}
Op::Mul { dst, left, right } => {
let left_val = interp.coerce_to_number(self.get_reg(left))?;
let right_val = interp.coerce_to_number(self.get_reg(right))?;
self.set_reg(dst, JsValue::Number(left_val * right_val));
Ok(OpResult::Continue)
}
Op::Div { dst, left, right } => {
let left_val = interp.coerce_to_number(self.get_reg(left))?;
let right_val = interp.coerce_to_number(self.get_reg(right))?;
self.set_reg(dst, JsValue::Number(left_val / right_val));
Ok(OpResult::Continue)
}
Op::Mod { dst, left, right } => {
let left_val = interp.coerce_to_number(self.get_reg(left))?;
let right_val = interp.coerce_to_number(self.get_reg(right))?;
self.set_reg(dst, JsValue::Number(left_val % right_val));
Ok(OpResult::Continue)
}
Op::Exp { dst, left, right } => {
let left_val = interp.coerce_to_number(self.get_reg(left))?;
let right_val = interp.coerce_to_number(self.get_reg(right))?;
self.set_reg(dst, JsValue::Number(math::powf(left_val, right_val)));
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Comparison Operations
// ═══════════════════════════════════════════════════════════════════════════
Op::Eq { dst, left, right } => {
let left_val = self.get_reg(left);
let right_val = self.get_reg(right);
let result = interp.abstract_equals(left_val, right_val);
self.set_reg(dst, JsValue::Boolean(result));
Ok(OpResult::Continue)
}
Op::NotEq { dst, left, right } => {
let left_val = self.get_reg(left);
let right_val = self.get_reg(right);
let result = interp.abstract_equals(left_val, right_val);
self.set_reg(dst, JsValue::Boolean(!result));
Ok(OpResult::Continue)
}
Op::StrictEq { dst, left, right } => {
let left_val = self.get_reg(left);
let right_val = self.get_reg(right);
let result = left_val.strict_equals(right_val);
self.set_reg(dst, JsValue::Boolean(result));
Ok(OpResult::Continue)
}
Op::StrictNotEq { dst, left, right } => {
let left_val = self.get_reg(left);
let right_val = self.get_reg(right);
let result = !left_val.strict_equals(right_val);
self.set_reg(dst, JsValue::Boolean(result));
Ok(OpResult::Continue)
}
Op::Lt { dst, left, right } => {
let left_val = self.get_reg(left).to_number();
let right_val = self.get_reg(right).to_number();
self.set_reg(dst, JsValue::Boolean(left_val < right_val));
Ok(OpResult::Continue)
}
Op::LtEq { dst, left, right } => {
let left_val = self.get_reg(left).to_number();
let right_val = self.get_reg(right).to_number();
self.set_reg(dst, JsValue::Boolean(left_val <= right_val));
Ok(OpResult::Continue)
}
Op::Gt { dst, left, right } => {
let left_val = self.get_reg(left).to_number();
let right_val = self.get_reg(right).to_number();
self.set_reg(dst, JsValue::Boolean(left_val > right_val));
Ok(OpResult::Continue)
}
Op::GtEq { dst, left, right } => {
let left_val = self.get_reg(left).to_number();
let right_val = self.get_reg(right).to_number();
self.set_reg(dst, JsValue::Boolean(left_val >= right_val));
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Bitwise Operations
// ═══════════════════════════════════════════════════════════════════════════
Op::BitAnd { dst, left, right } => {
let left_val = self.get_reg(left).to_number() as i32;
let right_val = self.get_reg(right).to_number() as i32;
self.set_reg(dst, JsValue::Number((left_val & right_val) as f64));
Ok(OpResult::Continue)
}
Op::BitOr { dst, left, right } => {
let left_val = self.get_reg(left).to_number() as i32;
let right_val = self.get_reg(right).to_number() as i32;
self.set_reg(dst, JsValue::Number((left_val | right_val) as f64));
Ok(OpResult::Continue)
}
Op::BitXor { dst, left, right } => {
let left_val = self.get_reg(left).to_number() as i32;
let right_val = self.get_reg(right).to_number() as i32;
self.set_reg(dst, JsValue::Number((left_val ^ right_val) as f64));
Ok(OpResult::Continue)
}
Op::LShift { dst, left, right } => {
let left_val = self.get_reg(left).to_number() as i32;
let right_val = (self.get_reg(right).to_number() as u32) & 0x1F;
self.set_reg(dst, JsValue::Number((left_val << right_val) as f64));
Ok(OpResult::Continue)
}
Op::RShift { dst, left, right } => {
let left_val = self.get_reg(left).to_number() as i32;
let right_val = (self.get_reg(right).to_number() as u32) & 0x1F;
self.set_reg(dst, JsValue::Number((left_val >> right_val) as f64));
Ok(OpResult::Continue)
}
Op::URShift { dst, left, right } => {
let left_val = (self.get_reg(left).to_number() as i32) as u32;
let right_val = ((self.get_reg(right).to_number() as i32) as u32) & 0x1F;
self.set_reg(dst, JsValue::Number((left_val >> right_val) as f64));
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Special Binary Operations
// ═══════════════════════════════════════════════════════════════════════════
Op::In { dst, left, right } => {
let key = self.get_reg(left);
let obj = self.get_reg(right);
let JsValue::Object(obj_ref) = obj else {
return Err(JsError::type_error(
"Cannot use 'in' operator with non-object",
));
};
let prop_key = interp.property_key_from_value(key);
// Check if this is a proxy - delegate to proxy_has if so
let has_prop = if matches!(obj_ref.borrow().exotic, ExoticObject::Proxy(_)) {
crate::interpreter::builtins::proxy::proxy_has(
interp,
obj_ref.cheap_clone(),
&prop_key,
)?
} else {
obj_ref.borrow().has_own_property(&prop_key)
};
self.set_reg(dst, JsValue::Boolean(has_prop));
Ok(OpResult::Continue)
}
Op::Instanceof { dst, left, right } => {
let left_val = self.get_reg(left);
let right_val = self.get_reg(right);
// right must be an object
let JsValue::Object(right_obj) = right_val else {
return Err(JsError::type_error(
"Right-hand side of 'instanceof' is not an object",
));
};
// Step 1: Check for Symbol.hasInstance method (custom instanceof behavior)
let well_known = interp.well_known_symbols;
let has_instance_symbol = crate::value::JsSymbol::new(
well_known.has_instance,
Some(interp.intern("Symbol.hasInstance")),
);
let has_instance_key = PropertyKey::Symbol(Box::new(has_instance_symbol));
// Look up Symbol.hasInstance on right object (and its prototype chain)
let has_instance_method = right_obj.borrow().get_property(&has_instance_key);
if let Some(JsValue::Object(method_obj)) = has_instance_method
&& method_obj.borrow().is_callable()
{
// Call the custom Symbol.hasInstance method
let result = interp.call_function(
JsValue::Object(method_obj),
right_val.clone(),
core::slice::from_ref(left_val),
)?;
// Convert result to boolean
self.set_reg(dst, JsValue::Boolean(result.value.to_boolean()));
return Ok(OpResult::Continue);
}
// Step 2: Fall back to OrdinaryHasInstance
// right must be callable for OrdinaryHasInstance
if !right_obj.borrow().is_callable() {
return Err(JsError::type_error(
"Right-hand side of 'instanceof' is not callable",
));
}
// Get right.prototype
let proto_key = PropertyKey::String(interp.intern("prototype"));
let right_proto = right_obj.borrow().get_property(&proto_key);
// If prototype is not an object, throw TypeError
let Some(JsValue::Object(right_proto_obj)) = right_proto else {
return Err(JsError::type_error(
"Function has non-object prototype in instanceof check",
));
};
// Check if left's prototype chain contains right.prototype
let result = if let JsValue::Object(left_obj) = left_val {
let mut current = left_obj.borrow().prototype.clone();
let target_id = right_proto_obj.id();
let mut found = false;
while let Some(proto) = current {
if proto.id() == target_id {
found = true;
break;
}
current = proto.borrow().prototype.clone();
}
found
} else {
false
};
self.set_reg(dst, JsValue::Boolean(result));
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Unary Operations
// ═══════════════════════════════════════════════════════════════════════════
Op::Neg { dst, src } => {
let val = interp.coerce_to_number(self.get_reg(src))?;
self.set_reg(dst, JsValue::Number(-val));
Ok(OpResult::Continue)
}
Op::Plus { dst, src } => {
let val = interp.coerce_to_number(self.get_reg(src))?;
self.set_reg(dst, JsValue::Number(val));
Ok(OpResult::Continue)
}
Op::Not { dst, src } => {
let val = self.get_reg(src).to_boolean();
self.set_reg(dst, JsValue::Boolean(!val));
Ok(OpResult::Continue)
}
Op::BitNot { dst, src } => {
let val = self.get_reg(src).to_number() as i32;
self.set_reg(dst, JsValue::Number((!val) as f64));
Ok(OpResult::Continue)
}
Op::Typeof { dst, src } => {
let type_str = match self.get_reg(src) {
JsValue::Undefined => "undefined",
JsValue::Null => "object",
JsValue::Boolean(_) => "boolean",
JsValue::Number(_) => "number",
JsValue::String(_) => "string",
JsValue::Symbol(_) => "symbol",
JsValue::Object(obj) => {
if obj.borrow().is_callable() {
"function"
} else {
"object"
}
}
};
self.set_reg(dst, JsValue::String(interp.intern(type_str)));
Ok(OpResult::Continue)
}
Op::Void { dst, src: _ } => {
self.set_reg(dst, JsValue::Undefined);
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Control Flow
// ═══════════════════════════════════════════════════════════════════════════
Op::Jump { target } => {
self.ip = target as usize;
Ok(OpResult::Continue)
}
Op::JumpIfTrue { cond, target } => {
if self.get_reg(cond).to_boolean() {
self.ip = target as usize;
}
Ok(OpResult::Continue)
}
Op::JumpIfFalse { cond, target } => {
if !self.get_reg(cond).to_boolean() {
self.ip = target as usize;
}
Ok(OpResult::Continue)
}
Op::JumpIfNullish { cond, target } => {
let val = self.get_reg(cond);
if matches!(val, JsValue::Null | JsValue::Undefined) {
self.ip = target as usize;
}
Ok(OpResult::Continue)
}
Op::JumpIfNotNullish { cond, target } => {
let val = self.get_reg(cond);
if !matches!(val, JsValue::Null | JsValue::Undefined) {
self.ip = target as usize;
}
Ok(OpResult::Continue)
}
Op::Break {
target,
try_depth,
scope_depth,
} => self.execute_break(target as usize, try_depth, scope_depth, interp),
Op::Continue {
target,
try_depth,
scope_depth,
} => self.execute_continue(target as usize, try_depth, scope_depth, interp),
// ═══════════════════════════════════════════════════════════════════════════
// Variable Access
// ═══════════════════════════════════════════════════════════════════════════
Op::GetVar { dst, name } => {
let name = self
.get_string_constant(name)
.ok_or_else(|| JsError::internal_error("Invalid variable name constant"))?;
// Intern the string to ensure pointer-based lookup works
let interned_name = interp.intern(name.as_str());
let value = interp.env_get(&interned_name)?;
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::TryGetVar { dst, name } => {
let name = self
.get_string_constant(name)
.ok_or_else(|| JsError::internal_error("Invalid variable name constant"))?;
// Intern the string to ensure pointer-based lookup works
let interned_name = interp.intern(name.as_str());
// Try to get the variable, return undefined if not found
let value = interp.env_get(&interned_name).unwrap_or(JsValue::Undefined);
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::SetVar { name, src } => {
let name = self
.get_string_constant(name)
.ok_or_else(|| JsError::internal_error("Invalid variable name constant"))?;
// Intern the string to ensure pointer-based lookup works
let interned_name = interp.intern(name.as_str());
let value = self.get_reg(src).clone();
interp.env_set(&interned_name, value)?;
Ok(OpResult::Continue)
}
Op::DeclareVar {
name,
init,
mutable,
} => {
let name = self
.get_string_constant(name)
.ok_or_else(|| JsError::internal_error("Invalid variable name constant"))?;
let value = self.get_reg(init).clone();
// Intern the string to ensure pointer-based lookup works
let interned_name = interp.intern(name.as_str());
interp.env_define(interned_name, value, mutable);
Ok(OpResult::Continue)
}
Op::DeclareVarHoisted { name, init } => {
let name = self
.get_string_constant(name)
.ok_or_else(|| JsError::internal_error("Invalid variable name constant"))?;
// Intern the string to ensure pointer-based lookup works
let interned_name = interp.intern(name.as_str());
let value = self.get_reg(init).clone();
interp.env_define(interned_name, value, true);
Ok(OpResult::Continue)
}
Op::GetGlobal { dst, name } => {
let name = self
.get_string_constant(name)
.ok_or_else(|| JsError::internal_error("Invalid global name constant"))?;
let global = interp.global.cheap_clone();
let prop_key = PropertyKey::String(name);
let value = global
.borrow()
.get_property(&prop_key)
.unwrap_or(JsValue::Undefined);
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::SetGlobal { name, src } => {
let name = self
.get_string_constant(name)
.ok_or_else(|| JsError::internal_error("Invalid global name constant"))?;
let value = self.get_reg(src).clone();
let global = interp.global.clone();
global
.borrow_mut()
.set_property(PropertyKey::String(name), value);
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Object/Array Operations
// ═══════════════════════════════════════════════════════════════════════════
Op::CreateObject { dst } => {
let guard = interp.heap.create_guard();
let obj = interp.create_object(&guard);
self.set_reg(dst, JsValue::Object(obj));
Ok(OpResult::Continue)
}
Op::CreateArray { dst, start, count } => {
let mut elements = Vec::with_capacity(count as usize);
for i in 0..count {
elements.push(self.get_reg(start + i as u8).clone());
}
let guard = interp.heap.create_guard();
let arr = interp.create_array_from(&guard, elements);
self.set_reg(dst, JsValue::Object(arr));
Ok(OpResult::Continue)
}
Op::ArrayPush { arr, value } => {
use crate::value::ExoticObject;
let arr_val = self.get_reg(arr);
let val = self.get_reg(value).clone();
if let JsValue::Object(arr_obj) = arr_val {
let mut arr_ref = arr_obj.borrow_mut();
if let ExoticObject::Array { ref mut elements } = arr_ref.exotic {
elements.push(val);
}
}
Ok(OpResult::Continue)
}
Op::GetProperty { dst, obj, key } => {
let obj_val = self.get_reg(obj);
let key_val = self.get_reg(key);
let Guarded { value, .. } = self.get_property_value(interp, obj_val, key_val)?;
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::GetPropertyConst { dst, obj, key } => {
let obj_val = self.get_reg(obj);
let key = self
.get_string_constant(key)
.ok_or_else(|| JsError::internal_error("Invalid property key constant"))?;
let key_val = JsValue::String(key);
let Guarded { value, .. } = self.get_property_value(interp, obj_val, &key_val)?;
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::SetProperty { obj, key, value } => {
let obj_val = self.get_reg(obj);
let key_val = self.get_reg(key);
let val = self.get_reg(value).clone();
self.set_property_value(interp, obj_val, key_val, val)?;
Ok(OpResult::Continue)
}
Op::SetPropertyConst { obj, key, value } => {
let obj_val = self.get_reg(obj);
let key = self
.get_string_constant(key)
.ok_or_else(|| JsError::internal_error("Invalid property key constant"))?;
let val = self.get_reg(value).clone();
let key_val = JsValue::String(key);
self.set_property_value(interp, obj_val, &key_val, val)?;
Ok(OpResult::Continue)
}
Op::DeleteProperty { dst, obj, key } => {
let obj_val = self.get_reg(obj);
let key_val = self.get_reg(key);
match obj_val {
JsValue::Null => {
return Err(JsError::type_error("Cannot delete property of null"));
}
JsValue::Undefined => {
return Err(JsError::type_error("Cannot delete property of undefined"));
}
JsValue::Object(obj_ref) => {
let prop_key = interp.property_key_from_value(key_val);
// Check if this is a proxy - delegate to proxy_delete_property if so
if matches!(obj_ref.borrow().exotic, ExoticObject::Proxy(_)) {
let result =
crate::interpreter::builtins::proxy::proxy_delete_property(
interp,
obj_ref.cheap_clone(),
&prop_key,
)?;
self.set_reg(dst, JsValue::Boolean(result));
} else {
// Check if property is configurable before deleting
{
let obj_borrowed = obj_ref.borrow();
if let Some(prop) = obj_borrowed.properties.get(&prop_key)
&& !prop.configurable()
{
return Err(JsError::type_error(format!(
"Cannot delete property '{}' of object",
prop_key
)));
}
}
// For arrays, handle index deletion specially
{
let mut obj_borrowed = obj_ref.borrow_mut();
if let PropertyKey::Index(idx) = &prop_key
&& let Some(elements) = obj_borrowed.array_elements_mut()
{
let idx = *idx as usize;
if idx < elements.len() {
// Set to undefined (creating a hole)
if let Some(elem) = elements.get_mut(idx) {
*elem = JsValue::Undefined;
}
}
}
obj_borrowed.properties.remove(&prop_key);
}
self.set_reg(dst, JsValue::Boolean(true));
}
}
// Primitives: delete returns true
JsValue::Number(_)
| JsValue::String(_)
| JsValue::Boolean(_)
| JsValue::Symbol(_) => {
self.set_reg(dst, JsValue::Boolean(true));
}
}
Ok(OpResult::Continue)
}
Op::DeletePropertyConst { dst, obj, key } => {
let obj_val = self.get_reg(obj);
let key = self
.get_string_constant(key)
.ok_or_else(|| JsError::internal_error("Invalid property key constant"))?;
match obj_val {
JsValue::Null => {
return Err(JsError::type_error("Cannot delete property of null"));
}
JsValue::Undefined => {
return Err(JsError::type_error("Cannot delete property of undefined"));
}
JsValue::Object(obj_ref) => {
let prop_key = PropertyKey::String(key);
// Check if this is a proxy - delegate to proxy_delete_property if so
if matches!(obj_ref.borrow().exotic, ExoticObject::Proxy(_)) {
let result =
crate::interpreter::builtins::proxy::proxy_delete_property(
interp,
obj_ref.cheap_clone(),
&prop_key,
)?;
self.set_reg(dst, JsValue::Boolean(result));
} else {
// Check if property is configurable before deleting
{
let obj_borrowed = obj_ref.borrow();
if let Some(prop) = obj_borrowed.properties.get(&prop_key)
&& !prop.configurable()
{
return Err(JsError::type_error(format!(
"Cannot delete property '{}' of object",
prop_key
)));
}
}
obj_ref.borrow_mut().properties.remove(&prop_key);
self.set_reg(dst, JsValue::Boolean(true));
}
}
// Primitives: delete returns true
JsValue::Number(_)
| JsValue::String(_)
| JsValue::Boolean(_)
| JsValue::Symbol(_) => {
self.set_reg(dst, JsValue::Boolean(true));
}
}
Ok(OpResult::Continue)
}
Op::DefineProperty {
obj,
key,
value,
flags: _,
} => {
let obj_val = self.get_reg(obj);
let key_val = self.get_reg(key);
if let JsValue::Object(obj_ref) = obj_val {
let prop_key = interp.property_key_from_value(key_val);
let val = self.get_reg(value).clone();
obj_ref.borrow_mut().set_property(prop_key, val);
}
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Function Operations
// ═══════════════════════════════════════════════════════════════════════════
Op::Call {
dst,
callee,
this,
args_start,
argc,
} => {
// Acquire args vec first (mutable borrow), then get register values
let mut args = self.acquire_arguments_vec(argc as usize);
for i in 0..argc {
args.push(self.get_reg(args_start + i).clone());
}
let callee_val = self.get_reg(callee).clone();
let this_val = self.get_reg(this).clone();
// Create guard and protect all object values
let guard = interp.heap.create_guard();
callee_val.guard_by(&guard);
this_val.guard_by(&guard);
for arg in &args {
arg.guard_by(&guard);
}
// Use trampoline for function calls
Ok(OpResult::Call {
callee: callee_val,
this_value: this_val,
args,
return_register: dst,
new_target: JsValue::Undefined,
is_super_call: false,
guard,
})
}
Op::CallSpread {
dst,
callee,
this,
args_start,
argc: _,
} => {
// CallSpread: args_start points to an array of arguments
// We extract the array elements and call the function with them
let callee_val = self.get_reg(callee).clone();
let this_val = self.get_reg(this).clone();
let args_val = self.get_reg(args_start).clone();
let args: Vec<JsValue> = if let JsValue::Object(arr_ref) = &args_val {
if let Some(elems) = arr_ref.borrow().array_elements() {
elems.to_vec()
} else {
Vec::new()
}
} else {
Vec::new()
};
// Create guard and protect all object values
let guard = interp.heap.create_guard();
callee_val.guard_by(&guard);
this_val.guard_by(&guard);
for arg in &args {
arg.guard_by(&guard);
}
// Use trampoline for function calls
Ok(OpResult::Call {
callee: callee_val,
this_value: this_val,
args,
return_register: dst,
new_target: JsValue::Undefined,
is_super_call: false,
guard,
})
}
Op::TailCall {
callee,
this,
args_start,
argc,
} => {
// Tail call optimization: reuse current frame for bytecode functions
let mut args = self.acquire_arguments_vec(argc as usize);
for i in 0..argc {
args.push(self.get_reg(args_start + i).clone());
}
let callee_val = self.get_reg(callee).clone();
let this_val = self.get_reg(this).clone();
self.execute_tail_call(interp, callee_val, this_val, args)
}
Op::TailCallSpread {
callee,
this,
args_start,
argc: _,
} => {
// Tail call with spread arguments
let callee_val = self.get_reg(callee).clone();
let this_val = self.get_reg(this).clone();
let args_val = self.get_reg(args_start).clone();
let args: Vec<JsValue> = if let JsValue::Object(arr_ref) = &args_val {
if let Some(elems) = arr_ref.borrow().array_elements() {
elems.to_vec()
} else {
Vec::new()
}
} else {
Vec::new()
};
self.execute_tail_call(interp, callee_val, this_val, args)
}
Op::TailCallAwait {
dst,
callee,
this,
args_start,
argc,
} => {
// Async tail call optimization for `return await fn()` pattern
let mut args = self.acquire_arguments_vec(argc as usize);
for i in 0..argc {
args.push(self.get_reg(args_start + i).clone());
}
let callee_val = self.get_reg(callee).clone();
let this_val = self.get_reg(this).clone();
self.execute_async_tail_call(interp, callee_val, this_val, args, dst)
}
Op::TailCallAwaitSpread {
dst,
callee,
this,
args_start,
argc: _,
} => {
// Async tail call with spread arguments
let callee_val = self.get_reg(callee).clone();
let this_val = self.get_reg(this).clone();
let args_val = self.get_reg(args_start).clone();
let args: Vec<JsValue> = if let JsValue::Object(arr_ref) = &args_val {
if let Some(elems) = arr_ref.borrow().array_elements() {
elems.to_vec()
} else {
Vec::new()
}
} else {
Vec::new()
};
self.execute_async_tail_call(interp, callee_val, this_val, args, dst)
}
Op::DirectEval { dst, arg } => {
// Direct eval - executes code in the current lexical scope
let arg_val = self.get_reg(arg);
// If argument is not a string, return it directly
let code = match &arg_val {
JsValue::String(s) => s,
_ => {
self.set_reg(dst, arg_val.clone());
return Ok(OpResult::Continue);
}
};
// Execute the code in current scope with the current `this` value
let Guarded {
value,
guard: _guard,
} = crate::interpreter::builtins::global::eval_code_in_scope_with_this(
interp,
code.as_str(),
false,
self.this_value.clone(),
)?;
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::CallMethod {
dst,
obj,
method,
args_start,
argc,
} => {
// Acquire args vec first (mutable borrow), then get register values
let mut args = self.acquire_arguments_vec(argc as usize);
for i in 0..argc {
args.push(self.get_reg(args_start + i).clone());
}
let obj_val = self.get_reg(obj).clone();
let method_name = self
.get_string_constant(method)
.ok_or_else(|| JsError::internal_error("Invalid method name constant"))?;
let Guarded {
value: callee,
guard: callee_guard,
} = self.get_property_value(interp, &obj_val, &JsValue::String(method_name))?;
// Create guard and protect all object values
let guard = interp.heap.create_guard();
callee.guard_by(&guard);
obj_val.guard_by(&guard);
for arg in &args {
arg.guard_by(&guard);
}
// Transfer callee guard to our guard (if any)
if let Some(cg) = callee_guard {
if let JsValue::Object(obj) = &callee {
guard.guard(obj.cheap_clone());
}
drop(cg);
}
// Use trampoline for function calls
Ok(OpResult::Call {
callee,
this_value: obj_val,
args,
return_register: dst,
new_target: JsValue::Undefined,
is_super_call: false,
guard,
})
}
Op::Construct {
dst,
callee,
args_start,
argc,
} => {
// Acquire args vec first (mutable borrow), then get register values
let mut args = self.acquire_arguments_vec(argc as usize);
for i in 0..argc {
args.push(self.get_reg(args_start + i).clone());
}
let callee_val = self.get_reg(callee).clone();
// Inline constructor call logic (similar to evaluate_new)
let JsValue::Object(ctor) = &callee_val else {
return Err(JsError::type_error("Constructor is not a callable object"));
};
// Check if this is a proxy - delegate to proxy_construct if so
if matches!(ctor.borrow().exotic, ExoticObject::Proxy(_)) {
let Guarded {
value,
guard: _guard,
} = crate::interpreter::builtins::proxy::proxy_construct(
interp,
ctor.cheap_clone(),
args,
callee_val.clone(), // new.target is the proxy itself
)?;
self.set_reg(dst, value);
return Ok(OpResult::Continue);
}
// Check if this is `new eval()` - eval is not a constructor
if let ExoticObject::Function(JsFunction::Native(native)) = &ctor.borrow().exotic
&& native.name.as_str() == "eval"
{
return Err(JsError::type_error("eval is not a constructor"));
}
// Create guard for OpResult values
let guard = interp.heap.create_guard();
guard.guard(ctor.cheap_clone());
// Create a new object
let new_obj = interp.create_object(&guard);
// Get the constructor's prototype
let proto_key = PropertyKey::String(interp.intern("prototype"));
if let Some(JsValue::Object(proto)) = ctor.borrow().get_property(&proto_key) {
new_obj.borrow_mut().prototype = Some(proto.cheap_clone());
}
// Guard all object values in args
for arg in &args {
arg.guard_by(&guard);
}
// Use trampoline for constructor call
let this = JsValue::Object(new_obj.cheap_clone());
Ok(OpResult::Construct {
callee: callee_val.clone(),
this_value: this,
args,
return_register: dst,
new_target: callee_val, // new.target is the constructor itself
new_obj,
guard,
})
}
Op::ConstructSpread {
dst,
callee,
args_start,
argc: _,
} => {
// ConstructSpread: args_start points to an array of arguments
let callee_val = self.get_reg(callee);
let args_val = self.get_reg(args_start);
let args: Vec<JsValue> = if let JsValue::Object(arr_ref) = &args_val {
if let Some(elems) = arr_ref.borrow().array_elements() {
elems.to_vec()
} else {
Vec::new()
}
} else {
Vec::new()
};
// Inline constructor call logic (same as Construct)
let JsValue::Object(ctor) = callee_val else {
return Err(JsError::type_error("Constructor is not a callable object"));
};
// Check if this is a proxy - delegate to proxy_construct if so
if matches!(ctor.borrow().exotic, ExoticObject::Proxy(_)) {
let Guarded {
value,
guard: _guard,
} = crate::interpreter::builtins::proxy::proxy_construct(
interp,
ctor.cheap_clone(),
args,
callee_val.clone(), // new.target is the proxy itself
)?;
self.set_reg(dst, value);
return Ok(OpResult::Continue);
}
// Check if this is `new eval()` - eval is not a constructor
if let ExoticObject::Function(JsFunction::Native(native)) = &ctor.borrow().exotic
&& native.name.as_str() == "eval"
{
return Err(JsError::type_error("eval is not a constructor"));
}
// Create guard for OpResult values
let guard = interp.heap.create_guard();
guard.guard(ctor.cheap_clone());
// Create a new object
let new_obj = interp.create_object(&guard);
// Get the constructor's prototype
let proto_key = PropertyKey::String(interp.intern("prototype"));
if let Some(JsValue::Object(proto)) = ctor.borrow().get_property(&proto_key) {
new_obj.borrow_mut().prototype = Some(proto.cheap_clone());
}
// Guard all object values in args
for arg in &args {
arg.guard_by(&guard);
}
// Use trampoline for constructor call
let this = JsValue::Object(new_obj.cheap_clone());
Ok(OpResult::Construct {
callee: callee_val.clone(),
this_value: this,
args,
return_register: dst,
new_target: callee_val.clone(), // new.target is the constructor itself
new_obj,
guard,
})
}
Op::Return { value } => {
let return_val = self.get_reg(value).clone();
// NOTE: review
self.execute_return(return_val, interp)
}
Op::ReturnUndefined => self.execute_return(JsValue::Undefined, interp),
Op::CreateClosure { dst, chunk_idx } => {
// Get the function bytecode chunk from constants
let chunk = match self.get_constant(chunk_idx) {
Some(Constant::Chunk(c)) => c.clone(),
_ => return Err(JsError::internal_error("Invalid closure chunk index")),
};
// Create a BytecodeFunction with the current environment as closure
let bc_func = BytecodeFunction {
chunk,
closure: interp.env.cheap_clone(),
captured_this: None, // Regular functions don't capture this
};
// Create function object
let guard = interp.heap.create_guard();
let func_obj = interp.create_bytecode_function(&guard, bc_func);
self.set_reg(dst, JsValue::Object(func_obj));
Ok(OpResult::Continue)
}
Op::CreateArrow { dst, chunk_idx } => {
// Get the function bytecode chunk from constants
let chunk = match self.get_constant(chunk_idx) {
Some(Constant::Chunk(c)) => c.clone(),
_ => return Err(JsError::internal_error("Invalid arrow chunk index")),
};
// Check if this is an async arrow function
let is_async = chunk
.function_info
.as_ref()
.is_some_and(|info| info.is_async);
// Arrow functions capture lexical this
let bc_func = BytecodeFunction {
chunk,
closure: interp.env.cheap_clone(),
captured_this: Some(Box::new(self.this_value.clone())),
};
// Create function object - use async variant for async arrow functions
let guard = interp.heap.create_guard();
let func_obj = if is_async {
interp.create_bytecode_async_function(&guard, bc_func)
} else {
interp.create_bytecode_function(&guard, bc_func)
};
self.set_reg(dst, JsValue::Object(func_obj));
Ok(OpResult::Continue)
}
Op::CreateGenerator { dst, chunk_idx } => {
// Get the generator function bytecode chunk from constants
let chunk = match self.get_constant(chunk_idx) {
Some(Constant::Chunk(c)) => c.clone(),
_ => return Err(JsError::internal_error("Invalid generator chunk index")),
};
// Create a BytecodeGenerator function with the current environment as closure
let bc_func = BytecodeFunction {
chunk,
closure: interp.env.cheap_clone(),
captured_this: None,
};
// Create function object with the BytecodeGenerator variant
let guard = interp.heap.create_guard();
let func_obj = interp.create_bytecode_generator_function(&guard, bc_func);
self.set_reg(dst, JsValue::Object(func_obj));
Ok(OpResult::Continue)
}
Op::CreateAsync { dst, chunk_idx } => {
// Get the async function bytecode chunk from constants
let chunk = match self.get_constant(chunk_idx) {
Some(Constant::Chunk(c)) => c.clone(),
_ => {
return Err(JsError::internal_error(
"Invalid async function chunk index",
));
}
};
// Create a BytecodeAsync function with the current environment as closure
let bc_func = BytecodeFunction {
chunk,
closure: interp.env.cheap_clone(),
captured_this: None,
};
// Create function object with the BytecodeAsync variant
let guard = interp.heap.create_guard();
let func_obj = interp.create_bytecode_async_function(&guard, bc_func);
self.set_reg(dst, JsValue::Object(func_obj));
Ok(OpResult::Continue)
}
Op::CreateAsyncGenerator { dst, chunk_idx } => {
// Get the async generator function bytecode chunk from constants
let chunk = match self.get_constant(chunk_idx) {
Some(Constant::Chunk(c)) => c.clone(),
_ => {
return Err(JsError::internal_error(
"Invalid async generator chunk index",
));
}
};
// Create a BytecodeAsyncGenerator function with the current environment as closure
let bc_func = BytecodeFunction {
chunk,
closure: interp.env.cheap_clone(),
captured_this: None,
};
// Create function object with the BytecodeAsyncGenerator variant
let guard = interp.heap.create_guard();
let func_obj = interp.create_bytecode_async_generator_function(&guard, bc_func);
self.set_reg(dst, JsValue::Object(func_obj));
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Exception Handling
// ═══════════════════════════════════════════════════════════════════════════
Op::Throw { value } => {
let val = self.get_reg(value).clone();
let guarded = Guarded::from_value(val, &interp.heap);
Err(JsError::ThrownValue { guarded })
}
Op::PushTry {
catch_target,
finally_target,
} => {
self.try_stack.push(TryHandler {
catch_ip: catch_target as usize,
finally_ip: finally_target as usize,
registers_snapshot: self.registers.len(),
frame_depth: self.call_stack.len(),
scope_depth: self.saved_env_stack.len(),
iterator_reg: None,
});
Ok(OpResult::Continue)
}
Op::PopTry => {
self.try_stack.pop();
Ok(OpResult::Continue)
}
Op::PushIterTry {
iterator,
catch_target,
} => {
self.try_stack.push(TryHandler {
catch_ip: catch_target as usize,
finally_ip: 0, // No finally for iterator try
registers_snapshot: self.registers.len(),
frame_depth: self.call_stack.len(),
scope_depth: self.saved_env_stack.len(),
iterator_reg: Some(iterator),
});
Ok(OpResult::Continue)
}
Op::PopIterTry => {
// Pop the iterator try handler (normal completion, no exception)
self.try_stack.pop();
Ok(OpResult::Continue)
}
Op::FinallyEnd => {
// Complete any pending return/throw/break/continue after finally block finishes
if let Some(pending) = self.pending_completion.take() {
match pending {
PendingCompletion::Return(guarded) => {
// Continue with the return (recursively handles nested finally blocks)
return self.execute_return(guarded.value, interp);
}
PendingCompletion::Throw(guarded) => {
// Re-throw the exception after finally
return Err(JsError::ThrownValue { guarded });
}
PendingCompletion::Break {
target,
try_depth,
scope_depth,
} => {
// Continue with the break (recursively handles nested finally blocks)
return self.execute_break(target, try_depth, scope_depth, interp);
}
PendingCompletion::Continue {
target,
try_depth,
scope_depth,
} => {
// Continue with the continue (recursively handles nested finally blocks)
return self.execute_continue(target, try_depth, scope_depth, interp);
}
}
}
Ok(OpResult::Continue)
}
Op::GetException { dst } => {
let val = self
.exception_value
.take()
.map(|g| g.value)
.unwrap_or(JsValue::Undefined);
self.set_reg(dst, val);
Ok(OpResult::Continue)
}
Op::Rethrow => {
if let Some(guarded) = self.exception_value.take() {
Err(JsError::ThrownValue { guarded })
} else {
Err(JsError::internal_error("No exception to rethrow"))
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Async/Generator
// ═══════════════════════════════════════════════════════════════════════════
Op::Await { dst, promise } => {
use crate::value::{ExoticObject, PromiseStatus};
let promise_val = self.get_reg(promise);
// Check if it's an object with special async behavior
if let JsValue::Object(obj) = promise_val {
let obj_ref = obj.borrow();
// Check for PendingOrder first - these suspend immediately for host response
if let ExoticObject::PendingOrder { id, .. } = &obj_ref.exotic {
let order_id = crate::OrderId(*id);
drop(obj_ref);
return Ok(OpResult::SuspendForOrder {
order_id,
resume_register: dst,
});
}
// Check for Promise
if let ExoticObject::Promise(state) = &obj_ref.exotic {
let state_ref = state.borrow();
match state_ref.status {
PromiseStatus::Fulfilled => {
// Extract the resolved value
let result = state_ref.result.clone().unwrap_or(JsValue::Undefined);
drop(state_ref);
drop(obj_ref);
self.set_reg(dst, result);
return Ok(OpResult::Continue);
}
PromiseStatus::Rejected => {
// Throw the rejection reason
let reason = state_ref.result.clone().unwrap_or(JsValue::Undefined);
drop(state_ref);
drop(obj_ref);
let guarded = Guarded::from_value(reason, &interp.heap);
return Err(JsError::thrown(guarded));
}
PromiseStatus::Pending => {
// Suspend execution and wait for promise resolution
drop(state_ref);
drop(obj_ref);
return Ok(OpResult::Suspend {
promise: Guarded::from_value(promise_val.clone(), &interp.heap),
resume_register: dst,
});
}
}
}
}
// Not a promise or pending order - treat as resolved value (await 42 === 42)
self.set_reg(dst, promise_val.clone());
Ok(OpResult::Continue)
}
Op::Yield { dst, value } => {
let yield_val = self.get_reg(value).clone();
// Return a Yield result - the generator will be suspended
// The dst register will receive the value passed to next() when resumed
Ok(OpResult::Yield {
value: Guarded::from_value(yield_val, &interp.heap),
resume_register: dst,
})
}
Op::YieldStar { dst, iterable } => {
// yield* delegates to another iterator
let iterable_val = self.get_reg(iterable).clone();
Ok(OpResult::YieldStar {
iterable: Guarded::from_value(iterable_val, &interp.heap),
resume_register: dst,
})
}
// ═══════════════════════════════════════════════════════════════════════════
// Scope Management
// ═══════════════════════════════════════════════════════════════════════════
Op::PushScope => {
let env = interp.push_scope();
// Push the saved environment onto the stack
self.saved_env_stack.push(env);
Ok(OpResult::Continue)
}
Op::PopScope => {
if let Some(env) = self.saved_env_stack.pop() {
interp.pop_scope(env);
}
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Iteration
// ═══════════════════════════════════════════════════════════════════════════
Op::GetIterator { dst, obj } => {
let obj_val = self.get_reg(obj);
// For arrays and strings, create an internal array iterator
// The iterator is stored as an object with internal index state
match obj_val {
JsValue::Object(obj_ref) => {
// Check if it's a proxy first - need to get Symbol.iterator through proxy trap
let is_proxy = matches!(obj_ref.borrow().exotic, ExoticObject::Proxy(_));
if is_proxy {
// For proxies, use proxy_get to get Symbol.iterator method
let well_known = interp.well_known_symbols;
let iterator_symbol = crate::value::JsSymbol::new(
well_known.iterator,
Some(interp.intern("Symbol.iterator")),
);
let iterator_key = PropertyKey::Symbol(Box::new(iterator_symbol));
let iterator_method_result =
crate::interpreter::builtins::proxy::proxy_get(
interp,
obj_ref.cheap_clone(),
iterator_key,
obj_val.clone(),
)?;
if let JsValue::Object(method_obj) = iterator_method_result.value {
// Call the iterator method with the proxy as `this`
let Guarded {
value,
guard: _guard,
} = interp.call_function(
JsValue::Object(method_obj),
obj_val.clone(),
&[],
)?;
self.set_reg(dst, value);
} else {
return Err(JsError::type_error("Object is not iterable"));
}
return Ok(OpResult::Continue);
}
// Check if it's an array - use direct element iteration
if obj_ref.borrow().array_elements().is_some() {
// Create an iterator object with the array and index
// Use register_guard to keep it alive across loop iterations
let guard = interp.heap.create_guard();
let iter = interp.create_object(&guard);
iter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__array__")),
JsValue::Object(obj_ref.clone()),
);
iter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__index__")),
JsValue::Number(0.0),
);
self.set_reg(dst, JsValue::Object(iter));
return Ok(OpResult::Continue);
}
// For non-array objects, try Symbol.iterator
let well_known = interp.well_known_symbols;
let iterator_symbol = crate::value::JsSymbol::new(
well_known.iterator,
Some(interp.intern("Symbol.iterator")),
);
let iterator_key = PropertyKey::Symbol(Box::new(iterator_symbol));
let iterator_method = obj_ref.borrow().get_property(&iterator_key);
if let Some(JsValue::Object(method_obj)) = iterator_method {
// Call the iterator method
let Guarded {
value,
guard: _guard,
} = interp.call_function(
JsValue::Object(method_obj),
obj_val.clone(),
&[],
)?;
self.set_reg(dst, value);
} else {
return Err(JsError::type_error("Object is not iterable"));
}
}
JsValue::String(s) => {
// Create a string iterator
let guard = interp.heap.create_guard();
let iter = interp.create_object(&guard);
iter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__string__")),
JsValue::String(s.cheap_clone()),
);
iter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__index__")),
JsValue::Number(0.0),
);
self.set_reg(dst, JsValue::Object(iter));
}
_ => {
return Err(JsError::type_error("Object is not iterable"));
}
}
Ok(OpResult::Continue)
}
Op::GetKeysIterator { dst, obj } => {
let obj_val = self.get_reg(obj);
// Create a keys iterator that iterates over enumerable property keys
let keys: Vec<JsValue> = match obj_val {
JsValue::Object(obj_ref) => {
// Check if this is a proxy - use proxy_own_keys if so
let is_proxy = matches!(obj_ref.borrow().exotic, ExoticObject::Proxy(_));
if is_proxy {
// Get keys through proxy trap
let Guarded {
value,
guard: _guard,
} = crate::interpreter::builtins::proxy::proxy_own_keys(
interp,
obj_ref.cheap_clone(),
)?;
// proxy_own_keys returns an array of keys
if let JsValue::Object(keys_arr) = value {
if let Some(elements) = keys_arr.borrow().array_elements() {
elements.to_vec()
} else {
Vec::new()
}
} else {
Vec::new()
}
} else {
let obj_borrowed = obj_ref.borrow();
let mut result = Vec::new();
// For arrays, first add all array indices
if let Some(elements) = obj_borrowed.array_elements() {
for i in 0..elements.len() {
result.push(JsValue::String(JsString::from(i.to_string())));
}
}
// Then add own enumerable property keys (excluding indices already added)
for (k, prop) in obj_borrowed.properties.iter() {
// Only include enumerable properties
if !prop.enumerable() {
continue;
}
match k {
PropertyKey::String(s) => {
result.push(JsValue::String(s.cheap_clone()));
}
PropertyKey::Index(i) => {
// Only add if not an array (arrays already handled above)
if obj_borrowed.array_elements().is_none() {
result.push(JsValue::String(JsString::from(
i.to_string(),
)));
}
}
_ => {} // Skip symbols for for-in
}
}
result
}
}
JsValue::String(s) => {
// For strings, iterate over character indices
(0..s.as_str().chars().count())
.map(|i| JsValue::String(JsString::from(i.to_string())))
.collect()
}
JsValue::Null | JsValue::Undefined => {
// for-in on null/undefined should just not iterate
Vec::new()
}
_ => Vec::new(),
};
// Create a keys array iterator
let guard = interp.heap.create_guard();
let iter = interp.create_object(&guard);
let keys_arr = interp.create_array_from(&self.register_guard, keys);
iter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__keys__")),
JsValue::Object(keys_arr),
);
iter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__index__")),
JsValue::Number(0.0),
);
self.set_reg(dst, JsValue::Object(iter));
Ok(OpResult::Continue)
}
Op::GetAsyncIterator { dst, obj } => {
let obj_val = self.get_reg(obj);
// For async iteration, we first try Symbol.asyncIterator, then fall back to Symbol.iterator.
// For arrays without Symbol.asyncIterator, we use the same internal iterator as sync iteration.
// The Await opcode that follows IteratorNext will handle awaiting each value.
match obj_val {
JsValue::Object(obj_ref) => {
// Check if it's a proxy first
let is_proxy = matches!(obj_ref.borrow().exotic, ExoticObject::Proxy(_));
if is_proxy {
// For proxies, try Symbol.asyncIterator first, then Symbol.iterator
let well_known = interp.well_known_symbols;
// Try Symbol.asyncIterator first
let async_iterator_symbol = crate::value::JsSymbol::new(
well_known.async_iterator,
Some(interp.intern("Symbol.asyncIterator")),
);
let async_iterator_key =
PropertyKey::Symbol(Box::new(async_iterator_symbol));
let async_method_result =
crate::interpreter::builtins::proxy::proxy_get(
interp,
obj_ref.cheap_clone(),
async_iterator_key,
obj_val.clone(),
)?;
if let JsValue::Object(method_obj) = async_method_result.value {
// Call the async iterator method with the proxy as `this`
let Guarded {
value,
guard: _guard,
} = interp.call_function(
JsValue::Object(method_obj),
obj_val.clone(),
&[],
)?;
self.set_reg(dst, value);
return Ok(OpResult::Continue);
}
// Fall back to Symbol.iterator
let iterator_symbol = crate::value::JsSymbol::new(
well_known.iterator,
Some(interp.intern("Symbol.iterator")),
);
let iterator_key = PropertyKey::Symbol(Box::new(iterator_symbol));
let iterator_method_result =
crate::interpreter::builtins::proxy::proxy_get(
interp,
obj_ref.cheap_clone(),
iterator_key,
obj_val.clone(),
)?;
if let JsValue::Object(method_obj) = iterator_method_result.value {
let Guarded {
value,
guard: _guard,
} = interp.call_function(
JsValue::Object(method_obj),
obj_val.clone(),
&[],
)?;
self.set_reg(dst, value);
} else {
return Err(JsError::type_error("Object is not async iterable"));
}
return Ok(OpResult::Continue);
}
// Check for Symbol.asyncIterator first
let well_known = interp.well_known_symbols;
let async_iterator_symbol = crate::value::JsSymbol::new(
well_known.async_iterator,
Some(interp.intern("Symbol.asyncIterator")),
);
let async_iterator_key =
PropertyKey::Symbol(Box::new(async_iterator_symbol));
let async_method = obj_ref.borrow().get_property(&async_iterator_key);
if let Some(JsValue::Object(method_obj)) = async_method {
// Call the async iterator method
let Guarded {
value,
guard: _guard,
} = interp.call_function(
JsValue::Object(method_obj),
obj_val.clone(),
&[],
)?;
self.set_reg(dst, value);
return Ok(OpResult::Continue);
}
// Check if it's an array - use direct element iteration
// The Await opcode will handle awaiting each element (promise or plain value)
if obj_ref.borrow().array_elements().is_some() {
let guard = interp.heap.create_guard();
let iter = interp.create_object(&guard);
iter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__array__")),
JsValue::Object(obj_ref.clone()),
);
iter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__index__")),
JsValue::Number(0.0),
);
self.set_reg(dst, JsValue::Object(iter));
return Ok(OpResult::Continue);
}
// Try Symbol.iterator as fallback
let iterator_symbol = crate::value::JsSymbol::new(
well_known.iterator,
Some(interp.intern("Symbol.iterator")),
);
let iterator_key = PropertyKey::Symbol(Box::new(iterator_symbol));
let iterator_method = obj_ref.borrow().get_property(&iterator_key);
if let Some(JsValue::Object(method_obj)) = iterator_method {
let Guarded {
value,
guard: _guard,
} = interp.call_function(
JsValue::Object(method_obj),
obj_val.clone(),
&[],
)?;
self.set_reg(dst, value);
} else {
return Err(JsError::type_error("Object is not async iterable"));
}
}
JsValue::String(s) => {
// Create a string iterator (same as sync - Await will handle values)
let guard = interp.heap.create_guard();
let iter = interp.create_object(&guard);
iter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__string__")),
JsValue::String(s.cheap_clone()),
);
iter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__index__")),
JsValue::Number(0.0),
);
self.set_reg(dst, JsValue::Object(iter));
}
_ => {
return Err(JsError::type_error("Object is not async iterable"));
}
}
Ok(OpResult::Continue)
}
Op::IteratorNext { dst, iterator } => {
let iter_val = self.get_reg(iterator);
let JsValue::Object(iter_obj) = iter_val else {
return Err(JsError::type_error("Iterator is not an object"));
};
// Check if this is our internal array iterator
let array_prop = iter_obj
.borrow()
.get_property(&PropertyKey::String(interp.intern("__array__")));
if let Some(JsValue::Object(arr_ref)) = array_prop {
// If the array is a proxy, fall through to custom iterator path
// which will call the next() method (which handles proxies properly)
let index_key = PropertyKey::String(interp.intern("__index__"));
let is_proxy = matches!(arr_ref.borrow().exotic, ExoticObject::Proxy(_));
if !is_proxy {
let index = match iter_obj.borrow().get_property(&index_key) {
Some(JsValue::Number(n)) => n as usize,
_ => 0,
};
let elements = arr_ref.borrow().array_elements().map(|e| e.to_vec());
let (value, done) = if let Some(elems) = elements {
if index < elems.len() {
let val = elems.get(index).cloned().unwrap_or(JsValue::Undefined);
(val, false)
} else {
(JsValue::Undefined, true)
}
} else {
(JsValue::Undefined, true)
};
// Update index
iter_obj
.borrow_mut()
.set_property(index_key, JsValue::Number((index + 1) as f64));
// Create result object { value, done }
let guard = interp.heap.create_guard();
let result = interp.create_object(&guard);
result
.borrow_mut()
.set_property(PropertyKey::String(interp.intern("value")), value);
result.borrow_mut().set_property(
PropertyKey::String(interp.intern("done")),
JsValue::Boolean(done),
);
self.set_reg(dst, JsValue::Object(result));
return Ok(OpResult::Continue);
}
}
// Check if this is our internal string iterator
let string_prop = iter_obj
.borrow()
.get_property(&PropertyKey::String(interp.intern("__string__")));
if let Some(JsValue::String(s)) = string_prop {
let index_key = PropertyKey::String(interp.intern("__index__"));
let index = match iter_obj.borrow().get_property(&index_key) {
Some(JsValue::Number(n)) => n as usize,
_ => 0,
};
let chars: Vec<char> = s.as_str().chars().collect();
let (value, done) = if index < chars.len() {
let val = chars
.get(index)
.map(|c| JsValue::String(JsString::from(c.to_string())))
.unwrap_or(JsValue::Undefined);
(val, false)
} else {
(JsValue::Undefined, true)
};
// Update index
iter_obj
.borrow_mut()
.set_property(index_key, JsValue::Number((index + 1) as f64));
// Create result object { value, done }
let guard = interp.heap.create_guard();
let result = interp.create_object(&guard);
let value_key = interp.property_key("value");
let done_key = interp.property_key("done");
result.borrow_mut().set_property(value_key, value);
result
.borrow_mut()
.set_property(done_key, JsValue::Boolean(done));
self.set_reg(dst, JsValue::Object(result));
return Ok(OpResult::Continue);
}
// Check if this is our internal keys iterator (for for-in)
let index_key = PropertyKey::String(interp.intern("__index__"));
let keys_prop = iter_obj
.borrow()
.get_property(&PropertyKey::String(interp.intern("__keys__")));
if let Some(JsValue::Object(keys_arr)) = keys_prop {
let index = match iter_obj.borrow().get_property(&index_key) {
Some(JsValue::Number(n)) => n as usize,
_ => 0,
};
let elements = keys_arr.borrow().array_elements().map(|e| e.to_vec());
let (value, done) = if let Some(elems) = elements {
if index < elems.len() {
let val = elems.get(index).cloned().unwrap_or(JsValue::Undefined);
(val, false)
} else {
(JsValue::Undefined, true)
}
} else {
(JsValue::Undefined, true)
};
// Update index
iter_obj
.borrow_mut()
.set_property(index_key, JsValue::Number((index + 1) as f64));
// Create result object { value, done }
let guard = interp.heap.create_guard();
let result = interp.create_object(&guard);
let value_key = interp.property_key("value");
let done_key = interp.property_key("done");
result.borrow_mut().set_property(value_key, value);
result
.borrow_mut()
.set_property(done_key, JsValue::Boolean(done));
self.set_reg(dst, JsValue::Object(result));
return Ok(OpResult::Continue);
}
// For custom iterators, call next() method
let next_method = iter_obj
.borrow()
.get_property(&PropertyKey::String(interp.intern("next")));
if let Some(JsValue::Object(next_fn)) = next_method {
let Guarded {
value,
guard: _guard,
} = interp.call_function(
JsValue::Object(next_fn),
JsValue::Object(iter_obj.clone()),
&[],
)?;
self.set_reg(dst, value);
} else {
return Err(JsError::type_error("Iterator must have a next method"));
}
Ok(OpResult::Continue)
}
Op::IteratorDone { result, target } => {
let result_val = self.get_reg(result);
let done = if let JsValue::Object(obj_ref) = result_val {
match obj_ref
.borrow()
.get_property(&PropertyKey::String(interp.intern("done")))
{
Some(JsValue::Boolean(b)) => b,
_ => false,
}
} else {
true
};
if done {
self.ip = target as usize;
}
Ok(OpResult::Continue)
}
Op::IteratorValue { dst, result } => {
let result_val = self.get_reg(result);
let value = if let JsValue::Object(obj_ref) = result_val {
obj_ref
.borrow()
.get_property(&PropertyKey::String(interp.intern("value")))
.unwrap_or(JsValue::Undefined)
} else {
JsValue::Undefined
};
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::IteratorClose { iterator } => {
let iter_val = self.get_reg(iterator);
// Check if iterator has a return() method
if let JsValue::Object(iter_obj) = iter_val {
// For internal array/string/keys iterators, there's no return method
// Only check for custom iterators that have a 'return' property
let return_key = PropertyKey::String(interp.intern("return"));
let return_method = iter_obj.borrow().get_property(&return_key);
if let Some(JsValue::Object(return_fn)) = return_method {
// Call the return method
// Per ES spec 7.4.6: If Type(innerResult.[[value]]) is not Object,
// throw a TypeError exception.
let Guarded {
value,
guard: _guard,
} = interp.call_function(
JsValue::Object(return_fn),
JsValue::Object(iter_obj.clone()),
&[],
)?;
// Check that result is an object
if !matches!(value, JsValue::Object(_)) {
return Err(JsError::type_error("Iterator result is not an object"));
}
}
}
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Class Operations
// ═══════════════════════════════════════════════════════════════════════════
Op::CreateClass {
dst,
constructor,
super_class,
} => {
// Get constructor function - it should be a function object
let ctor_val = self.get_reg(constructor);
let JsValue::Object(ctor_obj) = ctor_val else {
return Err(JsError::type_error("Class constructor must be a function"));
};
// Create prototype object
let guard = interp.heap.create_guard();
let prototype = interp.create_object(&guard);
// Handle superclass if provided
let super_val = self.get_reg(super_class);
if !matches!(super_val, JsValue::Undefined) {
let JsValue::Object(super_ctor) = &super_val else {
return Err(JsError::type_error(
"Class extends value is not a constructor",
));
};
// Set prototype chain: prototype.__proto__ = superClass.prototype
let proto_key = PropertyKey::String(interp.intern("prototype"));
if let Some(JsValue::Object(super_proto)) =
super_ctor.borrow().get_property(&proto_key)
{
prototype.borrow_mut().prototype = Some(super_proto.cheap_clone());
}
// Store __super__ on constructor for super() calls
ctor_obj.borrow_mut().set_property(
PropertyKey::String(interp.intern("__super__")),
JsValue::Object(super_ctor.cheap_clone()),
);
// Store __super_target__ for super.x property access
if let Some(sp) = super_ctor
.borrow()
.get_property(&PropertyKey::String(interp.intern("prototype")))
{
ctor_obj.borrow_mut().set_property(
PropertyKey::String(interp.intern("__super_target__")),
sp,
);
}
}
// Set constructor.prototype = prototype (non-writable, non-enumerable, non-configurable per spec)
ctor_obj.borrow_mut().define_property(
PropertyKey::String(interp.intern("prototype")),
Property::with_attributes(
JsValue::Object(prototype.cheap_clone()),
false,
false,
false,
),
);
// Set prototype.constructor = constructor (non-enumerable, writable, configurable per spec)
prototype.borrow_mut().define_property(
PropertyKey::String(interp.intern("constructor")),
Property::with_attributes(
JsValue::Object(ctor_obj.cheap_clone()),
true,
false,
true,
),
);
self.set_reg(dst, JsValue::Object(ctor_obj.clone()));
Ok(OpResult::Continue)
}
Op::DefineMethod {
class,
name,
method,
is_static,
} => {
let class_val = self.get_reg(class);
let JsValue::Object(class_obj) = class_val else {
return Err(JsError::type_error("Class is not an object"));
};
let method_val = self.get_reg(method);
let method_name = self
.get_string_constant(name)
.ok_or_else(|| JsError::internal_error("Invalid method name constant"))?;
// Store __super__ and __super_target__ on method for super access
if let JsValue::Object(method_obj) = method_val {
// Copy __super__ from class constructor
let super_key = PropertyKey::String(interp.intern("__super__"));
if let Some(super_val) = class_obj.borrow().get_property(&super_key) {
method_obj
.borrow_mut()
.set_property(super_key.clone(), super_val.clone());
// For static methods, __super_target__ = parent constructor (__super__)
// For instance methods, __super_target__ = parent prototype (from class)
if is_static {
method_obj.borrow_mut().set_property(
PropertyKey::String(interp.intern("__super_target__")),
super_val,
);
} else if let Some(super_target) = class_obj
.borrow()
.get_property(&PropertyKey::String(interp.intern("__super_target__")))
{
method_obj.borrow_mut().set_property(
PropertyKey::String(interp.intern("__super_target__")),
super_target,
);
}
}
}
// Use from_value to handle numeric string keys correctly (e.g., "2" -> Index(2))
let prop_key =
interp.property_key_from_value(&JsValue::String(method_name.cheap_clone()));
if is_static {
// Add to class constructor directly
// Methods are non-enumerable, writable, configurable (per spec)
class_obj.borrow_mut().define_property(
prop_key,
Property::with_attributes(method_val.clone(), true, false, true),
);
} else {
// Add to prototype
// Methods are non-enumerable, writable, configurable (per spec)
let proto_key = PropertyKey::String(interp.intern("prototype"));
if let Some(JsValue::Object(proto)) =
class_obj.borrow().get_property(&proto_key)
{
proto.borrow_mut().define_property(
prop_key,
Property::with_attributes(method_val.clone(), true, false, true),
);
}
}
Ok(OpResult::Continue)
}
Op::DefineAccessor {
class,
name,
getter,
setter,
is_static,
} => {
let class_val = self.get_reg(class);
let JsValue::Object(class_obj) = class_val else {
return Err(JsError::type_error("Class is not an object"));
};
let getter_val = self.get_reg(getter);
let setter_val = self.get_reg(setter);
let accessor_name = self
.get_string_constant(name)
.ok_or_else(|| JsError::internal_error("Invalid accessor name constant"))?;
// Extract function objects (undefined means keep existing)
let new_getter = if let JsValue::Object(g) = getter_val {
Some(g)
} else {
None
};
let new_setter = if let JsValue::Object(s) = setter_val {
Some(s)
} else {
None
};
// Get target object (class for static, prototype for instance)
let target = if is_static {
class_obj.cheap_clone()
} else {
let proto_key = PropertyKey::String(interp.intern("prototype"));
if let Some(JsValue::Object(proto)) =
class_obj.borrow().get_property(&proto_key)
{
proto
} else {
return Ok(OpResult::Continue);
}
};
// Get existing accessor property if any
// Use from_value to handle numeric string keys correctly (e.g., "2" -> Index(2))
let prop_key =
interp.property_key_from_value(&JsValue::String(accessor_name.cheap_clone()));
let (existing_getter, existing_setter) = {
let target_ref = target.borrow();
if let Some(prop) = target_ref.properties.get(&prop_key) {
(prop.getter().cloned(), prop.setter().cloned())
} else {
(None, None)
}
};
// Merge with existing accessors
let final_getter = new_getter.cloned().or(existing_getter);
let final_setter = new_setter.cloned().or(existing_setter);
// Create accessor property
let property = Property::accessor(final_getter, final_setter);
target.borrow_mut().define_property(prop_key, property);
Ok(OpResult::Continue)
}
Op::DefineMethodComputed {
class,
key,
method,
is_static,
} => {
let class_val = self.get_reg(class);
let JsValue::Object(class_obj) = class_val else {
return Err(JsError::type_error("Class is not an object"));
};
let method_val = self.get_reg(method);
let key_val = self.get_reg(key);
// Convert key to string for property name
let method_name = interp.to_js_string(key_val);
// Store __super__ and __super_target__ on method for super access
if let JsValue::Object(method_obj) = &method_val {
// Copy __super__ from class constructor
let super_key = PropertyKey::String(interp.intern("__super__"));
if let Some(super_val) = class_obj.borrow().get_property(&super_key) {
method_obj
.borrow_mut()
.set_property(super_key.clone(), super_val.clone());
// For static methods, __super_target__ = parent constructor (__super__)
// For instance methods, __super_target__ = parent prototype (from class)
if is_static {
method_obj.borrow_mut().set_property(
PropertyKey::String(interp.intern("__super_target__")),
super_val,
);
} else if let Some(super_target) = class_obj
.borrow()
.get_property(&PropertyKey::String(interp.intern("__super_target__")))
{
method_obj.borrow_mut().set_property(
PropertyKey::String(interp.intern("__super_target__")),
super_target,
);
}
}
}
// Use from_value to handle numeric string keys correctly (e.g., "2" -> Index(2))
let prop_key = interp.property_key_from_value(&JsValue::String(method_name));
if is_static {
// Add to class constructor directly
// Methods are non-enumerable, writable, configurable (per spec)
class_obj.borrow_mut().define_property(
prop_key,
Property::with_attributes(method_val.clone(), true, false, true),
);
} else {
// Add to prototype
// Methods are non-enumerable, writable, configurable (per spec)
let proto_key = PropertyKey::String(interp.intern("prototype"));
if let Some(JsValue::Object(proto)) =
class_obj.borrow().get_property(&proto_key)
{
proto.borrow_mut().define_property(
prop_key,
Property::with_attributes(method_val.clone(), true, false, true),
);
}
}
Ok(OpResult::Continue)
}
Op::DefineAccessorComputed {
class,
key,
getter,
setter,
is_static,
} => {
let class_val = self.get_reg(class);
let JsValue::Object(class_obj) = class_val else {
return Err(JsError::type_error("Class is not an object"));
};
let getter_val = self.get_reg(getter);
let setter_val = self.get_reg(setter);
let key_val = self.get_reg(key);
// Convert key to string for accessor name
let accessor_name = interp.to_js_string(key_val);
// Extract function objects (undefined means keep existing)
let new_getter = if let JsValue::Object(g) = getter_val {
Some(g)
} else {
None
};
let new_setter = if let JsValue::Object(s) = setter_val {
Some(s)
} else {
None
};
// Get target object (class for static, prototype for instance)
let target = if is_static {
class_obj.cheap_clone()
} else {
let proto_key = PropertyKey::String(interp.intern("prototype"));
if let Some(JsValue::Object(proto)) =
class_obj.borrow().get_property(&proto_key)
{
proto
} else {
return Ok(OpResult::Continue);
}
};
// Get existing accessor property if any
// Use from_value to handle numeric string keys correctly (e.g., "2" -> Index(2))
let prop_key = interp.property_key_from_value(&JsValue::String(accessor_name));
let (existing_getter, existing_setter) = {
let target_ref = target.borrow();
if let Some(prop) = target_ref.properties.get(&prop_key) {
(prop.getter().cloned(), prop.setter().cloned())
} else {
(None, None)
}
};
// Merge with existing accessors
let final_getter = new_getter.cloned().or(existing_getter);
let final_setter = new_setter.cloned().or(existing_setter);
// Create accessor property
let property = Property::accessor(final_getter, final_setter);
target.borrow_mut().define_property(prop_key, property);
Ok(OpResult::Continue)
}
Op::SuperCall {
dst,
args_start,
argc,
} => {
// Get the current function's __super__ property (parent constructor)
let super_ctor = self.get_super_constructor(interp)?;
let mut args = self.acquire_arguments_vec(argc as usize);
for i in 0..argc {
args.push(self.get_reg(args_start + i).clone());
}
// Create guard and protect all object values
let guard = interp.heap.create_guard();
super_ctor.guard_by(&guard);
self.this_value.guard_by(&guard);
for arg in &args {
arg.guard_by(&guard);
}
// Call super constructor with current this - use trampoline
let this = self.this_value.clone();
Ok(OpResult::Call {
callee: super_ctor,
this_value: this,
args,
return_register: dst,
new_target: JsValue::Undefined,
is_super_call: true, // This is a super() call
guard,
})
}
Op::SuperCallSpread { dst, args_array } => {
// Get the current function's __super__ property (parent constructor)
let super_ctor = self.get_super_constructor(interp)?;
// Extract arguments from the array
let args_val = self.get_reg(args_array);
let args: Vec<JsValue> = if let JsValue::Object(arr_ref) = args_val {
if let Some(elems) = arr_ref.borrow().array_elements() {
elems.to_vec()
} else {
Vec::new()
}
} else {
Vec::new()
};
// Create guard and protect all object values
let guard = interp.heap.create_guard();
super_ctor.guard_by(&guard);
self.this_value.guard_by(&guard);
for arg in &args {
arg.guard_by(&guard);
}
// Call super constructor with current this - use trampoline
let this = self.this_value.clone();
Ok(OpResult::Call {
callee: super_ctor,
this_value: this,
args,
return_register: dst,
new_target: JsValue::Undefined,
is_super_call: true, // This is a super() call
guard,
})
}
Op::SuperGet { dst, key } => {
let key_val = self.get_reg(key);
let super_target = self.get_super_target(interp)?;
let Guarded { value, .. } =
self.get_property_value(interp, &super_target, key_val)?;
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::SuperGetConst { dst, key } => {
let key_str = self
.get_string_constant(key)
.ok_or_else(|| JsError::internal_error("Invalid super property key"))?;
let super_target = self.get_super_target(interp)?;
let Guarded { value, .. } =
self.get_property_value(interp, &super_target, &JsValue::String(key_str))?;
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::SuperSet { key, value } => {
// In JavaScript, super.x = value sets the property on `this`, not on the super prototype
// The lookup is done through super (for semantics), but the assignment is to `this`
let key_val = self.get_reg(key);
if let JsValue::Object(this_obj) = &self.this_value {
let prop_key = interp.property_key_from_value(key_val);
let set_value = self.get_reg(value);
this_obj
.borrow_mut()
.set_property(prop_key, set_value.clone());
}
Ok(OpResult::Continue)
}
Op::SuperSetConst { key, value } => {
// In JavaScript, super.x = value sets the property on `this`, not on the super prototype
let key_str = self
.get_string_constant(key)
.ok_or_else(|| JsError::internal_error("Invalid super property key"))?;
if let JsValue::Object(this_obj) = &self.this_value {
let set_value = self.get_reg(value);
this_obj
.borrow_mut()
.set_property(PropertyKey::String(key_str), set_value.clone());
}
Ok(OpResult::Continue)
}
Op::ApplyClassDecorator {
class,
decorator,
class_name,
initializers,
} => {
let class_val = self.get_reg(class);
let decorator_val = self.get_reg(decorator);
let initializers_arr = self.get_reg(initializers);
// Get class name for context (None if class_name is MAX)
let name = if class_name == u16::MAX {
None
} else {
self.get_string_constant(class_name)
};
// Create decorator context object
let guard = interp.heap.create_guard();
let ctx = interp.create_object(&guard);
// Set context.kind = "class"
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("kind")),
JsValue::String(interp.intern("class")),
);
// Set context.name if we have a class name
if let Some(n) = name {
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("name")),
JsValue::String(n),
);
}
// Set context.static = false (classes don't have static flag)
// This is for consistency with method/field decorators
// Note: TC39 spec doesn't define static for class decorators,
// but some tests expect it to be undefined
// Store the initializers array on context so addInitializer can access it
let init_key = interp.intern("__initializers__");
ctx.borrow_mut()
.set_property(PropertyKey::String(init_key), initializers_arr.clone());
// Create addInitializer function that pushes to context.__initializers__
let add_init_fn = interp.create_native_fn(
&guard,
"addInitializer",
|interp, this, args| {
// Get the callback from args
let callback = args.first().cloned().unwrap_or(JsValue::Undefined);
// Get __initializers__ array from this (the context object)
if let JsValue::Object(ctx_obj) = this {
let init_key = interp.intern("__initializers__");
if let Some(JsValue::Object(arr)) = ctx_obj
.borrow()
.get_property(&PropertyKey::String(init_key))
{
// Push callback to the array using array_elements_mut
let mut arr_ref = arr.borrow_mut();
if let Some(elements) = arr_ref.array_elements_mut() {
elements.push(callback.clone());
}
}
}
Ok(crate::value::Guarded::unguarded(JsValue::Undefined))
},
1,
);
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("addInitializer")),
JsValue::Object(add_init_fn),
);
// Call decorator(class, context)
let Guarded {
value,
guard: _guard,
} = interp.call_function(
decorator_val.clone(),
JsValue::Undefined,
&[class_val.clone(), JsValue::Object(ctx)],
)?;
// If decorator returns undefined, keep original class; otherwise use return value
if matches!(value, JsValue::Undefined) {
// Keep original class value in register
} else {
self.set_reg(class, value);
}
Ok(OpResult::Continue)
}
Op::RunClassInitializers {
class,
initializers,
} => {
let class_val = self.get_reg(class);
let initializers_val = self.get_reg(initializers);
// Get the initializers array and call each function with class as `this`
if let JsValue::Object(arr) = initializers_val {
// Clone elements to avoid borrow issues during iteration
let callbacks: Vec<JsValue> = {
let arr_ref = arr.borrow();
if let crate::value::ExoticObject::Array { ref elements } = arr_ref.exotic {
elements.clone()
} else {
Vec::new()
}
};
for callback in callbacks {
// Call the initializer with class as `this`
interp.call_function(callback, class_val.clone(), &[])?;
}
}
Ok(OpResult::Continue)
}
Op::ApplyMethodDecorator {
method,
decorator,
name,
kind,
is_static,
is_private,
} => {
let method_val = self.get_reg(method);
let decorator_val = self.get_reg(decorator);
let method_name = self.get_string_constant(name);
// Create decorator context object
let guard = interp.heap.create_guard();
let ctx = interp.create_object(&guard);
// Set context.kind based on kind byte (0 = method, 1 = getter, 2 = setter)
let kind_str = match kind {
0 => "method",
1 => "getter",
2 => "setter",
_ => "method",
};
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("kind")),
JsValue::String(interp.intern(kind_str)),
);
// Set context.name
if let Some(n) = method_name {
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("name")),
JsValue::String(n),
);
}
// Set context.static
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("static")),
JsValue::Boolean(is_static),
);
// Set context.private
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("private")),
JsValue::Boolean(is_private),
);
// Call decorator(method, context)
let Guarded {
value,
guard: _guard,
} = interp.call_function(
decorator_val.clone(),
JsValue::Undefined,
&[method_val.clone(), JsValue::Object(ctx)],
)?;
// If decorator returns undefined, keep original method; otherwise use return value
if matches!(value, JsValue::Undefined) {
// Keep original method value in register
} else {
self.set_reg(method, value);
}
Ok(OpResult::Continue)
}
Op::ApplyParameterDecorator {
target,
decorator,
method_name,
param_name,
param_index,
is_static,
} => {
let target_val = self.get_reg(target);
let decorator_val = self.get_reg(decorator);
let method_name_str = self.get_string_constant(method_name);
let param_name_str = self.get_string_constant(param_name);
// Create decorator context object
let guard = interp.heap.create_guard();
let ctx = interp.create_object(&guard);
// Set context.kind = "parameter"
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("kind")),
JsValue::String(interp.intern("parameter")),
);
// Set context.name (parameter name)
if let Some(n) = param_name_str
&& !n.is_empty()
{
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("name")),
JsValue::String(n),
);
}
// Set context.function (method name)
if let Some(n) = method_name_str {
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("function")),
JsValue::String(n),
);
}
// Set context.index (parameter index)
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("index")),
JsValue::Number(f64::from(param_index)),
);
// Set context.static
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("static")),
JsValue::Boolean(is_static),
);
// Call decorator(target, context)
// Parameter decorators are called for side effects only (like metadata registration)
let _result = interp.call_function(
decorator_val.clone(),
JsValue::Undefined,
&[target_val.clone(), JsValue::Object(ctx)],
)?;
Ok(OpResult::Continue)
}
Op::ApplyFieldDecorator {
dst,
decorator,
name,
is_static,
is_private,
is_accessor,
} => {
let decorator_val = self.get_reg(decorator);
let field_name = self.get_string_constant(name);
// Create decorator context object
let guard = interp.heap.create_guard();
let ctx = interp.create_object(&guard);
// Set context.kind = "field" or "accessor" for auto-accessors
let kind_str = if is_accessor { "accessor" } else { "field" };
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("kind")),
JsValue::String(interp.intern(kind_str)),
);
// Set context.name
if let Some(n) = field_name {
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("name")),
JsValue::String(n),
);
}
// Set context.static
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("static")),
JsValue::Boolean(is_static),
);
// Set context.private
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("private")),
JsValue::Boolean(is_private),
);
// Call decorator(undefined, context)
// Field decorators receive undefined as first arg and return an initializer transformer
let Guarded {
value,
guard: _guard,
} = interp.call_function(
decorator_val.clone(),
JsValue::Undefined,
&[JsValue::Undefined, JsValue::Object(ctx)],
)?;
// Store the result (initializer transformer or undefined)
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::StoreFieldInitializer {
class,
name,
initializer,
} => {
let class_val = self.get_reg(class);
let initializer_val = self.get_reg(initializer);
let field_name = self
.get_string_constant(name)
.unwrap_or_else(|| interp.intern(""));
if let JsValue::Object(class_obj) = class_val {
// Get or create __field_initializers__ object
let init_key = interp.intern("__field_initializers__");
#[allow(clippy::map_clone)]
let inits_obj = {
let borrowed = class_obj.borrow();
borrowed
.get_property(&PropertyKey::String(init_key.cheap_clone()))
.map(|v| v.clone())
};
let guard = interp.heap.create_guard();
let inits = match inits_obj {
Some(JsValue::Object(obj)) => obj,
_ => {
// Create new __field_initializers__ object
let new_obj = interp.create_object_raw(&guard);
class_obj.borrow_mut().set_property(
PropertyKey::String(init_key),
JsValue::Object(new_obj.cheap_clone()),
);
new_obj
}
};
// Store the initializer for this field
inits
.borrow_mut()
.set_property(PropertyKey::String(field_name), initializer_val.clone());
}
Ok(OpResult::Continue)
}
Op::GetFieldInitializer { dst, class, name } => {
let class_val = self.get_reg(class);
let field_name = self
.get_string_constant(name)
.unwrap_or_else(|| interp.intern(""));
let mut initializer = JsValue::Undefined;
if let JsValue::Object(class_obj) = class_val {
let init_key = interp.intern("__field_initializers__");
let borrowed = class_obj.borrow();
if let Some(JsValue::Object(inits)) =
borrowed.get_property(&PropertyKey::String(init_key))
&& let Some(init) = inits
.borrow()
.get_property(&PropertyKey::String(field_name))
{
initializer = init.clone();
}
}
self.set_reg(dst, initializer);
Ok(OpResult::Continue)
}
Op::ApplyFieldInitializer { value, initializer } => {
let init_val = self.get_reg(initializer);
// If initializer is a function, call it with the value
if matches!(&init_val, JsValue::Object(_)) {
let value_val = self.get_reg(value);
let result = interp.call_function(
init_val.clone(),
JsValue::Undefined,
core::slice::from_ref(value_val),
)?;
self.set_reg(value, result.value);
}
// If initializer is undefined, keep original value
Ok(OpResult::Continue)
}
Op::DefineAutoAccessor {
class,
name,
init_value,
target_dst,
is_static,
} => {
let class_val = self.get_reg(class);
let JsValue::Object(class_obj) = class_val else {
return Err(JsError::type_error("Class is not an object"));
};
let accessor_name = self
.get_string_constant(name)
.unwrap_or_else(|| interp.intern(""));
let init_val = self.get_reg(init_value).clone();
// Create a unique storage key for this accessor
let storage_key =
interp.intern(&format!("__accessor_{}__", accessor_name.as_str()));
let guard = interp.heap.create_guard();
// Create getter function (AccessorGetter)
let getter = interp.create_object(&guard);
getter.borrow_mut().prototype = Some(interp.function_prototype.cheap_clone());
getter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__accessor_storage_key__")),
JsValue::String(storage_key.cheap_clone()),
);
getter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__accessor_init_value__")),
init_val,
);
getter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__accessor_kind__")),
JsValue::String(interp.intern("getter")),
);
getter.borrow_mut().exotic = ExoticObject::Function(JsFunction::AccessorGetter);
// Create setter function (AccessorSetter)
let setter = interp.create_object(&guard);
setter.borrow_mut().prototype = Some(interp.function_prototype.cheap_clone());
setter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__accessor_storage_key__")),
JsValue::String(storage_key),
);
setter.borrow_mut().set_property(
PropertyKey::String(interp.intern("__accessor_kind__")),
JsValue::String(interp.intern("setter")),
);
setter.borrow_mut().exotic = ExoticObject::Function(JsFunction::AccessorSetter);
// Get target object (class for static, prototype for instance)
let target = if is_static {
class_obj.cheap_clone()
} else {
let proto_key = PropertyKey::String(interp.intern("prototype"));
if let Some(JsValue::Object(proto)) =
class_obj.borrow().get_property(&proto_key)
{
proto
} else {
return Err(JsError::type_error("Class has no prototype"));
}
};
// Define the accessor property on target
let prop_key = PropertyKey::String(accessor_name.cheap_clone());
let property =
Property::accessor(Some(getter.cheap_clone()), Some(setter.cheap_clone()));
target.borrow_mut().define_property(prop_key, property);
// Create target object { get, set } for decorators
let target_obj = interp.create_object(&guard);
target_obj.borrow_mut().set_property(
PropertyKey::String(interp.intern("get")),
JsValue::Object(getter),
);
target_obj.borrow_mut().set_property(
PropertyKey::String(interp.intern("set")),
JsValue::Object(setter),
);
self.set_reg(target_dst, JsValue::Object(target_obj));
Ok(OpResult::Continue)
}
Op::StoreAutoAccessor {
class,
name,
accessor_obj,
is_static,
} => {
let class_val = self.get_reg(class);
let JsValue::Object(class_obj) = class_val else {
return Err(JsError::type_error("Class is not an object"));
};
let accessor_name = self
.get_string_constant(name)
.unwrap_or_else(|| interp.intern(""));
let accessor_val = self.get_reg(accessor_obj);
// Get target object (class for static, prototype for instance)
let target = if is_static {
class_obj.cheap_clone()
} else {
let proto_key = PropertyKey::String(interp.intern("prototype"));
if let Some(JsValue::Object(proto)) =
class_obj.borrow().get_property(&proto_key)
{
proto
} else {
return Err(JsError::type_error("Class has no prototype"));
}
};
// Extract getter and setter from the accessor object
let (final_getter, final_setter) = if let JsValue::Object(obj) = accessor_val {
let obj_ref = obj.borrow();
let get_key = interp.intern("get");
let set_key = interp.intern("set");
let getter = if let Some(JsValue::Object(g)) =
obj_ref.get_property(&PropertyKey::String(get_key))
{
Some(g.cheap_clone())
} else {
None
};
let setter = if let Some(JsValue::Object(s)) =
obj_ref.get_property(&PropertyKey::String(set_key))
{
Some(s.cheap_clone())
} else {
None
};
(getter, setter)
} else {
(None, None)
};
// Define the accessor property on target
let prop_key = PropertyKey::String(accessor_name);
let property = Property::accessor(final_getter, final_setter);
target.borrow_mut().define_property(prop_key, property);
Ok(OpResult::Continue)
}
Op::ApplyAutoAccessorDecorator {
target,
decorator,
name,
is_static,
} => {
let decorator_val = self.get_reg(decorator);
let target_val = self.get_reg(target);
let accessor_name = self.get_string_constant(name);
// Create decorator context object
let guard = interp.heap.create_guard();
let ctx = interp.create_object(&guard);
// Set context.kind = "accessor"
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("kind")),
JsValue::String(interp.intern("accessor")),
);
// Set context.name
if let Some(n) = accessor_name {
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("name")),
JsValue::String(n),
);
}
// Set context.static
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("static")),
JsValue::Boolean(is_static),
);
// Set context.private = false (public auto-accessors)
ctx.borrow_mut().set_property(
PropertyKey::String(interp.intern("private")),
JsValue::Boolean(false),
);
// Call decorator(target, context)
let Guarded {
value,
guard: _guard,
} = interp.call_function(
decorator_val.clone(),
JsValue::Undefined,
&[target_val.clone(), JsValue::Object(ctx)],
)?;
// If decorator returns an object, use it as new target
// Otherwise keep the original target
if matches!(&value, JsValue::Object(_)) {
self.set_reg(target, value);
}
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Spread/Rest
// ═══════════════════════════════════════════════════════════════════════════
Op::SpreadArray { dst, src } => {
// Spread elements from src iterable onto the dst array
// dst should already be an array - we append elements to it
let src_val = self.get_reg(src);
let dst_val = self.get_reg(dst);
let elements_to_add: Vec<JsValue> = match &src_val {
JsValue::Object(obj_ref) => {
if let Some(elems) = obj_ref.borrow().array_elements() {
elems.to_vec()
} else {
// Try iterator protocol
match interp.collect_iterator_values(src_val) {
Ok(Some(values)) => values,
Ok(None) => Vec::new(),
Err(e) => return Err(e),
}
}
}
JsValue::String(s) => s
.as_str()
.chars()
.map(|c| JsValue::String(JsString::from(c.to_string())))
.collect(),
_ => Vec::new(),
};
// Append elements to the destination array
if let JsValue::Object(dst_arr) = dst_val
&& let Some(existing) = dst_arr.borrow_mut().array_elements_mut()
{
existing.extend(elements_to_add);
}
Ok(OpResult::Continue)
}
// NOTE: review
Op::CreateRestArray { dst, start_index } => {
// Create an array from remaining iterator elements
// This is used for rest patterns like [...rest] = arr
// The iterator state is assumed to be in the register before this one
// We need to collect all remaining elements from the current iterator
// For now, this opcode is context-dependent - it needs the iterator
// that was being used. We'll check if there's an internal iterator in scope.
// This is a simplified implementation that works with the pattern compiler.
// Look for the iterator in a previous register (typically dst - 3 based on pattern)
// This is a heuristic - the pattern compiler allocates registers in a specific order
let iter_reg = dst.saturating_sub(3);
let iter_val = self.get_reg(iter_reg);
let mut elements = Vec::new();
if let JsValue::Object(iter_obj) = iter_val {
// Check for internal array iterator
let array_prop = iter_obj
.borrow()
.get_property(&PropertyKey::String(interp.intern("__array__")));
if let Some(JsValue::Object(arr_ref)) = array_prop {
let index = match iter_obj
.borrow()
.get_property(&PropertyKey::String(interp.intern("__index__")))
{
Some(JsValue::Number(n)) => n as usize,
_ => start_index as usize,
};
if let Some(elems) = arr_ref.borrow().array_elements() {
for i in index..elems.len() {
if let Some(val) = elems.get(i) {
elements.push(val.clone());
}
}
}
}
}
let guard = interp.heap.create_guard();
let arr = interp.create_array_from(&guard, elements);
self.set_reg(dst, JsValue::Object(arr));
Ok(OpResult::Continue)
}
Op::CreateObjectRest {
dst,
src,
excluded_keys,
} => {
// Create an object with all properties from src except excluded_keys
let src_val = self.get_reg(src);
// Get excluded keys from constant pool
let excluded = match self.chunk.constants.get(excluded_keys as usize) {
Some(Constant::ExcludedKeys(keys)) => keys,
_ => &vec![],
};
let guard = interp.heap.create_guard();
let result = interp.create_object(&guard);
if let JsValue::Object(src_obj) = src_val {
// Copy all enumerable own properties except excluded ones
let src_borrowed = src_obj.borrow();
for (key, prop) in src_borrowed.properties.iter() {
// Skip non-enumerable properties
if !prop.enumerable() {
continue;
}
// Check if this key should be excluded
let should_exclude = match key {
PropertyKey::String(s) => {
excluded.iter().any(|k| k.as_str() == s.as_str())
}
PropertyKey::Symbol(_) | PropertyKey::Index(_) => false,
};
if !should_exclude {
result
.borrow_mut()
.set_property(key.clone(), prop.value.clone());
}
}
}
self.set_reg(dst, JsValue::Object(result));
Ok(OpResult::Continue)
}
Op::SpreadObject { dst, src } => {
// Copy all enumerable own properties from src to dst
let dst_val = self.get_reg(dst);
let src_val = self.get_reg(src);
if let (JsValue::Object(dst_obj), JsValue::Object(src_obj)) = (dst_val, src_val) {
// Collect properties first to avoid borrow issues
let props_to_copy: Vec<_> = {
let src_borrowed = src_obj.borrow();
src_borrowed
.properties
.iter()
.filter(|(_, prop)| prop.enumerable())
.map(|(key, prop)| (key.clone(), prop.value.clone()))
.collect()
};
// Copy properties to destination
let mut dst_borrowed = dst_obj.borrow_mut();
for (key, value) in props_to_copy {
dst_borrowed.set_property(key, value);
}
}
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Template Literals
// ═══════════════════════════════════════════════════════════════════════════
Op::TemplateConcat { dst, start, count } => {
let mut result = String::new();
let to_string_key = PropertyKey::String(interp.intern("toString"));
for i in 0..count {
let val = self.get_reg(start + i);
// For objects, call toString method; for primitives, use to_js_string
let str_val = if let JsValue::Object(obj) = &val {
// Check if object has a custom toString method
if let Some(JsValue::Object(func_obj)) =
obj.borrow().get_property(&to_string_key)
{
if func_obj.borrow().is_callable() {
// Call toString()
match interp.call_function(
JsValue::Object(func_obj.clone()),
val.clone(),
&[],
) {
Ok(Guarded { value, guard: _ }) => interp.to_js_string(&value),
Err(_) => interp.to_js_string(val),
}
} else {
interp.to_js_string(val)
}
} else {
interp.to_js_string(val)
}
} else {
interp.to_js_string(val)
};
result.push_str(str_val.as_str());
}
self.set_reg(dst, JsValue::String(JsString::from(result)));
Ok(OpResult::Continue)
}
Op::TaggedTemplate {
dst,
tag,
this,
template,
exprs_start,
exprs_count,
} => {
// Get the template strings constant
let template_const =
self.chunk.constants.get(template as usize).ok_or_else(|| {
JsError::internal_error("Invalid template constant index")
})?;
let (cooked, raw) = match template_const {
Constant::TemplateStrings { cooked, raw } => (cooked.clone(), raw.clone()),
_ => return Err(JsError::internal_error("Expected TemplateStrings constant")),
};
// Create the strings array (cooked strings)
let guard = interp.heap.create_guard();
let strings: Vec<JsValue> = cooked
.iter()
.map(|s| JsValue::String(s.cheap_clone()))
.collect();
let strings_arr = interp.create_array_from(&guard, strings);
// Create the raw strings array
let raw_strings: Vec<JsValue> = raw
.iter()
.map(|s| JsValue::String(s.cheap_clone()))
.collect();
let raw_arr = interp.create_array_from(&guard, raw_strings);
// Add 'raw' property to strings array
let raw_key = PropertyKey::String(interp.intern("raw"));
strings_arr
.borrow_mut()
.set_property(raw_key, JsValue::Object(raw_arr));
// Build args: [strings_array, ...expressions]
let mut args = vec![JsValue::Object(strings_arr)];
for i in 0..exprs_count {
args.push(self.get_reg(exprs_start + i).clone());
}
// Get the tag function and this value
let tag_fn = self.get_reg(tag);
let this_val = self.get_reg(this);
// Call the tag function
let Guarded {
value,
guard: _guard,
} = interp.call_function(tag_fn.clone(), this_val.clone(), &args)?;
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Function Name Inference
// ═══════════════════════════════════════════════════════════════════════════
Op::SetFunctionName { func, name } => {
let func_val = self.get_reg(func);
let name_str = self
.get_string_constant(name)
.ok_or_else(|| JsError::internal_error("Invalid function name constant"))?;
// Only set name if value is a function object without a name
if let JsValue::Object(obj) = func_val {
let mut obj_ref = obj.borrow_mut();
// Check if this is a function and if it doesn't have a name already
let should_set_name =
if let crate::value::ExoticObject::Function(func) = &obj_ref.exotic {
// Check if function already has a non-empty name
let has_name = match func {
JsFunction::Native(f) => !f.name.as_str().is_empty(),
JsFunction::Bytecode(bc)
| JsFunction::BytecodeGenerator(bc)
| JsFunction::BytecodeAsync(bc)
| JsFunction::BytecodeAsyncGenerator(bc) => bc
.chunk
.function_info
.as_ref()
.and_then(|info| info.name.as_ref())
.is_some_and(|n| !n.as_str().is_empty()),
JsFunction::Bound(_) => true, // Bound functions already have names
// Internal functions don't need names set
JsFunction::PromiseResolve(_)
| JsFunction::PromiseReject(_)
| JsFunction::PromiseAllFulfill { .. }
| JsFunction::PromiseAllReject(_)
| JsFunction::PromiseRaceSettle { .. }
| JsFunction::AccessorGetter
| JsFunction::AccessorSetter
| JsFunction::ModuleExportGetter { .. }
| JsFunction::ModuleReExportGetter { .. }
| JsFunction::ProxyRevoke(_) => true,
};
// Also check if there's already an own name property set
let name_key = PropertyKey::String(interp.intern("name"));
let has_own_name = obj_ref.get_own_property(&name_key).is_some();
!has_name && !has_own_name
} else {
false // Not a function
};
if should_set_name {
let name_key = PropertyKey::String(interp.intern("name"));
obj_ref.define_property(
name_key,
Property::with_attributes(
JsValue::String(name_str),
false, // not writable
false, // not enumerable
true, // configurable
),
);
}
}
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Miscellaneous
// ═══════════════════════════════════════════════════════════════════════════
Op::Nop => Ok(OpResult::Continue),
Op::Halt => {
let result = self
.registers
.first()
.cloned()
.unwrap_or(JsValue::Undefined);
Ok(OpResult::Halt(Guarded::from_value(result, &interp.heap)))
}
Op::Debugger => Ok(OpResult::Continue),
Op::Pop => Ok(OpResult::Continue),
Op::Dup { dst, src } => {
let value = self.get_reg(src).clone();
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::LoadThis { dst } => {
self.set_reg(dst, self.this_value.clone());
Ok(OpResult::Continue)
}
Op::LoadArguments { dst } => {
// Create an arguments object (array-like) from the stored arguments
let guard = interp.heap.create_guard();
let args_array = interp.create_array_from(&guard, self.arguments.clone());
self.set_reg(dst, JsValue::Object(args_array));
Ok(OpResult::Continue)
}
Op::LoadNewTarget { dst } => {
// Return the new.target value
self.set_reg(dst, self.new_target.clone());
Ok(OpResult::Continue)
}
Op::GetPrivateField {
dst,
obj,
class_brand,
field_name,
} => {
let obj_val = self.get_reg(obj);
let field_name_str = self.get_string_constant(field_name).ok_or_else(|| {
JsError::internal_error("Invalid private field name constant")
})?;
let JsValue::Object(obj_ref) = obj_val else {
return Err(JsError::type_error(format!(
"Cannot read private member {} from non-object",
field_name_str
)));
};
let key = crate::value::PrivateFieldKey::new(class_brand, field_name_str);
let value = obj_ref
.borrow()
.get_private_field(&key)
.cloned()
.ok_or_else(|| {
JsError::type_error(format!(
"Cannot read private member {} from an object whose class did not declare it",
key.field_name
))
})?;
self.set_reg(dst, value);
Ok(OpResult::Continue)
}
Op::SetPrivateField {
obj,
class_brand,
field_name,
value,
} => {
let obj_val = self.get_reg(obj);
let field_name_str = self.get_string_constant(field_name).ok_or_else(|| {
JsError::internal_error("Invalid private field name constant")
})?;
let val = self.get_reg(value).clone();
let JsValue::Object(obj_ref) = obj_val else {
return Err(JsError::type_error(format!(
"Cannot write private member {} to non-object",
field_name_str
)));
};
let key =
crate::value::PrivateFieldKey::new(class_brand, field_name_str.cheap_clone());
// Check that this object has this private field (brand check)
if !obj_ref.borrow().has_private_field(&key) {
return Err(JsError::type_error(format!(
"Cannot write private member {} to an object whose class did not declare it",
field_name_str
)));
}
obj_ref.borrow_mut().set_private_field(key, val);
Ok(OpResult::Continue)
}
Op::DefinePrivateField {
obj,
class_brand,
field_name,
value,
} => {
let obj_val = self.get_reg(obj);
let field_name_str = self.get_string_constant(field_name).ok_or_else(|| {
JsError::internal_error("Invalid private field name constant")
})?;
let val = self.get_reg(value).clone();
let JsValue::Object(obj_ref) = obj_val else {
return Err(JsError::type_error(
"Cannot define private field on non-object",
));
};
let key = crate::value::PrivateFieldKey::new(class_brand, field_name_str);
obj_ref.borrow_mut().set_private_field(key, val);
Ok(OpResult::Continue)
}
Op::DefinePrivateMethod {
class,
class_brand,
method_name,
method,
is_static,
} => {
let class_val = self.get_reg(class);
let method_name_str = self.get_string_constant(method_name).ok_or_else(|| {
JsError::internal_error("Invalid private method name constant")
})?;
let method_val = self.get_reg(method).clone();
let JsValue::Object(class_obj) = class_val else {
return Err(JsError::type_error("Class is not an object"));
};
// For static private methods, install directly on the class constructor
if is_static {
let key = crate::value::PrivateFieldKey::new(class_brand, method_name_str);
class_obj.borrow_mut().set_private_field(key, method_val);
} else {
// For instance private methods, we store them on the constructor
// under a special key (__private_methods__) so that the constructor
// can install them on new instances.
// Each class stores its private methods in a map keyed by field name.
let private_methods_key =
PropertyKey::String(interp.intern("__private_methods__"));
let methods_map = {
let class_borrowed = class_obj.borrow();
class_borrowed
.get_own_property(&private_methods_key)
.and_then(|p| {
if let JsValue::Object(obj) = &p.value {
Some(obj.cheap_clone())
} else {
None
}
})
};
let methods_obj = if let Some(existing) = methods_map {
existing
} else {
// Create a new object to store private methods
let guard = interp.heap.create_guard();
let new_obj = interp.create_object_raw(&guard);
class_obj.borrow_mut().set_property(
private_methods_key.clone(),
JsValue::Object(new_obj.cheap_clone()),
);
new_obj
};
// Store method with a key that includes class_brand for brand checking
// Key format: "brand:field_name"
let storage_key = PropertyKey::String(JsString::from(format!(
"{}:{}",
class_brand,
method_name_str.as_str()
)));
methods_obj
.borrow_mut()
.set_property(storage_key, method_val);
}
Ok(OpResult::Continue)
}
Op::InstallPrivateMethod {
class_brand,
method_name,
} => {
let method_name_str = self.get_string_constant(method_name).ok_or_else(|| {
JsError::internal_error("Invalid private method name constant")
})?;
// Get new.target (the class constructor)
let JsValue::Object(new_target) = &self.new_target else {
return Err(JsError::internal_error(
"InstallPrivateMethod requires new.target to be an object",
));
};
// Get __private_methods__ from new.target
let private_methods_key = PropertyKey::String(interp.intern("__private_methods__"));
let methods_obj = {
let new_target_borrowed = new_target.borrow();
new_target_borrowed
.get_own_property(&private_methods_key)
.and_then(|p| {
if let JsValue::Object(obj) = &p.value {
Some(obj.cheap_clone())
} else {
None
}
})
};
if let Some(methods) = methods_obj {
// Look up method by brand:name key
let storage_key = PropertyKey::String(interp.intern(&format!(
"{}:{}",
class_brand,
method_name_str.as_str()
)));
let method_val = methods
.borrow()
.get_own_property(&storage_key)
.map(|p| p.value.clone())
.unwrap_or(JsValue::Undefined);
if !matches!(method_val, JsValue::Undefined) {
// Install on this
let this_val = self.this_value.clone();
let JsValue::Object(this_obj) = this_val else {
return Err(JsError::type_error("this is not an object"));
};
let key = crate::value::PrivateFieldKey::new(class_brand, method_name_str);
this_obj.borrow_mut().set_private_field(key, method_val);
}
}
Ok(OpResult::Continue)
}
// ═══════════════════════════════════════════════════════════════════════════
// Module Operations
// ═══════════════════════════════════════════════════════════════════════════
Op::ExportBinding {
export_name,
binding_name,
value,
} => {
let export_name_str = self
.get_string_constant(export_name)
.ok_or_else(|| JsError::internal_error("Invalid export name constant"))?;
let binding_name_str = self
.get_string_constant(binding_name)
.ok_or_else(|| JsError::internal_error("Invalid binding name constant"))?;
let val = self.get_reg(value).clone();
// Store in interpreter's exports map
interp.exports.insert(
export_name_str,
crate::value::ModuleExport::Direct {
name: binding_name_str,
value: val,
},
);
Ok(OpResult::Continue)
}
Op::ExportNamespace {
export_name,
module_specifier,
} => {
let export_name_str = self
.get_string_constant(export_name)
.ok_or_else(|| JsError::internal_error("Invalid export name constant"))?;
let specifier_str = self
.get_string_constant(module_specifier)
.ok_or_else(|| JsError::internal_error("Invalid module specifier constant"))?;
// Resolve the module and get its namespace object
let module_obj = interp.resolve_module(specifier_str.as_ref())?;
// Store the module namespace as a direct export
// (not a live binding - namespace objects are already live)
interp.exports.insert(
export_name_str.cheap_clone(),
crate::value::ModuleExport::Direct {
name: export_name_str,
value: JsValue::Object(module_obj),
},
);
Ok(OpResult::Continue)
}
Op::ReExport {
export_name,
source_module,
source_key,
} => {
let export_name_str = self
.get_string_constant(export_name)
.ok_or_else(|| JsError::internal_error("Invalid export name constant"))?;
let source_specifier = self
.get_string_constant(source_module)
.ok_or_else(|| JsError::internal_error("Invalid source module constant"))?;
let source_key_str = self
.get_string_constant(source_key)
.ok_or_else(|| JsError::internal_error("Invalid source key constant"))?;
// Resolve the source module
let source_module_obj = interp.resolve_module(source_specifier.as_ref())?;
// Store as a re-export with delegation to the source module
interp.exports.insert(
export_name_str,
crate::value::ModuleExport::ReExport {
source_module: source_module_obj,
source_key: PropertyKey::String(source_key_str),
},
);
Ok(OpResult::Continue)
}
}
}
/// Get a property value from an object, invoking getters if present.
/// Returns a Guarded to keep newly allocated objects alive (e.g., from getters or proxies).
fn get_property_value(
&self,
interp: &mut Interpreter,
obj: &JsValue,
key: &JsValue,
) -> Result<Guarded, JsError> {
match obj {
JsValue::Object(obj_ref) => {
// Check if this is a proxy - delegate to proxy_get if so
if matches!(obj_ref.borrow().exotic, ExoticObject::Proxy(_)) {
let prop_key = interp.property_key_from_value(key);
// proxy_get already returns Guarded
return crate::interpreter::builtins::proxy::proxy_get(
interp,
obj_ref.cheap_clone(),
prop_key,
obj.clone(),
);
}
// Handle __proto__ special property - return prototype
if let JsValue::String(k) = key
&& k.as_str() == "__proto__"
{
return Ok(Guarded::unguarded(
obj_ref
.borrow()
.prototype
.as_ref()
.map(|p| JsValue::Object(p.clone()))
.unwrap_or(JsValue::Null),
));
}
let prop_key = interp.property_key_from_value(key);
// Get property descriptor to check for accessor properties
let prop_desc = obj_ref.borrow().get_property_descriptor(&prop_key);
match prop_desc {
Some((prop, _)) if prop.is_accessor() => {
// Property has a getter - invoke it
if let Some(getter) = prop.getter() {
// call_function already returns Guarded
interp.call_function(JsValue::Object(getter.clone()), obj.clone(), &[])
} else {
Ok(Guarded::unguarded(JsValue::Undefined))
}
}
Some((prop, _)) => Ok(Guarded::unguarded(prop.value.clone())),
None => Ok(Guarded::unguarded(JsValue::Undefined)),
}
}
JsValue::String(s) => match key {
JsValue::String(k) if k.as_str() == "length" => Ok(Guarded::unguarded(
JsValue::Number(s.as_str().chars().count() as f64),
)),
JsValue::Number(n) => {
let idx = *n as usize;
if let Some(c) = s.as_str().chars().nth(idx) {
return Ok(Guarded::unguarded(JsValue::String(JsString::from(
c.to_string(),
))));
}
Ok(Guarded::unguarded(JsValue::Undefined))
}
_ => {
let prop_key = interp.property_key_from_value(key);
if let Some(val) = interp.string_prototype.borrow().get_property(&prop_key) {
Ok(Guarded::unguarded(val.clone()))
} else {
Ok(Guarded::unguarded(JsValue::Undefined))
}
}
},
JsValue::Number(_) => {
let prop_key = interp.property_key_from_value(key);
if let Some(val) = interp.number_prototype.borrow().get_property(&prop_key) {
Ok(Guarded::unguarded(val.clone()))
} else {
Ok(Guarded::unguarded(JsValue::Undefined))
}
}
JsValue::Boolean(_) => {
let prop_key = interp.property_key_from_value(key);
if let Some(val) = interp.boolean_prototype.borrow().get_property(&prop_key) {
Ok(Guarded::unguarded(val.clone()))
} else {
Ok(Guarded::unguarded(JsValue::Undefined))
}
}
JsValue::Null => Err(JsError::type_error("Cannot read properties of null")),
JsValue::Undefined => Err(JsError::type_error("Cannot read properties of undefined")),
JsValue::Symbol(sym) => {
// Symbols have a description property
if let JsValue::String(k) = key
&& k.as_str() == "description"
{
return Ok(Guarded::unguarded(
sym.description
.as_ref()
.map(|d| JsValue::String(d.cheap_clone()))
.unwrap_or(JsValue::Undefined),
));
}
// Other symbol prototype methods
let prop_key = interp.property_key_from_value(key);
if let Some(val) = interp.symbol_prototype.borrow().get_property(&prop_key) {
Ok(Guarded::unguarded(val.clone()))
} else {
Ok(Guarded::unguarded(JsValue::Undefined))
}
}
}
}
/// Set a property value on an object, invoking setters if present
fn set_property_value(
&self,
interp: &mut Interpreter,
obj: &JsValue,
key: &JsValue,
value: JsValue,
) -> Result<(), JsError> {
match obj {
JsValue::Object(obj_ref) => {
// Check if this is a proxy - delegate to proxy_set if so
if matches!(obj_ref.borrow().exotic, ExoticObject::Proxy(_)) {
let prop_key = interp.property_key_from_value(key);
crate::interpreter::builtins::proxy::proxy_set(
interp,
obj_ref.cheap_clone(),
prop_key,
value,
obj.clone(),
)?;
return Ok(());
}
// Handle __proto__ special property - set prototype
if let JsValue::String(k) = key
&& k.as_str() == "__proto__"
{
match &value {
JsValue::Object(proto) => {
obj_ref.borrow_mut().prototype = Some(proto.clone());
}
JsValue::Null => {
obj_ref.borrow_mut().prototype = None;
}
_ => {
// Non-object, non-null values are ignored for __proto__ set
}
}
return Ok(());
}
let prop_key = interp.property_key_from_value(key);
// Check if object is frozen/sealed or property is non-writable
// First, check for accessor or non-writable property (including prototype chain)
let setter_to_call = {
let obj_borrowed = obj_ref.borrow();
// Use get_property_descriptor to search prototype chain for setters
if let Some((prop, _from_proto)) =
obj_borrowed.get_property_descriptor(&prop_key)
{
if prop.is_accessor() {
// Clone setter for later invocation
Some(prop.setter().cloned())
} else if !prop.writable() {
return Err(JsError::type_error(format!(
"Cannot assign to read only property '{}'",
prop_key
)));
} else {
None
}
} else if !obj_borrowed.extensible {
return Err(JsError::type_error(format!(
"Cannot add property '{}' to non-extensible object",
prop_key
)));
} else {
None
}
};
// Call setter if we have one
if let Some(maybe_setter) = setter_to_call {
if let Some(setter) = maybe_setter {
interp.call_function(JsValue::Object(setter), obj.clone(), &[value])?;
} else {
// Accessor property with no setter - throw TypeError in strict mode
return Err(JsError::type_error(format!(
"Cannot set property '{}' which has only a getter",
prop_key
)));
}
// Accessor property handled, return
return Ok(());
}
// Regular data property
obj_ref.borrow_mut().set_property(prop_key, value);
Ok(())
}
JsValue::Null => Err(JsError::type_error("Cannot set properties of null")),
JsValue::Undefined => Err(JsError::type_error("Cannot set properties of undefined")),
_ => Ok(()),
}
}
/// Execute a return, running any pending finally blocks first
// NOTE: review
fn execute_return(
&mut self,
return_val: JsValue,
interp: &mut Interpreter,
) -> Result<OpResult, JsError> {
// Check if there's a try handler with a finally block that needs to run
// We need to find try handlers for the current function (same call frame depth)
let current_frame_depth = self.call_stack.len();
// Find try handlers that belong to the current function
if let Some(handler_idx) = self
.try_stack
.iter()
.rposition(|h| h.frame_depth == current_frame_depth && h.finally_ip != 0)
{
// There's a finally block that needs to run
let handler = self
.try_stack
.get(handler_idx)
.cloned()
.ok_or_else(|| JsError::internal_error("Missing try handler"))?;
// Save the pending return with a guard to keep it alive during finally execution
self.pending_completion = Some(PendingCompletion::Return(Guarded::from_value(
return_val,
&interp.heap,
)));
// Pop the try handler (we're exiting this try block)
self.try_stack.truncate(handler_idx);
// Jump to the finally block
self.ip = handler.finally_ip;
return Ok(OpResult::Continue);
}
// No finally block, do normal return
if let Some(frame) = self.call_stack.pop() {
self.ip = frame.return_ip;
self.chunk = frame.return_chunk;
self.registers.truncate(frame.registers_base);
if let Some(env) = frame.saved_env {
interp.env = env;
}
self.set_reg(frame.return_register, return_val);
Ok(OpResult::Continue)
} else {
Ok(OpResult::Halt(Guarded::from_value(
return_val,
&interp.heap,
)))
}
}
/// Execute a break, running any pending finally blocks first.
/// scope_depth is the saved_env_stack depth to unwind to at the target.
fn execute_break(
&mut self,
target: usize,
try_depth: u8,
scope_depth: u32,
interp: &mut Interpreter,
) -> Result<OpResult, JsError> {
// Check if there's a try handler with a finally block between us and the target
let target_try_depth = try_depth as usize;
// Find the first try handler ABOVE target depth that has a finally block
if let Some(handler_idx) = self
.try_stack
.iter()
.enumerate()
.skip(target_try_depth)
.find(|(_, h)| h.finally_ip != 0)
.map(|(i, _)| i)
{
// There's a finally block that needs to run
let handler = self
.try_stack
.get(handler_idx)
.cloned()
.ok_or_else(|| JsError::internal_error("Missing try handler"))?;
// Save the pending break (scope_depth preserved for after finally)
self.pending_completion = Some(PendingCompletion::Break {
target,
try_depth,
scope_depth,
});
// Pop the try handler (we're exiting this try block)
self.try_stack.truncate(handler_idx);
// Jump to the finally block
self.ip = handler.finally_ip;
return Ok(OpResult::Continue);
}
// No finally block, do normal break (just jump)
// Unwind any scopes between the current position and the break target
let target_scope = scope_depth as usize;
while self.saved_env_stack.len() > target_scope {
if let Some(saved_env) = self.saved_env_stack.pop() {
interp.pop_scope(saved_env);
}
}
// Also pop try handlers down to the target level
self.try_stack.truncate(target_try_depth);
self.ip = target;
Ok(OpResult::Continue)
}
/// Execute a continue, running any pending finally blocks first.
/// scope_depth is the saved_env_stack depth to unwind to at the target.
fn execute_continue(
&mut self,
target: usize,
try_depth: u8,
scope_depth: u32,
interp: &mut Interpreter,
) -> Result<OpResult, JsError> {
// Check if there's a try handler with a finally block between us and the target
let target_try_depth = try_depth as usize;
// Find the first try handler ABOVE target depth that has a finally block
if let Some(handler_idx) = self
.try_stack
.iter()
.enumerate()
.skip(target_try_depth)
.find(|(_, h)| h.finally_ip != 0)
.map(|(i, _)| i)
{
// There's a finally block that needs to run
let handler = self
.try_stack
.get(handler_idx)
.cloned()
.ok_or_else(|| JsError::internal_error("Missing try handler"))?;
// Save the pending continue (scope_depth preserved for after finally)
self.pending_completion = Some(PendingCompletion::Continue {
target,
try_depth,
scope_depth,
});
// Pop the try handler (we're exiting this try block)
self.try_stack.truncate(handler_idx);
// Jump to the finally block
self.ip = handler.finally_ip;
return Ok(OpResult::Continue);
}
// No finally block, do normal continue (just jump)
// Unwind any scopes between the current position and the continue target
let target_scope = scope_depth as usize;
while self.saved_env_stack.len() > target_scope {
if let Some(saved_env) = self.saved_env_stack.pop() {
interp.pop_scope(saved_env);
}
}
// Also pop try handlers down to the target level
self.try_stack.truncate(target_try_depth);
self.ip = target;
Ok(OpResult::Continue)
}
}
/// Result of executing a single opcode
enum OpResult {
/// Continue to next instruction
Continue,
/// Halt with a value
Halt(Guarded),
/// Suspend execution (for await on Promise)
Suspend {
promise: Guarded,
resume_register: Register,
},
/// Suspend for order fulfillment from host
SuspendForOrder {
order_id: crate::OrderId,
resume_register: Register,
},
/// Yield a value (for generators)
Yield {
value: Guarded,
resume_register: Register,
},
/// Yield* delegate to another iterator
YieldStar {
iterable: Guarded,
resume_register: Register,
},
/// Call a function (for trampoline)
Call {
callee: JsValue,
this_value: JsValue,
args: Vec<JsValue>,
return_register: Register,
new_target: JsValue,
/// If true, this is a super() call and the callee should be set as current_constructor
is_super_call: bool,
/// Guard keeping all object values alive between OpResult creation and trampoline handling
guard: Guard<JsObject>,
},
/// Construct a new object (for trampoline)
Construct {
callee: JsValue,
this_value: JsValue,
args: Vec<JsValue>,
return_register: Register,
new_target: JsValue,
/// The new object to use if constructor doesn't return an object
new_obj: Gc<JsObject>,
/// Guard keeping all object values alive between OpResult creation and trampoline handling
guard: Guard<JsObject>,
},
}