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
use super::*;
impl<'a> Interp<'a> {
/// Throws a `TypeError` if `handle` is a revoked proxy (used to guard every
/// proxy operation).
pub(crate) fn guard_revoked(&mut self, handle: Handle) -> Result<(), ExecError> {
if self.realm.proxy_revoked(handle) {
let m = self.new_str("Cannot perform operation on a revoked proxy");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
Ok(())
}
/// Resolves a proxy `handler[trap]` (`GetMethod`): `Ok(Some(fn))` when present
/// and callable, `Ok(None)` when absent (`undefined`/`null`, so the operation
/// forwards to the target), and a `TypeError` when present but not callable.
pub(crate) fn proxy_trap(
&mut self,
handler: Handle,
name: &str,
) -> Result<Option<NanBox>, ExecError> {
// GetMethod(handler, name) is a full `[[Get]]` — it invokes an inherited
// getter (a handler whose trap is an accessor) and propagates its throw.
let trap = self.read_member(handler, name)?;
if matches!(trap.unpack(), Unpacked::Undefined | Unpacked::Null) {
return Ok(None);
}
if trap
.as_handle()
.is_some_and(|r| self.is_callable(Handle::from_raw(r)))
{
return Ok(Some(trap));
}
Err(self.type_error(&alloc::format!("proxy '{name}' trap is not a function")))
}
/// `Array.isArray` semantics: follow a chain of proxies to the underlying target and
/// report whether it is a (non-function) array. A revoked proxy in the chain throws.
pub(crate) fn is_array_unwrap_proxy(&mut self, v: NanBox) -> Result<bool, ExecError> {
let mut cur = v;
for _ in 0..1000 {
let Some(raw) = cur.as_handle() else {
return Ok(false);
};
let h = Handle::from_raw(raw);
self.guard_revoked(h)?;
if let Some((target, _)) = self.realm.proxy_at(h) {
cur = NanBox::handle(target.to_raw());
continue;
}
// A genuine Array exotic object: not a VM function. A typed array is a
// distinct `Cell::TypedArray`, so `is_array` already rejects it (per
// `Array.isArray`).
return Ok(self.realm.is_array(h) && !self.realm.is_vm_function(h));
}
Ok(false)
}
/// Applies a property descriptor object (`{ value }` or `{ get, set }`) to
/// `obj[key]` — shared by `Object.defineProperty`/`defineProperties`.
/// Builds the property descriptor object for own property `key` of `obj`
/// (accessor or data), or `None` if `key` is not an own property.
pub(crate) fn build_descriptor(&mut self, obj: Handle, key: &str) -> Option<NanBox> {
// A **mapped `arguments` index** (10.4.4.1 `[[GetOwnProperty]]`): its
// reported `[[Value]]` is the live parameter binding it aliases. Refresh the
// stored own data property from that binding before the generic path reads
// it (the property is always writable while mapped, so the write succeeds).
if let Some((scope, param)) = self.arg_map_binding(obj, key) {
let value = scope.get(¶m).unwrap_or_else(NanBox::undefined);
self.realm.set_property(obj, key, value);
}
// A **String exotic object**'s own index / `length` (StringGetOwnProperty):
// an index `"0".."length-1"` is `{ value: char, writable: false,
// enumerable: true, configurable: false }`; `length` is
// `{ value: len, writable: false, enumerable: false, configurable: false }`.
// A wrapper's named own props fall through to the generic path below.
if let Some(slen) = self.string_index_count(obj) {
let build = |this: &mut Self, value: NanBox, enumerable: bool| {
let d = this.realm.new_object();
this.realm.set_property(d, "value", value);
this.realm
.set_property(d, "writable", NanBox::boolean(false));
this.realm
.set_property(d, "enumerable", NanBox::boolean(enumerable));
this.realm
.set_property(d, "configurable", NanBox::boolean(false));
NanBox::handle(d.to_raw())
};
if key == "length" {
return Some(build(self, NanBox::number(slen as f64), false));
}
if let Ok(i) = key.parse::<usize>()
&& alloc::format!("{i}") == key
&& i < slen
{
let ch = self.read_member(obj, key).ok()?;
return Some(build(self, ch, true));
}
}
// A RegExp instance's `lastIndex` is an own data property
// `{ writable: true, enumerable: false, configurable: false }` stored as a
// compact cell field; synthesize the descriptor when it has not been
// materialized into the aux object.
if key == "lastIndex"
&& self.realm.regexp_at(obj).is_some()
&& !self.realm.regex_aux_last_index_defined(obj)
{
let v = NanBox::number(self.realm.regex_last_index(obj) as f64);
let d = self.realm.new_object();
self.realm.set_property(d, "value", v);
self.realm
.set_property(d, "writable", NanBox::boolean(true));
self.realm
.set_property(d, "enumerable", NanBox::boolean(false));
self.realm
.set_property(d, "configurable", NanBox::boolean(false));
return Some(NanBox::handle(d.to_raw()));
}
// An array index / `length` is a data property (not stored as a named slot):
// an in-range index is writable, enumerable, configurable; `length` is
// writable but non-enumerable and non-configurable.
if let Some(len) = self.realm.array_length(obj) {
// `length`: non-enumerable, non-configurable, writable unless demoted via
// `defineProperty(arr,"length",{writable:false})`. An in-range index:
// writable, enumerable, configurable.
let (value, writable, enumerable, configurable) = if key == "length" {
let writable = !self.realm.array_length_is_readonly(obj);
(Some(NanBox::number(len as f64)), writable, false, false)
} else if let Ok(i) = key.parse::<usize>() {
// An array index may hold a *user-defined accessor* (via
// `Object.defineProperty(arr, i, {get/set})`); that is reported as
// an accessor descriptor by the generic path below, not as a data
// property — fall through when one exists.
if i < len
&& alloc::format!("{i}") == key
&& self.realm.accessor(obj, key).is_none()
// A hole (absent index) is not an own property even within
// `length`; only a present element is a data property.
&& !self.realm.array_hole_at(obj, i)
{
// An in-range index is writable/enumerable/configurable by
// default, but `Object.defineProperty(arr, i, …)` can demote
// any of those attributes (recorded in the element-flag maps);
// reflect the actual recorded flags rather than the defaults.
// A frozen array's elements are non-writable (the write is already
// blocked at runtime; reflect it in the descriptor too).
let writable =
!self.realm.property_is_readonly(obj, key) && !self.realm.is_frozen(obj);
let enumerable = self.realm.property_is_enumerable(obj, key);
let configurable = !self.realm.property_is_non_configurable(obj, key);
(
Some(self.realm.get_element(obj, i)),
writable,
enumerable,
configurable,
)
} else {
(None, false, false, false)
}
} else {
(None, false, false, false)
};
if let Some(v) = value {
let d = self.realm.new_object();
self.realm.set_property(d, "value", v);
self.realm
.set_property(d, "writable", NanBox::boolean(writable));
self.realm
.set_property(d, "enumerable", NanBox::boolean(enumerable));
self.realm
.set_property(d, "configurable", NanBox::boolean(configurable));
return Some(NanBox::handle(d.to_raw()));
}
}
// Every built-in/ordinary function has own `length` and `name` data
// properties with attributes `{ writable: false, enumerable: false,
// configurable: true }` (ECMA-262 — "Built-in Function Objects" and
// CreateBuiltinFunction). When the value is computed rather than stored —
// natives carry no physical `length`; a bound function / class derives
// both `name` and `length` — synthesize the descriptor from the live
// value. A physically-stored own property (a user `defineProperty`, or a
// native whose `name` was installed as a real slot) flows through the
// generic data-property path below, which reads its recorded attributes.
if matches!(key, "length" | "name")
&& !self.realm.has_own(obj, key)
&& (self.is_callable(obj) || self.realm.class_at(obj).is_some())
&& !self.realm.is_array(obj)
{
let v = self.read_member(obj, key).unwrap_or(NanBox::undefined());
let d = self.realm.new_object();
self.realm.set_property(d, "value", v);
self.realm
.set_property(d, "writable", NanBox::boolean(false));
self.realm
.set_property(d, "enumerable", NanBox::boolean(false));
self.realm
.set_property(d, "configurable", NanBox::boolean(true));
return Some(NanBox::handle(d.to_raw()));
}
let configurable = NanBox::boolean(!self.realm.property_is_non_configurable(obj, key));
if let Some((g, s)) = self.realm.accessor(obj, key) {
let enumerable = self.realm.property_is_enumerable(obj, key);
let d = self.realm.new_object();
self.realm.set_property(d, "get", g);
self.realm.set_property(d, "set", s);
self.realm
.set_property(d, "enumerable", NanBox::boolean(enumerable));
self.realm.set_property(d, "configurable", configurable);
Some(NanBox::handle(d.to_raw()))
} else if self.realm.has_own(obj, key) {
let v = self
.realm
.get_property(obj, key)
.unwrap_or(NanBox::undefined());
let writable = !self.realm.property_is_readonly(obj, key);
let enumerable = self.realm.property_is_enumerable(obj, key);
let d = self.realm.new_object();
self.realm.set_property(d, "value", v);
self.realm
.set_property(d, "writable", NanBox::boolean(writable));
self.realm
.set_property(d, "enumerable", NanBox::boolean(enumerable));
self.realm.set_property(d, "configurable", configurable);
Some(NanBox::handle(d.to_raw()))
} else {
None
}
}
/// `Object/Reflect.getOwnPropertyDescriptor(obj, key)` — routing a proxy
/// through its `getOwnPropertyDescriptor` trap (or forwarding to the target),
/// else building the descriptor from the own property.
pub(crate) fn descriptor_of(&mut self, obj: Handle, key: &str) -> Result<NanBox, ExecError> {
// A Deferred Module Namespace (`import defer`) evaluates its target on a
// `[[GetOwnProperty]]` with a String (non-"then") key.
#[cfg(all(feature = "module", feature = "std"))]
self.trigger_deferred_namespace(obj, key)?;
// A module namespace's `[[GetOwnProperty]]` reads the binding value
// (§10.4.6.5 step 4 routes through `[[Get]]`), so a TDZ export throws.
#[cfg(all(feature = "module", feature = "std"))]
self.namespace_binding_tdz(obj, key)?;
if let Some((target, handler)) = self.realm.proxy_at(obj) {
self.guard_revoked(obj)?;
if let Some(trap) = self.proxy_trap(handler, "getOwnPropertyDescriptor")? {
let key_v = self.key_to_value(key);
let handler_box = NanBox::handle(handler.to_raw());
let trap_result = self.call_with_this(
trap,
handler_box,
&[NanBox::handle(target.to_raw()), key_v],
)?;
// The trap result must be an Object or undefined (10.5.5 step 8).
if !matches!(trap_result.unpack(), Unpacked::Undefined)
&& !self.is_object_value(trap_result)
{
return Err(self.type_error(
"proxy 'getOwnPropertyDescriptor' must return an object or undefined",
));
}
// The target's own descriptor (proxy-aware) and extensibility drive
// the 10.5.5 invariants.
let target_desc = self.descriptor_of(target, key)?;
let target_has = !matches!(target_desc.unpack(), Unpacked::Undefined);
let ext = self.is_extensible_of(target)?;
let extensible = self.realm.truthy(ext);
if matches!(trap_result.unpack(), Unpacked::Undefined) {
// Reporting a property as absent has invariants.
if target_has {
if self.target_key_nonconfigurable(target, key) {
return Err(self.type_error(
"proxy 'getOwnPropertyDescriptor' reported a non-configurable property as absent",
));
}
if !extensible {
return Err(self.type_error(
"proxy 'getOwnPropertyDescriptor' reported a property of a non-extensible target as absent",
));
}
}
return Ok(NanBox::undefined());
}
// Present: normalize (ToPropertyDescriptor + CompletePropertyDescriptor)
// and validate against the target.
let rh = trap_result.as_handle().map(Handle::from_raw).unwrap();
let norm = self.normalize_property_descriptor(rh)?;
// Steps 13-14: the reported descriptor must be compatible with the
// target's current property (or, when absent, an extensible target).
if !self.is_compatible_property_descriptor(extensible, norm, target_desc) {
return Err(self.type_error(
"proxy 'getOwnPropertyDescriptor' reported a descriptor incompatible with the target",
));
}
let result_configurable = self
.realm
.get_property(norm, "configurable")
.is_some_and(|v| self.realm.truthy(v));
if !result_configurable {
// A non-configurable reported descriptor is illegal if the target
// has no such key, or the target's key is configurable.
if !target_has || !self.target_key_nonconfigurable(target, key) {
return Err(self.type_error(
"proxy 'getOwnPropertyDescriptor' reported a non-configurable descriptor for a configurable or missing target property",
));
}
// A reported non-writable data descriptor requires the target's
// property to be non-writable too (step 15b — gated on the
// presence of [[Writable]], not [[Value]]).
let result_writable = self
.realm
.get_property(norm, "writable")
.is_some_and(|v| self.realm.truthy(v));
let has_writable = self.realm.has_own(norm, "writable");
if has_writable
&& !result_writable
&& !self.realm.property_is_readonly(target, key)
{
return Err(self.type_error(
"proxy 'getOwnPropertyDescriptor' reported a non-writable descriptor for a writable target property",
));
}
}
// Return the *completed* descriptor object (with default attributes
// filled), as CompletePropertyDescriptor would.
return Ok(self.complete_descriptor(norm));
}
return self.descriptor_of(target, key);
}
Ok(self
.build_descriptor(obj, key)
.unwrap_or(NanBox::undefined()))
}
/// CompletePropertyDescriptor: fills a normalized descriptor's missing fields
/// with their defaults so the returned object has every attribute. A data
/// descriptor gets `value:undefined`/`writable:false`; an accessor gets
/// `get:undefined`/`set:undefined`; both get `enumerable:false`/
/// `configurable:false` when absent.
fn complete_descriptor(&mut self, d: Handle) -> NanBox {
let is_accessor = self.realm.has_own(d, "get") || self.realm.has_own(d, "set");
if is_accessor {
if !self.realm.has_own(d, "get") {
self.realm.set_property(d, "get", NanBox::undefined());
}
if !self.realm.has_own(d, "set") {
self.realm.set_property(d, "set", NanBox::undefined());
}
} else {
if !self.realm.has_own(d, "value") {
self.realm.set_property(d, "value", NanBox::undefined());
}
if !self.realm.has_own(d, "writable") {
self.realm
.set_property(d, "writable", NanBox::boolean(false));
}
}
if !self.realm.has_own(d, "enumerable") {
self.realm
.set_property(d, "enumerable", NanBox::boolean(false));
}
if !self.realm.has_own(d, "configurable") {
self.realm
.set_property(d, "configurable", NanBox::boolean(false));
}
NanBox::handle(d.to_raw())
}
/// `Object/Reflect.isExtensible(obj)` — routing a proxy through its
/// `isExtensible` trap (or forwarding to the target).
pub(crate) fn is_extensible_of(&mut self, obj: Handle) -> Result<NanBox, ExecError> {
if let Some((target, handler)) = self.realm.proxy_at(obj) {
self.guard_revoked(obj)?;
if let Some(trap) = self.proxy_trap(handler, "isExtensible")? {
let handler_box = NanBox::handle(handler.to_raw());
let r =
self.call_with_this(trap, handler_box, &[NanBox::handle(target.to_raw())])?;
let result = self.realm.truthy(r);
// Invariant (10.5.3 step 8): the boolean trap result must equal the
// target's actual `[[IsExtensible]]()` — else a TypeError. The
// target's extensibility is authoritative; a trap cannot lie.
let target_ext = self.is_extensible_of(target)?;
if result != self.realm.truthy(target_ext) {
return Err(self.type_error(
"proxy 'isExtensible' trap result does not match the target's extensibility",
));
}
return Ok(NanBox::boolean(result));
}
// An absent trap forwards to the target's `[[IsExtensible]]` — recursing
// so a target that is itself a proxy runs its own trap.
return self.is_extensible_of(target);
}
Ok(NanBox::boolean(self.realm.is_extensible(obj)))
}
/// `Object/Reflect.setPrototypeOf(obj, proto)` — routing a proxy through its
/// `setPrototypeOf` trap (or forwarding to the target).
/// `Object.getPrototypeOf` / `Reflect.getPrototypeOf`, honoring a proxy's
/// `getPrototypeOf` trap (else forwarding to the target / reading the link).
pub(crate) fn get_proto_of(&mut self, obj: Handle) -> Result<NanBox, ExecError> {
if let Some((target, handler)) = self.realm.proxy_at(obj) {
self.guard_revoked(obj)?;
if let Some(trap) = self.proxy_trap(handler, "getPrototypeOf")? {
let handler_box = NanBox::handle(handler.to_raw());
let r =
self.call_with_this(trap, handler_box, &[NanBox::handle(target.to_raw())])?;
// The trap result must be an Object or null (ECMA-262 step 7).
if !matches!(r.unpack(), Unpacked::Null) && !self.is_object_value(r) {
return Err(
self.type_error("proxy getPrototypeOf trap must return an object or null")
);
}
// Invariant (10.5.1 step 9): a non-extensible target must report its
// actual [[Prototype]].
if !self.realm.is_extensible(target) {
let actual = self
.realm
.object_proto(target)
.map_or(NanBox::null(), |p| NanBox::handle(p.to_raw()));
if !self.realm.strict_equals(r, actual) {
return Err(self.type_error(
"proxy 'getPrototypeOf' returned a different prototype for a non-extensible target",
));
}
}
return Ok(r);
}
// An absent trap forwards to the target's `[[GetPrototypeOf]]` —
// recursing so a target that is itself a proxy runs its own trap.
return self.get_proto_of(target);
}
Ok(self
.realm
.object_proto(obj)
.map_or(NanBox::null(), |p| NanBox::handle(p.to_raw())))
}
/// `OrdinarySetPrototypeOf` (and the proxy `setPrototypeOf` trap). Returns the
/// boolean success: `Object.setPrototypeOf` throws when it is `false`, while
/// `Reflect.setPrototypeOf` surfaces it. A non-extensible object rejects any
/// change to a *different* prototype (setting the same prototype is a no-op
/// that still succeeds).
pub(crate) fn set_proto_of(
&mut self,
obj: Handle,
proto: Option<Handle>,
) -> Result<bool, ExecError> {
if let Some((target, handler)) = self.realm.proxy_at(obj) {
self.guard_revoked(obj)?;
if let Some(trap) = self.proxy_trap(handler, "setPrototypeOf")? {
let proto_box = proto.map_or(NanBox::null(), |p| NanBox::handle(p.to_raw()));
let handler_box = NanBox::handle(handler.to_raw());
let r = self.call_with_this(
trap,
handler_box,
&[NanBox::handle(target.to_raw()), proto_box],
)?;
if !self.realm.truthy(r) {
return Ok(false);
}
// Steps 9-13: `extensibleTarget = ? IsExtensible(target)` — routed
// through the target's (possibly proxy) `[[IsExtensible]]`. If the
// target is extensible, return true WITHOUT consulting its prototype
// (so a throwing `getPrototypeOf` is not observed). Otherwise the new
// prototype must equal `? target.[[GetPrototypeOf]]()`.
let ext = self.is_extensible_of(target)?;
let extensible = self.realm.truthy(ext);
if extensible {
return Ok(true);
}
let target_proto = self.get_proto_of(target)?;
let proto_box = proto.map_or(NanBox::null(), |p| NanBox::handle(p.to_raw()));
if !self.realm.strict_equals(proto_box, target_proto) {
return Err(self.type_error(
"proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
));
}
return Ok(true);
}
return self.set_proto_of(target, proto);
}
// A non-extensible object's prototype is fixed: a change to a different
// [[Prototype]] fails (returns false); setting the current value is a no-op
// that succeeds.
let current = self.realm.object_proto(obj);
if current == proto {
return Ok(true);
}
// `Object.prototype` is an immutable-prototype exotic object (10.4.7.2):
// its `[[SetPrototypeOf]]` succeeds only for the current prototype (handled
// just above) and otherwise fails — so `setPrototypeOf(Object.prototype, x)`
// throws and `Reflect.setPrototypeOf` returns `false`.
if self.realm.default_object_proto() == Some(obj) {
return Ok(false);
}
if !self.realm.is_extensible(obj) {
return Ok(false);
}
// Reject a cycle: walk `proto`'s ordinary [[Prototype]] chain; if it
// reaches `obj`, setting it would form a loop (a chain through an exotic
// proxy stops the static check, matching the spec's early-exit). (10.1.2)
let mut cur = proto;
while let Some(p) = cur {
if p == obj {
return Ok(false);
}
// Stop at a proxy: its [[GetPrototypeOf]] is not an ordinary link, so the
// static cycle scan ends here (the spec allows the assignment).
if self.realm.proxy_at(p).is_some() {
break;
}
cur = self.realm.object_proto(p);
}
self.realm.set_object_proto(obj, proto);
Ok(true)
}
/// `HasProperty(obj, key)` — whether `key` is present on `obj` or anywhere on
/// its prototype chain (own data/accessor property, or an in-range array index /
/// `length`). Mirrors the `in` operator / `Reflect.has`.
pub(crate) fn has_property(&mut self, obj: Handle, key: &str) -> bool {
// Route through the proxy-aware `[[HasProperty]]` (`has_property_proxied`)
// so a **proxy** receiver — or a proxy anywhere on the prototype chain —
// forwards to its `has` trap / target instead of reporting every index as
// absent. This is what makes generic array-like algorithms and iteration
// (`[...proxyOfArray]`, `Array.prototype.forEach.call(proxy, …)`) observe
// the proxied elements rather than skipping them as holes. The proxied
// form's non-proxy path is a superset of the plain chain walk (it also
// honors in-range array indices and accessors), so ordinary objects are
// unaffected. A throwing `has` trap — an extreme edge in the boolean
// callers — collapses to `false`; call sites where a trap throw must
// propagate (the `in` operator, `Reflect.has`) use `has_property_proxied`
// directly.
self.has_property_proxied(obj, key).unwrap_or(false)
}
/// ToPropertyDescriptor (ECMA-262 6.2.6.5): normalizes a user-supplied
/// descriptor object into a fresh plain object whose own data properties are
/// exactly the descriptor fields present (via `HasProperty`, prototype-chain
/// aware), each read with `Get` (invoking inherited getters). Coerces
/// `enumerable`/`configurable`/`writable` to booleans. Throws a `TypeError` if a
/// supplied `get`/`set` is neither callable nor `undefined`.
pub(crate) fn normalize_property_descriptor(
&mut self,
desc: Handle,
) -> Result<Handle, ExecError> {
let out = self.realm.new_object();
for field in ["enumerable", "configurable", "writable"] {
if self.has_property(desc, field) {
let v = self.read_member(desc, field)?;
self.realm
.set_property(out, field, NanBox::boolean(self.realm.truthy(v)));
}
}
if self.has_property(desc, "value") {
let v = self.read_member(desc, "value")?;
self.realm.set_property(out, "value", v);
}
for field in ["get", "set"] {
if self.has_property(desc, field) {
let v = self.read_member(desc, field)?;
let ok = matches!(v.unpack(), Unpacked::Undefined)
|| v.as_handle()
.is_some_and(|r| self.is_callable(Handle::from_raw(r)));
if !ok {
let m = self.new_str("Getter/setter must be a function or undefined");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
self.realm.set_property(out, field, v);
}
}
Ok(out)
}
/// `IsCompatiblePropertyDescriptor(Extensible, Desc, Current)` — the
/// object-less `ValidateAndApplyPropertyDescriptor` (10.1.6.3) used to validate
/// a proxy `defineProperty` / `getOwnPropertyDescriptor` trap result against the
/// target's current own property. `requested` is the *normalized* descriptor
/// (its own fields are exactly the descriptor fields present); `current` is
/// `undefined` (the property is absent on the target) or a fully-completed
/// descriptor object (as `build_descriptor` / `complete_descriptor` produce).
pub(crate) fn is_compatible_property_descriptor(
&mut self,
extensible: bool,
requested: Handle,
current: NanBox,
) -> bool {
let Some(cur) = current
.as_handle()
.map(Handle::from_raw)
.filter(|_| !matches!(current.unpack(), Unpacked::Undefined))
else {
// Current is undefined: a new property is only compatible with an
// extensible target.
return extensible;
};
// Presence of a field on the *requested* descriptor.
let has = |this: &Self, k: &str| this.realm.has_own(requested, k);
let req_truthy = |this: &Self, k: &str| {
this.realm
.get_property(requested, k)
.is_some_and(|v| this.realm.truthy(v))
};
let cur_truthy = |this: &Self, k: &str| {
this.realm
.get_property(cur, k)
.is_some_and(|v| this.realm.truthy(v))
};
let cur_configurable = cur_truthy(self, "configurable");
if cur_configurable {
// A configurable current property accepts any change.
return true;
}
// Non-configurable current property.
if has(self, "configurable") && req_truthy(self, "configurable") {
return false;
}
if has(self, "enumerable")
&& req_truthy(self, "enumerable") != cur_truthy(self, "enumerable")
{
return false;
}
let req_has_value = has(self, "value");
let req_has_writable = has(self, "writable");
let req_has_get = has(self, "get");
let req_has_set = has(self, "set");
let req_is_generic = !req_has_value && !req_has_writable && !req_has_get && !req_has_set;
if req_is_generic {
return true;
}
let req_is_data = req_has_value || req_has_writable;
let cur_is_data = self.realm.has_own(cur, "value") || self.realm.has_own(cur, "writable");
if cur_is_data != req_is_data {
// Changing a non-configurable property between data and accessor.
return false;
}
if cur_is_data {
if !cur_truthy(self, "writable") {
if req_has_writable && req_truthy(self, "writable") {
return false;
}
if req_has_value {
let rv = self
.realm
.get_property(requested, "value")
.unwrap_or(NanBox::undefined());
let cv = self
.realm
.get_property(cur, "value")
.unwrap_or(NanBox::undefined());
if !self.realm.same_value(rv, cv) {
return false;
}
}
}
} else {
// Both accessor descriptors: a non-configurable accessor's get/set are
// fixed.
for field in ["get", "set"] {
if has(self, field) {
let rv = self
.realm
.get_property(requested, field)
.unwrap_or(NanBox::undefined());
let cv = self
.realm
.get_property(cur, field)
.unwrap_or(NanBox::undefined());
if !self.realm.same_value(rv, cv) {
return false;
}
}
}
}
true
}
/// Applies a property descriptor (the shared `Object.defineProperty` / `Reflect
/// .defineProperty` logic). Returns whether `[[DefineOwnProperty]]` succeeded. An
/// *invalid* descriptor always throws; a *failed* definition (new property on a
/// non-extensible object, or a disallowed redefine of a non-configurable one) throws
/// when `reflect` is false (Object.defineProperty) but returns `Ok(false)` when it is
/// true (Reflect.defineProperty, which yields a boolean rather than throwing).
pub(crate) fn apply_descriptor(
&mut self,
obj: Handle,
key: &str,
desc: Handle,
reflect: bool,
) -> Result<bool, ExecError> {
// A module namespace exotic object has its own `[[DefineOwnProperty]]`
// (§10.4.6.11): a String key can only be redefined inertly; a non-export
// or shape-altering request fails (Reflect → false, Object → TypeError).
#[cfg(all(feature = "module", feature = "std"))]
if let Some(ok) = self.namespace_define_own_property(obj, key, desc)? {
if !ok && !reflect {
return Err(self.type_error(&alloc::format!(
"Cannot redefine property '{key}' of a module namespace object"
)));
}
return Ok(ok);
}
// A proxy routes `Object.defineProperty` through its `defineProperty` trap
// (called `trap(target, key, descriptor)`), or forwards to the target.
if let Some((target, handler)) = self.realm.proxy_at(obj) {
self.guard_revoked(obj)?;
if let Some(trap) = self.proxy_trap(handler, "defineProperty")? {
let key_v = 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_v,
NanBox::handle(desc.to_raw()),
],
)?;
// A falsy trap result is a failed [[DefineOwnProperty]]:
// `Object.defineProperty` throws, `Reflect.defineProperty` returns
// false.
if !self.realm.truthy(r) {
if reflect {
return Ok(false);
}
return Err(self.type_error(&alloc::format!(
"proxy 'defineProperty' trap returned falsish for property '{key}'"
)));
}
// Invariants (10.5.6 steps 14-18) on a successful define. Normalize
// the incoming descriptor to inspect what was requested, and read the
// target's current own descriptor (proxy-aware) + extensibility.
let nd = self.normalize_property_descriptor(desc)?;
let setting_nonconf = self.realm.has_own(nd, "configurable")
&& !self
.realm
.get_property(nd, "configurable")
.is_some_and(|v| self.realm.truthy(v));
let target_desc = self.descriptor_of(target, key)?;
let target_has = !matches!(target_desc.unpack(), Unpacked::Undefined);
let ext = self.is_extensible_of(target)?;
let extensible = self.realm.truthy(ext);
if !target_has {
// A new property requires an extensible target; and a
// non-configurable descriptor cannot be added.
if !extensible {
return Err(self.type_error(
"proxy 'defineProperty' added a property to a non-extensible target",
));
}
if setting_nonconf {
return Err(self.type_error(
"proxy 'defineProperty' added a non-configurable property absent on the target",
));
}
} else {
// Redefining an existing target property: the requested
// descriptor must be compatible (IsCompatiblePropertyDescriptor),
// and a non-configurable target property may not be redefined
// non-configurably unless the target's was already
// non-configurable.
if !self.is_compatible_property_descriptor(extensible, nd, target_desc) {
return Err(self.type_error(
"proxy 'defineProperty' trap result is not compatible with the target's property",
));
}
if setting_nonconf && !self.realm.property_is_non_configurable(target, key) {
return Err(self.type_error(
"proxy 'defineProperty' set configurable:false on a configurable target property",
));
}
// Step 18c: a non-configurable, writable *data* property on the
// target may not be redefined non-writable through the trap.
if let Some(tdh) = target_desc.as_handle().map(Handle::from_raw) {
let t_is_data =
self.realm.has_own(tdh, "value") || self.realm.has_own(tdh, "writable");
let t_conf = self
.realm
.get_property(tdh, "configurable")
.is_some_and(|v| self.realm.truthy(v));
let t_writable = self
.realm
.get_property(tdh, "writable")
.is_some_and(|v| self.realm.truthy(v));
let req_has_writable = self.realm.has_own(nd, "writable");
let req_writable = self
.realm
.get_property(nd, "writable")
.is_some_and(|v| self.realm.truthy(v));
if t_is_data && !t_conf && t_writable && req_has_writable && !req_writable {
return Err(self.type_error(
"proxy 'defineProperty' made a non-configurable writable property non-writable",
));
}
}
}
return Ok(true);
}
return self.apply_descriptor(target, key, desc, reflect);
}
// ToPropertyDescriptor (ECMA-262 6.2.6.5): a descriptor's attributes are
// read by `HasProperty` (which walks the prototype chain) and `Get` (which
// invokes inherited getters), not by own-property inspection. Normalize the
// user descriptor into a fresh plain object whose own data properties are
// exactly the fields the descriptor *has* (anywhere on its chain), each set
// to its `Get` value. The remainder of this routine then inspects that
// normalized object with own-only `has_own`/`get_property`.
let desc = self.normalize_property_descriptor(desc)?;
// A descriptor may not mix accessor fields (`get`/`set`) with data fields
// (`value`/`writable`) — that is an invalid descriptor (ToPropertyDescriptor).
let has_accessor_field = self.realm.has_own(desc, "get") || self.realm.has_own(desc, "set");
let has_data_field =
self.realm.has_own(desc, "value") || self.realm.has_own(desc, "writable");
if has_accessor_field && has_data_field {
let m = self.new_str(
"Invalid property descriptor. Cannot both specify accessors and a value or writable attribute",
);
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// Mapped `arguments` exotic `[[DefineOwnProperty]]` (10.4.4.2): capture the
// aliased `(scope, parameter name)` up front (`None` for any other object /
// an already-broken index). Step 3: when the descriptor demotes the index to
// a non-writable data property *without* an explicit value, substitute the
// current binding value into the (freshly normalized) descriptor so it is
// preserved after the mapping breaks. The post-store mapping update (accessor
// / value / non-writable) runs at the end, once the define has succeeded.
let arg_binding = self.arg_map_binding(obj, key);
if let Some((scope, param)) = &arg_binding
&& has_data_field
&& !self.realm.has_own(desc, "value")
&& self.realm.has_own(desc, "writable")
&& !self
.realm
.get_property(desc, "writable")
.is_some_and(|v| self.realm.truthy(v))
{
let cur = scope.get(param).unwrap_or_else(NanBox::undefined);
self.realm.set_property(desc, "value", cur);
}
// Integer-indexed exotic `[[DefineOwnProperty]]` (ECMA-262 10.4.5.3): when
// `obj` is a typed array and `key` is a canonical numeric index, the only
// legal define is a writable, enumerable, configurable data property at a
// valid index — anything else (an invalid index, a non-configurable /
// non-enumerable / non-writable field, or an accessor) fails. A success
// stores the (coerced) value through the element; a failure throws for
// `Object.defineProperty` and returns `false` for `Reflect.defineProperty`.
if self.realm.typed_kind(obj).is_some()
&& let Some(n) = canonical_numeric_index(key)
{
let fail = |this: &mut Self| -> Result<bool, ExecError> {
if reflect {
return Ok(false);
}
let m = this.new_str(&alloc::format!(
"Cannot define property {key} on a TypedArray with an invalid descriptor or index"
));
Err(ExecError::Throw(this.make_error(N_TYPE_ERROR, Some(m))))
};
// IsValidIntegerIndex: an in-bounds non-negative integer, `-0` excluded,
// backing buffer attached.
let is_neg_zero = n == 0.0 && n.is_sign_negative();
let detached = self.typed_array_detached(obj);
let valid = !detached
&& !is_neg_zero
&& n == (n as i64) as f64
&& n >= 0.0
&& self
.realm
.typed_len(obj)
.is_some_and(|len| (n as usize) < len);
if !valid {
return fail(self);
}
// An accessor descriptor, or a data field that is non-configurable /
// non-enumerable / non-writable, is rejected.
let bad_bool = |this: &Self, field: &str| -> bool {
this.realm.has_own(desc, field)
&& !this
.realm
.get_property(desc, field)
.is_some_and(|v| this.realm.truthy(v))
};
if has_accessor_field
|| bad_bool(self, "configurable")
|| bad_bool(self, "enumerable")
|| bad_bool(self, "writable")
{
return fail(self);
}
// Store the value (if the descriptor carries one), coercing to the view's
// element type (a Number into a BigInt view throws here).
if self.realm.has_own(desc, "value") {
let v = self
.realm
.get_property(desc, "value")
.unwrap_or(NanBox::undefined());
let coerced = if self.realm.typed_kind(obj).is_some_and(is_bigint_kind) {
self.coerce_typed_array_write(obj, v)?
} else {
self.coerce_to_number(v)?
};
self.realm.set_element(obj, n as usize, coerced);
}
return Ok(true);
}
// String exotic object `[[DefineOwnProperty]]` (ECMA-262 10.4.3.4): an own
// index (`"0".."length-1"`) or `length` is a synthesized data property that
// is non-writable and non-configurable. StringGetOwnProperty yields it, and
// the define must be `IsCompatiblePropertyDescriptor` against it — so only a
// same-value, same-attributes redefine succeeds; any change of value, kind,
// writability, enumerability, or configurability fails (a TypeError for
// `Object.defineProperty`, `false` for `Reflect.defineProperty`). A wrapper's
// *named* own property is ordinary and falls through to the generic path.
if let Some(slen) = self.string_index_count(obj) {
let is_index = key
.parse::<usize>()
.ok()
.filter(|&i| alloc::format!("{i}") == key && i < slen)
.is_some();
if key == "length" || is_index {
let cur_value = if key == "length" {
NanBox::number(slen as f64)
} else {
self.read_member(obj, key)?
};
// An index is enumerable; `length` is not.
let cur_enum = is_index;
let truthy_field = |this: &Self, field: &str| -> bool {
this.realm.has_own(desc, field)
&& this
.realm
.get_property(desc, field)
.is_some_and(|v| this.realm.truthy(v))
};
// IsCompatiblePropertyDescriptor for a non-configurable, non-writable
// data property: reject making it configurable/writable, toggling
// enumerable, switching to an accessor, or changing the value.
let value_changed = self.realm.has_own(desc, "value") && {
let nv = self
.realm
.get_property(desc, "value")
.unwrap_or(NanBox::undefined());
!self.realm.same_value(nv, cur_value)
};
let incompatible = truthy_field(self, "configurable")
|| truthy_field(self, "writable")
|| has_accessor_field
|| (self.realm.has_own(desc, "enumerable")
&& truthy_field(self, "enumerable") != cur_enum)
|| value_changed;
if incompatible {
if reflect {
return Ok(false);
}
let m = self.new_str(&alloc::format!(
"Cannot redefine property '{key}' of a String exotic object"
));
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
return Ok(true);
}
}
// An array's `length` is an exotic own data property governed by
// ArraySetLength (ECMA-262 10.4.3.1): it is `{enumerable:false,
// configurable:false}`, writable by default, and its "value" resizes the
// array. Route it through a dedicated validator rather than the generic
// ordinary-object path (which would store a shadowing aux slot).
if self.realm.is_array(obj) && key == "length" {
return self.apply_array_length_descriptor(obj, desc, reflect);
}
// A RegExp's `lastIndex` is a synthesized own data property
// ({ writable:true, enumerable:false, configurable:false }) backed by the
// cell's compact field. Before a `[[DefineOwnProperty]]`, materialize it as
// a real aux property carrying its *actual* attributes, so the generic path
// below merges a partial descriptor against them — a `{ value }`-only
// redefine keeps `writable:true` (rather than falling to the new-property
// `writable:false` default). `exec`'s `set_last_index_value` keeps the aux
// slot in sync with the cell once it exists.
if key == "lastIndex"
&& self.realm.regexp_at(obj).is_some()
&& !self.realm.regex_aux_last_index_defined(obj)
{
let cur = NanBox::number(self.realm.regex_last_index(obj) as f64);
self.realm.set_property(obj, "lastIndex", cur);
self.realm.mark_hidden(obj, "lastIndex");
self.realm.set_non_configurable_property(obj, "lastIndex");
// `writable` intentionally left true (the synthesized default).
}
// ArrayDefineOwnProperty (10.4.2.1): defining an index `>= length` when the
// array's `length` is non-writable fails — a new element cannot grow a
// frozen length. (An in-range index, or a redefine of an existing one, is
// governed by the ordinary rules below.)
if self.realm.is_array(obj)
&& self.realm.array_length_is_readonly(obj)
&& let Ok(i) = key.parse::<usize>()
&& alloc::format!("{i}") == key
&& i >= self.realm.array_length(obj).unwrap_or(0)
{
if reflect {
return Ok(false);
}
let m = self.new_str("Cannot add array index past a non-writable length");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// A callable's `length` and `name` are own properties per spec
// (`{writable:false, enumerable:false, configurable:true}`), but they are
// synthesized lazily and may not be materialized in the cell's aux object
// yet — so `has_own` would miss them. Treat them as existing own data
// properties with their intrinsic attributes so a redefine merges over the
// spec defaults (and the second redefine sees them as configurable).
let is_intrinsic_callable_prop = (key == "length" || key == "name")
&& self.realm.is_callable_cell(obj)
&& !self.realm.has_own(obj, key)
&& self.realm.accessor(obj, key).is_none();
let is_own = self.realm.has_own(obj, key)
|| self.realm.accessor(obj, key).is_some()
|| is_intrinsic_callable_prop;
// Adding a *new* property to a non-extensible object fails.
if !is_own && !self.realm.is_extensible(obj) {
if reflect {
return Ok(false);
}
let m = self.new_str("Cannot define property: object is not extensible");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// The *shape* of the incoming descriptor (ToPropertyDescriptor semantics):
// a field counts only when it is an OWN field of the descriptor object. A
// descriptor with neither accessor (`get`/`set`) nor data (`value`/
// `writable`) field is "generic" and, on a redefine, preserves the current
// property's kind.
let desc_is_accessor = has_accessor_field;
let desc_is_data = has_data_field;
// The existing property's kind and attributes (only meaningful when
// `is_own`). An intrinsic callable `length`/`name` is a data property.
let existing_is_accessor = self.realm.accessor(obj, key).is_some();
// The resulting property kind: an accessor descriptor makes it an accessor,
// a data descriptor makes it data, and a generic redefine keeps the current
// kind (a generic *new* property defaults to a data property).
let result_is_accessor = if desc_is_accessor {
true
} else if desc_is_data {
false
} else {
is_own && existing_is_accessor
};
// ValidateAndApplyPropertyDescriptor — a non-configurable property allows
// only a restricted set of changes; anything else is a rejection (a
// TypeError for `Object.defineProperty`, `false` for `Reflect`).
if is_own && self.realm.property_is_non_configurable(obj, key) {
let writable = !self.realm.property_is_readonly(obj, key);
let allowed = self.redefine_allowed_on_non_configurable(
obj,
key,
desc,
existing_is_accessor,
result_is_accessor,
writable,
)?;
if !allowed {
if reflect {
return Ok(false);
}
let m = self.new_str("Cannot redefine non-configurable property");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
}
// Per `ValidateAndApplyPropertyDescriptor`, redefining an existing own
// property MERGES over its current attributes: an attribute field the
// descriptor omits keeps the property's existing value. For a *new*
// property each omitted attribute takes its ECMAScript default (`false`).
// Resolve each effective attribute up front (explicit field, else the
// preserved existing value on a redefine, else the default `false`).
let resolve = |this: &Self, field: &str, existing: bool| -> bool {
match this.realm.get_property(desc, field) {
Some(v) if this.realm.has_own(desc, field) => this.realm.truthy(v),
_ if is_own => existing,
_ => false,
}
};
let want_enum = resolve(
self,
"enumerable",
self.realm.property_is_enumerable(obj, key),
);
let want_configurable = resolve(
self,
"configurable",
is_own && !self.realm.property_is_non_configurable(obj, key),
);
if result_is_accessor {
// Merge omitted accessor fields with the existing accessor's get/set so
// a redefine that touches only enumerable/configurable keeps the
// current getter and setter. When converting from a data property the
// omitted side defaults to `undefined`.
let (cur_get, cur_set) = if existing_is_accessor {
self.realm
.accessor(obj, key)
.unwrap_or((NanBox::undefined(), NanBox::undefined()))
} else {
(NanBox::undefined(), NanBox::undefined())
};
let getter = if self.realm.has_own(desc, "get") {
self.realm
.get_property(desc, "get")
.unwrap_or(NanBox::undefined())
} else {
cur_get
};
let setter = if self.realm.has_own(desc, "set") {
self.realm
.get_property(desc, "set")
.unwrap_or(NanBox::undefined())
} else {
cur_set
};
// Converting a data property to an accessor: drop the stored value and
// its writable mark. `define_accessor` only overwrites get/set when the
// supplied value is defined, so seed a clean accessor first to allow a
// getter/setter to be reset to `undefined`.
//
// Begin unified own-key order tracking *before* the data slot is deleted:
// deleting drops the key from the shape, so if this is an existing data
// property being redefined as an accessor, seeding now records its real
// insertion position — otherwise `define_accessor` would seed from the
// post-deletion key set and append the key at the end, corrupting
// `[[OwnPropertyKeys]]` order.
self.realm.ensure_key_order(obj);
self.realm.clear_accessor(obj, key);
self.realm.delete_data_slot(obj, key);
self.realm.clear_readonly_property(obj, key);
// An accessor at an array index (ArrayDefineOwnProperty, 10.4.2.1):
// the dense element store can only hold data, so punch a hole at the
// index (the accessor takes precedence on read) and grow `length` to
// index+1 when the index is at/beyond the current length.
if self.realm.is_array(obj)
&& let Ok(i) = key.parse::<usize>()
&& alloc::format!("{i}") == key
{
self.realm.array_index_to_hole(obj, i);
}
self.realm.define_accessor(obj, key, getter, setter);
// Enumerable: explicit field, else preserved on redefine, else default false.
if want_enum {
self.realm.clear_hidden_property(obj, key);
} else {
self.realm.mark_hidden(obj, key);
}
} else {
// An intrinsic callable `length`/`name` is non-writable by default; its
// lazy form isn't yet flagged readonly in the aux object, so seed the
// spec value explicitly.
let existing_writable = is_own
&& !is_intrinsic_callable_prop
&& !existing_is_accessor
&& !self.realm.property_is_readonly(obj, key);
let want_writable = resolve(self, "writable", existing_writable);
// Redefining as a data property removes any prior accessor.
self.realm.clear_accessor(obj, key);
// A `defineProperty` redefines attributes from scratch: drop any prior
// non-writable mark so the new value takes effect, then set it.
self.realm.clear_readonly_property(obj, key);
// Only overwrite the stored value when the descriptor supplies one (a
// bare `{writable:...}` redefine keeps the existing value); a fresh
// define with no `value` field, or a conversion from an accessor, uses
// `undefined`.
// For a numeric index on an array, the value lives in the dense
// element store (so `arr[i]` reads it and `length` grows), not the aux
// named-property map. `set_element` extends the array as needed.
// Only a *canonical* array index (`0 ..= 2**32 - 2`) is an element; a
// larger numeric key (`"4294967295"`+) is an ordinary named property and
// does not grow `length`.
let array_index = if self.realm.is_array(obj) {
key.parse::<u32>()
.ok()
.filter(|&i| i != u32::MAX && alloc::format!("{i}") == key)
.map(|i| i as usize)
} else {
None
};
// Store a value at an array index, falling back to sparse aux storage
// (and a logical `length` bump) when the index is beyond the dense cap
// — the backing `Vec` cannot hold billions of slots, but the property
// must still exist and `length` become `i + 1`.
let store_array_index = |this: &mut Self, i: usize, value: NanBox| {
if !this.realm.set_element(obj, i, value) && i >= this.realm.limits.max_array_len {
this.realm.force_set_property(obj, key, value);
let target_len = i + 1;
if this.realm.array_length(obj).unwrap_or(0) < target_len {
this.realm.set_array_length(obj, target_len);
}
}
};
if self.realm.has_own(desc, "value") {
let value = self
.realm
.get_property(desc, "value")
.unwrap_or(NanBox::undefined());
if let Some(i) = array_index {
store_array_index(self, i, value);
} else {
// `[[DefineOwnProperty]]` validates extensibility itself, so the
// store must bypass the ordinary non-extensible / frozen guard
// (e.g. converting an accessor to a data property on a sealed
// object, or changing a configurable property's value after
// `preventExtensions`).
self.realm.force_set_property(obj, key, value);
}
} else if !is_own || existing_is_accessor {
if let Some(i) = array_index {
store_array_index(self, i, NanBox::undefined());
} else {
self.realm.force_set_property(obj, key, NanBox::undefined());
}
}
// Writable: explicit field, else preserved on redefine, else default false.
if !want_writable {
self.realm.set_readonly_property(obj, key);
}
// Enumerable: explicit field, else preserved on redefine, else default false.
if want_enum {
self.realm.clear_hidden_property(obj, key);
} else {
self.realm.mark_hidden(obj, key);
}
}
// Configurable: explicit field, else preserved on redefine, else default false.
if want_configurable {
self.realm.clear_non_configurable_property(obj, key);
} else {
self.realm.set_non_configurable_property(obj, key);
}
// Mapped `arguments` `[[DefineOwnProperty]]` step 6: after a successful
// define, keep the parameter binding in sync and/or break the mapping.
if let Some((scope, param)) = &arg_binding {
if desc_is_accessor {
// Redefining the index as an accessor severs the alias.
self.arg_map_break(obj, key);
} else {
// A supplied value flows through to the aliased binding (so
// `defineProperty(arguments, i, {value})` updates the parameter).
if self.realm.has_own(desc, "value") {
let v = self
.realm
.get_property(desc, "value")
.unwrap_or(NanBox::undefined());
scope.set(param, v);
}
// Demoting the index to non-writable severs the alias.
if self.realm.has_own(desc, "writable")
&& !self
.realm
.get_property(desc, "writable")
.is_some_and(|v| self.realm.truthy(v))
{
self.arg_map_break(obj, key);
}
}
}
Ok(true)
}
/// `Object.defineProperty(arr, "length", desc)` — the ArraySetLength exotic
/// (ECMA-262 10.4.3.1). The array's `length` is `{enumerable:false,
/// configurable:false}`, writable unless explicitly demoted. A length descriptor
/// may change the value (resizing the array) and may turn writability off, but
/// once non-writable it cannot be made writable again nor have its value changed.
pub(crate) fn apply_array_length_descriptor(
&mut self,
obj: Handle,
desc: Handle,
reflect: bool,
) -> Result<bool, ExecError> {
let reject = |this: &mut Self| -> Result<bool, ExecError> {
if reflect {
return Ok(false);
}
let m = this.new_str("Cannot redefine property: length");
Err(ExecError::Throw(this.make_error(N_TYPE_ERROR, Some(m))))
};
// ArraySetLength: the new `length` value is coerced FIRST (ToUint32 +
// ToNumber via ToPrimitive — running a user `valueOf`/`toString`, which may
// throw or yield a non-integral value → RangeError), *before* any
// descriptor-attribute rejection. (10.4.3.1 steps 2–4: the RangeError on
// an invalid value precedes the configurable/enumerable/writable checks,
// so `defineProperty(arr,"length",{value:-1,configurable:true})` is a
// RangeError, not a TypeError.)
let new_len = if self.realm.has_own(desc, "value") {
let value = self
.realm
.get_property(desc, "value")
.unwrap_or(NanBox::undefined());
// ToUint32 / ToNumber must agree (a fractional, NaN, or out-of-range
// length is a RangeError). `coerce_to_number` runs ToPrimitive (a
// throwing `toString`/`valueOf` propagates; one returning a non-
// primitive is itself a TypeError).
let prim = self.coerce_to_number(value)?;
let num = self.realm.to_number(prim);
let len = num as u32;
if !(num.is_finite() && f64::from(len) == num) {
let m = self.new_str("Invalid array length");
return Err(ExecError::Throw(self.make_error(N_RANGE_ERROR, Some(m))));
}
Some(len as usize)
} else {
None
};
// `length` is non-configurable and non-enumerable: reject any descriptor
// that asks to make it configurable or enumerable.
if self.realm.has_own(desc, "configurable")
&& self
.realm
.get_property(desc, "configurable")
.is_some_and(|v| self.realm.truthy(v))
{
return reject(self);
}
if self.realm.has_own(desc, "enumerable")
&& self
.realm
.get_property(desc, "enumerable")
.is_some_and(|v| self.realm.truthy(v))
{
return reject(self);
}
// A `length` descriptor is a data descriptor; accessor fields are invalid.
if self.realm.has_own(desc, "get") || self.realm.has_own(desc, "set") {
return reject(self);
}
let cur_writable = !self.realm.array_length_is_readonly(obj);
let new_writable = if self.realm.has_own(desc, "writable") {
self.realm
.get_property(desc, "writable")
.is_some_and(|v| self.realm.truthy(v))
} else {
cur_writable
};
// A non-writable `length` cannot be made writable again.
if !cur_writable && new_writable {
return reject(self);
}
if let Some(len) = new_len {
let cur_len = self.realm.array_length(obj).unwrap_or(0);
// A non-writable `length` rejects a value change (a same-value "change"
// is allowed).
if !cur_writable && len != cur_len {
return reject(self);
}
// ArraySetLength: a shrink that hits a non-configurable index stops there
// and fails (the length is left one above it). Apply the writability
// demotion *before* reporting the failure, per 10.4.3.1 steps 17–19.
let all_deleted = self.set_array_length_checked(obj, len)?;
if !all_deleted {
self.realm.set_array_length_readonly(obj, !new_writable);
return reject(self);
}
}
// Apply the (possibly lowered) writability last.
self.realm.set_array_length_readonly(obj, !new_writable);
Ok(true)
}
/// ValidateAndApplyPropertyDescriptor's non-configurable guard: whether
/// redefining the existing **non-configurable** own property `key` of `obj` with
/// `desc` is permitted. A non-configurable property forbids: becoming
/// configurable, an enumerable toggle, a data<->accessor switch, an accessor
/// get/set change, making a non-writable data property writable, and changing a
/// non-writable data property's value (a same-value redefine is always allowed).
pub(crate) fn redefine_allowed_on_non_configurable(
&mut self,
obj: Handle,
key: &str,
desc: Handle,
existing_is_accessor: bool,
result_is_accessor: bool,
writable: bool,
) -> Result<bool, ExecError> {
// Becoming configurable is never allowed.
if self.realm.has_own(desc, "configurable")
&& self
.realm
.get_property(desc, "configurable")
.is_some_and(|v| self.realm.truthy(v))
{
return Ok(false);
}
// An enumerable toggle is not allowed.
if self.realm.has_own(desc, "enumerable")
&& self
.realm
.get_property(desc, "enumerable")
.is_some_and(|v| self.realm.truthy(v))
!= self.realm.property_is_enumerable(obj, key)
{
return Ok(false);
}
// Switching kind (data <-> accessor) is not allowed.
if result_is_accessor != existing_is_accessor {
return Ok(false);
}
if existing_is_accessor {
// An accessor's get/set cannot change.
let (cur_get, cur_set) = self
.realm
.accessor(obj, key)
.unwrap_or((NanBox::undefined(), NanBox::undefined()));
if self.realm.has_own(desc, "get") {
let g = self
.realm
.get_property(desc, "get")
.unwrap_or(NanBox::undefined());
if !self.realm.same_value(g, cur_get) {
return Ok(false);
}
}
if self.realm.has_own(desc, "set") {
let s = self
.realm
.get_property(desc, "set")
.unwrap_or(NanBox::undefined());
if !self.realm.same_value(s, cur_set) {
return Ok(false);
}
}
return Ok(true);
}
// A writable data property may change its value and writability freely.
if writable {
return Ok(true);
}
// A non-writable data property: cannot be made writable, and cannot change
// its value.
if self.realm.has_own(desc, "writable")
&& self
.realm
.get_property(desc, "writable")
.is_some_and(|v| self.realm.truthy(v))
{
return Ok(false);
}
if self.realm.has_own(desc, "value") {
let new_val = self
.realm
.get_property(desc, "value")
.unwrap_or(NanBox::undefined());
// An array index's value lives in the dense element store, not a named
// slot, so read it with `get_element` for a same-value comparison.
let cur_val = if self.realm.is_array(obj)
&& let Ok(i) = key.parse::<usize>()
&& alloc::format!("{i}") == key
{
self.realm.get_element(obj, i)
} else {
self.realm
.get_property(obj, key)
.unwrap_or(NanBox::undefined())
};
if !self.realm.same_value(new_val, cur_val) {
return Ok(false);
}
}
Ok(true)
}
/// `structuredClone(v)`: a deep copy. Primitives and immutable heap values
/// (strings, BigInts) are shared; Dates, Maps, Sets, arrays, and plain
/// objects are recursively cloned. `seen` maps each visited source handle to
/// its clone so cyclic and shared references are preserved. Functions and
/// symbols are not cloneable (a TypeError, like `DataCloneError`).
pub(crate) fn structured_clone(
&mut self,
v: NanBox,
seen: &mut Vec<(u64, NanBox)>,
) -> Result<NanBox, ExecError> {
let Some(raw) = v.as_handle() else {
return Ok(v); // a primitive
};
let h = Handle::from_raw(raw);
// Immutable heap values are shared, not copied.
if self.realm.is_string_handle(h) || self.realm.bigint_at(h).is_some() {
return Ok(v);
}
if self.is_callable(h) || self.realm.symbol_at(h).is_some() {
let m = self.new_str("value could not be cloned");
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
// A previously-cloned handle (cycle or shared reference).
if let Some((_, c)) = seen.iter().find(|(r, _)| *r == raw) {
return Ok(*c);
}
// Bound the recursion so a deep acyclic structure throws rather than
// overflowing the host stack.
if seen.len() >= self.realm.limits.max_display_depth {
let m = self.new_str("Maximum call stack size exceeded");
return Err(ExecError::Throw(self.make_error(N_RANGE_ERROR, Some(m))));
}
if let Some(ms) = self.realm.date_at(h) {
return Ok(NanBox::handle(self.realm.new_date(ms).to_raw()));
}
if let Some(is_set) = self.realm.collection_is_set(h) {
let coll = self.realm.new_collection(is_set);
let cbox = NanBox::handle(coll.to_raw());
seen.push((raw, cbox));
for (k, val) in self.realm.collection_entries(h).unwrap_or_default() {
let ck = self.structured_clone(k, seen)?;
let cv = self.structured_clone(val, seen)?;
self.realm.collection_set(coll, ck, cv);
}
return Ok(cbox);
}
if let Some(elems) = self.realm.array_elements(h).map(<[_]>::to_vec) {
let arr = self.realm.new_array(Vec::new());
let abox = NanBox::handle(arr.to_raw());
seen.push((raw, abox));
for e in elems {
let c = self.structured_clone(e, seen)?;
self.realm.array_push(arr, c);
}
return Ok(abox);
}
// A plain object: clone own enumerable string-keyed properties.
let obj = self.realm.new_object();
let obox = NanBox::handle(obj.to_raw());
seen.push((raw, obox));
for k in self.realm.object_keys(h).unwrap_or_default() {
if let Some(pv) = self.realm.get_property(h, &k) {
let c = self.structured_clone(pv, seen)?;
self.realm.set_property(obj, &k, c);
}
}
Ok(obox)
}
/// CanBeHeldWeakly(v) (ECMA-262): true for an object or a *non-registered*
/// symbol. A symbol obtained from `Symbol.for` (present in the global symbol
/// registry) cannot be held weakly. Primitives (string/number/bigint/bool/
/// null/undefined) cannot either.
pub(crate) fn can_be_held_weakly(&self, v: NanBox) -> bool {
let Some(h) = v.as_handle().map(Handle::from_raw) else {
return false;
};
// A symbol: weakly holdable unless it lives in the global registry.
if self.realm.symbol_at(h).is_some() {
return !self
.symbol_registry
.values()
.any(|s| self.realm.same_value(*s, v));
}
// Any other heap value that is not a non-object primitive (string /
// bigint are heap cells but not weakly holdable).
!self.realm.is_string_handle(h) && self.realm.bigint_at(h).is_none()
}
/// `thisSymbolValue(this)` (ECMA-262 20.4.3): if `this` is a Symbol
/// primitive, return it; if it is a Symbol wrapper object (a [`PRIM_WRAP`]
/// holding a symbol), return the boxed symbol; otherwise a TypeError. Used by
/// the brand-checking `Symbol.prototype` methods. (Here `Object(sym)` returns
/// the primitive itself, so the wrapper branch is a belt-and-braces fallback.)
pub(crate) fn this_symbol_value(&mut self) -> Result<NanBox, ExecError> {
let this = self.this_val;
if let Some(h) = this.as_handle().map(Handle::from_raw) {
if self.realm.symbol_at(h).is_some() {
return Ok(this);
}
if let Some(prim) = self.realm.get_property(h, PRIM_WRAP)
&& prim
.as_handle()
.map(Handle::from_raw)
.is_some_and(|ph| self.realm.symbol_at(ph).is_some())
{
return Ok(prim);
}
}
Err(self.type_error("Symbol.prototype method called on a non-symbol value"))
}
/// `CanonicalizeKeyedCollectionKey(key)` (ECMA-262): `-0𝔽` becomes `+0𝔽`;
/// every other value is returned unchanged. Used by the upsert proposal's
/// `getOrInsert`/`getOrInsertComputed` so the canonical key is both stored and
/// handed to the callback. (`-0.0 == 0.0` in Rust, and `NanBox::number(0.0)`
/// produces positive zero, so this normalizes the sign.)
#[must_use]
pub(crate) fn canonicalize_collection_key(key: NanBox) -> NanBox {
if key.as_number() == Some(0.0) {
NanBox::number(0.0)
} else {
key
}
}
/// The key validation shared by `getOrInsert`/`getOrInsertComputed`. For a
/// WeakMap, `CanBeHeldWeakly(key)` must hold — an object or a non-registered
/// symbol — else a TypeError (this correctly rejects registered symbols and
/// every primitive). For a non-weak Map there is no constraint.
pub(crate) fn guard_get_or_insert_key(
&mut self,
coll: Handle,
key: NanBox,
) -> Result<(), ExecError> {
if !self.realm.collection_is_weak(coll) || self.can_be_held_weakly(key) {
return Ok(());
}
let m = self.new_str("Invalid value used as weak collection key");
Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))))
}
pub(crate) fn guard_weak_key(&mut self, coll: Handle, key: NanBox) -> Result<(), ExecError> {
if !self.realm.collection_is_weak(coll) {
return Ok(());
}
// CanBeHeldWeakly(key): an object or a *non-registered* symbol. A symbol
// from `Symbol.for` (in the global registry) cannot be held weakly.
if self.can_be_held_weakly(key) {
return Ok(());
}
let m = self.new_str("Invalid value used as weak collection key");
Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))))
}
pub(crate) fn make_primitive_wrapper(&mut self, prim: NanBox, ctor_id: u16) -> NanBox {
let obj = self.realm.new_object();
// The wrapper's `[[Prototype]]` is the corresponding constructor's
// `.prototype` (so `Object.getPrototypeOf(new Number(1)) === Number.prototype`
// and inherited methods such as `toFixed` resolve to the prototype's).
let ctor_name = match ctor_id {
N_NUMBER => Some("Number"),
N_STRING => Some("String"),
N_BOOLEAN => Some("Boolean"),
N_SYMBOL => Some("Symbol"),
N_BIGINT => Some("BigInt"),
_ => None,
};
if let Some(proto) = ctor_name
.and_then(|n| self.current.get(n))
.and_then(|v| v.as_handle())
.map(Handle::from_raw)
.and_then(|c| self.realm.get_property(c, "prototype"))
.and_then(|p| p.as_handle())
.map(Handle::from_raw)
{
self.realm.set_object_proto(obj, Some(proto));
}
self.realm.set_hidden_property(obj, PRIM_WRAP, prim);
self.realm
.set_hidden_property(obj, PRIM_WRAP_TYPE, NanBox::number(f64::from(ctor_id)));
NanBox::handle(obj.to_raw())
}
/// Builds an `arguments` exotic object for a function call (`args`), per
/// 10.4.4 CreateUnmappedArgumentsObject / a best-effort mapped object:
///
/// - `[[Prototype]]` is `Object.prototype` (not `Array.prototype`).
/// - Indexed elements `0..len` are ordinary enumerable, writable,
/// configurable own data properties.
/// - `length` is a writable, configurable, **non-enumerable** data property.
/// - `[Symbol.iterator]` is `Array.prototype.values` (writable, configurable,
/// non-enumerable), so `[...arguments]`/`for-of` work.
/// - `callee`: in sloppy mode the *function itself* (writable, configurable,
/// non-enumerable) on a *mapped* object; on an *unmapped* one a poisoned
/// accessor throwing `TypeError`.
/// - A hidden `ARGS_MARKER` makes `Object.prototype.toString` report
/// `[object Arguments]`.
///
/// When `mapped_params` is `Some(names)` (a sloppy-mode function with a simple
/// parameter list, `names` being its formal-parameter names in order), the
/// object is **mapped**: each index `i < min(argc, names.len())` that is the
/// *last* parameter with its name aliases the parameter binding in
/// `self.current` (10.4.4 `CreateMappedArgumentsObject`), recorded in
/// [`Interp::arg_maps`]. When `None` (strict, or a non-simple parameter list),
/// the object is unmapped — the indices are a plain snapshot of the arguments.
pub(crate) fn make_arguments_object(
&mut self,
args: &[NanBox],
callee: NanBox,
mapped_params: Option<&[&str]>,
) -> NanBox {
let obj = self.realm.new_object();
// [[Prototype]] = Object.prototype.
if let Some(proto) = self
.current
.get("Object")
.and_then(|v| v.as_handle())
.map(Handle::from_raw)
.and_then(|c| self.realm.get_property(c, "prototype"))
.and_then(|p| p.as_handle())
.map(Handle::from_raw)
{
self.realm.set_object_proto(obj, Some(proto));
}
// Indexed elements: ordinary enumerable own data properties.
for (i, v) in args.iter().enumerate() {
self.realm.set_property(obj, &alloc::format!("{i}"), *v);
}
// `length` — writable, configurable, non-enumerable.
self.realm
.set_hidden_property(obj, "length", NanBox::number(args.len() as f64));
// `[Symbol.iterator]` = `%Array.prototype.values%` — the SAME function
// value as `Array.prototype[Symbol.iterator]` (i.e. `[][Symbol.iterator]`,
// which aliases `values`), so a `verifyProperty(arguments, Symbol.iterator,
// {value: [][Symbol.iterator]})` SameValue check holds. Non-enumerable.
let iter_sym = self.well_known_symbol("iterator");
let iter_key = self.member_key(iter_sym);
if let Some(values) = self
.current
.get("Array")
.and_then(|v| v.as_handle())
.map(Handle::from_raw)
.and_then(|c| self.realm.get_property(c, "prototype"))
.and_then(|p| p.as_handle())
.map(Handle::from_raw)
.and_then(|proto| self.realm.get_property(proto, "values"))
{
self.realm.set_hidden_property(obj, &iter_key, values);
}
// `callee`. It is the poisoned accessor on every **unmapped** arguments
// object (10.4.4.6 CreateUnmappedArgumentsObject step 6) — not only in
// strict mode: a *sloppy* function with a non-simple parameter list
// (`function f(a = 0) {}`) is also unmapped and also gets the accessor.
if mapped_params.is_none() {
// An unmapped arguments object's `callee` is a poisoned accessor
// (`%ThrowTypeError%`, which has own non-configurable `name`/`length`).
// Reuse the realm's single canonical `%ThrowTypeError%` so this getter
// is the *same* function object as `Function.prototype.caller`'s
// (ECMA-262: one `%ThrowTypeError%` per realm); fall back to a fresh
// native only if global setup has not installed it yet.
let thrower_h = self.realm.throw_type_error_intrinsic().unwrap_or_else(|| {
let h = self.realm.new_native(N_THROW_TYPE_ERROR);
self.install_fn_name_length(h, "", 0);
self.realm.set_non_configurable_property(h, "name");
self.realm.set_non_configurable_property(h, "length");
h
});
let thrower = NanBox::handle(thrower_h.to_raw());
self.realm.define_accessor(obj, "callee", thrower, thrower);
// A strict arguments object's `callee` accessor is non-enumerable AND
// non-configurable (`{enumerable:false, configurable:false}`).
self.realm.mark_hidden(obj, "callee");
self.realm.set_non_configurable_property(obj, "callee");
} else {
self.realm.set_hidden_property(obj, "callee", callee);
}
self.realm
.set_hidden_property(obj, ARGS_MARKER, NanBox::boolean(true));
// CreateMappedArgumentsObject: build the `[[ParameterMap]]`. An index is
// mapped iff it is bound by an argument (`i < argc`) AND its parameter name
// does not recur in a *later* formal position (a duplicate name maps only
// its last occurrence, per the spec's high-to-low index walk).
if let Some(names) = mapped_params {
let bound = args.len().min(names.len());
let mut slots = alloc::collections::BTreeMap::new();
for i in 0..bound {
let name = names[i];
if !names[i + 1..].contains(&name) {
slots.insert(i, String::from(name));
}
}
if !slots.is_empty() {
self.arg_maps.insert(
obj.to_raw(),
super::ArgMap {
scope: self.current.clone(),
slots,
},
);
}
}
NanBox::handle(obj.to_raw())
}
/// The `(scope, parameter name)` a mapped `arguments` index currently aliases,
/// or `None` if `handle` is not a mapped arguments object or `key` is not (or
/// no longer) a mapped index. `key` must be a canonical integer string.
pub(crate) fn arg_map_binding(&self, handle: Handle, key: &str) -> Option<(Scope, String)> {
let map = self.arg_maps.get(&handle.to_raw())?;
let i = key.parse::<usize>().ok()?;
if alloc::format!("{i}") != key {
return None;
}
let name = map.slots.get(&i)?;
Some((map.scope.clone(), name.clone()))
}
/// Breaks the mapping of index `key` on a mapped `arguments` object (drops its
/// slot) — the spec's `map.[[Delete]](P)` on a `delete` or on a
/// `defineProperty` that installs an accessor / non-writable data property.
pub(crate) fn arg_map_break(&mut self, handle: Handle, key: &str) {
if let Some(map) = self.arg_maps.get_mut(&handle.to_raw())
&& let Ok(i) = key.parse::<usize>()
&& alloc::format!("{i}") == key
{
map.slots.remove(&i);
}
}
/// `ToObject(v)` for `Object(v)`: `null`/`undefined` yield a fresh object; an
/// existing object/array/function is returned unchanged; a primitive is boxed in
/// its wrapper (so `Object(42).valueOf()` is `42`).
pub(crate) fn coerce_to_object(&mut self, v: NanBox) -> NanBox {
match v.unpack() {
Unpacked::Undefined | Unpacked::Null => {
NanBox::handle(self.realm.new_object().to_raw())
}
Unpacked::Number(_) => self.make_primitive_wrapper(v, N_NUMBER),
Unpacked::Bool(_) => self.make_primitive_wrapper(v, N_BOOLEAN),
Unpacked::Handle(raw) => {
let h = Handle::from_raw(raw);
if self.realm.is_string_handle(h) {
self.make_primitive_wrapper(v, N_STRING)
} else if self.realm.symbol_at(h).is_some() {
// ToObject(Symbol) → a Symbol wrapper object (its prototype
// methods read the boxed symbol via `thisSymbolValue`).
self.make_primitive_wrapper(v, N_SYMBOL)
} else if self.realm.bigint_at(h).is_some() {
// ToObject(BigInt) → a BigInt wrapper object.
self.make_primitive_wrapper(v, N_BIGINT)
} else {
// An already-object value (object/array/function).
v
}
}
}
}
/// Resolves a (trap-less) proxy to its target for key enumeration, so
/// `Object.keys`/`values`/`entries` on a pass-through proxy see the target's
/// own keys. A non-proxy is returned unchanged. (The `ownKeys` trap is not
/// invoked here.)
pub(crate) fn proxy_key_target(&self, mut h: crate::heap::Handle) -> crate::heap::Handle {
while let Some((target, _)) = self.realm.proxy_at(h) {
h = target;
}
h
}
/// `Object.keys` for a proxy that defines an `ownKeys` trap: invoke the trap,
/// then keep each string key whose property is enumerable — via the
/// `getOwnPropertyDescriptor` trap if present, else the target. Returns `None`
/// when there is no `ownKeys` trap (so the caller uses the target's keys).
pub(crate) fn proxy_own_enumerable_keys(
&mut self,
proxy: Handle,
) -> Result<Option<Vec<String>>, ExecError> {
let Some((target, handler)) = self.realm.proxy_at(proxy) else {
return Ok(None);
};
// `[[OwnPropertyKeys]]`: the validated `ownKeys` trap result, or — with no
// trap — the target's own keys (the proxy's default forward). Either way the
// proxy's `[[OwnPropertyKeys]]` is consulted, then EnumerableOwnPropertyNames
// runs `[[GetOwnProperty]]` per key below.
let _ = handler;
let _ = target;
let keys = self.own_property_keys_values(proxy)?;
let mut out = Vec::new();
for k in keys {
// Only string keys participate in `Object.keys` (symbols are skipped).
let Some(name) = k
.as_handle()
.map(Handle::from_raw)
.and_then(|h| self.realm.string_value(h))
else {
continue;
};
// EnumerableOwnPropertyNames calls `O.[[GetOwnProperty]](key)` per key —
// the proxy's `[[GetOwnProperty]]`, which invokes the
// `getOwnPropertyDescriptor` trap (or, absent a trap, forwards to the
// target). Using `descriptor_of` keeps that observable interleaving even
// when the handler has no descriptor trap (the trap *lookup* still fires
// the handler's own `[[Get]]`, e.g. a proxy-wrapped handler).
let desc = self.descriptor_of(proxy, &name)?;
if matches!(desc.unpack(), Unpacked::Undefined) {
continue;
}
let enumerable = desc
.as_handle()
.map(Handle::from_raw)
.and_then(|dh| self.realm.get_property(dh, "enumerable"))
.is_some_and(|v| self.realm.truthy(v));
if enumerable {
out.push(name);
}
}
Ok(Some(out))
}
/// `EnumerableOwnProperties(proxy, kind)` for `Object.values`/`entries`, keeping
/// the spec-exact per-key interleaving: for each String own key,
/// `[[GetOwnProperty]]` (the `getOwnPropertyDescriptor` trap) fires *immediately
/// before* the enumerable key's `[[Get]]` (the `get` trap) — not a first pass of
/// all descriptors and then a second pass of all reads. Returns `None` when
/// `handle` is not a proxy (the caller then uses the ordinary object path).
pub(crate) fn proxy_enumerable_entries(
&mut self,
proxy: Handle,
) -> Result<Option<Vec<(alloc::string::String, NanBox)>>, ExecError> {
if self.realm.proxy_at(proxy).is_none() {
return Ok(None);
}
let Some(keys) = self.proxy_own_keys_raw(proxy)? else {
return Ok(None);
};
let mut out = Vec::new();
for k in keys {
// Only String keys participate (symbols are skipped).
let Some(name) = k
.as_handle()
.map(Handle::from_raw)
.and_then(|h| self.realm.string_value(h))
else {
continue;
};
// `[[GetOwnProperty]]` (proxy-aware) — the descriptor trap fires here.
let desc = self.descriptor_of(proxy, &name)?;
if matches!(desc.unpack(), Unpacked::Undefined) {
continue;
}
let enumerable = desc
.as_handle()
.map(Handle::from_raw)
.and_then(|dh| self.realm.get_property(dh, "enumerable"))
.is_some_and(|v| self.realm.truthy(v));
if !enumerable {
continue;
}
// `[[Get]]` (the `get` trap) immediately after this key's descriptor.
let v = self.read_member(proxy, &name)?;
out.push((name, v));
}
Ok(Some(out))
}
/// The proxy `set` trap success invariant (10.5.9): a `true` result is illegal
/// when the target has `key` as a non-configurable, non-writable data property
/// with a different value, or as a non-configurable accessor whose setter is
/// undefined. Call after a `set` trap returns truthy.
pub(crate) fn proxy_set_invariant_check(
&mut self,
target: Handle,
key: &str,
value: NanBox,
) -> Result<(), ExecError> {
if let Some((g, s)) = self.realm.accessor(target, key) {
let _ = g;
if self.realm.property_is_non_configurable(target, key)
&& matches!(s.unpack(), Unpacked::Undefined)
{
return Err(self.type_error(
"proxy 'set' trap succeeded for a non-configurable accessor with no setter",
));
}
return Ok(());
}
if self.realm.has_own(target, key)
&& self.realm.property_is_non_configurable(target, key)
&& self.realm.property_is_readonly(target, key)
{
let cur = self
.realm
.get_property(target, key)
.unwrap_or(NanBox::undefined());
if !self.realm.strict_equals(cur, value) {
return Err(self.type_error(
"proxy 'set' trap succeeded for a non-configurable non-writable property with a different value",
));
}
}
Ok(())
}
/// `[[Delete]]` honoring a proxy's `deleteProperty` trap (and its invariants).
/// Returns the boolean result. Used by `Reflect.deleteProperty`.
pub(crate) fn delete_property_of(&mut self, obj: Handle, key: &str) -> Result<bool, ExecError> {
// 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(obj, key)?;
if let Some((target, handler)) = self.realm.proxy_at(obj) {
self.guard_revoked(obj)?;
if let Some(trap) = self.proxy_trap(handler, "deleteProperty")? {
let kb = 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()), kb])?;
if !self.realm.truthy(r) {
return Ok(false);
}
let present =
self.realm.has_own(target, key) || self.realm.accessor(target, key).is_some();
if present && self.realm.property_is_non_configurable(target, key) {
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",
));
}
return Ok(true);
}
return self.delete_property_of(target, key);
}
// A non-proxy target: a String exotic object's own `length` / index and a
// RegExp's own `lastIndex` are non-configurable synthesized properties, so
// `[[Delete]]` returns false. `delete_property` only tracks physical slots,
// so guard those exotics via their descriptor here.
if (self.realm.string_object_len(obj).is_some() || self.realm.regexp_at(obj).is_some())
&& let Some(desc) = self.build_descriptor(obj, key)
&& let Some(dh) = desc.as_handle().map(Handle::from_raw)
&& self
.realm
.get_property(dh, "configurable")
.is_some_and(|v| !self.realm.truthy(v))
{
return Ok(false);
}
let result = self.realm.delete_property(obj, key);
// A successful delete of a mapped `arguments` index breaks its aliasing.
if result {
self.arg_map_break(obj, key);
}
Ok(result)
}
/// `SetIntegrityLevel(O, level)` (7.3.15) routed through a proxy's traps:
/// `[[PreventExtensions]]`, then `[[OwnPropertyKeys]]` and — per key —
/// `[[GetOwnProperty]]` + `[[DefineOwnProperty]]` making it non-configurable
/// (and a data property non-writable when `frozen`). A failed prevent-extensions
/// or a rejected define is a TypeError.
pub(crate) fn proxy_set_integrity_level(
&mut self,
obj: Handle,
frozen: bool,
) -> Result<(), ExecError> {
if !self.prevent_extensions_of(obj)? {
return Err(
self.type_error("Object.freeze/seal: object could not be made non-extensible")
);
}
let keys = self.own_property_keys_values(obj)?;
for key in keys {
let name = self.member_key(key);
let current = self.descriptor_of(obj, &name)?;
if matches!(current.unpack(), Unpacked::Undefined) {
continue;
}
let is_accessor = current
.as_handle()
.map(Handle::from_raw)
.is_some_and(|dh| self.realm.has_own(dh, "get") || self.realm.has_own(dh, "set"));
let desc = self.realm.new_object();
self.realm
.set_property(desc, "configurable", NanBox::boolean(false));
if frozen && !is_accessor {
self.realm
.set_property(desc, "writable", NanBox::boolean(false));
}
// `apply_descriptor(reflect=false)` routes through the `defineProperty`
// trap and throws a TypeError if it is rejected (DefinePropertyOrThrow).
self.apply_descriptor(obj, &name, desc, false)?;
}
Ok(())
}
/// `TestIntegrityLevel(O, level)` (7.3.16) routed through a proxy's traps: a
/// non-extensible object all of whose own properties (via `[[GetOwnProperty]]`)
/// are non-configurable — and, when `frozen`, every data property non-writable.
pub(crate) fn proxy_test_integrity_level(
&mut self,
obj: Handle,
frozen: bool,
) -> Result<bool, ExecError> {
let ext = self.is_extensible_of(obj)?;
if self.realm.truthy(ext) {
return Ok(false);
}
let keys = self.own_property_keys_values(obj)?;
for key in keys {
let name = self.member_key(key);
let current = self.descriptor_of(obj, &name)?;
let Some(dh) = current.as_handle().map(Handle::from_raw) else {
continue;
};
let configurable = self
.realm
.get_property(dh, "configurable")
.is_some_and(|v| self.realm.truthy(v));
if configurable {
return Ok(false);
}
if frozen {
let is_data = self.realm.has_own(dh, "value") || self.realm.has_own(dh, "writable");
let writable = self
.realm
.get_property(dh, "writable")
.is_some_and(|v| self.realm.truthy(v));
if is_data && writable {
return Ok(false);
}
}
}
Ok(true)
}
/// `[[PreventExtensions]]` honoring a proxy's `preventExtensions` trap. Returns
/// the boolean success. A `true` trap result is validated against the spec
/// invariant: the target must then report non-extensible (else a TypeError).
pub(crate) fn prevent_extensions_of(&mut self, obj: Handle) -> Result<bool, ExecError> {
if let Some((target, handler)) = self.realm.proxy_at(obj) {
self.guard_revoked(obj)?;
if let Some(trap) = self.proxy_trap(handler, "preventExtensions")? {
let handler_box = NanBox::handle(handler.to_raw());
let r =
self.call_with_this(trap, handler_box, &[NanBox::handle(target.to_raw())])?;
if self.realm.truthy(r) {
// Invariant: a successful trap requires the target to be
// non-extensible.
if self.realm.is_extensible(target) {
return Err(self.type_error(
"proxy 'preventExtensions' trap returned true but the target is extensible",
));
}
return Ok(true);
}
return Ok(false);
}
return self.prevent_extensions_of(target);
}
self.realm.prevent_extensions(obj);
Ok(true)
}
/// `CreateListFromArrayLike(obj)` (default element types): the argument must be
/// an Object; reads `length` (ToLength) then each indexed element via `[[Get]]`
/// (so getters / proxy traps fire), returning the value list. Used by
/// `Reflect.apply` / `Reflect.construct`.
pub(crate) fn create_list_from_array_like(
&mut self,
v: NanBox,
) -> Result<Vec<NanBox>, ExecError> {
if !self.is_object_value(v) {
return Err(self.type_error("CreateListFromArrayLike called on non-object"));
}
let h = v.as_handle().map(Handle::from_raw).unwrap();
// A real dense array: fast path. A hole is normalized to `undefined` — the
// spec does `Get(obj, index)`, which on an absent index of an ordinary
// array yields `undefined` (not the internal hole sentinel, which must
// never escape as a value).
if let Some(elems) = self.realm.array_elements(h) {
return Ok(elems
.iter()
.map(|e| if e.is_hole() { NanBox::undefined() } else { *e })
.collect());
}
let len_val = self.read_member(h, "length")?;
let len_num = self.coerce_to_number(len_val)?;
let raw = self.realm.to_number(len_num);
let len = if raw.is_nan() || raw <= 0.0 {
0
} else {
(raw.min(9_007_199_254_740_991.0)) as usize
};
let mut out = Vec::with_capacity(len.min(1 << 16));
for i in 0..len {
out.push(self.read_member(h, &alloc::format!("{i}"))?);
}
Ok(out)
}
/// A proxy's `[[OwnPropertyKeys]]` (ECMA-262 10.5.11): invoke the `ownKeys`
/// trap and validate the result — every entry must be a String or Symbol, with
/// no duplicates; the result must contain every non-configurable own key of the
/// target and (when the target is non-extensible) exactly the target's own
/// keys. Returns the validated key list (String/Symbol NanBoxes). Returns
/// `None` if there is no `ownKeys` trap (the caller falls back to the target).
pub(crate) fn proxy_own_keys_raw(
&mut self,
proxy: Handle,
) -> Result<Option<Vec<NanBox>>, ExecError> {
let Some((target, handler)) = self.realm.proxy_at(proxy) else {
return Ok(None);
};
self.guard_revoked(proxy)?;
let Some(trap) = self.proxy_trap(handler, "ownKeys")? else {
return Ok(None);
};
let target_box = NanBox::handle(target.to_raw());
let handler_box = NanBox::handle(handler.to_raw());
let result = self.call_with_this(trap, handler_box, &[target_box])?;
// CreateListFromArrayLike(result, « String, Symbol »): the trap result must
// be an Object; each element must be a String or Symbol.
if !self.is_object_value(result) {
return Err(self.type_error("proxy 'ownKeys' trap must return an array-like object"));
}
let rh = result.as_handle().map(Handle::from_raw).unwrap();
let len = self
.read_member(rh, "length")?
.as_number()
.map(|n| n.max(0.0) as usize)
.unwrap_or(0);
let mut keys: Vec<NanBox> = Vec::with_capacity(len);
let mut seen_strs: alloc::collections::BTreeSet<String> =
alloc::collections::BTreeSet::new();
let mut seen_syms: alloc::collections::BTreeSet<u64> = alloc::collections::BTreeSet::new();
for i in 0..len {
let el = self.read_member(rh, &alloc::format!("{i}"))?;
let elh = el.as_handle().map(Handle::from_raw);
// Each key must be a String or Symbol; duplicates are a TypeError.
if let Some(eh) = elh
&& let Some(s) = self.realm.string_value(eh)
{
if !seen_strs.insert(s) {
return Err(self.type_error("proxy 'ownKeys' trap returned duplicate entries"));
}
} else if let Some(eh) = elh
&& let Some((_, sid)) = self.realm.symbol_at(eh)
{
if !seen_syms.insert(sid) {
return Err(self.type_error("proxy 'ownKeys' trap returned duplicate entries"));
}
} else {
return Err(
self.type_error("proxy 'ownKeys' trap returned a non-string, non-symbol key")
);
}
keys.push(el);
}
// Invariant checks against the target's own keys.
let extensible = self.realm.is_extensible(target);
let target_keys = self.target_own_key_set(target);
// Every non-configurable own key of the target must be present.
for tk in &target_keys {
let is_nonconf = self.target_key_nonconfigurable(target, tk);
if is_nonconf && !self.key_list_contains(&keys, tk) {
return Err(self.type_error(
"proxy 'ownKeys' trap omitted a non-configurable key of the target",
));
}
}
if !extensible {
// The result must contain exactly the target's own keys.
for tk in &target_keys {
if !self.key_list_contains(&keys, tk) {
return Err(self.type_error(
"proxy 'ownKeys' trap omitted a key of a non-extensible target",
));
}
}
for k in &keys {
let kd = self.key_descriptor_string(*k);
if !target_keys.contains(&kd) {
return Err(self.type_error(
"proxy 'ownKeys' trap added a key not on a non-extensible target",
));
}
}
}
Ok(Some(keys))
}
/// The own keys of `target` as canonical descriptor strings (a symbol becomes
/// its internal `"\0sym:<id>"` storage key), for proxy ownKeys invariants.
fn target_own_key_set(&mut self, target: Handle) -> Vec<String> {
let mut out = Vec::new();
if let Some(indices) = self.realm.array_present_indices(target) {
for i in indices {
out.push(alloc::format!("{i}"));
}
out.push(String::from("length"));
}
for k in self.realm.own_property_names(target).unwrap_or_default() {
if !out.contains(&k) {
out.push(k);
}
}
for k in self.realm.object_all_keys(target) {
if k.starts_with("\u{0}sym:") && !out.contains(&k) {
out.push(k);
}
}
out
}
/// The canonical descriptor string for a String/Symbol key NanBox.
fn key_descriptor_string(&self, key: NanBox) -> String {
if let Some(h) = key.as_handle().map(Handle::from_raw) {
if let Some(s) = self.realm.string_value(h) {
return s;
}
if let Some((_, id)) = self.realm.symbol_at(h) {
return alloc::format!("\u{0}sym:{id}");
}
}
String::new()
}
/// Whether the key list (String/Symbol NanBoxes) contains `target_key` (given
/// as its canonical descriptor string).
fn key_list_contains(&self, keys: &[NanBox], target_key: &str) -> bool {
keys.iter()
.any(|k| self.key_descriptor_string(*k) == target_key)
}
/// Whether `target`'s own property `key` (a canonical descriptor string) is
/// non-configurable.
fn target_key_nonconfigurable(&mut self, target: Handle, key: &str) -> bool {
if key == "length" && self.realm.is_array(target) {
return true; // array `length` is non-configurable
}
if let Some((_, _)) = self.realm.accessor(target, key) {
return self.realm.property_is_non_configurable(target, key);
}
if self.realm.has_own(target, key) {
return self.realm.property_is_non_configurable(target, key);
}
false
}
/// Whether `handle` or any object on its prototype chain carries the hidden
/// `brand` marker. Used to detect that a receiver inherits a branded built-in
/// prototype (`ArrayBuffer.prototype`, `%TypedArray%.prototype`, …) whose
/// slot-requiring accessors must throw when no internal slot is present.
pub(crate) fn brand_on_chain(&self, handle: Handle, brand: &str) -> bool {
let mut cur = Some(handle);
let mut guard = 0;
while let Some(h) = cur {
if self.realm.has_own(h, brand) {
return true;
}
guard += 1;
if guard > 1000 {
break;
}
cur = self.realm.object_proto(h);
}
false
}
pub(crate) fn object_string_tag(
&mut self,
h: crate::heap::Handle,
) -> Result<String, ExecError> {
// The spec order (20.1.3.6) computes a `builtinTag` FIRST (IsArray is
// proxy-aware and a proxy whose target is callable reports "Function"),
// then a string `Symbol.toStringTag` OVERRIDES it.
// IsArray walks proxy chains (a revoked proxy throws).
let is_array = self.is_array_unwrap_proxy(NanBox::handle(h.to_raw()))?;
// A callable proxy (target has [[Call]]) reports "Function".
let is_callable_unwrapped = {
let mut cur = h;
let mut callable = false;
for _ in 0..1000 {
if let Some((target, _)) = self.realm.proxy_at(cur) {
cur = target;
continue;
}
callable = self.is_callable(cur) || self.realm.class_at(cur).is_some();
break;
}
callable
};
let builtin_tag = if is_array {
"Array"
} else if let Some(kind) = self.realm.typed_kind(h) {
TYPED_ARRAY_KINDS[kind as usize].0
} else if is_callable_unwrapped {
"Function"
} else if let Some(prim) = self.realm.get_property(h, PRIM_WRAP) {
// A boxed primitive wrapper reports its primitive's class — but only
// Number / Boolean / String have a builtin tag. A Symbol or BigInt
// wrapper has no [[NumberData]]-style slot, so its tag is "Object".
match prim.unpack() {
Unpacked::Number(_) => "Number",
Unpacked::Bool(_) => "Boolean",
Unpacked::Handle(praw)
if self
.realm
.string_value(crate::heap::Handle::from_raw(praw))
.is_some() =>
{
"String"
}
_ => "Object",
}
} else if self.realm.is_string_handle(h) {
"String"
} else if self.realm.date_at(h).is_some() {
"Date"
} else if self.realm.regexp_at(h).is_some() {
"RegExp"
} else if self.is_error_object(h) {
"Error"
} else if self.realm.get_property(h, ARGS_MARKER).is_some() {
"Arguments"
} else {
"Object"
};
// A string `Symbol.toStringTag` (read through the prototype chain, firing an
// accessor) overrides the builtin tag.
let tag_sym = self.well_known_symbol("toStringTag");
let tag_key = self.member_key(tag_sym);
let v = self.read_member(h, &tag_key)?;
if let Some(sh) = v.as_handle().map(Handle::from_raw)
&& let Some(s) = self.realm.string_value(sh)
{
return Ok(s);
}
Ok(String::from(builtin_tag))
}
/// `HasProperty(O, P)` — the `in` operator / `Reflect.has`, honoring a proxy's
/// `has` trap *anywhere on the prototype chain* (OrdinaryHasProperty recurses
/// into `parent.[[HasProperty]]`, and a proxy parent runs its own trap).
pub(crate) fn has_property_proxied(
&mut self,
obj: Handle,
key: &str,
) -> Result<bool, ExecError> {
// Integer-indexed exotic `[[HasProperty]]`: a canonical numeric index on a
// (non-proxy) typed array is exactly IsValidIntegerIndex — the prototype
// chain is never consulted (an out-of-bounds or proto-set numeric key is
// absent).
if self.realm.proxy_at(obj).is_none()
&& self.realm.typed_kind(obj).is_some()
&& let Some(n) = canonical_numeric_index(key)
{
let is_neg_zero = n == 0.0 && n.is_sign_negative();
return Ok(!self.typed_array_detached(obj)
&& !is_neg_zero
&& n == (n as i64) as f64
&& n >= 0.0
&& self
.realm
.typed_len(obj)
.is_some_and(|len| (n as usize) < len));
}
let mut cur = Some(obj);
// Bound to guard against a `getPrototypeOf` trap returning a cycle.
for _ in 0..100_000 {
let Some(c) = cur else { return Ok(false) };
if let Some((target, handler)) = self.realm.proxy_at(c) {
self.guard_revoked(c)?;
if let Some(trap) = self.proxy_trap(handler, "has")? {
let kb = 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()), kb],
)?;
let result = self.realm.truthy(r);
// Invariant (10.5.7): a false result is illegal if the property
// exists as a non-configurable own property of the target, or if
// the target is non-extensible and the property is own.
if !result {
let target_has = self.realm.has_own(target, key)
|| self.realm.accessor(target, key).is_some()
|| (key == "length" && self.realm.is_array(target))
|| (self.realm.array_length(target).is_some()
&& key
.parse::<usize>()
.is_ok_and(|i| i < self.realm.array_length(target).unwrap()));
if target_has {
if self.target_key_nonconfigurable(target, key) {
return Err(self.type_error(
"proxy 'has' trap returned false for a non-configurable property of the target",
));
}
if !self.realm.is_extensible(target) {
return Err(self.type_error(
"proxy 'has' trap returned false for a property of a non-extensible target",
));
}
}
}
return Ok(result);
}
// No `has` trap: forward `[[HasProperty]]` to the target (which
// itself walks its chain, possibly through further proxies).
return self.has_property_proxied(target, key);
}
// An own data/accessor property. `has_own` is hole-aware for arrays —
// it reports `length` and every in-range **non-hole** index (a hole is
// absent), so a bare `i < len` must NOT be used here or `[2,,3]` would
// report index 1 (a hole) as present in `in` / `HasProperty` and in the
// generic array-like iteration that probes presence with this.
let here = self.realm.has_own(c, key)
|| self.realm.accessor(c, key).is_some()
// A RegExp instance's `lastIndex` is always an own data property
// (stored as a compact cell field, so not reported by `has_own`
// until materialized).
|| (key == "lastIndex" && self.realm.regexp_at(c).is_some());
if here {
return Ok(true);
}
cur = self.realm.object_proto(c);
}
Ok(false)
}
/// Whether `handle` is an Error object (has `[[ErrorData]]`): its prototype
/// chain includes `Error.prototype`, or it is a class instance whose `extends`
/// chain reaches a native `Error*` constructor.
pub(crate) fn is_error_object(&mut self, handle: Handle) -> bool {
// The `[[ErrorData]]` internal slot (see `ERROR_DATA`), NOT membership of
// an error prototype chain: `Object.prototype.toString` reports
// `[object Error]` only for objects that *have* the slot. Every
// `NativeError.prototype` inherits from `%Error.prototype%` but is an
// ordinary object without the slot, so it reports `[object Object]` — as
// does any plain object given an error prototype.
self.realm.has_own(handle, crate::nbexec::ERROR_DATA)
}
/// Whether `handle` has `name` as an own or inherited property (walks the
/// prototype chain; includes accessors).
/// `ToObject(v)` for the spec sites that require an Object argument and must
/// reject `null`/`undefined` with a TypeError (e.g. the *Properties* argument
/// of `Object.create`/`Object.defineProperties`). An object passes through; a
/// primitive wrapper boxes; `null`/`undefined` throw using `site` in the
/// message.
/// The `Reflect.*` target requirement: `v` must be an Object (ECMA-262 — the
/// first step of every `Reflect` operation is `if Type(target) is not Object,
/// throw a TypeError`). A string/symbol/bigint primitive or an immediate
/// (number/boolean/null/undefined) is rejected. Returns the target handle.
pub(crate) fn reflect_object_target(
&mut self,
v: NanBox,
op: &str,
) -> Result<Handle, ExecError> {
if self.is_object_value(v)
&& let Some(raw) = v.as_handle()
{
return Ok(Handle::from_raw(raw));
}
Err(self.type_error(&alloc::format!("Reflect.{op} called on non-object")))
}
pub(crate) fn require_object_coercible_to_object(
&mut self,
v: NanBox,
site: &str,
) -> Result<Handle, ExecError> {
if matches!(v.unpack(), Unpacked::Null | Unpacked::Undefined) {
return Err(self.type_error(&alloc::format!("{site} called on null or undefined")));
}
let obj = self.coerce_to_object(v);
obj.as_handle().map(Handle::from_raw).ok_or_else(|| {
self.type_error(&alloc::format!(
"{site} could not coerce argument to an object"
))
})
}
/// Applies the own *enumerable* property descriptors of `descs` onto `target`
/// (`Object.defineProperties` / the second argument of `Object.create`). Each
/// descriptor object is read and validated via `apply_descriptor`
/// (ToPropertyDescriptor), so a malformed descriptor (e.g. both `value` and
/// `get`) throws.
pub(crate) fn apply_property_descriptors(
&mut self,
target: Handle,
descs: Handle,
) -> Result<(), ExecError> {
// A proxy Properties object drives `[[OwnPropertyKeys]]` + per-key
// `[[GetOwnProperty]]` (getOwnPropertyDescriptor trap) then `[[Get]]` (get
// trap) through its handler, in spec order — the physical key scan below
// would see none of the proxy's virtual keys.
if self.realm.proxy_at(descs).is_some() {
let keys = self.own_property_keys_values(descs)?;
for key in keys {
let name = self.member_key(key);
let desc = self.descriptor_of(descs, &name)?;
if matches!(desc.unpack(), Unpacked::Undefined) {
continue;
}
let enumerable = desc
.as_handle()
.map(Handle::from_raw)
.and_then(|dh| self.realm.get_property(dh, "enumerable"))
.is_some_and(|v| self.realm.truthy(v));
if !enumerable {
continue;
}
let d_val = self.read_member(descs, &name)?;
let Some(d) = d_val
.as_handle()
.map(Handle::from_raw)
.filter(|_| self.is_object_value(d_val))
else {
return Err(self.type_error("Property description must be an object"));
};
self.apply_descriptor(target, &name, d, false)?;
}
return Ok(());
}
// OwnPropertyKeys(Properties) filtered to enumerable, in spec order. A
// function/array/native keeps its named (accessor) properties in the aux
// object, so fall back to `aux_named_keys` like `Object.keys`. An array's
// own enumerable keys also include its integer indices.
let mut keys: Vec<alloc::string::String> = Vec::new();
// A String exotic Properties object (`Object.create(p, "abc")` /
// `defineProperties(o, new String("abc"))`) exposes its code-unit indices as
// own enumerable properties; each value is a one-char string, so
// ToPropertyDescriptor rejects it — the point of these keys enumerating.
if let Some(n) = self.string_index_count(descs) {
for i in 0..n {
keys.push(alloc::format!("{i}"));
}
}
if let Some(indices) = self.realm.array_present_indices(descs)
&& !self.realm.is_vm_function(descs)
{
for i in indices {
keys.push(alloc::format!("{i}"));
}
}
if let Some(named) = self.realm.object_keys(descs) {
keys.extend(named);
} else {
keys.extend(self.realm.aux_named_keys(descs));
}
for key in keys {
// Get(props, key) invokes a getter (the descriptor value may be
// computed); the result must be an object (ToPropertyDescriptor).
let d_val = self.read_member(descs, &key)?;
let Some(d) = d_val
.as_handle()
.map(Handle::from_raw)
.filter(|_| self.is_object_value(d_val))
else {
return Err(self.type_error("Property description must be an object"));
};
self.apply_descriptor(target, &key, d, false)?;
}
Ok(())
}
/// Reads a named member, honoring class statics and accessor getters before
/// ordinary property/length access.
/// The global constructor a built-in heap value reports as its `.constructor`
/// (so `[].constructor === Array`), resolved by the value's cell kind. Returns
/// the actual global binding (identity-equal to `Array`, `Object`, …), or
/// `None` for kinds without a distinct constructor.
pub(crate) fn builtin_constructor_for(
&mut self,
handle: crate::heap::Handle,
) -> Option<NanBox> {
let name = if self.realm.is_array(handle) {
"Array"
} else if self.realm.is_string_handle(handle) {
"String"
} else if self.realm.regexp_at(handle).is_some() {
"RegExp"
} else if self.realm.bigint_at(handle).is_some() {
"BigInt"
} else if self.realm.symbol_at(handle).is_some() {
"Symbol"
} else if self.realm.date_at(handle).is_some() {
"Date"
} else if let Some(is_set) = self.realm.collection_is_set(handle) {
// Distinguish weak collections so `wm.constructor === WeakMap` (not 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.promise_state(handle).is_some() {
"Promise"
} else if self.realm.object_keys(handle).is_some() {
// A plain object reports `Object`. (Error objects are handled earlier in
// `read_member`, before their prototype's generic `constructor`.)
"Object"
} else {
return None;
};
self.current.get(name)
}
/// `O.[[OwnPropertyKeys]]()` as a list of key values (Strings then Symbols,
/// each in insertion / integer-ascending order), routed through a proxy's
/// `ownKeys` trap when present. Used by `Object.assign`'s CopyDataProperties.
pub(crate) fn own_property_keys_values(
&mut self,
handle: crate::heap::Handle,
) -> Result<Vec<NanBox>, ExecError> {
// A Deferred Module Namespace (`import defer`) evaluates its target on any
// `[[OwnPropertyKeys]]` (Object.keys / getOwnProperty{Names,Symbols} /
// Reflect.ownKeys).
#[cfg(all(feature = "module", feature = "std"))]
self.force_deferred_namespace(handle)?;
// A proxy routes [[OwnPropertyKeys]] through its `ownKeys` trap; with no
// trap it forwards to the target's [[OwnPropertyKeys]] (the proxy cell
// itself has no physical keys).
if let Some((target, _)) = self.realm.proxy_at(handle) {
self.guard_revoked(handle)?;
if let Some(keys) = self.proxy_own_keys_raw(handle)? {
return Ok(keys);
}
return self.own_property_keys_values(target);
}
let mut out = Vec::new();
for k in self.realm.own_property_names(handle).unwrap_or_default() {
out.push(self.new_str(&k));
}
// Symbol keys live directly on a genuine object cell (`object_all_keys`),
// but a non-object exotic (typed array, array, function) stores its symbol
// keys in the auxiliary object — so consult both (a cell has at most one of
// the two, so no duplication) or symbols on a typed array would be dropped
// from `[[OwnPropertyKeys]]`.
let mut seen_syms: Vec<u64> = Vec::new();
for k in self
.realm
.object_all_keys(handle)
.into_iter()
.chain(self.realm.aux_all_keys(handle))
{
if let Some(idstr) = k.strip_prefix("\u{0}sym:")
&& let Ok(id) = idstr.parse::<u64>()
&& !seen_syms.contains(&id)
&& let Some(sh) = self.realm.symbol_for_id(id)
{
seen_syms.push(id);
out.push(NanBox::handle(sh.to_raw()));
}
}
Ok(out)
}
/// CopyDataProperties(`target`, `source`, `excluded`) — the spec operation
/// shared by object spread (`{...src}`) and object-rest patterns
/// (`{...rest}` in a binding or assignment target). Copies every own
/// **enumerable** property of `source` — String **and** Symbol keys, routed
/// through the proxy `ownKeys`/`getOwnPropertyDescriptor`/`get` protocol when
/// `source` is a proxy — whose key (in internal [`member_key`] form) is not
/// in `excluded`, installing each as a plain data property on `target`. A
/// getter / `get` trap fires exactly once per key and its throw propagates.
pub(crate) fn copy_data_properties(
&mut self,
target: crate::heap::Handle,
source: crate::heap::Handle,
excluded: &[String],
) -> Result<(), ExecError> {
for key in self.own_property_keys_values(source)? {
let name = self.member_key(key);
if excluded.contains(&name) {
continue;
}
let desc = self.descriptor_of(source, &name)?;
if matches!(desc.unpack(), Unpacked::Undefined) {
continue;
}
let enumerable = desc
.as_handle()
.map(Handle::from_raw)
.and_then(|dh| self.realm.get_property(dh, "enumerable"))
.is_some_and(|v| self.realm.truthy(v));
if !enumerable {
continue;
}
let v = self.read_member(source, &name)?;
self.realm.set_property(target, &name, v);
}
Ok(())
}
pub(crate) fn member_value(&self, handle: crate::heap::Handle, key: &str) -> NanBox {
if let Some(v) = self.realm.get_property(handle, key) {
return v;
}
if key == "length" {
if let Some(len) = self.realm.array_length(handle) {
return NanBox::number(len as f64);
}
// `String.length` counts UTF-16 code units (astral chars = 2, a lone
// surrogate = 1). P3: borrow the leaf when possible so `.length` in a
// loop does not flatten the rope into an owned `Vec` on every read.
if let Some(leaf) = self.realm.string_leaf_bytes(handle) {
return NanBox::number(crate::wtf8::utf16_len(leaf) as f64);
}
if let Some(bytes) = self.realm.string_bytes(handle) {
return NanBox::number(crate::wtf8::utf16_len(&bytes) as f64);
}
}
// `Map`/`Set` expose `size`.
// `Map`/`Set` expose `.size`; the weak variants do not (no enumeration).
if key == "size"
&& !self.realm.collection_is_weak(handle)
&& let Some(n) = self.realm.collection_size(handle)
{
return NanBox::number(n as f64);
}
NanBox::undefined()
}
/// Decides whether a data-property write may proceed. A write to a
/// non-writable property (its own `writable: false`, or any property of a
/// frozen object) is a `TypeError` in strict mode and silently ignored
/// otherwise. Returns `true` when the caller should perform the write.
/// Whether `handle[key] = …` is permitted (non-throwing): the property is not
/// read-only/frozen, and either already own or the object is extensible. The shared
/// predicate behind `allow_property_write` (which adds the strict-mode throw) and
/// `Reflect.set` (which returns the boolean).
/// If `h` is a String (a string primitive cell or a String wrapper object),
/// returns its UTF-16 length — the count of own index properties ToObject(str)
/// exposes (`"0".."length-1"`). `None` for any non-string.
pub(crate) fn string_index_count(&self, h: crate::heap::Handle) -> Option<usize> {
// A String wrapper object boxes its primitive under PRIM_WRAP.
let sh = if let Some(prim) = self.realm.get_property(h, PRIM_WRAP) {
prim.as_handle().map(Handle::from_raw)?
} else {
h
};
let bytes = self.realm.string_bytes(sh)?;
Some(crate::wtf8::utf16_len(&bytes))
}
/// `Set(O, key, value, true)` — a [[Set]] whose `Throw` is true regardless of
/// the caller's strictness (used by `Object.assign`, whose CopyDataProperties
/// step always throws on a failed write). `key_name` is the string form of the
/// key (the `\0sym:` sentinel for a symbol) for the writability predicate;
/// `key_box` is the value passed to the [[Set]] machinery.
pub(crate) fn set_or_throw(
&mut self,
target: crate::heap::Handle,
key_box: NanBox,
key_name: &str,
value: NanBox,
) -> Result<(), ExecError> {
// A **proxy** performs its own `[[Set]]` (the `set` trap, or trapless
// forwarding to the target with the proxy as receiver); the ordinary
// data-write gate below inspects the proxy *cell* — which has no own keys
// and reads as non-extensible — so it would wrongly reject every write
// (e.g. `Object.assign(new Proxy({},{}), {x:1})`). Delegate straight to
// `[[Set]]`, which enforces the real invariants.
if self.realm.proxy_at(target).is_some() {
return self.assign_member_value(target, key_box, value);
}
// An own accessor takes precedence: its setter runs (and a frozen object's
// accessor is still writable through the setter), so delegate without the
// data-write gate. The `[[Set]]` path itself rejects a getter-only accessor.
let has_own_accessor = self.realm.accessor(target, key_name).is_some();
// A data write that OrdinarySet would reject (read-only / frozen property,
// or a new property on a non-extensible target) is a TypeError here even in
// sloppy mode. A property with a setter, or a writable slot, passes the
// predicate and is delegated to the normal [[Set]] (which runs setters,
// proxy traps, array-index and length handling).
if !has_own_accessor && !self.can_write_property(target, key_name) {
let add_to_non_extensible =
!self.realm.has_own(target, key_name) && !self.realm.is_extensible(target);
let m = if add_to_non_extensible {
self.new_str(&alloc::format!(
"Cannot add property '{key_name}', object is not extensible"
))
} else {
self.new_str(&alloc::format!(
"Cannot assign to read only property '{key_name}'"
))
};
return Err(ExecError::Throw(self.make_error(N_TYPE_ERROR, Some(m))));
}
self.assign_member_value(target, key_box, value)
}
pub(crate) fn can_write_property(&self, handle: crate::heap::Handle, key: &str) -> bool {
// A string's index properties (`"abc"[0]`, or `new String("abc")[0]`) are
// non-writable own data properties, so a write to an in-range index fails.
if let Ok(i) = key.parse::<usize>()
&& self.string_index_count(handle).is_some_and(|n| i < n)
{
return false;
}
let add_to_non_extensible =
!self.realm.has_own(handle, key) && !self.realm.is_extensible(handle);
let readonly = self.realm.property_is_readonly(handle, key)
|| (self.realm.is_frozen(handle) && self.realm.get_property(handle, key).is_some());
!readonly && !add_to_non_extensible
}
pub(crate) fn allow_property_write(
&mut self,
handle: crate::heap::Handle,
key: &str,
) -> Result<bool, ExecError> {
if !self.can_write_property(handle, key) {
if self.strict {
let add_to_non_extensible =
!self.realm.has_own(handle, key) && !self.realm.is_extensible(handle);
let m = if add_to_non_extensible {
self.new_str(&alloc::format!(
"Cannot add property '{key}', object is not extensible"
))
} else {
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(false); // sloppy mode: the write is silently dropped
}
Ok(true)
}
}