1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
use super::*;
impl<'a> Interp<'a> {
// --- expressions ---
/// Resolves an identifier *reference* and returns its value (`GetValue`):
/// the predeclared globals (`undefined`/`NaN`/`Infinity`), a `with`-object
/// property, a lexical binding, or a global-object own property — throwing a
/// catchable `ReferenceError` when the reference is unresolvable. Shared by a
/// bare-identifier read and the read step of a compound assignment.
pub(crate) fn read_ident_ref(&mut self, name: &str) -> Result<NanBox, ExecError> {
// An imported binding (`import { x } from "m"`) resolves *live* through
// the exporting module's own scope, so a later mutation of the export is
// observed here. A reference before the source module has run leaves the
// slot absent (TDZ) and throws a ReferenceError.
#[cfg(all(feature = "module", feature = "std"))]
if let Some((src_scope, src_name)) = self.module_imports.get(name).cloned() {
return match src_scope.get(&src_name) {
// The slot is either absent (source module not yet run) or holds
// the TDZ sentinel (the source `let`/`const`/`class` is hoisted but
// its initializer has not run): both are an uninitialized binding.
Some(v) if !v.is_tdz() => Ok(v),
_ => {
let msg = self.new_str(&alloc::format!(
"Cannot access '{name}' before initialization"
));
Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(msg)),
))
}
};
}
// A bare identifier inside `with (obj)` first resolves against the
// with-object's properties (via `[[Get]]`, so accessors fire) — this
// shadows even the `undefined`/`NaN`/`Infinity` global identifiers when
// the with-object provides them (`with ({ NaN: 1 }) { NaN }` is 1).
if let Some(h) = self.with_binding_result(name)? {
// `GetBindingValue(N, S)` for an object environment record re-checks
// `? HasProperty(bindingObject, N)` (a second proxy `has` trap) *after*
// the `HasBinding` resolution above — so a binding deleted by the
// `@@unscopables` getter is observed: strict → ReferenceError, sloppy →
// undefined.
if !self.has_property_proxied(h, name)? {
if self.strict {
let msg = self.new_str(&alloc::format!("{name} is not defined"));
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(msg)),
));
}
return Ok(NanBox::undefined());
}
return self.read_member(h, name);
}
self.read_ident_lexical(name)
}
/// The non-`with` portion of `GetValue` for a bare identifier: the
/// predeclared globals, a lexical binding, or a global-object own property.
/// Split out so a caller that has *already* resolved (and rejected) the `with`
/// object frames — e.g. a bare-identifier **call**, whose callee reference and
/// `this`-base must be resolved by a single `HasBinding` — can finish the read
/// without re-consulting the `with` chain (which would re-run its `has` trap).
pub(crate) fn read_ident_lexical(&mut self, name: &str) -> Result<NanBox, ExecError> {
// A live module-import binding (as in `read_ident_ref`) — preserved here so
// callers using this non-`with` path (e.g. a bare-identifier call) still
// resolve imported functions.
#[cfg(all(feature = "module", feature = "std"))]
if let Some((src_scope, src_name)) = self.module_imports.get(name).cloned() {
return match src_scope.get(&src_name) {
Some(v) if !v.is_tdz() => Ok(v),
_ => {
let msg = self.new_str(&alloc::format!(
"Cannot access '{name}' before initialization"
));
Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(msg)),
))
}
};
}
match name {
"undefined" => return Ok(NanBox::undefined()),
"NaN" => return Ok(NanBox::number(f64::NAN)),
"Infinity" => return Ok(NanBox::number(f64::INFINITY)),
_ => {}
}
match self.current.get(name) {
// A binding still in its temporal dead zone (a formal parameter
// referenced by its own / an earlier parameter's default before it is
// initialized — `(a = a) =>`, `(a = b, b) =>`) throws a ReferenceError.
Some(v) if v.is_tdz() => {
let msg = self.new_str(&alloc::format!(
"Cannot access '{name}' before initialization"
));
Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(msg)),
))
}
Some(v) => Ok(v),
// Not in the lexical scope chain: a property added directly to the
// global object (`this.x = …` / `globalThis.x = …` at script level) is
// a global binding, so fall back to a global-object own property.
None => {
if let Some(g) = self.global_this.as_handle().map(Handle::from_raw)
&& self.realm.has_own(g, name)
{
return self.read_member(g, name);
}
let msg = self.new_str(&alloc::format!("{name} is not defined"));
Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(msg)),
))
}
}
}
/// Returns the cached well-known symbol `name` (e.g. `iterator`), creating it
/// on first use. Each is a stable, unique symbol for the realm's lifetime.
pub(crate) fn well_known_symbol(&mut self, name: &'static str) -> NanBox {
if let Some(s) = self.well_known_symbols.get(name) {
return *s;
}
let sym = NanBox::handle(
self.realm
.new_symbol(&alloc::format!("Symbol.{name}"))
.to_raw(),
);
self.well_known_symbols.insert(name, sym);
sym
}
/// Evaluates `e` and returns its JS truthiness (heap-aware, so an empty
/// string is falsy).
pub(crate) fn eval_truthy(&mut self, e: &'a Expr) -> Result<bool, ExecError> {
let v = self.eval(e)?;
Ok(self.realm.truthy(v))
}
/// Calls `f(args)` and returns the result's truthiness.
/// Calls `f` with an explicit `this` and returns whether the result is truthy
/// (for array predicates with a `thisArg`).
pub(crate) fn call_truthy_this(
&mut self,
f: NanBox,
this: NanBox,
args: &[NanBox],
) -> Result<bool, ExecError> {
let r = self.call_with_this(f, this, args)?;
Ok(self.realm.truthy(r))
}
/// Resolves an object/class property key to its string name, evaluating a
/// `[computed]` key expression where present (a symbol maps to its identity
/// key, any other value to its string form).
pub(crate) fn eval_prop_key(&mut self, key: &'a PropertyKey) -> Result<String, ExecError> {
match key {
PropertyKey::Computed(e) => {
let v = self.eval(e)?;
// ToPropertyKey: a symbol keeps its identity; any other object is
// coerced via ToPrimitive(string) so a user `toString` runs and an
// uncoercible key (e.g. `Object.create(null)` or a non-callable
// `Symbol.toPrimitive`) throws a TypeError.
self.coerce_property_key(v)
}
// A private name (`#x`) resolves to the storage key of the `#x`
// declared in the lexically-enclosing class of this access site.
PropertyKey::Private(s) => Ok(self.private_access_key(s)),
_ => static_key(key),
}
}
/// The storage key for a property access value: a symbol becomes a unique,
/// non-enumerable `"\0sym:<id>"` key (so symbol-keyed properties keep their
/// identity and stay out of string enumeration); anything else is its string
/// form.
pub(crate) fn member_key(&self, k: NanBox) -> String {
if let Some(raw) = k.as_handle()
&& let Some((_, id)) = self.realm.symbol_at(Handle::from_raw(raw))
{
return alloc::format!("\u{0}sym:{id}");
}
self.realm.to_display_string(k)
}
/// Inverse of [`member_key`] for handing a property key to a Proxy trap: a
/// `"\0sym:<id>"` storage key becomes the real Symbol *value* (so the trap sees
/// `Symbol(Symbol.iterator)`, not the internal sentinel string); any other key
/// becomes a String.
pub(crate) fn key_to_value(&mut self, name: &str) -> NanBox {
if let Some(idstr) = name.strip_prefix("\u{0}sym:")
&& let Ok(id) = idstr.parse::<u64>()
&& let Some(sh) = self.realm.symbol_for_id(id)
{
return NanBox::handle(sh.to_raw());
}
self.new_str(name)
}
/// The `(old, next)` pair for a `++`/`--` on `current`: `old` is the numeric (or
/// BigInt) value to yield for a postfix update, `next` the incremented/decremented
/// value to store. Runs `ToNumeric` (a BigInt stays BigInt; an object operand goes
/// through ToPrimitive, whose `valueOf`/`toString` may throw).
fn update_value(
&mut self,
op: crate::ast::UpdateOp,
current: NanBox,
) -> Result<(NanBox, NanBox), ExecError> {
if let Some(big) = current
.as_handle()
.and_then(|raw| self.realm.bigint_at(Handle::from_raw(raw)))
{
let one = crate::bignum::BigInt::from_i128(1);
let next = match op {
crate::ast::UpdateOp::Inc => big.add(&one),
crate::ast::UpdateOp::Dec => big.sub(&one),
};
let next_box = NanBox::handle(self.realm.new_bigint(next).to_raw());
let old_box = NanBox::handle(self.realm.new_bigint(big).to_raw());
return Ok((old_box, next_box));
}
let coerced = self.coerce_to_number(current)?;
let old = self.realm.to_number(coerced);
let next = match op {
crate::ast::UpdateOp::Inc => old + 1.0,
crate::ast::UpdateOp::Dec => old - 1.0,
};
Ok((NanBox::number(old), NanBox::number(next)))
}
/// `ToPropertyKey(k)`: like `member_key`, but a non-string, non-symbol object
/// key is coerced with ToPrimitive(String) so a user `toString` is honored
/// (`obj[{toString(){return "x"}}]` keys on `"x"`).
pub(crate) fn coerce_property_key(&mut self, k: NanBox) -> Result<String, ExecError> {
let is_object_key = k.as_handle().is_some_and(|raw| {
let h = Handle::from_raw(raw);
self.realm.symbol_at(h).is_none() && !self.realm.is_string_handle(h)
});
if is_object_key {
let p = self.coerce_object(k, "string")?;
// ToPropertyKey: if ToPrimitive produced a Symbol, it is the key as-is
// (do NOT ToString it). Otherwise ToString the primitive.
if let Some(raw) = p.as_handle()
&& self.realm.symbol_at(Handle::from_raw(raw)).is_some()
{
return Ok(self.member_key(p));
}
return Ok(self.realm.to_display_string(p));
}
Ok(self.member_key(k))
}
/// Invokes a plain object's `[Symbol.toPrimitive](hint)` method, if it has a
/// callable one. Returns `None` to fall back to `valueOf`/`toString`.
pub(crate) fn symbol_to_primitive(
&mut self,
v: NanBox,
hint: &str,
) -> Result<Option<NanBox>, ExecError> {
let Some(raw) = v.as_handle() else {
return Ok(None);
};
let h = Handle::from_raw(raw);
let sym = self.well_known_symbol("toPrimitive");
let key = self.member_key(sym);
// `Get(O, @@toPrimitive)` — through `read_member` so an *accessor*
// `[Symbol.toPrimitive]` getter actually runs (and is observed), and an
// inherited method resolves. A bare `get_property` would skip getters.
let f = self.read_member(h, &key)?;
if !matches!(f.unpack(), Unpacked::Undefined | Unpacked::Null) {
// A non-undefined/null `@@toPrimitive` that is not callable is a
// TypeError (per ToPrimitive step 2.c.i).
if !f
.as_handle()
.is_some_and(|r| self.is_callable(Handle::from_raw(r)))
{
let m = self.new_str("Symbol.toPrimitive is not a function");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
let hint_box = self.new_str(hint);
let r = self.call_with_this(f, v, &[hint_box])?;
// `[Symbol.toPrimitive]` must return a primitive, else a TypeError.
if self.is_object_value(r) {
let m = self.new_str("Cannot convert object to primitive value");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(Some(r));
}
Ok(None)
}
/// Whether `v` is an object (a non-primitive heap value: object/array/function/…)
/// rather than a string/symbol/bigint primitive or an immediate.
pub(crate) fn is_object_value(&self, v: NanBox) -> bool {
v.as_handle().map(Handle::from_raw).is_some_and(|h| {
!self.realm.is_string_handle(h)
&& self.realm.symbol_at(h).is_none()
&& self.realm.bigint_at(h).is_none()
})
}
/// Builds a tagged template's argument list `[stringsObject, ...substitutions]`.
/// The frozen strings object (with its `.raw` array) is created once per
/// template-literal site and reused on every evaluation — its identity is
/// observable to the tag. Shared by the ordinary tagged-template evaluation
/// and the proper-tail-call path (a tagged template's tag is called in tail
/// position).
pub(crate) fn tagged_template_args(
&mut self,
quasi: &'a crate::ast::TemplateLiteral,
) -> Result<Vec<NanBox>, ExecError> {
let cache_key = (core::ptr::from_ref(quasi) as usize, self.eval_site_epoch);
let strings_arr = if let Some(cached) = self.tagged_template_cache.get(&cache_key) {
*cached
} else {
// A quasi with an invalid escape sequence has no cooked value
// (`undefined`), while its `.raw` is still preserved (ES2018).
let strings: Vec<NanBox> = quasi
.quasis
.iter()
.map(|q| match q.cooked.as_deref() {
Some(s) => self.new_str_bytes(s.to_vec()),
None => NanBox::undefined(),
})
.collect();
let raw: Vec<NanBox> = quasi.quasis.iter().map(|q| self.new_str(&q.raw)).collect();
let strings_h = self.realm.new_array(strings);
// The strings object carries a `.raw` array (for `String.raw` and tags
// reading `strings.raw`). Both arrays are frozen, per spec — freeze
// `.raw` first and `strings` last so the property write lands.
let raw_h = self.realm.new_array(raw);
self.realm.freeze_object(raw_h);
self.realm
.set_property(strings_h, "raw", NanBox::handle(raw_h.to_raw()));
// Per spec the template object's `raw` is
// `{ writable:false, enumerable:false, configurable:false }` — mark it
// non-enumerable *before* freezing (freeze then locks writable /
// configurable). Without this it enumerates in `for-in`/`Object.keys`.
self.realm.mark_hidden(strings_h, "raw");
self.realm.freeze_object(strings_h);
let arr = NanBox::handle(strings_h.to_raw());
self.tagged_template_cache.insert(cache_key, arr);
arr
};
let mut args = alloc::vec![strings_arr];
for e in &quasi.expressions {
args.push(self.eval(e)?);
}
Ok(args)
}
pub(crate) fn eval(&mut self, expr: &'a Expr) -> Result<NanBox, ExecError> {
// C2: guard the native recursion that `eval` performs on nested
// expressions (a deep `a + a + … + a` is shallow in the AST but recurses
// here once per term). Throw a catchable `RangeError` past the limit
// instead of overflowing the host stack. Bounded by the dedicated
// `max_eval_depth` knob (separate from `max_call_depth`).
if self.eval_depth >= self.realm.limits.max_eval_depth {
let msg = self.new_str("Maximum call stack size exceeded");
let err = self.make_error(N_ERROR_BASE + 2, Some(msg));
return Err(ExecError::Throw(err));
}
self.eval_depth += 1;
let r = self.eval_inner(expr);
self.eval_depth -= 1;
r
}
pub(crate) fn eval_inner(&mut self, expr: &'a Expr) -> Result<NanBox, ExecError> {
match expr {
Expr::Null(_) => Ok(NanBox::null()),
Expr::Bool { value, .. } => Ok(NanBox::boolean(*value)),
Expr::Number { value, .. } => Ok(NanBox::number(*value)),
Expr::BigInt { digits, .. } => {
let n = parse_bigint(digits);
Ok(NanBox::handle(self.realm.new_bigint(n).to_raw()))
}
Expr::Str { value, .. } => {
// The cooked value is WTF-8 bytes; preserve any lone surrogates.
let h = self.realm.new_string_wtf8(value.to_vec());
Ok(NanBox::handle(h.to_raw()))
}
Expr::Ident(id) => self.read_ident_ref(&id.name),
Expr::Regex { pattern, flags, .. } => Ok(NanBox::handle(
self.new_regexp_instance(pattern, flags).to_raw(),
)),
// A template literal: interleave cooked quasis with interpolations.
// Built as WTF-8 bytes so a surrogate-bearing quasi (`` `\uD800` ``)
// round-trips.
Expr::Template(t) => {
let mut out: Vec<u8> = Vec::new();
for (i, quasi) in t.quasis.iter().enumerate() {
match &quasi.cooked {
Some(cooked) => out.extend_from_slice(cooked),
// An invalid escape is allowed only in a *tagged* template; in a
// plain template literal it is a SyntaxError.
None => {
let m = self.new_str("Invalid escape sequence in template literal");
return Err(ExecError::Throw(self.make_error(N_SYNTAX_ERROR, Some(m))));
}
}
if let Some(e) = t.expressions.get(i) {
let v = self.eval(e)?;
out.extend_from_slice(&self.coerce_to_string_bytes(v)?);
}
}
Ok(self.new_str_bytes(out))
}
// The comma operator: evaluate all, yield the last.
Expr::Sequence { expressions, .. } => {
let mut last = NanBox::undefined();
for e in expressions {
last = self.eval(e)?;
}
Ok(last)
}
// A tagged template: `tag(stringsArray, ...interpolatedValues)`.
Expr::TaggedTemplate { tag, quasi, .. } => {
let args = self.tagged_template_args(quasi)?;
// A `recv.tag` tag (e.g. `String.raw`) is dispatched as a method
// call, so a built-in tag works even if it isn't a readable value.
if let Expr::Member {
object, property, ..
} = &**tag
&& let PropertyKey::Ident(name) | PropertyKey::Str(name) = property
{
let recv = self.eval(object)?;
if let Some(result) = self.call_method(recv, name, &args)? {
return Ok(result);
}
// Fall back to a property-valued tag function. A primitive
// receiver has no callable tag here — a catchable TypeError.
let Some(raw) = recv.as_handle() else {
let m = self.new_str("is not a function");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
};
let f = self.member(Handle::from_raw(raw), property)?;
return self.call_with_this(f, recv, &args);
}
let tagf = self.eval(tag)?;
self.call(tagf, &args)
}
Expr::This(_) => {
// In a derived constructor, `this` is in its temporal dead zone
// until `super(...)` runs (ReferenceError if accessed before).
if self.this_val.is_tdz() {
let m = self.new_str(
"Must call super constructor before accessing 'this' or returning from derived constructor",
);
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
}
Ok(self.this_val)
}
Expr::NewTarget(_) => Ok(self.new_target),
Expr::Await { argument, .. } => {
let v = self.eval(argument)?;
self.await_value(v)
}
// Eager generators: `yield x` appends `x` to the active buffer;
// `yield* it` appends each value of the iterable. The expression's
// own value is `undefined` (we cannot thread `next()` arguments back).
Expr::Yield {
argument, delegate, ..
} => {
let v = match argument {
Some(e) => self.eval(e)?,
None => NanBox::undefined(),
};
if *delegate {
let vals = self.iterate_values(v)?;
if let Some(sink) = self.gen_sink.as_mut() {
if sink.len() + vals.len() > GEN_CAP {
return Err(ExecError::Throw(self.new_str("generator yield limit")));
}
sink.extend(vals);
}
// `yield* iterable` evaluates to the iterator's final value — a
// delegated generator's `return` value (else `undefined`).
let ret = v
.as_handle()
.map(Handle::from_raw)
.and_then(|h| self.realm.get_property(h, GEN_RET))
.unwrap_or(NanBox::undefined());
return Ok(ret);
} else if let Some(sink) = self.gen_sink.as_mut() {
if sink.len() >= GEN_CAP {
return Err(ExecError::Throw(self.new_str("generator yield limit")));
}
sink.push(v);
}
Ok(NanBox::undefined())
}
Expr::Function(func) => Ok(self.eval_fn_expr(func)),
Expr::Arrow(arrow) => Ok(self.eval_arrow(arrow)),
Expr::Class(class) => self.make_class(class),
Expr::Unary { op, argument, .. } => {
// `delete obj.x` removes a property; `typeof undefinedVar` must
// not throw — both inspect the operand rather than its value.
match op {
UnaryOp::Delete => {
// `delete` returns `false` when the property is
// non-configurable (sealed/frozen); `true` otherwise.
let mut result = true;
let mut is_property_delete = false;
// `delete a?.b` unwraps the optional-chain target; a nullish base
// short-circuits the whole `delete` to a no-op returning `true`.
// A *plain* member whose base is nullish is NOT a short-circuit —
// `delete u.x` / `delete n[0]` does ToObject(base), which throws a
// TypeError — so track whether the target was optional.
let (argument, base_optional): (&Expr, bool) = match &**argument {
Expr::OptChain { expr, .. } => (expr, true),
other => (other, false),
};
if let Expr::Member {
object, property, ..
} = argument
{
is_property_delete = true;
// `delete super.prop` / `delete super[expr]` is a runtime
// ReferenceError (a super reference is never deletable).
if matches!(&**object, Expr::Super(_)) {
let m = self.new_str("Cannot delete a super property");
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
}
// A nullish link in the base (`delete a?.b.c` with nullish `a`)
// short-circuits the whole `delete` to a no-op returning `true`.
let obj = match self.eval(object) {
Ok(v) => v,
Err(ExecError::OptShortCircuit) => {
return Ok(NanBox::boolean(true));
}
Err(e) => return Err(e),
};
if matches!(obj.unpack(), Unpacked::Undefined | Unpacked::Null) {
// An optional target (`delete a?.b` with nullish `a`)
// short-circuits to `true`; a plain member delete on a
// nullish base throws a TypeError (ToObject fails).
if base_optional {
return Ok(NanBox::boolean(true));
}
let m = self.new_str("Cannot convert undefined or null to object");
return Err(ExecError::Throw(
self.make_error(N_TYPE_ERROR, Some(m)),
));
}
if let Some(raw) = obj.as_handle() {
let h = Handle::from_raw(raw);
let name = match property {
PropertyKey::Ident(s) | PropertyKey::Str(s) => {
Some(String::from(&**s))
}
PropertyKey::Computed(e) => {
let k = self.eval(e)?;
Some(self.member_key(k))
}
_ => None,
};
if let Some(name) = name {
// A Deferred Module Namespace (`import defer`)
// evaluates its target on a `[[Delete]]` with a
// String (non-"then") key.
#[cfg(all(feature = "module", feature = "std"))]
self.trigger_deferred_namespace(h, &name)?;
// Proxy `deleteProperty` trap, or forward.
if let Some((target, handler)) = self.realm.proxy_at(h) {
self.guard_revoked(h)?;
if let Some(trap) =
self.proxy_trap(handler, "deleteProperty")?
{
let kb = self.key_to_value(&name);
let handler_box = NanBox::handle(handler.to_raw());
let r = self.call_with_this(
trap,
handler_box,
&[NanBox::handle(target.to_raw()), kb],
)?;
result = self.realm.truthy(r);
// Invariant (10.5.10): a true result is
// illegal if the property exists as a
// non-configurable own property of the
// target, or the target is non-extensible
// and the property is present.
if result {
let present = self.realm.has_own(target, &name)
|| self.realm.accessor(target, &name).is_some();
if present
&& self
.realm
.property_is_non_configurable(target, &name)
{
return Err(self.type_error(
"proxy 'deleteProperty' trap removed a non-configurable property",
));
}
if present && !self.realm.is_extensible(target) {
return Err(self.type_error(
"proxy 'deleteProperty' trap removed a property of a non-extensible target",
));
}
}
} else {
// No `deleteProperty` trap: forward
// `[[Delete]]` to the target — which may
// itself be a proxy, so recurse rather than
// doing an ordinary delete on it.
result = self.delete_property_of(target, &name)?;
}
} else if self.realm.typed_kind(h).is_some()
&& let Some(n) = canonical_numeric_index(&name)
{
// Integer-indexed exotic `[[Delete]]`: deleting a
// *valid* index fails (`false`); any other
// canonical numeric index succeeds (`true`), and
// the prototype chain is never consulted.
let is_neg_zero = n == 0.0 && n.is_sign_negative();
let detached = self.typed_array_detached(h);
let valid = !detached
&& !is_neg_zero
&& n == (n as i64) as f64
&& n >= 0.0
&& self
.realm
.typed_len(h)
.is_some_and(|len| (n as usize) < len);
result = !valid;
} else {
// `delete arr[i]` punches a hole in the dense
// store (and rejects a non-configurable index
// or `length`); all other deletes route the
// same way. `delete_property` handles arrays,
// objects, and aux-bearing cells uniformly.
result = self.realm.delete_property(h, &name);
// A successful delete of a mapped `arguments`
// index breaks its aliasing (10.4.4.5).
if result {
self.arg_map_break(h, &name);
}
}
}
}
} else if let Expr::Ident(id) = argument {
if let Some(frame) = self.current.owner_frame(&id.name) {
// A resolvable lexical/var binding is non-deletable
// (a no-op returning `false`) EXCEPT a binding a
// sloppy `eval` introduced as deletable into a
// non-global variable environment
// (EvalDeclarationInstantiation
// `CreateMutableBinding(name, true)`): those are
// removed and return `true`, after which the name
// resolves to a ReferenceError.
if !frame.ptr_eq(&self.global_scope)
&& frame.is_local_deletable(&id.name)
{
frame.delete_local(&id.name);
result = true;
} else {
result = false;
}
} else if let Some(h) = self.with_binding(&id.name) {
// A bare name that resolves through a `with` object's
// environment deletes that object's property — not the
// similarly-named global (`with (o) { delete p }`
// removes `o.p`, leaving any global `p` intact).
result = self.realm.delete_property(h, &id.name);
is_property_delete = true;
} else if let Some(g) = self.global_object()
&& (self.realm.has_own(g, &id.name)
|| self.realm.accessor(g, &id.name).is_some())
{
// `delete name` where `name` resolves to a property of the
// global object: succeeds only if that property is
// configurable (e.g. `delete NaN`/`Infinity`/`undefined`
// — non-configurable — returns `false`).
result = self.realm.delete_property(g, &id.name);
is_property_delete = true;
}
// An unresolvable name (`delete notDefined`) returns `true`.
} else {
// `delete <non-Reference>` (e.g. `delete foo()`): the operand
// is still evaluated for its side effects, then `true` is
// returned (there is no binding/property to remove).
self.eval(argument)?;
}
// A failed delete of a non-configurable property throws in strict
// mode (rather than silently returning `false`).
if self.strict && is_property_delete && !result {
let m =
self.new_str("Cannot delete property of a non-configurable object");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(NanBox::boolean(result));
}
UnaryOp::Typeof => {
// `typeof importedBinding` is *not* the unresolved-reference
// shortcut: an imported binding exists (resolving live, and
// possibly in TDZ), so `typeof` must read it (and may throw
// for a `let`/`const`/`class` export not yet initialised).
#[cfg(all(feature = "module", feature = "std"))]
let is_import = if let Expr::Ident(id) = &**argument {
self.module_imports.contains_key(&*id.name)
} else {
false
};
#[cfg(not(all(feature = "module", feature = "std")))]
let is_import = false;
if let Expr::Ident(id) = &**argument
&& !is_import
&& self.current.get(&id.name).is_none()
&& self.with_binding(&id.name).is_none()
&& !matches!(&*id.name, "undefined" | "NaN" | "Infinity")
// A binding may live only as a global-object own property
// (e.g. `globalThis.x = …`, or a built-in declared onto the
// global object rather than the lexical scope) — `typeof`
// must see it, not report "undefined".
&& !self
.global_this
.as_handle()
.map(Handle::from_raw)
.is_some_and(|g| self.realm.has_own(g, &id.name))
{
return Ok(self.new_str("undefined"));
}
}
_ => {}
}
let v = self.eval(argument)?;
self.unary(*op, v)
}
// `x++` / `++x` / `x--` / `--x` on an identifier or member.
Expr::Update {
op,
prefix,
argument,
..
} => {
// AnnexB web-compat: a direct CallExpression operand of `++`/`--`
// parses in sloppy code but is a runtime ReferenceError (the call is
// evaluated first for its side effects). Strict mode rejected it at
// parse time.
if argument.is_web_compat_call_target() {
self.eval(argument)?;
let m = self
.new_str("Invalid left-hand side expression in prefix/postfix operation");
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
}
// `++super[key]` / `super.x--`: the SuperProperty reference is
// evaluated once (GetThisBinding, then — for a computed key — the key
// expression + GetSuperBase, captured before ToPropertyKey), then
// GetValue and PutValue share it.
if let Expr::Member {
object, property, ..
} = &**argument
&& matches!(&**object, Expr::Super(_))
{
self.require_super_this()?;
let (name, obj_base) = match property {
PropertyKey::Computed(key_expr) => {
let k = self.eval(key_expr)?;
let obj_base = self.object_super_base();
(self.coerce_property_key(k)?, obj_base)
}
_ => {
let name = self.eval_prop_key(property)?;
(name, self.object_super_base())
}
};
let current = match obj_base {
Some(Some(proto)) => self.read_super_member_object(proto, &name)?,
Some(None) => {
return Err(self.type_error("Cannot read property of null (super)"));
}
None => self.resolve_super_member(&name)?,
};
let (old, next) = self.update_value(*op, current)?;
match obj_base {
Some(Some(proto)) => self.assign_super_member_object(proto, &name, next)?,
Some(None) => {
return Err(self.type_error("Cannot set property on null (super)"));
}
None => self.assign_super_member(&name, next)?,
}
return Ok(if *prefix { next } else { old });
}
// For a member target, the reference is evaluated exactly once: the
// base and (computed) key run once, then GetValue + PutValue share
// them — so `obj[keyWithSideEffect()]++` does not run the key twice.
if let Expr::Member {
object, property, ..
} = &**argument
&& !matches!(&**object, Expr::Super(_))
{
let obj = self.eval(object)?;
// Evaluate the computed key *expression* now (observable side
// effects: `base[f()]--` runs `f()`), but defer ToPropertyKey
// (its `toString`) until after the null/undefined-base check —
// so `null[objWithThrowingToString]--` is a TypeError, not the
// key's `toString` error.
let raw_key = match property {
PropertyKey::Computed(e) => Some(self.eval(e)?),
_ => None,
};
if matches!(obj.unpack(), Unpacked::Null | Unpacked::Undefined) {
return Err(self.type_error("Cannot read properties of null or undefined"));
}
// A primitive base is boxed for the read; the write then lands on
// the throwaway wrapper (a no-op, as for any primitive property set).
let handle = match obj.as_handle() {
Some(raw) => Handle::from_raw(raw),
None => Handle::from_raw(
self.coerce_to_object(obj)
.as_handle()
.ok_or_else(|| self.type_error("cannot convert to object"))?,
),
};
let key = match raw_key {
Some(kv) => self.coerce_property_key(kv)?,
None => self.eval_prop_key(property)?,
};
let current = self.read_member(handle, &key)?;
let (old, next) = self.update_value(*op, current)?;
let key_box = self.new_str(&key);
self.assign_member_value(handle, key_box, next)?;
return Ok(if *prefix { next } else { old });
}
// A bare identifier resolving to a `with`-object binding: resolve
// the object ONCE, so a read through a self-mutating getter (e.g.
// `get x(){ delete this.x; return 2 }`) does not change where the
// write lands — GetValue and PutValue share the same reference.
if let Expr::Ident(id) = &**argument
&& let Some(h) = self.with_binding(&id.name)
{
let current = self.read_member(h, &id.name)?;
let (old, next) = self.update_value(*op, current)?;
let key = self.new_str(&id.name);
self.assign_member_value(h, key, next)?;
return Ok(if *prefix { next } else { old });
}
let current = self.read_target(argument)?;
let (old, next) = self.update_value(*op, current)?;
self.assign_to(argument, next)?;
Ok(if *prefix { next } else { old })
}
Expr::Binary {
op, left, right, ..
} => {
// `#x in obj` — the ergonomic brand check (private fields are
// stored under a `#`-prefixed key).
if matches!(op, BinaryOp::In)
&& let Expr::PrivateName(name, _) = &**left
{
let obj = self.eval(right)?;
// §13.10.1: `PrivateIdentifier in ShiftExpression` throws a
// TypeError when the right-hand value is not an Object (rather
// than reporting the brand as absent).
if !self.is_object_value(obj) {
let m = self.new_str(
"Cannot use 'in' operator to check for a private name in a non-object",
);
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
let key = self.private_access_key(name);
let present = obj.as_handle().map(Handle::from_raw).is_some_and(|h| {
self.realm.has_own(h, &key) || self.realm.accessor(h, &key).is_some()
});
return Ok(NanBox::boolean(present));
}
let a = self.eval(left)?;
let b = self.eval(right)?;
self.binary(*op, a, b)
}
Expr::Logical {
op, left, right, ..
} => {
let l = self.eval(left)?;
let take_right = match op {
LogicalOp::And => self.realm.truthy(l),
LogicalOp::Or => !self.realm.truthy(l),
LogicalOp::Nullish => {
matches!(l.unpack(), Unpacked::Undefined | Unpacked::Null)
}
};
if take_right { self.eval(right) } else { Ok(l) }
}
Expr::Conditional {
test,
consequent,
alternate,
..
} => {
if self.eval_truthy(test)? {
self.eval(consequent)
} else {
self.eval(alternate)
}
}
Expr::Assign {
op, target, value, ..
} => self.eval_assign(*op, target, value),
Expr::Call {
callee,
arguments,
optional: call_optional,
..
} => {
// Dynamic `import(specifier)`. The parser desugars it to a call of
// the bare `import` reference; intercept it here (before that
// reference would throw) and return a promise of the requested
// module's namespace object. Works in scripts and modules alike.
#[cfg(all(feature = "module", feature = "std"))]
if let Expr::Ident(id) = &**callee
&& id.name.as_ref() == "import"
{
return self.dynamic_import(arguments);
}
// `import.defer(x)` — the import-defer proposal: load + link but do
// not evaluate, returning a promise of the Deferred Module
// Namespace (which evaluates lazily on first access).
#[cfg(all(feature = "module", feature = "std"))]
if let Expr::Member {
object, property, ..
} = &**callee
&& matches!(&**object, Expr::Ident(id) if id.name.as_ref() == "import")
&& matches!(property, PropertyKey::Ident(p) if &**p == "defer")
{
return self.dynamic_import_deferred(arguments);
}
// `import.source(x)` — the source-phase proposal, unimplemented.
// ToString the specifier (a throw rejects with that), then return a
// promise rejected with a SyntaxError — NOT a plain dynamic import.
#[cfg(all(feature = "module", feature = "std"))]
if let Expr::Member {
object, property, ..
} = &**callee
&& matches!(&**object, Expr::Ident(id) if id.name.as_ref() == "import")
&& matches!(property, PropertyKey::Ident(p) if &**p == "source")
{
let p = self.fresh_promise();
let arg0 = arguments.first().map(|a| match a {
crate::ast::Argument::Item(e) | crate::ast::Argument::Spread(e) => e,
});
let rejection = match arg0 {
Some(e) => match self.eval(e).and_then(|v| self.coerce_to_string(v)) {
Ok(_) => {
let m =
self.new_str("source-phase / deferred import is not supported");
self.make_error(N_SYNTAX_ERROR, Some(m))
}
Err(ExecError::Throw(t)) => t,
Err(other) => return Err(other),
},
None => {
let m = self.new_str("source-phase / deferred import is not supported");
self.make_error(N_SYNTAX_ERROR, Some(m))
}
};
self.settle(p, rejection, false);
return Ok(NanBox::handle(p.to_raw()));
}
// `super(args)` — invoke the base constructor on the current
// instance.
if matches!(&**callee, Expr::Super(_)) {
let args = self.eval_args(arguments)?;
// SuperCall evaluation order: after ArgumentListEvaluation,
// GetSuperConstructor + its IsConstructor check, then
// `Construct(superCtor, args, newTarget)`, and only *then*
// `BindThisValue` — whose "already initialized" check (a second
// `super()`) is a ReferenceError thrown *after* the base
// constructor has run. So even a doomed second `super()` still
// evaluates its arguments and invokes the base constructor (whose
// side effects therefore happen); its result is then discarded.
//
// The instance + this class's id are stashed in
// `pending_this_init` while `this` is in its TDZ (set by the
// derived constructor). A second `super()` leaves it `None`.
let pending = self.pending_this_init;
// GetSuperConstructor reassigned-to-non-constructor check (only the
// first, binding, `super()` reaches BindThisValue without throwing
// for another reason; a second one is a ReferenceError regardless).
if let Some((_, derived_cid)) = pending
&& let Some(cval) = self.class_handles.get(derived_cid as usize).copied()
&& let Some(ch) = cval.as_handle().map(Handle::from_raw)
{
let super_ctor = self
.realm
.object_proto(ch)
.map_or(NanBox::null(), |p| NanBox::handle(p.to_raw()));
if !self.is_constructor_value(super_ctor) {
let m = self.new_str("Super constructor is not a constructor");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
}
// Resolve the super-constructor binding. Normally it is the
// transient `pending_super*` set while the enclosing derived
// constructor runs. But an arrow `() => super()` can be invoked
// *after* that constructor has returned (those transients are then
// cleared) — recover the binding from the arrow's lexical home
// class so the base still runs (SuperCall step 7) before
// BindThisValue throws.
let have_pending = self.pending_super.is_some()
|| self.pending_super_native.is_some()
|| self.pending_super_fn.is_some();
let (eff_super, eff_native, eff_fn) = if have_pending {
(
self.pending_super.clone(),
self.pending_super_native,
self.pending_super_fn,
)
} else if let Some(home) = self.current_home {
let native = self
.class_native_super
.get(home as usize)
.copied()
.flatten();
let fnp = self.class_fn_super.get(home as usize).copied().flatten();
let classp = if native.is_none()
&& fnp.is_none()
&& let Some(class) = self.classes.get(home as usize).copied()
{
let cenv = self.current.clone();
self.resolve_super(class, &cenv)?
} else {
None
};
(classp, native, fnp)
} else {
(None, None, None)
};
// The object the base constructor initializes: the derived
// instance on the first `super()`; a throwaway on a second one
// (the base still runs, but its result is discarded and
// BindThisValue then throws).
let (inst_val, first_call) = match pending {
Some((iv, _)) => (iv, true),
None => (NanBox::handle(self.realm.new_object().to_raw()), false),
};
let inst = inst_val.as_handle().map(Handle::from_raw);
// Point `this` at the object under construction and clear the
// pending marker BEFORE invoking the base constructor — the base's
// body reads `this`, and a nested second `super()` must now see
// `None`. On a second `super()` the already-bound `this` is saved
// and restored after the (discarded) base construction.
let saved_this_val = self.this_val;
self.this_val = inst_val;
self.pending_this_init = None;
// `Construct(superCtor, args, newTarget)`. An Object return rebinds
// `this` (`BindThisValue`), replacing the allocated instance.
let base_result = (|| -> Result<Option<NanBox>, ExecError> {
if let Some((pid, penv)) = eff_super {
match inst {
Some(h) => self.run_constructor(pid, &penv, h, &args),
None => Ok(None),
}
} else if let Some(nid) = eff_native {
// `super(...)` reaching a native constructor (`extends Error`).
if let Some(h) = inst {
self.apply_native_super(nid, h, &args)?;
}
Ok(None)
} else if let Some(fnp) = eff_fn {
// `super(...)` reaching an ordinary-function superclass:
// `[[Construct]](args, newTarget)` — the SuperCall's
// newTarget is the derived constructor's own `new.target`
// (so a `Reflect.construct(Derived, …, NT)` threads `NT`
// into the base function's `new.target`). Its object return
// overrides `this`.
self.pending_new_target = Some(self.new_target);
self.call_with_this(fnp, inst_val, &args).map(Some)
} else {
Err(ExecError::Unsupported(
"super outside a derived constructor",
))
}
})();
if !first_call {
// Second `super()`: the base ran (side effects happened) on the
// throwaway; a base error still precedes BindThisValue, so
// propagate it first, then throw the "already initialized"
// ReferenceError. `this` and the field initializers are
// untouched (fields run exactly once, on the first `super()`).
base_result?;
self.this_val = saved_this_val;
let m = self.new_str("Super constructor may only be called once");
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
}
let returned = base_result?;
// A returned *object* (not a primitive wrapper handle) rebinds
// `this`; the field initializers below then target it.
let this_handle = match self.constructor_return_handle(returned) {
Some(h) => {
self.this_val = NanBox::handle(h.to_raw());
Some(h)
}
None => inst,
};
// `this` is now initialized (BindThisValue): publish it into the
// this-binding cell so an arrow captured before `super()` (whose
// lexical `this` was in its TDZ) observes the bound value. Done
// *after* the base constructor so such an arrow still sees TDZ
// while the base's own body runs.
if let Some(cell) = self.this_cell {
self.realm
.set_hidden_property(cell, THIS_CELL_SLOT, self.this_val);
}
// This class's field initializers run *after* `super()` returns —
// exactly once (a second `super()` took the branch above).
if let Some((_, derived_cid)) = pending
&& let Some(h) = this_handle
{
self.init_instance_fields(derived_cid, h)?;
}
// `SuperCall` evaluates to the newly-bound `this` value
// (`thisER.BindThisValue(result)`), which a base constructor's
// object return may have overridden — so `x = super()` observes it.
return Ok(self.this_val);
}
// `super.method(args)` — invoke the base-class method with the
// current `this`.
if let Expr::Member {
object, property, ..
} = &**callee
&& matches!(&**object, Expr::Super(_))
{
// `super.m(args)` and `super[expr](args)` — resolve the method
// name (a computed key is evaluated to a property key) and invoke
// it with the current `this`.
let name = match property {
PropertyKey::Ident(name) | PropertyKey::Str(name) => {
alloc::string::String::from(&**name)
}
PropertyKey::Number(n) => self.realm.to_display_string(NanBox::number(*n)),
PropertyKey::Computed(e) => {
let k = self.eval(e)?;
self.coerce_property_key(k)?
}
PropertyKey::Private(_) => {
return Err(ExecError::Unsupported("private super member"));
}
};
// MakeSuperPropertyReference does GetThisBinding, which throws a
// ReferenceError if `this` is uninitialized (a derived
// constructor before `super(...)`).
self.require_super_this()?;
let args = self.eval_args(arguments)?;
let f = self.resolve_super_method(&name)?;
return self.call_with_this(f, self.this_val, &args);
}
// A **parenthesized** optional chain used as a call target, e.g.
// `(a?.b)()` / `(a?.b)?.()`. A ParenthesizedExpression is
// reference-transparent, so the call keeps `this` = the member's
// base — unlike a bare `a?.b()` (one chain), the outer `()` is *not*
// part of the chain, so a `?.` short-circuit inside yields
// `undefined` which the outer call then invokes (a TypeError, unless
// the outer call is itself `?.()`).
if let Expr::OptChain { expr, .. } = &**callee
&& let Expr::Member {
object,
property,
optional,
..
} = &**expr
{
let recv = match self.eval(object) {
Ok(v) => v,
// The inner chain short-circuited (`object` was nullish at a
// `?.`): the parenthesized value is `undefined`.
Err(ExecError::OptShortCircuit) => {
if *call_optional {
return Err(ExecError::OptShortCircuit);
}
let args = self.eval_args(arguments)?;
return self.call(NanBox::undefined(), &args);
}
Err(e) => return Err(e),
};
if *optional && matches!(recv.unpack(), Unpacked::Undefined | Unpacked::Null) {
if *call_optional {
return Err(ExecError::OptShortCircuit);
}
let args = self.eval_args(arguments)?;
return self.call(NanBox::undefined(), &args);
}
self.method_recv_check(recv, property, *optional)?;
let args = self.eval_args(arguments)?;
return self.call_member_dispatch(recv, property, *call_optional, &args);
}
// A `recv.method(args)` call: try a built-in method on the
// receiver before falling back to a property-valued function.
if let Expr::Member {
object,
property,
optional,
..
} = &**callee
{
let recv = self.eval(object)?;
// Resolving the callee member (`obj.m`) on a nullish base is a
// TypeError (or, for `obj?.m()`, an optional short-circuit),
// thrown *before* the arguments are evaluated (spec reference
// order): `o.bar.gar(foo())` throws before `foo()`.
self.method_recv_check(recv, property, *optional)?;
let args = self.eval_args(arguments)?;
return self.call_member_dispatch(recv, property, *call_optional, &args);
}
// A bare-identifier callee: resolve the reference **once** (a single
// `HasBinding`) so the `has` trap of a `with (proxy)` frame fires
// exactly once. If a `with` object provides the name, the call's
// `this` is that object (`with (o) { m(); }` calls `o.m` with
// `this`=`o`) and the callee read re-checks `HasProperty`
// (`GetBindingValue`); otherwise finish the read against the lexical
// / global scope without re-consulting the `with` chain.
if let Expr::Ident(id) = &**callee {
let name = &*id.name;
if let Some(h) = self.with_binding_result(name)? {
// `GetBindingValue`: a binding deleted after `HasBinding`
// (via the `@@unscopables` getter) is a strict ReferenceError,
// else `undefined` (→ not-callable TypeError below).
let f = if self.has_property_proxied(h, name)? {
self.read_member(h, name)?
} else if self.strict {
let m = self.new_str(&alloc::format!("{name} is not defined"));
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
} else {
NanBox::undefined()
};
if *call_optional
&& matches!(f.unpack(), Unpacked::Undefined | Unpacked::Null)
{
return Err(ExecError::OptShortCircuit);
}
let args = self.eval_args(arguments)?;
return self.call_with_this(f, NanBox::handle(h.to_raw()), &args);
}
}
let f = if let Expr::Ident(id) = &**callee {
// The `with` chain was already consulted above (no match); finish
// against the lexical / global scope so its `has` trap is not
// re-run.
self.read_ident_lexical(&id.name)?
} else {
self.eval(callee)?
};
if *call_optional && matches!(f.unpack(), Unpacked::Undefined | Unpacked::Null) {
return Err(ExecError::OptShortCircuit);
}
let args = self.eval_args(arguments)?;
// Direct eval: the callee is the literal identifier `eval` and it
// still resolves to the built-in `eval`. Such a call runs in the
// caller's scope (so it can read/modify locals and hoist `var`s),
// inheriting the caller's strictness — unlike an indirect eval,
// which `call`/`call_native` route through the global scope.
//
// An *optional* call `eval?.(x)` is an OptionalChain, not the
// direct-eval syntactic form (`CallExpression : MemberExpression
// Arguments`), so it is always an *indirect* eval — fall through to
// `self.call` below.
if let Expr::Ident(id) = &**callee
&& !*call_optional
&& id.name.as_ref() == "eval"
&& f.as_handle()
.map(Handle::from_raw)
.and_then(|h| self.realm.native_at(h))
== Some(N_EVAL)
{
let arg0 = args.first().copied().unwrap_or(NanBox::undefined());
let Some(source) = arg0
.as_handle()
.and_then(|raw| self.realm.string_value(Handle::from_raw(raw)))
else {
// A non-string argument is returned unchanged (per spec).
return Ok(arg0);
};
return self.eval_string(&source, true);
}
self.call(f, &args)
}
// The optional-chain boundary: a `?.` short-circuit inside becomes
// `undefined` here (the rest of the chain was skipped).
Expr::OptChain { expr, .. } => match self.eval(expr) {
Err(ExecError::OptShortCircuit) => Ok(NanBox::undefined()),
other => other,
},
Expr::New {
callee, arguments, ..
} => {
let f = self.eval(callee)?;
let args = self.eval_args(arguments)?;
self.construct(f, &args)
}
Expr::Array { elements, .. } => {
let mut items = Vec::new();
for el in elements {
match el {
ArrayElement::Hole => items.push(NanBox::hole()),
ArrayElement::Item(e) => items.push(self.eval(e)?),
ArrayElement::Spread(e) => {
let v = self.eval(e)?;
items.extend(self.iterate_values(v)?);
}
}
}
let h = self.realm.new_array(items);
Ok(NanBox::handle(h.to_raw()))
}
Expr::Object { members, .. } => {
let handle = self.realm.new_object();
for m in members {
match m {
ObjectMember::Property {
key,
value,
shorthand,
method,
span: member_span,
} => {
// `{ __proto__: obj }` — only the *unquoted identifier*
// form (not `"__proto__":`, computed, shorthand, or a
// method) sets the prototype; a quoted/computed key makes
// an ordinary own `__proto__` data property.
if !shorthand
&& !matches!(&**value, Expr::Function(_))
&& let PropertyKey::Ident(s) = key
&& &**s == "__proto__"
{
// Per spec, the `__proto__` property name in an object
// literal sets `[[Prototype]]` only when the value is an
// Object or `null`; any other primitive (string, number,
// boolean, undefined, symbol, bigint) is ignored — the
// object keeps `%Object.prototype%` and gains *no* own
// `__proto__` property.
let v = self.eval(value)?;
if matches!(v.unpack(), Unpacked::Null) {
self.realm.set_object_proto(handle, None);
} else if self.is_object_value(v)
&& let Some(p) = v.as_handle().map(Handle::from_raw)
{
self.realm.set_object_proto(handle, Some(p));
}
continue;
}
let k = self.eval_prop_key(key)?;
let v = self.eval(value)?;
// A method / function-valued property is named after its
// key when otherwise anonymous. A computed key that is a
// Symbol names the method `[description]` (or `""`); a
// static identifier/string key names it directly.
if matches!(
&**value,
Expr::Function(_) | Expr::Arrow(_) | Expr::Class(_)
) {
match key {
PropertyKey::Ident(s) | PropertyKey::Str(s) => {
self.set_fn_name(v, s);
}
PropertyKey::Computed(_) => {
// `k` is the storage key (a `\0sym:` key for a
// Symbol); `method_display_name` renders the
// spec name. Install it if the value is still
// anonymous (an anonymous class included).
let params: &[Param] = match &**value {
Expr::Function(f) => &f.params,
_ => &[],
};
if let Some(name) =
self.method_display_name(&k, MethodKind::Method)
&& v.as_handle()
.map(Handle::from_raw)
.is_some_and(|h| self.fn_name_unset(h))
{
if matches!(&**value, Expr::Class(_)) {
// A class already has its `length`; only
// its `name` is set by NamedEvaluation.
let nm = self.new_str(&name);
if let Some(h) = v.as_handle().map(Handle::from_raw)
{
// The class carries a readonly `name`
// `""` placeholder from creation, and
// `set_property` no-ops on a readonly
// property — clear the flag first so the
// NamedEvaluation name actually lands.
self.realm.clear_readonly_property(h, "name");
self.realm.set_property(h, "name", nm);
self.realm.mark_hidden(h, "name");
self.realm.set_readonly_property(h, "name");
}
} else {
self.install_method_meta(v, &name, params);
}
}
}
_ => {}
}
}
// A concise method (`{ m() {} }`, not an arrow) records
// this object as its `[[HomeObject]]`, so `super.x`
// inside it resolves through the object's prototype, and
// is flagged as a method (no `[[Construct]]`).
if *method
&& matches!(&**value, Expr::Function(_))
&& let Some(fv) = v.as_handle().map(Handle::from_raw)
{
// A concise method's source text (ECMA-262
// 20.2.3.5) is its whole MethodDefinition — the key,
// any `*`/`async`/`get`/`set` prefix, params and
// body — i.e. the object member's span, not the
// inner function-expression span `eval` stamped.
self.set_fn_source(v, *member_span);
self.realm.set_hidden_property(
fv,
HOME_OBJECT,
NanBox::handle(handle.to_raw()),
);
if let Some((fid, _)) = self.realm.function_at(fv) {
self.functions[fid as usize].is_method = true;
// A concise method is non-constructable and has
// no `prototype` — except a *generator* method,
// which does. Strip the tentatively-materialized
// property for the non-generator case.
if !self.functions[fid as usize].is_generator {
self.demote_fn_prototype(fv);
}
}
}
self.realm.set_property(handle, &k, v);
}
// `{ ...src }` — copy own enumerable properties.
ObjectMember::Spread { value, .. } => {
let src = self.eval(value)?;
self.object_spread_into(handle, src)?;
}
// `{ get x() {} }` / `{ set x(v) {} }`.
ObjectMember::Accessor {
key,
is_getter,
value,
span: member_span,
} => {
let k = self.eval_prop_key(key)?;
let f = self.make_function(
&value.params,
Body::Block(&value.body),
false,
false,
);
// The accessor's source text (ECMA-262 20.2.3.5) is its
// whole `get`/`set` MethodDefinition — the member span.
self.set_fn_source(f, *member_span);
// An object-literal accessor's `[[HomeObject]]` is this
// object, so `super.x` inside it resolves via the proto;
// an accessor is a method (no `[[Construct]]`).
if let Some(fh) = f.as_handle().map(Handle::from_raw) {
if let Some((fid, _)) = self.realm.function_at(fh) {
self.functions[fid as usize].is_method = true;
}
// An accessor has no `prototype`.
self.demote_fn_prototype(fh);
self.realm.set_hidden_property(
fh,
HOME_OBJECT,
NanBox::handle(handle.to_raw()),
);
// The accessor's `name` is `"get <key>"` / `"set <key>"`
// (a symbol key → `"get [desc]"`), per SetFunctionName.
let kind = if *is_getter {
MethodKind::Get
} else {
MethodKind::Set
};
if let Some(nm) = self.method_display_name(&k, kind)
&& self.fn_name_unset(fh)
{
// `length` is the ExpectedArgumentCount: params
// before the first one with a default / rest. A
// setter with a defaulted param (`set m(x = 42)`)
// therefore has `length` 0, not 1.
let len = value
.params
.iter()
.take_while(|p| p.default.is_none() && !p.rest)
.count()
as u32;
self.install_fn_name_length(fh, &nm, len);
}
}
if *is_getter {
self.realm
.define_accessor(handle, &k, f, NanBox::undefined());
} else {
self.realm
.define_accessor(handle, &k, NanBox::undefined(), f);
}
}
}
}
Ok(NanBox::handle(handle.to_raw()))
}
Expr::Member {
object,
property,
optional,
..
} => {
// `import.meta` — the module meta-property. The parser desugars it
// to `(import).meta`; resolve it to the current module's meta
// object (set up by the module evaluator) here, before the bare
// `import` reference would throw "import is not defined".
#[cfg(all(feature = "module", feature = "std"))]
if let Expr::Ident(id) = &**object
&& id.name.as_ref() == "import"
&& matches!(property, PropertyKey::Ident(p) if &**p == "meta")
{
return Ok(self.import_meta.unwrap_or_else(NanBox::undefined));
}
// `super.name` reads a super getter/method (not via `this`).
if matches!(&**object, Expr::Super(_)) {
// `super[expr]` — a computed super member. Outside any method
// (no `[[HomeObject]]`), `super` is a SyntaxError and the key
// expression must NOT be evaluated; throw before evaluating.
if let PropertyKey::Computed(key_expr) = property {
if self.current_home.is_none() && self.current_home_object.is_none() {
let m = self.new_str("'super' keyword unexpected here");
return Err(ExecError::Throw(self.make_error(N_SYNTAX_ERROR, Some(m))));
}
// GetThisBinding precedes evaluating the key expression: in a
// derived constructor before `super()`, `this` is uninitialized
// → ReferenceError, and the key expression is never evaluated.
self.require_super_this()?;
let key = self.eval(key_expr)?;
// For an object-literal method, GetSuperBase is captured here —
// *before* ToPropertyKey — so a key whose `toString` mutates the
// home object's prototype still reads from the original base.
if let Some(base) = self.object_super_base() {
let name = self.coerce_property_key(key)?;
let Some(proto) = base else {
return Err(self.type_error("Cannot read property of null (super)"));
};
return self.read_super_member_object(proto, &name);
}
// `ToPropertyKey`: a Symbol key must become its sentinel
// form (so `super[Symbol.x]` reads the real symbol-keyed
// property — and, for a deferred namespace, does *not*
// trigger evaluation), not a `"Symbol(…)"` display string.
let name = self.coerce_property_key(key)?;
return self.resolve_super_member(&name);
}
self.require_super_this()?;
let name = match property {
PropertyKey::Ident(name) | PropertyKey::Str(name) => {
alloc::string::String::from(&**name)
}
PropertyKey::Number(n) => self.realm.to_display_string(NanBox::number(*n)),
PropertyKey::Private(_) => {
return Err(ExecError::Unsupported("private super member"));
}
// Computed handled above.
PropertyKey::Computed(_) => unreachable!(),
};
return self.resolve_super_member(&name);
}
let obj = self.eval(object)?;
self.read_member_of(obj, property, *optional)
}
_ => Err(ExecError::Unsupported("expression")),
}
}
/// Phase A of a method call `recv.property(...)`: the nullish-base check that
/// runs *before* argument evaluation. Returns `Err(OptShortCircuit)` when the
/// base is nullish and the member access is optional (`obj?.m()`), a
/// `TypeError` when it is nullish and not optional, and `Ok(())` otherwise.
/// Factored out so the generator/async step-machine can perform it eagerly
/// (correct pre-argument order) before stepping suspending arguments.
pub(crate) fn method_recv_check(
&mut self,
recv: NanBox,
property: &'a PropertyKey,
member_optional: bool,
) -> Result<(), ExecError> {
if matches!(recv.unpack(), Unpacked::Undefined | Unpacked::Null) {
if member_optional {
return Err(ExecError::OptShortCircuit);
}
let key = match property {
PropertyKey::Ident(s) | PropertyKey::Str(s) => alloc::string::String::from(&**s),
PropertyKey::Number(n) => self.realm.to_display_string(NanBox::number(*n)),
PropertyKey::Computed(e) => {
let k = self.eval(e)?;
self.coerce_property_key(k)?
}
PropertyKey::Private(s) => alloc::format!("#{s}"),
};
return Err(self.type_error(&alloc::format!(
"Cannot read properties of {} (reading '{key}')",
self.realm.to_display_string(recv)
)));
}
Ok(())
}
/// Phase C of a method call `recv.property(args)`: the built-in/own-property/
/// primitive dispatch that runs *after* the receiver (already checked
/// non-nullish by [`Self::method_recv_check`]) and the arguments have been
/// evaluated. `call_optional` is the *call*'s own `?.()` flag. Factored out
/// verbatim from the eager `Expr::Call` path so the generator/async
/// step-machine can reify a method call whose *arguments* contain an
/// `await`/`yield`: evaluate the receiver eagerly, step the arguments (so a
/// suspension parks), then complete here with identical semantics (built-in
/// dispatch, own-property shadowing, `this` binding, primitive boxing).
pub(crate) fn call_member_dispatch(
&mut self,
recv: NanBox,
property: &'a PropertyKey,
call_optional: bool,
args: &[NanBox],
) -> Result<NanBox, ExecError> {
// The built-in name-based dispatch (`call_method`) is an
// optimization for *unshadowed* built-in methods. If the
// receiver carries an *own* property of this name (e.g.
// `s.valueOf = Number.prototype.valueOf`), that property is the
// method to invoke — resolving and calling the function value
// preserves its own `this`-validation (so a cross-type
// `Number.prototype.valueOf` call on a String wrapper throws),
// rather than the receiver's built-in behavior.
if let PropertyKey::Ident(name) | PropertyKey::Str(name) = property
&& recv
.as_handle()
.map(Handle::from_raw)
.is_some_and(|h| self.realm.has_own(h, name))
{
let rh = recv.as_handle().map(Handle::from_raw).unwrap();
let f = self.read_member(rh, name)?;
if f.as_handle()
.map(Handle::from_raw)
.is_some_and(|fh| self.is_callable(fh))
{
return self.call_with_this(f, recv, args);
}
}
// A monkey-patched *inherited* `Promise.prototype.{then,catch,finally}` must
// be honored on a direct `promise.then(…)` call: the native fast-path below
// (`call_method`) bypasses the prototype chain, so a user reassignment of
// these methods would otherwise be invisible (observable in reaction/species
// call-counting tests). Only when the resolved method is a *user* function
// (no native backing) do we route through it; the pristine intrinsic keeps
// the fast path.
{
let pname = match property {
PropertyKey::Ident(n) | PropertyKey::Str(n) => Some(&**n),
_ => None,
};
if let Some(name) = pname
&& matches!(name, "then" | "catch" | "finally")
&& let Some(rh) = recv.as_handle().map(Handle::from_raw)
&& self.realm.promise_state(rh).is_some()
{
let f = self.read_member(rh, name)?;
if let Some(fh) = f.as_handle().map(Handle::from_raw)
&& self.is_callable(fh)
&& self.realm.native_at(fh).is_none()
{
return self.call_with_this(f, recv, args);
}
}
}
if let PropertyKey::Ident(name) | PropertyKey::Str(name) = property
&& let Some(result) = self.call_method(recv, name, args)?
{
return Ok(result);
}
// `obj[Symbol.iterator]()` → an iterator over the receiver.
if let PropertyKey::Computed(e) = property {
let key = self.eval(e)?;
let iter_sym = self.well_known_symbol("iterator");
if self.realm.strict_equals(key, iter_sym) {
// A generator/iterator is its own iterator (identity) —
// both the eager built-in iterables (`GEN_BUF`) and a
// lazy generator (`GEN_FRAME`).
if recv.as_handle().map(Handle::from_raw).is_some_and(|h| {
self.realm.get_property(h, GEN_BUF).is_some()
|| self.realm.get_property(h, GEN_FRAME).is_some()
|| self.realm.get_property(h, GEN_COLL).is_some()
|| self.realm.get_property(h, GEN_TA).is_some()
}) {
return Ok(recv);
}
// A typed array yields a **live** values iterator.
if let Some(h) = recv.as_handle().map(Handle::from_raw)
&& self.realm.typed_kind(h).is_some()
{
return Ok(self.make_live_typed_iterator(h, 1));
}
// A real array yields a **live** `%ArrayIterator%` (each `next()`
// re-reads `length` and `Get`s the element at the cursor, so a
// `push`/length change after `[Symbol.iterator]()` is observed —
// `CreateArrayIterator`).
if let Some(h) = recv.as_handle().map(Handle::from_raw)
&& (self.realm.array_elements(h).is_some() || self.realm.is_array(h))
{
return Ok(self.make_live_array_iterator(h, 1));
}
// A generic array-like object whose `@@iterator` is the intrinsic
// `%Array.prototype.values%` (e.g. an `arguments` exotic object)
// also iterates **live** over its `length` property.
if let Some(h) = recv.as_handle().map(Handle::from_raw)
&& self.realm.get_property(h, "length").is_some()
{
let iter_key = self.member_key(iter_sym);
let own_iter = self.realm.get_property(h, &iter_key);
let arr_values = self
.realm
.array_proto_intrinsic()
.and_then(|p| self.realm.get_property(p, "values"));
if let (Some(oi), Some(av)) = (own_iter, arr_values)
&& oi.as_handle().is_some()
&& oi.as_handle() == av.as_handle()
{
return Ok(self.make_live_array_iterator(h, 1));
}
}
// A non-weak Map/Set yields a **live** iterator (a Set
// over its values, a Map over its entries), so
// `s[Symbol.iterator]()` observes mutation mid-iteration.
if let Some(h) = recv.as_handle().map(Handle::from_raw)
&& !self.realm.collection_is_weak(h)
&& self.realm.collection_entries(h).is_some()
{
let is_set = self.realm.collection_is_set(h) == Some(true);
let tag = if is_set {
"Set Iterator"
} else {
"Map Iterator"
};
let kind = if is_set { 1 } else { 2 };
return Ok(self.make_live_collection_iterator(h, kind, tag));
}
let vals = self.iterate_values(recv)?;
// Tag the iterator with the receiver's kind so its
// prototype is the real `%ArrayIteratorPrototype%` /
// `%StringIteratorPrototype%` / `%Map|SetIteratorPrototype%`.
let tag = recv.as_handle().map(Handle::from_raw).and_then(|h| {
if self.realm.array_elements(h).is_some()
|| self.realm.is_array(h)
|| self.realm.typed_kind(h).is_some()
{
Some("Array Iterator")
} else if self.realm.is_string_handle(h)
|| self
.realm
.get_property(h, PRIM_WRAP_TYPE)
.and_then(|t| t.as_number())
== Some(f64::from(N_STRING))
{
// A primitive string cell, or a boxed `String`
// wrapper (`new String("…")`) whose `[[StringData]]`
// lives in the `PRIM_WRAP` slot.
Some("String Iterator")
} else {
match self.realm.collection_is_set(h) {
Some(true) => Some("Set Iterator"),
Some(false) => Some("Map Iterator"),
None => None,
}
}
});
return Ok(match tag {
Some(t) => self.make_builtin_iterator(vals, t),
None => self.make_generator(vals),
});
}
}
// Not a built-in method: read the member and call it.
let Some(raw) = recv.as_handle() else {
if call_optional {
return Err(ExecError::OptShortCircuit);
}
// The receiver is a primitive. `null`/`undefined` cannot be
// coerced, so any member access is a catchable TypeError.
if matches!(recv.unpack(), Unpacked::Undefined | Unpacked::Null) {
let m = self.new_str("cannot read property of null or undefined");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// For a number/boolean primitive, an inherited (or
// prototype-assigned) method is found by boxing the value and
// walking its prototype chain — then invoked with the original
// primitive as `this` (e.g.
// `Number.prototype.toLowerCase = String.prototype.toLowerCase`,
// or a computed key like `false["toString"]()`).
let name = match property {
PropertyKey::Ident(name) | PropertyKey::Str(name) => {
Some(alloc::string::String::from(&**name))
}
PropertyKey::Number(n) => Some(self.realm.to_display_string(NanBox::number(*n))),
PropertyKey::Computed(e) => {
let k = self.eval(e)?;
Some(self.coerce_property_key(k)?)
}
PropertyKey::Private(_) => None,
};
if let Some(name) = name {
let boxed = self.coerce_to_object(recv);
if let Some(bh) = boxed.as_handle().map(Handle::from_raw) {
let f = self.read_member(bh, &name)?;
if call_optional && matches!(f.unpack(), Unpacked::Undefined | Unpacked::Null) {
return Err(ExecError::OptShortCircuit);
}
if f.as_handle()
.is_some_and(|r| self.is_callable(Handle::from_raw(r)))
{
return self.call_with_this(f, recv, args);
}
}
}
let m = self.new_str("is not a function");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
};
let f = self.member(Handle::from_raw(raw), property)?;
// `f?.()` short-circuits when `f` is nullish.
if call_optional && matches!(f.unpack(), Unpacked::Undefined | Unpacked::Null) {
return Err(ExecError::OptShortCircuit);
}
// Method call: `this` is the receiver.
self.call_with_this(f, recv, args)
}
/// Reads `property` off the already-evaluated member base `obj` — the tail of
/// a (non-`super`) `Expr::Member` evaluation, factored out so the generator/
/// async step-machine can reify a member read whose *object* contains an
/// `await`/`yield` (evaluating the base step-by-step, then completing the read
/// here with identical semantics — getters, computed keys, primitive bases).
pub(crate) fn read_member_of(
&mut self,
obj: NanBox,
property: &'a PropertyKey,
optional: bool,
) -> Result<NanBox, ExecError> {
if matches!(obj.unpack(), Unpacked::Undefined | Unpacked::Null) {
if optional {
// Short-circuit the rest of the enclosing optional chain.
return Err(ExecError::OptShortCircuit);
}
// `null.x` / `undefined.x` throws a catchable TypeError.
let msg = self.new_str("cannot read property of null or undefined");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(msg))));
}
let Some(raw) = obj.as_handle() else {
// PrivateFieldGet / PrivateMethodOrAccessorGet step 2: if the receiver
// is not an object (a primitive `this`, e.g. `method.call(15)` reaching
// `this.#p`), throw a TypeError — a primitive can never carry a private
// brand.
if let PropertyKey::Private(s) = property {
let m = self.new_str(&alloc::format!(
"Cannot read private member #{s} from a non-object"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// Reading a property of a number/boolean primitive follows
// GetValue → ToObject → [[Get]]: box the primitive into its wrapper
// (whose [[Prototype]] is the intrinsic `Number.prototype` /
// `Boolean.prototype`) and read through it, so an inherited property
// — a built-in like `constructor`/`toFixed` *or* a user-added
// `Number.prototype.foo` — resolves instead of reporting `undefined`.
if matches!(obj.unpack(), Unpacked::Number(_) | Unpacked::Bool(_)) {
let wrapper = self.coerce_to_object(obj);
if let Some(wh) = wrapper.as_handle().map(Handle::from_raw) {
return self.member(wh, property);
}
}
return Ok(NanBox::undefined());
};
let handle = crate::heap::Handle::from_raw(raw);
self.member(handle, property)
}
/// PutValue for a reference whose base is a **primitive** (number, boolean,
/// string, symbol, or BigInt): ToObject the primitive into its wrapper
/// (`Number.prototype` / `String.prototype` / … on its chain) and perform
/// `[[Set]]` with the primitive as the conceptual receiver. An inherited
/// setter or a Proxy on the wrapper's prototype chain handles the write;
/// otherwise the write would create an own data property on the non-object
/// receiver, which fails — a strict-mode TypeError, a sloppy silent no-op.
pub(crate) fn write_primitive_member(
&mut self,
prim: NanBox,
property: &'a PropertyKey,
new: NanBox,
) -> Result<(), ExecError> {
let key = self.eval_prop_key(property)?;
let wrapper = self.coerce_to_object(prim);
let Some(wh) = wrapper.as_handle().map(Handle::from_raw) else {
return Ok(());
};
if self.set_through_proto_chain(wh, &key, new)?.is_some() {
return Ok(());
}
if self.strict {
return Err(self.type_error(&alloc::format!(
"Cannot create property '{key}' on a primitive value"
)));
}
Ok(())
}
pub(crate) fn eval_fn_expr(&mut self, func: &'a Function) -> NanBox {
// A named function expression binds its own name in an intermediate scope
// that the closure captures, so the body can recurse by that name.
if let Some(id) = &func.id {
let inner = self.current.child();
let saved = core::mem::replace(&mut self.current, inner);
let f = self.make_function(
&func.params,
Body::Block(&func.body),
func.is_async,
func.is_generator,
);
self.set_fn_name(f, &id.name);
self.set_fn_source(f, func.span);
// The name is an immutable binding: reassigning it inside the body
// throws in strict mode and is a silent no-op in sloppy mode.
self.current.declare_soft_const(&id.name, f);
self.current = saved;
return f;
}
let f = self.make_function(
&func.params,
Body::Block(&func.body),
func.is_async,
func.is_generator,
);
self.set_fn_source(f, func.span);
f
}
pub(crate) fn eval_arrow(&mut self, arrow: &'a Arrow) -> NanBox {
let body = match &arrow.body {
ArrowBody::Expr(e) => Body::Expr(e),
ArrowBody::Block(b) => Body::Block(b),
};
let f = self.make_function(&arrow.params, body, arrow.is_async, false);
self.set_fn_source(f, arrow.span);
// Arrows have no own `arguments` binding (they inherit the enclosing one).
if let Some(raw) = f.as_handle()
&& let Some((func_id, _)) = self.realm.function_at(Handle::from_raw(raw))
{
self.functions[func_id as usize].is_arrow = true;
// An arrow is not constructable: strip the `prototype` own property
// `make_method` tentatively materialized (before `is_arrow` was set).
self.demote_fn_prototype(Handle::from_raw(raw));
// Capture the *lexical* `this`/`new.target`/home at the definition site
// (hidden slots), so a later call (including via `call`/`apply`/`bind`)
// resolves them from here rather than the call site.
let h = Handle::from_raw(raw);
self.realm.set_hidden_property(h, ARROW_THIS, self.this_val);
// Inside a derived constructor before `super(...)`, the lexical `this`
// is still in its temporal dead zone. Snapshotting `tdz()` would make
// the arrow throw forever; instead capture the constructor's this-binding
// *cell* so a call resolves the (later-bound) value live.
if self.this_val.is_tdz()
&& let Some(cell) = self.this_cell
{
self.realm
.set_hidden_property(h, ARROW_THIS_CELL, NanBox::handle(cell.to_raw()));
}
self.realm
.set_hidden_property(h, ARROW_NEW_TARGET, self.new_target);
if let Some(home) = self.current_home_object {
self.realm
.set_hidden_property(h, ARROW_HOME_OBJ, NanBox::handle(home.to_raw()));
}
if let Some(hc) = self.current_home {
self.realm
.set_hidden_property(h, ARROW_HOME_CLASS, NanBox::number(f64::from(hc)));
}
self.realm.set_hidden_property(
h,
ARROW_HOME_STATIC,
NanBox::boolean(self.current_home_static),
);
}
f
}
/// Records a function value's name (`fn.name`).
pub(crate) fn set_fn_name(&mut self, value: NanBox, name: &'a str) {
if let Some(raw) = value.as_handle()
&& let Some((func_id, _)) = self.realm.function_at(Handle::from_raw(raw))
// Don't clobber a name the function already has (a named function
// expression keeps its own name over the binding/key name).
&& self.functions[func_id as usize].name.is_empty()
{
self.functions[func_id as usize].name = name;
// Overwrite the `name` "" placeholder materialized at creation with the
// NamedEvaluation name (own, non-enumerable, non-writable, configurable),
// so `hasOwnProperty`/`getOwnPropertyDescriptor`/`verifyProperty` see it.
let handle = Handle::from_raw(raw);
let len = self.functions[func_id as usize]
.params
.iter()
.take_while(|p| p.default.is_none() && !p.rest)
.count() as u32;
self.install_fn_name_length(handle, name, len);
return;
}
// NamedEvaluation of an anonymous class: `let C = class {}` gives the
// class constructor an own `name` of `"C"` (its `length` was already
// installed at class creation). A class with a declared id keeps it.
if let Some(raw) = value.as_handle() {
let handle = Handle::from_raw(raw);
if let Some((cid, _)) = self.realm.class_at(handle)
&& self.classes[cid as usize].id.is_none()
// The class carries a default `name === ""` placeholder unless its
// own body declares a `static name` element (which set the real
// value). Only overwrite the placeholder — never an explicit one.
&& !self.class_declares_static_name(cid)
{
let name_v = self.new_str(name);
self.realm.clear_readonly_property(handle, "name");
self.realm.set_property(handle, "name", name_v);
self.realm.mark_hidden(handle, "name");
self.realm.set_readonly_property(handle, "name");
}
}
}
/// `SetFunctionName` for a name known only at runtime (a `String`, not a
/// source `&'a str`) — used by class field initializers, whose field name is
/// a computed/private key resolved during evaluation. Mirrors [`set_fn_name`]
/// but materializes only the `name` own property (the anonymous function's
/// internal `name` stays `""`; `.name` reads resolve to the own property).
///
/// [`set_fn_name`]: Self::set_fn_name
pub(crate) fn set_fn_name_owned(&mut self, value: NanBox, name: &str) {
if let Some(raw) = value.as_handle()
&& let Some((func_id, _)) = self.realm.function_at(Handle::from_raw(raw))
// Don't clobber a name the function already has (a named function
// expression keeps its own name over the field name).
&& self.functions[func_id as usize].name.is_empty()
{
let handle = Handle::from_raw(raw);
let len = self.functions[func_id as usize]
.params
.iter()
.take_while(|p| p.default.is_none() && !p.rest)
.count() as u32;
self.install_fn_name_length(handle, name, len);
return;
}
// An anonymous class initializer (`#f = class {}`) takes the field name.
if let Some(raw) = value.as_handle() {
let handle = Handle::from_raw(raw);
if let Some((cid, _)) = self.realm.class_at(handle)
&& self.classes[cid as usize].id.is_none()
// The class carries a default `name === ""` placeholder unless its
// own body declares a `static name` element (which set the real
// value). Only overwrite the placeholder — never an explicit one.
&& !self.class_declares_static_name(cid)
{
let name_v = self.new_str(name);
self.realm.clear_readonly_property(handle, "name");
self.realm.set_property(handle, "name", name_v);
self.realm.mark_hidden(handle, "name");
self.realm.set_readonly_property(handle, "name");
}
}
}
/// Whether class `cid`'s body declares a `static name` member (a method,
/// accessor, or field with the literal key `name`) — which supplies the
/// constructor's `name` own property and therefore blocks NamedEvaluation
/// from overwriting it. A computed `static [x]` key is not statically known,
/// so it is conservatively ignored here.
fn class_declares_static_name(&self, cid: u32) -> bool {
self.classes[cid as usize].body.iter().any(|m| {
let (is_static, key) = match m {
crate::ast::ClassMember::Method(mm) => (mm.is_static, &mm.key),
crate::ast::ClassMember::Field(f) => (f.is_static, &f.key),
crate::ast::ClassMember::StaticBlock { .. } => return false,
};
is_static
&& matches!(key, PropertyKey::Ident(s) | PropertyKey::Str(s) if &**s == "name")
})
}
/// `[[Get]]` of integer index `i` on an array-like receiver, returning
/// `Some(value)` when the index is a *present* own element (a typed-array
/// in-bounds element, or a plain-array in-range non-hole slot), or `None`
/// when the read must fall through to the named `[[Get]]` (a hole or an
/// out-of-range index, which consults the prototype chain).
pub(crate) fn array_element_get(
&mut self,
handle: crate::heap::Handle,
i: usize,
) -> Option<NanBox> {
if self.realm.typed_kind(handle).is_some() {
return Some(self.realm.get_element(handle, i));
}
// Only an index within the *dense* backing can be a present element; an
// index in `[dense_len, length)` is a hole or a sparse aux-stored element,
// so fall through (`None`) to the named `[[Get]]` (which consults the aux
// property table, then the prototype chain).
if i < self.realm.array_dense_len(handle).unwrap_or(0) {
let v = self.realm.get_element(handle, i);
if !v.is_hole() {
return Some(v);
}
}
None
}
pub(crate) fn member(
&mut self,
handle: crate::heap::Handle,
key: &'a PropertyKey,
) -> Result<NanBox, ExecError> {
match key {
PropertyKey::Number(n)
if as_index(*n).is_some() && self.realm.is_array_like(handle) =>
{
let i = as_index(*n).unwrap();
if let Some(v) = self.array_element_get(handle, i) {
return Ok(v);
}
// A hole / out-of-range index on a plain array consults the prototype.
self.read_member(handle, &alloc::format!("{i}"))
}
PropertyKey::Computed(e) => {
let k = self.eval(e)?;
if let Some(i) = k.as_number().and_then(as_index)
&& self.realm.is_array_like(handle)
{
if let Some(v) = self.array_element_get(handle, i) {
return Ok(v);
}
return self.read_member(handle, &alloc::format!("{i}"));
}
let name = self.coerce_property_key(k)?;
self.read_member(handle, &name)
}
PropertyKey::Ident(s) | PropertyKey::Str(s) => self.read_member(handle, s),
PropertyKey::Number(n) => self.read_member(handle, &alloc::format!("{n}")),
// Private names (`this.#x`) are stored under a `#`-prefixed key.
PropertyKey::Private(s) => {
// `obj.#x` where obj's class did not declare `#x` is a TypeError, not
// `undefined`. The holder carries the brand as an OWN private element:
// an instance field/method/accessor, or — for `Class.#static` — a
// static private in the class's own statics. Static privates are
// **not inherited**, so a subclass constructor (whose `[[Prototype]]`
// is the base class) that lacks the own element throws even though a
// plain `read_member` would walk up to the base's static private.
let key = self.private_access_key(s);
// A private element is an OWN internal slot, never inherited and
// never routed through a proxy's `get` trap. A private accessor is
// invoked directly; a private field/method is read raw from the
// holder's own storage (its auxiliary object for an exotic holder
// such as a Proxy), bypassing `read_member`'s prototype walk and
// proxy traps.
if let Some((getter, _)) = self.realm.accessor(handle, &key) {
// A private accessor declared with only a setter (`set #g(v) {}`)
// has no getter — reading it is a TypeError.
if matches!(getter.unpack(), Unpacked::Undefined) {
let m = self.new_str(&alloc::format!(
"Cannot read private member #{s} which has only a setter"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return self.call_with_this(getter, NanBox::handle(handle.to_raw()), &[]);
}
if !self.realm.has_own(handle, &key) {
let m = self.new_str(&alloc::format!(
"Cannot read private member #{s} from an object whose class did not declare it"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
Ok(self
.realm
.get_property(handle, &key)
.unwrap_or_else(NanBox::undefined))
}
}
}
/// Reads a member by an already-evaluated key value (an array index when the
/// key is a numeric index and the receiver is an array, else a named read).
pub(crate) fn read_member_value(
&mut self,
handle: crate::heap::Handle,
key: NanBox,
) -> Result<NanBox, ExecError> {
if let Some(i) = key.as_number().and_then(as_index)
&& self.realm.is_array_like(handle)
// A plain Array's element keys are [0, 2**32−1); the boundary value
// 2**32−1 is an ordinary named property. Typed arrays accept any index.
&& (self.realm.typed_kind(handle).is_some() || (i as u64) < u64::from(u32::MAX))
{
// A typed array reads directly (no holes, no prototype indices). A plain
// array reads the element only when the index is a present own slot; a
// hole or an out-of-range index falls through to the named `[[Get]]`
// (which walks the prototype chain).
if self.realm.typed_kind(handle).is_some() {
return Ok(self.realm.get_element(handle, i));
}
if i < self.realm.array_length(handle).unwrap_or(0) {
let v = self.realm.get_element(handle, i);
if !v.is_hole() {
return Ok(v);
}
}
}
let name = self.member_key(key);
self.read_member(handle, &name)
}
/// `{ ...src }` — copy `src`'s own enumerable properties onto `target`
/// (CopyDataProperties). Spreading an array/string copies its indexed elements
/// as `"0"`, `"1"`, … properties; any other object copies its own enumerable
/// string + symbol keys (invoking getters); a primitive is a no-op. Shared by
/// the object-literal evaluator and the generator step-machine.
pub(crate) fn object_spread_into(
&mut self,
target: crate::heap::Handle,
src: NanBox,
) -> Result<(), ExecError> {
if let Some(sh) = src.as_handle().map(Handle::from_raw) {
if let Some(elems) = self.realm.array_elements(sh).map(<[_]>::to_vec) {
for (i, e) in elems.iter().enumerate() {
self.realm.set_property(target, &alloc::format!("{i}"), *e);
}
} else if let Some(s) = self.realm.string_value(sh) {
for (i, c) in s.chars().enumerate() {
let cv = self.new_str(&alloc::string::String::from(c));
self.realm.set_property(target, &alloc::format!("{i}"), cv);
}
} else if self.realm.proxy_at(sh).is_some() {
// A **proxy** source runs full CopyDataProperties through the
// proxy protocol (`ownKeys` trap → per-key enumerable check →
// `get` trap). The plain `object_keys_with_symbols` path below
// reads the proxy *cell's* keys (none), which is why spread
// otherwise saw `{}`.
self.copy_data_properties(target, sh, &[])?;
} else {
let keys = self.realm.object_keys_with_symbols(sh);
for key in keys {
// `read_member` invokes a getter where present.
let pv = self.read_member(sh, &key)?;
self.realm.set_property(target, &key, pv);
}
}
}
Ok(())
}
/// OrdinarySet's *parent* walk for a computed write when the receiver has no
/// own binding for `key`: an inherited **setter**, or a **proxy** on the
/// prototype chain, performs the write via `parent.[[Set]]` (the setter runs,
/// or the proxy's `set` trap fires, with Receiver = the original object).
/// Returns `Some(())` if the chain handled the write (the caller must NOT
/// create an own property), or `None` to fall through to the ordinary
/// own-property write. Mirrors the `assign_member` (dot-key) prototype walk so
/// the computed-key path (`o[k] = v`, `arr[i] = v`) matches it.
pub(crate) fn set_through_proto_chain(
&mut self,
receiver: crate::heap::Handle,
key: &str,
new: NanBox,
) -> Result<Option<()>, ExecError> {
let mut cur = self.realm.object_proto(receiver);
while let Some(c) = cur {
// A proxy above the receiver handles the write through its own
// `[[Set]]` (trap, or trapless forward to an inherited setter, else the
// own-property creation on the receiver).
if let Some((target, p_handler)) = self.realm.proxy_at(c) {
self.guard_revoked(c)?;
if let Some(trap) = self.proxy_trap(p_handler, "set")? {
let key_box = self.new_str(key);
let recv = NanBox::handle(receiver.to_raw());
let handler_box = NanBox::handle(p_handler.to_raw());
let r = self.call_with_this(
trap,
handler_box,
&[NanBox::handle(target.to_raw()), key_box, new, recv],
)?;
if self.strict && !self.realm.truthy(r) {
let m = self.new_str(&alloc::format!(
"'set' on proxy: trap returned falsish for property '{key}'"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(Some(()));
}
if let Some((_, setter)) = self.realm.accessor(target, key)
&& !matches!(setter.unpack(), Unpacked::Undefined)
{
let this = NanBox::handle(receiver.to_raw());
self.call_with_this(setter, this, &[new])?;
return Ok(Some(()));
}
return Ok(None);
}
// Integer-indexed exotic `[[Set]]` reached via the prototype chain: a
// *canonical numeric index* on a typed array in the chain never delegates
// to a prototype accessor (10.4.5.5). An **invalid** index (out of bounds /
// fractional / `-0` / negative / detached) is a silent no-op success — the
// write is dropped and the chain is *not* walked further (so a getter/setter
// defined on `%TypedArray.prototype%[key]` is unreachable). A **valid** index
// falls through to the `has_own` shadow-break below (the element shadows any
// prototype accessor; the caller then writes an own property on the receiver).
if self.realm.typed_kind(c).is_some()
&& let Some(n) = canonical_numeric_index(key)
{
let is_neg_zero = n == 0.0 && n.is_sign_negative();
let valid = !self.typed_array_detached(c)
&& !is_neg_zero
&& n == (n as i64) as f64
&& n >= 0.0
&& self
.realm
.typed_len(c)
.is_some_and(|len| (n as usize) < len);
if !valid {
return Ok(Some(()));
}
}
if let Some((_, setter)) = self.realm.accessor(c, key) {
if !matches!(setter.unpack(), Unpacked::Undefined) {
let this = NanBox::handle(receiver.to_raw());
self.call_with_this(setter, this, &[new])?;
}
// A getter-only inherited accessor shadows the data write (the
// existing computed-path behavior; strict-throw is not introduced
// here to avoid changing unrelated cases).
return Ok(Some(()));
}
// An own data property below shadows an inherited accessor/proxy.
if self.realm.has_own(c, key) {
// OrdinarySetWithOwnDescriptor recursion: a *non-writable* inherited
// data property makes the whole [[Set]] fail — strict throws, sloppy
// silently drops — and no shadowing own property is created on the
// receiver. A writable inherited data property allows shadowing (fall
// through to the own-property write on the receiver). The walk starts
// above the receiver, so `c` is always an ancestor here.
if !self.can_write_property(c, key) {
if self.strict {
let m = self.new_str(&alloc::format!(
"Cannot assign to read only property '{key}'"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(Some(()));
}
break;
}
cur = self.realm.object_proto(c);
}
Ok(None)
}
/// A proxy's `[[Set]]` returning the **boolean** result (for `Reflect.set`,
/// which reports success/failure rather than throwing on a falsy trap
/// result): invokes the `set` trap with `receiver`, or forwards trapless to
/// the target's `[[Set]]` (recursing if the target is itself a proxy). A
/// truthy trap result is subject to the success invariants (which *do*
/// throw). An ordinary (non-proxy) forward target performs the set and
/// reports success.
pub(crate) fn proxy_set_bool(
&mut self,
handle: crate::heap::Handle,
key: &str,
value: NanBox,
receiver: NanBox,
) -> Result<bool, ExecError> {
let Some((target, handler)) = self.realm.proxy_at(handle) else {
// Reached an ordinary object `O = handle` via a trapless forward:
// OrdinarySet(O, key, value, Receiver) returning the boolean. An
// inherited **getter-only** accessor fails (`false`); a setter runs
// (with the Receiver as `this`) and succeeds; otherwise the write lands
// on the *Receiver* (OrdinarySetWithOwnDescriptor).
let mut cur = Some(handle);
while let Some(c) = cur {
// A **proxy** reached while walking the prototype chain: its own
// `[[Set]]` internal method takes over (OrdinarySetWithOwnDescriptor
// delegates to `parent.[[Set]](P, V, Receiver)` when the property is
// absent on the descendant). This fires the proxy's `set` trap (or
// forwards to its target, possibly another proxy) with the ORIGINAL
// Receiver preserved. `handle` itself is never a proxy here (that case
// takes the trap path below), so this only triggers for an ancestor.
if self.realm.proxy_at(c).is_some() {
return self.proxy_set_bool(c, key, value, receiver);
}
// Integer-indexed exotic `[[Set]]` (10.4.5.5): a canonical numeric
// index on a **TypedArray** reached in the chain is governed by that
// view's bounds and NEVER consults an inherited setter/data property
// (the prototype chain past it is unreachable for such a key).
// - SameValue(O, Receiver): TypedArraySetElement — coerce V (its
// side effects run), write only if the index is still valid, and
// always report success.
// - O ≠ Receiver, *invalid* index: a silent success (no write) —
// terminal, so an inherited setter is unreachable.
// - O ≠ Receiver, *valid* index: fall through to OrdinarySet, which
// creates the data property on the Receiver below.
if self.realm.typed_kind(c).is_some()
&& let Some(n) = canonical_numeric_index(key)
{
let index_ok =
n == (n as i64) as f64 && n >= 0.0 && !(n == 0.0 && n.is_sign_negative());
let valid = index_ok
&& !self.typed_array_detached(c)
&& self
.realm
.typed_len(c)
.is_some_and(|len| (n as usize) < len);
if receiver.as_handle() == Some(c.to_raw()) {
let coerced = if self.realm.typed_kind(c).is_some_and(is_bigint_kind) {
self.coerce_typed_array_write(c, value)?
} else {
self.coerce_to_number(value)?
};
let still_valid = index_ok
&& !self.typed_array_detached(c)
&& self
.realm
.typed_len(c)
.is_some_and(|len| (n as usize) < len);
if still_valid {
self.guard_view_immutable(c)?;
self.realm.set_element(c, n as usize, coerced);
}
return Ok(true);
}
if !valid {
return Ok(true);
}
break;
}
if let Some((_, setter)) = self.realm.accessor(c, key) {
if matches!(setter.unpack(), Unpacked::Undefined) {
return Ok(false);
}
self.call_with_this(setter, receiver, &[value])?;
return Ok(true);
}
if self.realm.has_own(c, key) {
break;
}
cur = self.realm.object_proto(c);
}
// No accessor on the chain: the own descriptor (if any) is a data
// descriptor. The value is written to the **Receiver**, not to `O`.
let Some(recv_h) = receiver.as_handle().map(Handle::from_raw) else {
return Ok(false);
};
if recv_h == handle {
// Receiver === O: ordinary own write (honoring read-only /
// non-extensible gates).
if !self.can_write_property(recv_h, key) {
return Ok(false);
}
let key_box = self.new_str(key);
self.assign_member_value(recv_h, key_box, value)?;
return Ok(true);
}
// Receiver differs from O (a trapless proxy forwarded here with the
// original Receiver): OrdinarySetWithOwnDescriptor writes to the
// Receiver via `[[DefineOwnProperty]]` — for a proxy Receiver this runs
// its `getOwnPropertyDescriptor` + `defineProperty` traps.
if self.realm.proxy_at(recv_h).is_some() {
let existing = self.descriptor_of(recv_h, key)?;
let desc = self.realm.new_object();
self.realm.set_property(desc, "value", value);
if let Some(dh) = existing.as_handle().map(Handle::from_raw) {
let is_accessor = self.realm.get_property(dh, "get").is_some()
|| self.realm.get_property(dh, "set").is_some();
let writable = self
.realm
.get_property(dh, "writable")
.is_some_and(|v| self.realm.truthy(v));
if is_accessor || !writable {
return Ok(false);
}
} else {
self.realm
.set_property(desc, "writable", NanBox::boolean(true));
self.realm
.set_property(desc, "enumerable", NanBox::boolean(true));
self.realm
.set_property(desc, "configurable", NanBox::boolean(true));
}
let ok = self.apply_descriptor(recv_h, key, desc, true)?;
return Ok(ok);
}
// Ordinary Receiver distinct from O: an own accessor / non-writable
// own data property rejects; otherwise create/update the own data
// property on the Receiver.
if self.realm.accessor(recv_h, key).is_some() {
return Ok(false);
}
if self.realm.has_own(recv_h, key) {
if !self.can_write_property(recv_h, key) {
return Ok(false);
}
} else if !self.realm.is_extensible(recv_h) {
return Ok(false);
}
let key_box = self.new_str(key);
self.assign_member_value(recv_h, key_box, value)?;
return Ok(true);
};
self.guard_revoked(handle)?;
if let Some(trap) = self.proxy_trap(handler, "set")? {
let key_box = self.key_to_value(key);
let handler_box = NanBox::handle(handler.to_raw());
let r = self.call_with_this(
trap,
handler_box,
&[NanBox::handle(target.to_raw()), key_box, value, receiver],
)?;
if !self.realm.truthy(r) {
return Ok(false);
}
self.proxy_set_invariant_check(target, key, value)?;
return Ok(true);
}
// No `set` trap: forward `[[Set]]` to the target with the same receiver.
self.proxy_set_bool(target, key, value, receiver)
}
/// Assigns a member by an already-evaluated key value (used when the target's
/// computed key must be resolved before the RHS, per spec evaluation order).
/// Mirrors `assign_member`'s proxy / array-index / setter / length handling.
pub(crate) fn assign_member_value(
&mut self,
handle: crate::heap::Handle,
key: NanBox,
new: NanBox,
) -> Result<(), ExecError> {
// Proxy `[[Set]]`: route through the receiver-aware `proxy_set_bool`
// (shared with `Reflect.set`), passing the proxy itself as the Receiver.
// This preserves the Receiver across a trapless forward — so an inherited
// accessor setter (e.g. `Object.prototype.__proto__`) runs with `this` =
// the proxy, and a nested proxy target re-enters its own trap. A `false`
// result is a failed [[Set]]: strict code throws, sloppy code is silent.
if self.realm.proxy_at(handle).is_some() {
let name = self.member_key(key);
let recv = NanBox::handle(handle.to_raw());
let ok = self.proxy_set_bool(handle, &name, new, recv)?;
if !ok && self.strict {
let m = self.new_str(&alloc::format!(
"'set' on proxy: trap returned falsish for property '{name}'"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(());
}
// A module namespace exotic object's `[[Set]]` (§10.4.6.9) always returns
// false: a write is a silent no-op in sloppy code and a TypeError in strict
// code (all module code is strict). The property table stays authoritative
// for the live read-through; only user-level assignment is rejected here
// (engine-internal refreshes go through `realm.set_property`).
#[cfg(all(feature = "module", feature = "std"))]
if self.module_namespaces.contains_key(&handle.to_raw()) {
if self.strict {
let name = self.member_key(key);
let m = self.new_str(&alloc::format!(
"Cannot assign to read only property '{name}' of a module namespace object"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(());
}
// Integer-indexed exotic `[[Set]]`: for a typed array, a *canonical numeric
// index* key writes the element (after coercing the value — whose side
// effects/throw still run for an out-of-bounds index) and is a no-op when the
// index is invalid; it never creates an own property or reaches a prototype
// setter. Handles negative / fractional / `-0` / out-of-bounds canonical keys
// that the integer-index path below (which only accepts `usize`) would miss.
if self.realm.typed_kind(handle).is_some() {
let s = self.member_key(key);
if let Some(n) = canonical_numeric_index(&s) {
// Coerce the value first (a BigInt view ToBigInt-coerces, a numeric
// view ToNumber-coerces) so its observable effects run regardless.
let coerced = if self.realm.typed_kind(handle).is_some_and(is_bigint_kind) {
self.coerce_typed_array_write(handle, new)?
} else {
self.coerce_to_number(new)?
};
// A write through a view over an immutable buffer is a TypeError
// (after the value coercion, per TypedArraySetElement).
self.guard_view_immutable(handle)?;
let is_neg_zero = n == 0.0 && n.is_sign_negative();
if !is_neg_zero
&& n == (n as i64) as f64
&& n >= 0.0
&& self
.realm
.typed_len(handle)
.is_some_and(|len| (n as usize) < len)
&& !self.typed_array_detached(handle)
{
self.realm.set_element(handle, n as usize, coerced);
}
return Ok(());
}
}
// A numeric index — a number, or a canonical numeric string ("1", not "01"
// or "1.0") as produced by `Reflect.set`/`arr["1"]=` — addresses array (or
// typed-array view) element storage.
if self.realm.is_array_like(handle) {
let idx = key.as_number().and_then(as_index).or_else(|| {
key.as_handle()
.map(Handle::from_raw)
.and_then(|h| self.realm.string_value(h))
.and_then(|s| {
s.parse::<usize>()
.ok()
.filter(|i| alloc::format!("{i}") == s)
})
});
// For a plain Array, a valid array index is in [0, 2**32−1) — the
// boundary value 2**32−1 is an ordinary named property, not an element
// (and must not trigger ArraySetLength). Typed-array views accept any
// in-bounds integer key here.
let idx = idx.filter(|&i| {
self.realm.typed_kind(handle).is_some() || (i as u64) < u64::from(u32::MAX)
});
if let Some(i) = idx {
// For a plain array, `store_array_index` takes the dense fast path
// unless the index carries a descriptor override (accessor / readonly
// / frozen), which it then honors. A typed-array view writes through
// its bytes via `set_element_checked`.
if self.realm.typed_kind(handle).is_none() {
// OrdinarySet: when the index has no own property (a hole or past
// the end) an inherited setter / proxy on the chain handles the
// write. This walk is skipped for the common case — a pristine
// `%Array.prototype%` chain (no inherited index setters) unless one
// was installed (`proto_index_accessor_dirty`), e.g.
// `Array.prototype[0] = set…` or `Object.setPrototypeOf(arr, proxy)`.
// An *own* accessor at the index shadows any inherited one, so it
// is left to `store_array_index` (which fires the own setter).
let absent_own = self
.realm
.array_length(handle)
.is_none_or(|len| i >= len || self.realm.get_element(handle, i).is_hole());
if absent_own
&& (self.realm.object_proto(handle) != self.realm.array_proto_intrinsic()
|| self.realm.proto_index_accessor_dirty())
&& self
.realm
.accessor(handle, &alloc::format!("{i}"))
.is_none()
&& let Some(()) =
self.set_through_proto_chain(handle, &alloc::format!("{i}"), new)?
{
return Ok(());
}
self.store_array_index(handle, i, new)?;
} else {
self.set_element_checked(handle, i, new)?;
}
return Ok(());
}
}
let name = self.coerce_property_key(key)?;
// A **mapped `arguments` index** (10.4.4.4 `[[Set]]`): also write the live
// parameter binding it aliases (`arguments[i] = v` updates the i-th
// parameter). Fall through to the ordinary store so the own property's
// value stays in sync for a subsequent `getOwnPropertyDescriptor`.
if let Some((scope, param)) = self.arg_map_binding(handle, &name) {
scope.set(¶m, new);
}
// A typed array's `length` is fixed (non-writable): ignore the assignment.
if name == "length" && self.realm.typed_len(handle).is_some() {
return Ok(());
}
// `regex.lastIndex = n` updates the RegExp's stateful search position
// (honoring a non-writable descriptor installed via `defineProperty`).
if name == "lastIndex" && self.realm.regexp_at(handle).is_some() {
return self.regex_write_last_index(handle, new);
}
// An own accessor setter takes precedence.
if let Some((_, setter)) = self.realm.accessor(handle, &name) {
if !matches!(setter.unpack(), Unpacked::Undefined) {
let this = NanBox::handle(handle.to_raw());
self.call_with_this(setter, this, &[new])?;
} else if self.strict {
// A getter-only accessor cannot be written: the throwing form of
// `[[Set]]` raises a TypeError; sloppy assignment drops the write.
let m = self.new_str(&alloc::format!(
"Cannot assign to read only property '{name}' (accessor has no setter)"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(());
}
// No own property: an *inherited* accessor **or a proxy** on the prototype
// chain handles the write via `parent.[[Set]]` (its setter runs, or the
// proxy's `set` trap fires, with `this`/Receiver = the receiver). An
// inherited data property, or none, falls through to creating an own data
// property.
if !self.realm.has_own(handle, &name)
&& let Some(()) = self.set_through_proto_chain(handle, &name, new)?
{
return Ok(());
}
// `arr.length = n` resizes the array (with ToUint32 + RangeError check).
if name == "length" && self.realm.is_array(handle) {
// ToUint32(value) is coerced first (it may RangeError), *before* the
// non-writable check — matching the descriptor path's ordering.
let n = self.array_length_from_value(new)?;
self.write_array_length(handle, n)?;
} else if self.allow_property_write(handle, &name)? {
// Honor a non-writable own data property / non-extensible object:
// strict mode throws, sloppy mode silently drops the write (this is
// the computed-key `obj[k] = v` path, e.g. a Symbol-keyed write to a
// `writable: false` property).
// A writable array index that reached here (it carries a non-default
// attribute override, so it skipped the dense fast path) stores into the
// element store, not a shadowing aux slot.
// Only a real array index `[0, 2**32−1)` addresses element storage; the
// boundary `2**32−1` and above are ordinary named properties.
let array_index = self.realm.is_array(handle).then(|| {
name.parse::<usize>()
.ok()
.filter(|i| alloc::format!("{i}") == name && (*i as u64) < u64::from(u32::MAX))
});
if let Some(Some(i)) = array_index {
self.set_element_checked(handle, i, new)?;
} else {
self.realm.set_property(handle, &name, new);
}
}
Ok(())
}
/// `arr[i] = v` for an array index: the dense fast path unless the index carries
/// a non-default attribute override or accessor (or the array is frozen/sealed),
/// in which case the descriptor is honored — an accessor's setter runs, a
/// non-writable index drops the write (strict → TypeError). Mirrors the inline
/// logic of the primary computed-assignment path.
pub(crate) fn store_array_index(
&mut self,
handle: Handle,
i: usize,
new: NanBox,
) -> Result<(), ExecError> {
if self.realm.typed_kind(handle).is_none() && self.realm.array_index_has_override(handle, i)
{
let key = alloc::format!("{i}");
// An accessor setter takes precedence. A getter-only accessor (no
// setter) cannot be written: strict mode throws, sloppy drops.
if let Some((_, setter)) = self.realm.accessor(handle, &key) {
if !matches!(setter.unpack(), Unpacked::Undefined) {
let this = NanBox::handle(handle.to_raw());
self.call_with_this(setter, this, &[new])?;
} else if self.strict {
let m = self.new_str(&alloc::format!(
"Cannot assign to read only property '{key}' (accessor has no setter)"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(());
}
// A non-writable / frozen index: strict throws, sloppy drops.
if self.allow_property_write(handle, &key)? {
self.set_element_checked(handle, i, new)?;
}
return Ok(());
}
self.set_element_checked(handle, i, new)
}
/// `arr.length = n` (the assignment path of `ArraySetLength`, ECMA-262
/// 10.4.3.1): applies the (already ToUint32-coerced) `n`. A non-writable
/// `length` rejects any change — silently in sloppy mode, with a TypeError in
/// strict mode (a same-value assignment is a no-op either way). When shrinking
/// hits a non-configurable index, the truncation stops there; strict mode then
/// throws (the length is left one above the stuck index in both modes).
pub(crate) fn write_array_length(&mut self, handle: Handle, n: usize) -> Result<(), ExecError> {
if self.realm.array_length_is_readonly(handle) {
// Ordinary `[[Set]]` of a non-writable data property returns `false`
// whether or not the new value equals the current one — the same-value
// exception lives only in `[[DefineOwnProperty]]`/ValidateAndApply, not
// in `[[Set]]`. So `Set(O, "length", V, true)` on a frozen / non-writable
// -length array (e.g. the closing `Set` of `pop`/`push` on an empty
// frozen array) throws in strict mode; a sloppy assignment drops silently.
if self.strict {
let m = self.new_str("Cannot assign to read only property 'length'");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(()); // sloppy: silently dropped
}
let all_deleted = self.set_array_length_checked(handle, n)?;
if !all_deleted && self.strict {
let m = self.new_str("Cannot delete non-configurable array element");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
Ok(())
}
/// `ArraySetLength` length coercion: `ToUint32(v)` must equal `ToNumber(v)`
/// (so `-1`, `4294967296`, `1.5`, `NaN` are RangeErrors), and the `ToNumber`
/// coercion fires `valueOf`/`toString` (a Symbol throws). Returns the
/// validated `u32` length.
pub(crate) fn array_length_from_value(&mut self, v: NanBox) -> Result<usize, ExecError> {
// ToNumber(v) — abrupt-propagating (a Symbol/throwing valueOf).
let num = self.coerce_to_number(v)?;
match self.realm.array_length_uint32(num) {
Some(n) => Ok(n as usize),
None => {
let m = self.new_str("Invalid array length");
Err(ExecError::Throw(self.make_error(N_RANGE_ERROR, Some(m))))
}
}
}
/// The proxy `[[Get]]` success invariants (10.5.8): a non-configurable,
/// non-writable data property of the target must be reported with its actual
/// value; a non-configurable accessor with no getter must report `undefined`.
pub(crate) fn proxy_get_invariant_check(
&mut self,
target: crate::heap::Handle,
name: &str,
result: NanBox,
) -> Result<(), ExecError> {
if let Some((getter, _)) = self.realm.accessor(target, name) {
if self.realm.property_is_non_configurable(target, name)
&& matches!(getter.unpack(), Unpacked::Undefined)
&& !matches!(result.unpack(), Unpacked::Undefined)
{
return Err(self.type_error(
"proxy 'get' returned a value for a non-configurable accessor with no getter",
));
}
} else if self.realm.has_own(target, name)
&& self.realm.property_is_non_configurable(target, name)
&& self.realm.property_is_readonly(target, name)
{
let actual = self
.realm
.get_property(target, name)
.unwrap_or(NanBox::undefined());
if !self.realm.strict_equals(result, actual) {
return Err(self.type_error(
"proxy 'get' returned a different value for a non-configurable non-writable property",
));
}
}
Ok(())
}
/// `[[Get]](P, Receiver)` on `obj`, threading an explicit Receiver so that an
/// inherited accessor getter (or a proxy `get` trap) runs with `this` =
/// `receiver` — the piece the receiver-less `read_member` drops when it
/// forwards a trapless proxy to its target or descends into a proxy on the
/// prototype chain. Data / exotic properties are receiver-independent, so those
/// defer to `read_member`.
pub(crate) fn get_with_receiver(
&mut self,
obj: crate::heap::Handle,
name: &str,
receiver: NanBox,
) -> Result<NanBox, ExecError> {
// A proxy: its `get` trap (with the Receiver), or a trapless forward to the
// target that keeps the Receiver (recursing so a proxy target runs its own
// trap / chain).
if let Some((target, handler)) = self.realm.proxy_at(obj) {
self.guard_revoked(obj)?;
if let Some(trap) = self.proxy_trap(handler, "get")? {
let key = self.key_to_value(name);
let handler_box = NanBox::handle(handler.to_raw());
let result = self.call_with_this(
trap,
handler_box,
&[NanBox::handle(target.to_raw()), key, receiver],
)?;
self.proxy_get_invariant_check(target, name, result)?;
return Ok(result);
}
return self.get_with_receiver(target, name, receiver);
}
// An ordinary object: walk own → prototype chain. An accessor getter runs
// with the Receiver; a proxy on the chain delegates its `[[Get]]` with the
// same Receiver; an own data property (or reaching a non-proxy end) defers
// to `read_member` for the receiver-independent read of `obj`.
let mut cur = Some(obj);
while let Some(c) = cur {
if c != obj && self.realm.proxy_at(c).is_some() {
return self.get_with_receiver(c, name, receiver);
}
if let Some((getter, _)) = self.realm.accessor(c, name) {
if matches!(getter.unpack(), Unpacked::Undefined) {
return Ok(NanBox::undefined());
}
return self.call_with_this(getter, receiver, &[]);
}
if self.realm.has_own(c, name) {
break;
}
cur = self.realm.object_proto(c);
}
self.read_member(obj, name)
}
pub(crate) fn read_member(
&mut self,
handle: crate::heap::Handle,
name: &str,
) -> Result<NanBox, ExecError> {
// A Deferred Module Namespace (`import defer`) evaluates its target the
// first time one of its exports is read — directly or as a prototype /
// `super` home object (import-defer proposal).
#[cfg(all(feature = "module", feature = "std"))]
self.trigger_deferred_in_chain(handle, name)?;
// A **module namespace** export is a *live* binding: read the current
// value from its backing slot (so a mutation in the exporting module that
// happens after the namespace was materialised is observed). The
// refreshed value is also written back so `getOwnPropertyDescriptor`
// reports it.
#[cfg(all(feature = "module", feature = "std"))]
if let Some((scope, local)) = self
.module_namespaces
.get(&handle.to_raw())
.and_then(|m| m.get(name))
.map(|(s, l)| (s.clone(), l.clone()))
{
let value = scope.get(&local).unwrap_or_else(NanBox::undefined);
// A namespace binding whose source `let`/`const`/`class`/`function*`
// has not yet run its initializer is in its Temporal Dead Zone: the
// [[Get]] (GetBindingValue with Strict=true) throws a ReferenceError
// rather than returning `undefined`.
if value.is_tdz() {
let msg = self.new_str(&alloc::format!(
"Cannot access '{name}' before initialization"
));
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(msg)),
));
}
// Refresh the stored data property (it is non-configurable but
// writable, so the engine-internal write is permitted).
self.realm.set_property(handle, name, value);
return Ok(value);
}
// A **mapped `arguments` index** (10.4.4.3 `[[Get]]`): the value is the live
// parameter binding it aliases. Refresh the stored data property too so a
// later `getOwnPropertyDescriptor` reports the current value.
if let Some((scope, param)) = self.arg_map_binding(handle, name) {
let value = scope.get(¶m).unwrap_or_else(NanBox::undefined);
self.realm.set_property(handle, name, value);
return Ok(value);
}
// String index access (`"abc"[1]`) → the UTF-16 code unit at the index
// (a lone surrogate preserved as a one-unit string).
//
// P3: read the unit through the *borrowing* `string_leaf_bytes` when the
// rope is a single leaf (the overwhelmingly common case) so that
// `for (i…) c = s[i]` is O(1) per read instead of flattening the whole
// rope into an owned `Vec` every time (which made the loop O(n²)). A
// `Concat` tree (no contiguous leaf) falls back to the owned
// `string_bytes`; a non-string receiver makes both return `None`, so the
// fast numeric-index path is skipped without any allocation.
if let Ok(i) = name.parse::<usize>() {
if let Some(leaf) = self.realm.string_leaf_bytes(handle) {
if let Some(u) = crate::wtf8::utf16_index(leaf, i) {
return Ok(self.new_str_bytes(crate::wtf8::from_utf16(&[u])));
}
// Out of range: a String *wrapper* object can still carry an
// ordinary own property at that index (`Object.defineProperty(new
// String("s"), "4", …)`) — String-exotic `[[GetOwnProperty]]` falls
// back to OrdinaryGetOwnProperty. Only shortcut to `undefined` when
// there is no such own property (the common primitive-string case).
if !self.realm.has_own(handle, name) {
return Ok(NanBox::undefined());
}
} else if let Some(bytes) = self.realm.string_bytes(handle) {
if let Some(u) = crate::wtf8::utf16_index(&bytes, i) {
return Ok(self.new_str_bytes(crate::wtf8::from_utf16(&[u])));
}
if !self.realm.has_own(handle, name) {
return Ok(NanBox::undefined());
}
}
}
// A canonical numeric string key on an array (`arr["0"]`) reads the
// element, exactly like `arr[0]` — but only for a valid array index
// [0, 2**32−1); the boundary value 2**32−1 is an ordinary named property
// (handled by the aux lookup below).
if self.realm.is_array(handle)
&& let Ok(i) = name.parse::<usize>()
&& alloc::format!("{i}") == name
&& (i as u64) < u64::from(u32::MAX)
&& i < self.realm.array_dense_len(handle).unwrap_or(0)
{
let v = self.realm.get_element(handle, i);
// A genuine hole (absent index) is not an own property: the lookup
// continues up the `[[Prototype]]` chain (handled by the generic walk
// below) instead of resolving to `undefined` here. An out-of-range
// index (`i >= length`) likewise falls through (guarded above).
if !v.is_hole() {
return Ok(v);
}
}
// Integer-indexed exotic `[[Get]]`: when `handle` is a typed array and `name`
// is a *canonical numeric index*, the result is the element if the index is
// valid (an in-bounds non-negative integer, `-0` excluded, buffer attached),
// else `undefined` — and the prototype chain is **never** consulted (so a
// throwing getter at `TypedArray.prototype["-1"]` is not invoked).
if self.realm.typed_kind(handle).is_some()
&& let Some(n) = canonical_numeric_index(name)
{
// IsValidIntegerIndex: a detached buffer, `-0`, a non-integer, or an
// out-of-bounds index all read `undefined`.
if self.typed_array_detached(handle) {
return Ok(NanBox::undefined());
}
let is_neg_zero = n == 0.0 && n.is_sign_negative();
if !is_neg_zero
&& n == (n as i64) as f64
&& n >= 0.0
&& let Some(len) = self.realm.typed_len(handle)
&& (n as usize) < len
{
return Ok(self.realm.get_element(handle, n as usize));
}
return Ok(NanBox::undefined());
}
// Proxy `[[Get]]`: the `get` trap, or a trapless forward to the target that
// preserves the Receiver (so an inherited accessor getter runs with `this`
// = the proxy). Routed through `get_with_receiver` with Receiver = the
// proxy itself.
if self.realm.proxy_at(handle).is_some() {
return self.get_with_receiver(handle, name, NanBox::handle(handle.to_raw()));
}
// An error object's `.constructor` is its specific error global — its
// prototype otherwise reports a generic `Object`. Recognized by an own
// `name` in the error family plus a `message`. This is a *fallback* only:
// it fires when nothing before `Object.prototype` defines `constructor`,
// so a subclass instance (`class E extends Error {}`, whose `constructor`
// resolves to `E` through its own/prototype chain) is never overridden.
if name == "constructor" {
let mut cur = Some(handle);
let obj_proto = self.realm.default_object_proto();
let mut resolved = false;
while let Some(c) = cur {
if Some(c) == obj_proto {
break;
}
if self.realm.has_own(c, "constructor") {
resolved = true;
break;
}
cur = self.realm.object_proto(c);
}
if !resolved {
let nm = self
.realm
.get_property(handle, "name")
.map(|v| self.realm.to_display_string(v))
.unwrap_or_default();
if ERROR_NAMES.contains(&nm.as_str())
&& self.realm.get_property(handle, "message").is_some()
&& let Some(ctor) = self.current.get(&nm)
{
return Ok(ctor);
}
}
}
// Well-known `Symbol.iterator` / `Symbol.asyncIterator` (lazily created).
if self.realm.native_at(handle) == Some(N_SYMBOL)
&& matches!(
name,
"iterator"
| "asyncIterator"
| "hasInstance"
| "toPrimitive"
| "toStringTag"
| "species"
| "isConcatSpreadable"
| "match"
| "matchAll"
| "replace"
| "search"
| "split"
| "unscopables"
| "dispose"
| "asyncDispose"
)
{
// The name is the well-known symbol's key.
let key: &'static str = match name {
"iterator" => "iterator",
"asyncIterator" => "asyncIterator",
"hasInstance" => "hasInstance",
"toPrimitive" => "toPrimitive",
"toStringTag" => "toStringTag",
"species" => "species",
"isConcatSpreadable" => "isConcatSpreadable",
"match" => "match",
"matchAll" => "matchAll",
"replace" => "replace",
"search" => "search",
"split" => "split",
"dispose" => "dispose",
"asyncDispose" => "asyncDispose",
_ => "unscopables",
};
return Ok(self.well_known_symbol(key));
}
// A symbol's `description` (`undefined` for a no-argument `Symbol()`).
if let Some((desc, _)) = self.realm.symbol_at(handle)
&& name == "description"
{
return Ok(if &*desc == SYMBOL_NO_DESC {
NanBox::undefined()
} else {
self.new_str(&desc)
});
}
// A constructor function's `.prototype` (lazily created), so
// `Fn.prototype.method = …` and prototype-chain inheritance work. Skip the
// synthesis when an own `prototype` property is present — a *non-object*
// assignment (`Fn.prototype = undefined`) can't enter the `fn_protos`
// side-table (it holds Handles) and is stored as an own property, which
// must be honored (else the synthesized default wrongly shadows it).
if name == "prototype"
&& let Some((func_id, _)) = self.realm.function_at(handle)
&& !self.realm.has_own(handle, "prototype")
// Only constructable functions have a `prototype`; a non-constructable
// one (arrow / `async` / concise method / accessor) reads it as absent.
// Constructable functions normally carry a materialized own property
// (so `has_own` is true and this is skipped); this synthesis remains a
// safety net for any constructable function created off the main path.
&& self.fn_has_prototype(func_id)
{
let proto = self.realm.function_prototype(func_id);
return Ok(NanBox::handle(proto.to_raw()));
}
// A class's `.prototype` (lazily materialized with its instance
// methods/accessors and a `constructor` back-link).
if name == "prototype"
&& let Some((class_id, _)) = self.realm.class_at(handle)
&& !self.realm.has_own(handle, "prototype")
{
let proto = self.class_prototype(class_id, handle);
return Ok(NanBox::handle(proto.to_raw()));
}
// A bound function's `name` is `"bound " + target.name` (recursing so a
// re-bound function reads `"bound bound …"`); its `length` is the target's
// length minus the bound arguments (floored at 0).
if matches!(name, "name" | "length")
&& !self.realm.has_own(handle, name)
&& let Some(target) = self.realm.get_property(handle, BOUND_TARGET)
{
let th = target.as_handle().map(Handle::from_raw);
if name == "name" {
let tname = match th {
Some(t) => {
let v = self.read_member(t, "name")?;
self.realm.to_display_string(v)
}
None => String::new(),
};
return Ok(self.new_str(&alloc::format!("bound {tname}")));
}
// `length`: target.length − number of pre-bound arguments.
let tlen = match th {
Some(t) => {
let v = self.read_member(t, "length")?;
self.realm.to_number(v)
}
None => 0.0,
};
let bound = self
.realm
.get_property(handle, BOUND_ARGS)
.and_then(|a| a.as_handle().map(Handle::from_raw))
.and_then(|bh| self.realm.array_length(bh))
.unwrap_or(0);
return Ok(NanBox::number((tlen - bound as f64).max(0.0)));
}
// `obj.__proto__` reads the prototype link (unless shadowed by an own
// data property of that name).
// The `__proto__` magic only applies when the object actually inherits
// `Object.prototype`'s accessor; a null-proto object (module namespace,
// `Object.create(null)`) reads it as an ordinary absent property.
if name == "__proto__"
&& !self.realm.has_own(handle, "__proto__")
&& self.realm.inherits_object_proto(handle)
{
return Ok(match self.realm.object_proto(handle) {
Some(p) => NanBox::handle(p.to_raw()),
None => NanBox::null(),
});
}
// A class's `name` is its declared identifier (`class C {}` → `"C"`), or
// the name bound by NamedEvaluation (`let C = class {}`), which is stored
// as an own property — so an own `name` takes precedence over the (empty)
// declared id of an anonymous class.
if name == "name"
&& self.realm.class_at(handle).is_some()
&& !self.realm.has_own(handle, "name")
{
let cname = self
.realm
.class_at(handle)
.and_then(|(cid, _)| self.classes[cid as usize].id.as_ref())
.map_or("", |i| &i.name);
return Ok(self.new_str(cname));
}
// A function's `length` (params before a default/rest) and `name`.
if matches!(name, "length" | "name")
&& !self.realm.has_own(handle, name)
&& let Some((func_id, _)) = self.realm.function_at(handle)
{
let def = self.functions[func_id as usize];
return Ok(if name == "length" {
let len = def
.params
.iter()
.take_while(|p| p.default.is_none() && !p.rest)
.count();
NanBox::number(len as f64)
} else {
self.new_str(def.name)
});
}
// A dynamically-registered host function (`register_fn`, ROADMAP §4.0)
// reports the declared `name`/`length` its registry entry carries.
if matches!(name, "length" | "name")
&& !self.realm.has_own(handle, name)
&& let Some(id) = self.realm.host_fn_at(handle)
&& let Some((fn_name, len)) = self.host_fn_meta(id)
{
return Ok(if name == "length" {
NanBox::number(f64::from(len))
} else {
let fn_name = String::from(fn_name);
self.new_str(&fn_name)
});
}
// A built-in function's `name` and `length`. Plain natives carry `name` in
// their aux object (resolved above / via `member_value`) but no physical
// `length`; first-class prototype/static methods (bound natives) carry
// neither. Synthesize both from the dispatch identity so every built-in
// function exposes the spec-mandated own `name`/`length` data properties.
if matches!(name, "length" | "name") && !self.realm.has_own(handle, name) {
if let Some((id, target)) = self.realm.bound_native_at(handle) {
let method = if id == N_ARRAY_PROTO_FN
|| id == N_AB_PROTO_FN
|| id == N_SAB_PROTO_FN
|| id == N_TYPED_ARRAY_PROTO_FN
{
self.realm.string_value(target)
} else if id == N_STATIC_METHOD {
self.realm
.array_elements(target)
.and_then(|p| p.get(1).copied())
.and_then(|v| v.as_handle().map(Handle::from_raw))
.and_then(|h| self.realm.string_value(h))
} else {
None
};
if let Some(method) = method {
return Ok(if name == "name" {
self.new_str(&method)
} else {
NanBox::number(builtin_method_arity(&method) as f64)
});
}
}
if let Some(id) = self.realm.native_at(handle) {
// `Function.prototype[Symbol.hasInstance].name` is the spec's
// bracketed symbol description.
if id == N_FN_HAS_INSTANCE && name == "name" {
return Ok(self.new_str("[Symbol.hasInstance]"));
}
if name == "length" {
return Ok(NanBox::number(builtin_native_arity(id) as f64));
}
}
}
// `Number.*` static constants.
if self.realm.native_at(handle) == Some(N_NUMBER) {
match name {
"MAX_SAFE_INTEGER" => return Ok(NanBox::number(9_007_199_254_740_991.0)),
"MIN_SAFE_INTEGER" => return Ok(NanBox::number(-9_007_199_254_740_991.0)),
"MAX_VALUE" => return Ok(NanBox::number(f64::MAX)),
// The smallest positive value is the least *subnormal* (5e-324),
// not Rust's `MIN_POSITIVE` (the smallest *normal*, 2.2e-308).
"MIN_VALUE" => return Ok(NanBox::number(f64::from_bits(1))),
"EPSILON" => return Ok(NanBox::number(f64::EPSILON)),
"POSITIVE_INFINITY" => return Ok(NanBox::number(f64::INFINITY)),
"NEGATIVE_INFINITY" => return Ok(NanBox::number(f64::NEG_INFINITY)),
"NaN" => return Ok(NanBox::number(f64::NAN)),
_ => {}
}
}
// A class static — walking the `extends` chain for inherited statics. The
// own level is mirrored as a real own property (so `delete`/`defineProperty`
// take effect); only fall through to the side tables for *inherited*
// statics, which live on the superclass and are not mirrored on `handle`.
if let Some((cid, _)) = self.realm.class_at(handle) {
// The own level is mirrored as a real own property of the constructor.
// An own accessor falls through to the generic accessor path below
// (invoked with `this` = the class); an own data property is
// authoritative here (so `delete`/`defineProperty` are honored). Only
// when the name is *not* an own property do we walk the superclass
// chain via the side tables for an inherited static.
let has_own_accessor = self.realm.accessor(handle, name).is_some_and(|(g, _)| {
g.as_handle()
.is_some_and(|r| self.is_callable(Handle::from_raw(r)))
});
if !has_own_accessor {
if self.realm.has_own(handle, name) {
if let Some(v) = self.realm.get_property(handle, name) {
return Ok(v);
}
} else {
// Inherited statics: walk the superclass chain.
let class = self.classes[cid as usize];
let env = self.class_envs[cid as usize].clone();
let mut cur = self.resolve_super(class, &env)?.map(|(pid, _)| pid);
while let Some(c) = cur {
if let Some(v) = self.class_statics[c as usize].get(name) {
return Ok(*v);
}
if let Some(getter) = self.class_static_get[c as usize].get(name).copied() {
let this = NanBox::handle(handle.to_raw());
return self.call_with_this(getter, this, &[]);
}
let class = self.classes[c as usize];
let env = self.class_envs[c as usize].clone();
cur = self.resolve_super(class, &env)?.map(|(pid, _)| pid);
}
}
}
}
if let Some((getter, _)) = self.realm.accessor(handle, name) {
if matches!(getter.unpack(), Unpacked::Undefined) {
return Ok(NanBox::undefined());
}
let this = NanBox::handle(handle.to_raw());
return self.call_with_this(getter, this, &[]);
}
// `RegExp.prototype.lastIndex` — a real own *data* property of every
// RegExp instance, stored in the cell (not in the shape), so it is read
// here directly. Unless overridden by an own aux slot (a user
// `Object.defineProperty(re,"lastIndex",…)` would land in aux), the cell
// value is authoritative. `source`/`flags`/the flag getters are spec
// *accessor* properties on `RegExp.prototype` and resolve through the
// prototype walk below (so they escape the source, validate the brand, and
// honor a subclass override).
if name == "lastIndex"
&& self.realm.regexp_at(handle).is_some()
&& !self.realm.regex_aux_last_index_defined(handle)
{
return Ok(NanBox::number(self.realm.regex_last_index(handle) as f64));
}
// Branded-prototype accessors. `ArrayBuffer.prototype.byteLength`,
// `DataView.prototype.buffer`, `%TypedArray%.prototype.buffer`, … are spec
// accessor properties whose getter requires the matching internal slot on
// its receiver (RequireInternalSlot). When the receiver inherits the
// branded prototype but lacks the slot — most visibly the prototype object
// itself (`ArrayBuffer.prototype.byteLength`) — the getter throws a
// TypeError instead of returning `undefined`. The slot-bearing instance
// paths below are reached first for real buffers/views/typed arrays (they
// have the `ARRAY_BUFFER_BYTES`/`DATA_VIEW_BUF`/typed-kind tags), so this
// only fires for slot-less receivers.
if self
.realm
.get_property(handle, ARRAY_BUFFER_BYTES)
.is_none()
&& matches!(
name,
"byteLength" | "detached" | "maxByteLength" | "resizable"
)
&& self.brand_on_chain(handle, ARRAY_BUFFER_PROTO_BRAND)
{
return Err(self
.type_error("ArrayBuffer.prototype accessor called on a non-ArrayBuffer object"));
}
if self.realm.get_property(handle, DATA_VIEW_BUF).is_none()
&& matches!(name, "buffer" | "byteLength" | "byteOffset")
&& self.brand_on_chain(handle, DATA_VIEW_PROTO_BRAND)
{
return Err(
self.type_error("DataView.prototype accessor called on a non-DataView object")
);
}
if self.realm.typed_kind(handle).is_none()
&& matches!(name, "buffer" | "byteLength" | "byteOffset" | "length")
// An own property on the receiver shadows the inherited branded accessor
// (ordinary [[Get]] finds the own property first). Most visibly, an Array
// or String-wrapper receiver whose `[[Prototype]]` was set to a typed
// array (`Object.setPrototypeOf([], ta)`) still reads its *own* `length`.
&& !self.realm.has_own(handle, name)
&& !(name == "length"
&& (self.realm.is_array(handle)
|| self.realm.string_object_len(handle).is_some()))
&& self.brand_on_chain(handle, TYPED_ARRAY_PROTO_BRAND)
{
return Err(
self.type_error("TypedArray.prototype accessor called on a non-TypedArray object")
);
}
// `ArrayBuffer.prototype` methods (`slice`/`resize`/`transfer`/
// `transferToFixedLength`) are installed as real first-class own properties on
// the prototype (with proper name/length), and every `ArrayBuffer` instance
// inherits the prototype — so a read of `ab.slice` resolves them through the
// chain (and a user write to `ArrayBuffer.prototype.slice` is honored). No
// special case needed here.
// `ArrayBuffer.prototype.resizable` / `.maxByteLength` (ES2024 resizable buffers).
if matches!(name, "resizable" | "maxByteLength")
&& self
.realm
.get_property(handle, ARRAY_BUFFER_BYTES)
.is_some()
{
let max = self.realm.get_property(handle, ARRAY_BUFFER_MAXLEN);
if name == "resizable" {
return Ok(NanBox::boolean(max.is_some()));
}
// `maxByteLength` is the recorded max, or — for a non-resizable buffer — its
// current `byteLength`.
return Ok(match max {
Some(m) => m,
None => self.read_member(handle, "byteLength")?,
});
}
// `ArrayBuffer.prototype.detached` — true once `transfer()` has emptied it.
if name == "detached"
&& self
.realm
.get_property(handle, ARRAY_BUFFER_BYTES)
.is_some()
{
let detached = self
.realm
.get_property(handle, ARRAY_BUFFER_DETACHED)
.is_some();
return Ok(NanBox::boolean(detached));
}
// `ArrayBuffer.byteLength` (the byte store's length; 0 once detached).
if name == "byteLength"
&& let Some(b) = self.realm.get_property(handle, ARRAY_BUFFER_BYTES)
&& let Some(bh) = b.as_handle().map(Handle::from_raw)
{
if self
.realm
.get_property(handle, ARRAY_BUFFER_DETACHED)
.is_some()
{
return Ok(NanBox::number(0.0));
}
return Ok(NanBox::number(self.realm.bytes_len(bh).unwrap_or(0) as f64));
}
// `DataView.prototype` get*/set* methods are installed as real first-class
// own properties on the prototype (with proper name/length), so a read of
// `dv.getInt8` resolves them through the prototype chain — no special case.
// `DataView.byteLength` / `.buffer` / `.byteOffset`.
if matches!(name, "byteLength" | "buffer" | "byteOffset")
&& let Some(buf) = self.realm.get_property(handle, DATA_VIEW_BUF)
{
// `get DataView.prototype.byteLength`/`.byteOffset` throw a TypeError when
// the viewed buffer is detached (`.buffer` does not — it returns it).
if matches!(name, "byteLength" | "byteOffset")
&& let Some(bh) = buf.as_handle().map(Handle::from_raw)
&& self.realm.get_property(bh, ARRAY_BUFFER_DETACHED).is_some()
{
return Err(
self.type_error("Cannot perform DataView operation on a detached ArrayBuffer")
);
}
// IsViewOutOfBounds: a resizable buffer shrank under the view — its
// `byteLength`/`byteOffset` getters then throw a TypeError. A
// length-tracking DataView (no recorded length) is out of bounds only
// when its offset alone is past the current end; a fixed-length view
// when its offset+length no longer fits.
if matches!(name, "byteLength" | "byteOffset")
&& let Some(bh) = buf.as_handle().map(Handle::from_raw)
{
let total = self
.array_buffer_bytes(bh)
.and_then(|b| self.realm.bytes_len(b))
.unwrap_or(0);
let off = self
.realm
.get_property(handle, DATA_VIEW_OFF)
.and_then(|n| n.as_number())
.unwrap_or(0.0) as usize;
let recorded = self
.realm
.get_property(handle, DATA_VIEW_LEN)
.and_then(|n| n.as_number())
.map(|n| n as usize);
let oob = match recorded {
Some(len) => off.checked_add(len).is_none_or(|end| end > total),
None => off > total,
};
if oob {
return Err(
self.type_error("get DataView.prototype accessor on an out-of-bounds view")
);
}
}
return Ok(match name {
"buffer" => buf,
"byteOffset" => self
.realm
.get_property(handle, DATA_VIEW_OFF)
.unwrap_or(NanBox::number(0.0)),
_ => {
// An explicit byteLength wins; else the rest of the buffer.
if let Some(len) = self
.realm
.get_property(handle, DATA_VIEW_LEN)
.and_then(|n| n.as_number())
{
return Ok(NanBox::number(len));
}
let total = buf
.as_handle()
.map(Handle::from_raw)
.and_then(|h| self.array_buffer_bytes(h))
.and_then(|bh| self.realm.bytes_len(bh))
.unwrap_or(0);
let off = self
.realm
.get_property(handle, DATA_VIEW_OFF)
.and_then(|n| n.as_number())
.unwrap_or(0.0) as usize;
NanBox::number(total.saturating_sub(off) as f64)
}
});
}
// Static `<TypedArray>.BYTES_PER_ELEMENT` (on the constructor itself).
if name == "BYTES_PER_ELEMENT"
&& let Some(id) = self.realm.native_at(handle)
&& (N_TYPED_ARRAY_BASE..N_TYPED_ARRAY_BASE + TYPED_ARRAY_KINDS.len() as u16)
.contains(&id)
{
return Ok(NanBox::number(f64::from(
TYPED_ARRAY_KINDS[(id - N_TYPED_ARRAY_BASE) as usize].1,
)));
}
// A typed array's `.buffer` — its `[[ViewedArrayBuffer]]` object, returned
// directly so it is SameValue-stable and shared with sibling views.
if name == "buffer"
&& let Some(buf) = self.realm.typed_array_object(handle)
{
return Ok(NanBox::handle(buf.to_raw()));
}
// Typed-array-specific methods that aren't shared with `Array.prototype`
// (`set`/`subarray`), exposed as readable methods.
if matches!(name, "set" | "subarray") && self.realm.typed_kind(handle).is_some() {
return Ok(self.readable_native_method(name));
}
// Typed-array introspection (`byteLength`, `BYTES_PER_ELEMENT`, `byteOffset`).
if matches!(name, "byteLength" | "BYTES_PER_ELEMENT" | "byteOffset")
&& let Some(kind) = self.realm.typed_kind(handle)
{
let bpe = f64::from(TYPED_ARRAY_KINDS[kind as usize].1);
// A detached or out-of-bounds view reports byteOffset 0 (and typed_len,
// used for byteLength, already collapses to 0).
let oob =
self.typed_array_detached(handle) || self.realm.typed_array_out_of_bounds(handle);
return Ok(NanBox::number(match name {
"BYTES_PER_ELEMENT" => bpe,
"byteOffset" if oob => 0.0,
"byteOffset" => self.realm.typed_byte_offset(handle).unwrap_or(0) as f64,
_ => self.realm.typed_len(handle).unwrap_or(0) as f64 * bpe,
}));
}
// A String wrapper delegates `length` and indexed reads to its boxed
// string (`new String("hi").length`, `wrapper[0]`). P3: take the borrowing
// leaf path for `length`/indexed reads (the hot ones) and fall back to the
// owned bytes only for a `Concat` rope.
if let Some(prim) = self.realm.get_property(handle, PRIM_WRAP)
&& let Some(ph) = prim.as_handle().map(Handle::from_raw)
&& self.realm.string_bytes(ph).is_some()
{
if name == "length" {
let len = if let Some(leaf) = self.realm.string_leaf_bytes(ph) {
crate::wtf8::utf16_len(leaf)
} else {
crate::wtf8::utf16_len(&self.realm.string_bytes(ph).unwrap_or_default())
};
return Ok(NanBox::number(len as f64));
}
if let Ok(i) = name.parse::<usize>() {
let unit = if let Some(leaf) = self.realm.string_leaf_bytes(ph) {
crate::wtf8::utf16_index(leaf, i)
} else {
crate::wtf8::utf16_index(&self.realm.string_bytes(ph).unwrap_or_default(), i)
};
if let Some(u) = unit {
return Ok(self.new_str_bytes(crate::wtf8::from_utf16(&[u])));
}
// Out of range: String-exotic `[[GetOwnProperty]]` falls back to
// OrdinaryGetOwnProperty, so an own property defined at that index on
// the *wrapper* (`Object.defineProperty(new String("s"), "4", …)`) is
// still read. Only shortcut to `undefined` when there is none.
if !self.realm.has_own(handle, name) {
return Ok(NanBox::undefined());
}
}
let v = self.member_value(ph, name);
if !matches!(v.unpack(), Unpacked::Undefined) {
return Ok(v);
}
}
// Own property (or a built-in like `length`) wins.
let direct = self.member_value(handle, name);
if !matches!(direct.unpack(), Unpacked::Undefined) || self.realm.has_own(handle, name) {
return Ok(direct);
}
// Otherwise walk the `[[Prototype]]` chain for an inherited property or
// accessor (the receiver stays `handle`).
let mut cur = self.realm.object_proto(handle);
while let Some(p) = cur {
// A proxy in the prototype chain handles the read via its own `[[Get]]`
// (a `get` trap, or forwarding to the target and its prototype chain),
// which is terminal for the lookup. The Receiver stays the original
// object so an inherited accessor getter runs with the right `this`.
if self.realm.proxy_at(p).is_some() {
return self.get_with_receiver(p, name, NanBox::handle(handle.to_raw()));
}
if let Some((getter, _)) = self.realm.accessor(p, name) {
if matches!(getter.unpack(), Unpacked::Undefined) {
return Ok(NanBox::undefined());
}
let this = NanBox::handle(handle.to_raw());
return self.call_with_this(getter, this, &[]);
}
// A prototype that is itself an Array (or typed array) exposes its
// elements and `length` as inherited indexed/`length` properties —
// so `Object.create([1,2,3])[0]`/`.length` resolve when the chain
// reaches the backing array (`get_property` only reads an array's
// *aux* named props, never its elements).
if self.realm.is_array_like(p) {
if let Ok(i) = name.parse::<usize>()
&& alloc::format!("{i}") == name
{
if i < self.realm.array_length(p).unwrap_or(0) {
let v = self.realm.get_element(p, i);
// A hole on a prototype array is also absent — keep walking.
if !v.is_hole() {
return Ok(v);
}
}
} else if name == "length"
&& let Some(len) = self.realm.array_length(p)
{
return Ok(NanBox::number(len as f64));
}
}
if self.realm.has_own(p, name) {
return Ok(self
.realm
.get_property(p, name)
.unwrap_or(NanBox::undefined()));
}
cur = self.realm.object_proto(p);
}
// A built-in value with no own/inherited `constructor` reports its global
// constructor (`[].constructor === Array`); user functions/classes resolve
// theirs through the prototype walk above and never reach here.
if name == "constructor"
&& let Some(ctor) = self.builtin_constructor_for(handle)
{
return Ok(ctor);
}
// A built-in array/string/function exposes its prototype's methods as
// first-class values — so feature detection (`if (arr.flat)`,
// `typeof str.padStart`) and detached-method access resolve. (Ordinary
// `recv.m(args)` calls dispatch via `call_method` and never reach here.)
if let Some(m) = self.builtin_proto_method(handle, name) {
return Ok(m);
}
Ok(direct)
}
/// For a built-in array/string/function value, the first-class method `name`
/// from its constructor's prototype (`Array.prototype` etc.), or `None`.
pub(crate) fn builtin_proto_method(&mut self, handle: Handle, name: &str) -> Option<NanBox> {
let ctor_name = if self.realm.is_string_handle(handle) {
"String"
} else if self.realm.is_array_like(handle) {
"Array"
} else if let Some(is_set) = self.realm.collection_is_set(handle) {
// A *weak* collection inherits from `%WeakMap/WeakSet.prototype%`, not
// the strong `%Map/Set.prototype%` — conflating them resolved a WeakMap's
// first-class members (e.g. a `Symbol.toStringTag` fallback) from
// `Map.prototype`, wrongly reporting `[object Map]`.
match (self.realm.collection_is_weak(handle), is_set) {
(true, true) => "WeakSet",
(true, false) => "WeakMap",
(false, true) => "Set",
(false, false) => "Map",
}
} else if self.realm.function_at(handle).is_some()
|| self.realm.native_at(handle).is_some()
|| self.realm.bound_native_at(handle).is_some()
{
"Function"
} else {
return None;
};
let proto = self
.current
.get(ctor_name)
.and_then(|v| v.as_handle())
.map(Handle::from_raw)
.and_then(|ns| self.realm.get_property(ns, "prototype"))
.and_then(|p| p.as_handle())
.map(Handle::from_raw)?;
let m = self.realm.get_property(proto, name)?;
(!matches!(m.unpack(), Unpacked::Undefined)).then_some(m)
}
pub(crate) fn eval_assign(
&mut self,
op: AssignOp,
target: &'a Expr,
value: &'a Expr,
) -> Result<NanBox, ExecError> {
// AnnexB "Runtime Errors for Function Call Assignment Targets": a direct
// CallExpression LHS parses in sloppy code but is a runtime ReferenceError.
// The call itself is evaluated (its side effects run), then the assignment
// fails *before* the RHS is evaluated — matching the spec's ordering
// (`f() = g()` calls `f`, never `g`). Strict mode rejected this at parse
// time, so only sloppy `=`/`op=` reach here.
if target.is_web_compat_call_target() {
self.eval(target)?;
let m = self.new_str("Invalid left-hand side in assignment");
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
}
// Logical assignment (`&&=`/`||=`/`??=`) short-circuits: the right side
// is evaluated and stored only when the current value warrants it.
if matches!(
op,
AssignOp::AndAssign | AssignOp::OrAssign | AssignOp::NullishAssign
) {
// A computed-member target (non-super): evaluate base + key ONCE,
// shared by the read and the write — this both avoids the key
// double-eval (`obj[f()] &&= g()` calls `f()` once) and evaluates the
// key even on a null base, before that base's GetValue TypeError
// (`null[f()] &&= g()` runs `f()` first).
if let Expr::Member {
object,
property: PropertyKey::Computed(key_expr),
..
} = target
&& !matches!(&**object, Expr::Super(_))
{
let obj = self.eval(object)?;
let mut key = self.eval(key_expr)?;
let Some(raw) = obj.as_handle() else {
// A null/undefined base is a TypeError (the key was already
// evaluated); a number/boolean primitive reads `undefined` and
// its write is a sloppy no-op.
if matches!(obj.unpack(), Unpacked::Null | Unpacked::Undefined) {
return Err(self.type_error("Cannot read property of null or undefined"));
}
if matches!(op, AssignOp::AndAssign) {
return Ok(NanBox::undefined());
}
return self.eval(value);
};
let handle = crate::heap::Handle::from_raw(raw);
// Coerce an object key to a primitive property key once (its
// `toString` runs once, before the RHS), reused for read and write.
if key.as_handle().is_some_and(|r| {
let h = crate::heap::Handle::from_raw(r);
self.realm.symbol_at(h).is_none() && !self.realm.is_string_handle(h)
}) {
let pk = self.coerce_property_key(key)?;
key = self.new_str(&pk);
}
let current = self.read_member_value(handle, key)?;
let assign = match op {
AssignOp::AndAssign => self.realm.truthy(current),
AssignOp::OrAssign => !self.realm.truthy(current),
_ => matches!(current.unpack(), Unpacked::Undefined | Unpacked::Null),
};
if !assign {
return Ok(current);
}
let rhs = self.eval(value)?;
self.assign_member_value(handle, key, rhs)?;
return Ok(rhs);
}
let current = self.read_target(target)?;
let assign = match op {
AssignOp::AndAssign => self.realm.truthy(current),
AssignOp::OrAssign => !self.realm.truthy(current),
_ => matches!(current.unpack(), Unpacked::Undefined | Unpacked::Null),
};
if !assign {
return Ok(current);
}
let rhs = self.eval(value)?;
// NamedEvaluation: `x &&= function(){}` / `x ||= () => {}` /
// `x ??= class {}` names the anonymous RHS after the LHS *identifier*
// (only a simple identifier target, only an anonymous fn/arrow/class).
if let Expr::Ident(id) = target
&& matches!(value, Expr::Function(_) | Expr::Arrow(_) | Expr::Class(_))
{
self.set_fn_name(rhs, &id.name);
}
self.assign_to(target, rhs)?;
return Ok(rhs);
}
// A computed-member target evaluates the object and key *before* the RHS
// (spec order): `arr[i] = i = 1` writes the original `arr[i]`. A computed
// `super[expr]` target is excluded here — it has no evaluable base object
// and is handled by the `super` assignment arm below.
if let Expr::Member {
object,
property: PropertyKey::Computed(key_expr),
..
} = target
&& !matches!(&**object, Expr::Super(_))
{
let obj = self.eval(object)?;
// Spec reference order: evaluate the base, then the key expression,
// then (for a plain assignment) the RHS — *before* PutValue's
// RequireObjectCoercible. So a `null`/`undefined` base still evaluates
// the key and RHS, and only then throws a TypeError (not before).
let key = self.eval(key_expr)?;
let Some(raw) = obj.as_handle() else {
// `null`/`undefined` (or a number/boolean) base: a number/boolean
// is a primitive whose write is silently ignored in sloppy mode.
// For a *compound* op the LHS `GetValue` (RequireObjectCoercible)
// runs before the RHS, so a `null`/`undefined` base throws *before*
// the RHS is evaluated; a plain `=` defers the throw past the RHS.
let is_nullish = matches!(obj.unpack(), Unpacked::Null | Unpacked::Undefined);
if op != AssignOp::Assign && is_nullish {
return Err(self.type_error("Cannot read property of null or undefined"));
}
let rhs = self.eval(value)?;
if is_nullish {
return Err(self.type_error("Cannot set property of null or undefined"));
}
return Ok(rhs);
};
let handle = crate::heap::Handle::from_raw(raw);
let mut key = key;
let new = if op == AssignOp::Assign {
// Plain `=`: ToPropertyKey is deferred to PutValue, i.e. *after* the
// RHS — so the key's `toString` runs after the RHS is evaluated.
self.eval(value)?
} else {
// Compound `op=`: the LHS reference's GetValue runs before the RHS
// and performs ToPropertyKey on the key exactly once. For an object
// key, coerce now (a throwing or observable `toString` therefore
// runs before the RHS, and only once) and reuse the resulting
// primitive key for both the read and the write. Primitive keys
// (number / string / symbol) are left as-is so the array-index and
// typed-array fast paths in `read_member_value` still apply.
if key.as_handle().is_some_and(|raw| {
let h = Handle::from_raw(raw);
self.realm.symbol_at(h).is_none() && !self.realm.is_string_handle(h)
}) {
let pk = self.coerce_property_key(key)?;
key = self.new_str(&pk);
}
let current = self.read_member_value(handle, key)?;
let rhs = self.eval(value)?;
self.binary(compound_op(op)?, current, rhs)?
};
self.assign_member_value(handle, key, new)?;
return Ok(new);
}
// A computed `super[expr] = …` target: the key expression is evaluated
// before the RHS (spec reference order), then the inherited setter is
// invoked with the current `this`.
if let Expr::Member {
object,
property: PropertyKey::Computed(key_expr),
..
} = target
&& matches!(&**object, Expr::Super(_))
{
// GetThisBinding precedes evaluating the key expression: a derived
// constructor before `super()` throws ReferenceError here, never running
// the key or the RHS.
self.require_super_this()?;
// Evaluate the key *expression* first; for a plain assignment the RHS
// is evaluated before the key is ToPropertyKey-coerced, so
// `super[obj] = rhs()` runs `rhs` before `obj.toString` (the spec
// defers a super reference's key coercion past the RHS). A compound op
// must read `super[key]` first, so it coerces the key up front.
let k = self.eval(key_expr)?;
// For an object-literal method, GetSuperBase is captured now — before
// ToPropertyKey — so a key whose `toString` mutates the home object's
// prototype still targets the original base for both read and write.
let obj_base = self.object_super_base();
let (name, new) = if op == AssignOp::Assign {
let rhs = self.eval(value)?;
(self.coerce_property_key(k)?, rhs)
} else {
let name = self.coerce_property_key(k)?;
let current = match obj_base {
Some(Some(proto)) => self.read_super_member_object(proto, &name)?,
Some(None) => {
return Err(self.type_error("Cannot read property of null (super)"));
}
None => self.resolve_super_member(&name)?,
};
let rhs = self.eval(value)?;
(name, self.binary(compound_op(op)?, current, rhs)?)
};
match obj_base {
Some(Some(proto)) => self.assign_super_member_object(proto, &name, new)?,
Some(None) => {
return Err(self.type_error("Cannot set property on null (super)"));
}
None => self.assign_super_member(&name, new)?,
}
return Ok(new);
}
// A *compound* assignment to a static (non-computed, non-super) member
// target follows spec reference order: evaluate the base (`lref`), read the
// current value (`lval = GetValue(lref)`), *then* evaluate the RHS, apply the
// op, and write back. So `obj.x op= rhs()` reads `obj.x` before running
// `rhs()`, and a nullish base throws *before* the RHS is evaluated.
// (Computed-key targets are handled by the branch above.)
if op != AssignOp::Assign
&& let Expr::Member {
object, property, ..
} = target
&& !matches!(&**object, Expr::Super(_))
&& !matches!(property, PropertyKey::Computed(_))
{
let obj = self.eval(object)?;
let Some(raw) = obj.as_handle() else {
if matches!(obj.unpack(), Unpacked::Null | Unpacked::Undefined) {
return Err(self.type_error("Cannot read property of null or undefined"));
}
// A primitive base: read the (boxed) current value, evaluate the RHS
// for side effects, then ignore the write (sloppy mode).
let key = static_key(property)?;
let boxed = self.coerce_to_object(obj);
let current = match boxed.as_handle() {
Some(br) => self.read_member(crate::heap::Handle::from_raw(br), &key)?,
None => NanBox::undefined(),
};
let rhs = self.eval(value)?;
return self.binary(compound_op(op)?, current, rhs);
};
let handle = crate::heap::Handle::from_raw(raw);
let current = self.member(handle, property)?;
let rhs = self.eval(value)?;
let new = self.binary(compound_op(op)?, current, rhs)?;
self.assign_member(handle, property, new)?;
return Ok(new);
}
// A *compound* assignment to a bare identifier follows spec reference
// order: evaluate `lref` and read `lval = GetValue(lref)` *before* the
// RHS, then `PutValue(lref, …)` using that same reference. Capturing the
// binding's scope frame up front matters when the RHS has a side effect
// that introduces a more-local binding of the same name — e.g. a direct
// `eval("var x = …")` inside the RHS: the write must still target the
// originally-resolved (outer) binding, and the new local only shows
// through to *later* reads.
if op != AssignOp::Assign
&& let Expr::Ident(id) = target
{
let name = &*id.name;
// A `with`-object binding (captured before the RHS so the object's
// current value is read first and a setter fires on write). Both
// `GetBindingValue` (the read) and `SetMutableBinding` (the write)
// re-run `? HasProperty` (a proxy `has` trap) after the `HasBinding`
// resolution — a binding deleted mid-operation is a strict-mode
// ReferenceError.
if let Some(h) = self.with_binding_result(name)? {
let current = if self.has_property_proxied(h, name)? {
self.read_member(h, name)?
} else if self.strict {
let m = self.new_str(&alloc::format!("{name} is not defined"));
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
} else {
NanBox::undefined()
};
let rhs = self.eval(value)?;
let new = self.binary(compound_op(op)?, current, rhs)?;
if !self.has_property_proxied(h, name)? && self.strict {
let m = self.new_str(&alloc::format!("{name} is not defined"));
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
}
let key = self.new_str(name);
self.assign_member_value(h, key, new)?;
return Ok(new);
}
// An imported binding is immutable (module code is strict): error
// before running the RHS, matching the plain-assign path.
#[cfg(all(feature = "module", feature = "std"))]
if self.module_imports.contains_key(name) && self.current.get(name).is_none() {
let m = self.new_str("Assignment to constant variable.");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
if self.current.is_const(name) {
let m = self.new_str("Assignment to constant variable.");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// A named-function-expression name is a soft immutable binding: strict
// reassignment throws, sloppy is a silent no-op (the expression still
// evaluates to the RHS).
if self.current.is_soft_const(name) {
let rhs = self.eval(value)?;
if self.strict {
let m = self.new_str("Assignment to constant variable.");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
let current = self.read_ident_ref(name)?;
return Ok(if op == AssignOp::Assign {
rhs
} else {
self.binary(compound_op(op)?, current, rhs)?
});
}
// Capture the declarative reference (owning scope frame) *now*.
let frame = self.current.owner_frame(name);
let current = self.read_ident_ref(name)?;
let rhs = self.eval(value)?;
let new = self.binary(compound_op(op)?, current, rhs)?;
if let Some(fr) = frame {
fr.declare(name, new);
} else if !self.current.set(name, new) {
if self.strict {
let m = self.new_str(&alloc::format!("{name} is not defined"));
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
}
self.declare_sloppy_global(name, new);
}
return Ok(new);
}
// For `name = class {}`, hand the LHS name to `make_class` so an anonymous
// class's `name` is set before its static initializers run.
if op == AssignOp::Assign
&& let Expr::Ident(id) = target
&& let Expr::Class(c) = value
&& c.id.is_none()
{
self.pending_class_name = Some(&id.name);
}
// PutValue resolves the LHS reference *before* the RHS runs. For a plain
// `x = rhs` naming a bare identifier with no binding, capture whether `x`
// is already an own global-object property NOW, so a strict assignment to
// an unresolvable reference still throws even when the RHS creates that
// property (`undeclared = (this.undeclared = 5)` must throw).
let ident_pre_own_global = if let Expr::Ident(id) = target {
self.global_this
.as_handle()
.map(Handle::from_raw)
.is_some_and(|g| self.realm.has_own(g, &id.name))
} else {
false
};
// PutValue also resolves *which* binding the LHS names before the RHS runs.
// Capture that base now — the `with`-object frame that provides the name, or
// else the scope frame that owns it — so a RHS that mutates the binding
// structure (a `with`-object `delete`, or a direct-eval `var` that creates a
// shadowing local) cannot redirect the write to a different binding
// (test262 assignment/S11.13.1_A5*/A6*). The `with` walk is gated on there
// being a `with` scope at all, keeping the common case a single frame walk.
let (ident_with_ref, ident_owner_scope) = if let Expr::Ident(id) = target {
let with_ref = if self.in_with_scope() {
self.with_binding_result(&id.name)?
} else {
None
};
let owner = if with_ref.is_none() {
self.current.owner_frame(&id.name)
} else {
None
};
(with_ref, owner)
} else {
(None, None)
};
let rhs = self.eval(value)?;
self.pending_class_name = None;
// Destructuring assignment: `[a, b] = …` / `({ x } = …)`.
if op == AssignOp::Assign && matches!(target, Expr::Array { .. } | Expr::Object { .. }) {
self.assign_destructure(target, rhs)?;
return Ok(rhs);
}
match target {
Expr::Ident(id) => {
let name = &*id.name;
// An imported binding (`import { x } from "m"`) is an immutable
// indirect binding: assigning to it is a TypeError (module code is
// strict). The alias only applies when the name is not shadowed by
// a binding in the current scope chain — a same-named *local* of
// another module (e.g. a callee defined in a different module whose
// own `x` happens to match this module's import alias) is a normal,
// mutable binding.
#[cfg(all(feature = "module", feature = "std"))]
if self.module_imports.contains_key(name) && self.current.get(name).is_none() {
let m = self.new_str("Assignment to constant variable.");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// A bare identifier inside `with (obj)` reads/writes the with-object's
// property when it provides the name (so `with(o){ x op= v }` and
// setters/getters work). The providing object was resolved *before*
// the RHS (`ident_with_ref`), per PutValue's reference order.
if let Some(h) = ident_with_ref {
let new = if op == AssignOp::Assign {
rhs
} else {
let current = self.read_member(h, name)?;
self.binary(compound_op(op)?, current, rhs)?
};
// `SetMutableBinding` re-checks `? HasProperty` (a second `has`
// trap) after `HasBinding`: a strict write to a now-missing
// binding is a ReferenceError; sloppy still `[[Set]]`s.
if !self.has_property_proxied(h, name)? && self.strict {
let m = self.new_str(&alloc::format!("{name} is not defined"));
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
}
let key = self.new_str(name);
self.assign_member_value(h, key, new)?;
return Ok(new);
}
// Assigning to a lexical binding still in its temporal dead zone
// (a `let`/`const`/`class` referenced by a bare `x = v` before its
// declaration executes) is a ReferenceError — PutValue on an
// uninitialized binding throws, exactly as reading it does. The
// compound path additionally reads first (read_ident_ref, which
// also throws TDZ); this guards the plain `=` case where no read
// occurs before the write.
if self.current.get(name).is_some_and(|v| v.is_tdz()) {
let msg = self.new_str(&alloc::format!(
"Cannot access '{name}' before initialization"
));
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(msg)),
));
}
// Reassigning a `const` binding is a TypeError.
if self.current.is_const(name) {
let m = self.new_str("Assignment to constant variable.");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// A named-function-expression name is a soft immutable binding:
// strict reassignment throws, sloppy is a silent no-op (the
// expression still evaluates to the RHS / compound result).
if self.current.is_soft_const(name) {
if self.strict {
let m = self.new_str("Assignment to constant variable.");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(if op == AssignOp::Assign {
rhs
} else {
let current = self.read_ident_ref(name)?;
self.binary(compound_op(op)?, current, rhs)?
});
}
let new = if op == AssignOp::Assign {
// NamedEvaluation: `x = function(){}` / `x = () => {}` /
// `x = class {}` names the anonymous definition after the LHS
// identifier (only for a plain `=`, and only when the RHS is an
// anonymous function/arrow/class).
if matches!(value, Expr::Function(_) | Expr::Arrow(_) | Expr::Class(_)) {
self.set_fn_name(rhs, name);
}
rhs
} else {
// A compound assignment reads the LHS first (`GetValue`); an
// unresolvable reference throws a catchable ReferenceError (matching
// a bare-identifier read), not an internal error.
let current = self.read_ident_ref(name)?;
self.binary(compound_op(op)?, current, rhs)?
};
// Write through the frame resolved *before* the RHS
// (`ident_owner_scope`) so a direct-eval `var` created by the RHS
// cannot capture the assignment; in the common case this is the same
// frame `self.current.set` would find.
let stored = match &ident_owner_scope {
Some(sc) => sc.set(name, new),
None => self.current.set(name, new),
};
if !stored {
// A property on the global object (created via `this.x = …` /
// `globalThis.x = …`, or a global `var`) is a *resolvable*
// reference — assignment updates it, in strict mode too. Only a
// truly unresolvable reference is a strict-mode ReferenceError.
// Mirrors the read path's global-object own-property fallback.
// Skipped inside a `with` scope (object-first resolution): a
// deleted `with` binding must still reach the strict throw.
// Uses the pre-RHS resolvability (`ident_pre_own_global`): the
// reference is resolved before the RHS, so a property the RHS
// itself creates does NOT make the reference resolvable
// (`undeclared = (this.undeclared = 5)` throws in strict). But
// SetMutableBinding for the global object env record also re-checks
// HasProperty at PutValue time: if the RHS deleted the property, a
// strict write throws ReferenceError while a sloppy write recreates
// it (`x = (delete global.x, 2)`).
if !self.in_with_scope()
&& ident_pre_own_global
&& let Some(g) = self.global_this.as_handle().map(Handle::from_raw)
&& (self.realm.has_own(g, name) || !self.strict)
{
// …unless the property is non-writable (`NaN`,
// `Infinity`, `undefined`): `[[Set]]` returns false, which
// `PutValue` turns into a TypeError for a strict
// reference and silently ignores for a sloppy one.
if self.realm.property_is_readonly(g, name) {
if self.strict {
let m = self.new_str(&alloc::format!(
"Cannot assign to read only property '{name}'"
));
return Err(ExecError::Throw(
self.make_error(N_TYPE_ERROR, Some(m)),
));
}
return Ok(new);
}
self.realm.set_property(g, name, new);
return Ok(new);
}
// A strict write whose global-object property the RHS deleted
// (or an unresolvable reference) falls through to the throw.
if self.strict {
let m = self.new_str(&alloc::format!("{name} is not defined"));
return Err(ExecError::Throw(
self.make_error(N_REFERENCE_ERROR, Some(m)),
));
}
// Sloppy implicit global: bind on the global scope + object.
self.declare_sloppy_global(name, new);
}
Ok(new)
}
Expr::Member {
object, property, ..
} if matches!(&**object, Expr::Super(_)) => {
// `super.x = v` (and `super.x op= v`) invokes the inherited setter with
// the current `this`; a compound op reads through `super.x` first.
let name = self.eval_prop_key(property)?;
let new = if op == AssignOp::Assign {
rhs
} else {
let current = self.resolve_super_member(&name)?;
self.binary(compound_op(op)?, current, rhs)?
};
self.assign_super_member(&name, new)?;
Ok(new)
}
Expr::Member {
object, property, ..
} => {
let obj = self.eval(object)?;
let Some(raw) = obj.as_handle() else {
// A `null`/`undefined` base throws a TypeError; another primitive
// (number/boolean) silently ignores the write in sloppy mode.
if matches!(obj.unpack(), Unpacked::Null | Unpacked::Undefined) {
return Err(self.type_error("Cannot set property of null or undefined"));
}
// PrivateFieldSet step 2: a private write requires an object
// receiver — a primitive `this` (`method.call(15)` reaching
// `this.#p = …`) is a TypeError, never a silent no-op.
if let PropertyKey::Private(s) = property {
let m = self.new_str(&alloc::format!(
"Cannot write private member #{s} to a non-object"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// Writing a property of a number/boolean primitive follows
// PutValue → ToObject → [[Set]] (see `write_primitive_member`):
// an inherited setter / prototype Proxy fires, else it is a
// strict-mode TypeError / sloppy no-op.
if matches!(obj.unpack(), Unpacked::Number(_) | Unpacked::Bool(_)) {
let new = if op == AssignOp::Assign {
rhs
} else {
let current = self.read_member_of(obj, property, false)?;
self.binary(compound_op(op)?, current, rhs)?
};
self.write_primitive_member(obj, property, new)?;
return Ok(new);
}
return Ok(rhs);
};
// A primitive base that is a *heap* value (a String / Symbol /
// BigInt primitive) is ToObject'd before `[[Set]]`: an inherited
// setter or a Proxy on the wrapper's prototype chain fires, else
// the write would create an own data property on the non-object
// primitive receiver — a strict-mode TypeError, a sloppy no-op
// (see `write_primitive_member`). An ordinary object base writes
// directly.
if !self.is_object_value(obj) {
let new = if op == AssignOp::Assign {
rhs
} else {
let current = self.read_member_of(obj, property, false)?;
self.binary(compound_op(op)?, current, rhs)?
};
self.write_primitive_member(obj, property, new)?;
return Ok(new);
}
let handle = crate::heap::Handle::from_raw(raw);
let new = if op == AssignOp::Assign {
rhs
} else {
let current = self.member(handle, property)?;
self.binary(compound_op(op)?, current, rhs)?
};
self.assign_member(handle, property, new)?;
Ok(new)
}
_ => Err(ExecError::Unsupported("assignment target")),
}
}
pub(crate) fn assign_member(
&mut self,
handle: crate::heap::Handle,
property: &'a PropertyKey,
new: NanBox,
) -> Result<(), ExecError> {
// A **module namespace exotic object**'s `[[Set]]` always fails (§28.3.6):
// its bindings are not assignable through the namespace. In strict code
// (module code always is) the failed Set is a TypeError.
#[cfg(all(feature = "module", feature = "std"))]
if self.module_namespaces.contains_key(&handle.to_raw()) {
if self.strict {
return Err(self.type_error(
"cannot assign to a read-only property of a module namespace object",
));
}
return Ok(());
}
// `regex.lastIndex = n` updates the RegExp's stateful search position
// (honoring a non-writable descriptor installed via `defineProperty`).
if let PropertyKey::Ident(s) | PropertyKey::Str(s) = property
&& &**s == "lastIndex"
&& self.realm.regexp_at(handle).is_some()
{
return self.regex_write_last_index(handle, new);
}
// `obj.__proto__ = proto` invokes the inherited `set __proto__` accessor
// (Annex B), which performs `O.[[SetPrototypeOf]]` like
// `Object.setPrototypeOf` — a non-object, non-null value is ignored, and a
// failed set (non-extensible object, or a prototype cycle) throws a
// TypeError. The magic only applies when the object actually inherits
// `Object.prototype`'s accessor and has no own `__proto__` data property;
// otherwise the write falls through to an ordinary property assignment.
if let PropertyKey::Ident(s) | PropertyKey::Str(s) = property
&& &**s == "__proto__"
&& !self.realm.has_own(handle, "__proto__")
&& self.realm.inherits_object_proto(handle)
{
let proto = match new.unpack() {
Unpacked::Null => Some(None),
_ if self.is_object_value(new) => Some(new.as_handle().map(Handle::from_raw)),
_ => None,
};
if let Some(p) = proto
&& !self.set_proto_of(handle, p)?
{
return Err(self.type_error(
"Object.prototype.__proto__: cannot set prototype of this object",
));
}
return Ok(());
}
// Writing a static on a class (`C.field = v`, `++C.field`). Statics are
// mirrored as real own properties on the constructor, so an own accessor is
// invoked through that mirror and an own data write lands on the mirror —
// keeping reflection and the fast read path (which now reads the mirror)
// in sync. An *inherited* static setter (on a superclass) is still
// dispatched via the side tables.
if let Some((cid, _)) = self.realm.class_at(handle) {
let key = self.eval_prop_key(property)?;
// Own accessor (getter/setter installed on this constructor's mirror).
if let Some((_, setter)) = self.realm.accessor(handle, &key) {
if !matches!(setter.unpack(), Unpacked::Undefined) {
let this = NanBox::handle(handle.to_raw());
self.call_with_this(setter, this, &[new])?;
} else if let PropertyKey::Private(s) = property {
// A getter-only *private* accessor always throws on set (there
// is no silent-failure path for private references).
let m = self.new_str(&alloc::format!(
"Cannot write private member #{s} which has only a getter"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// A getter-only own (public) accessor: the write is silently
// ignored (non-strict) — matching ordinary accessor semantics.
return Ok(());
}
// Inherited static setter (walk the superclass chain).
let class = self.classes[cid as usize];
let env = self.class_envs[cid as usize].clone();
let mut cur = self.resolve_super(class, &env)?.map(|(pid, _)| pid);
while let Some(c) = cur {
if let Some(setter) = self.class_static_set[c as usize].get(&key).copied() {
let this = NanBox::handle(handle.to_raw());
self.call_with_this(setter, this, &[new])?;
return Ok(());
}
if self.class_static_get[c as usize].contains_key(&key) {
// Inherited getter-only: write ignored (non-strict).
return Ok(());
}
let class = self.classes[c as usize];
let env = self.class_envs[c as usize].clone();
cur = self.resolve_super(class, &env)?.map(|(pid, _)| pid);
}
// PrivateSet brand check on a class receiver: writing `this.#x` where
// this class does not carry `#x` (a distinct per-class brand) is a
// TypeError — e.g. `C1.access.call(C2)` writing `C1`'s static `#m` on an
// unrelated class `C2`. An own accessor was already dispatched above, so
// reaching here without an own key means the element is genuinely absent.
if let PropertyKey::Private(s) = property {
if !self.realm.has_own(handle, &key) {
let m = self.new_str(&alloc::format!(
"Cannot write private member #{s} to an object whose class did not declare it"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// A static private *method* is a non-writable own key: PrivateSet
// on it is a TypeError (methods and getter-only accessors can't be
// assigned).
if self.realm.property_is_readonly(handle, &key) {
let m = self.new_str(&alloc::format!(
"Cannot write to private method or accessor #{s}"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
}
// An accessor inherited through the *ordinary* `[[Prototype]]` chain
// (not the class-static side tables) handles the write — most notably
// the poisoned `Function.prototype.caller`/`.arguments` accessors that a
// class constructor inherits. `set_through_proto_chain` invokes the
// setter (a poisoned one throws) and stops; it returns `None` for a plain
// inherited/absent data property, which falls through to the data write.
if !self.realm.has_own(handle, &key)
&& let Some(()) = self.set_through_proto_chain(handle, &key, new)?
{
return Ok(());
}
// Plain own data static: update both the mirror (authoritative for
// reflection/reads) and the side table (kept consistent for any
// remaining side-table consumer).
self.realm.set_property(handle, &key, new);
self.class_statics[cid as usize].insert(key, new);
return Ok(());
}
// Proxy `[[Set]]`: route through the receiver-aware `proxy_set_bool`
// (shared with `Reflect.set` and `assign_member_value`), passing the proxy
// itself as the Receiver. A trapless forward keeps the Receiver, so an
// inherited accessor setter (e.g. `Object.prototype.__proto__`) runs with
// `this` = the proxy and a nested proxy target re-enters its own trap. A
// `false` result is a failed [[Set]]: strict code throws, sloppy is silent.
if self.realm.proxy_at(handle).is_some() {
let key = self.eval_prop_key(property)?;
let recv = NanBox::handle(handle.to_raw());
let ok = self.proxy_set_bool(handle, &key, new, recv)?;
if !ok && self.strict {
let m = self.new_str(&alloc::format!(
"'set' on proxy: trap returned falsish for property '{key}'"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(());
}
// An accessor setter — own or inherited via the prototype chain — takes
// precedence over creating a data property. A private accessor
// (`set #x() {…}`) is stored under the `#`-prefixed key, so resolve that.
let setter_key: Option<alloc::string::String> = match property {
PropertyKey::Ident(s) | PropertyKey::Str(s) => Some(String::from(&**s)),
PropertyKey::Private(s) => Some(self.private_access_key(s)),
_ => None,
};
if let Some(skey) = setter_key {
let mut cur = Some(handle);
while let Some(c) = cur {
// OrdinarySet: a proxy *on the prototype chain* (above the original
// receiver) handles the write via its own `[[Set]]` — invoke its
// `set` trap with Receiver = the original object, then stop.
if c != handle
&& let Some((target, p_handler)) = self.realm.proxy_at(c)
{
self.guard_revoked(c)?;
if let Some(trap) = self.proxy_trap(p_handler, "set")? {
let key_box = self.new_str(&skey);
let recv = NanBox::handle(handle.to_raw());
let handler_box = NanBox::handle(p_handler.to_raw());
let r = self.call_with_this(
trap,
handler_box,
&[NanBox::handle(target.to_raw()), key_box, new, recv],
)?;
if self.strict && !self.realm.truthy(r) {
let m = self.new_str(&alloc::format!(
"'set' on proxy: trap returned falsish for property '{skey}'"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(());
}
// No `set` trap: the proxy's `[[Set]]` is OrdinarySet on the
// target with the *original* receiver. If the target has an
// inherited accessor it would fire, but the common case is a
// data property (or absent), which creates/updates an OWN data
// property on the original receiver. Stop the prototype walk and
// fall through to the own-property write on `handle` — unless the
// target itself has a *setter* for this key, which must run.
if let Some((_, setter)) = self.realm.accessor(target, &skey)
&& !matches!(setter.unpack(), Unpacked::Undefined)
{
let this = NanBox::handle(handle.to_raw());
self.call_with_this(setter, this, &[new])?;
return Ok(());
}
break;
}
if let Some((_, setter)) = self.realm.accessor(c, &skey) {
if !matches!(setter.unpack(), Unpacked::Undefined) {
let this = NanBox::handle(handle.to_raw());
self.call_with_this(setter, this, &[new])?;
} else if self.strict || matches!(property, PropertyKey::Private(_)) {
// Writing a getter-only accessor is a TypeError in strict
// mode; for a *private* accessor it always throws (there is
// no silent-failure path for private references).
let m = self.new_str(&alloc::format!(
"Cannot set property {skey} which has only a getter"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// A getter-only accessor still shadows a data assignment.
return Ok(());
}
// An own data property below shadows an inherited accessor.
if self.realm.has_own(c, &skey) {
// OrdinarySetWithOwnDescriptor: an *inherited* (`c != handle`)
// non-writable data property makes the whole [[Set]] fail — strict
// throws, sloppy drops — with no shadowing own property created on
// the receiver. The receiver's own property (`c == handle`) falls
// through to the normal write, which honors its own writability.
if c != handle && !self.can_write_property(c, &skey) {
if self.strict {
let m = self.new_str(&alloc::format!(
"Cannot assign to read only property '{skey}'"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(());
}
break;
}
cur = self.realm.object_proto(c);
}
}
match property {
PropertyKey::Number(n) if as_index(*n).is_some() && self.realm.is_array(handle) => {
self.store_array_index(handle, as_index(*n).unwrap(), new)?;
}
PropertyKey::Computed(e) => {
let k = self.eval(e)?;
// A numeric index only addresses array storage; on an object a
// numeric key is the equivalent string property.
if let Some(i) = k.as_number().and_then(as_index)
&& self.realm.is_array(handle)
{
// OrdinarySet: when the index has no own property, honor an
// inherited index setter reached through the prototype chain
// (e.g. `Array.prototype[1]`'s setter, for a `for (arr[1] in …)`
// / `[arr[1]] = …` target) before the dense write. Guarded like
// `assign_member_value` so a pristine `%Array.prototype%` chain
// keeps the fast path.
let absent_own = self
.realm
.array_length(handle)
.is_none_or(|len| i >= len || self.realm.get_element(handle, i).is_hole());
if absent_own
&& (self.realm.object_proto(handle) != self.realm.array_proto_intrinsic()
|| self.realm.proto_index_accessor_dirty())
&& self
.realm
.accessor(handle, &alloc::format!("{i}"))
.is_none()
&& let Some(()) =
self.set_through_proto_chain(handle, &alloc::format!("{i}"), new)?
{
return Ok(());
}
self.store_array_index(handle, i, new)?;
} else {
let name = self.coerce_property_key(k)?;
if self.allow_property_write(handle, &name)? {
self.realm.set_property(handle, &name, new);
}
}
}
PropertyKey::Ident(s) | PropertyKey::Str(s) => {
// `arr.length = n` resizes the array (truncate/pad), rather than
// storing a `length` property.
if &**s == "length" && self.realm.is_array(handle) {
let n = self.array_length_from_value(new)?;
self.write_array_length(handle, n)?;
} else if &**s == "prototype"
&& let Some((func_id, _)) = self.realm.function_at(handle)
&& let Some(praw) = new.as_handle()
&& !self.realm.property_is_readonly(handle, "prototype")
{
// `Fn.prototype = obj` reassigns the constructor's prototype.
// Keep the side table (drives the `new`/`Reflect.construct`
// read) and the materialized own data property in sync.
self.realm
.set_function_prototype(func_id, Handle::from_raw(praw));
self.realm.set_property(handle, "prototype", new);
} else if self.allow_property_write(handle, s)? {
self.realm.set_property(handle, s, new);
}
}
PropertyKey::Number(n) => {
// Canonical `ToString(Number)` so a non-canonical literal write
// (`obj[0.0000001] = v`) keys identically to the read (`"1e-7"`).
self.realm
.set_property(handle, &crate::realm::js_number_string(*n), new);
}
PropertyKey::Private(s) => {
// Writing `obj.#x` where obj's class did not declare `#x` is a TypeError.
// (Field initialization writes via `set_property` directly, not this path,
// so the initial creation of a field is exempt; a class receiver, for
// static privates, is resolved via separate per-class storage.)
let key = self.private_access_key(s);
// PrivateSet requires the receiver to actually carry the private
// element — as a field (own data key) or an accessor. This holds for
// *static* privates too: `C1.access.call(C2)` writing `this.#m` throws
// a TypeError because `C2` lacks `C1`'s `#m` (its distinct per-class
// brand). A found accessor was already invoked by the prototype-chain
// walk above, so reaching here means the element is genuinely absent.
// (First-time field creation writes via `set_property` directly, not
// this path, so a fresh field is exempt.)
if !self.realm.has_own(handle, &key) && self.realm.accessor(handle, &key).is_none()
{
let m = self.new_str(&alloc::format!(
"Cannot write private member #{s} to an object whose class did not declare it"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// PrivateSet on a private *method* is a TypeError (methods are
// non-writable). Such a property is installed read-only, so an
// own read-only private key here is a method, not a field.
if self.realm.has_own(handle, &key) && self.realm.property_is_readonly(handle, &key)
{
let m = self.new_str(&alloc::format!(
"Cannot write to private method or accessor #{s}"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
self.realm.set_property(handle, &key, new);
}
}
Ok(())
}
pub(crate) fn unary(&mut self, op: UnaryOp, v: NanBox) -> Result<NanBox, ExecError> {
// BigInt negation / bitwise-not stay BigInt.
if let Some(big) = v
.as_handle()
.and_then(|raw| self.realm.bigint_at(Handle::from_raw(raw)))
{
match op {
UnaryOp::Minus => {
return Ok(NanBox::handle(self.realm.new_bigint(big.neg()).to_raw()));
}
UnaryOp::BitNot => {
// `~x` on a BigInt is `-(x + 1)`.
let one = crate::bignum::BigInt::from_i128(1);
let nx = big.add(&one).neg();
return Ok(NanBox::handle(self.realm.new_bigint(nx).to_raw()));
}
UnaryOp::Not => return Ok(NanBox::boolean(big.is_zero())),
_ => {}
}
}
// A Symbol cannot be converted to a number (unary `+`/`-`/`~`).
if matches!(op, UnaryOp::Plus | UnaryOp::Minus | UnaryOp::BitNot)
&& v.as_handle()
.map(Handle::from_raw)
.is_some_and(|h| self.realm.symbol_at(h).is_some())
{
let m = self.new_str("Cannot convert a Symbol value to a number");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// For the numeric unary operators, ToPrimitive(number) may surface a boxed
// Symbol/BigInt (e.g. `+Object(Symbol())`, `-Object(1n)`). ToNumber then
// throws a TypeError for a Symbol and for a BigInt under `+`; `-`/`~` on a
// BigInt stay BigInt (ToNumeric).
if matches!(op, UnaryOp::Plus | UnaryOp::Minus | UnaryOp::BitNot) {
let p = self.coerce_object(v, "number")?;
if let Some(h) = p.as_handle().map(Handle::from_raw) {
if self.realm.symbol_at(h).is_some() {
let m = self.new_str("Cannot convert a Symbol value to a number");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
if let Some(big) = self.realm.bigint_at(h) {
return match op {
UnaryOp::Minus => {
Ok(NanBox::handle(self.realm.new_bigint(big.neg()).to_raw()))
}
#[cfg(feature = "std")]
UnaryOp::BitNot => {
let one = crate::bignum::BigInt::from_i128(1);
let nx = big.add(&one).neg();
Ok(NanBox::handle(self.realm.new_bigint(nx).to_raw()))
}
_ => {
let m = self.new_str("Cannot convert a BigInt value to a number");
Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))))
}
};
}
}
return Ok(match op {
UnaryOp::Plus => NanBox::number(self.realm.to_number(p)),
UnaryOp::Minus => self.realm.neg(p),
#[cfg(feature = "std")]
UnaryOp::BitNot => self.realm.bit_not(p),
#[cfg(not(feature = "std"))]
UnaryOp::BitNot => return Err(ExecError::Unsupported("~ needs std")),
_ => unreachable!(),
});
}
Ok(match op {
UnaryOp::Not => self.realm.logical_not(v),
UnaryOp::Typeof => {
let t = self.realm.type_of_value(v);
NanBox::handle(self.realm.new_string(t).to_raw())
}
UnaryOp::Void => NanBox::undefined(),
UnaryOp::Plus | UnaryOp::Minus | UnaryOp::BitNot => unreachable!(),
UnaryOp::Delete => return Err(ExecError::Unsupported("delete")),
})
}
/// The BigInt operator path. Returns `None` to fall through (e.g. `bigint +
/// string` is string concatenation). Both operands BigInt → i128 arithmetic;
/// a mix with a Number throws a `TypeError` for arithmetic but compares
/// numerically for `<`/`==`.
pub(crate) fn bigint_binary(
&mut self,
op: BinaryOp,
abig: Option<crate::bignum::BigInt>,
bbig: Option<crate::bignum::BigInt>,
a: NanBox,
b: NanBox,
) -> Result<Option<NanBox>, ExecError> {
// Strict equality: equal only if both are BigInt with the same value.
match op {
BinaryOp::EqEqEq => return Ok(Some(NanBox::boolean(abig.is_some() && abig == bbig))),
BinaryOp::NotEqEq => {
return Ok(Some(NanBox::boolean(!(abig.is_some() && abig == bbig))));
}
_ => {}
}
if let (Some(x), Some(y)) = (abig.clone(), bbig.clone()) {
use core::cmp::Ordering;
let val = |this: &mut Self, n: crate::bignum::BigInt| {
NanBox::handle(this.realm.new_bigint(n).to_raw())
};
let throw = |this: &mut Self, msg: &str| {
let m = this.new_str(msg);
ExecError::Throw(this.make_error(N_TYPE_ERROR, Some(m)))
};
// BigInt division/remainder by zero and a negative exponent are
// RangeErrors (not TypeErrors) per BigInt::divide/remainder/exponentiate.
let range_throw = |this: &mut Self, msg: &str| {
let m = this.new_str(msg);
ExecError::Throw(this.make_error(N_RANGE_ERROR, Some(m)))
};
let r = match op {
BinaryOp::Add => val(self, x.add(&y)),
BinaryOp::Sub => val(self, x.sub(&y)),
BinaryOp::Mul => val(self, x.mul(&y)),
BinaryOp::Div => match x.divmod(&y) {
Some((q, _)) => val(self, q),
None => return Err(range_throw(self, "Division by zero")),
},
BinaryOp::Mod => match x.divmod(&y) {
Some((_, rem)) => val(self, rem),
None => return Err(range_throw(self, "Division by zero")),
},
BinaryOp::Exp => {
if y.is_negative() {
return Err(range_throw(self, "Exponent must be non-negative"));
}
let e = y.to_i128().and_then(|v| u64::try_from(v).ok()).unwrap_or(0);
// Projected result size ≈ bit_len(x) × e. `try_pow` rejects
// before the (possibly multi-GB) allocation, else `2n ** 1e10n`
// OOMs. Belt and suspenders: the same cap is enforced here so
// the error path is unmistakable.
let Some(p) = x.try_pow(e, self.realm.limits.max_bigint_bits) else {
let m = self.new_str("Maximum BigInt size exceeded");
return Err(ExecError::Throw(self.make_error(N_RANGE_ERROR, Some(m))));
};
val(self, p)
}
// Two's-complement bitwise ops at arbitrary precision.
BinaryOp::BitAnd => val(self, x.bitand(&y)),
BinaryOp::BitOr => val(self, x.bitor(&y)),
BinaryOp::BitXor => val(self, x.bitxor(&y)),
// `<<`/`>>` as multiply/floor-divide by `2^n` (a negative shift
// count reverses direction). BigInts have no unsigned `>>>`.
BinaryOp::Shl | BinaryOp::Shr => {
let two = crate::bignum::BigInt::from_i128(2);
let count = y.to_i128().unwrap_or(0);
// `>>` is `<<` by the negated count, and vice versa.
let left = (op == BinaryOp::Shl) == (count >= 0);
let mag = u64::try_from(count.unsigned_abs()).unwrap_or(0);
// A left shift grows the result to ≈ bit_len(x) + mag bits;
// reject an attacker count before building `2^mag`. (A right
// shift only shrinks, so it needs no bound — but `2^mag` is
// still built, so cap the exponent itself.)
let projected = if left {
x.bit_len().saturating_add(mag)
} else {
mag
};
if projected > self.realm.limits.max_bigint_bits {
let m = self.new_str("Maximum BigInt size exceeded");
return Err(ExecError::Throw(self.make_error(N_RANGE_ERROR, Some(m))));
}
let pow2 = two.pow(mag);
if left {
val(self, x.mul(&pow2))
} else {
match x.divmod(&pow2) {
// Arithmetic shift floors; truncating divmod needs a
// `-1` correction for a negative value with a remainder.
Some((q, rem)) => {
if x.is_negative() && !rem.is_zero() {
val(self, q.sub(&crate::bignum::BigInt::from_i128(1)))
} else {
val(self, q)
}
}
None => val(self, crate::bignum::BigInt::zero()),
}
}
}
BinaryOp::Ushr => {
return Err(throw(self, "BigInts have no unsigned right shift"));
}
BinaryOp::Lt => NanBox::boolean(x.cmp(&y) == Ordering::Less),
BinaryOp::Gt => NanBox::boolean(x.cmp(&y) == Ordering::Greater),
BinaryOp::LtEq => NanBox::boolean(x.cmp(&y) != Ordering::Greater),
BinaryOp::GtEq => NanBox::boolean(x.cmp(&y) != Ordering::Less),
BinaryOp::EqEq => NanBox::boolean(x == y),
BinaryOp::NotEq => NanBox::boolean(x != y),
_ => return Ok(None),
};
return Ok(Some(r));
}
// Mixed: `bigint + string` (either side a string) → string concat.
if matches!(op, BinaryOp::Add) {
let is_str = |this: &Self, v: NanBox| {
v.as_handle()
.is_some_and(|raw| this.realm.string_value(Handle::from_raw(raw)).is_some())
};
if is_str(self, a) || is_str(self, b) {
return Ok(None);
}
}
// BigInt vs a non-BigInt primitive: exactly one operand is a BigInt (the
// both-BigInt case returned above). Equality and the relational operators
// compare per spec — a String coerces via StringToBigInt (an invalid string
// is "undefined", i.e. never equal / an undefined ordering → `false`), a
// Number/Boolean/null compares *mathematically exactly* (no lossy `f64`
// round-trip), a Symbol throws for a relational compare (and is unequal for
// `==`), and `undefined` is incomparable.
if matches!(
op,
BinaryOp::EqEq
| BinaryOp::NotEq
| BinaryOp::Lt
| BinaryOp::Gt
| BinaryOp::LtEq
| BinaryOp::GtEq
) {
use core::cmp::Ordering;
let is_equality = matches!(op, BinaryOp::EqEq | BinaryOp::NotEq);
let is_relational = !is_equality;
// The single BigInt operand and whether it is the left-hand side.
let (big, big_left) = match (&abig, &bbig) {
(Some(x), _) => (x.clone(), true),
(_, Some(y)) => (y.clone(), false),
_ => return Ok(None),
};
let other = if big_left { b } else { a };
// Resolve `other` to something comparable to a BigInt.
enum Rhs {
Big(crate::bignum::BigInt),
Num(f64),
Incomparable,
}
let resolved = match other.unpack() {
Unpacked::Number(n) => Rhs::Num(n),
Unpacked::Bool(bl) => Rhs::Num(if bl { 1.0 } else { 0.0 }),
// `==` null/undefined → not equal; a relational compares numerically
// (ToNumeric(null) = 0, ToNumeric(undefined) = NaN → incomparable).
Unpacked::Null => {
if is_equality {
Rhs::Incomparable
} else {
Rhs::Num(0.0)
}
}
Unpacked::Undefined => Rhs::Incomparable,
Unpacked::Handle(raw) => {
let h = Handle::from_raw(raw);
if let Some(s) = self.realm.string_value(h) {
match string_to_bigint_opt(&s) {
Some(nb) => Rhs::Big(nb),
None => Rhs::Incomparable,
}
} else if self.realm.symbol_at(h).is_some() {
if is_relational {
let m = self.new_str("Cannot convert a Symbol value to a number");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
Rhs::Incomparable
} else {
// A coercible object is excluded upstream; anything else is
// not a BigInt-comparable primitive — defer.
return Ok(None);
}
}
};
// `ord` is `big` compared against `other`; flip when the BigInt is on
// the right so it reflects the source (left-vs-right) order.
let ord = match resolved {
Rhs::Incomparable => None,
Rhs::Big(ob) => Some(big.cmp(&ob)),
Rhs::Num(n) => bigint_cmp_f64(&big, n),
};
let ord = if big_left {
ord
} else {
ord.map(Ordering::reverse)
};
let r = match op {
BinaryOp::EqEq => ord == Some(Ordering::Equal),
BinaryOp::NotEq => ord != Some(Ordering::Equal),
BinaryOp::Lt => ord == Some(Ordering::Less),
BinaryOp::Gt => ord == Some(Ordering::Greater),
BinaryOp::LtEq => matches!(ord, Some(Ordering::Less | Ordering::Equal)),
_ => matches!(ord, Some(Ordering::Greater | Ordering::Equal)),
};
return Ok(Some(NanBox::boolean(r)));
}
// Mixed arithmetic is a TypeError.
let m = self.new_str("Cannot mix BigInt and other types");
Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))))
}
/// `ToNumber`'s Symbol guard: a Symbol primitive has no numeric conversion, so
/// `ToNumeric`/`ToNumber` on one is a `TypeError`. Used to reject a lhs Symbol
/// mid-`ToNumeric` before the rhs is converted (spec operand order).
fn throw_if_symbol_to_number(&mut self, v: NanBox) -> Result<(), ExecError> {
if v.as_handle()
.map(Handle::from_raw)
.is_some_and(|h| self.realm.symbol_at(h).is_some())
{
let m = self.new_str("Cannot convert a Symbol value to a number");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
Ok(())
}
pub(crate) fn binary(
&mut self,
op: BinaryOp,
a: NanBox,
b: NanBox,
) -> Result<NanBox, ExecError> {
// An operand that is a wrapper/plain object (not a bigint/string primitive
// or symbol) must be ToPrimitive-coerced *before* the BigInt path, so a
// BigInt wrapper (`Object(1n)`) or a `Symbol.toPrimitive` yielding a BigInt
// is unwrapped first. Defer the BigInt check in that case.
let is_coercible_object = |this: &Self, v: NanBox| {
v.as_handle().map(Handle::from_raw).is_some_and(|h| {
this.realm.bigint_at(h).is_none()
&& !this.realm.is_string_handle(h)
&& this.realm.symbol_at(h).is_none()
})
};
// BigInt operands take a dedicated path (i128 arithmetic; mixing with
// other numeric types throws, per the spec).
let abig = a
.as_handle()
.and_then(|raw| self.realm.bigint_at(Handle::from_raw(raw)));
let bbig = b
.as_handle()
.and_then(|raw| self.realm.bigint_at(Handle::from_raw(raw)));
if (abig.is_some() || bbig.is_some())
&& !is_coercible_object(self, a)
&& !is_coercible_object(self, b)
&& let Some(r) = self.bigint_binary(op, abig, bbig, a, b)?
{
return Ok(r);
}
// Arithmetic and relational operators apply ToPrimitive to object
// operands (`valueOf`/`toString`); equality/`instanceof`/`in` do not.
let coerces = matches!(
op,
BinaryOp::Add
| BinaryOp::Sub
| BinaryOp::Mul
| BinaryOp::Div
| BinaryOp::Mod
| BinaryOp::Exp
| BinaryOp::Lt
| BinaryOp::Gt
| BinaryOp::LtEq
| BinaryOp::GtEq
| BinaryOp::Shl
| BinaryOp::Shr
| BinaryOp::Ushr
| BinaryOp::BitAnd
| BinaryOp::BitOr
| BinaryOp::BitXor
);
// `+` uses the "default" hint; the other numeric operators use "number".
let hint = if matches!(op, BinaryOp::Add) {
"default"
} else {
"number"
};
let (a, b) = if coerces && (a.as_handle().is_some() || b.as_handle().is_some()) {
// A multiplicative/additive/bitwise/shift operator applies
// `ToNumeric(lhs)` *fully* — ToPrimitive **and** ToNumber, the latter
// throwing for a Symbol — before touching the rhs, so a lhs whose
// conversion throws never evaluates the rhs's `valueOf`
// (`order-of-evaluation`). `+` and the relational operators instead
// ToPrimitive *both* operands first (a Symbol only throws at the later
// ToNumeric/ToString step), so they coerce as a pair.
let sequential = !matches!(
op,
BinaryOp::Add | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::LtEq | BinaryOp::GtEq
);
if sequential {
let a = self.coerce_primitive(a, hint)?;
self.throw_if_symbol_to_number(a)?;
let b = self.coerce_primitive(b, hint)?;
self.throw_if_symbol_to_number(b)?;
(a, b)
} else {
(
self.coerce_primitive(a, hint)?,
self.coerce_primitive(b, hint)?,
)
}
} else {
(a, b)
};
// ToPrimitive may have unwrapped a BigInt wrapper object (`Object(1n)`) or a
// `Symbol.toPrimitive` returning a BigInt; retry the BigInt path now that the
// operands are primitives (`Object(5n) & 3n` → `1n`).
if coerces {
let abig = a
.as_handle()
.and_then(|raw| self.realm.bigint_at(Handle::from_raw(raw)));
let bbig = b
.as_handle()
.and_then(|raw| self.realm.bigint_at(Handle::from_raw(raw)));
if (abig.is_some() || bbig.is_some())
&& let Some(r) = self.bigint_binary(op, abig, bbig, a, b)?
{
return Ok(r);
}
}
// `==`/`!=` between an object/array and a number/string primitive coerces
// the object side (arrays via their join; plain objects via ToPrimitive).
let (a, b) = if matches!(op, BinaryOp::EqEq | BinaryOp::NotEq) {
// True for a real object/array — a heap value that is *not* itself a
// primitive (string / Symbol / BigInt cells are primitives, and
// ToPrimitive on them is a no-op, so they are not the "object" side).
let obj = |this: &Self, v: NanBox| {
v.as_handle().map(Handle::from_raw).is_some_and(|h| {
!this.realm.is_string_handle(h)
&& this.realm.symbol_at(h).is_none()
&& this.realm.bigint_at(h).is_none()
})
};
// True for any primitive against which an object is converted with
// ToPrimitive per the `==` algorithm — a Number, Boolean, String,
// Symbol, or BigInt (so `0n == Object(0n)` and `sym == Object(sym)`
// coerce the object side and then compare as primitives).
let prim = |this: &Self, v: NanBox| {
v.as_number().is_some()
|| matches!(v.unpack(), crate::nanbox::Unpacked::Bool(_))
|| v.as_handle().map(Handle::from_raw).is_some_and(|h| {
this.realm.is_string_handle(h)
|| this.realm.symbol_at(h).is_some()
|| this.realm.bigint_at(h).is_some()
})
};
let (a, b) = if obj(self, a) && prim(self, b) {
(self.coerce_for_eq(a)?, b)
} else if obj(self, b) && prim(self, a) {
(a, self.coerce_for_eq(b)?)
} else {
(a, b)
};
// ToPrimitive of the object side may have produced a BigInt (a BigInt
// wrapper / a `valueOf` returning a BigInt) or a String to compare
// against a BigInt: re-run the dedicated BigInt equality path so
// `bigintN == { toString(){ return "N" } }` applies StringToBigInt
// rather than a mismatched cross-cell `strict_equals`.
let abig = a
.as_handle()
.and_then(|raw| self.realm.bigint_at(Handle::from_raw(raw)));
let bbig = b
.as_handle()
.and_then(|raw| self.realm.bigint_at(Handle::from_raw(raw)));
if (abig.is_some() || bbig.is_some())
&& let Some(r) = self.bigint_binary(op, abig, bbig, a, b)?
{
return Ok(r);
}
(a, b)
} else {
(a, b)
};
// A Symbol cannot be implicitly converted to a number or string, so any
// arithmetic/relational operator on one throws a TypeError.
if coerces {
let is_sym = |this: &Self, v: NanBox| {
v.as_handle()
.map(Handle::from_raw)
.is_some_and(|h| this.realm.symbol_at(h).is_some())
};
if is_sym(self, a) || is_sym(self, b) {
let msg = if matches!(op, BinaryOp::Add) {
"Cannot convert a Symbol value to a string"
} else {
"Cannot convert a Symbol value to a number"
};
let m = self.new_str(msg);
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
}
Ok(match op {
BinaryOp::Add => match self.realm.add_checked(a, b) {
Some(v) => v,
None => {
let m = self.new_str("Invalid string length");
return Err(ExecError::Throw(self.make_error(N_RANGE_ERROR, Some(m))));
}
},
BinaryOp::Sub => self.realm.sub(a, b),
BinaryOp::Mul => self.realm.mul(a, b),
BinaryOp::Div => self.realm.div(a, b),
BinaryOp::Mod => self.realm.rem(a, b),
BinaryOp::Lt => self.realm.less_than(a, b),
BinaryOp::Gt => self.realm.greater_than(a, b),
BinaryOp::LtEq => self.realm.less_equal(a, b),
BinaryOp::GtEq => self.realm.greater_equal(a, b),
BinaryOp::EqEq => NanBox::boolean(self.realm.loose_equals(a, b)),
BinaryOp::NotEq => NanBox::boolean(!self.realm.loose_equals(a, b)),
BinaryOp::EqEqEq => NanBox::boolean(self.realm.strict_equals(a, b)),
BinaryOp::NotEqEq => NanBox::boolean(!self.realm.strict_equals(a, b)),
#[cfg(feature = "std")]
BinaryOp::Exp => self.realm.pow(a, b),
#[cfg(feature = "std")]
BinaryOp::Shl => self.realm.shl(a, b),
#[cfg(feature = "std")]
BinaryOp::Shr => self.realm.shr(a, b),
#[cfg(feature = "std")]
BinaryOp::Ushr => self.realm.ushr(a, b),
#[cfg(feature = "std")]
BinaryOp::BitAnd => self.realm.bit_and(a, b),
#[cfg(feature = "std")]
BinaryOp::BitOr => self.realm.bit_or(a, b),
#[cfg(feature = "std")]
BinaryOp::BitXor => self.realm.bit_xor(a, b),
#[cfg(not(feature = "std"))]
BinaryOp::Exp
| BinaryOp::Shl
| BinaryOp::Shr
| BinaryOp::Ushr
| BinaryOp::BitAnd
| BinaryOp::BitOr
| BinaryOp::BitXor => return Err(ExecError::Unsupported("** / bitwise need std")),
BinaryOp::In => {
// The right operand must be an object (a primitive is a TypeError).
if !self.is_object_value(b) {
let m = self.new_str("Cannot use 'in' operator to search in a non-object");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
let key = self.member_key(a);
// A Deferred Module Namespace (`import defer`) evaluates its target
// on a `[[HasProperty]]` with a String (non-"then") key — directly
// or anywhere in the prototype chain.
#[cfg(all(feature = "module", feature = "std"))]
if let Some(h) = b.as_handle().map(Handle::from_raw) {
self.trigger_deferred_in_chain(h, &key)?;
}
// The full `[[HasProperty]]`: a proxy `has` trap (or forwarding to
// the target — which may itself be a proxy), typed-array integer
// indices, and an ordinary own-or-inherited (accessor-aware) chain
// walk. Delegating keeps the `in` operator consistent with member
// lookup instead of re-deriving (and previously mis-deriving) it.
let present = match b.as_handle().map(Handle::from_raw) {
Some(h) => self.has_property_proxied(h, &key)?,
None => false,
};
NanBox::boolean(present)
}
BinaryOp::Instanceof => NanBox::boolean(self.instance_of(a, b)?),
})
}
/// `obj instanceof Ctor`: true when `obj` was constructed from `Ctor`'s
/// class or one of its subclasses (via the instance's class tag and the
/// `extends` chain).
/// `OrdinaryHasInstance(C, O)` for `Function.prototype[Symbol.hasInstance]`:
/// `false` if `C` is not callable; a bound function defers to its target;
/// otherwise walk `O`'s `[[Prototype]]` chain for `C.prototype`. `instance_of`
/// already implements this (and skips the default `@@hasInstance` to avoid
/// recursion), so delegate with the arguments in instanceof order.
pub(crate) fn ordinary_has_instance(
&mut self,
c: NanBox,
o: NanBox,
) -> Result<bool, ExecError> {
// IsCallable(C): a non-callable `this` reports `false` (no throw). The
// `Get(C,"prototype")` must-be-Object check (a TypeError otherwise) is
// performed inside `instance_of`'s ordinary path.
let Some(ch) = c.as_handle().map(Handle::from_raw) else {
return Ok(false);
};
if !(self.is_callable(ch) || self.realm.class_at(ch).is_some()) {
return Ok(false);
}
self.instance_of(o, c)
}
pub(crate) fn instance_of(&mut self, obj: NanBox, ctor: NanBox) -> Result<bool, ExecError> {
// A custom `[Symbol.hasInstance]` on the right-hand side overrides the
// ordinary prototype/cell-kind check (and applies even to a primitive
// left-hand side, e.g. `4 instanceof Even`). Read via `read_member` so a
// `static [Symbol.hasInstance]` on a class is found.
if let Some(ch) = ctor.as_handle().map(Handle::from_raw) {
let sym = self.well_known_symbol("hasInstance");
let key = self.member_key(sym);
let method = self.read_member(ch, &key)?;
if let Some(mh) = method.as_handle().map(Handle::from_raw)
&& self.is_callable(mh)
// Skip the *default* `Function.prototype[Symbol.hasInstance]`
// (every function inherits it): it just performs OrdinaryHasInstance,
// which is exactly the ordinary path below — calling it here would
// recurse. Only a *user* `[Symbol.hasInstance]` override is honored.
&& self.realm.native_at(mh) != Some(N_FN_HAS_INSTANCE)
{
let result = self.call_with_this(method, ctor, &[obj])?;
return Ok(self.realm.truthy(result));
}
}
// The RHS must be a callable object (without a `[Symbol.hasInstance]`); a
// primitive or a non-constructor object is a TypeError.
let Some(ch) = ctor.as_handle().map(Handle::from_raw) else {
let m = self.new_str("Right-hand side of 'instanceof' is not an object");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
};
// A bound function tests `instanceof` against its target function.
if let Some(target) = self.realm.get_property(ch, BOUND_TARGET) {
return self.instance_of(obj, target);
}
let is_ctor = self.realm.native_at(ch).is_some()
|| self.realm.host_fn_at(ch).is_some()
|| self.realm.function_at(ch).is_some()
|| self.realm.class_at(ch).is_some()
|| self.realm.bound_native_at(ch).is_some()
// Any callable is a valid `instanceof` RHS per OrdinaryHasInstance's
// IsCallable test — notably `%Function.prototype%` itself, which is a
// callable object but not a native/user function (so `[] instanceof
// Function.prototype` reads its `.prototype` and walks, rather than
// wrongly throwing "not callable").
|| self.is_callable(ch)
|| self.current.get("Array").and_then(|v| v.as_handle()) == ctor.as_handle()
|| self.current.get("Object").and_then(|v| v.as_handle()) == ctor.as_handle();
if !is_ctor {
let m = self.new_str("Right-hand side of 'instanceof' is not callable");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// A primitive left-hand side is not an instance of anything. As well as the
// NanBox primitives (number/boolean/null/undefined), the heap-cell
// primitives — String, Symbol, BigInt — are values, not objects, so
// OrdinaryHasInstance returns false for them (e.g. `Symbol() instanceof
// Symbol` is false). A primitive *wrapper* object is a plain `Cell::Object`
// and is unaffected.
let Some(oh) = obj.as_handle().map(Handle::from_raw) else {
return Ok(false);
};
if self.realm.symbol_at(oh).is_some()
|| self.realm.is_string_handle(oh)
|| self.realm.bigint_at(oh).is_some()
{
return Ok(false);
}
// Built-in constructors: check the cell kind directly.
if let Some(id) = self.realm.native_at(ch) {
// A primitive wrapper (`new Number(…)`) matches its constructor.
if let Some(wt) = self.realm.get_property(oh, PRIM_WRAP_TYPE)
&& wt.as_number() == Some(f64::from(id))
{
return Ok(true);
}
// A typed array matches its constructor (kind index == id − base).
if (N_TYPED_ARRAY_BASE..N_TYPED_ARRAY_BASE + TYPED_ARRAY_KINDS.len() as u16)
.contains(&id)
&& self.realm.typed_kind(oh) == Some((id - N_TYPED_ARRAY_BASE) as u8)
{
return Ok(true);
}
// The `WebAssembly.*` boundary objects match by their marker slot.
let wasm_marker = match id {
N_WASM_GLOBAL => Some(WASM_GLOBAL_VALUE),
N_WASM_MEMORY => Some(WASM_MEM_BUFFER),
N_WASM_TABLE => Some(WASM_TABLE_ELEMS),
N_WASM_MODULE => Some(WASM_IS_MODULE),
N_WASM_INSTANCE => Some(WASM_INSTANCE_ID),
_ => None,
};
if let Some(slot) = wasm_marker
&& self.realm.get_property(oh, slot).is_some()
{
return Ok(true);
}
// `ArrayBuffer` / `DataView` match by their marker slot. (A typed array is
// a `Cell::TypedArray`, not an object with `ARRAY_BUFFER_BYTES`, so
// `typedArray instanceof ArrayBuffer` is correctly false.)
if id == N_ARRAY_BUFFER && self.realm.get_property(oh, ARRAY_BUFFER_BYTES).is_some() {
return Ok(true);
}
if id == N_DATA_VIEW && self.realm.get_property(oh, DATA_VIEW_BUF).is_some() {
return Ok(true);
}
// The `Error` family: an error instance now links to its constructor's
// `.prototype`, so OrdinaryHasInstance (the prototype-chain walk) is the
// authoritative check — robust against `name` being reassigned.
if (N_ERROR_BASE..N_ERROR_BASE + ERROR_NAMES.len() as u16).contains(&id) {
if let Some(proto) = self
.realm
.get_property(ch, "prototype")
.and_then(|p| p.as_handle())
.map(Handle::from_raw)
{
let mut cur = oh;
for _ in 0..100_000 {
let next = self.get_proto_of(cur)?;
let Some(p) = next.as_handle().map(Handle::from_raw) else {
break;
};
if p == proto {
return Ok(true);
}
cur = p;
}
}
let want = ERROR_NAMES[(id - N_ERROR_BASE) as usize];
// A user class extending a native error: walk its class chain for
// a native error super (so `customErr instanceof Error` holds even
// when the subclass overrides `this.name`).
if let Some(tag) = self.realm.class_tag(oh) {
let mut cur = Some(tag);
while let Some(cid) = cur {
if let Some(nsup) = self.class_native_super[cid as usize]
&& (N_ERROR_BASE..N_ERROR_BASE + ERROR_NAMES.len() as u16)
.contains(&nsup)
{
let have = ERROR_NAMES[(nsup - N_ERROR_BASE) as usize];
if want == "Error" || want == have {
return Ok(true);
}
}
cur = self
.resolve_super(
self.classes[cid as usize],
&self.class_envs[cid as usize].clone(),
)?
.map(|(p, _)| p);
}
}
// Plain error objects: match by the `name` property.
let obj_name = self
.realm
.get_property(oh, "name")
.map(|v| self.realm.to_display_string(v))
.unwrap_or_default();
if !ERROR_NAMES.contains(&obj_name.as_str()) {
return Ok(false);
}
return Ok(want == "Error" || obj_name == want);
}
match id {
N_REGEXP => return Ok(self.realm.regexp_at(oh).is_some()),
N_MAP | N_SET | N_WEAKMAP | N_WEAKSET => {
return Ok(self.realm.collection_is_set(oh).is_some());
}
N_DATE => return Ok(self.realm.date_at(oh).is_some()),
id if crate::nbexec::temporal::is_temporal_ctor_id(id) => {
// `x instanceof Temporal.<Type>` — a branded instance of that
// exact kind.
return Ok(self.realm.temporal_at(oh).map(|d| d.kind)
== crate::nbexec::temporal::kind_for_ctor_id(id));
}
N_PROMISE => return Ok(self.realm.promise_state(oh).is_some()),
// Every callable (function, native, bound) and every class is a
// `Function`.
N_FUNCTION => {
return Ok(self.is_callable(oh) || self.realm.class_at(oh).is_some());
}
_ => {}
}
// OrdinaryHasInstance fallback for any other built-in constructor (e.g.
// `%Iterator%`, whose instances are recognized only by their prototype
// chain): walk `obj`'s `[[Prototype]]` chain for the ctor's `.prototype`.
if let Some(proto) = self
.realm
.get_property(ch, "prototype")
.and_then(|p| p.as_handle())
.map(Handle::from_raw)
{
let mut cur = oh;
for _ in 0..100_000 {
let next = self.get_proto_of(cur)?;
let Some(p) = next.as_handle().map(Handle::from_raw) else {
return Ok(false);
};
if p == proto {
return Ok(true);
}
cur = p;
}
}
return Ok(false);
}
// `Array`/`Object` are namespace objects (not natives), matched by the
// identity of the global binding.
if self.current.get("Array").and_then(|v| v.as_handle()) == ctor.as_handle() {
return Ok(self.realm.is_array(oh));
}
if self.current.get("Object").and_then(|v| v.as_handle()) == ctor.as_handle() {
// Heap primitives (string/symbol/bigint values) are not objects.
if self.realm.is_string_handle(oh)
|| self.realm.symbol_at(oh).is_some()
|| self.realm.bigint_at(oh).is_some()
{
return Ok(false);
}
// OrdinaryHasInstance: an object is `instanceof Object` iff its
// `[[Prototype]]` chain reaches `Object.prototype`. A null-prototype
// object (module namespace, `Object.create(null)`) is therefore *not*
// an instance of `Object`.
return Ok(self.realm.inherits_object_proto(oh));
}
// Plain function constructors: walk the instance's `[[Prototype]]` chain for
// the constructor's current `.prototype` (so `Object.create(C.prototype)` is an
// instance, and reassigning `C.prototype` is reflected). `Get(C,"prototype")`
// must be an Object — otherwise OrdinaryHasInstance is a TypeError (e.g.
// `C.prototype = undefined`).
// A registered host constructor (`register_constructor`) walks the same
// way: its instances have `[[Prototype]] = hostFn.prototype`.
if self.realm.function_at(ch).is_some() || self.realm.host_fn_at(ch).is_some() {
let proto_val = self.read_member(ch, "prototype")?;
let Some(proto) = proto_val
.as_handle()
.map(Handle::from_raw)
.filter(|_| self.is_object_value(proto_val))
else {
return Err(
self.type_error("Function has non-object prototype in instanceof check")
);
};
// Walk via `get_proto_of` so a proxy's `getPrototypeOf` trap is honored at
// each step (bounded to guard against a trap returning a cycle).
let mut cur = oh;
for _ in 0..100_000 {
let next = self.get_proto_of(cur)?;
let Some(p) = next.as_handle().map(Handle::from_raw) else {
return Ok(false);
};
if p == proto {
return Ok(true);
}
cur = p;
}
return Ok(false);
}
// User class RHS: OrdinaryHasInstance is the authoritative prototype-chain
// walk against the class's `.prototype` — so an instance built with a
// distinct `newTarget` (`Reflect.construct(C, args, D)`, whose instance has
// `D.prototype` on its chain) is `instanceof D` and `instanceof C`. `Get(ch,
// "prototype")` fires a proxy `get` trap; `get_proto_of` honors a
// `getPrototypeOf` trap at each step.
let proto_val = self.read_member(ch, "prototype")?;
let proto = proto_val
.as_handle()
.map(Handle::from_raw)
.filter(|_| self.is_object_value(proto_val));
// A non-class callable RHS (e.g. `%Function.prototype%`) follows
// OrdinaryHasInstance strictly: `Get(C, "prototype")` must be an Object,
// otherwise it is a TypeError (`prototype-getter-with-primitive`).
if self.realm.class_at(ch).is_none() {
let Some(proto) = proto else {
return Err(
self.type_error("Function has non-object prototype in instanceof check")
);
};
let mut cur = oh;
for _ in 0..100_000 {
let next = self.get_proto_of(cur)?;
let Some(p) = next.as_handle().map(Handle::from_raw) else {
return Ok(false);
};
if p == proto {
return Ok(true);
}
cur = p;
}
return Ok(false);
}
if let Some(proto) = proto {
let mut cur = oh;
for _ in 0..100_000 {
let next = self.get_proto_of(cur)?;
let Some(p) = next.as_handle().map(Handle::from_raw) else {
break;
};
if p == proto {
return Ok(true);
}
cur = p;
}
}
// Fallback: the instance's class-tag chain (its class, then each `extends`)
// — robust when an instance's prototype was detached but its class identity
// is still recorded.
let (Some(tag), Some((target_id, _))) = (self.realm.class_tag(oh), self.realm.class_at(ch))
else {
return Ok(false);
};
let mut cur = Some(tag);
while let Some(cid) = cur {
if cid == target_id {
return Ok(true);
}
let class = self.classes[cid as usize];
// Resolve the superclass in the class's own captured scope.
let env = self.class_envs[cid as usize].clone();
cur = self.resolve_super(class, &env)?.map(|(pid, _)| pid);
}
Ok(false)
}
}
/// `StringToBigInt(str)` (ES2020 7.1.14) as a fallible parse: a trimmed, empty
/// (or all-whitespace) string is `0n`; a `0x`/`0o`/`0b` prefix selects the radix;
/// otherwise a decimal (optionally signed) integer literal. Returns `None` — the
/// spec's `undefined` — for any string that is not a valid `StringIntegerLiteral`
/// (e.g. `"0."`, `"1.5"`, `"x"`), which the comparison operators treat as an
/// unequal / undefined-ordering result rather than a throw.
fn string_to_bigint_opt(s: &str) -> Option<crate::bignum::BigInt> {
let t = s.trim();
if t.is_empty() {
return Some(crate::bignum::BigInt::zero());
}
let (radix, body) = match t.get(0..2) {
Some("0x" | "0X") => (16, &t[2..]),
Some("0o" | "0O") => (8, &t[2..]),
Some("0b" | "0B") => (2, &t[2..]),
_ => (10, t),
};
crate::bignum::BigInt::from_str_radix(body, radix)
}
/// Exact comparison of a `BigInt` against an IEEE-754 double, with **no** loss of
/// precision (the mathematical values are compared, so `2n**60n` vs a nearby
/// `f64`, or `Number.MAX_VALUE` vs a 1024-bit BigInt, order correctly). Returns
/// `None` iff `f` is `NaN` (an undefined comparison).
fn bigint_cmp_f64(big: &crate::bignum::BigInt, f: f64) -> Option<core::cmp::Ordering> {
use core::cmp::Ordering;
if f.is_nan() {
return None;
}
if f == f64::INFINITY {
return Some(Ordering::Less);
}
if f == f64::NEG_INFINITY {
return Some(Ordering::Greater);
}
// Decompose `f` into integer `mantissa * 2^exp` (exact for every finite f64).
let bits = f.to_bits();
let sign_neg = bits >> 63 == 1;
let raw_exp = ((bits >> 52) & 0x7ff) as i64;
let frac = bits & 0x000f_ffff_ffff_ffff;
let (mantissa, exp) = if raw_exp == 0 {
(frac, -1074i64) // subnormal (or zero)
} else {
(frac | 0x0010_0000_0000_0000, raw_exp - 1075)
};
if mantissa == 0 {
return Some(big.cmp(&crate::bignum::BigInt::zero())); // f is ±0
}
let m = crate::bignum::BigInt::from_i128(i128::from(mantissa));
let m = if sign_neg { m.neg() } else { m };
let two = crate::bignum::BigInt::from_i128(2);
// Compare `big` against `m * 2^exp` by clearing the power of two exactly.
Some(if exp >= 0 {
big.cmp(&m.mul(&two.pow(exp as u64)))
} else {
big.mul(&two.pow((-exp) as u64)).cmp(&m)
})
}