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
//! Interpreter for executing TypeScript AST
//!
//! This module implements a minimal interpreter using the new guard-based GC.
// Builtin function implementations
pub mod builtins;
// Bytecode virtual machine
pub mod bytecode_vm;
use crate::prelude::*;
// Platform provider imports based on target/features
use crate::platform::{ConsoleLevel, ConsoleProvider, RandomProvider, TimeProvider};
#[cfg(not(feature = "std"))]
use crate::platform::{NoOpConsoleProvider, NoOpRandomProvider, NoOpTimeProvider};
#[cfg(feature = "std")]
use crate::platform::{StdConsoleProvider, StdRandomProvider, StdTimeProvider};
// RegExp provider imports
#[cfg(feature = "regex")]
use crate::platform::FancyRegexProvider;
#[cfg(not(feature = "regex"))]
use crate::platform::NoOpRegExpProvider;
use crate::platform::RegExpProvider;
use crate::StepResult;
use crate::ast::{ImportSpecifier, Program, Statement};
use crate::error::JsError;
use crate::gc::{Gc, Guard, Heap};
use crate::parser::Parser;
use crate::string_dict::StringDict;
use crate::value::{
Binding, BytecodeFunction, BytecodeGeneratorState, CheapClone, EnvRef, EnvironmentData,
ExoticObject, GeneratorStatus, Guarded, ImportBinding, JsFunction, JsObject, JsString,
JsSymbol, JsValue, ModuleExport, NativeFn, NativeFunction, PromiseStatus, Property,
PropertyKey, VarKey, create_environment_unrooted, create_environment_unrooted_with_capacity,
};
use self::builtins::symbol::WellKnownSymbols;
// Re-export Guarded from value module - see value.rs for documentation
/// A stack frame for tracking call stack
#[derive(Debug, Clone)]
pub struct StackFrame {
/// Function name (or "<anonymous>" for anonymous functions)
pub function_name: String,
/// Source location if available
pub location: Option<(u32, u32)>, // (line, column)
}
// ═══════════════════════════════════════════════════════════════════════════════
// Async Context Management Types
// ═══════════════════════════════════════════════════════════════════════════════
/// Unique identifier for a suspended async context
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ContextId(pub u64);
/// Unique identifier for tracking Promises in the wait graph
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PromiseId(pub u64);
/// A suspended async execution context
pub struct SuspendedContext {
/// Unique identifier for this context
pub id: ContextId,
/// Saved VM state (registers, call frames, etc.)
pub state: bytecode_vm::SavedVmState,
/// The Promise this context is waiting on
pub waiting_on: Gc<JsObject>,
/// Promise ID for quick lookup in the wait graph
pub waiting_on_id: PromiseId,
/// Register to store the resolved value when resumed
pub resume_register: crate::compiler::Register,
}
/// Tracks all suspended async contexts and their Promise dependencies
#[derive(Default)]
pub struct WaitGraph {
/// All suspended contexts, indexed by ContextId
pub contexts: FxHashMap<ContextId, SuspendedContext>,
/// Promise → contexts waiting on it
/// When a Promise resolves, we look up all waiters here
pub promise_waiters: FxHashMap<PromiseId, Vec<ContextId>>,
/// Contexts ready to resume (their Promise has resolved)
pub ready_queue: VecDeque<ContextId>,
}
impl WaitGraph {
/// Create an empty wait graph
pub fn new() -> Self {
Self::default()
}
/// Add a suspended context to the graph
pub fn add_context(&mut self, ctx: SuspendedContext) {
let ctx_id = ctx.id;
let promise_id = ctx.waiting_on_id;
self.promise_waiters
.entry(promise_id)
.or_default()
.push(ctx_id);
self.contexts.insert(ctx_id, ctx);
}
/// Called when a Promise is resolved - moves waiters to ready queue
pub fn promise_resolved(&mut self, promise_id: PromiseId) {
if let Some(waiter_ids) = self.promise_waiters.remove(&promise_id) {
for ctx_id in waiter_ids {
self.ready_queue.push_back(ctx_id);
}
}
}
/// Take the next ready context for execution
pub fn take_ready(&mut self) -> Option<SuspendedContext> {
while let Some(ctx_id) = self.ready_queue.pop_front() {
if let Some(ctx) = self.contexts.remove(&ctx_id) {
return Some(ctx);
}
// Context was cancelled/removed, skip it
}
None
}
/// Check if any contexts are waiting
pub fn has_waiting_contexts(&self) -> bool {
!self.contexts.is_empty()
}
}
// OrderSuspension is now VmOrderSuspension in bytecode_vm.rs
/// The interpreter state
pub struct Interpreter {
// ═══════════════════════════════════════════════════════════════════════════
// GC Infrastructure
// ═══════════════════════════════════════════════════════════════════════════
/// The GC heap managing all objects
pub heap: Heap<JsObject>,
/// Root guard for permanent objects (prototypes, global, global_env)
root_guard: Guard<JsObject>,
// ═══════════════════════════════════════════════════════════════════════════
// Global State
// ═══════════════════════════════════════════════════════════════════════════
/// Global object
pub global: Gc<JsObject>,
/// Global environment (variable bindings for global scope)
pub global_env: EnvRef,
/// Current execution environment
pub env: EnvRef,
/// Stack of guards for environments (keeps them alive during execution).
/// Environments are pushed when entering scopes and popped when leaving.
/// This ensures that environments on the execution stack remain alive.
env_guards: Vec<Guard<JsObject>>,
/// String dictionary for interning strings
pub string_dict: StringDict,
// ═══════════════════════════════════════════════════════════════════════════
// Prototypes (all rooted via root_guard)
// ═══════════════════════════════════════════════════════════════════════════
/// Object.prototype
pub object_prototype: Gc<JsObject>,
/// Array.prototype
pub array_prototype: Gc<JsObject>,
/// Function.prototype
pub function_prototype: Gc<JsObject>,
/// String.prototype (for string primitive methods)
pub string_prototype: Gc<JsObject>,
/// Number.prototype (for number primitive methods)
pub number_prototype: Gc<JsObject>,
/// Boolean.prototype (for boolean primitive methods)
pub boolean_prototype: Gc<JsObject>,
/// RegExp.prototype (for regexp methods)
pub regexp_prototype: Gc<JsObject>,
/// Map.prototype (for Map methods)
pub map_prototype: Gc<JsObject>,
/// Set.prototype (for Set methods)
pub set_prototype: Gc<JsObject>,
/// Date.prototype (for Date methods)
pub date_prototype: Gc<JsObject>,
/// Symbol.prototype (for Symbol methods)
pub symbol_prototype: Gc<JsObject>,
/// Promise.prototype (for Promise methods)
pub promise_prototype: Gc<JsObject>,
/// Generator.prototype (for generator methods)
pub generator_prototype: Gc<JsObject>,
// ═══════════════════════════════════════════════════════════════════════════
// Error Prototypes (for creating proper error objects from JsError)
// ═══════════════════════════════════════════════════════════════════════════
/// Error.prototype
pub error_prototype: Gc<JsObject>,
/// TypeError.prototype
pub type_error_prototype: Gc<JsObject>,
/// ReferenceError.prototype
pub reference_error_prototype: Gc<JsObject>,
/// RangeError.prototype
pub range_error_prototype: Gc<JsObject>,
/// SyntaxError.prototype
pub syntax_error_prototype: Gc<JsObject>,
// ═══════════════════════════════════════════════════════════════════════════
// Execution State
// ═══════════════════════════════════════════════════════════════════════════
/// Exported values from the module
/// Uses ModuleExport to distinguish direct exports (with live bindings) from re-exports
pub exports: FxHashMap<JsString, ModuleExport>,
/// Call stack for stack traces
pub call_stack: Vec<StackFrame>,
/// Counter for generating unique generator IDs
next_generator_id: u64,
/// Counter for generating unique symbol IDs
next_symbol_id: u64,
/// Symbol registry for Symbol.for() / Symbol.keyFor()
symbol_registry: FxHashMap<JsString, JsSymbol>,
/// Well-known symbols (Symbol.iterator, Symbol.toStringTag, etc.)
pub well_known_symbols: WellKnownSymbols,
/// Console timers for console.time() / console.timeEnd()
/// Stores timer start values from TimeProvider::start_timer()
console_timers: FxHashMap<String, u64>,
/// Console counters for console.count() / console.countReset()
console_counters: FxHashMap<String, u64>,
/// Current FFI callback ID (set before calling native functions with ffi_id > 0)
/// Used by the FFI layer to look up C callbacks
pub current_ffi_id: usize,
/// FFI context pointer (set during tsrun_step/tsrun_run)
/// Used by native callback trampoline to access TsRunContext
#[cfg(feature = "c-api")]
pub(crate) ffi_context: *mut core::ffi::c_void,
// ═══════════════════════════════════════════════════════════════════════════
// Platform Providers
// ═══════════════════════════════════════════════════════════════════════════
/// Time provider for Date.now(), console.time(), etc.
time_provider: Box<dyn TimeProvider>,
/// Random provider for Math.random()
random_provider: Box<dyn RandomProvider>,
/// Console provider for console.log(), console.error(), etc.
console_provider: Box<dyn ConsoleProvider>,
/// RegExp provider for regex operations.
/// Defaults to FancyRegexProvider when `regex` feature is enabled.
regexp_provider: Rc<dyn RegExpProvider>,
// ═══════════════════════════════════════════════════════════════════════════
// Step-based Execution
// ═══════════════════════════════════════════════════════════════════════════
/// Active VM for step-based execution.
/// When set, step() will execute one instruction and return.
/// When None, there is no active execution.
/// Boxed to make take/put-back cheap (pointer move instead of struct move).
pub(crate) active_vm: Option<Box<bytecode_vm::BytecodeVM>>,
/// Module path for active execution (needed for finalizing exports on completion)
pub(crate) active_module_path: Option<crate::ModulePath>,
/// Saved environment for active execution (needed for restoration on completion)
pub(crate) active_saved_env: Option<Gc<JsObject>>,
/// Module environment for active execution (needed for finalizing exports on completion)
pub(crate) active_module_env: Option<Gc<JsObject>>,
// ═══════════════════════════════════════════════════════════════════════════
// Module System
// ═══════════════════════════════════════════════════════════════════════════
/// Registered internal modules (specifier -> module definition)
internal_modules: FxHashMap<String, crate::InternalModule>,
/// Instantiated internal module objects (cached after first import)
internal_module_cache: FxHashMap<String, Gc<JsObject>>,
/// Loaded external modules (normalized path -> module namespace)
loaded_modules: FxHashMap<crate::ModulePath, Gc<JsObject>>,
/// The path of the main module (set by eval with a path)
main_module_path: Option<crate::ModulePath>,
/// The path of the currently executing module (for resolving relative imports)
current_module_path: Option<crate::ModulePath>,
// ═══════════════════════════════════════════════════════════════════════════
// Order System
// ═══════════════════════════════════════════════════════════════════════════
/// Counter for generating unique order IDs
pub(crate) next_order_id: u64,
/// Pending orders waiting for host fulfillment.
/// Each Order contains a RuntimeValue that keeps the payload alive.
pub(crate) pending_orders: Vec<crate::Order>,
/// Order responses from host, waiting to be consumed on resume
pub(crate) order_responses: FxHashMap<crate::OrderId, Result<crate::RuntimeValue, JsError>>,
/// Cancelled order IDs
pub(crate) cancelled_orders: Vec<crate::OrderId>,
/// Suspended VM state waiting for order response from host
pub(crate) suspended_for_order: Option<bytecode_vm::VmOrderSuspension>,
/// Promises waiting on specific orders. When an order is fulfilled,
/// all promises registered for that order ID are resolved.
pub(crate) order_promises: FxHashMap<crate::OrderId, Vec<Gc<JsObject>>>,
// ═══════════════════════════════════════════════════════════════════════════
// Async Context Management
// ═══════════════════════════════════════════════════════════════════════════
/// Wait graph tracking all suspended async contexts
pub(crate) wait_graph: WaitGraph,
/// Counter for generating unique context IDs
pub(crate) next_context_id: u64,
/// Counter for generating unique promise IDs
pub(crate) next_promise_id: u64,
/// Map from promise object to PromiseId for quick lookup
/// Uses Gc identity (pointer comparison via Hash impl)
pub(crate) promise_ids: FxHashMap<Gc<JsObject>, PromiseId>,
// ═══════════════════════════════════════════════════════════════════════════
// Program State
// ═══════════════════════════════════════════════════════════════════════════
/// Pending program waiting for imports to be provided
pub(crate) pending_program: Option<crate::ast::Program>,
/// Pending module sources waiting for their imports to be satisfied
/// Maps normalized path -> parsed program
pub(crate) pending_module_sources: FxHashMap<crate::ModulePath, crate::ast::Program>,
}
impl Interpreter {
/// Create a new interpreter instance
pub fn new() -> Self {
let heap: Heap<JsObject> = Heap::new();
let root_guard = heap.create_guard();
// Create prototypes (all rooted)
let object_prototype = root_guard.alloc();
let array_prototype = root_guard.alloc();
let function_prototype = root_guard.alloc();
let string_prototype = root_guard.alloc();
let number_prototype = root_guard.alloc();
let boolean_prototype = root_guard.alloc();
let regexp_prototype = root_guard.alloc();
let map_prototype = root_guard.alloc();
let set_prototype = root_guard.alloc();
let date_prototype = root_guard.alloc();
let symbol_prototype = root_guard.alloc();
let promise_prototype = root_guard.alloc();
let generator_prototype = root_guard.alloc();
// Create error prototypes (all rooted)
let error_prototype = root_guard.alloc();
let type_error_prototype = root_guard.alloc();
let reference_error_prototype = root_guard.alloc();
let range_error_prototype = root_guard.alloc();
let syntax_error_prototype = root_guard.alloc();
// Set up prototype chain - all prototypes inherit from object_prototype
array_prototype.borrow_mut().prototype = Some(object_prototype.clone());
function_prototype.borrow_mut().prototype = Some(object_prototype.clone());
string_prototype.borrow_mut().prototype = Some(object_prototype.clone());
number_prototype.borrow_mut().prototype = Some(object_prototype.clone());
boolean_prototype.borrow_mut().prototype = Some(object_prototype.clone());
regexp_prototype.borrow_mut().prototype = Some(object_prototype.clone());
map_prototype.borrow_mut().prototype = Some(object_prototype.clone());
set_prototype.borrow_mut().prototype = Some(object_prototype.clone());
date_prototype.borrow_mut().prototype = Some(object_prototype.clone());
symbol_prototype.borrow_mut().prototype = Some(object_prototype.clone());
promise_prototype.borrow_mut().prototype = Some(object_prototype.clone());
generator_prototype.borrow_mut().prototype = Some(object_prototype.clone());
// Set up error prototype chain
// Error.prototype inherits from Object.prototype
error_prototype.borrow_mut().prototype = Some(object_prototype.clone());
// All specific error prototypes inherit from Error.prototype
type_error_prototype.borrow_mut().prototype = Some(error_prototype.clone());
reference_error_prototype.borrow_mut().prototype = Some(error_prototype.clone());
range_error_prototype.borrow_mut().prototype = Some(error_prototype.clone());
syntax_error_prototype.borrow_mut().prototype = Some(error_prototype.clone());
// Create global object (rooted)
let global = root_guard.alloc();
global.borrow_mut().prototype = Some(object_prototype.clone());
// Create global environment (rooted, owned by global)
let global_env = root_guard.alloc();
{
let mut env_ref = global_env.borrow_mut();
env_ref.null_prototype = true;
env_ref.exotic = ExoticObject::Environment(EnvironmentData::new());
}
let string_dict = StringDict::new();
// Initialize symbol counter and well-known symbols
// Well-known symbols get IDs 1-12, next_symbol_id starts at 13
let mut symbol_counter = 1u64;
let well_known_symbols = WellKnownSymbols::new(&mut symbol_counter);
let mut interp = Self {
heap,
root_guard,
global,
global_env: global_env.clone(),
env: global_env,
env_guards: Vec::new(), // global_env is rooted via root_guard
string_dict,
object_prototype,
array_prototype,
function_prototype,
string_prototype,
number_prototype,
boolean_prototype,
regexp_prototype,
map_prototype,
set_prototype,
date_prototype,
symbol_prototype,
promise_prototype,
generator_prototype,
error_prototype,
type_error_prototype,
reference_error_prototype,
range_error_prototype,
syntax_error_prototype,
exports: FxHashMap::default(),
call_stack: Vec::new(),
next_generator_id: 1,
next_symbol_id: symbol_counter,
symbol_registry: FxHashMap::default(),
well_known_symbols,
console_timers: FxHashMap::default(),
console_counters: FxHashMap::default(),
current_ffi_id: 0,
#[cfg(feature = "c-api")]
ffi_context: core::ptr::null_mut(),
// Platform providers - std takes priority, then wasm, then no-op
#[cfg(feature = "std")]
time_provider: Box::new(StdTimeProvider::new()),
#[cfg(not(feature = "std"))]
time_provider: Box::new(NoOpTimeProvider),
#[cfg(feature = "std")]
random_provider: Box::new(StdRandomProvider::new()),
#[cfg(not(feature = "std"))]
random_provider: Box::new(NoOpRandomProvider),
#[cfg(feature = "std")]
console_provider: Box::new(StdConsoleProvider::new()),
#[cfg(not(feature = "std"))]
console_provider: Box::new(NoOpConsoleProvider),
// RegExp provider - regex feature takes priority, then no-op
#[cfg(feature = "regex")]
regexp_provider: Rc::new(FancyRegexProvider::new()),
#[cfg(not(feature = "regex"))]
regexp_provider: Rc::new(NoOpRegExpProvider),
// Step-based execution
active_vm: None,
active_module_path: None,
active_saved_env: None,
active_module_env: None,
// Module system
internal_modules: FxHashMap::default(),
internal_module_cache: FxHashMap::default(),
loaded_modules: FxHashMap::default(),
main_module_path: None,
current_module_path: None,
// Order system
next_order_id: 1,
pending_orders: Vec::new(),
order_responses: FxHashMap::default(),
cancelled_orders: Vec::new(),
suspended_for_order: None,
order_promises: FxHashMap::default(),
// Async context management
wait_graph: WaitGraph::new(),
next_context_id: 1,
next_promise_id: 1,
promise_ids: FxHashMap::default(),
// Program state
pending_program: None,
pending_module_sources: FxHashMap::default(),
};
// Initialize built-in globals
interp.init_globals();
// Register built-in internal modules
interp.register_internal_module(builtins::create_eval_internal_module());
interp
}
/// Create a new interpreter with a custom console provider.
///
/// This is useful for WASM environments where you want to capture
/// console output into a buffer rather than sending it to the browser console.
pub fn with_console(console_provider: Box<dyn ConsoleProvider>) -> Self {
let mut interp = Self::new();
interp.console_provider = console_provider;
interp
}
/// Create a new interpreter with a custom RegExp provider.
///
/// This is useful for:
/// - WASM environments where you want to use the browser's native RegExp
/// - C FFI embeddings with custom regex implementations
/// - Testing with mock regex providers
pub fn with_regexp_provider(regexp_provider: Rc<dyn RegExpProvider>) -> Self {
let mut interp = Self::new();
interp.regexp_provider = regexp_provider;
interp
}
/// Set the RegExp provider at runtime.
///
/// Note: This only affects newly compiled regexes. Already-cached compiled
/// regexes in existing RegExp objects will continue to use the old provider.
pub fn set_regexp_provider(&mut self, provider: Rc<dyn RegExpProvider>) {
self.regexp_provider = provider;
}
/// Set the console provider at runtime.
pub fn set_console(&mut self, provider: Box<dyn ConsoleProvider>) {
self.console_provider = provider;
}
/// Set the time provider at runtime.
///
/// This affects `Date.now()`, `console.time()`, and other time-related operations.
pub fn set_time_provider(&mut self, provider: Box<dyn TimeProvider>) {
self.time_provider = provider;
}
/// Set the random provider at runtime.
///
/// This affects `Math.random()` and other randomness-related operations.
pub fn set_random_provider(&mut self, provider: Box<dyn RandomProvider>) {
self.random_provider = provider;
}
/// Get a reference to the current RegExp provider.
pub fn regexp_provider(&self) -> &Rc<dyn RegExpProvider> {
&self.regexp_provider
}
/// Compile a regex pattern using the configured RegExp provider.
///
/// This is a convenience method that wraps the provider's compile method.
pub fn compile_regexp(
&self,
pattern: &str,
flags: &str,
) -> Result<Rc<dyn crate::platform::CompiledRegex>, JsError> {
self.regexp_provider
.compile(pattern, flags)
.map_err(|e| JsError::syntax_error(e, 0, 0))
}
/// Initialize built-in global values
fn init_globals(&mut self) {
// For now, minimal globals - just define undefined and NaN
let undefined_name = self.intern("undefined");
self.env_define(undefined_name, JsValue::Undefined, false);
let nan_name = self.intern("NaN");
self.env_define(nan_name, JsValue::Number(f64::NAN), false);
let infinity_name = self.intern("Infinity");
self.env_define(infinity_name, JsValue::Number(f64::INFINITY), false);
// Initialize Array builtin methods
builtins::init_array_prototype(self);
// Initialize String prototype methods
builtins::init_string_prototype(self);
// Initialize Function.prototype (call, apply, bind)
builtins::init_function_prototype(self);
// Initialize Function constructor (global Function function)
let function_constructor = builtins::create_function_constructor(self);
let function_name = self.intern("Function");
self.env_define(function_name, JsValue::Object(function_constructor), false);
// Initialize Math global object
builtins::init_math(self);
// Initialize JSON global object
builtins::init_json(self);
// Initialize console global object (only when console feature is enabled)
#[cfg(feature = "console")]
builtins::console::init_console(self);
// Initialize Number prototype methods
builtins::init_number_prototype(self);
// Initialize Error constructor
builtins::init_error(self);
// Initialize global functions (parseInt, parseFloat, isNaN, isFinite, URI functions)
builtins::init_global_functions(self);
// Initialize Map constructor and prototype
builtins::init_map(self);
// Initialize Set constructor and prototype
builtins::init_set(self);
// Initialize Date constructor and prototype
builtins::init_date(self);
// Initialize Symbol constructor and prototype
builtins::init_symbol(self);
// Initialize String constructor (global String function)
let string_constructor = builtins::create_string_constructor(self);
let string_name = self.intern("String");
self.env_define(string_name, JsValue::Object(string_constructor), false);
// Initialize Array constructor (global Array function)
let array_constructor = builtins::create_array_constructor(self);
let array_name = self.intern("Array");
self.env_define(array_name, JsValue::Object(array_constructor), false);
// Initialize Object prototype and constructor
builtins::init_object_prototype(self);
let object_constructor = builtins::create_object_constructor(self);
let object_name = self.intern("Object");
self.env_define(
object_name.clone(),
JsValue::Object(object_constructor.clone()),
false,
);
// Also set on global object for lodash/Node.js compatibility
self.global.borrow_mut().set_property(
PropertyKey::String(object_name),
JsValue::Object(object_constructor),
);
// Initialize RegExp prototype and constructor
builtins::regexp::init_regexp_prototype(self);
let regexp_constructor = builtins::regexp::create_regexp_constructor(self);
let regexp_name = self.intern("RegExp");
self.env_define(regexp_name, JsValue::Object(regexp_constructor), false);
// Initialize Number constructor (global Number function)
let number_constructor = builtins::create_number_constructor(self);
let number_name = self.intern("Number");
self.env_define(number_name, JsValue::Object(number_constructor), false);
// Initialize Boolean prototype and constructor (global Boolean function)
builtins::init_boolean_prototype(self);
let boolean_constructor = builtins::create_boolean_constructor(self);
let boolean_name = self.intern("Boolean");
self.env_define(boolean_name, JsValue::Object(boolean_constructor), false);
// Initialize Promise prototype and constructor
builtins::promise::init_promise_prototype(self);
let promise_constructor = builtins::promise::create_promise_constructor(self);
let promise_name = self.intern("Promise");
self.env_define(promise_name, JsValue::Object(promise_constructor), false);
// Initialize Generator prototype
builtins::init_generator_prototype(self);
// Initialize Proxy constructor and Reflect object
builtins::proxy::init_proxy(self);
}
/// Create an interpreter with configuration
pub fn with_config(config: crate::InterpreterConfig) -> Self {
let mut interp = Self::new();
// Apply custom regexp provider if specified
if let Some(provider) = config.regexp_provider {
interp.regexp_provider = provider;
}
// Register internal modules
for module in config.internal_modules {
interp.register_internal_module(module);
}
interp
}
// ═══════════════════════════════════════════════════════════════════════════
// Call Stack Depth
// ═══════════════════════════════════════════════════════════════════════════
/// Get the current call stack depth.
///
/// Returns the total depth combining the interpreter's call stack and
/// the active VM's trampoline stack (if any).
pub fn call_depth(&self) -> usize {
let vm_depth = self
.active_vm
.as_ref()
.map(|vm| vm.trampoline_depth())
.unwrap_or(0);
self.call_stack.len() + vm_depth
}
/// Set the GC threshold (0 = disable automatic collection)
///
/// Lower values reduce peak memory but increase GC overhead.
/// Higher values improve throughput but may use more memory.
pub fn set_gc_threshold(&self, threshold: usize) {
self.heap.set_gc_threshold(threshold);
}
/// Force a garbage collection cycle
pub fn collect(&self) {
self.heap.collect();
}
/// Get the number of env_guards (for debugging/testing)
pub fn env_guards_len(&self) -> usize {
self.env_guards.len()
}
/// Get GC statistics
pub fn gc_stats(&self) -> crate::gc::GcStats {
self.heap.stats()
}
// ═══════════════════════════════════════════════════════════════════════════
// Symbol Management
// ═══════════════════════════════════════════════════════════════════════════
/// Generate a unique symbol ID
pub fn next_symbol_id(&mut self) -> u64 {
let id = self.next_symbol_id;
self.next_symbol_id += 1;
id
}
/// Get a symbol from the registry by key (for Symbol.for)
pub fn symbol_registry_get(&self, key: &JsString) -> Option<JsSymbol> {
self.symbol_registry.get(key).cloned()
}
/// Insert a symbol into the registry (for Symbol.for)
pub fn symbol_registry_insert(&mut self, key: JsString, symbol: JsSymbol) {
self.symbol_registry.insert(key, symbol);
}
/// Find the key for a registered symbol (for Symbol.keyFor)
pub fn symbol_registry_key_for(&self, symbol_id: u64) -> Option<JsString> {
for (key, sym) in &self.symbol_registry {
if sym.id() == symbol_id {
return Some(key.cheap_clone());
}
}
None
}
// ═══════════════════════════════════════════════════════════════════════════
// Console State
// ═══════════════════════════════════════════════════════════════════════════
/// Start a console timer
pub fn console_timer_start(&mut self, label: String) {
let start = self.time_provider.start_timer();
self.console_timers.insert(label, start);
}
/// End a console timer and return elapsed milliseconds, or None if timer doesn't exist
pub fn console_timer_end(&mut self, label: &str) -> Option<u64> {
self.console_timers
.remove(label)
.map(|start| self.time_provider.elapsed_millis(start))
}
// ═══════════════════════════════════════════════════════════════════════════
// Platform Provider Access
// ═══════════════════════════════════════════════════════════════════════════
/// Get current time in milliseconds since Unix epoch
/// Used by Date.now() and Date constructor
pub fn now_millis(&self) -> i64 {
self.time_provider.now_millis()
}
/// Generate a random number in [0, 1)
/// Used by Math.random()
pub fn random(&mut self) -> f64 {
self.random_provider.random()
}
/// Write a message to the console at the specified level.
/// Used by console.log(), console.error(), etc.
pub fn console_write(&self, level: ConsoleLevel, message: &str) {
self.console_provider.write(level, message);
}
/// Clear the console.
/// Used by console.clear()
pub fn console_clear(&self) {
self.console_provider.clear();
}
/// Increment a console counter and return the new count
pub fn console_counter_increment(&mut self, label: String) -> u64 {
let count = self.console_counters.entry(label).or_insert(0);
*count += 1;
*count
}
/// Reset a console counter
pub fn console_counter_reset(&mut self, label: &str) {
self.console_counters.remove(label);
}
// ═══════════════════════════════════════════════════════════════════════════
// Internal Module System
// ═══════════════════════════════════════════════════════════════════════════
/// Register an internal module for import
pub fn register_internal_module(&mut self, module: crate::InternalModule) {
self.internal_modules
.insert(module.specifier.clone(), module);
}
/// Check if a specifier is an internal module
pub fn is_internal_module(&self, specifier: &str) -> bool {
// Check both registered internal modules and FFI-registered modules
self.internal_modules.contains_key(specifier)
|| self.internal_module_cache.contains_key(specifier)
}
// ═══════════════════════════════════════════════════════════════════════════
// Full Runtime API (imports + orders)
// ═══════════════════════════════════════════════════════════════════════════
/// Evaluate TypeScript/JavaScript code with full runtime support.
///
/// The optional `module_path` is used as the base for resolving relative imports.
/// For example, if `module_path` is `/project/src/main.ts` and the code
/// contains `import { foo } from "./utils"`, it will resolve to
/// `/project/src/utils`.
///
/// If no path is provided, relative imports will be treated as bare specifiers.
///
/// Returns StepResult which may indicate:
/// - Complete: execution finished with a value
/// - NeedImports: modules need to be provided before continuing
/// - Suspended: waiting for orders to be fulfilled
pub fn eval(
&mut self,
source: &str,
module_path: Option<crate::ModulePath>,
) -> Result<StepResult, JsError> {
use crate::compiler::Compiler;
use bytecode_vm::BytecodeVM;
// Set main module path if this is the entry point
if self.main_module_path.is_none() {
self.main_module_path = module_path.clone();
}
self.current_module_path = module_path.clone();
// Parse the source
let mut parser = Parser::new(source, &mut self.string_dict);
let program = parser.parse_program()?;
// Collect all import requests with resolved paths
// For main module, importer is None (we pass module_path for resolution but not as importer)
let imports = self.collect_import_requests_internal(&program, module_path.as_ref(), None);
// Filter to only missing imports and deduplicate
let missing = self.filter_missing_imports(imports);
let missing = Self::dedupe_import_requests(missing);
if !missing.is_empty() {
// Save the program for later execution when imports are provided
self.pending_program = Some(program);
return Ok(StepResult::NeedImports(missing));
}
// Create module environment for main module (if module_path is provided)
// This is needed to support exports and live bindings
let (saved_env, module_env) = if module_path.is_some() {
let saved = self.env.cheap_clone();
let module_env = self.create_module_environment();
// Root the module environment - it must persist for live bindings
self.root_guard.guard(module_env.clone());
self.env = module_env.cheap_clone();
(Some(saved), Some(module_env))
} else {
(None, None)
};
// All imports satisfied - set up import bindings first
self.setup_import_bindings(&program)?;
// Compile the program to bytecode
let chunk = if let Some(ref path) = module_path {
Compiler::compile_program_with_source(&program, path.as_str().to_string())?
} else {
Compiler::compile_program(&program)?
};
// Run the bytecode VM
let vm_guard = self.heap.create_guard();
let vm = BytecodeVM::with_guard(chunk, JsValue::Object(self.global.clone()), vm_guard);
let result = self.run_vm_to_completion(vm);
// Restore environment and finalize exports if we used a module environment
if let (Some(saved), Some(module_env)) = (saved_env, module_env) {
self.env = saved;
// If execution completed successfully, store the main module exports
if let Ok(StepResult::Complete(_)) = &result
&& let Some(ref path) = module_path
{
self.finalize_module_exports(path.clone(), module_env);
}
}
result
}
/// Create a module namespace object from current exports and store in loaded_modules
fn finalize_module_exports(
&mut self,
module_path: crate::ModulePath,
module_env: Gc<JsObject>,
) {
let guard = self.heap.create_guard();
let module_obj = self.create_object(&guard);
// Drain exports to a vector to avoid borrow conflict
let exports: Vec<_> = self.exports.drain().collect();
// Create properties for exports with proper live binding support
for (export_name, module_export) in exports {
match module_export {
ModuleExport::Direct { name, value } => {
// Intern the name to ensure pointer-based VarKey lookup works correctly
let interned_name = self.intern(name.as_str());
// Check if there's a binding in the module environment
let has_binding = {
let env_ref = module_env.borrow();
if let Some(env_data) = env_ref.as_environment() {
let var_key = VarKey(interned_name.cheap_clone());
env_data.bindings.contains_key(&var_key)
} else {
false
}
};
if has_binding {
// Direct export with binding: create getter for live binding
let getter_obj = guard.alloc();
{
let mut getter_ref = getter_obj.borrow_mut();
getter_ref.prototype = Some(self.function_prototype.cheap_clone());
getter_ref.exotic =
ExoticObject::Function(JsFunction::ModuleExportGetter {
module_env: module_env.cheap_clone(),
binding_name: interned_name,
});
}
// Set as accessor property (getter only, no setter)
module_obj.borrow_mut().properties.insert(
PropertyKey::String(export_name),
Property::accessor(Some(getter_obj), None),
);
} else {
// Direct export without binding (e.g., namespace re-export: export * as ns)
// Use the stored value directly
module_obj
.borrow_mut()
.set_property(PropertyKey::String(export_name), value);
}
}
ModuleExport::ReExport {
source_module,
source_key,
} => {
// Re-export: create getter that delegates to source module's property
// This enables live bindings through re-exports
let getter_obj = guard.alloc();
{
let mut getter_ref = getter_obj.borrow_mut();
getter_ref.prototype = Some(self.function_prototype.cheap_clone());
getter_ref.exotic =
ExoticObject::Function(JsFunction::ModuleReExportGetter {
source_module,
source_key,
});
}
// Set as accessor property (getter only, no setter)
module_obj.borrow_mut().properties.insert(
PropertyKey::String(export_name),
Property::accessor(Some(getter_obj), None),
);
}
}
}
// Root the module namespace object (lives forever)
self.root_guard.guard(module_obj.clone());
// Cache it by normalized path
self.loaded_modules.insert(module_path, module_obj);
}
/// Run a bytecode VM to completion or suspension
fn run_vm_to_completion(
&mut self,
mut vm: bytecode_vm::BytecodeVM,
) -> Result<StepResult, JsError> {
use bytecode_vm::VmResult;
let result = vm.run(self);
match result {
VmResult::Complete(guarded) => {
// Check if there are pending orders to return
if !self.pending_orders.is_empty() {
let pending = mem::take(&mut self.pending_orders);
let cancelled = mem::take(&mut self.cancelled_orders);
return Ok(StepResult::Suspended { pending, cancelled });
}
// Check for suspended order awaits or waiting async contexts
if self.suspended_for_order.is_some() || self.wait_graph.has_waiting_contexts() {
let cancelled = mem::take(&mut self.cancelled_orders);
return Ok(StepResult::Suspended {
pending: Vec::new(),
cancelled,
});
}
Ok(StepResult::Complete(crate::RuntimeValue::from_guarded(
guarded,
)))
}
VmResult::Error(err) => Err(self.materialize_thrown_error(err)),
VmResult::Suspend(suspension) => {
// Promise await suspension - add to wait graph
let ctx_id = ContextId(self.next_context_id);
self.next_context_id += 1;
// Get or create PromiseId for this promise
let promise_key = suspension.waiting_on.cheap_clone();
let promise_id = *self.promise_ids.entry(promise_key).or_insert_with(|| {
let id = PromiseId(self.next_promise_id);
self.next_promise_id += 1;
id
});
// Create suspended context
let suspended_ctx = SuspendedContext {
id: ctx_id,
state: suspension.state,
waiting_on: suspension.waiting_on,
waiting_on_id: promise_id,
resume_register: suspension.resume_register,
};
self.wait_graph.add_context(suspended_ctx);
let pending = mem::take(&mut self.pending_orders);
let cancelled = mem::take(&mut self.cancelled_orders);
Ok(StepResult::Suspended { pending, cancelled })
}
VmResult::SuspendForOrder(order_suspension) => {
// Order suspension - waiting for host to provide a value
self.suspended_for_order = Some(order_suspension);
let pending = mem::take(&mut self.pending_orders);
let cancelled = mem::take(&mut self.cancelled_orders);
Ok(StepResult::Suspended { pending, cancelled })
}
VmResult::Yield(_) | VmResult::YieldStar(_) => Err(JsError::internal_error(
"Bytecode execution cannot yield at top level",
)),
}
}
/// Execute a single bytecode instruction.
///
/// Returns `StepResult::Continue` if more instructions remain,
/// or a terminal result if execution completed or needs input.
///
/// Call `prepare()` to set up execution before using `step()`.
#[inline]
pub fn step(&mut self) -> Result<StepResult, JsError> {
use bytecode_vm::{BytecodeVM, VmStepResult};
// If there's no active VM, try to set one up from various sources
if self.active_vm.is_none() {
// 1. Check for order suspension with fulfilled response
if let Some(order_suspension) = self.suspended_for_order.take() {
if let Some(result) = self.order_responses.remove(&order_suspension.order_id) {
match result {
Ok(runtime_value) => {
let value = runtime_value.value().clone();
let vm_guard = self.heap.create_guard();
if let JsValue::Object(ref obj) = value {
vm_guard.guard(obj.cheap_clone());
}
let mut vm = BytecodeVM::from_saved_state(
order_suspension.state,
JsValue::Object(self.global.clone()),
vm_guard,
&self.heap,
);
// Set response value directly in resume register
vm.set_resume_value(order_suspension.resume_register, value);
self.active_vm = Some(Box::new(vm));
}
Err(error) => {
// Inject error as exception
let vm_guard = self.heap.create_guard();
let mut vm = BytecodeVM::from_saved_state(
order_suspension.state,
JsValue::Object(self.global.clone()),
vm_guard,
&self.heap,
);
let error_msg = JsValue::String(JsString::from(error.to_string()));
if vm.inject_exception(self, error_msg.clone()) {
self.active_vm = Some(Box::new(vm));
} else {
let guarded = Guarded::from_value(error_msg, &self.heap);
return Err(JsError::thrown(guarded));
}
}
}
} else {
// Order not yet fulfilled - re-suspend
self.suspended_for_order = Some(order_suspension);
let pending = mem::take(&mut self.pending_orders);
let cancelled = mem::take(&mut self.cancelled_orders);
return Ok(StepResult::Suspended { pending, cancelled });
}
}
// 2. Check for waiting async contexts with resolved promises
if self.active_vm.is_none() {
self.check_resolved_promises();
if let Some(ctx) = self.wait_graph.take_ready() {
let promise_status = {
let obj_ref = ctx.waiting_on.borrow();
if let ExoticObject::Promise(promise_state) = &obj_ref.exotic {
let status = promise_state.borrow().status.clone();
let result = promise_state.borrow().result.clone();
Some((status, result))
} else {
None
}
};
if let Some((status, result)) = promise_status {
let result_value = result.unwrap_or(JsValue::Undefined);
match status {
PromiseStatus::Fulfilled => {
let vm_guard = self.heap.create_guard();
let mut vm = BytecodeVM::from_saved_state(
ctx.state,
JsValue::Object(self.global.clone()),
vm_guard,
&self.heap,
);
vm.set_resume_value(ctx.resume_register, result_value);
self.active_vm = Some(Box::new(vm));
}
PromiseStatus::Rejected => {
let vm_guard = self.heap.create_guard();
let mut vm = BytecodeVM::from_saved_state(
ctx.state,
JsValue::Object(self.global.clone()),
vm_guard,
&self.heap,
);
if vm.inject_exception(self, result_value.clone()) {
self.active_vm = Some(Box::new(vm));
} else {
let guarded = Guarded::from_value(result_value, &self.heap);
return Err(JsError::thrown(guarded));
}
}
PromiseStatus::Pending => {
// Re-add to wait graph (should not happen for ready contexts)
self.wait_graph.add_context(ctx);
}
}
}
}
}
// 3. Check for pending program that needs imports
if self.active_vm.is_none()
&& let Some(program) = self.pending_program.take()
{
// Try to set up the VM from the pending program
let setup_result = self.setup_vm_from_program(program)?;
if !matches!(setup_result, StepResult::Continue) {
// Still needs imports or other action
return Ok(setup_result);
}
}
}
// Take the VM out temporarily to work with it
let Some(mut vm) = self.active_vm.take() else {
// No VM and nothing to resume
// Check if there are waiting contexts (unresolved promises) or suspended orders
if self.suspended_for_order.is_some() || self.wait_graph.has_waiting_contexts() {
let pending = mem::take(&mut self.pending_orders);
let cancelled = mem::take(&mut self.cancelled_orders);
return Ok(StepResult::Suspended { pending, cancelled });
}
// Truly done
return Ok(StepResult::Done);
};
let step_result = vm.step(self);
match step_result {
VmStepResult::Continue => {
// Put VM back and return Continue
self.active_vm = Some(vm);
Ok(StepResult::Continue)
}
VmStepResult::Terminal(vm_result) => {
// Terminal state - process and clear active execution state
let result = self.process_vm_result(*vm_result)?;
// If not suspended (i.e., actually complete), finalize
if matches!(result, crate::StepResult::Complete(_)) {
self.finalize_active_execution();
}
Ok(result)
}
}
}
/// Process a terminal VmResult and convert to StepResult
fn process_vm_result(&mut self, result: bytecode_vm::VmResult) -> Result<StepResult, JsError> {
use bytecode_vm::VmResult;
match result {
VmResult::Complete(guarded) => {
// Check if there are pending orders to return
if !self.pending_orders.is_empty() {
let pending = mem::take(&mut self.pending_orders);
let cancelled = mem::take(&mut self.cancelled_orders);
return Ok(StepResult::Suspended { pending, cancelled });
}
// Check for suspended order awaits or waiting async contexts
if self.suspended_for_order.is_some() || self.wait_graph.has_waiting_contexts() {
let cancelled = mem::take(&mut self.cancelled_orders);
return Ok(StepResult::Suspended {
pending: Vec::new(),
cancelled,
});
}
Ok(StepResult::Complete(crate::RuntimeValue::from_guarded(
guarded,
)))
}
VmResult::Error(err) => Err(self.materialize_thrown_error(err)),
VmResult::Suspend(suspension) => {
// Promise await suspension - add to wait graph
let ctx_id = ContextId(self.next_context_id);
self.next_context_id += 1;
// Get or create PromiseId for this promise
let promise_key = suspension.waiting_on.cheap_clone();
let promise_id = *self.promise_ids.entry(promise_key).or_insert_with(|| {
let id = PromiseId(self.next_promise_id);
self.next_promise_id += 1;
id
});
// Create suspended context
let suspended_ctx = SuspendedContext {
id: ctx_id,
state: suspension.state,
waiting_on: suspension.waiting_on,
waiting_on_id: promise_id,
resume_register: suspension.resume_register,
};
self.wait_graph.add_context(suspended_ctx);
let pending = mem::take(&mut self.pending_orders);
let cancelled = mem::take(&mut self.cancelled_orders);
Ok(StepResult::Suspended { pending, cancelled })
}
VmResult::SuspendForOrder(order_suspension) => {
// Order suspension - waiting for host to provide a value
self.suspended_for_order = Some(order_suspension);
let pending = mem::take(&mut self.pending_orders);
let cancelled = mem::take(&mut self.cancelled_orders);
Ok(StepResult::Suspended { pending, cancelled })
}
VmResult::Yield(_) | VmResult::YieldStar(_) => Err(JsError::internal_error(
"Bytecode execution cannot yield at top level",
)),
}
}
/// Run the interpreter to completion.
///
/// Loops `step()` until execution finishes. Returns the final value.
///
/// Returns `Err` if:
/// - Execution encounters a JavaScript error
/// - Execution requires unresolved imports (`NeedImports`)
/// - Execution suspends waiting for async orders (`Suspended`)
///
/// For scripts that need module loading or async orders, use `step()` directly.
///
/// # Example
/// ```
/// use tsrun::Interpreter;
///
/// let mut interp = Interpreter::new();
/// interp.prepare("1 + 2", None).unwrap();
/// let result = interp.run_to_completion().unwrap();
/// assert_eq!(result.as_number(), Some(3.0));
/// ```
pub fn run_to_completion(&mut self) -> Result<crate::RuntimeValue, JsError> {
loop {
match self.step()? {
StepResult::Continue => continue,
StepResult::Complete(rv) => return Ok(rv),
StepResult::Done => return Ok(crate::RuntimeValue::unguarded(JsValue::Undefined)),
StepResult::NeedImports(specifiers) => {
return Err(JsError::type_error(format!(
"Unresolved imports: {:?}",
specifiers
)));
}
StepResult::Suspended { pending, .. } => {
return Err(JsError::type_error(format!(
"Execution suspended waiting for {} orders",
pending.len()
)));
}
}
}
}
/// Finalize active execution (restore environment, finalize exports)
fn finalize_active_execution(&mut self) {
// Take state
let saved_env = self.active_saved_env.take();
let module_env = self.active_module_env.take();
let module_path = self.active_module_path.take();
// Restore environment and finalize exports if we used a module environment
if let (Some(saved), Some(env)) = (saved_env, module_env) {
self.env = saved;
// Store the main module exports
if let Some(path) = module_path {
self.finalize_module_exports(path, env);
}
}
}
/// Prepare code for step-based execution without running it.
///
/// After calling this, use `step()` to execute one instruction at a time.
/// Returns `Ok(())` if setup succeeded, or an error if parsing/compilation failed
/// or if imports are needed.
pub fn prepare(
&mut self,
source: &str,
module_path: Option<crate::ModulePath>,
) -> Result<StepResult, JsError> {
use crate::compiler::Compiler;
use bytecode_vm::BytecodeVM;
// Set main module path if this is the entry point
if self.main_module_path.is_none() {
self.main_module_path = module_path.clone();
}
self.current_module_path = module_path.clone();
// Parse the source
let mut parser = Parser::new(source, &mut self.string_dict);
let program = parser.parse_program()?;
// Collect all import requests with resolved paths
let imports = self.collect_import_requests_internal(&program, module_path.as_ref(), None);
// Filter to only missing imports and deduplicate
let missing = self.filter_missing_imports(imports);
let missing = Self::dedupe_import_requests(missing);
if !missing.is_empty() {
// Save the program for later execution when imports are provided
self.pending_program = Some(program);
return Ok(StepResult::NeedImports(missing));
}
// Create module environment for main module (if module_path is provided)
let (saved_env, module_env) = if module_path.is_some() {
let saved = self.env.cheap_clone();
let module_env = self.create_module_environment();
self.root_guard.guard(module_env.clone());
self.env = module_env.cheap_clone();
(Some(saved), Some(module_env))
} else {
(None, None)
};
// All imports satisfied - set up import bindings first
self.setup_import_bindings(&program)?;
// Compile the program to bytecode
let chunk = if let Some(ref path) = module_path {
Compiler::compile_program_with_source(&program, path.as_str().to_string())?
} else {
Compiler::compile_program(&program)?
};
// Create VM but don't run it
let vm_guard = self.heap.create_guard();
let vm = BytecodeVM::with_guard(chunk, JsValue::Object(self.global.clone()), vm_guard);
// Store VM and state for step-based execution
self.active_vm = Some(Box::new(vm));
self.active_module_path = module_path;
self.active_saved_env = saved_env;
self.active_module_env = module_env;
Ok(StepResult::Continue)
}
/// Set the active VM for step-based execution.
///
/// This is used by `api::prepare_call` to set up the interpreter for
/// executing a function call via the step loop.
pub(crate) fn set_active_vm(&mut self, vm: bytecode_vm::BytecodeVM) {
self.active_vm = Some(Box::new(vm));
self.active_module_path = None;
self.active_saved_env = None;
self.active_module_env = None;
}
/// Process any pending module sources that are ready to execute.
/// This executes modules in dependency order until all are executed
/// or some still have missing imports.
/// Process pending modules that have all their imports satisfied.
/// Returns a list of unprovided imports if some pending modules still need dependencies
/// that the host hasn't provided yet.
fn process_pending_modules(&mut self) -> Result<Vec<crate::ImportRequest>, JsError> {
loop {
// Collect all unprovided imports across all pending modules
// (imports that the host hasn't provided yet)
let mut all_unprovided: Vec<crate::ImportRequest> = Vec::new();
let mut ready_modules: Vec<crate::ModulePath> = Vec::new();
// Clone keys to avoid borrow issues
let pending_keys: Vec<crate::ModulePath> =
self.pending_module_sources.keys().cloned().collect();
for module_path in &pending_keys {
// Skip if already loaded
if self.loaded_modules.contains_key(module_path) {
continue;
}
// Get the program to check its imports
if let Some(program) = self.pending_module_sources.get(module_path) {
let imports = self.collect_import_requests(program, Some(module_path));
// Check if all imports are LOADED (not just provided)
let missing_from_loaded = self.filter_missing_imports(imports.clone());
if missing_from_loaded.is_empty() {
// All imports are loaded - this module is ready to execute
ready_modules.push(module_path.clone());
} else {
// Check which imports the HOST still needs to provide
let unprovided = self.filter_unprovided_imports(imports);
for req in unprovided {
let already_in_list = all_unprovided
.iter()
.any(|r| r.resolved_path == req.resolved_path);
if !already_in_list {
all_unprovided.push(req);
}
}
}
}
}
// If we have modules ready to execute, execute them
if !ready_modules.is_empty() {
for module_path in ready_modules {
self.execute_pending_module(&module_path)?;
}
// Continue the loop to check if more modules are now ready
continue;
}
// Return any imports the host still needs to provide
return Ok(all_unprovided);
}
}
/// Set up VM from a pending program (called when imports have been provided)
fn setup_vm_from_program(
&mut self,
program: crate::ast::Program,
) -> Result<StepResult, JsError> {
use crate::compiler::Compiler;
use bytecode_vm::BytecodeVM;
let module_path = self.current_module_path.clone();
// Collect all import requests with resolved paths
let imports = self.collect_import_requests_internal(&program, module_path.as_ref(), None);
// Check what the HOST still needs to provide (not in loaded_modules OR pending_module_sources)
let unprovided = self.filter_unprovided_imports(imports.clone());
let unprovided = Self::dedupe_import_requests(unprovided);
if !unprovided.is_empty() {
// Host needs to provide these modules
self.pending_program = Some(program);
return Ok(StepResult::NeedImports(unprovided));
}
// Execute any pending modules before setting up the main program
// This will execute in topological order (dependencies first)
let pending_module_unprovided = self.process_pending_modules()?;
if !pending_module_unprovided.is_empty() {
// Pending modules have dependencies the host hasn't provided yet
self.pending_program = Some(program);
return Ok(StepResult::NeedImports(pending_module_unprovided));
}
// After processing, verify all main program imports are now loaded
let still_missing = self.filter_missing_imports(imports);
if !still_missing.is_empty() {
// This shouldn't happen if process_pending_modules worked correctly
// But handle it gracefully
self.pending_program = Some(program);
let unprovided = self.filter_unprovided_imports(still_missing);
return Ok(StepResult::NeedImports(unprovided));
}
// Create module environment for main module (if module_path is provided)
let (saved_env, module_env) = if module_path.is_some() {
let saved = self.env.cheap_clone();
let module_env = self.create_module_environment();
self.root_guard.guard(module_env.clone());
self.env = module_env.cheap_clone();
(Some(saved), Some(module_env))
} else {
(None, None)
};
// All imports satisfied - set up import bindings first
self.setup_import_bindings(&program)?;
// Compile the program to bytecode
let chunk = if let Some(ref path) = module_path {
Compiler::compile_program_with_source(&program, path.as_str().to_string())?
} else {
Compiler::compile_program(&program)?
};
// Create VM
let vm_guard = self.heap.create_guard();
let vm = BytecodeVM::with_guard(chunk, JsValue::Object(self.global.clone()), vm_guard);
// Store VM and state for step-based execution
self.active_vm = Some(Box::new(vm));
self.active_module_path = module_path;
self.active_saved_env = saved_env;
self.active_module_env = module_env;
Ok(StepResult::Continue)
}
/// Convert ThrownValue errors to RuntimeError with string data
///
/// JsError::ThrownValue contains a JsValue that may have Gc pointers.
/// These pointers become invalid when the interpreter/heap is dropped.
/// This function extracts the error information while it's still valid.
fn materialize_thrown_error(&mut self, error: JsError) -> JsError {
match error {
JsError::ThrownValue { guarded } => {
// Extract error name and message from the thrown value
if let JsValue::Object(obj) = &guarded.value {
let name_key = self.property_key("name");
let message_key = self.property_key("message");
let obj_ref = obj.borrow();
let name_val = obj_ref.get_property(&name_key);
let message_val = obj_ref.get_property(&message_key);
drop(obj_ref);
let name = name_val
.map(|v| self.to_js_string(&v).to_string())
.unwrap_or_else(|| "Error".to_string());
let message = message_val
.map(|v| self.to_js_string(&v).to_string())
.unwrap_or_default();
JsError::RuntimeError {
kind: name,
message,
stack: Vec::new(),
}
} else {
// Non-object thrown value - convert to string
let message = self.to_js_string(&guarded.value).to_string();
JsError::RuntimeError {
kind: "Error".to_string(),
message,
stack: Vec::new(),
}
}
}
// Pass through other error types unchanged
other => other,
}
}
/// Provide a module source for a pending import.
///
/// The `resolved_path` should be the normalized path from `ImportRequest.resolved_path`.
/// The module is parsed and stored, but not executed until `continue_eval` is called.
/// This allows collecting all needed imports before execution.
pub fn provide_module(
&mut self,
resolved_path: crate::ModulePath,
source: &str,
) -> Result<(), JsError> {
// Parse the module
let mut parser = Parser::new(source, &mut self.string_dict);
let program = parser.parse_program()?;
// Store the parsed program for later execution
self.pending_module_sources.insert(resolved_path, program);
Ok(())
}
/// Set up import bindings for a program before bytecode execution.
/// This resolves all imports and creates bindings in the current environment
/// so that the bytecode can reference imported values.
fn setup_import_bindings(&mut self, program: &Program) -> Result<(), JsError> {
for stmt in program.body.iter() {
if let Statement::Import(import) = stmt {
// Skip type-only imports
if import.type_only {
continue;
}
let specifier = import.source.value.to_string();
// Resolve the module
let module_obj = self.resolve_module(&specifier)?;
// Set up bindings for each import specifier
for spec in &import.specifiers {
match spec {
ImportSpecifier::Named {
local, imported, ..
} => {
// import { foo as bar } from "mod" -> bar binds to mod.foo
let property_key = PropertyKey::String(imported.name.cheap_clone());
self.env_define_import(
local.name.cheap_clone(),
module_obj.cheap_clone(),
property_key,
);
}
ImportSpecifier::Default { local, .. } => {
// import foo from "mod" -> foo binds to mod.default
let property_key = PropertyKey::String(self.intern("default"));
self.env_define_import(
local.name.cheap_clone(),
module_obj.cheap_clone(),
property_key,
);
}
ImportSpecifier::Namespace { local, .. } => {
// import * as foo from "mod" -> foo binds to the entire module object
// For namespace imports, we define a regular binding to the module object
self.env_define(
local.name.cheap_clone(),
JsValue::Object(module_obj.cheap_clone()),
false, // immutable
);
}
}
}
}
}
Ok(())
}
/// Execute a pending module that has all its imports satisfied.
fn execute_pending_module(&mut self, module_path: &crate::ModulePath) -> Result<(), JsError> {
let program = self
.pending_module_sources
.remove(module_path)
.ok_or_else(|| {
JsError::internal_error(format!("Module '{}' not found", module_path))
})?;
// Save current state
let saved_env = self.env.cheap_clone();
let saved_module_path = self.current_module_path.take();
// Set current module path for resolving nested imports
self.current_module_path = Some(module_path.clone());
// Create module environment (rooted so it persists for live bindings)
let module_env = self.create_module_environment();
// Root the module environment - it must persist for live bindings
self.root_guard.guard(module_env.clone());
self.env = module_env.cheap_clone();
// Set up import bindings before bytecode execution
self.setup_import_bindings(&program)?;
// Execute module using bytecode compilation
let result = self.execute_program_bytecode(&program);
// Restore state
self.env = saved_env;
self.current_module_path = saved_module_path;
result?;
// Create module namespace object from exports
let guard = self.heap.create_guard();
let module_obj = self.create_object(&guard);
// Drain exports to a vector to avoid borrow conflict
let exports: Vec<_> = self.exports.drain().collect();
// Create properties for exports with proper live binding support
for (export_name, module_export) in exports {
match module_export {
ModuleExport::Direct { name, value } => {
// Intern the name to ensure pointer-based VarKey lookup works correctly
let interned_name = self.intern(name.as_str());
// Check if there's a binding in the module environment
let has_binding = {
let env_ref = module_env.borrow();
if let Some(env_data) = env_ref.as_environment() {
let var_key = VarKey(interned_name.cheap_clone());
env_data.bindings.contains_key(&var_key)
} else {
false
}
};
if has_binding {
// Direct export with binding: create getter for live binding
let getter_obj = guard.alloc();
{
let mut getter_ref = getter_obj.borrow_mut();
getter_ref.prototype = Some(self.function_prototype.cheap_clone());
getter_ref.exotic =
ExoticObject::Function(JsFunction::ModuleExportGetter {
module_env: module_env.cheap_clone(),
binding_name: interned_name,
});
}
// Set as accessor property (getter only, no setter)
module_obj.borrow_mut().properties.insert(
PropertyKey::String(export_name),
Property::accessor(Some(getter_obj), None),
);
} else {
// Direct export without binding (e.g., namespace re-export: export * as ns)
// Use the stored value directly
module_obj
.borrow_mut()
.set_property(PropertyKey::String(export_name), value);
}
}
ModuleExport::ReExport {
source_module,
source_key,
} => {
// Re-export: create getter that delegates to source module's property
// This enables live bindings through re-exports
let getter_obj = guard.alloc();
{
let mut getter_ref = getter_obj.borrow_mut();
getter_ref.prototype = Some(self.function_prototype.cheap_clone());
getter_ref.exotic =
ExoticObject::Function(JsFunction::ModuleReExportGetter {
source_module,
source_key,
});
}
// Set as accessor property (getter only, no setter)
module_obj.borrow_mut().properties.insert(
PropertyKey::String(export_name),
Property::accessor(Some(getter_obj), None),
);
}
}
}
// Root the module namespace object (lives forever)
self.root_guard.guard(module_obj.clone());
// Cache it by normalized path
self.loaded_modules.insert(module_path.clone(), module_obj);
Ok(())
}
/// Fulfill orders with responses from the host
///
/// The host can provide any value as the order response:
/// - Plain objects: returned directly to JS code
/// - Promises: returned to JS code, can be awaited for deferred resolution
/// - Primitives: returned directly to JS code
///
/// For parallel async operations, the host can return unresolved Promises
/// and resolve them later via api::resolve_promise.
pub fn fulfill_orders(&mut self, responses: Vec<crate::OrderResponse>) {
for response in responses {
let order_id = response.id;
// Resolve any promises that were registered for this order
// (e.g., promises created when PendingOrder markers were passed to Promise.all)
if let Some(promises) = self.order_promises.remove(&order_id) {
for promise in promises {
match &response.result {
Ok(rv) => {
let value = rv.value().clone();
// Resolve the promise - ignore errors (promise might be settled)
let _ = builtins::promise::resolve_promise_value(self, &promise, value);
}
Err(e) => {
// Reject the promise with the error
let _ = builtins::promise::reject_promise_value(
self,
&promise,
e.to_value(),
);
}
}
}
}
// Store response - will be injected into VM when execution resumes
self.order_responses.insert(order_id, response.result);
}
}
/// Check all waiting contexts for resolved promises and move them to ready queue
fn check_resolved_promises(&mut self) {
// Collect promise IDs that are now resolved
let mut resolved: Vec<PromiseId> = Vec::new();
for (&promise_id, waiter_ids) in &self.wait_graph.promise_waiters {
// Check if any waiter's promise is resolved
for &ctx_id in waiter_ids {
if let Some(ctx) = self.wait_graph.contexts.get(&ctx_id) {
let is_resolved = {
let obj_ref = ctx.waiting_on.borrow();
if let ExoticObject::Promise(promise_state) = &obj_ref.exotic {
!matches!(promise_state.borrow().status, PromiseStatus::Pending)
} else {
false
}
};
if is_resolved {
resolved.push(promise_id);
break; // One resolved waiter is enough to mark this promise_id
}
}
}
}
// Move resolved promise waiters to ready queue
for promise_id in resolved {
self.wait_graph.promise_resolved(promise_id);
}
}
/// Public wrapper for check_resolved_promises
pub(crate) fn check_resolved_promises_public(&mut self) {
self.check_resolved_promises();
}
/// Create a module environment (for executing modules)
fn create_module_environment(&mut self) -> Gc<JsObject> {
let env = self.root_guard.alloc();
{
let mut env_ref = env.borrow_mut();
env_ref.null_prototype = true;
env_ref.exotic = ExoticObject::Environment(EnvironmentData::with_outer(Some(
self.global_env.cheap_clone(),
)));
}
env
}
/// Resolve a module specifier to a normalized path.
///
/// Uses the current module path (or main module path) as the base for resolving
/// relative imports like `./foo` or `../bar`.
pub fn resolve_module_specifier(&self, specifier: &str) -> crate::ModulePath {
let base = self
.current_module_path
.as_ref()
.or(self.main_module_path.as_ref());
crate::ModulePath::resolve(specifier, base)
}
/// Collect all import requests from a program, resolving relative paths.
///
/// Uses the same path for both resolution base and importer.
/// For main module imports, use `collect_import_requests_internal` instead.
fn collect_import_requests(
&self,
program: &Program,
module_path: Option<&crate::ModulePath>,
) -> Vec<crate::ImportRequest> {
self.collect_import_requests_internal(program, module_path, module_path)
}
/// Collect all import requests from a program with separate resolution base and importer.
///
/// - `resolve_base`: Used to resolve relative paths (e.g., ./foo becomes /project/src/foo)
/// - `importer`: Stored in ImportRequest.importer (None for main module)
fn collect_import_requests_internal(
&self,
program: &Program,
resolve_base: Option<&crate::ModulePath>,
importer: Option<&crate::ModulePath>,
) -> Vec<crate::ImportRequest> {
use crate::ast::Statement;
let mut imports = Vec::new();
for stmt in program.body.iter() {
let specifier = match stmt {
Statement::Import(import) => Some(import.source.value.to_string()),
Statement::Export(export) => {
// Re-export from another module: export { foo } from "./bar"
export.source.as_ref().map(|s| s.value.to_string())
}
_ => None,
};
if let Some(spec) = specifier {
let resolved = crate::ModulePath::resolve(&spec, resolve_base);
imports.push(crate::ImportRequest {
specifier: spec,
resolved_path: resolved,
importer: importer.cloned(),
});
}
}
imports
}
/// Filter import requests to only those that are missing (not internal, not already loaded).
/// Note: pending_module_sources are NOT considered "available" - they must be loaded first.
fn filter_missing_imports(
&self,
imports: Vec<crate::ImportRequest>,
) -> Vec<crate::ImportRequest> {
imports
.into_iter()
.filter(|req| {
// Internal modules are resolved automatically
if self.is_internal_module(&req.specifier) {
return false;
}
// Already loaded modules don't need to be requested
if self.loaded_modules.contains_key(&req.resolved_path) {
return false;
}
// Note: We do NOT check pending_module_sources here.
// A module is only truly available when it's in loaded_modules.
// Checking pending_module_sources would break topological ordering.
true
})
.collect()
}
/// Filter import requests, also considering pending module sources as "provided".
/// Use this when checking if the HOST needs to provide more modules.
fn filter_unprovided_imports(
&self,
imports: Vec<crate::ImportRequest>,
) -> Vec<crate::ImportRequest> {
imports
.into_iter()
.filter(|req| {
// Internal modules are resolved automatically
if self.is_internal_module(&req.specifier) {
return false;
}
// Already loaded modules don't need to be requested
if self.loaded_modules.contains_key(&req.resolved_path) {
return false;
}
// Pending module sources (provided but not yet executed)
if self.pending_module_sources.contains_key(&req.resolved_path) {
return false;
}
true
})
.collect()
}
/// Deduplicate import requests by resolved path.
fn dedupe_import_requests(imports: Vec<crate::ImportRequest>) -> Vec<crate::ImportRequest> {
let mut seen = FxHashSet::default();
imports
.into_iter()
.filter(|req| seen.insert(req.resolved_path.clone()))
.collect()
}
// ═══════════════════════════════════════════════════════════════════════════
// Environment Operations
// ═══════════════════════════════════════════════════════════════════════════
/// Define a variable in the current environment
pub fn env_define(&mut self, name: JsString, value: JsValue, mutable: bool) {
// Intern the name to ensure pointer-based VarKey lookup works correctly.
// The bytecode VM interns strings before lookup, so we must intern here too.
let interned_name = self.intern(name.as_str());
let mut env_ref = self.env.borrow_mut();
if let Some(data) = env_ref.as_environment_mut() {
data.bindings.insert(
VarKey(interned_name),
Binding {
value,
mutable,
initialized: true,
import_binding: None,
},
);
}
}
/// Define an import binding in the current environment (for live bindings)
pub fn env_define_import(
&mut self,
name: JsString,
module_obj: Gc<JsObject>,
property_key: PropertyKey,
) {
// Intern the name to ensure pointer-based VarKey lookup works correctly.
// The bytecode VM interns strings before lookup, so we must intern here too.
let interned_name = self.intern(name.as_str());
let mut env_ref = self.env.borrow_mut();
if let Some(data) = env_ref.as_environment_mut() {
data.bindings.insert(
VarKey(interned_name),
Binding {
value: JsValue::Undefined, // Not used for import bindings
mutable: false, // Imports are always read-only
initialized: true,
import_binding: Some(ImportBinding {
module_obj,
property_key,
}),
},
);
}
}
/// Get a variable from the environment chain
pub fn env_get(&self, name: &JsString) -> Result<JsValue, JsError> {
let mut current = Some(self.env.cheap_clone());
// Create VarKey once for pointer-based lookup
let key = VarKey(name.cheap_clone());
while let Some(env) = current {
let env_ref = env.borrow();
if let Some(data) = env_ref.as_environment() {
if let Some(binding) = data.bindings.get(&key) {
if !binding.initialized {
return Err(JsError::reference_error(format!(
"Cannot access '{}' before initialization",
name
)));
}
// Handle import bindings (for live bindings)
if let Some(ref import_binding) = binding.import_binding {
return self.resolve_import_binding(import_binding);
}
return Ok(binding.value.clone());
}
current = data.outer.cheap_clone();
} else {
break;
}
}
// Check global object properties
let global = self.global.borrow();
if let Some(prop) = global.get_property(&PropertyKey::String(name.cheap_clone())) {
return Ok(prop);
}
Err(JsError::reference_error(name.to_string()))
}
/// Resolve an import binding by reading from the module's environment
/// This handles both direct exports (ModuleExportGetter) and re-exports (ModuleReExportGetter)
fn resolve_import_binding(&self, import_binding: &ImportBinding) -> Result<JsValue, JsError> {
self.resolve_module_property(&import_binding.module_obj, &import_binding.property_key)
}
/// Resolve a property from a module namespace object, handling live bindings
/// This recursively resolves through re-export chains
#[allow(clippy::only_used_in_recursion)]
fn resolve_module_property(
&self,
module_obj: &Gc<JsObject>,
prop_key: &PropertyKey,
) -> Result<JsValue, JsError> {
// Get the property descriptor from the module namespace object
let prop_desc = module_obj.borrow().get_property_descriptor(prop_key);
match prop_desc {
Some((prop, _)) if prop.is_accessor() => {
// The property has a getter - could be ModuleExportGetter or ModuleReExportGetter
if let Some(getter) = prop.getter() {
let getter_ref = getter.borrow();
match &getter_ref.exotic {
ExoticObject::Function(JsFunction::ModuleExportGetter {
module_env,
binding_name,
}) => {
// Direct export: read from the module's environment
let env_ref = module_env.borrow();
if let Some(env_data) = env_ref.as_environment() {
let var_key = VarKey(binding_name.cheap_clone());
if let Some(binding) = env_data.bindings.get(&var_key) {
return Ok(binding.value.clone());
}
}
}
ExoticObject::Function(JsFunction::ModuleReExportGetter {
source_module,
source_key,
}) => {
// Re-export: recursively resolve from source module
return self.resolve_module_property(source_module, source_key);
}
_ => {}
}
}
Ok(JsValue::Undefined)
}
Some((prop, _)) => Ok(prop.value.clone()),
None => Ok(JsValue::Undefined),
}
}
/// Get an exported value from the main module by name.
///
/// This resolves the export through the module namespace object, handling
/// live bindings correctly. Returns `None` if no main module has been evaluated
/// or if the export doesn't exist.
///
/// # Example
/// ```ignore
/// // After evaluating: export const processor = { ... }
/// let processor = interp.get_export("processor");
/// ```
pub fn get_export(&self, name: &str) -> Option<JsValue> {
// Get the main module path
let main_path = self.main_module_path.as_ref()?;
// Get the module namespace object
let module_obj = self.loaded_modules.get(main_path)?;
// Resolve the property (handles live bindings)
let prop_key = PropertyKey::String(JsString::from(name));
match self.resolve_module_property(module_obj, &prop_key) {
Ok(value) if !value.is_undefined() => Some(value),
_ => None,
}
}
/// Get all export names from the main module.
///
/// Returns an empty vector if no main module has been evaluated.
pub fn get_export_names(&self) -> Vec<String> {
let Some(main_path) = self.main_module_path.as_ref() else {
return Vec::new();
};
let Some(module_obj) = self.loaded_modules.get(main_path) else {
return Vec::new();
};
let borrowed = module_obj.borrow();
borrowed
.properties
.keys()
.filter_map(|k| match k {
PropertyKey::String(s) => Some(s.to_string()),
_ => None,
})
.collect()
}
/// Set a variable in the environment chain
pub fn env_set(&mut self, name: &JsString, value: JsValue) -> Result<(), JsError> {
let mut current = Some(self.env.clone());
// Create VarKey once for pointer-based lookup
let key = VarKey(name.cheap_clone());
while let Some(env) = current {
let mut env_ref = env.borrow_mut();
if let Some(data) = env_ref.as_environment_mut() {
if let Some(binding) = data.bindings.get_mut(&key) {
if !binding.mutable {
return Err(JsError::type_error(format!(
"Assignment to constant variable '{}'",
name
)));
}
// Update binding value - Gc clone/drop handles ref_count automatically
binding.value = value;
return Ok(());
}
let outer = data.outer.clone();
drop(env_ref);
current = outer;
} else {
break;
}
}
Err(JsError::reference_error(name.to_string()))
}
/// Push a new scope and return the saved environment
pub fn push_scope(&mut self) -> EnvRef {
let (new_env, new_guard) =
create_environment_unrooted(&self.heap, Some(self.env.cheap_clone()));
let old_env = self.env.cheap_clone();
self.env = new_env;
self.env_guards.push(new_guard);
old_env
}
/// Pop scope by restoring saved environment
pub fn pop_scope(&mut self, saved_env: EnvRef) {
self.env = saved_env;
// Pop the guard that was pushed when this scope was created
self.env_guards.pop();
}
/// Push an environment guard (for env changes without push_scope)
pub fn push_env_guard(&mut self, guard: Guard<JsObject>) {
self.env_guards.push(guard);
}
/// Pop an environment guard
pub fn pop_env_guard(&mut self) {
self.env_guards.pop();
}
// ═══════════════════════════════════════════════════════════════════════════
// Object/Array/Function Creation
// ═══════════════════════════════════════════════════════════════════════════
/// Create a new plain object with `object_prototype`.
/// Caller provides the guard to control object lifetime.
pub fn create_object(&mut self, guard: &Guard<JsObject>) -> Gc<JsObject> {
let obj = guard.alloc();
obj.borrow_mut().prototype = Some(self.object_prototype.cheap_clone());
obj
}
/// Create a new plain object without prototype.
/// Caller provides the guard to control object lifetime.
pub fn create_object_raw(&mut self, guard: &Guard<JsObject>) -> Gc<JsObject> {
guard.alloc()
}
/// Create an object with pre-allocated property capacity.
/// Use this when you know the number of properties upfront to avoid hashmap resizing.
pub fn create_object_with_capacity(
&mut self,
guard: &Guard<JsObject>,
capacity: usize,
) -> Gc<JsObject> {
let obj = guard.alloc();
{
let mut obj_ref = obj.borrow_mut();
obj_ref.prototype = Some(self.object_prototype.cheap_clone());
obj_ref.properties.reserve(capacity);
}
obj
}
/// Create a RegExp literal object.
/// Caller provides the guard to control object lifetime.
fn create_regexp_literal(
&mut self,
guard: &Guard<JsObject>,
pattern: &str,
flags: &str,
) -> Gc<JsObject> {
// Pre-intern all property keys
let source_key = PropertyKey::String(self.intern("source"));
let flags_key = PropertyKey::String(self.intern("flags"));
let global_key = PropertyKey::String(self.intern("global"));
let ignore_case_key = PropertyKey::String(self.intern("ignoreCase"));
let multiline_key = PropertyKey::String(self.intern("multiline"));
let dot_all_key = PropertyKey::String(self.intern("dotAll"));
let unicode_key = PropertyKey::String(self.intern("unicode"));
let sticky_key = PropertyKey::String(self.intern("sticky"));
let last_index_key = PropertyKey::String(self.intern("lastIndex"));
let regexp_obj = self.create_object_raw(guard);
{
let mut obj = regexp_obj.borrow_mut();
obj.exotic = ExoticObject::RegExp {
pattern: pattern.to_string(),
flags: flags.to_string(),
compiled: None, // Will be lazily compiled on first use
};
obj.prototype = Some(self.regexp_prototype.clone());
obj.set_property(source_key, JsValue::String(JsString::from(pattern)));
obj.set_property(flags_key, JsValue::String(JsString::from(flags)));
obj.set_property(global_key, JsValue::Boolean(flags.contains('g')));
obj.set_property(ignore_case_key, JsValue::Boolean(flags.contains('i')));
obj.set_property(multiline_key, JsValue::Boolean(flags.contains('m')));
obj.set_property(dot_all_key, JsValue::Boolean(flags.contains('s')));
obj.set_property(unicode_key, JsValue::Boolean(flags.contains('u')));
obj.set_property(sticky_key, JsValue::Boolean(flags.contains('y')));
obj.set_property(last_index_key, JsValue::Number(0.0));
}
regexp_obj
}
/// Create a new array with elements and `array_prototype`.
/// Caller provides the guard to control object lifetime.
pub fn create_array_from(
&mut self,
guard: &Guard<JsObject>,
elements: Vec<JsValue>,
) -> Gc<JsObject> {
let arr = guard.alloc();
{
let mut arr_ref = arr.borrow_mut();
arr_ref.prototype = Some(self.array_prototype.cheap_clone());
arr_ref.exotic = ExoticObject::Array { elements };
}
arr
}
/// Create a new empty array with `array_prototype`.
/// Caller provides the guard to control object lifetime.
pub fn create_empty_array(&mut self, guard: &Guard<JsObject>) -> Gc<JsObject> {
self.create_array_from(guard, Vec::new())
}
/// Create a native function object.
/// Caller provides the guard to control object lifetime.
pub fn create_native_fn(
&mut self,
guard: &Guard<JsObject>,
name: &str,
func: NativeFn,
arity: usize,
) -> Gc<JsObject> {
let name_str = self.intern(name);
let func_obj = guard.alloc();
{
let mut f_ref = func_obj.borrow_mut();
f_ref.prototype = Some(self.function_prototype.clone());
f_ref.exotic = ExoticObject::Function(JsFunction::Native(NativeFunction {
name: name_str,
func,
arity,
ffi_id: 0,
}));
}
func_obj
}
/// Create a native function object with FFI callback support.
/// The `ffi_id` is used to look up the C callback in the FFI registry.
/// Caller provides the guard to control object lifetime.
#[cfg(feature = "c-api")]
pub fn create_ffi_native_fn(
&mut self,
guard: &Guard<JsObject>,
name: &str,
func: NativeFn,
arity: usize,
ffi_id: usize,
) -> Gc<JsObject> {
let name_str = self.intern(name);
let func_obj = guard.alloc();
{
let mut f_ref = func_obj.borrow_mut();
f_ref.prototype = Some(self.function_prototype.clone());
f_ref.exotic = ExoticObject::Function(JsFunction::Native(NativeFunction {
name: name_str,
func,
arity,
ffi_id,
}));
}
func_obj
}
/// Register a pre-built module namespace object as an internal module.
/// This is used by the C FFI to register modules built from C callbacks.
#[cfg(feature = "c-api")]
pub fn register_ffi_module(&mut self, specifier: &str, namespace: Gc<JsObject>) {
// Root the module (lives forever)
self.root_guard.guard(namespace.clone());
// Cache it directly
self.internal_module_cache
.insert(specifier.to_string(), namespace);
}
/// Create a bytecode function object.
/// Caller provides the guard to control object lifetime.
pub fn create_bytecode_function(
&mut self,
guard: &Guard<JsObject>,
bc_func: BytecodeFunction,
) -> Gc<JsObject> {
let length_key = PropertyKey::String(self.intern("length"));
let name_key = PropertyKey::String(self.intern("name"));
let proto_key = PropertyKey::String(self.intern("prototype"));
let ctor_key = PropertyKey::String(self.intern("constructor"));
// Get name, param count, and is_arrow from function_info
let (func_name, param_count, is_arrow) = bc_func
.chunk
.function_info
.as_ref()
.map(|info| {
let name = info
.name
.as_ref()
.map(|n| n.cheap_clone())
.unwrap_or_else(|| JsString::from(""));
(name, info.param_count, info.is_arrow)
})
.unwrap_or_else(|| (JsString::from(""), 0, false));
let func_obj = guard.alloc();
{
let mut f_ref = func_obj.borrow_mut();
f_ref.prototype = Some(self.function_prototype.clone());
f_ref.exotic = ExoticObject::Function(JsFunction::Bytecode(bc_func));
// Set length property (number of formal parameters)
f_ref.set_property(length_key, JsValue::Number(param_count as f64));
// Set name property
f_ref.set_property(name_key, JsValue::String(func_name));
}
// Regular functions (not arrow functions) need a .prototype property
// This is the prototype object that will be used when the function is called with `new`
if !is_arrow {
let proto_obj = guard.alloc();
proto_obj.borrow_mut().prototype = Some(self.object_prototype.clone());
// Set prototype.constructor = function
proto_obj
.borrow_mut()
.set_property(ctor_key, JsValue::Object(func_obj.cheap_clone()));
// Set function.prototype = prototype object
func_obj
.borrow_mut()
.set_property(proto_key, JsValue::Object(proto_obj));
}
func_obj
}
/// Create a bytecode generator function object.
/// Caller provides the guard to control object lifetime.
// NOTE: review
pub fn create_bytecode_generator_function(
&mut self,
guard: &Guard<JsObject>,
bc_func: BytecodeFunction,
) -> Gc<JsObject> {
let length_key = PropertyKey::String(self.intern("length"));
let name_key = PropertyKey::String(self.intern("name"));
// Get name and param count from function_info
let (func_name, param_count) = bc_func
.chunk
.function_info
.as_ref()
.map(|info| {
let name = info
.name
.as_ref()
.map(|n| n.cheap_clone())
.unwrap_or_else(|| JsString::from(""));
(name, info.param_count)
})
.unwrap_or_else(|| (JsString::from(""), 0));
let func_obj = guard.alloc();
{
let mut f_ref = func_obj.borrow_mut();
f_ref.prototype = Some(self.function_prototype.clone());
f_ref.exotic = ExoticObject::Function(JsFunction::BytecodeGenerator(bc_func));
f_ref.set_property(length_key, JsValue::Number(param_count as f64));
f_ref.set_property(name_key, JsValue::String(func_name));
}
func_obj
}
/// Create a bytecode async function object.
/// Caller provides the guard to control object lifetime.
// NOTE: review
pub fn create_bytecode_async_function(
&mut self,
guard: &Guard<JsObject>,
bc_func: BytecodeFunction,
) -> Gc<JsObject> {
let length_key = PropertyKey::String(self.intern("length"));
let name_key = PropertyKey::String(self.intern("name"));
// Get name and param count from function_info
let (func_name, param_count) = bc_func
.chunk
.function_info
.as_ref()
.map(|info| {
let name = info
.name
.as_ref()
.map(|n| n.cheap_clone())
.unwrap_or_else(|| JsString::from(""));
(name, info.param_count)
})
.unwrap_or_else(|| (JsString::from(""), 0));
let func_obj = guard.alloc();
{
let mut f_ref = func_obj.borrow_mut();
f_ref.prototype = Some(self.function_prototype.clone());
f_ref.exotic = ExoticObject::Function(JsFunction::BytecodeAsync(bc_func));
f_ref.set_property(length_key, JsValue::Number(param_count as f64));
f_ref.set_property(name_key, JsValue::String(func_name));
}
func_obj
}
/// Create a bytecode async generator function object.
/// Caller provides the guard to control object lifetime.
pub fn create_bytecode_async_generator_function(
&mut self,
guard: &Guard<JsObject>,
bc_func: BytecodeFunction,
) -> Gc<JsObject> {
let length_key = PropertyKey::String(self.intern("length"));
let name_key = PropertyKey::String(self.intern("name"));
// Get name and param count from function_info
let (func_name, param_count) = bc_func
.chunk
.function_info
.as_ref()
.map(|info| {
let name = info
.name
.as_ref()
.map(|n| n.cheap_clone())
.unwrap_or_else(|| JsString::from(""));
(name, info.param_count)
})
.unwrap_or_else(|| (JsString::from(""), 0));
let func_obj = guard.alloc();
{
let mut f_ref = func_obj.borrow_mut();
f_ref.prototype = Some(self.function_prototype.clone());
f_ref.exotic = ExoticObject::Function(JsFunction::BytecodeAsyncGenerator(bc_func));
f_ref.set_property(length_key, JsValue::Number(param_count as f64));
f_ref.set_property(name_key, JsValue::String(func_name));
}
func_obj
}
// ═══════════════════════════════════════════════════════════════════════════
// Builtin Helper Methods
// ═══════════════════════════════════════════════════════════════════════════
/// Intern a string
pub fn intern(&mut self, s: &str) -> JsString {
self.string_dict.get_or_insert(s)
}
/// Convert a JsValue to its string representation using interned strings
/// for common values (undefined, null, true, false).
pub fn to_js_string(&mut self, value: &JsValue) -> JsString {
match value {
JsValue::Undefined => self.intern("undefined"),
JsValue::Null => self.intern("null"),
JsValue::Boolean(true) => self.intern("true"),
JsValue::Boolean(false) => self.intern("false"),
JsValue::Number(n) => JsString::from(crate::value::number_to_string(*n)),
JsValue::String(s) => s.cheap_clone(),
JsValue::Symbol(s) => match &s.description {
Some(desc) => JsString::from(format!("Symbol({})", desc.as_str())),
None => self.intern("Symbol()"),
},
JsValue::Object(obj) => {
let borrowed = obj.borrow();
match &borrowed.exotic {
ExoticObject::Number(n) => JsString::from(crate::value::number_to_string(*n)),
ExoticObject::StringObj(s) => s.cheap_clone(),
ExoticObject::Boolean(b) => {
if *b {
self.intern("true")
} else {
self.intern("false")
}
}
ExoticObject::Array { elements } => {
let strings: Vec<String> = elements
.iter()
.map(|v| match v {
JsValue::Null | JsValue::Undefined => String::new(),
JsValue::String(s) => s.to_string(),
JsValue::Number(n) => crate::value::number_to_string(*n),
JsValue::Boolean(true) => "true".to_string(),
JsValue::Boolean(false) => "false".to_string(),
_ => "[object Object]".to_string(),
})
.collect();
JsString::from(strings.join(","))
}
_ => self.intern("[object Object]"),
}
}
}
}
/// Get the typeof result for a value as an interned string.
pub fn type_of(&mut self, value: &JsValue) -> JsString {
match value {
JsValue::Undefined => self.intern("undefined"),
JsValue::Null => self.intern("object"), // Historical quirk
JsValue::Boolean(_) => self.intern("boolean"),
JsValue::Number(_) => self.intern("number"),
JsValue::String(_) => self.intern("string"),
JsValue::Symbol(_) => self.intern("symbol"),
JsValue::Object(obj) => {
if obj.borrow().is_callable() {
self.intern("function")
} else {
self.intern("object")
}
}
}
}
/// Create a PropertyKey from a string, using interned strings.
pub fn property_key(&mut self, s: &str) -> PropertyKey {
// Fast path: check if it's an array index
if let Some(first) = s.bytes().next()
&& first.is_ascii_digit()
&& let Ok(idx) = s.parse::<u32>()
&& idx.to_string() == s
{
return PropertyKey::Index(idx);
}
PropertyKey::String(self.intern(s))
}
/// Create a PropertyKey from an already-interned JsString.
pub fn property_key_from_js_string(&mut self, s: JsString) -> PropertyKey {
// Fast path: check if it's an array index
if let Some(first) = s.as_str().bytes().next()
&& first.is_ascii_digit()
&& let Ok(idx) = s.parse::<u32>()
&& idx.to_string() == s.as_str()
{
return PropertyKey::Index(idx);
}
PropertyKey::String(s)
}
/// Create a PropertyKey from a JsValue.
pub fn property_key_from_value(&mut self, value: &JsValue) -> PropertyKey {
match value {
JsValue::Number(n) => {
let idx = *n as u32;
if idx as f64 == *n && *n >= 0.0 {
PropertyKey::Index(idx)
} else {
PropertyKey::String(self.to_js_string(value))
}
}
JsValue::String(s) => self.property_key_from_js_string(s.cheap_clone()),
JsValue::Symbol(s) => PropertyKey::Symbol(s.clone()),
_ => PropertyKey::String(self.to_js_string(value)),
}
}
/// Create a native function object, permanently rooted via `root_guard`.
/// Use this for builtin constructors and methods during initialization.
/// The function is permanently rooted and never collected.
pub fn create_native_function(
&mut self,
name: &str,
func: NativeFn,
arity: usize,
) -> Gc<JsObject> {
let name_str = self.intern(name);
let length_key = PropertyKey::String(self.intern("length"));
let name_key = PropertyKey::String(self.intern("name"));
let func_obj = self.root_guard.alloc();
{
let mut f_ref = func_obj.borrow_mut();
f_ref.prototype = Some(self.function_prototype.clone());
f_ref.exotic = ExoticObject::Function(JsFunction::Native(NativeFunction {
name: name_str.cheap_clone(),
func,
arity,
ffi_id: 0,
}));
// Set length property (number of formal parameters)
f_ref.set_property(length_key, JsValue::Number(arity as f64));
// Set name property
f_ref.set_property(name_key, JsValue::String(name_str));
}
func_obj
}
/// Create a function object from any JsFunction variant.
/// Caller provides the guard to control object lifetime.
pub fn create_js_function(
&mut self,
guard: &Guard<JsObject>,
func: JsFunction,
) -> Gc<JsObject> {
let length_key = PropertyKey::String(self.intern("length"));
let name_key = PropertyKey::String(self.intern("name"));
// Extract name and arity from the function
let (func_name, arity) = match &func {
JsFunction::Native(f) => (f.name.cheap_clone(), f.arity),
JsFunction::Bound(b) => {
// Bound functions: compute name and length from target
let (target_name, target_length) =
if let ExoticObject::Function(target_func) = &b.target.borrow().exotic {
match target_func {
JsFunction::Native(f) => (f.name.to_string(), f.arity),
_ => (String::new(), 0),
}
} else {
(String::new(), 0)
};
let name = self.intern(&format!("bound {}", target_name));
let arity = target_length.saturating_sub(b.bound_args.len());
(name, arity)
}
_ => (self.intern(""), 0),
};
let func_obj = guard.alloc();
{
let mut f_ref = func_obj.borrow_mut();
f_ref.prototype = Some(self.function_prototype.clone());
f_ref.exotic = ExoticObject::Function(func);
// Set length property (number of formal parameters)
f_ref.set_property(length_key, JsValue::Number(arity as f64));
// Set name property
f_ref.set_property(name_key, JsValue::String(func_name));
}
func_obj
}
/// Register a method on an object (for builtin initialization).
/// Uses root_guard internally - functions are permanently rooted.
/// Per ECMAScript spec, builtin methods are: writable, non-enumerable, configurable
pub fn register_method(
&mut self,
obj: &Gc<JsObject>,
name: &str,
func: NativeFn,
arity: usize,
) {
let func_obj = self.create_native_function(name, func, arity);
let key = PropertyKey::String(self.intern(name));
// Builtin methods: writable=true, enumerable=false, configurable=true
let prop = Property::with_attributes(JsValue::Object(func_obj), true, false, true);
obj.borrow_mut().define_property(key, prop);
}
/// Register Symbol.species getter on a constructor.
/// Per ECMAScript spec, Symbol.species is a getter that returns `this`.
/// Uses root_guard internally - the getter is permanently rooted.
/// The property is non-enumerable and configurable.
pub fn register_species_getter(&mut self, constructor: &Gc<JsObject>) {
// Create the getter function that returns `this`
let getter = self.create_native_function("get [Symbol.species]", species_getter, 0);
// Get the well-known Symbol.species
let well_known = self.well_known_symbols;
let species_symbol = JsSymbol::new(well_known.species, Some(self.intern("Symbol.species")));
let species_key = PropertyKey::Symbol(Box::new(species_symbol));
// Create accessor property (no setter, non-enumerable, configurable)
let mut prop = Property::accessor(Some(getter), None);
prop.set_enumerable(false);
prop.set_configurable(true);
constructor.borrow_mut().define_property(species_key, prop);
}
/// Create a guard for a value to prevent it from being garbage collected.
/// Returns Some(guard) if the value is an object, None for primitives.
///
/// Use this to guard input values before operations that may trigger GC.
/// The returned guard must be kept alive for the duration needed.
pub fn guard_value(&mut self, value: &JsValue) -> Option<Guard<JsObject>> {
if let JsValue::Object(obj) = value {
let guard = self.heap.create_guard();
guard.guard(obj.cheap_clone());
Some(guard)
} else {
None
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Generator Support
// ═══════════════════════════════════════════════════════════════════════════
/// Resume a bytecode generator from a suspended state
pub fn resume_bytecode_generator(
&mut self,
gen_state: &Rc<RefCell<BytecodeGeneratorState>>,
) -> Result<Guarded, JsError> {
use bytecode_vm::{BytecodeVM, VmResult};
// Check if generator is already completed
{
let state = gen_state.borrow();
if state.status == GeneratorStatus::Completed {
return Ok(builtins::create_generator_result(
self,
JsValue::Undefined,
true,
));
}
}
// Get generator info
let (
started,
sent_value,
saved_ip,
saved_registers,
saved_call_stack,
saved_try_stack,
chunk,
yield_result_register,
closure,
args,
func_env,
current_env,
this_value,
) = {
let state = gen_state.borrow();
(
state.started,
state.sent_value.clone(),
state.saved_ip,
state.saved_registers.clone(),
state.saved_call_stack.clone(),
state.saved_try_stack.clone(),
state.chunk.clone(),
state.yield_result_register,
state.closure.clone(),
state.args.clone(),
state.func_env.clone(),
state.current_env.clone(),
state.this_value.clone(),
)
};
// Save current environment
let saved_env = self.env.cheap_clone();
// For first call, create a new function environment from the closure
// For subsequent calls, use the saved current environment (which may include block scopes)
let (gen_env, env_guard) = if !started {
// Create a new environment with closure as parent
let (new_env, guard) =
create_environment_unrooted(&self.heap, Some(closure.cheap_clone()));
// Save it for future calls
gen_state.borrow_mut().func_env = Some(new_env.cheap_clone());
(new_env, Some(guard))
} else if let Some(env) = current_env {
// Use the saved current environment (includes any block scopes from yield point)
(env, None)
} else if let Some(env) = func_env {
// Fallback to function environment
(env, None)
} else {
// Fallback: create new environment (shouldn't happen)
let (new_env, guard) =
create_environment_unrooted(&self.heap, Some(closure.cheap_clone()));
gen_state.borrow_mut().func_env = Some(new_env.cheap_clone());
(new_env, Some(guard))
};
// Set the generator's environment as the current environment
self.env = gen_env;
if let Some(guard) = env_guard {
self.push_env_guard(guard);
}
let vm_guard = self.heap.create_guard();
// Run the generator
if !started {
// First call - create a new VM and run from the beginning
gen_state.borrow_mut().started = true;
// Handle rest parameters for generators too
let processed_args: Vec<JsValue> = if let Some(rest_idx) = chunk
.function_info
.as_ref()
.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 = self.create_array_from(&vm_guard, rest_elements);
result_args.push(JsValue::Object(rest_array));
result_args
} else {
args.clone()
};
// Create VM with arguments and the original this value
let mut vm = BytecodeVM::with_guard_and_args(
chunk,
this_value.clone(),
vm_guard,
&processed_args,
);
match vm.run(self) {
VmResult::Complete(guarded) => {
// Generator completed normally
gen_state.borrow_mut().status = GeneratorStatus::Completed;
self.env = saved_env;
Ok(builtins::create_generator_result(self, guarded.value, true))
}
VmResult::Yield(yield_result) => {
// Save the VM state and current environment for resumption
{
let mut state = gen_state.borrow_mut();
state.saved_ip = yield_result.state.ip;
state.saved_registers = yield_result.state.registers;
state.saved_call_stack = yield_result.state.frames;
state.saved_try_stack = yield_result.state.try_stack;
state.yield_result_register = Some(yield_result.resume_register);
// Save current environment (may include block scopes)
state.current_env = Some(self.env.cheap_clone());
}
self.env = saved_env;
Ok(builtins::create_generator_result(
self,
yield_result.value.value, // Extract JsValue from Guarded
false,
))
}
VmResult::YieldStar(yield_star_result) => {
// For yield*, we need to iterate over the iterable
// Save state and start delegating
{
let mut state = gen_state.borrow_mut();
state.saved_ip = yield_star_result.state.ip;
state.saved_registers = yield_star_result.state.registers;
state.saved_call_stack = yield_star_result.state.frames;
state.saved_try_stack = yield_star_result.state.try_stack;
state.yield_result_register = Some(yield_star_result.resume_register);
// Save current environment (may include block scopes)
state.current_env = Some(self.env.cheap_clone());
}
// Delegate to the iterable - get its iterator and next value
self.start_yield_star_delegation(
gen_state,
yield_star_result.iterable.value, // Extract JsValue from Guarded
saved_env,
)
}
VmResult::Suspend(_) | VmResult::SuspendForOrder(_) => {
// Should not happen for generators
gen_state.borrow_mut().status = GeneratorStatus::Completed;
self.env = saved_env;
Err(JsError::internal_error(
"Unexpected suspension in generator",
))
}
VmResult::Error(e) => {
gen_state.borrow_mut().status = GeneratorStatus::Completed;
self.env = saved_env;
Err(e)
}
}
} else {
// Resume from saved state
// Create guard for the saved state
let state_guard = self.heap.create_guard();
// Guard all objects in saved registers
for val in &saved_registers {
if let JsValue::Object(obj) = val {
state_guard.guard(obj.cheap_clone());
}
}
// Guard saved environments in call frames
for frame in &saved_call_stack {
if let Some(ref env) = frame.saved_env {
state_guard.guard(env.cheap_clone());
}
}
let saved_state = bytecode_vm::SavedVmState {
frames: saved_call_stack,
ip: saved_ip,
chunk,
registers: saved_registers,
try_stack: saved_try_stack,
guard: Some(state_guard),
arguments: args.clone(),
new_target: JsValue::Undefined,
trampoline_stack: Vec::new(), // Generators run at top level
};
// Create guard for the VM registers
let vm_guard = self.heap.create_guard();
let mut vm =
BytecodeVM::from_saved_state(saved_state, this_value.clone(), vm_guard, &self.heap);
// Check if we need to throw an exception (generator.throw())
let throw_value = gen_state.borrow_mut().throw_value.take();
if let Some(exception) = throw_value {
// Inject the exception - if there's a handler, it will jump to catch
// If no handler, the exception will propagate
if !vm.inject_exception(self, exception.clone()) {
// No exception handler found, propagate the error
gen_state.borrow_mut().status = GeneratorStatus::Completed;
self.env = saved_env;
let guarded = Guarded::from_value(exception, &self.heap);
return Err(JsError::ThrownValue { guarded });
}
// Handler found - continue to run the VM which will execute the catch block
} else {
// Normal resume - set the sent value in the yield result register
if let Some(resume_reg) = yield_result_register {
vm.set_reg(resume_reg, sent_value);
}
}
match vm.run(self) {
VmResult::Complete(guarded) => {
gen_state.borrow_mut().status = GeneratorStatus::Completed;
self.env = saved_env;
Ok(builtins::create_generator_result(self, guarded.value, true))
}
VmResult::Yield(yield_result) => {
// Save the VM state and current environment for next resumption
{
let mut state = gen_state.borrow_mut();
state.saved_ip = yield_result.state.ip;
state.saved_registers = yield_result.state.registers;
state.saved_call_stack = yield_result.state.frames;
state.saved_try_stack = yield_result.state.try_stack;
state.yield_result_register = Some(yield_result.resume_register);
// Save current environment (may include block scopes)
state.current_env = Some(self.env.cheap_clone());
}
self.env = saved_env;
Ok(builtins::create_generator_result(
self,
yield_result.value.value, // Extract JsValue from Guarded
false,
))
}
VmResult::YieldStar(yield_star_result) => {
// Save state for yield* delegation
{
let mut state = gen_state.borrow_mut();
state.saved_ip = yield_star_result.state.ip;
state.saved_registers = yield_star_result.state.registers;
state.saved_call_stack = yield_star_result.state.frames;
state.saved_try_stack = yield_star_result.state.try_stack;
state.yield_result_register = Some(yield_star_result.resume_register);
// Save current environment (may include block scopes)
state.current_env = Some(self.env.cheap_clone());
}
self.start_yield_star_delegation(
gen_state,
yield_star_result.iterable.value, // Extract JsValue from Guarded
saved_env,
)
}
VmResult::Suspend(_) | VmResult::SuspendForOrder(_) => {
gen_state.borrow_mut().status = GeneratorStatus::Completed;
self.env = saved_env;
Err(JsError::internal_error(
"Unexpected suspension in generator",
))
}
VmResult::Error(e) => {
gen_state.borrow_mut().status = GeneratorStatus::Completed;
self.env = saved_env;
Err(e)
}
}
}
}
/// Start yield* delegation - get the first value from the iterable
fn start_yield_star_delegation(
&mut self,
gen_state: &Rc<RefCell<BytecodeGeneratorState>>,
iterable: JsValue,
saved_env: Gc<JsObject>,
) -> Result<Guarded, JsError> {
// For yield*, we need to:
// 1. Get the iterator from the iterable
// 2. Store it in the generator state for delegation
// 3. Call next() to get the first value
// 4. On subsequent next() calls, delegate to the stored iterator
let is_async = gen_state.borrow().is_async;
// Try to get Symbol.iterator method
let JsValue::Object(obj) = &iterable else {
self.env = saved_env;
return Err(JsError::type_error("yield* value is not iterable"));
};
// Get Symbol.iterator (for async generators, also try Symbol.asyncIterator)
let well_known = self.well_known_symbols;
// Create a guard to keep the iterator and its contents alive throughout delegation
let iter_guard = self.heap.create_guard();
// Try to get the iterator method - for async generators, prefer Symbol.asyncIterator
let sym_iterator = self.intern("Symbol.iterator");
let sym_async_iterator = self.intern("Symbol.asyncIterator");
let iterator_method = if is_async {
// Try Symbol.asyncIterator first
let async_iterator_symbol =
JsSymbol::new(well_known.async_iterator, Some(sym_async_iterator));
let async_iterator_key = PropertyKey::Symbol(Box::new(async_iterator_symbol));
let async_method = obj.borrow().get_property(&async_iterator_key);
if async_method.is_some() {
async_method
} else {
// Fall back to Symbol.iterator
let iterator_symbol =
JsSymbol::new(well_known.iterator, Some(sym_iterator.cheap_clone()));
let iterator_key = PropertyKey::Symbol(Box::new(iterator_symbol));
obj.borrow().get_property(&iterator_key)
}
} else {
let iterator_symbol = JsSymbol::new(well_known.iterator, Some(sym_iterator));
let iterator_key = PropertyKey::Symbol(Box::new(iterator_symbol));
obj.borrow().get_property(&iterator_key)
};
let (iter_obj, next_method) = match iterator_method {
Some(method) => {
// Call the iterator method to get an iterator object
let iter_result = self.call_function(method, iterable.clone(), &[])?;
// Get next method from iterator
let JsValue::Object(iter_obj) = iter_result.value else {
self.env = saved_env;
return Err(JsError::type_error("Iterator is not an object"));
};
// Guard the iterator object to keep it and its properties alive
iter_guard.guard(iter_obj.cheap_clone());
let next_key = self.property_key("next");
let next_method = iter_obj
.borrow()
.get_property(&next_key)
.ok_or_else(|| JsError::type_error("Iterator has no next method"))?;
(iter_obj, next_method)
}
None => {
// Check if it's already an iterator (has .next())
let next_key = self.property_key("next");
if let Some(next_method) = obj.borrow().get_property(&next_key) {
iter_guard.guard(obj.cheap_clone());
(obj.cheap_clone(), next_method)
} else {
self.env = saved_env;
return Err(JsError::type_error("yield* value is not iterable"));
}
}
};
// Call next() to get the first value
let result = self.call_function(
next_method.clone(),
JsValue::Object(iter_obj.cheap_clone()),
&[],
)?;
// Keep guard alive until the iterator is stored in generator state
let _ = &iter_guard;
// For async generators, the result might be a Promise - resolve it synchronously
let actual_result = if is_async {
if let JsValue::Object(result_obj) = &result.value {
if matches!(result_obj.borrow().exotic, ExoticObject::Promise(_)) {
builtins::promise::resolve_promise_sync(self, result_obj)?
} else {
result.value.clone()
}
} else {
result.value.clone()
}
} else {
result.value.clone()
};
// Extract value and done
let (value, done) = self.extract_iterator_result(&actual_result);
if done {
// Iterator is immediately done, resume generator with return value
gen_state.borrow_mut().sent_value = value;
gen_state.borrow_mut().status = GeneratorStatus::Suspended;
self.env = saved_env;
// Resume the generator to continue after yield*
self.resume_bytecode_generator(gen_state)
} else {
// Store the delegated iterator for future next() calls
gen_state.borrow_mut().delegated_iterator = Some((iter_obj, next_method));
gen_state.borrow_mut().status = GeneratorStatus::Suspended;
self.env = saved_env;
Ok(builtins::create_generator_result(self, value, false))
}
}
/// Extract value and done from an iterator result object
fn extract_iterator_result(&mut self, result: &JsValue) -> (JsValue, bool) {
let JsValue::Object(obj) = result else {
return (JsValue::Undefined, true);
};
let value_key = self.property_key("value");
let done_key = self.property_key("done");
let value = obj
.borrow()
.get_property(&value_key)
.unwrap_or(JsValue::Undefined);
let done = match obj.borrow().get_property(&done_key) {
Some(JsValue::Boolean(b)) => b,
_ => false,
};
(value, done)
}
// ═══════════════════════════════════════════════════════════════════════════
// Evaluation Entry Point
// ═══════════════════════════════════════════════════════════════════════════
/// Run bytecode using the bytecode VM
///
/// This is the bytecode execution entry point. It compiles the program
/// to bytecode and then executes it using the bytecode VM.
pub fn run_bytecode(
&mut self,
chunk: Rc<crate::compiler::BytecodeChunk>,
) -> Result<Guarded, JsError> {
self.run_bytecode_with_this(chunk, JsValue::Object(self.global.clone()))
}
/// Run bytecode using the bytecode VM with a specific `this` value
fn run_bytecode_with_this(
&mut self,
chunk: Rc<crate::compiler::BytecodeChunk>,
this_value: JsValue,
) -> Result<Guarded, JsError> {
use bytecode_vm::{BytecodeVM, VmResult};
let vm_guard = self.heap.create_guard();
let mut vm = BytecodeVM::with_guard(chunk, this_value, vm_guard);
match vm.run(self) {
VmResult::Complete(guarded) => Ok(guarded),
VmResult::Error(err) => Err(err),
VmResult::Suspend(_) | VmResult::SuspendForOrder(_) => Err(JsError::internal_error(
"Bytecode execution cannot suspend at top level",
)),
VmResult::Yield(_) | VmResult::YieldStar(_) => Err(JsError::internal_error(
"Bytecode execution cannot yield at top level",
)),
}
}
/// Compile and run source code using bytecode VM
pub fn eval_bytecode(&mut self, source: &str) -> Result<JsValue, JsError> {
use crate::compiler::Compiler;
let mut parser = crate::parser::Parser::new(source, &mut self.string_dict);
let program = parser.parse_program()?;
let chunk = Compiler::compile_program(&program)?;
let result = self.run_bytecode(chunk)?;
Ok(result.value)
}
/// Execute a program (AST) using bytecode compilation
fn execute_program_bytecode(
&mut self,
program: &crate::ast::Program,
) -> Result<JsValue, JsError> {
use crate::compiler::Compiler;
// Use current module path for source file in stack traces
let chunk = if let Some(ref path) = self.current_module_path {
Compiler::compile_program_with_source(program, path.as_str().to_string())?
} else {
Compiler::compile_program(program)?
};
let result = self.run_bytecode(chunk)?;
Ok(result.value)
}
/// Execute a program (AST) for eval with proper completion value tracking
pub fn execute_program_for_eval(
&mut self,
program: &crate::ast::Program,
) -> Result<JsValue, JsError> {
use crate::compiler::Compiler;
let chunk = Compiler::compile_program_for_eval(program)?;
let result = self.run_bytecode(chunk)?;
Ok(result.value)
}
/// Execute a program (AST) for eval with a specific `this` value
pub fn execute_program_for_eval_with_this(
&mut self,
program: &crate::ast::Program,
this_value: JsValue,
) -> Result<JsValue, JsError> {
use crate::compiler::Compiler;
let chunk = Compiler::compile_program_for_eval(program)?;
let result = self.run_bytecode_with_this(chunk, this_value)?;
Ok(result.value)
}
// ═══════════════════════════════════════════════════════════════════════════
// Module Resolution (used by stack-based execution)
// ═══════════════════════════════════════════════════════════════════════════
/// Resolve a module specifier to a module namespace object.
///
/// The specifier is resolved relative to the current module path before
/// looking up in the loaded modules cache.
pub fn resolve_module(&mut self, specifier: &str) -> Result<Gc<JsObject>, JsError> {
// Check internal modules first (use original specifier for internal modules)
if let Some(module) = self.resolve_internal_module(specifier)? {
return Ok(module);
}
// Resolve the specifier to a normalized path
let resolved_path = self.resolve_module_specifier(specifier);
// Check loaded external modules by resolved path
if let Some(module) = self.loaded_modules.get(&resolved_path) {
return Ok(module.clone());
}
Err(JsError::reference_error(format!(
"Module '{}' not found (resolved to '{}')",
specifier, resolved_path
)))
}
/// Resolve an internal module (creates module object on first access)
fn resolve_internal_module(
&mut self,
specifier: &str,
) -> Result<Option<Gc<JsObject>>, JsError> {
// Return cached if exists
if let Some(cached) = self.internal_module_cache.get(specifier) {
return Ok(Some(cached.cheap_clone()));
}
// Check if it's a registered internal module
if !self.internal_modules.contains_key(specifier) {
return Ok(None);
}
// Get module definition - we need to clone to avoid borrow issues
let module_kind = {
let module = self
.internal_modules
.get(specifier)
.ok_or_else(|| JsError::internal_error("Module disappeared"))?;
module.kind.clone()
};
// Create module object based on kind
let guard = self.heap.create_guard();
let module_obj = match module_kind {
crate::InternalModuleKind::Native(exports) => {
self.create_native_module_object(&guard, &exports)?
}
crate::InternalModuleKind::Source(source) => {
self.create_source_module_object(&guard, specifier, &source)?
}
};
// Root the module (lives forever)
self.root_guard.guard(module_obj.clone());
// Cache it
self.internal_module_cache
.insert(specifier.to_string(), module_obj.clone());
Ok(Some(module_obj))
}
/// Create module object from native exports
fn create_native_module_object(
&mut self,
guard: &Guard<JsObject>,
exports: &[(String, crate::InternalExport)],
) -> Result<Gc<JsObject>, JsError> {
let module_obj = self.create_object(guard);
for (name, export) in exports {
let key = PropertyKey::String(self.intern(name));
let value = match export {
crate::InternalExport::Function {
name: fn_name,
func,
arity,
} => {
let fn_obj = self.create_internal_function(fn_name, *func, *arity);
JsValue::Object(fn_obj)
}
crate::InternalExport::Value(v) => v.clone(),
};
module_obj.borrow_mut().set_property(key, value);
}
Ok(module_obj)
}
/// Create module object from TypeScript source
fn create_source_module_object(
&mut self,
guard: &Guard<JsObject>,
_specifier: &str,
source: &str,
) -> Result<Gc<JsObject>, JsError> {
// Parse the source
let mut parser = Parser::new(source, &mut self.string_dict);
let program = parser.parse_program()?;
// Save current environment and exports
let saved_env = self.env.cheap_clone();
let saved_exports = mem::take(&mut self.exports);
// Create module environment (rooted so it persists for live bindings)
let module_env = self.create_module_environment();
// Root the module environment - it must persist for live bindings
self.root_guard.guard(module_env.clone());
self.env = module_env.cheap_clone();
// Set up import bindings before bytecode execution
self.setup_import_bindings(&program)?;
// Execute the module body using bytecode
let result = self.execute_program_bytecode(&program);
// Restore environment
self.env = saved_env;
// Handle errors
result?;
// Create module namespace object from exports
let module_obj = self.create_object(guard);
// Drain exports to a vector to avoid borrow conflict
let exports: Vec<_> = self.exports.drain().collect();
// Create properties for exports with proper live binding support
for (export_name, module_export) in exports {
match module_export {
ModuleExport::Direct { name, value } => {
// Intern the name to ensure pointer-based VarKey lookup works correctly
let interned_name = self.intern(name.as_str());
// Check if there's a binding in the module environment
let has_binding = {
let env_ref = module_env.borrow();
if let Some(env_data) = env_ref.as_environment() {
let var_key = VarKey(interned_name.cheap_clone());
env_data.bindings.contains_key(&var_key)
} else {
false
}
};
if has_binding {
// Direct export with binding: create getter for live binding
let getter_obj = guard.alloc();
{
let mut getter_ref = getter_obj.borrow_mut();
getter_ref.prototype = Some(self.function_prototype.cheap_clone());
getter_ref.exotic =
ExoticObject::Function(JsFunction::ModuleExportGetter {
module_env: module_env.cheap_clone(),
binding_name: interned_name,
});
}
// Set as accessor property (getter only, no setter)
module_obj.borrow_mut().properties.insert(
PropertyKey::String(export_name),
Property::accessor(Some(getter_obj), None),
);
} else {
// Direct export without binding (e.g., namespace re-export)
// Use the stored value directly
module_obj
.borrow_mut()
.set_property(PropertyKey::String(export_name), value);
}
}
ModuleExport::ReExport {
source_module,
source_key,
} => {
// Re-export: create getter that delegates to source module's property
let getter_obj = guard.alloc();
{
let mut getter_ref = getter_obj.borrow_mut();
getter_ref.prototype = Some(self.function_prototype.cheap_clone());
getter_ref.exotic =
ExoticObject::Function(JsFunction::ModuleReExportGetter {
source_module,
source_key,
});
}
// Set as accessor property (getter only, no setter)
module_obj.borrow_mut().properties.insert(
PropertyKey::String(export_name),
Property::accessor(Some(getter_obj), None),
);
}
}
}
// Restore saved exports
self.exports = saved_exports;
Ok(module_obj)
}
/// Create a function from an InternalFn.
/// Uses root_guard internally - the function is permanently rooted.
fn create_internal_function(
&mut self,
name: &str,
func: crate::InternalFn,
arity: usize,
) -> Gc<JsObject> {
// InternalFn and NativeFn have the same signature, so we can use it directly
self.create_native_function(name, func, arity)
}
// ═══════════════════════════════════════════════════════════════════════════
// Class Implementation
// ═══════════════════════════════════════════════════════════════════════════
/// Abstract Equality Comparison Algorithm (ECMAScript spec 7.2.14)
/// Implements the == operator with type coercion
fn abstract_equals(&mut self, left: &JsValue, right: &JsValue) -> bool {
// If types are the same, use strict equality
if mem::discriminant(left) == mem::discriminant(right) {
return left.strict_equals(right);
}
match (left, right) {
// 1. null == undefined and undefined == null
(JsValue::Undefined, JsValue::Null) | (JsValue::Null, JsValue::Undefined) => true,
// 2. Number == String: convert string to number
(JsValue::Number(n), JsValue::String(s)) => *n == s.parse().unwrap_or(f64::NAN),
(JsValue::String(s), JsValue::Number(n)) => s.parse().unwrap_or(f64::NAN) == *n,
// 3. Boolean == anything: convert boolean to number and compare again
(JsValue::Boolean(b), other) => {
let num = if *b { 1.0 } else { 0.0 };
self.abstract_equals(&JsValue::Number(num), other)
}
(other, JsValue::Boolean(b)) => {
let num = if *b { 1.0 } else { 0.0 };
self.abstract_equals(other, &JsValue::Number(num))
}
// 4. Object == String/Number/Symbol: convert object to primitive
(JsValue::Object(_), JsValue::Number(_) | JsValue::String(_)) => {
// ToPrimitive with default hint
match self.coerce_to_primitive(left, "default") {
Ok(prim) => self.abstract_equals(&prim, right),
Err(_) => false,
}
}
(JsValue::Number(_) | JsValue::String(_), JsValue::Object(_)) => {
match self.coerce_to_primitive(right, "default") {
Ok(prim) => self.abstract_equals(left, &prim),
Err(_) => false,
}
}
// 5. Object == Symbol: convert object to primitive
(JsValue::Object(_), JsValue::Symbol(_)) => {
match self.coerce_to_primitive(left, "default") {
Ok(prim) => self.abstract_equals(&prim, right),
Err(_) => false,
}
}
(JsValue::Symbol(_), JsValue::Object(_)) => {
match self.coerce_to_primitive(right, "default") {
Ok(prim) => self.abstract_equals(left, &prim),
Err(_) => false,
}
}
// All other cases: not equal
_ => false,
}
}
/// ToPrimitive: Convert an object to a primitive value.
/// For wrapper objects (Number, String, Boolean), this calls valueOf/toString.
/// `hint` specifies preference: "number" tries valueOf first, "string" tries toString first.
/// For Date objects with "default" hint, uses "string" per ES spec (Date.prototype[@@toPrimitive]).
/// Throws TypeError if neither method returns a primitive value (ES2015+ spec).
fn coerce_to_primitive(&mut self, value: &JsValue, hint: &str) -> Result<JsValue, JsError> {
let obj = match value {
JsValue::Object(obj) => obj,
// Already primitive
_ => return Ok(value.clone()),
};
// Per ES spec: Date objects prefer "string" for "default" hint
// This is what Date.prototype[@@toPrimitive] does
let effective_hint = if hint == "default" {
// Check if this is a Date object
if matches!(obj.borrow().exotic, ExoticObject::Date { .. }) {
"string"
} else {
hint
}
} else {
hint
};
// Determine method order based on hint
let (first_method, second_method) = if effective_hint == "string" {
("toString", "valueOf")
} else {
// "number" - try valueOf first
("valueOf", "toString")
};
// Try first method
let first_key = PropertyKey::String(self.intern(first_method));
let first_prop = obj.borrow().get_property(&first_key);
if let Some(JsValue::Object(method)) = first_prop
&& matches!(method.borrow().exotic, ExoticObject::Function(_))
{
let result = self.call_function(JsValue::Object(method), value.clone(), &[])?;
if !matches!(result.value, JsValue::Object(_)) {
return Ok(result.value);
}
}
// Try second method
let second_key = PropertyKey::String(self.intern(second_method));
if let Some(JsValue::Object(method)) = obj.borrow().get_property(&second_key)
&& matches!(method.borrow().exotic, ExoticObject::Function(_))
{
let result = self.call_function(JsValue::Object(method), value.clone(), &[])?;
if !matches!(result.value, JsValue::Object(_)) {
return Ok(result.value);
}
}
// Per ECMAScript spec: if neither method returns a primitive, throw TypeError
Err(JsError::type_error(
"Cannot convert object to primitive value",
))
}
/// Convert value to number, handling ToPrimitive for objects (ToNumber abstract operation).
/// This properly calls the object's valueOf/toString methods per ECMAScript spec.
pub fn coerce_to_number(&mut self, value: &JsValue) -> Result<f64, JsError> {
match value {
JsValue::Symbol(_) => Err(JsError::type_error(
"Cannot convert a Symbol value to a number",
)),
JsValue::Object(_) => {
let prim = self.coerce_to_primitive(value, "number")?;
// The primitive could be a Symbol if valueOf returns one
if matches!(prim, JsValue::Symbol(_)) {
return Err(JsError::type_error(
"Cannot convert a Symbol value to a number",
));
}
Ok(prim.to_number())
}
_ => Ok(value.to_number()),
}
}
/// Convert value to string, handling ToPrimitive for objects (ToString abstract operation).
/// This properly calls the object's toString/valueOf methods per ECMAScript spec.
pub fn coerce_to_string(&mut self, value: &JsValue) -> Result<JsString, JsError> {
match value {
JsValue::Object(_) => {
// ToPrimitive with "string" hint - tries toString first, then valueOf
let prim = self.coerce_to_primitive(value, "string")?;
Ok(self.to_js_string(&prim))
}
_ => Ok(self.to_js_string(value)),
}
}
/// ToObject abstract operation (ES2015+).
/// Converts primitives to their wrapper objects. Throws TypeError for null/undefined.
/// Returns a `Guarded` to keep wrapper objects alive until the caller is done with them.
pub fn to_object(&mut self, value: JsValue) -> Result<Guarded, JsError> {
match value {
JsValue::Object(obj) => Ok(Guarded::unguarded(JsValue::Object(obj))),
JsValue::Undefined | JsValue::Null => Err(JsError::type_error(
"Cannot convert undefined or null to object",
)),
JsValue::Boolean(b) => {
// Create Boolean wrapper object
let guard = self.heap.create_guard();
let gc_obj = guard.alloc();
{
let mut obj_ref = gc_obj.borrow_mut();
obj_ref.prototype = Some(self.boolean_prototype.cheap_clone());
obj_ref.exotic = ExoticObject::Boolean(b);
}
Ok(Guarded::with_guard(JsValue::Object(gc_obj), guard))
}
JsValue::Number(n) => {
// Create Number wrapper object
let guard = self.heap.create_guard();
let gc_obj = guard.alloc();
{
let mut obj_ref = gc_obj.borrow_mut();
obj_ref.prototype = Some(self.number_prototype.cheap_clone());
obj_ref.exotic = ExoticObject::Number(n);
}
Ok(Guarded::with_guard(JsValue::Object(gc_obj), guard))
}
JsValue::String(s) => {
// Create String wrapper object
let guard = self.heap.create_guard();
let gc_obj = guard.alloc();
{
let mut obj_ref = gc_obj.borrow_mut();
obj_ref.prototype = Some(self.string_prototype.cheap_clone());
obj_ref.exotic = ExoticObject::StringObj(s);
}
Ok(Guarded::with_guard(JsValue::Object(gc_obj), guard))
}
JsValue::Symbol(sym) => {
// Create Symbol wrapper object - use ordinary object with symbol prototype
// Store the symbol value in the exotic slot so it can be retrieved
let guard = self.heap.create_guard();
let gc_obj = guard.alloc();
{
let mut obj_ref = gc_obj.borrow_mut();
obj_ref.prototype = Some(self.symbol_prototype.cheap_clone());
obj_ref.exotic = ExoticObject::Symbol(sym);
}
Ok(Guarded::with_guard(JsValue::Object(gc_obj), guard))
}
}
}
// NOTE: review
// FIXME: pass guard
pub fn call_function(
&mut self,
callee: JsValue,
this_value: JsValue,
args: &[JsValue],
) -> Result<Guarded, JsError> {
self.call_function_with_new_target(callee, this_value, args, JsValue::Undefined)
}
/// Call a function with an explicit new.target value (for constructor calls)
pub fn call_function_with_new_target(
&mut self,
callee: JsValue,
this_value: JsValue,
args: &[JsValue],
new_target: JsValue,
) -> Result<Guarded, JsError> {
let JsValue::Object(func_obj) = callee else {
return Err(JsError::type_error("Not a function"));
};
// Check if this is a proxy - use apply trap
let is_proxy = matches!(func_obj.borrow().exotic, ExoticObject::Proxy(_));
if is_proxy {
return builtins::proxy::proxy_apply(self, func_obj, this_value, args.to_vec());
}
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::Native(native) => {
// Call native function - propagate the Guarded to preserve guard
(native.func)(self, this_value, args)
}
JsFunction::Bytecode(bc_func) => {
// Call bytecode-compiled function using the bytecode VM
self.call_bytecode_function_with_new_target(bc_func, this_value, args, new_target)
}
JsFunction::BytecodeGenerator(bc_func) => {
// Create a new bytecode generator object
self.create_and_call_bytecode_generator(bc_func, this_value, args)
}
JsFunction::BytecodeAsync(bc_func) => {
// Call async function - runs body and wraps result in Promise
self.call_bytecode_async_function(bc_func, this_value, args)
}
JsFunction::BytecodeAsyncGenerator(bc_func) => {
// Create a new bytecode async generator object
self.create_and_call_bytecode_async_generator(bc_func, this_value, args)
}
JsFunction::Bound(bound) => {
// Call bound function: use bound this and prepend bound args
let mut full_args = bound.bound_args.clone();
full_args.extend_from_slice(args);
self.call_function(
JsValue::Object(bound.target),
bound.this_arg.clone(),
&full_args,
)
}
JsFunction::PromiseResolve(promise) => {
let value = args.first().cloned().unwrap_or(JsValue::Undefined);
builtins::promise::resolve_promise_value(self, &promise, value)?;
Ok(Guarded::unguarded(JsValue::Undefined))
}
JsFunction::PromiseReject(promise) => {
let reason = args.first().cloned().unwrap_or(JsValue::Undefined);
builtins::promise::reject_promise_value(self, &promise, reason)?;
Ok(Guarded::unguarded(JsValue::Undefined))
}
JsFunction::PromiseAllFulfill { state, index } => {
let value = args.first().cloned().unwrap_or(JsValue::Undefined);
builtins::promise::handle_promise_all_fulfill(self, &state, index, value)?;
Ok(Guarded::unguarded(JsValue::Undefined))
}
JsFunction::PromiseAllReject(state) => {
let reason = args.first().cloned().unwrap_or(JsValue::Undefined);
builtins::promise::handle_promise_all_reject(self, &state, reason)?;
Ok(Guarded::unguarded(JsValue::Undefined))
}
JsFunction::PromiseRaceSettle {
state,
is_fulfill,
index,
} => {
let value = args.first().cloned().unwrap_or(JsValue::Undefined);
builtins::promise::handle_promise_race_settle(
self, &state, value, is_fulfill, index,
)?;
Ok(Guarded::unguarded(JsValue::Undefined))
}
JsFunction::AccessorGetter => {
// Auto-accessor getter - read from storage slot on `this`
let storage_key_prop = self.intern("__accessor_storage_key__");
let init_value_prop = self.intern("__accessor_init_value__");
let func_ref = func_obj.borrow();
let storage_key = func_ref
.get_property(&PropertyKey::String(storage_key_prop))
.and_then(|v| {
if let JsValue::String(s) = v {
Some(s)
} else {
None
}
});
let init_val = func_ref.get_property(&PropertyKey::String(init_value_prop));
drop(func_ref);
if let Some(key) = storage_key {
if let JsValue::Object(this_obj) = &this_value {
let this_ref = this_obj.borrow();
if let Some(val) = this_ref.get_property(&PropertyKey::String(key)) {
return Ok(Guarded::unguarded(val));
}
}
// Return initial value if not yet set
if let Some(val) = init_val {
return Ok(Guarded::unguarded(val));
}
}
Ok(Guarded::unguarded(JsValue::Undefined))
}
JsFunction::AccessorSetter => {
// Auto-accessor setter - write to storage slot on `this`
let storage_key_prop = self.intern("__accessor_storage_key__");
let value = args.first().cloned().unwrap_or(JsValue::Undefined);
let func_ref = func_obj.borrow();
let storage_key = func_ref
.get_property(&PropertyKey::String(storage_key_prop))
.and_then(|v| {
if let JsValue::String(s) = v {
Some(s)
} else {
None
}
});
drop(func_ref);
if let Some(key) = storage_key
&& let JsValue::Object(this_obj) = &this_value
{
this_obj
.borrow_mut()
.set_property(PropertyKey::String(key), value);
}
Ok(Guarded::unguarded(JsValue::Undefined))
}
JsFunction::ModuleExportGetter {
module_env,
binding_name,
} => {
// Module export getter - read binding from module's environment
let env_ref = module_env.borrow();
if let Some(env_data) = env_ref.as_environment() {
let key = VarKey(binding_name.cheap_clone());
if let Some(binding) = env_data.bindings.get(&key) {
return Ok(Guarded::unguarded(binding.value.clone()));
}
}
Ok(Guarded::unguarded(JsValue::Undefined))
}
JsFunction::ModuleReExportGetter {
source_module,
source_key,
} => {
// Re-export getter - delegate to source module's property
let value = self.resolve_module_property(&source_module, &source_key)?;
Ok(Guarded::unguarded(value))
}
JsFunction::ProxyRevoke(proxy) => {
// Revoke the associated proxy
let mut proxy_ref = proxy.borrow_mut();
if let ExoticObject::Proxy(ref mut data) = proxy_ref.exotic {
data.revoked = true;
}
Ok(Guarded::unguarded(JsValue::Undefined))
}
}
}
/// Call a bytecode-compiled function
fn call_bytecode_function(
&mut self,
bc_func: BytecodeFunction,
this_value: JsValue,
args: &[JsValue],
) -> Result<Guarded, JsError> {
self.call_bytecode_function_with_new_target(bc_func, this_value, args, JsValue::Undefined)
}
/// Call a bytecode-compiled function with an explicit new.target value
// NOTE: review
fn call_bytecode_function_with_new_target(
&mut self,
bc_func: BytecodeFunction,
this_value: JsValue,
args: &[JsValue],
new_target: JsValue,
) -> Result<Guarded, JsError> {
use crate::interpreter::bytecode_vm::{BytecodeVM, VmResult};
// 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());
self.call_stack.push(StackFrame {
function_name: func_name,
location: None,
});
// Create new environment for the function, with closure as parent
let (func_env, func_guard) =
create_environment_unrooted(&self.heap, Some(bc_func.closure.cheap_clone()));
// Bind `this` in the function environment
// For arrow functions, use captured_this; otherwise use provided this_value
let effective_this = if let Some(captured) = bc_func.captured_this {
*captured
} else {
this_value.clone()
};
{
let this_name = self.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,
},
);
}
}
// Set up environment for execution
let saved_env = self.env.cheap_clone();
self.env = func_env;
self.push_env_guard(func_guard);
// Handle rest parameters: if the function has a rest parameter, we need to
// collect all extra arguments into an array at that parameter index
let vm_guard = self.heap.create_guard();
let processed_args: 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);
// Copy regular parameters
for i in 0..rest_idx {
result_args.push(args.get(i).cloned().unwrap_or(JsValue::Undefined));
}
// Collect remaining args into an array for the rest parameter
let rest_elements: Vec<JsValue> = args.get(rest_idx..).unwrap_or_default().to_vec();
let rest_array = self.create_array_from(&vm_guard, rest_elements);
result_args.push(JsValue::Object(rest_array));
result_args
} else {
args.to_vec()
};
// Create VM and run with args pre-populated in registers
// Use new_target if provided (for constructor calls)
let mut vm = BytecodeVM::with_guard_args_and_new_target(
bc_func.chunk.clone(),
effective_this,
vm_guard,
&processed_args,
new_target,
);
let result = vm.run(self);
// Restore environment
self.pop_env_guard();
self.env = saved_env;
self.call_stack.pop();
// Convert VM result to Guarded
match result {
VmResult::Complete(guarded) => Ok(guarded),
VmResult::Error(e) => Err(e),
VmResult::Suspend(_) | VmResult::SuspendForOrder(_) => Err(JsError::internal_error(
"Bytecode function suspended unexpectedly",
)),
VmResult::Yield(_) | VmResult::YieldStar(_) => Err(JsError::internal_error(
"Bytecode function yielded unexpectedly",
)),
}
}
/// Call a bytecode async function - wraps result in Promise
// NOTE: review
fn call_bytecode_async_function(
&mut self,
bc_func: BytecodeFunction,
this_value: JsValue,
args: &[JsValue],
) -> Result<Guarded, JsError> {
// Execute the function body synchronously
let body_result = self.call_bytecode_function(bc_func, this_value, args);
// Wrap result in Promise (fulfilled or rejected)
match body_result {
Ok(guarded) => {
// Promise assimilation: if result is already a Promise, return it directly
if let JsValue::Object(obj) = &guarded.value
&& matches!(obj.borrow().exotic, ExoticObject::Promise(_))
{
return Ok(guarded);
}
// Create fulfilled promise with the result
let result = guarded.value;
let guard = self.heap.create_guard();
let promise = builtins::promise::create_fulfilled_promise(self, &guard, result);
Ok(Guarded::with_guard(JsValue::Object(promise), guard))
}
Err(e) => {
// Create rejected promise with the error
let guard = self.heap.create_guard();
let promise =
builtins::promise::create_rejected_promise(self, &guard, e.to_value());
Ok(Guarded::with_guard(JsValue::Object(promise), guard))
}
}
}
/// Create a bytecode generator object when a generator function is called
// NOTE: review
fn create_and_call_bytecode_generator(
&mut self,
bc_func: BytecodeFunction,
this_value: JsValue,
args: &[JsValue],
) -> Result<Guarded, JsError> {
use crate::value::{BytecodeGeneratorState, GeneratorStatus};
// Generate a unique ID for this generator
let gen_id = self.next_generator_id;
self.next_generator_id = self.next_generator_id.wrapping_add(1);
// Create the generator state with arguments
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, // Will be created on first call to next()
current_env: None, // Will be saved at each yield point
delegated_iterator: None, // For yield* delegation
is_async: false, // Regular generator, not async
throw_value: None, // For generator.throw()
};
// Create the generator object with a guard
let guard = self.heap.create_guard();
let gen_obj = builtins::generator::create_bytecode_generator_object(self, &guard, state);
Ok(Guarded::with_guard(JsValue::Object(gen_obj), guard))
}
/// Create a bytecode async generator object when an async generator function is called
// NOTE: review
fn create_and_call_bytecode_async_generator(
&mut self,
bc_func: BytecodeFunction,
this_value: JsValue,
args: &[JsValue],
) -> Result<Guarded, JsError> {
use crate::value::{BytecodeGeneratorState, GeneratorStatus};
// Generate a unique ID for this generator
let gen_id = self.next_generator_id;
self.next_generator_id = self.next_generator_id.wrapping_add(1);
// Create the generator state with arguments (same as regular generator but with is_async=true)
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, // Will be created on first call to next()
current_env: None, // Will be saved at each yield point
delegated_iterator: None, // For yield* delegation
is_async: true, // Async generator - next() returns Promise
throw_value: None, // For generator.throw()
};
// Create the generator object with a guard
let guard = self.heap.create_guard();
let gen_obj = builtins::generator::create_bytecode_generator_object(self, &guard, state);
Ok(Guarded::with_guard(JsValue::Object(gen_obj), guard))
}
/// Collect all values from an iterable using the Symbol.iterator protocol.
/// Returns a Vec of values if the object is iterable, or None if it doesn't have Symbol.iterator.
/// For arrays, this falls back to directly reading array elements for efficiency.
pub fn collect_iterator_values(
&mut self,
value: &JsValue,
) -> Result<Option<Vec<JsValue>>, JsError> {
let JsValue::Object(obj) = value else {
// Strings are iterable but handled separately
if let JsValue::String(s) = value {
return Ok(Some(
s.as_str()
.chars()
.map(|c| JsValue::String(JsString::from(c.to_string())))
.collect(),
));
}
return Ok(None);
};
// First check if it's a plain array - use fast path
{
let obj_ref = obj.borrow();
if let Some(elements) = obj_ref.array_elements() {
return Ok(Some(elements.to_vec()));
}
}
// Check for Symbol.iterator method
let well_known = self.well_known_symbols;
let iterator_symbol =
JsSymbol::new(well_known.iterator, Some(self.intern("Symbol.iterator")));
let iterator_key = PropertyKey::Symbol(Box::new(iterator_symbol));
let iterator_method = {
let obj_ref = obj.borrow();
obj_ref.get_property(&iterator_key)
};
let Some(JsValue::Object(method_obj)) = iterator_method else {
return Ok(None);
};
// Call the iterator method to get the iterator object
let Guarded {
value: iterator_obj,
guard: _iter_guard,
} = self.call_function(JsValue::Object(method_obj), value.clone(), &[])?;
let JsValue::Object(iterator) = iterator_obj else {
return Err(JsError::type_error("Symbol.iterator must return an object"));
};
// Iterate: call next() until done is true
let mut values = Vec::new();
let next_key = PropertyKey::String(self.intern("next"));
loop {
// Get the next method
let next_method = {
let iter_ref = iterator.borrow();
iter_ref.get_property(&next_key)
};
let Some(JsValue::Object(next_fn)) = next_method else {
return Err(JsError::type_error("Iterator must have a next method"));
};
// Call next()
let Guarded {
value: result,
guard: _result_guard,
} = self.call_function(
JsValue::Object(next_fn),
JsValue::Object(iterator.clone()),
&[],
)?;
let JsValue::Object(result_obj) = result else {
return Err(JsError::type_error("Iterator next() must return an object"));
};
// Check done property
let done = {
let result_ref = result_obj.borrow();
let done_key = PropertyKey::String(self.intern("done"));
result_ref
.get_property(&done_key)
.map(|v| v.to_boolean())
.unwrap_or(false)
};
if done {
break;
}
// Get value property
let iter_value = {
let result_ref = result_obj.borrow();
let value_key = PropertyKey::String(self.intern("value"));
result_ref
.get_property(&value_key)
.unwrap_or(JsValue::Undefined)
};
values.push(iter_value);
}
Ok(Some(values))
}
}
impl Default for Interpreter {
fn default() -> Self {
Self::new()
}
}
/// Native getter for Symbol.species that returns `this`.
/// Per ECMAScript spec, Symbol.species getter returns the constructor itself.
fn species_getter(
_interp: &mut Interpreter,
this: JsValue,
_args: &[JsValue],
) -> Result<Guarded, JsError> {
// Symbol.species getter simply returns `this`
Ok(Guarded::unguarded(this))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_unsigned_right_shift_basic() {
let mut interp = Interpreter::new();
let result = interp.eval_bytecode("32 >>> 2").unwrap();
assert_eq!(result, JsValue::Number(8.0));
}
#[test]
fn test_unsigned_right_shift_negative() {
let mut interp = Interpreter::new();
assert_eq!(
interp.eval_bytecode("-1 >>> 0").unwrap(),
JsValue::Number(4294967295.0)
);
}
#[test]
fn test_basic_arithmetic() {
let mut interp = Interpreter::new();
assert_eq!(interp.eval_bytecode("1 + 2").unwrap(), JsValue::Number(3.0));
assert_eq!(
interp.eval_bytecode("3 * 4").unwrap(),
JsValue::Number(12.0)
);
assert_eq!(
interp.eval_bytecode("10 / 2").unwrap(),
JsValue::Number(5.0)
);
}
#[test]
fn test_continue_outside_loop_error() {
let mut interp = Interpreter::new();
let result = interp.eval_bytecode("continue;");
assert!(result.is_err(), "continue outside loop should error");
let err = result.unwrap_err();
let err_str = format!("{:?}", err);
// Error should mention 'continue' and indicate it's invalid outside a loop
assert!(
err_str.contains("continue")
&& (err_str.contains("loop") || err_str.contains("Illegal")),
"Error should mention 'continue' and 'loop' or 'Illegal': {}",
err_str
);
}
#[test]
fn test_break_outside_loop_error() {
let mut interp = Interpreter::new();
let result = interp.eval_bytecode("break;");
assert!(result.is_err(), "break outside loop should error");
let err = result.unwrap_err();
let err_str = format!("{:?}", err);
// Error should mention 'break' and indicate it's invalid outside a loop/switch
assert!(
err_str.contains("break")
&& (err_str.contains("loop")
|| err_str.contains("switch")
|| err_str.contains("Illegal")),
"Error should mention 'break' and 'loop/switch' or 'Illegal': {}",
err_str
);
}
}