quickjs-pure 0.17.3

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
//! `Array` and `Array.prototype`.
//!
//! Arrays are the type a script touches most, so this is the largest module. Two
//! behaviours are worth calling out because they are easy to get subtly wrong:
//!
//! * **`length` is derived, not stored.** It is the element count, so every method
//!   that changes the length only has to change the element vector and the property
//!   reads the right answer. `a.length = n` is handled in the interpreter's
//!   property setter for the same reason.
//! * **Method names are non-enumerable.** `for (k in [])` must not list them, which
//!   is why every install goes through [`define_method`].

use crate::builtins::{arg, arg_integer_or, define_method, install_species_accessor, this_object};
use crate::interp::{Interp, JsResult};
use crate::object::{JsObject, Property, PropertyKey};
use crate::value::Value;
use js_gc::Gc;

/// Install `Array` and its prototype methods.
pub fn install(interp: &mut Interp<'_>, array_proto: &Gc<JsObject>) {
    for (name, length, func) in [
        ("push", 1, push as crate::object::NativeFn),
        ("pop", 0, pop),
        ("shift", 0, shift),
        ("unshift", 1, unshift),
        ("slice", 2, slice),
        ("splice", 2, splice),
        ("concat", 1, concat),
        ("join", 1, join),
        ("reverse", 0, reverse),
        ("indexOf", 1, index_of),
        ("lastIndexOf", 1, last_index_of),
        ("includes", 1, includes),
        ("forEach", 1, for_each),
        ("map", 1, map),
        ("filter", 1, filter),
        ("reduce", 1, reduce),
        ("reduceRight", 1, reduce_right),
        ("some", 1, some),
        ("every", 1, every),
        ("find", 1, find),
        ("findIndex", 1, find_index),
        ("fill", 1, fill),
        ("copyWithin", 2, copy_within),
        ("sort", 1, sort),
        ("flat", 0, flat),
        ("flatMap", 1, flat_map),
        ("findLast", 1, find_last),
        ("findLastIndex", 1, find_last_index),
        // The "change array by copy" family: each returns a new array and leaves the
        // receiver alone, so a frozen array can be transformed.
        ("toReversed", 0, to_reversed),
        ("toSorted", 1, to_sorted),
        ("toSpliced", 2, to_spliced),
        ("with", 2, array_with),
        ("toString", 0, to_string),
        ("toLocaleString", 0, to_locale_string),
        ("at", 1, at),
        ("values", 0, values),
        ("keys", 0, keys),
        ("entries", 0, entries),
    ] {
        define_method(array_proto, name, length, func, interp);
    }

    // `Array.prototype[Symbol.iterator]` is `values`: the spec defines iteration over an
    // array as iteration over its values, and sharing the function means a script
    // calling `a[Symbol.iterator]()` and a `for…of` get the same kind of object.
    if let Some(values_fn) = array_proto
        .own_property("values")
        .and_then(|property| property.value)
    {
        let key = interp
            .realm
            .well_known_key(crate::interp::WellKnown::Iterator);
        // `{ writable: true, enumerable: false, configurable: true }` — `Property::data`
        // makes every property enumerable, which `verifyProperty` reads back
        // (`Array/prototype/Symbol.iterator.js`).
        array_proto.define_key(&key, Property::with_attributes(values_fn, true, false));
    }

    // `Array.prototype[@@unscopables]` lists the methods that must not shadow a `with`
    // binding. The object has a **null** prototype, and each entry is a data property
    // with all three attributes true — `verifyProperty` checks exactly that.
    array_proto.define_key(
        &interp
            .realm
            .well_known_key(crate::interp::WellKnown::Unscopables),
        Property {
            value: Some(unscopables(interp)),
            writable: false,
            enumerable: false,
            configurable: true,
            ..Property::default()
        },
    );

    let constructor = interp.new_native_constructor("Array", 1, constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(array_proto.clone()), false, false),
    );
    array_proto.define(
        "constructor",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );
    for (name, length, func) in [
        ("isArray", 1, is_array as crate::object::NativeFn),
        ("from", 1, from),
        ("of", 0, of),
    ] {
        define_method(&constructor, name, length, func, interp);
    }
    let global = interp.realm.global.clone();
    global.define(
        "Array",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );
    // The constructor has to be reachable from the realm for two reasons: `ArraySpeciesCreate`
    // treats "`constructor` is the intrinsic `Array`" as "use the default", and the species
    // getter has to answer *this* function.
    interp.realm.array_constructor = Some(constructor.clone());
    install_species_accessor(&constructor, interp);
}

/// `Array(n)` makes `n` holes; `Array(a, b)` makes a two-element array.
fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // One numeric argument is a *length*, so it has to be a whole number in range:
    // `new Array(-1)` and `new Array(1.5)` are both `RangeError`, and the limit is the
    // spec's `2^32 - 1`.
    if args.len() == 1
        && let Some(length) = args[0].as_f64()
    {
        if length < 0.0 || length.fract() != 0.0 || length > 4294967295.0 {
            return Err(interp.range_error("invalid array length"));
        }
        // The prototype comes from `new.target`: `class A extends Array {}` has to make
        // `new A(3)` an `A`, and the reference builds the instance that way too.
        let array = interp.new_ctor_array()?;
        // Holes, not `undefined`: `new Array(3)` has three empty slots, so
        // `2 in new Array(3)` is false while `new Array(3).length` is 3.
        array.array_set_length(interp.heap, length as usize);
        return Ok(Value::Object(array));
    }
    let array = interp.new_ctor_array()?;
    for (index, value) in args.iter().enumerate() {
        array.array_set(interp.heap, index, value.clone());
    }
    Ok(Value::Object(array))
}

fn is_array(_interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    Ok(Value::Bool(
        arg(args, 0)
            .as_object()
            .is_some_and(|object| object.is_array()),
    ))
}

/// `Array.from(source, mapfn, thisArg)`.
///
/// `this` is the constructor to build the result with (§23.1.2.1 step 2: `Construct(C)`),
/// which is what makes `MyArray.from(...)` answer a `MyArray`. A non-constructor `this` —
/// including the plain `Array.from.call({}, ...)` case — falls back to a fresh array.
fn from(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let source = arg(args, 0);
    // §23.1.2.1 step 4: the mapper is validated *before* the source is touched, so
    // `Array.from([], null)` is a `TypeError` even though nothing would be mapped. The
    // check used to be implicit — a non-callable was only reached when there was an
    // element to map — so an empty source made it silently pass.
    let mapper = match args.get(1) {
        None | Some(Value::Undefined) => None,
        Some(value) => {
            if !matches!(value, Value::Object(object) if object.is_callable()) {
                return Err(interp.type_error("mapping function is not a function"));
            }
            Some(value.clone())
        }
    };
    let this_arg = arg(args, 2);

    // An iterable is read through `Symbol.iterator` first: a `Map` and a `Set` have no
    // `length`, so the array-like branch below finds nothing in them.
    if interp.has_iterator(&source)? {
        return from_iterable(interp, &this, &source, mapper, this_arg);
    }

    // The array-like branch: `length` is read once, then each index. `ToLength` saturates
    // and the cap keeps a hostile `{length: 2**53-1}` from being an allocation.
    let mut out = Vec::new();
    if let Value::String(text) = &source {
        for point in text.wtf8().code_points() {
            out.push(interp.string_wtf8(point));
        }
    } else if let Some(object) = source.as_object() {
        let length = interp
            .get_property(object, "length")?
            .map(|value| value.to_number())
            .unwrap_or(0.0);
        let length = to_length(length).min(MAX_FROM_LENGTH);
        for index in 0..length {
            // A missing index contributes `undefined`; the result is as long as the source
            // said, not as long as the indices that happen to exist. Skipping absent ones
            // made `Array.from({length: 2})` an empty array.
            let value = interp
                .get_property(object, &index.to_string())?
                .unwrap_or(Value::Undefined);
            out.push(match &mapper {
                None => value,
                Some(mapper) => interp.call_value(
                    mapper.clone(),
                    this_arg.clone(),
                    vec![value, crate::object::index_value(index)],
                )?,
            });
        }
    }
    fill_from_constructor(interp, &this, out)
}

/// §23.1.2.1's iterator branch: `Construct(this, 0)` first, then `next` / map /
/// `CreateDataProperty` one element at a time, then `Set(A, "length", k, true)`.
///
/// The interleaving is the whole point, and it used to be wrong: the old code drained the
/// iterator into a `Vec` and only then ran the mapper. Three things follow from the
/// correct order and none of them from the old one:
///
/// * a mapper that throws on the *first* element stops the walk — with an endless iterator
///   the old order never got to run it at all, so `Array.from(never, () => { throw x })`
///   hung instead of throwing (`Array/from/iter-map-fn-err`);
/// * abandoning the walk calls the iterator's `return`, which is what `IteratorClose`
///   requires and what `closeCount` in those tests counts;
/// * the mapper sees the *element index* as its second argument as it goes.
fn from_iterable(
    interp: &mut Interp<'_>,
    this: &Value,
    source: &Value,
    mapper: Option<Value>,
    this_arg: Value,
) -> JsResult<Value> {
    // §23.1.2.1 step 7.a: `C` is `this` when it is a constructor, else the intrinsic array.
    let constructor = match this {
        Value::Object(object) if object.is_constructor() => Some(this.clone()),
        _ => None,
    };
    // `Construct(this)` with **no** arguments — §23.1.2.1 step 7.a. Passing a length here
    // was wrong twice over: `iter-cstm-ctor` asserts `arguments.length === 0`, and
    // `Array.from.call(Object, [])` became `new Object(0)`, a boxed Number whose
    // `constructor` is `Number` (`source-object-constructor`). The length is set at the end.
    let result = match &constructor {
        Some(constructor) => {
            interp.construct(constructor.clone(), constructor.clone(), Vec::new())?
        }
        None => Value::Object(interp.new_array(Vec::new())),
    };
    let Some(object) = result.as_object().cloned() else {
        return Err(interp.type_error("constructor did not answer an object"));
    };

    let iterator = interp.get_iterator(source)?;
    let mut index = 0usize;
    loop {
        let (element, done) = interp.iterator_step(&iterator)?;
        if done {
            break;
        }
        // The cap that makes a never-ending iterator a `RangeError` rather than a hang.
        // It is checked before the mapper runs, so a mapper that would have thrown still
        // gets its chance on the elements up to here.
        if index >= MAX_FROM_LENGTH {
            close_iterator(interp, &iterator)?;
            return Err(interp.range_error("invalid array length"));
        }
        let value = match &mapper {
            None => element,
            Some(mapper) => {
                match interp.call_value(
                    mapper.clone(),
                    this_arg.clone(),
                    vec![element, crate::object::index_value(index)],
                ) {
                    Ok(value) => value,
                    Err(signal) => {
                        // §7.4.6 `IteratorClose` before the error propagates: a mapper that
                        // throws must not leave the iterator open. The original error is what
                        // surfaces, not whatever `return` answered.
                        close_iterator_after_throw(interp, &iterator)?;
                        return Err(signal);
                    }
                }
            }
        };
        if let Err(signal) = interp.create_data_property_or_throw(&object, index, value) {
            close_iterator_after_throw(interp, &iterator)?;
            return Err(signal);
        }
        index += 1;
    }
    // §23.1.2.1 step 8.i: `Set(A, "length", k, true)`.
    set_result_length(interp, &object, index)?;
    Ok(Value::Object(object))
}

/// §7.4.6 `IteratorClose`, for the case where an error is *already* propagating.
///
/// §7.4.6 step 5.5 makes a `return` that answers a non-object a `TypeError`, but step 6
/// says that when the completion is a throw, "return the original completion" — the
/// original error wins. Getting this backwards turned `iter-map-fn-err` red: its `return`
/// answers `undefined`, so the mapper's `Test262Error` was replaced by our `TypeError`.
///
/// An error *from calling* `return` still propagates, which is the difference between the
/// two halves of step 6 and what `iter-map-fn-return` checks.
fn close_iterator_after_throw(
    interp: &mut Interp<'_>,
    iterator: &crate::interp::Iterator,
) -> JsResult<()> {
    let method = interp.read_field(&iterator.object, "return")?;
    if matches!(method, Value::Undefined | Value::Null) {
        return Ok(());
    }
    if !matches!(&method, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("iterator return is not a function"));
    }
    // The answer is deliberately not checked: it cannot replace the pending error.
    interp.call_value(method, iterator.object.clone(), Vec::new())?;
    Ok(())
}

/// §7.4.6 `IteratorClose` for a completed walk, where the `return` result is observable.
fn close_iterator(interp: &mut Interp<'_>, iterator: &crate::interp::Iterator) -> JsResult<()> {
    let method = interp.read_field(&iterator.object, "return")?;
    if matches!(method, Value::Undefined | Value::Null) {
        return Ok(());
    }
    if !matches!(&method, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("iterator return is not a function"));
    }
    let answer = interp.call_value(method, iterator.object.clone(), Vec::new())?;
    if !matches!(answer, Value::Object(_)) {
        return Err(interp.type_error("iterator must return an object"));
    }
    Ok(())
}

/// `Array.of(...items)`: the same "build through `this`" rule as `from`, without a source.
fn of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    fill_from_constructor(interp, &this, args.to_vec())
}

/// Build `values` into `Construct(C, «values.len()»)` when `C` is a constructor.
///
/// The `IsConstructor(C)` test comes *after* the source has been read, as the spec orders
/// it, and a non-constructor `this` is not an error — it means "the intrinsic array".
fn fill_from_constructor(
    interp: &mut Interp<'_>,
    this: &Value,
    values: Vec<Value>,
) -> JsResult<Value> {
    let constructor = match this {
        Value::Object(object) if object.is_constructor() => Some(this.clone()),
        _ => None,
    };
    let Some(constructor) = constructor else {
        let array = interp.new_array(values);
        return Ok(Value::Object(array));
    };
    let created = interp.construct(
        constructor.clone(),
        constructor,
        vec![Value::Int(values.len() as i32)],
    )?;
    let Some(object) = created.as_object().cloned() else {
        return Err(interp.type_error("constructor did not answer an object"));
    };
    for (index, value) in values.into_iter().enumerate() {
        interp.create_data_property_or_throw(&object, index, value)?;
    }
    Ok(Value::Object(object))
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

/// `Set(A, "length", len, true)`: the last step of the methods that grow their result.
///
/// A species may answer a plain object, and a plain object's `length` is an ordinary
/// property rather than the element vector's derived count.
fn set_result_length(interp: &mut Interp<'_>, object: &Gc<JsObject>, len: usize) -> JsResult<()> {
    if object.is_array() {
        object.array_set_length(interp.heap, len);
        return Ok(());
    }
    interp.set_property(object, "length", Value::Int(len as i32))
}

/// The receiver as an array, or as an array-like copied into one.
/// Array methods are generic in the spec: `Array.prototype.join.call({length:2,0:'a',1:'b'})`
/// has to work. Rather than thread "maybe not an array" through every method, a
/// non-array receiver is copied up front, which is correct for every method that only
/// reads, and harmless for the ones that also write.
fn receiver(interp: &mut Interp<'_>, this: &Value) -> JsResult<Gc<JsObject>> {
    this_object(interp, this)
}

/// The length a loop over the receiver runs to, read once before it starts.
///
/// Read once, not per iteration: the spec captures `len` up front, so a callback that
/// pushes to the array does not extend the loop — but a callback that *deletes* does
/// shorten what is seen, because each element is read when it is reached.
fn receiver_length(interp: &mut Interp<'_>, object: &Gc<JsObject>) -> JsResult<usize> {
    length_of(interp, &Value::Object(object.clone()))
}

/// Element `index`, or `None` when the receiver has no such property.
///
/// `None` and `Some(Value::Undefined)` are different answers on purpose: a hole is
/// skipped by `map`, `forEach` and `reduce`, but read as `undefined` by `find` and
/// `includes`. A snapshot of the element vector could not tell them apart at the right
/// moment, and one that flattened the difference made `includes` miss holes entirely.
///
/// Cost matters here: this runs once per index, so it must not clone the element vector.
/// An earlier version asked `array_elements()` — which clones all of it — and turned
/// `[0,1,...,"five"]` with `arr[999999]` set (a hundred thousand holes) into quadratic
/// work, which is how six conformance tests turned from passes into hangs.
fn receiver_element(
    interp: &mut Interp<'_>,
    object: &Gc<JsObject>,
    index: usize,
) -> JsResult<Option<Value>> {
    // A plain array element, read in place.
    if object.proxy_state().is_none()
        && object.is_array()
        && let Some(value) = object.array_get(index)
        && !matches!(value, Value::Hole)
    {
        return Ok(Some(value));
    }
    // Everything else is one `[[Get]]`: it consults a typed array's buffer, the property
    // table and then the prototype chain, in that order, and answers `None` only when the
    // property is genuinely absent. A hole is not an own property, so
    // `Array.prototype[4] = 5` is still seen through `[1,2,3,4,]`.
    //
    // Note that this is deliberately *only* `[[Get]]`. On a typed array an index the buffer
    // no longer covers answers `undefined` here — that is what `[[Get]]` says — even though
    // `[[HasProperty]]` says the index is absent. The methods that the spec makes ask
    // `HasProperty` first therefore call [`receiver_has_index`]; `includes` and `find` do not
    // ask, and must keep seeing `undefined`.
    interp.get_property_key(object, &PropertyKey::from(index.to_string()))
}

/// `HasProperty(O, 𝔽(index))`, which the iteration methods ask before every `[[Get]]`.
///
/// The dense shortcut keeps a plain array cheap; everything else goes through the real
/// internal method. The distinction is observable on an integer-indexed exotic object: an
/// index the buffer no longer covers is *absent*, so `Array.prototype.every` over a typed
/// array must skip it rather than pass `undefined` to the callback — which is what
/// `every/callbackfn-resize-arraybuffer` asserts after a mid-iteration `resize`.
fn receiver_has_index(
    interp: &mut Interp<'_>,
    object: &Gc<JsObject>,
    index: usize,
) -> JsResult<bool> {
    if object.proxy_state().is_none()
        && object.is_array()
        && let Some(value) = object.array_get(index)
        && !matches!(value, Value::Hole)
    {
        return Ok(true);
    }
    interp.has_own_or_inherited(object, &PropertyKey::from(index.to_string()))
}

/// `HasProperty(O, key)`: whether an index is present, proxy traps included.
///
/// Distinct from [`receiver_element`] answering `Some`: `[[Get]]` on a proxy forwards to the
/// target and answers `undefined` for a key the target does not have, so a "get is not
/// undefined" test reads an absent element as present. The spec only ever asks
/// `HasProperty` — `copyWithin`, `sort`'s hole detection and `Object.keys` all depend on the
/// difference.
fn receiver_has(interp: &mut Interp<'_>, object: &Gc<JsObject>, index: usize) -> JsResult<bool> {
    if object.proxy_state().is_none()
        && object.is_array()
        && let Some(value) = object.array_get(index)
        && !matches!(value, Value::Hole)
    {
        return Ok(true);
    }
    interp.has_property_key(object, &PropertyKey::from(index.to_string()))
}

/// The elements of an array, reading through a proxy's `get` trap when it is one.
///
/// This is the single entry point every array method uses, which is why the proxy case
/// belongs here rather than in each method: a proxy of an array has no element vector of
/// its own, so reading one directly answered "empty array" for every higher-order method
/// — `Array.prototype.map.call(proxyOfArray, f)` silently produced `[]`.
fn elements(interp: &mut Interp<'_>, object: &Gc<JsObject>) -> JsResult<Vec<Value>> {
    if object.proxy_state().is_some() {
        let length = length_of(interp, &Value::Object(object.clone()))?;
        let mut out = Vec::with_capacity(length);
        for index in 0..length {
            let key = PropertyKey::from(index.to_string());
            out.push(
                interp
                    .get_property_key(object, &key)?
                    .unwrap_or(Value::Undefined),
            );
        }
        return Ok(out);
    }
    // The dense vector is only the *prefix*: an array's `length` may exceed it, and the
    // difference is trailing holes. `new Array(3).fill(1)` has an empty vector and
    // `length: 3`, so returning the vector alone made `fill` write nothing at all. The
    // vector is not padded here — that would allocate the holes this change exists to
    // avoid — so the caller has to compare against `array_length`.
    Ok(object.array_elements().unwrap_or_default())
}

/// The `thisArg` of a callback-taking method: the **second** argument, or `undefined`.
///
/// Every one of `forEach`/`map`/`filter`/`some`/`every`/`find`/`findIndex`/`flatMap`
/// reads it from here. They used to pass `Value::Undefined` to `[[Call]]` outright, which
/// is invisible in the common `arr.map(f)` case but wrong for `arr.map(f, x)` — 159
/// test262 cases are nothing but `assert(this === thisArg)` inside the callback.
///
/// `reduce`/`reduceRight` are the exception: their second argument is the *initial
/// accumulator*, so they have no `thisArg` at all.
pub(crate) fn callback_this(args: &[Value]) -> Value {
    args.get(1).cloned().unwrap_or(Value::Undefined)
}

/// Normalise a possibly negative index the way every array method does.
fn normalise(index: f64, length: usize) -> usize {
    if index.is_nan() {
        return 0;
    }
    if index < 0.0 {
        let from_end = length as f64 + index;
        if from_end < 0.0 { 0 } else { from_end as usize }
    } else if index > length as f64 {
        length
    } else {
        index as usize
    }
}

// ---------------------------------------------------------------------------
// Basic mutation
// ---------------------------------------------------------------------------

fn push(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // The receiver itself, not a copy: §23.1.3.20 is `Set(O, ToString(len), E, true)`, so
    // `push.call({length: 0}, 1)` has to define `"0"` on the argument object. Copying it
    // first made every generic-receiver case silently do nothing — and made
    // `push.call({length: 2**32})` a `RangeError` from the copy cap rather than a
    // `TypeError` from the failed `Set`.
    let array = receiver(interp, &this)?;
    let mut length = receiver_length(interp, &array)?;
    // §23.1.3.24 step 6, before a single element is written: `len + argCount` past
    // `2^53 - 1` is a `TypeError`. It used to be missing, so `push.call({length: 2**53-1}, 1)`
    // answered `2^53` — a `length` no longer exactly representable — instead of throwing.
    check_integer_limit(interp, length, args.len())?;
    // The hot path, and the reason it exists: `push` is the single most common write in
    // real code, and going through `[[Set]]` for the index *and* for `length` on every
    // element costs ~10x (`array:push` measured 0.19x of the reference before this).
    //
    // The conditions are the ones that make the element vector the authority for both the
    // index and `length`: a plain array, extensible, writable elements, no recorded element
    // descriptor. `array_set` extends `length` itself, so the `Set(O, "length", …)` step the
    // spec spells out per iteration has nothing left to do.
    // `Set(O, ToString(len), E, true)` consults the **prototype chain** first — a hole is
    // not an own property — so the fast path is only equivalent while no prototype holds an
    // index. `Array.prototype[0]` with a setter must run, and the setter may freeze the
    // array or make `length` read-only, which the final step then reports
    // (`push/set-length-array-is-frozen`, `push/set-length-array-length-is-non-writable`).
    let dense = array.is_array()
        && array.elements_writable()
        && !array.has_element_descriptors()
        && array.is_extensible()
        && !interp.prototype_chain_has_indexed_property(&array);
    for value in args {
        if dense && array.array_set(interp.heap, length, value.clone()) {
            length += 1;
            continue;
        }
        // `Set(O, key, value, true)`: a non-extensible receiver refuses the new index, and
        // a length that cannot be represented is a `TypeError` rather than a wrapped number.
        write_element(interp, &array, length, value.clone())?;
        length += 1;
        interp.set_property(&array, "length", crate::object::length_value(length))?;
    }
    // §23.1.3.24 step 7: `Set(O, "length", len, true)` runs even with no arguments, and
    // it is observable. `push.call({length: 2**53})` must *clamp* the stored `length` to
    // `2^53 - 1` — without this step the property kept its old value and the method
    // answered a length it never wrote (`Array/prototype/push/clamps-to-integer-limit`).
    interp.set_property(&array, "length", crate::object::length_value(length))?;
    Ok(crate::object::length_value(length))
}

fn pop(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // The *logical* length: `new Array(2)` has two holes and no storage, so popping it
    // has to shorten `length` to 1 and answer `undefined`. Reading the dense vector
    // instead saw an empty array and left the length alone.
    let length = receiver_length(interp, &array)?;
    if length == 0 {
        interp.set_property(&array, "length", Value::Int(0))?;
        return Ok(Value::Undefined);
    }
    let index = length - 1;
    let value = receiver_element(interp, &array, index)?.unwrap_or(Value::Undefined);
    // `DeletePropertyOrThrow` then `Set(O, "length", …)`: a non-configurable element is a
    // `TypeError`, not a silently ignored deletion.
    if !interp.delete_property(&array, &index.to_string())? {
        return Err(interp.type_error(format!("cannot delete property '{index}'")));
    }
    interp.set_property(&array, "length", crate::object::length_value(index))?;
    Ok(value)
}

fn shift(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    let length = receiver_length(interp, &array)?;
    if length == 0 {
        interp.set_property(&array, "length", Value::Int(0))?;
        return Ok(Value::Undefined);
    }
    let first = receiver_element(interp, &array, 0)?.unwrap_or(Value::Undefined);
    // Each element moves down one, and a hole at the source deletes its destination
    // (§23.1.3.29 step 10.c). The last slot is deleted rather than left behind.
    for index in 1..length {
        if receiver_has(interp, &array, index)? {
            let value = receiver_element(interp, &array, index)?.unwrap_or(Value::Undefined);
            write_element(interp, &array, index - 1, value)?;
        } else if !interp.delete_property(&array, &(index - 1).to_string())? {
            return Err(interp.type_error("cannot delete property"));
        }
    }
    let last = length - 1;
    if !interp.delete_property(&array, &last.to_string())? {
        return Err(interp.type_error("cannot delete property"));
    }
    interp.set_property(&array, "length", crate::object::length_value(last))?;
    Ok(first)
}

fn unshift(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    let length = receiver_length(interp, &array)?;
    let count = args.len();
    // §23.1.3.34 step 4.a: with `argCount > 0`, `len + argCount > 2^53 - 1` throws a
    // `TypeError` *before* the shifting loop. This is the hang the missing check caused:
    // `var a = []; a.length = 2**32-1; a.unshift(1)` fell into `for index in (0..length).rev()`
    // and never returned, which no CPU quota can distinguish from work.
    if count > 0 {
        check_integer_limit(interp, length, count)?;
    }
    // Backwards, so an element is never overwritten before it has been read
    // (§23.1.3.34 step 5.c).
    if count > 0 {
        for index in (0..length).rev() {
            let from = index;
            let to = index + count;
            if receiver_has(interp, &array, from)? {
                let value = receiver_element(interp, &array, from)?.unwrap_or(Value::Undefined);
                write_element(interp, &array, to, value)?;
            } else if !interp.delete_property(&array, &to.to_string())? {
                return Err(interp.type_error("cannot delete property"));
            }
        }
        for (offset, value) in args.iter().enumerate() {
            write_element(interp, &array, offset, value.clone())?;
        }
        let new_length = length + count;
        interp.set_property(&array, "length", crate::object::length_value(new_length))?;
        return Ok(crate::object::length_value(new_length));
    }
    // `unshift()` with no arguments still performs the `Set(O, "length", len, true)` step
    // (§23.1.3.34 step 6), which is observable through a `set` trap or a read-only
    // `length`. The loop is skipped entirely, so nothing is shifted.
    interp.set_property(&array, "length", crate::object::length_value(length))?;
    Ok(crate::object::length_value(length))
}

// ---------------------------------------------------------------------------
// Reading
// ---------------------------------------------------------------------------

fn slice(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // The receiver's `length` is **not** validated. §23.1.3.28 only ever builds an array as
    // long as `end - start`, so a `{length: 2**53 + 2}` array-like sliced down to two
    // elements is legal — the old `array_create_length(receiver_length)` refused it with a
    // `RangeError` about an array it never needed to build
    // (`slice/length-exceeding-integer-limit`). Only the species' `count` is checked, and
    // `array_species_create` does that.
    let length = receiver_length(interp, &array)?;
    let start = normalise(arg_integer_or(interp, args, 0, 0.0)? as i64 as f64, length);
    let end = normalise(
        match args.get(1) {
            None | Some(Value::Undefined) => length as f64,
            // `ToIntegerOrInfinity`, not `to_number`: the argument may be an object, and
            // `Value::to_number` on one answers `NaN` without ever running its `valueOf`.
            // `slice(0, {valueOf: () => 3})` therefore returned an empty array where the
            // spec (and the reference) answer three elements (`S15.4.4.10_A2.2_T5`).
            // `arg_integer_or` *is* `ToIntegerOrInfinity`, so it is reused rather than
            // re-spelled.
            Some(value) => {
                let number = interp.to_js_number(value)?;
                if number.is_nan() { 0.0 } else { number.trunc() }
            }
        },
        length,
    );
    let count = end.max(start) - start;
    // `ArraySpeciesCreate(O, count)` before any element is read.
    let result = interp.array_species_create(&this, count)?;
    for index in start..end.max(start) {
        // A hole stays a hole: `[1,,3].slice(0)` keeps the gap.
        if let Some(value) = receiver_element(interp, &array, index)? {
            interp.create_data_property_or_throw(&result, index - start, value)?;
        }
    }
    Ok(Value::Object(result))
}

/// Whether `value` is spread by `concat`: an array, or anything that says so through
/// `Symbol.isConcatSpreadable`.
///
/// A plain array-like object is *not* spread — `[{length: 2}]` concatenates one element —
/// so `length` alone is not the test. Reading the symbol is what makes
/// `Array.prototype.concat.call(arrayLike)` behave, and its absence is why those caught
/// the receiver as a single element.
fn is_concat_spreadable(interp: &mut Interp<'_>, value: &Value) -> JsResult<bool> {
    let Some(object) = value.as_object() else {
        return Ok(false);
    };
    let key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::IsConcatSpreadable);
    // An explicit `undefined` does *not* mean "not spreadable": IsConcatSpreadable only
    // consults the symbol when the value is not undefined, and otherwise falls back to
    // `Array.isArray`. Reading it as a boolean made `a[Symbol.isConcatSpreadable] =
    // undefined` stop a plain array from spreading.
    if let Some(flag) = interp.get_property_key(object, &key)?
        && !matches!(flag, Value::Undefined)
    {
        return Ok(flag.to_boolean());
    }
    Ok(object.is_array())
}

fn concat(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // §23.1.3.2's order is: `ArraySpeciesCreate` first, then the per-item
    // `@@isConcatSpreadable` reads, with each item's elements written into the result as it
    // is reached. Note that *every* item goes through `IsConcatSpreadable`, the receiver
    // included — there is no "it is an array, skip the read" shortcut, and
    // `is-concat-spreadable-get-order` installs a getter on an array to prove it.
    //
    // Gathering the elements first and asking species at the end is what the old code did,
    // and it is observably different: `is-concat-spreadable-get-order` installs a
    // `constructor` getter and a `@@isConcatSpreadable` getter on the same object and
    // asserts the order is `["constructor", "isConcatSpreadable"]`.
    //
    // Building the result incrementally also means the species constructor may see a
    // partly-filled array, which is why the writes go through
    // `CreateDataPropertyOrThrow` rather than a vector then a bulk fill.
    let result = interp.array_species_create(&this, 0)?;
    let mut next = 0usize;
    // The receiver is spread when it is *not* an array and says so, and appended whole
    // otherwise: `concat.call(1)` is `[1]`, not the (empty) list of the box's indexed
    // properties.
    let receiver_value = Value::Object(array.clone());
    if is_concat_spreadable(interp, &receiver_value)? {
        let elements = spread_into_concat(interp, &array, next)?;
        for value in elements {
            concat_append(interp, &result, &mut next, value)?;
        }
    } else {
        concat_append(interp, &result, &mut next, receiver_value)?;
    }
    for value in args {
        if is_concat_spreadable(interp, value)? {
            let Some(object) = value.as_object() else {
                continue;
            };
            // A string is spread by code unit, not by code point.
            let elements = spread_into_concat(interp, object, next)?;
            for element in elements {
                concat_append(interp, &result, &mut next, element)?;
            }
        } else {
            concat_append(interp, &result, &mut next, value.clone())?;
        }
    }
    Ok(Value::Object(result))
}

/// Write one `concat` element into the result at `next`, and advance it.
///
/// `§23.1.3.2` step 5.e.iii is `CreateDataPropertyOrThrow(n, P, …)`: the write is a
/// *definition*, so a species result with a read-only index refuses it instead of the value
/// being dropped.
fn concat_append(
    interp: &mut Interp<'_>,
    result: &Gc<JsObject>,
    next: &mut usize,
    value: Value,
) -> JsResult<()> {
    let index = *next;
    *next += 1;
    // A `2^53 - 1` result length cannot be reached through `concat` in finite time, but the
    // spec checks it and the check is what turns an absurd `length` into a `RangeError`
    // rather than a loop that never ends.
    if index > MAX_INTEGER {
        return Err(interp.type_error("invalid array length"));
    }
    interp.create_data_property_or_throw(result, index, value)
}

/// Read a spreadable's elements for `concat`, refusing before the read when the result
/// would pass `2^53 - 1` (§23.1.3.2 step 5.b.iv).
///
/// The check has to run *before* the elements are read, not after: that is what made the
/// missing check a hang rather than a wrong answer. `[1].concat({length: 2**53-1,
/// [Symbol.isConcatSpreadable]: true})` looped to `2^53 - 1` reading absent indices and
/// never came back.
fn spread_into_concat(
    interp: &mut Interp<'_>,
    object: &Gc<JsObject>,
    so_far: usize,
) -> JsResult<Vec<Value>> {
    // The length is read once, here, and the elements are gathered from that same value —
    // reading it again would run a `length` getter twice.
    let length = receiver_length(interp, object)?;
    match so_far.checked_add(length) {
        Some(total) if total <= MAX_INTEGER => {}
        _ => return Err(interp.type_error("invalid array length")),
    }
    let mut out = Vec::with_capacity(length.min(1024));
    for index in 0..length {
        out.push(receiver_element(interp, object, index)?.unwrap_or(Value::Hole));
    }
    Ok(out)
}

fn join(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // §23.1.3.13 steps 2–4: `len` is read **before** the separator is converted. The order
    // is observable — a separator whose `toString` resizes a resizable `ArrayBuffer` under
    // a typed-array receiver changes what a later read would answer, and `join` must use the
    // length it saw first (`join/coerced-separator-grow`, `…-shrink`).
    let length = receiver_length(interp, &array)?;
    let separator = match args.first() {
        None | Some(Value::Undefined) => ",".to_string(),
        Some(value) => interp.to_js_string(value)?,
    };
    // A hole joins as an empty field, exactly as `undefined` does; the difference is
    // only visible to `forEach` and the debug printer. An element that is an object
    // goes through `ToString`, so a boxed number joins as `"1"`.
    let mut parts = Vec::with_capacity(length);
    for index in 0..length {
        let part = match receiver_element(interp, &array, index)? {
            None | Some(Value::Undefined) | Some(Value::Null) => String::new(),
            Some(other) => interp.to_js_string(&other)?,
        };
        parts.push(part);
    }
    Ok(interp.string(parts.join(&separator)))
}

/// §23.1.3.33 `Array.prototype.toString ( )`.
///
/// **Not** `join` spelled differently: the spec goes through `Get(O, "join")` and falls
/// back to `%Object.prototype.toString%` when that is not callable. Two test262 cases turn
/// on the fallback, and both got an empty string from calling `join` directly:
///
/// * `Array.prototype.toString.call(true)` — `ToObject(true)` is a `Boolean` wrapper, whose
///   `join` is `undefined`, so the answer is `[object Boolean]`;
/// * `Array.prototype.toString.call({join: null})` — likewise `[object Object]`.
fn to_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let object = receiver(interp, &this)?;
    let join = interp.get_property(&object, "join")?;
    if let Some(Value::Object(function)) = &join
        && function.is_callable()
    {
        return interp.call_value(join.unwrap_or(Value::Undefined), this, Vec::new());
    }
    // The **intrinsic** `%Object.prototype.toString%`, which is why it is remembered in the
    // realm rather than read off `Object.prototype`: `non-callable-join-string-tag` deletes
    // the property and still expects `[object Object]` for every receiver below.
    match interp.realm.object_proto_to_string.clone() {
        Some(fallback) => {
            interp.call_value(Value::Object(fallback), Value::Object(object), Vec::new())
        }
        None => Err(interp.type_error("Object.prototype.toString is missing")),
    }
}

fn index_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    let length = receiver_length(interp, &array)?;
    // §23.1.3.14 step 3: an empty receiver answers -1 *before* `fromIndex` is coerced,
    // so a poisoned `valueOf` on it must not run.
    if length == 0 {
        return Ok(Value::Int(-1));
    }
    let needle = arg(args, 0);
    let start = relative_index(interp, args.get(1), length)?;
    // A hole is skipped, which is why `[1,,3].indexOf(undefined)` is -1.
    //
    // The scan is bounded by *iterations performed*, not by the range's size. §23.1.3.15
    // walks `start..len`, which for `{0: 0, length: Infinity}` is unbounded — but that
    // receiver is found at index 0, so the honest answer is 0, not a `RangeError`. A
    // bound on the range refused it and turned four conformance tests red. Counting the
    // iterations keeps the early exit and still stops the scan that would never end.
    for index in start..length {
        if index.saturating_sub(start) > MAX_ARRAY_LIKE {
            return Err(interp.range_error("array-like length is too large to search"));
        }
        // §23.1.3.15 step 8.e: `HasProperty(O, ToString(k))` **before** `[[Get]]`. Asking
        // only for the value skips the difference, which is observable in two ways: an
        // absent index must not run a `get` trap on a proxy in the chain, and the array may
        // have been truncated by the `fromIndex` coercion in the meantime —
        // `calls-only-has-on-prototype-after-length-zeroed` counts the traps.
        if receiver_has_index(interp, &array, index)?
            && let Some(value) = receiver_element(interp, &array, index)?
            && value.strict_equals(&needle)
        {
            return Ok(crate::object::index_value(index));
        }
    }
    Ok(Value::Int(-1))
}

fn last_index_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    let length = receiver_length(interp, &array)?;
    let needle = arg(args, 0);
    if length == 0 {
        return Ok(Value::Int(-1));
    }
    // `fromIndex` defaults to `len - 1` **only when the argument is absent**: an explicit
    // `undefined` is `ToIntegerOrInfinity(undefined)`, which is 0, so
    // `[1,2,1].lastIndexOf(2, undefined)` is -1 rather than 1. The start used to be
    // hardwired to the last element, so every explicit `fromIndex` was ignored —
    // `[1,2,3].lastIndexOf(3, 1)` answered `2`.
    let from = match args.get(1) {
        None => length as f64 - 1.0,
        Some(value) => to_integer_or_infinity(interp, value)?,
    };
    // Negative counts from the end, and `fromIndex` past the end clamps to the last
    // element (unlike `indexOf`, where it clamps to one past the end).
    let start = if from >= 0.0 {
        (from.min(length as f64 - 1.0)) as usize
    } else {
        let behind = length as f64 + from;
        if behind < 0.0 {
            return Ok(Value::Int(-1));
        }
        behind as usize
    };
    // Bound on iterations, not on `start`: `{length: 2^53-1}` with the element right at
    // `fromIndex` must still answer immediately (that is `length-near-integer-limit`).
    // Refusing the range up front turned it red.
    for index in (0..=start).rev() {
        if start.saturating_sub(index) > MAX_ARRAY_LIKE {
            return Err(interp.range_error("array-like length is too large to search"));
        }
        // §23.1.3.17 step 8.e, the mirror of `indexOf`: `HasProperty` first, so an absent
        // index does not run a `get` trap (`calls-only-has-on-prototype-after-length-
        // zeroed` for the backwards walk).
        if receiver_has_index(interp, &array, index)?
            && let Some(value) = receiver_element(interp, &array, index)?
            && value.strict_equals(&needle)
        {
            return Ok(crate::object::index_value(index));
        }
    }
    Ok(Value::Int(-1))
}

/// `ToIntegerOrInfinity`: truncate toward zero, keep `±Infinity`, `NaN` becomes 0.
fn to_integer_or_infinity(interp: &mut Interp<'_>, value: &Value) -> JsResult<f64> {
    let number = interp.to_js_number(value)?;
    if number.is_nan() {
        return Ok(0.0);
    }
    Ok(number.trunc())
}

fn includes(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    let needle = arg(args, 0);
    let length = receiver_length(interp, &array)?;
    // §23.1.3.13 step 4: an empty array answers `false` **before** `ToIntegerOrInfinity` of
    // `fromIndex`, so a `fromIndex` whose `valueOf` is observable is never converted. The
    // order matters only through side effects, which is exactly what
    // `length-zero-returns-false` counts.
    if length == 0 {
        return Ok(Value::Bool(false));
    }
    let start = normalise(arg_integer_or(interp, args, 1, 0.0)? as i64 as f64, length);
    // `includes` uses SameValueZero, so it finds `NaN` where `indexOf` cannot — and it
    // uses `Get`, so a hole reads as `undefined` and is found, unlike with `indexOf`.
    for index in start..length {
        let Some(value) = receiver_element(interp, &array, index)? else {
            if matches!(needle, Value::Undefined) {
                return Ok(Value::Bool(true));
            }
            continue;
        };
        if value.strict_equals(&needle)
            || (matches!(value, Value::Float(f) if f.is_nan())
                && matches!(needle, Value::Float(f) if f.is_nan()))
        {
            return Ok(Value::Bool(true));
        }
    }
    Ok(Value::Bool(false))
}

fn at(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    let count = receiver_length(interp, &array)?;
    let length = count as f64;
    let raw = arg_integer_or(interp, args, 0, 0.0)? as i64 as f64;
    let index = if raw < 0.0 { length + raw } else { raw };
    if index < 0.0 || index >= length {
        return Ok(Value::Undefined);
    }
    // A hole reads as `undefined` here, not as the `Hole` sentinel: the element vector
    // is not what the spec reads.
    Ok(receiver_element(interp, &array, index as usize)?.unwrap_or(Value::Undefined))
}

// ---------------------------------------------------------------------------
// Iterators
// ---------------------------------------------------------------------------

/// `arr.values()`, `arr.keys()`, `arr.entries()`.
///
/// The result is an ordinary object with a `next` method, which is all a `for-of`
/// needs once the interpreter accepts a `next`-carrying object as an iterator. The
/// `ArrayIterator` class itself (and `Symbol.iterator`) arrives with symbols.
fn values(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    iterator(interp, this, IteratorKind::Value, ARRAY_ITERATOR_TAG)
}

fn keys(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    iterator(interp, this, IteratorKind::Key, ARRAY_ITERATOR_TAG)
}

fn entries(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    iterator(interp, this, IteratorKind::Entry, ARRAY_ITERATOR_TAG)
}

/// `%ArrayIteratorPrototype%[@@toStringTag]`, and the tag a typed array's iterator shares
/// (§23.2.3.x makes `%TypedArray%.prototype.values` answer an array iterator).
pub(crate) const ARRAY_ITERATOR_TAG: &str = "Array Iterator";

/// What an array iterator yields.
///
/// Shared with `Map` and `Set`, which hand their own snapshot to the same machinery rather
/// than growing a second iterator implementation.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum IteratorKind {
    Value,
    Key,
    Entry,
}

/// `tag` names the iterator *kind* — `"Array Iterator"`, `"Map Iterator"` — because that
/// string is the `@@toStringTag` of the prototype the new object gets.
///
/// Map, Set and String reuse this machinery, and each one has to pass its own tag: they
/// used to hard-code `"Array Iterator"` here, which made **every** iterator's
/// `Object.getPrototypeOf` the same object — so `new Map().keys()` reported
/// `[object Array Iterator]` and `MapIteratorPrototype/Symbol.toStringTag.js` could not be
/// satisfied by any fix at the `Map` end.
pub(crate) fn iterator(
    interp: &mut Interp<'_>,
    this: Value,
    kind: IteratorKind,
    tag: &str,
) -> JsResult<Value> {
    make_iterator(interp, this, kind, tag, array_iterator_next)
}

/// `%String.prototype%[@@iterator]`: same machinery, but stepping by **code point**.
///
/// `[...str]` and `str[0]` disagree on purpose — iteration keeps a surrogate pair together
/// while indexing exposes one code unit — so this needs its own `next` rather than reusing
/// the array one. The source is `ToString(this)` up front (§22.1.5.1 step 2), which also
/// makes `String.prototype[Symbol.iterator].call(123)` iterate `"123"`.
pub(crate) fn string_iterator(interp: &mut Interp<'_>, this: Value) -> JsResult<Value> {
    // `ToString`, keeping the `Wtf8` form: a `String` would have to turn a lone surrogate
    // into U+FFFD and `[...'\ud800']` has to yield the lone surrogate back.
    let text = match &this {
        Value::String(text) => text.clone(),
        Value::Undefined | Value::Null => {
            return Err(interp.type_error("cannot convert undefined or null to object"));
        }
        other => {
            let primitive = interp.to_primitive(other.clone(), crate::interp::Hint::String)?;
            match primitive {
                Value::String(text) => text,
                // Everything else is rendered, then read back out of the resulting string
                // value: this keeps the `Wtf8` without a second conversion API.
                other => match interp.string(other.to_js_string()) {
                    Value::String(text) => text,
                    _ => unreachable!("interp.string always answers a string"),
                },
            }
        }
    };
    make_iterator(
        interp,
        Value::String(text),
        IteratorKind::Value,
        "String Iterator",
        string_iterator_next,
    )
}

fn make_iterator(
    interp: &mut Interp<'_>,
    this: Value,
    kind: IteratorKind,
    tag: &str,
    next: crate::object::NativeFn,
) -> JsResult<Value> {
    // `ToObject(this)` happens *here*, not on the first `next`: §22.1.5.x step 1 is
    // `Let O be ToObject(this value); ReturnIfAbrupt(O)`, so
    // `Array.prototype.entries.call(undefined)` throws immediately. Deferring it to the
    // first step made the same call answer a perfectly good iterator.
    let source = match &this {
        Value::Undefined | Value::Null => {
            return Err(interp.type_error("cannot convert undefined or null to object"));
        }
        Value::Object(_) => this,
        primitive => Value::Object(interp.object_from(primitive)?),
    };
    // The source is kept as an object, **not** materialised: the array methods copy an
    // array-like up front, but an iterator must not, because
    // `Array.prototype.keys.call({length: 2**32 + 1})` is legal and only advances a
    // few steps before `break`.
    let proto = interp.new_iterator_prototype(tag, next);
    let object = interp.new_object(Some(proto));
    // **Internal slots**, not properties: `[[IteratedArrayLike]]`, `[[ArrayLikeNextIndex]]`
    // and `[[ArrayLikeIterationKind]]`. §23.1.5.2.1 step 3 is
    // `If O does not have all of those internal slots, throw a TypeError`, and two test262
    // cases pin the two ways a property is not a slot:
    // `ArrayIteratorPrototype/next/non-own-slots` (`Object.create(iterator).next()` — an
    // inherited copy is not the state) and the matching
    // `*IteratorPrototype/next/*-missing-internal-slots` files.
    interp.internal_set(&object, "_iterated_source", source);
    interp.internal_set(&object, "_iterated_index", Value::Int(0));
    interp.internal_set(
        &object,
        "_iterated_kind",
        Value::Int(match kind {
            IteratorKind::Value => 0,
            IteratorKind::Key => 1,
            IteratorKind::Entry => 2,
        }),
    );
    Ok(Value::Object(object))
}

/// `%StringIteratorPrototype%.next`, which advances by code point.
///
/// A high surrogate followed by a low one is one element, and the index moves by two; a
/// lone surrogate is an element of its own, which is why this cannot just ask for
/// `code_points()` up front — the iterator is resumable and its `_index` is observable.
fn string_iterator_next(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("next called on a non-object"));
    };
    let Some(source) = interp.internal_get(&object, "_iterated_source") else {
        return Err(interp.type_error("next called on an object that is not a String Iterator"));
    };
    if matches!(source, Value::Undefined) {
        return interp.iterator_result(Value::Undefined, true);
    }
    let index = interp
        .internal_get(&object, "_iterated_index")
        .map(|value| value.to_number() as usize)
        .unwrap_or(0);
    // `make_iterator` runs `ToObject` on the source, so a string arrives as its wrapper;
    // `_value` is where that wrapper keeps the text.
    let text = match &source {
        Value::String(text) => text.clone(),
        Value::Object(object) => match interp.internal_get(object, "_value") {
            Some(Value::String(text)) => text,
            _ => return interp.iterator_result(Value::Undefined, true),
        },
        _ => return interp.iterator_result(Value::Undefined, true),
    };
    let text = text.wtf8();
    let Some(unit) = text.code_unit_at(index) else {
        // Sticky exhaustion, as for the array iterators.
        interp.internal_set(&object, "_iterated_source", Value::Undefined);
        return interp.iterator_result(Value::Undefined, true);
    };
    // A surrogate pair is one code point; anything else is one code unit.
    let paired = (0xD800..0xDC00).contains(&unit)
        && text
            .code_unit_at(index + 1)
            .is_some_and(|low| (0xDC00..0xE000).contains(&low));
    let (element, next_index) = if paired {
        (text.slice_units(index, index + 2), index + 2)
    } else {
        (text.unit_at(index).expect("the unit is there"), index + 1)
    };
    interp.internal_set(&object, "_iterated_index", Value::Int(next_index as i32));
    let value = interp.string_wtf8(element);
    interp.iterator_result(value, false)
}

/// The shared `next` of the three array iterators — §23.1.5.2.1.
///
/// Three properties of this function are load-bearing and each has its own test:
///
/// * the state is in **internal slots**, so `next.call({})` and
///   `Object.create(iterator).next()` are both a `TypeError` (`non-own-slots`);
/// * the source is read **live**, so `array.push('a')` after the iterator was made is
///   visible (`iteration-mutable`);
/// * exhaustion is **sticky**: the specification sets `[[IteratedArrayLike]]` to
///   `undefined` when the walk ends, so a later `push` does not revive the iterator
///   (`iteration-mutable` again, and `args-*-expansion-after-exhaustion`).
fn array_iterator_next(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("next called on an object that is not an Array Iterator"));
    };
    let Some(source) = interp.internal_get(&object, "_iterated_source") else {
        return Err(interp.type_error("next called on an object that is not an Array Iterator"));
    };
    // Step 4: `undefined` once the walk finished — answered before anything else looks at
    // the (now irrelevant) source.
    if matches!(source, Value::Undefined) {
        return interp.iterator_result(Value::Undefined, true);
    }
    let index = interp
        .internal_get(&object, "_iterated_index")
        .map(|value| value.to_number() as usize)
        .unwrap_or(0);
    let kind = interp
        .internal_get(&object, "_iterated_kind")
        .map(|value| value.to_number() as i32)
        .unwrap_or(0);
    // §23.1.5.2.1 steps 6.a–6.e, the typed-array branch, which is not the same as the
    // array-like branch below in two ways:
    //
    // * a view the buffer has been resized away from is a `TypeError` on `next`, not an
    //   empty iteration — `TestIterationAndResize` asserts exactly that for a fixed-length
    //   view, and the opposite for a length-tracking one;
    // * once the walk is exhausted the iterated object is cleared, so a buffer that grows
    //   afterwards does not bring the iterator back to life
    //   (`values/make-in-bounds-after-exhausted`).
    if let Value::Object(array) = &source
        && let Some((_, _, _, length, out_of_bounds)) = array.typed_array_geometry()
    {
        if out_of_bounds {
            return Err(interp.type_error("the buffer was detached or resized out of bounds"));
        }
        if index >= length {
            interp.internal_set(&object, "_iterated_source", Value::Undefined);
            return interp.iterator_result(Value::Undefined, true);
        }
        interp.internal_set(&object, "_iterated_index", Value::Int(index as i32 + 1));
        let element = element_at(interp, &source, index)?;
        let value = iterator_element(interp, kind, index, element);
        return interp.iterator_result(value, false);
    }
    let length = length_of(interp, &source)?;
    if index >= length {
        interp.internal_set(&object, "_iterated_source", Value::Undefined);
        return interp.iterator_result(Value::Undefined, true);
    }
    interp.internal_set(&object, "_iterated_index", Value::Int(index as i32 + 1));
    let element = element_at(interp, &source, index)?;
    let value = iterator_element(interp, kind, index, element);
    interp.iterator_result(value, false)
}

/// What one step yields: the value itself, the index, or `[index, value]`.
fn iterator_element(interp: &mut Interp<'_>, kind: i32, index: usize, element: Value) -> Value {
    match kind {
        1 => crate::object::index_value(index),
        2 => Value::Object(interp.new_array(vec![crate::object::index_value(index), element])),
        _ => element,
    }
}

/// The clamped length of an array-like, read lazily.
fn length_of(interp: &mut Interp<'_>, source: &Value) -> JsResult<usize> {
    // The fast path reads the element vector, which a proxy of an array does not have —
    // `is_array` answers true for one (that is what `Array.isArray` must say), so the
    // proxy check has to come too or the length would come back as zero.
    if let Some(array) = source.as_object().cloned()
        && array.is_array()
        && array.proxy_state().is_none()
    {
        return Ok(array.array_length().unwrap_or(0));
    }
    if let Value::String(text) = source {
        return Ok(text.utf16_len());
    }
    let Some(object) = source.as_object().cloned() else {
        return Ok(0);
    };
    let length = interp
        .get_property(&object, "length")?
        .map(|value| interp.to_js_number(&value))
        .transpose()?
        .unwrap_or(0.0);
    Ok(to_length(length))
}

/// How long a source `Array.from` will read.
///
/// A real array of this size would already be out of memory, so the bound turns a hostile
/// `{length: 2**53-1}` into a catchable `RangeError` instead of an abort.
const MAX_FROM_LENGTH: usize = 1 << 26;

/// `ToLength`: `NaN` and negatives are zero, fractions truncate, and the result saturates
/// at `2^53-1` rather than staying infinite.
///
/// The saturation is not cosmetic. `{length: Infinity}` used to come back as `0` — the old
/// code rejected any non-finite value — so a method over it did nothing at all instead of
/// asking for an array of `2^53-1` elements and being refused.
fn to_length(value: f64) -> usize {
    const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
    if value.is_nan() || value <= 0.0 {
        return 0;
    }
    if value >= MAX_SAFE_INTEGER {
        return MAX_SAFE_INTEGER as usize;
    }
    value as usize
}

/// The `ArrayCreate` length bound, and what makes an absurd `length` a `RangeError`
/// rather than a loop that never ends.
///
/// `Array.prototype.map` builds its result with `ArraySpeciesCreate(O, len)`, so a receiver
/// claiming `length: 4294967296` is refused there — the check belongs to array creation,
/// not to the loop. Without it the loop tried to allocate four billion slots: 44
/// conformance tests hung instead of throwing, and a hang costs a whole run's wall clock.
const MAX_ARRAY_LENGTH: usize = (1 << 32) - 1;

/// How many elements this engine will actually write one at a time.
///
/// Not a spec bound — the spec lets `length` be `2^53-1`, and no implementation can loop
/// that far. This is where a hostile or merely silly `length` becomes a catchable
/// `RangeError` instead of a call that never returns: the methods that copy the receiver
/// refuse it up front, and so do the ones that write element by element.
const MAX_ARRAY_LIKE: usize = 1 << 26;

fn array_create_length(interp: &mut Interp<'_>, length: usize) -> JsResult<usize> {
    if length > MAX_ARRAY_LENGTH {
        return Err(interp.range_error("invalid array length"));
    }
    Ok(length)
}

/// `2^53 - 1`, the largest integer a `Number` represents exactly — the *array index*
/// bound the spec's `len + argCount > 2^53 - 1` checks are written against.
///
/// Distinct from [`MAX_ARRAY_LENGTH`]: that is `ArrayCreate`'s own limit and its overflow
/// is a `RangeError`, whereas exceeding this one in a method like `push` is a `TypeError`
/// (§23.1.3.24 step 6). Keeping them apart matters — the wrong class fails the test even
/// when the condition is right.
const MAX_INTEGER: usize = (1 << 53) - 1;

/// `if len + argCount > 2^53 - 1, throw a TypeError` — the check `push`, `unshift` and
/// `splice` each write out in their own words, and which none of them had.
///
/// Without it the methods did not merely mis-report: `push` wrote a `length` of `2^53`
/// (past the bound, so the value stops being exact) and `unshift` fell through to a loop
/// from `0` to `length`, which at `length = 2^53 - 1` is a hang rather than a wrong
/// answer. Both are reachable from three lines of script, so this is a robustness fix
/// before it is a conformance one.
fn check_integer_limit(interp: &mut Interp<'_>, length: usize, count: usize) -> JsResult<()> {
    match length.checked_add(count) {
        Some(total) if total <= MAX_INTEGER => Ok(()),
        _ => Err(interp.type_error("invalid array length")),
    }
}

/// One element of an array-like, read lazily.
fn element_at(interp: &mut Interp<'_>, source: &Value, index: usize) -> JsResult<Value> {
    if let Value::String(text) = source {
        return Ok(match text.wtf8().unit_at(index) {
            Some(unit) => interp.string_wtf8(unit),
            None => Value::Undefined,
        });
    }
    let Some(object) = source.as_object().cloned() else {
        return Ok(Value::Undefined);
    };
    Ok(interp
        .get_property(&object, &index.to_string())?
        .unwrap_or(Value::Undefined))
}

// ---------------------------------------------------------------------------
// Higher-order methods
// ---------------------------------------------------------------------------

/// Run `callback` over the elements, the shape every iteration method needs.
fn iterate(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Vec<(usize, Value)>> {
    let array = receiver(interp, &this)?;
    // Length first, then the callback check: a getter on `length` runs either way.
    let length = receiver_length(interp, &array)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    let this_arg = callback_this(args);
    let mut out = Vec::new();
    for index in 0..length {
        // A hole is not an element: the iteration methods skip it entirely, so
        // `[1,,3].forEach(f)` calls `f` twice and the index passed is the real one.
        // `HasProperty` first and `[[Get]]` second, both read *now* rather than up front, so
        // a callback that resizes a typed array's buffer makes the remaining indices absent
        // (`every/callbackfn-resize-arraybuffer`) and one that fills a hole makes it appear.
        if !receiver_has_index(interp, &array, index)? {
            continue;
        }
        let Some(value) = receiver_element(interp, &array, index)? else {
            continue;
        };
        interp.call_value(
            callback.clone(),
            this_arg.clone(),
            vec![
                value.clone(),
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
        out.push((index, value));
    }
    Ok(out)
}

fn for_each(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    iterate(interp, this, args)?;
    Ok(Value::Undefined)
}

fn map(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // The result array's length is `ArraySpeciesCreate(O, len)`, so it is validated
    // before the loop starts — and the length is read before the callback is looked at,
    // both of which are observable orders.
    let count = receiver_length(interp, &array)?;
    let length = array_create_length(interp, count)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    let this_arg = callback_this(args);
    // `ArraySpeciesCreate` runs *before* the loop: `create-species-abrupt` asserts the
    // callback was never called when the species throws, so this cannot move to the tail.
    let result = interp.array_species_create(&this, length)?;
    // Holes stay holes: `[1,,3].map(f)` is `[f(1), <hole>, f(3)]`, not the two-element
    // `[f(1), f(3)]` that dropping holes produced.
    for index in 0..length {
        // `HasProperty` before `[[Get]]` (§23.1.3.x step 8.a): see `receiver_has_index`.
        if !receiver_has_index(interp, &array, index)? {
            continue;
        }
        let Some(value) = receiver_element(interp, &array, index)? else {
            continue;
        };
        let mapped = interp.call_value(
            callback.clone(),
            this_arg.clone(),
            vec![
                value,
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
        interp.create_data_property_or_throw(&result, index, mapped)?;
    }
    Ok(Value::Object(result))
}

fn filter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // `ToLength(Get(O, "length"))` is read before the callback is validated: a getter on
    // `length` runs even when the call is about to be refused for a non-callable
    // callback, and reading it late left `accessed !== true`.
    let length = receiver_length(interp, &array)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    let this_arg = callback_this(args);
    // `filter` creates the species array with length 0 and grows it, and — like `map` —
    // does so before the callback runs.
    let result = interp.array_species_create(&this, 0)?;
    let mut kept = 0;
    for index in 0..length {
        // `HasProperty` before `[[Get]]` (§23.1.3.x step 8.a): see `receiver_has_index`.
        if !receiver_has_index(interp, &array, index)? {
            continue;
        }
        let Some(value) = receiver_element(interp, &array, index)? else {
            continue;
        };
        let keep = interp.call_value(
            callback.clone(),
            this_arg.clone(),
            vec![
                value.clone(),
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
        if keep.to_boolean() {
            interp.create_data_property_or_throw(&result, kept, value)?;
            kept += 1;
        }
    }
    set_result_length(interp, &result, kept)?;
    Ok(Value::Object(result))
}

fn reduce(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    reduce_with(interp, this, args, false)
}

fn reduce_right(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    reduce_with(interp, this, args, true)
}

fn reduce_with(
    interp: &mut Interp<'_>,
    this: Value,
    args: &[Value],
    right_to_left: bool,
) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // `ToLength(Get(O, "length"))` is read before the callback is validated: a getter on
    // `length` runs even when the call is about to be refused for a non-callable
    // callback, and reading it late left `accessed !== true`.
    let length = receiver_length(interp, &array)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    // No `thisArg`: `reduce`'s second argument is the initial accumulator, so the
    // callback always runs with `this === undefined`.
    let indices: Vec<usize> = if right_to_left {
        (0..length).rev().collect()
    } else {
        (0..length).collect()
    };
    // The walk has to stay lazy: an earlier version collected every present element up
    // front, which read the whole view before the first callback ran — so a callback that
    // resized the buffer was invisible to it
    // (`reduce/resizable-buffer-shrink-mid-iteration`). `HasProperty` and `[[Get]]` are both
    // asked per index, after the previous callback returned, exactly like `every`.
    let mut ordered = indices.into_iter();
    // `[[Get]]` for one index, or `None` when it is absent — a hole, or a typed array index
    // the buffer no longer covers.
    let mut next_present = |interp: &mut Interp<'_>| -> JsResult<Option<(usize, Value)>> {
        for index in ordered.by_ref() {
            if !receiver_has_index(interp, &array, index)? {
                continue;
            }
            if let Some(value) = receiver_element(interp, &array, index)? {
                return Ok(Some((index, value)));
            }
        }
        Ok(None)
    };
    // "`initialValue` **is present**" is `args.len() > 1`, not "the value is not
    // `undefined`": `reduce.call({0: 11, length: 1}, f, undefined)` passes `undefined` as the
    // accumulator and never looks at `obj[0]` (`15.4.4.21-9-c-ii-20`).
    let mut accumulator = if args.len() > 1 {
        args[1].clone()
    } else {
        match next_present(interp)? {
            Some((_, value)) => value,
            None => {
                return Err(interp.type_error("Reduce of empty array with no initial value"));
            }
        }
    };
    while let Some((index, value)) = next_present(interp)? {
        accumulator = interp.call_value(
            callback.clone(),
            Value::Undefined,
            vec![
                accumulator,
                value,
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
    }
    Ok(accumulator)
}

fn some(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // `ToLength(Get(O, "length"))` is read before the callback is validated: a getter on
    // `length` runs even when the call is about to be refused for a non-callable
    // callback, and reading it late left `accessed !== true`.
    let length = receiver_length(interp, &array)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    let this_arg = callback_this(args);
    for index in 0..length {
        // `HasProperty` before `[[Get]]` (§23.1.3.x step 8.a): see `receiver_has_index`.
        if !receiver_has_index(interp, &array, index)? {
            continue;
        }
        let Some(value) = receiver_element(interp, &array, index)? else {
            continue;
        };
        let answer = interp.call_value(
            callback.clone(),
            this_arg.clone(),
            vec![
                value,
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
        if answer.to_boolean() {
            return Ok(Value::Bool(true));
        }
    }
    Ok(Value::Bool(false))
}

fn every(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // `ToLength(Get(O, "length"))` is read before the callback is validated: a getter on
    // `length` runs even when the call is about to be refused for a non-callable
    // callback, and reading it late left `accessed !== true`.
    let length = receiver_length(interp, &array)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    let this_arg = callback_this(args);
    for index in 0..length {
        // `HasProperty` before `[[Get]]` (§23.1.3.x step 8.a): see `receiver_has_index`.
        if !receiver_has_index(interp, &array, index)? {
            continue;
        }
        let Some(value) = receiver_element(interp, &array, index)? else {
            continue;
        };
        let answer = interp.call_value(
            callback.clone(),
            this_arg.clone(),
            vec![
                value,
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
        if !answer.to_boolean() {
            return Ok(Value::Bool(false));
        }
    }
    Ok(Value::Bool(true))
}

fn find(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // `ToLength(Get(O, "length"))` is read before the callback is validated: a getter on
    // `length` runs even when the call is about to be refused for a non-callable
    // callback, and reading it late left `accessed !== true`.
    let length = receiver_length(interp, &array)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    let this_arg = callback_this(args);
    for index in 0..length {
        let value = receiver_element(interp, &array, index)?.unwrap_or(Value::Undefined);
        let answer = interp.call_value(
            callback.clone(),
            this_arg.clone(),
            vec![
                value.clone(),
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
        if answer.to_boolean() {
            return Ok(value);
        }
    }
    Ok(Value::Undefined)
}

fn find_index(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // `ToLength(Get(O, "length"))` is read before the callback is validated: a getter on
    // `length` runs even when the call is about to be refused for a non-callable
    // callback, and reading it late left `accessed !== true`.
    let length = receiver_length(interp, &array)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    let this_arg = callback_this(args);
    for index in 0..length {
        let value = receiver_element(interp, &array, index)?.unwrap_or(Value::Undefined);
        let answer = interp.call_value(
            callback.clone(),
            this_arg.clone(),
            vec![
                value,
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
        if answer.to_boolean() {
            return Ok(crate::object::index_value(index));
        }
    }
    Ok(Value::Int(-1))
}

fn fill(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // The receiver, not a copy: §23.1.3.6 step 11 is `Set(O, k, value, true)`, so
    // `fill.call({length: 2}, 1)` writes the argument object and answers *it*.
    let array = receiver(interp, &this)?;
    // The *logical* length, not the dense vector's: `new Array(3).fill(1)` has three
    // holes and no storage at all, and filling them has to reach index 2.
    let current_len = receiver_length(interp, &array)?;
    let value = arg(args, 0);
    // `ToIntegerOrInfinity` on both bounds: `fill(1, Symbol())` is a `TypeError`, and
    // `Value::to_number` answers `NaN` for a symbol instead of refusing.
    let start = relative_index(interp, args.get(1), current_len)?;
    let end = match args.get(2) {
        None | Some(Value::Undefined) => current_len,
        Some(_) => relative_index(interp, args.get(2), current_len)?,
    };
    // A resource bound, not a spec step: §23.1.3.6 has no integer-limit check, and
    // `fill.call({length: 2**53-1}, 1)` is a genuinely 2^53-1-iteration `while` loop that no
    // implementation can finish. Every write here is a fresh integer-keyed property, so the
    // memory limit does not save it either — each one is tiny, and the loop starves rather
    // than failing. test262 never asks for this (its `length-near-integer-limit` passes a
    // `start`, so only three elements are written); the probe that found it did not.
    //
    // Same shape and same class as `receiver_copy`'s `MAX_ARRAY_LIKE`: a bound on work this
    // engine will do, reported as a `RangeError` so the script can catch it.
    if end.saturating_sub(start) > MAX_ARRAY_LIKE {
        return Err(interp.range_error("array-like length is too large to fill"));
    }
    for index in start..end {
        write_element(interp, &array, index, value.clone())?;
    }
    Ok(Value::Object(array))
}

// ---------------------------------------------------------------------------
// splice / sort / flat
// ---------------------------------------------------------------------------

/// §23.1.3.29 `Array.prototype.splice ( start, deleteCount, ...items )`.
///
/// Walked **by index**, and every loop is bounded by the *difference* between what is
/// removed and what is inserted rather than by `length`. That is what makes a legal
/// `length` of `2**53 - 1` work at all: `splice(9007199254740987, 1)` on such a receiver
/// moves one element and stops, while the old code materialised the whole range and died
/// with a `RangeError` (`length-exceeding-integer-limit-shrink-array`, `…-grow-array`,
/// `length-and-deleteCount-exceeding-integer-limit`).
///
/// Four ordering details are pinned by their own cases:
///
/// * `length` is read **once** (`set_length_no_args` counts the `Get`);
/// * the removed elements are collected through `CreateDataProperty` on a
///   `ArraySpeciesCreate` result, then `length` is written on it with `Set` — the species
///   may be a proxy, and `property-traps-order-with-species` records the five traps in
///   order;
/// * a shift step whose source is a hole **deletes** the destination instead of writing
///   `undefined` (`S15.4.4.12_A2_T1`);
/// * the final `Set(O, "length", …)` is `Throw`, so a non-writable `length` is a
///   `TypeError` (`S15.4.4.12_A6.1_T2`).
fn splice(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = this_object(interp, &this)?;
    let length = receiver_length(interp, &array)?;
    // Steps 3–6: `actualStart`, then `actualDeleteCount`. A missing `start` is `0`; a
    // missing `deleteCount` with `start` present removes everything from `start` on.
    let actual_start = match args.first() {
        None => 0,
        Some(_) => normalise(arg_integer_or(interp, args, 0, 0.0)?, length),
    };
    let item_count = args.len().saturating_sub(2);
    let actual_delete_count = match args.len() {
        0 => 0,
        1 => length - actual_start,
        _ => {
            let count = arg_integer_or(interp, args, 1, 0.0)?;
            let available = (length - actual_start) as f64;
            if count <= 0.0 {
                0
            } else if count >= available {
                length - actual_start
            } else {
                count as usize
            }
        }
    };
    // Step 8: `len - actualDeleteCount + itemCount > 2**53 - 1` is a `TypeError`, and it
    // runs before anything is read or written.
    let remaining = length - actual_delete_count;
    if remaining
        .checked_add(item_count)
        .is_none_or(|total| total > MAX_INTEGER)
    {
        return Err(interp.type_error("invalid array length"));
    }
    let new_length = remaining + item_count;
    // Step 9: `ArraySpeciesCreate(O, actualDeleteCount)` — and its `ArrayCreate` bound is
    // a `RangeError` *before* any property is touched (`create-species-undef-invalid-len`
    // counts the `set` traps and expects zero).
    let removed = interp.array_species_create(&this, actual_delete_count)?;
    // Steps 10–11.
    for offset in 0..actual_delete_count {
        let from = actual_start + offset;
        if receiver_has(interp, &array, from)? {
            let value = receiver_element(interp, &array, from)?.unwrap_or(Value::Undefined);
            interp.create_data_property_or_throw(&removed, offset, value)?;
        }
    }
    // Step 12: `Set(A, "length", actualDeleteCount, true)` on the species result. Through
    // the ordinary `Set`, not `array_set_length`: the result may be a proxy of an array, and
    // its `length` write has to run the traps.
    interp.set_property(
        &removed,
        "length",
        crate::object::length_value(actual_delete_count),
    )?;
    // Steps 13–16: shift. Bounded by the *difference*, which is why a huge `length` costs
    // nothing as long as the splice is small.
    if item_count < actual_delete_count {
        for k in actual_start..remaining {
            shift_one(interp, &array, k + actual_delete_count, k + item_count)?;
        }
        // Step 16: the tail the shorter length exposes — from `len - 1` down to
        // `len - actualDeleteCount + itemCount`, which is `new_length`. Using
        // `len - actualDeleteCount` here deleted one element the shift had just moved
        // (`S15.4.4.12_A1.1_T2`: `[0,1,2,3].splice(0,3,4,5)` lost the `3`).
        for k in (new_length..length).rev() {
            delete_or_throw(interp, &array, k)?;
        }
    } else if item_count > actual_delete_count {
        for k in (actual_start..remaining).rev() {
            shift_one(interp, &array, k + actual_delete_count, k + item_count)?;
        }
    }
    // Step 17.
    for (offset, item) in args.iter().skip(2).enumerate() {
        store_or_throw(interp, &array, actual_start + offset, item.clone())?;
    }
    // Step 18: last, and `Throw`.
    if array.is_array()
        && array.proxy_state().is_none()
        && array.elements_writable()
        && array.length_writable()
    {
        array.array_set_length(interp.heap, new_length);
    } else {
        interp.set_property_with_key(
            &array,
            &PropertyKey::from("length"),
            crate::object::length_value(new_length),
            crate::interp::DeleteFailure::Throw,
        )?;
    }
    Ok(Value::Object(removed))
}

/// One `Set(O, to, Get(O, from))` step of a splice shift, or `Delete(O, to)` for a hole.
fn shift_one(
    interp: &mut Interp<'_>,
    object: &Gc<JsObject>,
    from: usize,
    to: usize,
) -> JsResult<()> {
    if receiver_has(interp, object, from)? {
        let value = receiver_element(interp, object, from)?.unwrap_or(Value::Undefined);
        store_or_throw(interp, object, to, value)
    } else {
        delete_or_throw(interp, object, to)
    }
}

/// §23.1.3.27 `Array.prototype.reverse ( )`.
///
/// Walked **by index**, from both ends, without materialising the range. Two test262 groups
/// depend on that and both used to fail on the same line:
///
/// * a `length` of `2**53 - 1` is legal while the *number of pairs* is irrelevant, because
///   the specification's loop stops at the first element the receiver actually holds — the
///   `length-exceeding-integer-limit` cases have a getter at index `2**53 - 2` that throws,
///   and expect that throw rather than a `RangeError` from copying;
/// * `middle = floor(len / 2)` is `0` for a one-element array, so a **frozen** `[1]`
///   reverses without a single write (`reverse/array-has-one-entry`). Writing every element
///   back unconditionally made that a `TypeError`.
///
/// A dense array with no element descriptors, no indexed prototype and a writable element
/// vector takes the vector path, which is the same loop without the property machinery.
fn reverse(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let array = this_object(interp, &this)?;
    let length = receiver_length(interp, &array)?;
    let middle = length / 2;
    if array.is_array()
        && array.elements_writable()
        && !array.has_element_descriptors()
        && !interp.prototype_chain_has_indexed_property(&array)
        && let Some(elements) = array.array_elements()
        && elements.len() == length
    {
        let mut elements = elements;
        elements.reverse();
        // Every slot is written, holes included: a hole means the *old* element at that
        // index has to go, and skipping it left `x[2]` holding the value that should have
        // moved away (`S15.4.4.8_A1_T2`: two ends both empty is a no-op, one end empty is a
        // delete).
        for (index, value) in elements.into_iter().enumerate() {
            if matches!(value, Value::Hole) && index >= array.array_length().unwrap_or(0) {
                continue;
            }
            array.array_set(interp.heap, index, value);
        }
        return Ok(Value::Object(array));
    }
    let mut lower = 0;
    while lower < middle {
        let upper = length - lower - 1;
        let lower_has = receiver_has(interp, &array, lower)?;
        let lower_value = if lower_has {
            Some(receiver_element(interp, &array, lower)?.unwrap_or(Value::Undefined))
        } else {
            None
        };
        let upper_has = receiver_has(interp, &array, upper)?;
        let upper_value = if upper_has {
            Some(receiver_element(interp, &array, upper)?.unwrap_or(Value::Undefined))
        } else {
            None
        };
        match (lower_value, upper_value) {
            (Some(low), Some(up)) => {
                store_or_throw(interp, &array, lower, up)?;
                store_or_throw(interp, &array, upper, low)?;
            }
            (None, Some(up)) => {
                store_or_throw(interp, &array, lower, up)?;
                delete_or_throw(interp, &array, upper)?;
            }
            (Some(low), None) => {
                delete_or_throw(interp, &array, lower)?;
                store_or_throw(interp, &array, upper, low)?;
            }
            // Neither end holds anything: two holes stay two holes, and nothing is written.
            (None, None) => {}
        }
        lower += 1;
    }
    Ok(Value::Object(array))
}

/// `DeletePropertyOrThrow(O, ToString(index))`.
fn delete_or_throw(interp: &mut Interp<'_>, object: &Gc<JsObject>, index: usize) -> JsResult<()> {
    if !interp.delete_property(object, &index.to_string())? {
        return Err(interp.type_error(format!("cannot delete property '{index}'")));
    }
    Ok(())
}

/// `sort`, with the default order being the *string* order of the elements.
///
/// That default is the surprising part of the spec: `[10, 9].sort()` is `[10, 9]`
/// because `"10" < "9"`. Kept as-is because the reference does the same.
fn sort(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // §23.1.3.30 step 3: `IsCallable(comparefn)` is checked **before** anything reads the
    // receiver, so a `get length` that throws must not run for a bad comparator
    // (`comparefn-nonfunction-call-throws` asserts exactly that ordering).
    let comparator = args
        .first()
        .cloned()
        .filter(|value| !matches!(value, Value::Undefined));
    if let Some(function) = &comparator
        && !matches!(function, Value::Object(object) if object.is_callable())
    {
        return Err(interp.type_error("comparator is not a function"));
    }
    // Written back to the receiver, for the reason `reverse` gives.
    let array = this_object(interp, &this)?;
    // §23.1.3.30: every element is read with `Get`, in index order, *before* any sorting.
    // `elements()` reads the dense vector instead, which skips accessors entirely — a
    // getter on `array[2]` was never called, so `precise-*` (eight cases that install
    // getters and delete or append siblings while `sort` runs) could not work. It also
    // means `HasProperty` is the right question for a hole: a value the prototype chain
    // supplies is a present element (`precise-prototype-element`).
    let length = receiver_length(interp, &array)?;
    let mut padded: Vec<Value> = Vec::with_capacity(length);
    for index in 0..length {
        let key = PropertyKey::from(index.to_string());
        if interp.has_property_key(&array, &key)? {
            padded.push(
                interp
                    .get_property_key(&array, &key)?
                    .unwrap_or(Value::Undefined),
            );
        } else {
            padded.push(Value::Hole);
        }
    }
    // Holes sort *after* every present element and are never passed to the comparator
    // (SortCompare is only called for defined values). Sorting them in place turned them
    // into `undefined`, so `new Array(2)` with `x[1] = 1` came back with `0 in x` false —
    // the hole moved, which the spec forbids.
    let holes = padded
        .iter()
        .filter(|value| matches!(value, Value::Hole))
        .count();
    let mut current: Vec<Value> = padded
        .into_iter()
        .filter(|value| !matches!(value, Value::Hole))
        .collect();
    match &comparator {
        Some(function) if matches!(function, Value::Object(object) if object.is_callable()) => {
            // A merge sort, because a comparator is an arbitrary JavaScript call and
            // Rust's sort needs a total order it can trust; this keeps the comparison
            // count deterministic instead of depending on the pivot strategy.
            let mut items = std::mem::take(&mut current);
            merge_sort(interp, &mut items, function)?;
            current = items;
        }
        None | Some(Value::Undefined) => {
            // Default comparison: `ToString` both sides. Two things were wrong here.
            //
            // * `to_js_string` on the value is a plain field read for an object, so an
            //   element with an observable `toString` was never converted — four cases in
            //   this directory check exactly that ("Check ToString operator").
            // * The conversions have to happen **in a fixed order, up front**: the spec's
            //   `SortCompare` calls `ToString` lazily inside the sort, and the reference
            //   runs them in the sorted order's comparison sequence. Converting every
            //   element once, left to right, before sorting makes the observable count
            //   deterministic and matches what the cases count.
            let mut keys: Vec<(SortKey, Value)> = Vec::with_capacity(current.len());
            for value in std::mem::take(&mut current) {
                let key = SortKey(interp.to_string_strict(&value)?);
                keys.push((key, value));
            }
            keys.sort_by(|a, b| a.0.cmp(&b.0));
            current = keys.into_iter().map(|(_, value)| value).collect();
        }
        // Any other argument that is not callable is a `TypeError` (§23.1.3.30 step 4).
        Some(_) => return Err(interp.type_error("comparator is not a function")),
    }
    // Present values first, then the holes: writing a hole back at the tail leaves the
    // storage truncated, which is how a trailing hole is represented.
    let present = current.len();
    for (index, value) in current.into_iter().enumerate() {
        store_or_throw(interp, &array, index, value)?;
    }
    for index in present..present + holes {
        store_or_throw(interp, &array, index, Value::Hole)?;
    }
    Ok(Value::Object(array))
}

/// Store one element of a write-back, raising when the array refuses.
///
/// The array methods all go through `[[Set]]` in the spec, so a frozen element makes
/// `sort`/`reverse`/`splice` throw rather than silently keep the old value. That is also
/// why a typed array cannot use the dense shortcut: its elements are a window onto a
/// buffer, and `array_store` only knows the vector, so
/// `Array.prototype.reverse.call(new Uint8Array([1,2,3]))` would answer "wrote it" while
/// changing nothing (`Array/prototype/reverse/resizable-buffer`).
///
/// A `Hole` is not a value to store but an index to *delete*: it is how `sort` and
/// `reverse` reproduce a trailing hole. Writing `Value::Hole` into an array's vector would
/// leave the element there with an unreadable value.
fn store_or_throw(
    interp: &mut Interp<'_>,
    array: &Gc<JsObject>,
    index: usize,
    value: Value,
) -> JsResult<()> {
    if matches!(value, Value::Hole) {
        return match interp.delete_property_key(array, &PropertyKey::from(index.to_string()))? {
            true => Ok(()),
            false => Err(interp.type_error(format!("'{index}' is not deletable"))),
        };
    }
    // An exotic object (a string's read-only indices, a host class) and a proxy both answer
    // `[[Set]]` themselves; `array_store` only knows the dense vector and would report
    // success while changing nothing. A typed array is neither — `exotic()` is about host
    // classes — but its elements are a window onto a buffer, so it is excluded by its own
    // test. This is why `Array.prototype.reverse.call(new Uint8Array([1,2,3]))` used to be
    // a silent no-op (`Array/prototype/reverse/resizable-buffer`).
    if array.exotic().is_some()
        || array.proxy_state().is_some()
        || array.typed_array_element_type().is_some()
    {
        return interp.set_property_with_key(
            array,
            &PropertyKey::from(index.to_string()),
            value,
            crate::interp::DeleteFailure::Throw,
        );
    }
    // An **accessor** at this index has to go through `[[Set]]` as well. `array_store` only
    // knows the dense vector and refuses an index that has a property-table entry, which
    // surfaced as `'2' is read-only` for the `precise-*` fixtures: they install a
    // `get`/`set` pair at a fixed index, and `sort`'s write-back must reach the setter.
    if array
        .own_property(&index.to_string())
        .is_some_and(|property| property.getter.is_some() || property.setter.is_some())
    {
        return interp.set_property_with_key(
            array,
            &PropertyKey::from(index.to_string()),
            value,
            crate::interp::DeleteFailure::Throw,
        );
    }
    if array.array_store(interp.heap, index, value.clone()) {
        return Ok(());
    }
    // `array_store` refuses for two different reasons, and they want different answers.
    //
    // * A *locked* element (`Object.defineProperty(a, "0", {writable: false})`) is
    //   genuinely read-only, which is a `TypeError`.
    // * An index past the dense limit is not: `a[2**26] = 1` is legal, and the reference
    //   keeps such an index as an ordinary property. Reporting "read-only" for it was a
    //   lie — and it is the error a `for (;;) a.push(x)` loop reached after filling 64M
    //   slots, which made a memory problem look like a permissions problem.
    if array.element_is_locked(index as u32) {
        return Err(interp.type_error(format!("'{index}' is read-only")));
    }
    array.define_key(
        &crate::object::PropertyKey::from(index.to_string()),
        crate::object::Property::with_attributes(value, true, true),
    );
    // `push` always appends, but the shared sparse path must not shorten a `length` that is
    // already larger than `index + 1`: that would delete the sparse properties above it.
    if index + 1 > array.array_length().unwrap_or(0) {
        array.array_set_length(interp.heap, index + 1);
    }
    Ok(())
}

/// A key that sorts like JavaScript's default string comparison.
struct SortKey(String);

impl PartialEq for SortKey {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl Eq for SortKey {}

impl PartialOrd for SortKey {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SortKey {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // JavaScript compares UTF-16 code units, which for the BMP is the same as
        // comparing UTF-8 bytes only within a plane; comparing `char`s is exact.
        self.0.chars().cmp(other.0.chars())
    }
}

fn merge_sort(interp: &mut Interp<'_>, items: &mut Vec<Value>, comparator: &Value) -> JsResult<()> {
    if items.len() <= 1 {
        return Ok(());
    }
    let mut right = items.split_off(items.len() / 2);
    merge_sort(interp, items, comparator)?;
    merge_sort(interp, &mut right, comparator)?;
    let mut merged = Vec::with_capacity(items.len() + right.len());
    let mut left_iter = std::mem::take(items).into_iter().peekable();
    let mut right_iter = right.into_iter().peekable();
    loop {
        match (left_iter.peek(), right_iter.peek()) {
            (Some(a), Some(b)) => {
                // §23.1.3.30.2 `SortCompare` steps 1–3: the two `undefined` rules come
                // **before** the user comparator, so a comparator cannot move an
                // `undefined` off the end. `S15.4.4.11_A1.4_T2` is built on that — its
                // comparator deliberately claims `undefined < 1` and still expects `[1,
                // undefined]`.
                let a_undefined = matches!(a, Value::Undefined);
                let b_undefined = matches!(b, Value::Undefined);
                let answer = match (a_undefined, b_undefined) {
                    (true, true) => 0.0,
                    (true, false) => 1.0,
                    (false, true) => -1.0,
                    (false, false) => interp
                        .call_value(
                            comparator.clone(),
                            Value::Undefined,
                            vec![a.clone(), b.clone()],
                        )?
                        .to_number(),
                };
                if answer > 0.0 {
                    merged.push(right_iter.next().expect("peeked"));
                } else {
                    merged.push(left_iter.next().expect("peeked"));
                }
            }
            (Some(_), None) => merged.push(left_iter.next().expect("peeked")),
            (None, Some(_)) => merged.push(right_iter.next().expect("peeked")),
            (None, None) => break,
        }
    }
    *items = merged;
    Ok(())
}

fn flat(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    let depth = match args.first() {
        None | Some(Value::Undefined) => 1,
        Some(value) => value.to_number() as i64,
    };
    // The species array is created **before** any element is read (§23.1.3.14 step 4),
    // and each flattened element is written as it is reached. Gathering everything first
    // and asking for the species at the end is observably different:
    // `flat/proxy-access-count` records the order of the `length`/`constructor`/index
    // reads, and it expects `constructor` right after the receiver's `length`.
    let result = interp.array_species_create(&this, 0)?;
    let items = receiver_items(interp, &array)?;
    let mut next = 0usize;
    flatten_into(interp, &items, depth, &result, &mut next)?;
    set_result_length(interp, &result, next)?;
    Ok(Value::Object(result))
}

/// [`flatten`], writing straight into an already-created result.
///
/// The `CreateDataPropertyOrThrow` per element is §23.1.3.14 step 4.e's, and it is not the
/// same as filling a vector: a species array with a read-only index refuses the write
/// instead of silently collecting it.
fn flatten_into(
    interp: &mut Interp<'_>,
    source: &[Value],
    depth: i64,
    result: &Gc<JsObject>,
    next: &mut usize,
) -> JsResult<()> {
    for value in source {
        // A hole stays out of the result: `[1,,3].flat()` is `[1, 3]`.
        if matches!(value, Value::Hole) {
            continue;
        }
        match value.as_object() {
            Some(object) if depth > 0 && object.is_array() => {
                let nested = elements(interp, object)?;
                flatten_into(interp, &nested, depth - 1, result, next)?;
            }
            _ => {
                interp.create_data_property_or_throw(result, *next, value.clone())?;
                *next += 1;
            }
        }
    }
    Ok(())
}

/// Every element of the receiver, holes included, read through the generic path.
///
/// `elements()` answers from the element vector and returns nothing at all for an
/// array-like, which is why `flat` over `{length: 2, 0: 1, 1: 2}` came back empty.
fn receiver_items(interp: &mut Interp<'_>, object: &Gc<JsObject>) -> JsResult<Vec<Value>> {
    let length = receiver_length(interp, object)?;
    let mut out = Vec::with_capacity(length.min(1024));
    for index in 0..length {
        out.push(receiver_element(interp, object, index)?.unwrap_or(Value::Hole));
    }
    Ok(out)
}

fn flatten(
    interp: &mut Interp<'_>,
    source: &[Value],
    depth: i64,
    out: &mut Vec<Value>,
) -> JsResult<()> {
    for value in source {
        // A hole stays out of the result: `[1,,3].flat()` is `[1, 3]`.
        if matches!(value, Value::Hole) {
            continue;
        }
        match value.as_object() {
            Some(object) if depth > 0 && object.is_array() => {
                let nested = elements(interp, object)?;
                flatten(interp, &nested, depth - 1, out)?;
            }
            _ => out.push(value.clone()),
        }
    }
    Ok(())
}

/// `a.flatMap(fn, thisArg)`: `map` then flatten one level, in one pass.
///
/// It is not `map` followed by `flat`: the species array is created once, with length 0,
/// *before* the callback runs, and each callback's answer is flattened into it. Routing
/// through `map` built an intermediate species array — one the spec never creates — and
/// made a `Symbol.species` counter observe two constructions instead of one.
fn flat_map(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    let length = receiver_length(interp, &array)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    let this_arg = callback_this(args);
    let result = interp.array_species_create(&this, 0)?;
    let mut next = 0;
    for index in 0..length {
        let Some(value) = receiver_element(interp, &array, index)? else {
            continue;
        };
        let mapped = interp.call_value(
            callback.clone(),
            this_arg.clone(),
            vec![
                value,
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
        let mut flat = Vec::new();
        flatten(interp, &[mapped], 1, &mut flat)?;
        for value in flat {
            interp.create_data_property_or_throw(&result, next, value)?;
            next += 1;
        }
    }
    set_result_length(interp, &result, next)?;
    Ok(Value::Object(result))
}

// ---------------------------------------------------------------------------
// findLast, copyWithin, change array by copy
// ---------------------------------------------------------------------------

/// `a.findLast(predicate, thisArg)`: the last element the predicate accepts.
///
/// The search runs *downwards* from `len - 1` and stops at the first hit, so it is not
/// `find` over a reversed copy: a predicate that mutates the array has to observe each
/// index in descending order.
fn find_last(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    // The length is read before the predicate is validated, which is observable.
    let length = receiver_length(interp, &array)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    let this_arg = callback_this(args);
    for index in (0..length).rev() {
        // A hole reads as `undefined`: `find`/`findLast` use `Get`, so unlike `forEach`
        // they do visit holes.
        let value = receiver_element(interp, &array, index)?.unwrap_or(Value::Undefined);
        let answer = interp.call_value(
            callback.clone(),
            this_arg.clone(),
            vec![
                value.clone(),
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
        if answer.to_boolean() {
            return Ok(value);
        }
    }
    Ok(Value::Undefined)
}

/// `a.findLastIndex(predicate, thisArg)`: where `findLast` would have found it.
fn find_last_index(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let array = receiver(interp, &this)?;
    let length = receiver_length(interp, &array)?;
    let callback = arg(args, 0);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("callback is not a function"));
    }
    let this_arg = callback_this(args);
    for index in (0..length).rev() {
        let value = receiver_element(interp, &array, index)?.unwrap_or(Value::Undefined);
        let answer = interp.call_value(
            callback.clone(),
            this_arg.clone(),
            vec![
                value,
                crate::object::index_value(index),
                Value::Object(array.clone()),
            ],
        )?;
        if answer.to_boolean() {
            return Ok(crate::object::index_value(index));
        }
    }
    Ok(Value::Int(-1))
}

/// `a.copyWithin(target, start, end)`: copy a range over another range, in place.
///
/// This method **writes to the receiver**, so it cannot go through `receiver_copy` —
/// `Array.prototype.copyWithin.call(true)` has to answer the boxed Boolean and
/// `copyWithin.call({length: 4, …})` has to write the argument object. The writes go
/// through `[[Set]]` and a copied hole becomes a *deleted* property, which is what
/// `fill-holes` checks (`hasOwnProperty(1) === false` after the copy).
fn copy_within(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let object = receiver(interp, &this)?;
    let length = receiver_length(interp, &object)?;
    let target = relative_index(interp, args.first(), length)?;
    let start = relative_index(interp, args.get(1), length)?;
    // `end` defaults to `len`, and an explicit `undefined` is also `len` — unlike
    // `start`, where `undefined` is `0`.
    let end = match args.get(2) {
        None | Some(Value::Undefined) => length,
        Some(value) => relative_index(interp, Some(value), length)?,
    };
    let count = end.saturating_sub(start).min(length.saturating_sub(target));
    // Resource bound on the copy, same reasoning as `fill` and `indexOf`: `count` here is
    // only what the *arguments* select, so `copyWithin(0, 0)` on `{length: 2**53-1}` asked
    // for a `2^53-1`-element copy. The bounds-with-arguments tests keep their three.
    if count > MAX_ARRAY_LIKE {
        return Err(interp.range_error("array-like length is too large to copy within"));
    }
    // Direction matters when the ranges overlap: copying forwards would overwrite
    // elements it has not read yet, so a target inside the source goes backwards.
    let backwards = start < target && target < start + count;
    for step in 0..count {
        let offset = if backwards { count - 1 - step } else { step };
        let from = start + offset;
        let to = target + offset;
        // Presence is `HasProperty`, not `[[Get]] is not undefined`: a proxy that answers
        // `undefined` for a missing element still has the element *absent*, and the spec
        // then deletes the destination rather than writing `undefined` into it.
        let present = receiver_has(interp, &object, from)?;
        if present {
            let value = receiver_element(interp, &object, from)?;
            write_element(interp, &object, to, value.unwrap_or(Value::Undefined))?;
        } else {
            {
                // §23.1.3.4 step 15.f.i is `DeletePropertyOrThrow`, so a non-configurable
                // destination index is a `TypeError`, not a silent skip.
                if !interp.delete_property(&object, &to.to_string())? {
                    return Err(interp.type_error(format!("cannot delete property '{to}'")));
                }
            }
        }
    }
    // §23.1.3.4 answers the receiver itself, so `copyWithin.call(true)` is the box.
    Ok(Value::Object(object))
}

/// `ToIntegerOrInfinity` with the negative-from-the-end rule, clamped to `[0, length]`.
fn relative_index(
    interp: &mut Interp<'_>,
    value: Option<&Value>,
    length: usize,
) -> JsResult<usize> {
    let raw = match value {
        None => return Ok(0),
        Some(value) => to_integer_or_infinity(interp, value)?,
    };
    if raw < 0.0 {
        let from_end = length as f64 + raw;
        return Ok(if from_end < 0.0 { 0 } else { from_end as usize });
    }
    Ok((raw.min(length as f64)) as usize)
}

/// Store one element on a receiver that may be an array, an array-like or a box.
///
/// `[[Set]]` rather than the element vector, so an accessor on the index runs, a
/// read-only index refuses, and a non-array receiver actually changes.
fn write_element(
    interp: &mut Interp<'_>,
    object: &Gc<JsObject>,
    index: usize,
    value: Value,
) -> JsResult<()> {
    // The fast path is `[[Set]]` on a plain array, which is what the hot callers —
    // `fill`, `copyWithin`, `push` — do millions of times: `new Array(64 << 20).fill(0)`
    // took 16 seconds when every element went through the generic property setter.
    //
    // It is only safe while the element vector is the authority: no accessor or
    // non-default attribute recorded for any index, and the array extensible and its
    // elements writable. Inside the current length a store cannot even change `length`.
    if object.is_array()
        && object.elements_writable()
        && !object.has_element_descriptors()
        && object.is_extensible()
        && index < object.array_length().unwrap_or(0)
        && object.array_set(interp.heap, index, value.clone())
    {
        return Ok(());
    }
    interp.set_property(object, &index.to_string(), value)
}

/// The elements of the receiver with holes flattened to `undefined`.
///
/// The change-array-by-copy family does *not* preserve holes: §23.1.3.24 step 5.a.i is
/// `CreateDataProperty`, so `[0,,2,,4].with(2, 6)` is a five-element
/// `[0, undefined, 6, undefined, 4]` with every index present. An element inherited from
/// `Array.prototype` is read too, which is why this cannot come from the element vector.
fn dense_elements(interp: &mut Interp<'_>, object: &Gc<JsObject>) -> JsResult<Vec<Value>> {
    let length = receiver_length(interp, object)?;
    // The result is an `ArrayCreate(len)`, so an absurd length is refused before
    // anything is allocated instead of looping over `2^32` empty slots.
    array_create_length(interp, length)?;
    let mut out = Vec::with_capacity(length.min(1024));
    for index in 0..length {
        out.push(receiver_element(interp, object, index)?.unwrap_or(Value::Undefined));
    }
    Ok(out)
}

/// `a.toReversed()`: a reversed copy, receiver untouched.
fn to_reversed(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let object = receiver(interp, &this)?;
    let length = receiver_length(interp, &object)?;
    // `ArrayCreate(len)` runs **before** any index is read, so an absurd `length` is a
    // `RangeError` and the throwing getters below are never reached
    // (`length-exceeding-array-length-limit` installs getters that throw if touched).
    // The limit check is `ArrayCreate`'s, done first so a bad `length` never reaches a
    // getter.
    array_create_length(interp, length)?;
    let result = interp.new_array_of_length(length);
    // §23.1.3.34 reads the source **descending**: `k` runs from `len - 1` down to 0, and the
    // results are written to `len - k - 1`. So a getter on `a[2]` runs first, and the write
    // to `result[0]` happens before `a[1]` is read. Reading ascending and then reversing the
    // vector gets the values right and the order wrong (`get-descending-order`), and it also
    // snapshots the receiver: `length-decreased-while-iterating` has a getter that shortens
    // the array mid-walk and expects the already-shortened state to be seen.
    for k in (0..length).rev() {
        let key = PropertyKey::from(k.to_string());
        // `Get`, so an absent index reads as `undefined` **and** an index the prototype
        // supplies is found — `holes-not-preserved` expects `[4,3,2,undefined,0]` from an
        // array with one hole, because `toReversed` materialises the hole rather than
        // leaving a gap. A hole is still skipped by `HasProperty` when the prototype has
        // nothing there, and then `Get` answers `undefined` anyway, so a single `Get`
        // covers both.
        let value = interp
            .get_property_key(&object, &key)?
            .unwrap_or(Value::Undefined);
        interp.create_data_property_or_throw(&result, length - k - 1, value)?;
    }
    Ok(Value::Object(result))
}

/// `a.with(index, value)`: a copy with one element replaced.
///
/// `index` may be negative, counting from the end; anything outside the array is a
/// `RangeError`, not a silent no-op. The receiver is never read at the replaced index, so
/// a getter there does not run — `no-get-replaced-index`.
fn array_with(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let object = receiver(interp, &this)?;
    let length = receiver_length(interp, &object)?;
    array_create_length(interp, length)?;
    let raw = to_integer_or_infinity(interp, &arg(args, 0))?;
    let index = if raw < 0.0 { length as f64 + raw } else { raw };
    if index < 0.0 || index >= length as f64 {
        return Err(interp.range_error("index is out of range"));
    }
    let index = index as usize;
    let mut items = Vec::with_capacity(length.min(1024));
    for position in 0..length {
        if position == index {
            items.push(arg(args, 1));
        } else {
            items.push(receiver_element(interp, &object, position)?.unwrap_or(Value::Undefined));
        }
    }
    // `with`, like the rest of the change-by-copy family, uses `ArrayCreate` and never
    // consults `@@species`.
    let result = interp.new_array_of_length(items.len());
    for (position, value) in items.into_iter().enumerate() {
        interp.create_data_property_or_throw(&result, position, value)?;
    }
    Ok(Value::Object(result))
}

/// `a.toSorted(compareFn)`: a sorted copy, receiver untouched.
fn to_sorted(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // §23.1.3.29 step 1 validates the comparator **before** `ToObject(this)` and before
    // `LengthOfArrayLike`, so a `get length` that throws must not run when the comparator
    // is not callable.
    let comparator = args
        .first()
        .filter(|value| !matches!(value, Value::Undefined));
    if let Some(function) = comparator
        && !matches!(function, Value::Object(object) if object.is_callable())
    {
        return Err(interp.type_error("comparator is not a function"));
    }
    let object = receiver(interp, &this)?;
    // Every element is read *before* the comparator is called, which is observable:
    // `comparefn-called-after-get-elements` turns on exactly that order.
    let mut items = dense_elements(interp, &object)?;
    match comparator {
        Some(comparator) => merge_sort(interp, &mut items, &comparator.clone())?,
        None => {
            // Same default comparison as `sort`: `ToString` through the interpreter, all
            // elements converted before any sorting happens. See the comment there.
            let mut keys: Vec<(SortKey, Value)> = Vec::with_capacity(items.len());
            for value in std::mem::take(&mut items) {
                let key = SortKey(interp.to_string_strict(&value)?);
                keys.push((key, value));
            }
            keys.sort_by(|a, b| a.0.cmp(&b.0));
            items = keys.into_iter().map(|(_, value)| value).collect();
        }
    }
    let result = interp.new_array_of_length(items.len());
    for (index, value) in items.into_iter().enumerate() {
        interp.create_data_property_or_throw(&result, index, value)?;
    }
    Ok(Value::Object(result))
}

/// `a.toSpliced(start, deleteCount, ...items)`: a spliced copy, receiver untouched.
/// §23.1.3.34 `Array.prototype.toSpliced ( start, skipCount, ...items )`.
///
/// Three argument cases, and getting the *first* one wrong made the plain call answer `[]`:
/// with no arguments at all, `itemCount` is `0` so the spec's "`start` absent ⇒ delete
/// nothing" branch applies, where `args.get(1)` being `None` meant "delete to the end"
/// (`toSpliced/start-and-deleteCount-missing`).
///
/// Two bounds, in this order: `len - actualDeleteCount + itemCount > 2**53 - 1` is a
/// **`TypeError`** (the integer limit), and only then does `ArrayCreate` refuse a length past
/// `2**32 - 1` with a **`RangeError`**
/// (`toSpliced/length-exceeding-array-length-limit` asserts both, at both boundaries).
fn to_spliced(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let object = receiver(interp, &this)?;
    let length = receiver_length(interp, &object)?;
    let actual_start = match args.first() {
        None => 0,
        Some(value) => relative_index(interp, Some(value), length)?,
    };
    let actual_delete_count = match args.len() {
        0 => 0,
        1 => length - actual_start,
        _ => {
            let count = to_integer_or_infinity(interp, &args[1])?;
            if count <= 0.0 {
                0
            } else if count >= (length - actual_start) as f64 {
                length - actual_start
            } else {
                count as usize
            }
        }
    };
    let items: Vec<Value> = args.iter().skip(2).cloned().collect();
    let remaining = length - actual_delete_count;
    if remaining
        .checked_add(items.len())
        .is_none_or(|total| total > MAX_INTEGER)
    {
        return Err(interp.type_error("invalid array length"));
    }
    let new_length = remaining + items.len();
    // `ArrayCreate`'s own bound, which is the smaller of the two.
    array_create_length(interp, new_length)?;
    let result = interp.new_array_of_length(new_length);
    // The discarded range is never read, which is the point of
    // `discarded-element-not-read`: a getter on a deleted index must not run.
    // Plain `Get` per index, **not** `HasProperty`: a hole becomes an own `undefined`, and an
    // index the prototype supplies becomes an own value (`toSpliced/holes-not-preserved`
    // asserts `hasOwnProperty` at both).
    let mut target = 0usize;
    for index in 0..actual_start {
        let value = receiver_element(interp, &object, index)?.unwrap_or(Value::Undefined);
        interp.create_data_property_or_throw(&result, target, value)?;
        target += 1;
    }
    for item in items {
        interp.create_data_property_or_throw(&result, target, item)?;
        target += 1;
    }
    for index in (actual_start + actual_delete_count)..length {
        let value = receiver_element(interp, &object, index)?.unwrap_or(Value::Undefined);
        interp.create_data_property_or_throw(&result, target, value)?;
        target += 1;
    }
    Ok(Value::Object(result))
}

/// `a.toLocaleString()`: each element through its own `toLocaleString`, joined by `,`.
///
/// Distinct from `toString` because the *elements* are asked, not the array: `Number`
/// reaches `Number.prototype.toLocaleString`, `BigInt` reaches `BigInt.prototype`'s, and
/// an element that overrides the method is honoured.
fn to_locale_string(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let object = receiver(interp, &this)?;
    let length = receiver_length(interp, &object)?;
    let mut parts = Vec::with_capacity(length.min(1024));
    for index in 0..length {
        let element = receiver_element(interp, &object, index)?.unwrap_or(Value::Undefined);
        // `undefined` and `null` contribute an empty field, exactly as `join` does.
        if matches!(element, Value::Undefined | Value::Null) {
            parts.push(String::new());
            continue;
        }
        // Read `toLocaleString` off the element's own chain, boxing a primitive first so
        // that the prototype method is reachable.
        let method = match &element {
            Value::Object(element) => interp.get_property(element, "toLocaleString")?,
            primitive => {
                let boxed = interp.object_from(primitive)?;
                interp.get_property(&boxed, "toLocaleString")?
            }
        };
        let text = match method {
            Some(method) if matches!(&method, Value::Object(o) if o.is_callable()) => {
                let result = interp.call_value(method, element.clone(), Vec::new())?;
                interp.to_js_string(&result)?
            }
            // §23.1.3.26 step 6.b.ii invokes unconditionally and a missing method is a
            // `TypeError`, but the reference answers with `ToString` for the primitives
            // whose prototype method is absent, so this keeps that behaviour.
            _ => interp.to_js_string(&element)?,
        };
        parts.push(text);
    }
    Ok(interp.string(parts.join(",")))
}

/// The `@@unscopables` list: `Object.create(null)` with `true` at each method name.
///
/// `with (obj) { entries }` must resolve to `obj.entries`, not to
/// `Array.prototype.entries`, when `obj` is an array — that is the whole point of the
/// list. `with` is deliberately **absent**: it would otherwise hide the binding named
/// `obj.with`, and the spec leaves it off.
fn unscopables(interp: &Interp<'_>) -> Value {
    let list = interp.new_object(None);
    for name in [
        "at",
        "copyWithin",
        "entries",
        "fill",
        "find",
        "findIndex",
        "findLast",
        "findLastIndex",
        "flat",
        "flatMap",
        "includes",
        "keys",
        "toReversed",
        "toSorted",
        "toSpliced",
        "values",
    ] {
        list.define(name, Property::data(Value::Bool(true)));
    }
    Value::Object(list)
}