quickjs-pure 0.17.24

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
//! `Iterator` and its helpers (ES2025 §27.1.4 plus the sequencing additions).
//!
//! Every helper is *lazy*: `xs.map(f)` does no work until something calls `next`. That is
//! the whole point of the API — `(function*(){ while (true) yield 1 })().take(3).toArray()`
//! has to terminate — so the state a helper needs between calls lives on the returned
//! object and one shared `next` implementation drives all of them.
//!
//! The state is ordinary non-enumerable properties rather than a dedicated interior slot
//! because a `NativeFn` is a plain function pointer and cannot capture. Hidden properties
//! are also what keeps the collector honest: everything a helper holds is a `Value` in the
//! property table, so a suspended helper keeps its source iterator and callback alive.
//!
//! Two semantics are easy to get wrong and are called out where they matter:
//!
//! * **No eager brand check.** `Iterator.prototype.map.call({}, f)` does *not* throw: the
//!   receiver only has to be an object. The failure comes later, when `next` reads `this`
//!   as an iterator record and finds no callable `next`.
//! * **`return` propagates.** Closing a helper closes the iterator underneath it, exactly
//!   once, which is what makes `using` and `for…of` cleanup visible through a chain.

use crate::builtins::{arg, define_method};
use crate::interp::{Interp, JsResult, Signal};
use crate::object::{JsObject, Property};
use crate::value::Value;

/// Which helper a returned object implements.
///
/// Stored as an `int` property so it survives in the property table; the order is private
/// to this module.
const KIND_MAP: i32 = 1;
const KIND_FILTER: i32 = 2;
const KIND_TAKE: i32 = 3;
const KIND_DROP: i32 = 4;
const KIND_FLAT_MAP: i32 = 5;
const KIND_CHUNKS: i32 = 6;
const KIND_WINDOWS: i32 = 7;
const KIND_WRAP: i32 = 8;
const KIND_CONCAT: i32 = 9;
const KIND_ZIP: i32 = 10;
const KIND_ZIP_KEYED: i32 = 11;

/// The hidden properties of a helper object.
const SOURCE: &str = "_source";
const SOURCE_NEXT: &str = "_sourceNext";
const CALLBACK: &str = "_callback";
const KIND: &str = "_kind";
const REMAINING: &str = "_remaining";
const INNER: &str = "_inner";
const BUFFER: &str = "_buffer";
const LIST: &str = "_list";
const CURSOR: &str = "_cursor";
const CURSOR_INNER: &str = "_cursorInner";
/// The iterator methods `concat` captured, in the same order as [`LIST`].
const LIST_METHODS: &str = "_listMethods";
const MODE: &str = "_mode";
const KEYS: &str = "_keys";
const COUNTER: &str = "_counter";
const PADDING: &str = "_padding";
/// Per-source `open`/`closed`/`exhausted` state, as a JS array of ints.
const ZIP_STATES: &str = "_zipStates";
const DONE: &str = "_done";

/// Set while a helper's `next` is executing, so a re-entrant call is a `TypeError`.
const RUNNING: &str = "_running";
/// Whether the helper has yielded at least once, i.e. its generator state is
/// `suspended-yield` rather than `suspended-start`.
const STARTED: &str = "_started";

/// `windows(size, undersized)`: whether the last, short window is yielded.
///
/// §24.5.4.9's `undersized` defaults to `"only-full"`; `"allow-partial"` yields whatever is
/// left when the source runs out.
const ALLOW_PARTIAL: &str = "_allow_partial";

/// `2^53 - 1`, the upper bound `ToIntegerOrInfinity`'s callers impose on a count
/// (§7.1.5 gives the range, and `Iterator.prototype.take` refuses past it).
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;

/// Install `Iterator`.
pub fn install(interp: &mut Interp<'_>, object_proto: &js_gc::Gc<JsObject>) {
    let iterator_proto = interp.new_object(Some(object_proto.clone()));
    let iterator = interp.new_native("Iterator", 0, iterator_constructor);
    // `Iterator.prototype.constructor`'s getter is a bare `fn` pointer and cannot capture
    // this, so the realm holds it (`realm.iterator_ctor`).
    interp.realm.iterator_ctor = Some(iterator.clone());
    // `Iterator` is an abstract class: `new` is refused, and calling it says so with a
    // different message, which is how the reference distinguishes the two mistakes.
    iterator.set_constructible(true);
    iterator.set_class_constructor(true);
    iterator.define(
        "prototype",
        Property::with_attributes(Value::Object(iterator_proto.clone()), false, false),
    );
    iterator.define("name", Property::name_or_length(interp.string("Iterator")));
    iterator.define("length", Property::name_or_length(Value::Int(0)));

    define_method(&iterator_proto, "map", 1, map, interp);
    define_method(&iterator_proto, "filter", 1, filter, interp);
    define_method(&iterator_proto, "take", 1, take, interp);
    define_method(&iterator_proto, "drop", 1, drop, interp);
    define_method(&iterator_proto, "flatMap", 1, flat_map, interp);
    define_method(&iterator_proto, "reduce", 1, reduce, interp);
    define_method(&iterator_proto, "toArray", 0, to_array, interp);
    define_method(&iterator_proto, "forEach", 1, for_each, interp);
    define_method(&iterator_proto, "some", 1, some, interp);
    define_method(&iterator_proto, "every", 1, every, interp);
    define_method(&iterator_proto, "find", 1, find, interp);
    define_method(&iterator_proto, "join", 1, join, interp);
    define_method(&iterator_proto, "includes", 1, includes, interp);
    define_method(&iterator_proto, "chunks", 1, chunks, interp);
    define_method(&iterator_proto, "windows", 1, windows, interp);

    // `Iterator.prototype[Symbol.iterator]` answers `this`, so an iterator is iterable
    // and `for (x of it)` consumes it in place rather than copying.
    let iterator_key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::Iterator);
    let identity = interp.new_native("[Symbol.iterator]", 0, identity_iterator);
    iterator_proto.define_key(
        &iterator_key,
        Property::with_attributes(Value::Object(identity), true, false),
    );
    // §27.1.4.1: `Iterator.prototype[@@dispose]` closes the iterator, which is what lets
    // `using it = xs.values()` clean up.
    let dispose_key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::Disposable);
    let dispose = interp.new_native("[Symbol.dispose]", 0, dispose_self);
    iterator_proto.define_key(
        &dispose_key,
        Property::with_attributes(Value::Object(dispose), true, false),
    );
    // §27.1.3.1: `Iterator.prototype[@@toStringTag]` is an **accessor** pair, not a data
    // property — the getter answers `"Iterator"` for any receiver (including none), and the
    // setter is `SetterThatIgnoresPrototypeProperties`, so assigning to it from an ordinary
    // object shadows the accessor while assigning on the home object throws
    // (`Symbol.toStringTag/prop-desc`, `…/weird-setter`).
    let tag_getter = interp.new_native("get [Symbol.toStringTag]", 0, iterator_tag_getter);
    let tag_setter = interp.new_native("set [Symbol.toStringTag]", 1, iterator_tag_setter);
    let tag_key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::ToStringTag);
    iterator_proto.define_key(
        &tag_key,
        Property {
            getter: Some(Value::Object(tag_getter)),
            setter: Some(Value::Object(tag_setter)),
            enumerable: false,
            configurable: true,
            ..Property::default()
        },
    );

    // `Iterator.prototype.constructor` is an **accessor**, not a data property
    // (`sec-set-iteratorprototype-constructor`). Both halves are §7.3.40
    // `SetterThatIgnoresPrototypeProperties`, the same mechanism `Error.prototype.stack`
    // needs — so the setter here is one call into it, and the point is the same: assigning
    // to `Iterator.prototype.constructor` throws instead of shadowing the accessor.
    //
    // The getter answers `Iterator` for any object, including `get.call()` with no
    // receiver at all (`weird-setter` asserts exactly that), which is why it does not read
    // `this`.
    let ctor_getter = interp.new_native("get constructor", 0, iterator_constructor_getter);
    let ctor_setter = interp.new_native("set constructor", 1, iterator_constructor_setter);
    iterator_proto.define(
        "constructor",
        Property {
            getter: Some(Value::Object(ctor_getter)),
            setter: Some(Value::Object(ctor_setter)),
            enumerable: false,
            configurable: true,
            ..Property::default()
        },
    );

    // The helper prototype sits between a helper object and `Iterator.prototype`, so a
    // helper *is* an `Iterator` while still being recognisable as one.
    let helper_proto = interp.new_object(Some(iterator_proto.clone()));
    define_method(&helper_proto, "next", 0, helper_next, interp);
    define_method(&helper_proto, "return", 0, helper_return, interp);
    helper_proto.define_key(
        &interp
            .realm
            .well_known_key(crate::interp::WellKnown::ToStringTag),
        Property::with_attributes(interp.string("Iterator Helper"), false, false),
    );
    interp.realm.iterator_helper_proto = Some(helper_proto);

    // `Iterator.from` wraps an object that is iterable but is not itself an `Iterator`.
    // Its prototype forwards `next`/`return` verbatim and deliberately does not override
    // `@@toStringTag`, so such a wrapper still prints `[object Iterator]`.
    let wrap_proto = interp.new_object(Some(iterator_proto.clone()));
    define_method(&wrap_proto, "next", 0, wrap_next, interp);
    define_method(&wrap_proto, "return", 0, wrap_return, interp);
    interp.realm.iterator_wrap_proto = Some(wrap_proto);

    define_method(&iterator, "from", 1, from, interp);
    define_method(&iterator, "concat", 0, concat, interp);
    define_method(&iterator, "zip", 1, zip, interp);
    define_method(&iterator, "zipKeyed", 1, zip_keyed, interp);

    interp.realm.iterator_proto = Some(iterator_proto);
    let global = interp.realm.global.clone();
    global.define(
        "Iterator",
        Property::with_attributes(Value::Object(iterator), true, false),
    );
}

// ---------------------------------------------------------------------------
// The abstract constructor
// ---------------------------------------------------------------------------

fn iterator_constructor(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // §27.1.3.1: `Iterator` may be *subclassed* but not instantiated. `new Sub()` where
    // `class Sub extends Iterator {}` has to succeed and build a `Sub` — 171 test262 cases
    // subclass it — while `new Iterator()` itself throws.
    //
    // `NewTarget` is what separates the two, and `this` already answers for it: the
    // runtime pre-created this object from `NewTarget.prototype`, so its prototype is
    // exactly `Iterator.prototype` when and only when NewTarget was `Iterator` itself.
    if matches!(this, Value::Undefined) {
        return Err(Signal::Throw(
            interp.make_error("TypeError", "constructor requires 'new'"),
        ));
    }
    let own_proto = this
        .as_object()
        .and_then(|object| object.proto())
        .is_some_and(|proto| {
            interp
                .realm
                .iterator_proto
                .as_ref()
                .is_some_and(|target| proto.ptr_eq(target))
        });
    if own_proto {
        return Err(Signal::Throw(
            interp.make_error("TypeError", "abstract class not constructable"),
        ));
    }
    // A subclass: the instance the runtime made is the answer.
    Ok(this)
}

fn identity_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(this)
}

/// `Iterator.prototype.constructor`'s getter: always `Iterator`, whatever `this` is.
///
/// `weird-setter` calls `get.call()` with no receiver at all and expects `Iterator` back,
/// so this deliberately does not validate `this`.
fn iterator_constructor_getter(
    interp: &mut Interp<'_>,
    _this: Value,
    _args: &[Value],
) -> JsResult<Value> {
    match interp.realm.iterator_ctor.clone() {
        Some(ctor) => Ok(Value::Object(ctor)),
        None => Ok(Value::Undefined),
    }
}

/// `Iterator.prototype.constructor`'s setter: §7.3.40 with `home = Iterator.prototype`.
fn iterator_constructor_setter(
    interp: &mut Interp<'_>,
    this: Value,
    args: &[Value],
) -> JsResult<Value> {
    let Some(home) = interp.realm.iterator_proto.clone() else {
        return Err(interp.type_error("Iterator.prototype is not installed"));
    };
    interp.setter_that_ignores_prototype_properties(this, &home, "constructor", args)
}

fn dispose_self(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let record = iterator_record(interp, &this)?;
    close(interp, &record)?;
    Ok(Value::Undefined)
}

// ---------------------------------------------------------------------------
// Iterator records
// ---------------------------------------------------------------------------

/// `GetIteratorDirect(obj)`: a snapshot of `obj.next`.
///
/// Taking `next` once, here, is observable: an iterable whose `next` is a getter sees one
/// read, not one per step, and replacing `next` after the helper is created has no effect.
fn iterator_record(interp: &mut Interp<'_>, value: &Value) -> JsResult<crate::interp::Iterator> {
    let Some(object) = value.as_object().cloned() else {
        return Err(interp.type_error("not an object"));
    };
    // `Get(obj, "next")` and nothing more: §7.3.11 `GetIteratorDirect` does **not** check
    // that `next` is callable. That check happens when the method is called, which is why
    // `Iterator.from({return(){}})` — an object with no `next` at all — succeeds, while
    // `Iterator.prototype.find.call({next: 0}, f)` still throws, just one step later. See
    // [`step`] for where it happens.
    let next = interp
        .get_property(&object, "next")?
        .unwrap_or(Value::Undefined);
    Ok(crate::interp::Iterator {
        object: Value::Object(object),
        next,
    })
}

/// `IteratorStep`: one value, or `None` when the iterator is exhausted.
///
/// The callability check lives here rather than in [`iterator_record`], because that is
/// where the spec puts it: `[[NextMethod]]` is whatever `next` was at record-creation time,
/// and calling a non-callable is a `TypeError`. `iterator_step` treats a non-callable as
/// "already exhausted", which is the right reading for a `for…of` over a finished iterator
/// but not for a helper that was handed garbage.
fn step(interp: &mut Interp<'_>, record: &crate::interp::Iterator) -> JsResult<Option<Value>> {
    if !matches!(&record.next, Value::Object(function) if function.is_callable()) {
        return Err(interp.type_error("not a function"));
    }
    let (value, done) = interp.iterator_step(record)?;
    Ok(if done { None } else { Some(value) })
}

/// [`step`], on a helper whose source this is: a throw out of the source's own `next`
/// **completes the helper** without forwarding `return` to the source.
///
/// The distinction is `§`27.1.4.4's: an iterator helper's body is a generator, so an
/// abrupt completion from `next` runs the generator's own completion — which for these
/// helpers includes `IteratorClose` only for the *steps inside the body*, not for the step
/// that failed. `take/completed-after-abrupt-completion` asserts `retCalls === 0` after a
/// throwing source `next`, while `map/mapper-throws` asserts `returnCalls === 1` for a
/// throwing *callback*. Both are correct; the difference is where the throw came from.
fn step_source(
    interp: &mut Interp<'_>,
    helper: &JsObject,
    record: &crate::interp::Iterator,
) -> JsResult<Option<Value>> {
    match step(interp, record) {
        Err(signal) => {
            // Mark done so a later `next()` answers `{done: true}` and a later `return()`
            // is not forwarded (`helper_return` reads this flag).
            write_hidden(helper, DONE, Value::Bool(true));
            Err(signal)
        }
        ok => ok,
    }
}

/// `IteratorClose`: tell the iterator it will not be read again.
///
/// Used when a consumer stops early. Errors from the iterator's own `return` are swallowed
/// on the "we were already leaving" path, which is what §7.4.11 asks for.
fn close(interp: &mut Interp<'_>, record: &crate::interp::Iterator) -> JsResult<()> {
    let Some(source) = record.object.as_object().cloned() else {
        return Ok(());
    };
    let method = interp.get_property(&source, "return")?;
    match method {
        // §7.4.11 `IteratorClose` steps 4–6: a missing `return` is a no-op, but a
        // **non-callable** one is a `TypeError`, and a non-object result is one too. Both
        // are checked and neither was before, so `concat`'s three close tests saw a clean
        // exit instead of the error the spec asks for
        // (`return-method-not-callable`, `return-method-returns-non-object`).
        None | Some(Value::Undefined) | Some(Value::Null) => Ok(()),
        Some(Value::Object(function)) if function.is_callable() => {
            let result =
                interp.call_value(Value::Object(function), record.object.clone(), Vec::new())?;
            if !matches!(result, Value::Object(_)) {
                return Err(interp.type_error("iterator return did not answer an object"));
            }
            Ok(())
        }
        Some(_) => Err(interp.type_error("iterator return is not a function")),
    }
}

// ---------------------------------------------------------------------------
// Building a helper
// ---------------------------------------------------------------------------

/// `IfAbruptCloseIterator(this, …)` for a helper whose argument was rejected.
///
/// The receiver is closed *without* reading `next`: validation happens before
/// `GetIteratorDirect`, so a `next` getter that throws must never run — but `return` must,
/// which is what `argument-validation-failure-closes-underlying` checks.
fn close_receiver(interp: &mut Interp<'_>, this: &Value) -> JsResult<()> {
    let Some(object) = this.as_object().cloned() else {
        return Ok(());
    };
    match interp.get_property(&object, "return")? {
        Some(Value::Object(function)) if function.is_callable() => {
            interp.call_value(Value::Object(function), this.clone(), Vec::new())?;
            Ok(())
        }
        _ => Ok(()),
    }
}

/// `ToIntegerOrInfinity` for a helper's count argument.
///
/// `ToNumber` comes first and is *observable*, so it cannot be folded into this: a limit
/// object's `valueOf` runs before `next` is read, and a test records exactly that order.
fn count_argument(
    interp: &mut Interp<'_>,
    this: &Value,
    value: &Value,
    message: &str,
) -> JsResult<f64> {
    // §7.2.9: a non-object receiver is a `TypeError` *before* the argument is examined —
    // `windows.call(null, 0)` must not report the bad count.
    if !matches!(this, Value::Object(_)) {
        return Err(interp.type_error("not an object"));
    }
    let number = match interp.to_js_number(value) {
        Ok(number) => number,
        Err(signal) => {
            // A close that *itself* throws must not mask the original error: `IteratorClose`
            // returns the incoming throw completion whatever the `return` call did
            // (`chunks/argument-validation-failure-close-throws`).
            let _ = close_receiver(interp, this);
            return Err(signal);
        }
    };
    // The count is `ToNumber` → truncate, and then **`≥ 0` and `≤ 2^53 - 1`**. Note what
    // is *not* `ToIntegerOrInfinity`: `NaN` must stay a `RangeError` rather than becoming
    // `0`, and `undefined` (which `ToNumber`s to `NaN`) is refused for the same reason.
    // `take/limit-rangeerror` lists all of it, including `Infinity` being *accepted*.
    let integer = number.trunc();
    // `Infinity` is accepted (it means "no limit"); only a *finite* value past the bound is
    // refused, which is what `take/limit-rangeerror` distinguishes by listing both
    // `Infinity` (ok) and `MAX_SAFE_INTEGER + 1` (`RangeError`).
    let out_of_range =
        integer.is_nan() || integer < 0.0 || (integer.is_finite() && integer > MAX_SAFE_INTEGER);
    if out_of_range {
        // A close that *itself* throws must not mask the original error: `IteratorClose`
        // returns the incoming throw completion whatever the `return` call did
        // (`chunks/argument-validation-failure-close-throws`).
        let _ = close_receiver(interp, this);
        return Err(interp.range_error(message));
    }
    Ok(integer)
}

/// The `chunkSize`/`windowSize` argument: it must already be an integral Number.
///
/// Unlike `take`/`drop`, these two do **not** run `ToNumber`. `chunks("2")` is a
/// `TypeError`, not `chunks(2)` — a string that looks like a count is a mistake worth
/// reporting rather than guessing at. `NaN`, `0.5`, `Infinity` and objects are all
/// refused for the same reason.
fn integral_count(
    interp: &mut Interp<'_>,
    this: &Value,
    value: &Value,
    name: &str,
) -> JsResult<f64> {
    if !matches!(this, Value::Object(_)) {
        return Err(interp.type_error("not an object"));
    }
    let rejected = interp.type_error(format!("{name} is not an integral number"));
    let number = match value {
        Value::Int(number) => *number as f64,
        Value::Float(number) if number.is_finite() && number.trunc() == *number => *number,
        _ => {
            // A close that *itself* throws must not mask the original error: `IteratorClose`
            // returns the incoming throw completion whatever the `return` call did
            // (`chunks/argument-validation-failure-close-throws`).
            let _ = close_receiver(interp, this);
            return Err(rejected);
        }
    };
    // §24.5.4.6 step 8 / §24.5.4.9 step 8: `chunkSize < 1 or chunkSize > 2**32 - 1` is a
    // `RangeError`. The upper bound is `ToUint32`'s, not `MAX_SAFE_INTEGER`'s, which is why
    // `chunks/chunkSize-out-of-range` accepts `2**32 - 1` and refuses `2**32`.
    if !(1.0..=MAX_CHUNK_SIZE).contains(&number) {
        // A close that *itself* throws must not mask the original error: `IteratorClose`
        // returns the incoming throw completion whatever the `return` call did
        // (`chunks/argument-validation-failure-close-throws`).
        let _ = close_receiver(interp, this);
        return Err(interp.range_error(format!("{name} out of range")));
    }
    Ok(number)
}

/// The largest `chunkSize`/`windowSize` the helpers accept: `2**32 - 1`.
const MAX_CHUNK_SIZE: f64 = 4_294_967_295.0;

/// Allocate a helper object over `source` with the given `kind`.
fn helper(
    interp: &mut Interp<'_>,
    source: crate::interp::Iterator,
    kind: i32,
    callback: Option<Value>,
) -> JsResult<Value> {
    let proto = interp
        .realm
        .iterator_helper_proto
        .clone()
        .ok_or_else(|| interp.type_error("iterator helpers are not installed"))?;
    let object = interp.new_object(Some(proto));
    let hidden = |value: Value| Property::with_attributes(value, true, false);
    object.define(SOURCE, hidden(source.object));
    object.define(SOURCE_NEXT, hidden(source.next));
    object.define(KIND, hidden(Value::Int(kind)));
    object.define(DONE, hidden(Value::Bool(false)));
    object.define(COUNTER, hidden(Value::Int(0)));
    if let Some(callback) = callback {
        object.define(CALLBACK, hidden(callback));
    }
    Ok(Value::Object(object))
}

fn read_hidden(_interp: &mut Interp<'_>, object: &JsObject, name: &str) -> JsResult<Value> {
    // A hidden property is always an own data property written by `write_hidden`, so the
    // own-property read is both correct and immune to a script putting a getter named
    // `_source` on `Object.prototype`.
    Ok(object
        .own_property(name)
        .and_then(|property| property.value)
        .unwrap_or(Value::Undefined))
}

fn write_hidden(object: &JsObject, name: &str, value: Value) {
    object.define(name, Property::with_attributes(value, true, false));
}

/// The receiver as an iterator record, or the `TypeError` a non-object gets.
fn source_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<crate::interp::Iterator> {
    iterator_record(interp, this)
}

/// The callback argument, which must be callable.
/// The callback argument, which must be callable.
///
/// The receiver is closed on refusal: §7.4.11 applies to a failed *validation* as much as
/// to a throwing callback, and `argument-validation-failure-closes-underlying` checks it.
fn require_callback(interp: &mut Interp<'_>, this: &Value, value: &Value) -> JsResult<Value> {
    match value {
        Value::Object(object) if object.is_callable() => Ok(value.clone()),
        _ => {
            let _ = close_receiver(interp, this);
            Err(interp.type_error("not a function"))
        }
    }
}

// ---------------------------------------------------------------------------
// The shared `next`
// ---------------------------------------------------------------------------

fn helper_next(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // §27.1.4.4 step 1: a helper is a generator, and stepping a generator that is already
    // running is a `TypeError`. The case that notices is a source `next` which calls back
    // into the helper: `TestIterator.next` does `iter.next()` on the helper it is feeding
    // (`throws-typeerror-when-generator-is-running`, every helper).
    //
    // Tracked with a plain flag on the helper object rather than by reusing the generator
    // machinery, because these helpers are native functions with hidden slots, not real
    // generator frames.
    if let Some(object) = this.as_object().cloned() {
        // A helper that is already **completed** may be re-entered: `return` on a
        // suspended-start helper completes it *before* closing its sources, so a source's
        // `return` that calls back into the helper gets `{done: true}`
        // (`zip/suspended-start-iterator-close-calls-next`).
        if read_hidden(interp, &object, RUNNING)?.to_boolean()
            && !read_hidden(interp, &object, DONE)?.to_boolean()
        {
            return Err(interp.type_error("iterator helper is already running"));
        }
        write_hidden(&object, RUNNING, Value::Bool(true));
        let outcome = helper_step(interp, &this, args);
        write_hidden(&object, RUNNING, Value::Bool(false));
        // Track `[[GeneratorState]]`: a value handed out means `suspended-yield`, and that
        // is what tells `return` whether it is resuming abruptly (state `executing` while the
        // sources are closed) or completing a helper that never started.
        if let Ok(value) = &outcome
            && let Some(result) = value.as_object().cloned()
            && !interp
                .get_property(&result, "done")?
                .is_some_and(|done| done.to_boolean())
        {
            write_hidden(&object, STARTED, Value::Bool(true));
        }
        // A throw from a *callback* closes the source (§7.4.11): `map/mapper-throws`
        // counts exactly one `return` call. A throw from the source's own `next` does not
        // — `step_source` has already marked the helper done in that case, which is what
        // `completed-after-abrupt-completion` relies on (`retCalls === 0`).
        if outcome.is_err() && !read_hidden(interp, &object, DONE)?.to_boolean() {
            // `close_helper` sets `DONE` itself; setting it here first made the helper look
            // already-closed and the source was never told (`mapper-throws` counts zero
            // `return` calls instead of one).
            let _ = close_helper(interp, &object);
        }
        return outcome;
    }
    helper_step(interp, &this, args)
}

fn helper_step(interp: &mut Interp<'_>, this: &Value, _args: &[Value]) -> JsResult<Value> {
    let this = this.clone();
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("not an object"));
    };
    if read_hidden(interp, &object, DONE)?.to_boolean() {
        return Ok(done_result(interp));
    }
    let kind = read_hidden(interp, &object, KIND)?.to_number() as i32;
    match kind {
        KIND_MAP => {
            let source = stored_source(&object, interp)?;
            let Some(value) = step_source(interp, &object, &source)? else {
                write_hidden(&object, DONE, Value::Bool(true));
                return Ok(done_result(interp));
            };
            let callback = read_hidden(interp, &object, CALLBACK)?;
            let counter = read_hidden(interp, &object, COUNTER)?.to_number();
            write_hidden(&object, COUNTER, Value::Float(counter + 1.0));
            // The mapper gets `(value, counter)`: the second argument is a running index,
            // and a test checks it counts 0,1,2,… across a generator.
            let mapped = interp.call_value(
                callback,
                Value::Undefined,
                vec![value, Value::Int(counter as i32)],
            )?;
            Ok(value_result(interp, mapped))
        }
        KIND_FILTER => {
            let source = stored_source(&object, interp)?;
            let callback = read_hidden(interp, &object, CALLBACK)?;
            // Keep pulling until the predicate says yes; an exhausted source is the only
            // other way out, so an always-false predicate terminates instead of spinning.
            loop {
                let Some(value) = step_source(interp, &object, &source)? else {
                    write_hidden(&object, DONE, Value::Bool(true));
                    return Ok(done_result(interp));
                };
                let counter = read_hidden(interp, &object, COUNTER)?.to_number();
                write_hidden(&object, COUNTER, Value::Float(counter + 1.0));
                let keep = interp.call_value(
                    callback.clone(),
                    Value::Undefined,
                    vec![value.clone(), Value::Int(counter as i32)],
                )?;
                if keep.to_boolean() {
                    return Ok(value_result(interp, value));
                }
            }
        }
        KIND_TAKE => {
            let remaining = read_hidden(interp, &object, REMAINING)?.to_number();
            if remaining <= 0.0 {
                // `take(0)` never touches the source, and the spec still wants it closed.
                write_hidden(&object, DONE, Value::Bool(true));
                let source = stored_source(&object, interp)?;
                close(interp, &source)?;
                return Ok(done_result(interp));
            }
            let source = stored_source(&object, interp)?;
            let Some(value) = step_source(interp, &object, &source)? else {
                write_hidden(&object, DONE, Value::Bool(true));
                return Ok(done_result(interp));
            };
            // The close happens on the call **after** the last value, not during it.
            // `take` is a generator whose loop re-checks `remaining <= 0` on the next
            // resume, so `take(1)` yields one value and only the *second* `next` calls
            // `return` — and if that `return` throws, it is the second call that reports
            // it (`take/exhaustion-calls-return` asserts the throw and then two quiet
            // `done` results). Closing eagerly made the first `next` throw instead.
            write_hidden(&object, REMAINING, Value::Float(remaining - 1.0));
            Ok(value_result(interp, value))
        }
        KIND_DROP => {
            let source = stored_source(&object, interp)?;
            let mut left = read_hidden(interp, &object, REMAINING)?.to_number();
            while left > 0.0 {
                if step_source(interp, &object, &source)?.is_none() {
                    write_hidden(&object, DONE, Value::Bool(true));
                    return Ok(done_result(interp));
                }
                left -= 1.0;
            }
            write_hidden(&object, REMAINING, Value::Float(0.0));
            match step_source(interp, &object, &source)? {
                Some(value) => Ok(value_result(interp, value)),
                None => {
                    write_hidden(&object, DONE, Value::Bool(true));
                    Ok(done_result(interp))
                }
            }
        }
        KIND_FLAT_MAP => {
            let callback = read_hidden(interp, &object, CALLBACK)?;
            loop {
                // Drain the inner iterator first: `flatMap` flattens one level, so the
                // outer step only happens once the current inner one is exhausted.
                let inner = read_hidden(interp, &object, INNER)?;
                if let Value::Object(_) = &inner {
                    let inner_record = iterator_record(interp, &inner)?;
                    // §27.1.4.3 step 2.f.ii: `IfAbruptCloseIterator(innerValue, iterated)` —
                    // the **outer** iterator is closed, the inner one is not. Marking the
                    // helper done afterwards is what stops `helper_next`'s own error path
                    // from closing the inner one on the way out
                    // (`flatMap/inner-iterator-not-closed-when-inner-step-throws`).
                    let stepped = match step(interp, &inner_record) {
                        Ok(stepped) => stepped,
                        Err(signal) => {
                            write_hidden(&object, DONE, Value::Bool(true));
                            let source = stored_source(&object, interp)?;
                            let _ = close(interp, &source);
                            return Err(signal);
                        }
                    };
                    if let Some(value) = stepped {
                        return Ok(value_result(interp, value));
                    }
                    write_hidden(&object, INNER, Value::Undefined);
                }
                let source = stored_source(&object, interp)?;
                let Some(value) = step_source(interp, &object, &source)? else {
                    write_hidden(&object, DONE, Value::Bool(true));
                    return Ok(done_result(interp));
                };
                let counter = read_hidden(interp, &object, COUNTER)?.to_number();
                write_hidden(&object, COUNTER, Value::Float(counter + 1.0));
                let produced = interp.call_value(
                    callback.clone(),
                    Value::Undefined,
                    vec![value, Value::Int(counter as i32)],
                )?;
                // `flatMap` iterates what the callback returned, and that may be any
                // iterable — an array is the common case — so it goes through the same
                // wrapping `Iterator.from` does.
                // §27.1.4.3 `GetIteratorFlattenable(…, reject-primitives)`: a **string
                // primitive** is refused, because otherwise every character would be a
                // separate element — a `String` *wrapper* is a normal iterable and does
                // flatten (`flatMap/strings-are-not-flattened` checks both halves).
                if matches!(produced, Value::String(_)) {
                    let signal = interp.type_error("flatMap callback returned a string");
                    write_hidden(&object, DONE, Value::Bool(true));
                    close_helper(interp, &object)?;
                    return Err(signal);
                }
                let wrapped = into_iterator(interp, produced)?;
                write_hidden(&object, INNER, wrapped);
            }
        }
        KIND_CHUNKS => {
            let size = read_hidden(interp, &object, REMAINING)?.to_number();
            let source = stored_source(&object, interp)?;
            let mut items = Vec::new();
            while (items.len() as f64) < size {
                match step_source(interp, &object, &source)? {
                    Some(value) => items.push(value),
                    None => break,
                }
            }
            if items.is_empty() {
                write_hidden(&object, DONE, Value::Bool(true));
                return Ok(done_result(interp));
            }
            let array = interp.new_array(items);
            Ok(value_result(interp, Value::Object(array)))
        }
        KIND_WINDOWS => {
            let size = read_hidden(interp, &object, REMAINING)?.to_number() as usize;
            let source = stored_source(&object, interp)?;
            let buffer = read_hidden(interp, &object, BUFFER)?;
            let mut items: Vec<Value> = match &buffer {
                Value::Object(array) => array.array_elements().unwrap_or_default(),
                _ => Vec::new(),
            };
            let allow_partial = read_hidden(interp, &object, ALLOW_PARTIAL)?.to_boolean();
            // Both arms end up here when the source runs out: `"only-full"` stops, and
            // `"allow-partial"` yields whatever is left — one short window, once — which
            // is what `windows/windows-allow-partial` and `windows/undersized-default`
            // differ on. An empty buffer is `done` either way
            // (`windows/iterator-already-exhausted`).
            let mut exhausted = false;
            if items.is_empty() {
                // Prime the window, then yield the first one.
                while items.len() < size {
                    match step_source(interp, &object, &source)? {
                        Some(value) => items.push(value),
                        None => {
                            exhausted = true;
                            break;
                        }
                    }
                }
            } else {
                // Slide: drop the oldest, take the next.
                items.remove(0);
                match step_source(interp, &object, &source)? {
                    Some(value) => items.push(value),
                    None => exhausted = true,
                }
            }
            if exhausted {
                write_hidden(&object, DONE, Value::Bool(true));
                if !allow_partial || items.is_empty() {
                    return Ok(done_result(interp));
                }
            }
            let stored = interp.new_array(items.clone());
            write_hidden(&object, BUFFER, Value::Object(stored));
            let window = interp.new_array(items);
            Ok(value_result(interp, Value::Object(window)))
        }
        KIND_CONCAT => zip_next_concat(interp, &object),
        KIND_ZIP => zip_next(interp, &object, false),
        KIND_ZIP_KEYED => zip_next(interp, &object, true),
        _ => Err(interp.type_error("not a valid iterator helper")),
    }
}

/// `Iterator.concat(...).next()`: drain the current source, then move to the next one.
fn zip_next_concat(interp: &mut Interp<'_>, object: &JsObject) -> JsResult<Value> {
    loop {
        let inner = read_hidden(interp, object, CURSOR_INNER)?;
        if let Value::Object(_) = &inner {
            let record = iterator_record(interp, &inner)?;
            // `Iterator.concat`'s only `IteratorClose` is the one a *yield* completing
            // abruptly runs, so a step that throws propagates **without** closing the
            // iterator it came from. Marking the helper done is what keeps the error path in
            // `helper_next` from closing it on the way out
            // (`underlying-iterator-not-closed-when-step-throws`).
            let stepped = match step(interp, &record) {
                Ok(stepped) => stepped,
                Err(signal) => {
                    write_hidden(object, DONE, Value::Bool(true));
                    return Err(signal);
                }
            };
            if let Some(value) = stepped {
                return Ok(value_result(interp, value));
            }
            write_hidden(object, CURSOR_INNER, Value::Undefined);
        }
        let cursor = read_hidden(interp, object, CURSOR)?.to_number() as usize;
        let list = read_hidden(interp, object, LIST)?;
        let Some(array) = list.as_object().cloned() else {
            write_hidden(object, DONE, Value::Bool(true));
            return Ok(done_result(interp));
        };
        let items = array.array_elements().unwrap_or_default();
        if cursor >= items.len() {
            write_hidden(object, DONE, Value::Bool(true));
            return Ok(done_result(interp));
        }
        // Each source's `@@iterator` was read at construction; here the stored method is
        // *called*, which is the one call `get-iterator-method-only-once` counts.
        let methods = read_hidden(interp, object, LIST_METHODS)?;
        let Some(methods) = methods.as_object() else {
            write_hidden(object, DONE, Value::Bool(true));
            return Ok(done_result(interp));
        };
        let Some(method) = methods.array_get(cursor) else {
            write_hidden(object, DONE, Value::Bool(true));
            return Ok(done_result(interp));
        };
        let produced = interp.call_value(method, items[cursor].clone(), Vec::new())?;
        if !matches!(produced, Value::Object(_)) {
            return Err(interp.type_error("iterator is not an object"));
        }
        let record = iterator_record(interp, &produced)?;
        write_hidden(object, CURSOR, Value::Int(cursor as i32 + 1));
        write_hidden(object, CURSOR_INNER, record.object.clone());
        // Only the object is kept: the next loop turn re-derives the record from it, so
        // one canonical `next` is used for every source.
    }
}

/// `Iterator.zip(...).next()` / `Iterator.zipKeyed(...).next()`.
/// `Iterator.zip(...).next()` / `Iterator.zipKeyed(...).next()`.
///
/// Follows `IteratorZip`'s closure step by step, because every branch of it is a test: which
/// source is closed when one finishes early, whether the source that threw is closed (it is
/// not — it is the one whose completion is already abrupt), and whether a mismatched length
/// in `strict` mode closes the sources *before* or *after* the remaining ones are stepped.
///
/// Per-source state is the reference's three values: open, closed, and **exhausted** — the
/// last one meaning "this source finished, but `longest` mode keeps yielding its padding
/// value in that position".
fn zip_next(interp: &mut Interp<'_>, object: &JsObject, keyed: bool) -> JsResult<Value> {
    const OPEN: i32 = 0;
    const CLOSED: i32 = 1;
    const EXHAUSTED: i32 = 2;
    let mode = read_hidden(interp, object, MODE)?.to_number() as i32;
    let records = unpack_records(interp, object)?;
    if records.is_empty() {
        // Zero sources: nothing to zip. Answering `done` immediately also keeps the
        // "all exhausted" test below from being vacuously true forever.
        write_hidden(object, DONE, Value::Bool(true));
        return Ok(done_result(interp));
    }
    let mut states = zip_states(interp, object, records.len())?;
    let pads = {
        let stored = read_hidden(interp, object, PADDING)?;
        stored
            .as_object()
            .map(|array| array.array_elements().unwrap_or_default())
            .unwrap_or_default()
    };
    let count = records.len();
    let mut values: Vec<Value> = Vec::with_capacity(count);
    for index in 0..count {
        if states[index] == EXHAUSTED {
            values.push(pads.get(index).cloned().unwrap_or(Value::Undefined));
            continue;
        }
        let stepped = match step(interp, &records[index]) {
            Ok(stepped) => stepped,
            Err(signal) => {
                // The source that threw is *not* closed — it is the one whose completion is
                // already abrupt — but everything still open behind it is, in reverse, and
                // errors raised while closing are swallowed because the original wins.
                states[index] = CLOSED;
                write_hidden(object, DONE, Value::Bool(true));
                zip_close_open(interp, object, &records, &mut states, true);
                return Err(signal);
            }
        };
        match stepped {
            Some(value) => {
                values.push(value);
                continue;
            }
            None => {
                states[index] = CLOSED;
                match mode {
                    0 => {
                        // `shortest`: the first source to finish ends the zip, and every
                        // other open source is closed. Here the close runs with a *normal*
                        // completion, so a throwing `return` is reported.
                        write_hidden(object, DONE, Value::Bool(true));
                        if let Some(signal) =
                            zip_close_open(interp, object, &records, &mut states, false)
                        {
                            return Err(signal);
                        }
                        return Ok(done_result(interp));
                    }
                    2 => {
                        // `strict`: a source finishing at position 0 means every *other*
                        // source must have finished too, and that is checked by stepping
                        // them. Finishing anywhere else is a length mismatch.
                        if index != 0 {
                            let signal = interp.type_error("iterators have different lengths");
                            write_hidden(object, DONE, Value::Bool(true));
                            zip_close_open(interp, object, &records, &mut states, true);
                            return Err(signal);
                        }
                        for later in 1..count {
                            match step(interp, &records[later]) {
                                Ok(None) => states[later] = CLOSED,
                                Ok(Some(_)) => {
                                    let signal =
                                        interp.type_error("iterators have different lengths");
                                    write_hidden(object, DONE, Value::Bool(true));
                                    zip_close_open(interp, object, &records, &mut states, true);
                                    return Err(signal);
                                }
                                Err(signal) => {
                                    states[later] = CLOSED;
                                    write_hidden(object, DONE, Value::Bool(true));
                                    zip_close_open(interp, object, &records, &mut states, true);
                                    return Err(signal);
                                }
                            }
                        }
                        write_hidden(object, DONE, Value::Bool(true));
                        return Ok(done_result(interp));
                    }
                    _ => {
                        // `longest`: keep going while at least one source is still open;
                        // this position now reads its padding value from here on.
                        if !states.contains(&OPEN) {
                            write_hidden(object, DONE, Value::Bool(true));
                            return Ok(done_result(interp));
                        }
                        states[index] = EXHAUSTED;
                        values.push(pads.get(index).cloned().unwrap_or(Value::Undefined));
                        continue;
                    }
                }
            }
        }
    }
    write_zip_states(interp, object, &states);
    let result = if keyed {
        let keys = read_hidden(interp, object, KEYS)?;
        let names = keys
            .as_object()
            .map(|array| array.array_elements().unwrap_or_default())
            .unwrap_or_default();
        // A **null** prototype, not `Object.prototype`: the result is a plain record whose
        // keys come from script data, so inheriting anything would let a key like
        // `toString` collide with a method.
        let entry = interp.new_object(None);
        for (index, value) in values.into_iter().enumerate() {
            let Some(name) = names.get(index).cloned() else {
                continue;
            };
            let key = match &name {
                Value::Symbol(symbol) => crate::object::PropertyKey::Symbol(symbol.clone()),
                Value::String(text) => crate::object::PropertyKey::String(text.wtf8().clone()),
                other => crate::object::PropertyKey::from(other.to_js_string()),
            };
            entry.define_key(&key, Property::with_attributes(value, true, true));
        }
        Value::Object(entry)
    } else {
        let array = interp.new_array(values);
        Value::Object(array)
    };
    Ok(value_result(interp, result))
}

/// The source record a helper was built over.
fn stored_source(object: &JsObject, interp: &mut Interp<'_>) -> JsResult<crate::interp::Iterator> {
    Ok(crate::interp::Iterator {
        object: read_hidden(interp, object, SOURCE)?,
        next: read_hidden(interp, object, SOURCE_NEXT)?,
    })
}

fn helper_return(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // §27.1.4.4 step 1 applies to `return` as much as to `next`: a helper is a generator,
    // and re-entering one that is running is a `TypeError`. The case that notices is a
    // source `return` that calls back into the helper it belongs to
    // (`concat/throws-typeerror-when-generator-is-running-return`).
    let guard = this.as_object().cloned();
    if let Some(object) = &guard {
        // A helper that is already **completed** may be re-entered: a `return` on a
        // suspended-start helper sets the state to completed *before* closing the sources, so
        // a source's `return` that calls back into the helper gets `{done: true}`
        // (`zip/suspended-start-iterator-close-calls-next`).
        if read_hidden(interp, object, RUNNING)?.to_boolean()
            && !read_hidden(interp, object, DONE)?.to_boolean()
        {
            return Err(interp.type_error("iterator helper is already running"));
        }
        write_hidden(object, RUNNING, Value::Bool(true));
    }
    let outcome = helper_return_body(interp, this, args);
    if let Some(object) = &guard {
        write_hidden(object, RUNNING, Value::Bool(false));
    }
    outcome
}

/// [`helper_return`] without the re-entrancy guard.
fn helper_return_body(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // Closing a helper closes what is underneath it, once. Without the propagation a
    // `for…of` over `xs.map(f)` that breaks early would leave `xs` open.
    //
    // A helper that is *already* completed does **not** forward: an iterator helper's body
    // is a generator, so an abrupt completion from it completes the generator, and a later
    // `return()` on a completed generator answers `{done: true}` without running the body's
    // `finally`-equivalent — here, the `IteratorClose` of the source.
    //
    // `completed-after-abrupt-completion` counts exactly that: after a `next()` whose
    // source throws, `return()` must not call the source's `return` (`retCalls` stays 0,
    // while the source is still closed by the abrupt path itself). `close_helper` already
    // short-circuits on `DONE`; the read here is what makes the *intent* explicit and keeps
    // the two paths from sharing one flag by accident.
    if let Some(object) = this.as_object().cloned() {
        if read_hidden(interp, &object, DONE)?.to_boolean() {
            return Ok(done_result(interp));
        }
        // §27.1.4.4 step 4 splits on `[[GeneratorState]]`:
        //
        // * `suspended-start` sets the state to `completed` **before** `IteratorCloseAll`, so
        //   a source's `return` that calls back into the helper gets `{done: true}`
        //   (`zip/suspended-start-iterator-close-calls-next`);
        // * `suspended-yield` is a `GeneratorResumeAbrupt`, so the state is `executing` while
        //   the sources close and the same callback is a `TypeError`
        //   (`zip/suspended-yield-iterator-close-calls-return`).
        if read_hidden(interp, &object, STARTED)?.to_boolean() {
            // The helper is completed either way — a source whose `return` throws must not
            // leave it steppable (`concat/return-method-throws` checks the next two calls).
            let outcome = close_underlying(interp, &object);
            write_hidden(&object, DONE, Value::Bool(true));
            outcome?;
        } else {
            write_hidden(&object, DONE, Value::Bool(true));
            close_underlying(interp, &object)?;
        }
    }
    Ok(done_result(interp))
}

/// Close whatever the helper is currently reading, and mark it done.
///
/// Which source is "underneath" depends on the kind: `flatMap` has a per-element inner
/// iterator, `concat` a per-source one, and the rest a single fixed source. All three are
/// checked, because each is the live one for some helper. The `DONE` flag makes the second
/// close a no-op — a `return` followed by an abrupt completion must not close twice.
fn close_helper(interp: &mut Interp<'_>, object: &JsObject) -> JsResult<()> {
    if read_hidden(interp, object, DONE)?.to_boolean() {
        return Ok(());
    }
    write_hidden(object, DONE, Value::Bool(true));
    close_underlying(interp, object)
}

/// [`close_helper`] without the `DONE` bookkeeping, for the caller that has already set it.
fn close_underlying(interp: &mut Interp<'_>, object: &JsObject) -> JsResult<()> {
    for slot in [INNER, CURSOR_INNER] {
        let inner = read_hidden(interp, object, slot)?;
        if let Value::Object(_) = &inner {
            let record = iterator_record(interp, &inner)?;
            close(interp, &record)?;
        }
    }
    let source = read_hidden(interp, object, SOURCE)?;
    if let Value::Object(_) = &source {
        let record = stored_source(object, interp)?;
        close(interp, &record)?;
    }
    // `Iterator.zip`/`zipKeyed` keep their sources as a flat list rather than a single
    // `_source`, so neither of the slots above is one of them. `return()` on a zip closes
    // **every** underlying iterator, in reverse order — that is the `IteratorClose` its
    // generator body runs when it is returned from
    // (`zip/suspended-start-iterator-close-calls-next` and the nine beside it).
    let kind = read_hidden(interp, object, KIND)?.to_number() as i32;
    if kind == KIND_ZIP || kind == KIND_ZIP_KEYED {
        let records = unpack_records(interp, object)?;
        // Only the sources still **open** are closed: one that already finished, or that is
        // being padded, has nothing left to release (`longest-…-close-abrupt-completion`
        // expects the finished fourth source to be left alone).
        let mut states =
            zip_states(interp, object, records.len()).unwrap_or_else(|_| vec![0; records.len()]);
        // `DONE` is deliberately **not** set here: while a `suspended-yield` helper closes its
        // sources its generator state is `executing`, so a source's `return` that calls back
        // into the helper must be a `TypeError` (`suspended-yield-iterator-close-calls-return`).
        // The caller sets it once the close finishes.
        // The first failure is the completion, and the rest of the unwind still happens.
        if let Some(signal) = zip_close_open(interp, object, &records, &mut states, false) {
            return Err(signal);
        }
        return Ok(());
    }
    Ok(())
}

fn done_result(interp: &Interp<'_>) -> Value {
    let object = interp.new_object(Some(interp.realm.object_proto.clone()));
    object.define(
        "value",
        Property::with_attributes(Value::Undefined, true, true),
    );
    object.define(
        "done",
        Property::with_attributes(Value::Bool(true), true, true),
    );
    Value::Object(object)
}

fn value_result(interp: &Interp<'_>, value: Value) -> Value {
    let object = interp.new_object(Some(interp.realm.object_proto.clone()));
    object.define("value", Property::with_attributes(value, true, true));
    object.define(
        "done",
        Property::with_attributes(Value::Bool(false), true, true),
    );
    Value::Object(object)
}

// ---------------------------------------------------------------------------
// The prototype methods
// ---------------------------------------------------------------------------

/// Close the receiver after a *validation* failure.
///
/// Only validation closes this way. Once iteration has started, the rule is narrower: a
/// throwing callback closes the iterator, a throwing `next`/`done`/`value` does not. The
/// first is `IfAbruptCloseIterator`; the second is the iterator failing on its own and is
/// propagated untouched.
fn rejected(interp: &mut Interp<'_>, this: &Value, signal: Signal) -> Signal {
    let _ = close_receiver(interp, this);
    signal
}

fn map(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let callback = require_callback(interp, &this, &arg(args, 0))?;
    let source = source_of(interp, &this)?;
    helper(interp, source, KIND_MAP, Some(callback))
}

fn filter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let callback = require_callback(interp, &this, &arg(args, 0))?;
    let source = source_of(interp, &this)?;
    helper(interp, source, KIND_FILTER, Some(callback))
}

fn take(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let remaining = count_argument(interp, &this, &arg(args, 0), "must be positive")?;
    let source = source_of(interp, &this)?;
    let value = helper(interp, source, KIND_TAKE, None)?;
    if let Value::Object(object) = &value {
        write_hidden(object, REMAINING, Value::Float(remaining));
    }
    Ok(value)
}

fn drop(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let remaining = count_argument(interp, &this, &arg(args, 0), "must be positive")?;
    let source = source_of(interp, &this)?;
    let value = helper(interp, source, KIND_DROP, None)?;
    if let Value::Object(object) = &value {
        write_hidden(object, REMAINING, Value::Float(remaining));
    }
    Ok(value)
}

fn flat_map(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let callback = require_callback(interp, &this, &arg(args, 0))?;
    let source = source_of(interp, &this)?;
    helper(interp, source, KIND_FLAT_MAP, Some(callback))
}

fn chunks(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let size = integral_count(interp, &this, &arg(args, 0), "chunkSize")?;
    let source = source_of(interp, &this)?;
    let value = helper(interp, source, KIND_CHUNKS, None)?;
    if let Value::Object(object) = &value {
        write_hidden(object, REMAINING, Value::Float(size));
    }
    Ok(value)
}

fn windows(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // The order is `windowSize` then `undersized`, and both come before `next` is read
    // (`windows/argument-effect-order`). Checking `undersized` first reported a `TypeError`
    // where the spec asks for the `RangeError` an out-of-range `windowSize` produces.
    let size = integral_count(interp, &this, &arg(args, 0), "windowSize")?;
    // §24.5.4.9 steps 9–12: `undersized` is a String, defaulting to `"only-full"`. Anything
    // else is a `TypeError` — checked before `next` is read, which is what
    // `windows/argument-effect-order` records.
    let allow_partial = match args.get(1) {
        None | Some(Value::Undefined) => false,
        Some(Value::String(text)) => match text.as_str() {
            Some("only-full") => false,
            Some("allow-partial") => true,
            _ => {
                let signal = interp.type_error("bad undersized option");
                return Err(rejected(interp, &this, signal));
            }
        },
        Some(_) => {
            let signal = interp.type_error("bad undersized option");
            return Err(rejected(interp, &this, signal));
        }
    };
    let source = source_of(interp, &this)?;
    let value = helper(interp, source, KIND_WINDOWS, None)?;
    if let Value::Object(object) = &value {
        write_hidden(object, REMAINING, Value::Float(size));
        write_hidden(object, ALLOW_PARTIAL, Value::Bool(allow_partial));
    }
    Ok(value)
}

/// What a consumer does with one element: `Some` stops the walk with that answer.
type Consumer<'a> = dyn FnMut(&mut Interp<'_>, usize, Value) -> JsResult<Option<Value>> + 'a;

/// Drain the receiver through `f`, passing the index as the second argument.
///
/// The three ways out are deliberately different. A *natural* end leaves the iterator
/// alone: it is already done, and closing it would run a `return` the spec does not ask
/// for. An *early* stop closes it and lets a throwing `return` surface. An abrupt
/// completion **from the callback** closes it. An abrupt completion from the iterator's
/// own `next`/`done`/`value` does *not* — `IfAbruptCloseIterator` only covers the
/// callback, which is what all the `underlying-iterator-not-closed-when-step-throws`
/// tests check.
fn iterate(interp: &mut Interp<'_>, this: &Value, f: &mut Consumer<'_>) -> JsResult<Value> {
    let record = source_of(interp, this)?;
    let mut index = 0usize;
    loop {
        // `?` here is the "do not close" path: the iterator itself failed.
        let Some(value) = step(interp, &record)? else {
            return Ok(Value::Undefined);
        };
        match f(interp, index, value) {
            Ok(Some(result)) => {
                close(interp, &record)?;
                return Ok(result);
            }
            Ok(None) => index += 1,
            Err(signal) => {
                // The callback threw: close, but keep the original error.
                let _ = close(interp, &record);
                return Err(signal);
            }
        }
    }
}

fn to_array(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // No `closing` wrapper: `toArray` has no callback, so every way it can fail comes from
    // the iterator itself and must propagate without closing it.
    let record = source_of(interp, &this)?;
    let mut items = Vec::new();
    while let Some(value) = step(interp, &record)? {
        items.push(value);
    }
    Ok(Value::Object(interp.new_array(items)))
}

fn for_each(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let callback = require_callback(interp, &this, &arg(args, 0))?;
    iterate(interp, &this, &mut |interp, index, value| {
        interp.call_value(
            callback.clone(),
            Value::Undefined,
            vec![value, Value::Int(index as i32)],
        )?;
        Ok(None)
    })?;
    Ok(Value::Undefined)
}

fn some(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let callback = require_callback(interp, &this, &arg(args, 0))?;
    let found = iterate(interp, &this, &mut |interp, index, value| {
        let answer = interp.call_value(
            callback.clone(),
            Value::Undefined,
            vec![value, Value::Int(index as i32)],
        )?;
        Ok(answer.to_boolean().then_some(Value::Bool(true)))
    })?;
    Ok(Value::Bool(matches!(found, Value::Bool(true))))
}

fn every(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let callback = require_callback(interp, &this, &arg(args, 0))?;
    let stopped = iterate(interp, &this, &mut |interp, index, value| {
        let answer = interp.call_value(
            callback.clone(),
            Value::Undefined,
            vec![value, Value::Int(index as i32)],
        )?;
        Ok((!answer.to_boolean()).then_some(Value::Bool(false)))
    })?;
    Ok(Value::Bool(!matches!(stopped, Value::Bool(false))))
}

fn find(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let callback = require_callback(interp, &this, &arg(args, 0))?;
    iterate(interp, &this, &mut |interp, index, value| {
        let answer = interp.call_value(
            callback.clone(),
            Value::Undefined,
            vec![value.clone(), Value::Int(index as i32)],
        )?;
        Ok(answer.to_boolean().then_some(value))
    })
}

fn reduce(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let callback = require_callback(interp, &this, &arg(args, 0))?;
    let record = source_of(interp, &this)?;
    (|| -> JsResult<Value> {
        let mut accumulator = if args.len() > 1 {
            arg(args, 1)
        } else {
            // No initial value: the first element becomes the accumulator, and an
            // empty iterator is a `TypeError` rather than `undefined`.
            match step(interp, &record)? {
                Some(value) => value,
                None => {
                    return Err(interp.type_error("reduce of empty iterator with no initial value"));
                }
            }
        };
        // The index is the element's position in the *iterator*, so with no initial value
        // the first element (already taken as the accumulator) was index 0 and the
        // callback's first call is on index 1 (`reduce/reducer-args-no-initial-value`).
        let mut index = if args.len() > 1 { 0 } else { 1 };
        while let Some(value) = step(interp, &record)? {
            // §27.1.4.8 step 6 wraps the reducer call in `IfAbruptCloseIterator`: a throw
            // from the callback closes the source (`reduce/reducer-throws` counts one
            // `return`), and if that close also throws the **original** error wins
            // (`reducer-throws-then-closing-iterator-also-throws`).
            match interp.call_value(
                callback.clone(),
                Value::Undefined,
                vec![accumulator, value, Value::Int(index)],
            ) {
                Ok(next) => accumulator = next,
                Err(signal) => {
                    let _ = close(interp, &record);
                    return Err(signal);
                }
            }
            index += 1;
        }
        Ok(accumulator)
    })()
}

fn join(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // Like `toArray`, no callback means nothing to close for: `does-not-close-on-*`
    // covers a throwing `next`, a protocol violation and a throwing `next` getter.
    // §27.1.4.7 step 3: `ToString(separator)` runs **before** `GetIteratorDirect`, and a
    // throw from it still closes the receiver — but without ever reading `next`
    // (`join/closes-on-separator-coercion-exception` checks both halves).
    let separator = match args.first() {
        None | Some(Value::Undefined) => ",".to_string(),
        Some(value) => match interp.to_js_string(value) {
            Ok(text) => text,
            // The receiver is closed *without* `next` ever being read — `close_receiver`
            // only touches `return`, which is what lets the separator's error win
            // (`join/closes-on-separator-coercion-exception` asserts `gotNext === false`)
            // and keeps the order `toString` then `get next`
            // (`join/next-lookup-after-separator-tostring`).
            Err(signal) => {
                let _ = close_receiver(interp, &this);
                return Err(signal);
            }
        },
    };
    let record = source_of(interp, &this)?;
    let mut parts = Vec::new();
    while let Some(value) = step(interp, &record)? {
        // A nullish element joins as the empty string rather than "undefined".
        if matches!(value, Value::Undefined | Value::Null) {
            parts.push(String::new());
        } else {
            match interp.to_js_string(&value) {
                Ok(text) => parts.push(text),
                // `IfAbruptCloseIterator` around the element's `ToString`
                // (`join/closes-on-contents-coercion-exception`).
                Err(signal) => {
                    let _ = close(interp, &record);
                    return Err(signal);
                }
            }
        }
    }
    Ok(interp.string(parts.join(&separator)))
}

fn includes(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // `includes(searchElement, skippedElements)`: the second argument counts elements
    // to pass over first. It must be an integral Number — a string is a `TypeError`
    // rather than a coercion, and `1.5`/`NaN` are refused too.
    let mut skipped = match args.get(1) {
        None | Some(Value::Undefined) => 0.0,
        Some(value) => {
            let number = match value {
                Value::Int(number) => *number as f64,
                Value::Float(number) => *number,
                _ => {
                    // Validation failures close the receiver, and do it without reading
                    // `next` — the count is checked before `GetIteratorDirect`.
                    let signal = interp.type_error("not a number");
                    return Err(rejected(interp, &this, signal));
                }
            };
            // `Infinity` is allowed and simply skips everything.
            if number.is_nan() || (number.is_finite() && number.trunc() != number) {
                let signal = interp.type_error("not an integral number");
                return Err(rejected(interp, &this, signal));
            }
            if number < 0.0 {
                let signal = interp.range_error("must be positive");
                return Err(rejected(interp, &this, signal));
            }
            // Step 8: "if toSkip is finite and toSkip > 2**53 - 1, throw a RangeError" —
            // and `IteratorClose` runs first, without reading `next`
            // (`includes/skipped-elements-too-large-rangeerror`).
            if number.is_finite() && number > MAX_SAFE_INTEGER {
                let signal = interp.range_error("skippedElements is too large");
                return Err(rejected(interp, &this, signal));
            }
            number
        }
    };
    let needle = arg(args, 0);
    let record = source_of(interp, &this)?;
    let outcome = (|| -> JsResult<bool> {
        while let Some(value) = step(interp, &record)? {
            if skipped > 0.0 {
                skipped -= 1.0;
                continue;
            }
            // `SameValueZero`: `NaN` finds `NaN`, and `-0` finds `0`.
            if same_value_zero(&value, &needle) {
                return Ok(true);
            }
        }
        Ok(false)
    })();
    let found = outcome?;
    if found {
        close(interp, &record)?;
    }
    Ok(Value::Bool(found))
}

/// `SameValueZero`, which is `===` except that `NaN` matches itself.
fn same_value_zero(left: &Value, right: &Value) -> bool {
    match (left, right) {
        (Value::Float(a), Value::Float(b)) if a.is_nan() && b.is_nan() => true,
        (Value::Int(a), Value::Float(b)) => (*a as f64) == *b,
        (Value::Float(a), Value::Int(b)) => *a == (*b as f64),
        _ => left.strict_equals(right),
    }
}

// ---------------------------------------------------------------------------
// The static helpers
// ---------------------------------------------------------------------------

fn from(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    into_iterator(interp, arg(args, 0))
}

/// `GetIteratorFlattenable(value, iterateStrings)`.
///
/// The subtle part is step 3: when the object has **no** `@@iterator`, it is used as the
/// iterator record *itself*. That is what makes `Iterator.from({next(){...}})` work — a
/// bare iterator with no `Symbol.iterator` — and it is also why such an object has to be
/// *wrapped* rather than returned: it is not an `Iterator`, so it has no helper methods.
///
/// `iterate_strings` is `true` for `Iterator.from`, where a string primitive iterates its
/// characters, and `false` for `concat`/`zip`, where `Iterator.concat("ab")` is a
/// `TypeError`.
fn iterator_flattenable(
    interp: &mut Interp<'_>,
    value: &Value,
    iterate_strings: bool,
) -> JsResult<crate::interp::Iterator> {
    let allowed_primitive = iterate_strings && matches!(value, Value::String(_));
    if !matches!(value, Value::Object(_)) && !allowed_primitive {
        return Err(interp.type_error("not an object"));
    }
    let key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::Iterator);
    // `read_field_key` boxes a primitive receiver, which is how a string primitive finds
    // `String.prototype[Symbol.iterator]`.
    let method = interp.read_field_key(value, &key)?;
    match method {
        Value::Undefined | Value::Null => iterator_record(interp, value),
        callable if matches!(&callable, Value::Object(object) if object.is_callable()) => {
            let produced = interp.call_value(callable, value.clone(), Vec::new())?;
            if !matches!(produced, Value::Object(_)) {
                return Err(interp.type_error("iterator is not an object"));
            }
            iterator_record(interp, &produced)
        }
        _ => Err(interp.type_error("not a function")),
    }
}

/// `Iterator.from(value)`, which `flatMap` also needs.
///
/// `flatMap` maps each element through the callback and then iterates the *result*, so a
/// callback returning a plain array has to work: `[[1,2],[3]].values().flatMap(x => x)`
/// is the canonical example. Without wrapping, the array has no `next` and the helper
/// died with "not a function".
fn into_iterator(interp: &mut Interp<'_>, value: Value) -> JsResult<Value> {
    // Already an `Iterator`: hand it back untouched, so `Iterator.from(xs) === xs` holds
    // for anything this engine produced. The test is the prototype chain, which is the
    // same thing `instanceof Iterator` reports.
    if is_iterator(interp, &value) {
        return Ok(value);
    }
    let record = iterator_flattenable(interp, &value, true)?;
    let proto = interp
        .realm
        .iterator_wrap_proto
        .clone()
        .ok_or_else(|| interp.type_error("iterator helpers are not installed"))?;
    let object = interp.new_object(Some(proto));
    object.define(
        SOURCE,
        Property::with_attributes(record.object, true, false),
    );
    object.define(
        SOURCE_NEXT,
        Property::with_attributes(record.next, true, false),
    );
    object.define(
        KIND,
        Property::with_attributes(Value::Int(KIND_WRAP), true, false),
    );
    Ok(Value::Object(object))
}

/// Whether `value`'s prototype chain reaches `Iterator.prototype`.
fn is_iterator(interp: &mut Interp<'_>, value: &Value) -> bool {
    let Some(target) = interp.realm.iterator_proto.clone() else {
        return false;
    };
    let mut current = value.as_object().cloned();
    // Bounded walk: a proxy could answer with a cycle, and `instanceof` has the same
    // problem, so this stops rather than hangs.
    for _ in 0..10_000 {
        match current {
            Some(object) => {
                if object.ptr_eq(&target) {
                    return true;
                }
                current = object.proto();
            }
            None => return false,
        }
    }
    false
}

/// `%WrapForValidIteratorPrototype%.next`: forward to the wrapped iterator untouched.
///
/// The result object is returned *as the underlying `next` produced it*, not normalised:
/// the wrapper is transparent, so a `next` that answers `{value, done}` with extra
/// properties keeps them.
fn wrap_next(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("not an object"));
    };
    let next = read_hidden(interp, &object, SOURCE_NEXT)?;
    let source = read_hidden(interp, &object, SOURCE)?;
    interp.call_value(next, source, Vec::new())
}

fn wrap_return(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("not an object"));
    };
    // §27.1.4.2.2 step 2 is `RequireInternalSlot(O, [[Iterated]])`: only a wrapper this
    // function built may answer. Testing for the hidden slot rather than for "not an object"
    // is what makes `%WrapForValidIteratorPrototype%.return.call({})` a `TypeError` **and**
    // leaves a property-bag observer with no reads at all
    // (`from/return-method-throws-for-invalid-this`).
    if !matches!(
        read_hidden(interp, &object, KIND)?,
        Value::Int(kind) if kind == KIND_WRAP
    ) {
        return Err(interp.type_error("receiver is not a wrapped iterator"));
    }
    let source = read_hidden(interp, &object, SOURCE)?;
    let Value::Object(iterator) = &source else {
        return Err(interp.type_error("receiver is not a wrapped iterator"));
    };
    // §27.1.4.2.2 step 3: `GetMethod(iterator, "return")`, then `Call` it and hand its answer
    // back **unchanged** — the wrapper is transparent, so the caller sees the object the
    // underlying iterator made (`from/return-method-calls-base-return-method`), and nothing
    // happens at all when the method is absent.
    let key = crate::object::PropertyKey::from("return");
    let Some(method) = interp.get_property_key(iterator, &key)? else {
        return Ok(done_result(interp));
    };
    if matches!(method, Value::Undefined | Value::Null) {
        return Ok(done_result(interp));
    }
    if !matches!(&method, Value::Object(function) if function.is_callable()) {
        return Err(interp.type_error("return is not a function"));
    }
    interp.call_value(method, source, Vec::new())
}

fn concat(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // §27.1.3.1 `Iterator.concat(...items)` validates **every** item up front, in order,
    // and that is two separate observations:
    //
    // * a non-object item is a `TypeError` at the call (`Iterator.concat([1], 5)`);
    // * `GetIteratorDirect`'s method read — `Get(item, @@iterator)` — happens now too, so a
    //   *throwing getter* throws here, and a missing or non-callable method is a
    //   `TypeError` here. `arguments-checked-in-order` pins the order: `iterable1`'s getter
    //   runs once, then `null` is refused, and `iterable2`'s getter never runs.
    //
    // The method itself is **not called** until iteration reaches the item
    // (`get-iterator-method-only-once` counts one property read and zero calls), so what is
    // stored is the iterable, not an iterator.
    let mut items = Vec::with_capacity(args.len());
    let mut methods = Vec::with_capacity(args.len());
    let key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::Iterator);
    for item in args {
        if !matches!(item, Value::Object(_)) {
            return Err(interp.type_error("not an object"));
        }
        let method = interp.read_field_key(item, &key)?;
        if !matches!(&method, Value::Object(function) if function.is_callable()) {
            return Err(interp.type_error("iterable has no iterator method"));
        }
        items.push(item.clone());
        // The *method* is kept, not just the iterable: `GetIteratorDirect(iterable)` is
        // `Call(method, iterable)`, and re-reading `@@iterator` at step time is a second
        // property read (`get-iterator-method-only-once` counts one read in total).
        methods.push(method);
    }
    let helper = iterator_object(interp, KIND_CONCAT)?;
    if let Value::Object(object) = &helper {
        let list = interp.new_array(items);
        write_hidden(object, LIST, Value::Object(list));
        let method_list = interp.new_array(methods);
        write_hidden(object, LIST_METHODS, Value::Object(method_list));
        write_hidden(object, CURSOR, Value::Int(0));
        write_hidden(object, CURSOR_INNER, Value::Undefined);
    }
    Ok(helper)
}

/// An empty helper object with the given kind and no source.
///
/// `concat`/`zip` have a *list* of sources rather than one, so they cannot go through
/// [`helper`] and fill the single-source slots in.
fn iterator_object(interp: &mut Interp<'_>, kind: i32) -> JsResult<Value> {
    let proto = interp
        .realm
        .iterator_helper_proto
        .clone()
        .ok_or_else(|| interp.type_error("iterator helpers are not installed"))?;
    let object = interp.new_object(Some(proto));
    write_hidden(&object, KIND, Value::Int(kind));
    write_hidden(&object, DONE, Value::Bool(false));
    Ok(Value::Object(object))
}

/// `Iterator.zip(iterables, options)`.
///
/// Three orderings are observable and all three are tested: `mode` is read first, then
/// `padding` — but *only* when the mode is `longest`, so a `padding` getter must not fire
/// for `shortest` — and only then is the iterables argument opened. Every source is opened
/// at call time rather than on the first `next`.
///
/// `padding` is itself an **iterable**, pulled one value per source position; that is what
/// lets `padding: { *[Symbol.iterator]() { while (true) yield 100 + i++ } }` pad an
/// unbounded number of sources.
fn zip(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(iterables) = arg(args, 0).as_object().cloned() else {
        return Err(interp.type_error("not an object"));
    };
    let mode = zip_mode(interp, args.get(1))?;
    // §27.1.3.1 step 4: `padding` is only **read** in `longest` mode — a getter here must not
    // fire for `shortest` — and only the value is taken; its iterator is opened *after* the
    // sources, which is why a poisoned `padding[@@iterator]` closes them
    // (`padding-iteration-get-iterator-abrupt-completion`).
    let pad_option = if mode == 1 {
        zip_padding_option(interp, args.get(1))?
    } else {
        None
    };
    let outer = interp.get_iterator(&Value::Object(iterables))?;
    let mut records = Vec::new();
    // Collect first, then commit: the sources that were already opened have to be closed
    // if a later one fails, and they are closed in reverse order (the most recently opened
    // first), which `iterables-iteration-get-iterator-flattenable-abrupt-completion` counts.
    loop {
        let item = match step(interp, &outer) {
            Ok(Some(item)) => item,
            Ok(None) => break,
            Err(signal) => {
                // The outer iterator is **not** closed: it is the one whose completion is
                // already abrupt (`iterables-iteration-iterator-step-value-abrupt-completion`
                // counts no `return` on it).
                zip_close_collected(interp, &records);
                return Err(signal);
            }
        };
        let record = match iterator_flattenable(interp, &item, false) {
            Ok(record) => record,
            Err(signal) => {
                zip_close_collected(interp, &records);
                let _ = close(interp, &outer);
                return Err(signal);
            }
        };
        records.push(record);
    }
    let count = records.len();
    let mut pads = vec![Value::Undefined; count];
    if let Some(option) = pad_option {
        // §27.1.3.1 step 6: pull one padding value per position, then close the padding
        // iterator — its `return` is called even when it never ran out
        // (`padding-iteration` records `padding::return`).
        let source = match interp.get_iterator(&option) {
            Ok(source) => source,
            Err(signal) => {
                zip_close_collected(interp, &records);
                return Err(signal);
            }
        };
        let mut pulled = 0usize;
        while pulled < count {
            match step(interp, &source) {
                Ok(Some(value)) => {
                    pads[pulled] = value;
                    pulled += 1;
                }
                Ok(None) => break,
                Err(signal) => {
                    zip_close_collected(interp, &records);
                    return Err(signal);
                }
            }
        }
        // Still open means the pull stopped at `count` rather than at `done`, and closing it
        // is part of the specification — a throwing `return` here is reported.
        if pulled == count
            && let Err(signal) = close(interp, &source)
        {
            zip_close_collected(interp, &records);
            return Err(signal);
        }
    }
    finish_zip(interp, KIND_ZIP, mode, records, pads, None)
}

/// Close a partially-built source list, in reverse, ignoring every failure.
fn zip_close_collected(interp: &mut Interp<'_>, records: &[crate::interp::Iterator]) {
    for record in records.iter().rev() {
        let _ = close(interp, record);
    }
}

/// `Iterator.zipKeyed(iterables, options)`.
///
/// Keyed padding is a plain object read by key, not an iterable: `padding: {a: "pad"}`
/// gives `{a: "pad", b: …}`.
fn zip_keyed(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(source) = arg(args, 0).as_object().cloned() else {
        return Err(interp.type_error("not an object"));
    };
    let mode = zip_mode(interp, args.get(1))?;
    let padding = if mode == 1 {
        match arg(args, 1) {
            Value::Object(options) => match interp.get_property(&options, "padding")? {
                None | Some(Value::Undefined) => None,
                Some(Value::Object(map)) => Some(map),
                Some(_) => return Err(interp.type_error("padding must be an object")),
            },
            _ => None,
        }
    } else {
        None
    };
    let mut keys = Vec::new();
    let mut records = Vec::new();
    let mut pads = Vec::new();
    let mut pad_keys = Vec::new();
    // The key list is snapshotted once, but each key's *enumerability* is re-read at the
    // moment it is reached. That is observable and tested: `iterables-iteration-enumerable`
    // makes `c` non-enumerable from inside `b`'s getter and expects `c` to be skipped, then
    // makes `e` enumerable from inside `d`'s getter and expects `e` to be included.
    // Through the `[[OwnPropertyKeys]]` / `[[GetOwnProperty]]` internal methods, not the
    // object's own tables: a Proxy has to see its traps, and the tests build exactly such
    // a proxy to check the read order.
    // Collect first, commit second: a key whose `[[Get]]` or `GetIteratorFlattenable`
    // throws must leave the already-opened iterators closed, in reverse order — the most
    // recently opened one first, which `iterables-iteration-get-abrupt-completion` records.
    let outcome = (|| -> JsResult<()> {
        for key in interp.object_own_property_keys(&source)? {
            let Some(property) = interp.object_get_own_property(&source, &key)? else {
                continue;
            };
            if !property.enumerable {
                continue;
            }
            // `[[GetOwnProperty]]` decides enumerability; the *value* comes from a separate
            // `[[Get]]`, which is what runs a getter — readings a `Property` directly would
            // miss accessor properties entirely, and they are the common case here.
            let item = match interp.get_property_key(&source, &key)? {
                // `undefined` is skipped rather than refused, so `{a: undefined, b: xs}` zips
                // only `b`. Anything else that is not an object is a `TypeError`.
                None | Some(Value::Undefined) => continue,
                Some(value) => value,
            };
            if !matches!(item, Value::Object(_)) {
                return Err(interp.type_error("not an object"));
            }
            records.push(iterator_flattenable(interp, &item, false)?);
            // The padding value is read **after** every source is collected (§27.1.3.2
            // step 6), so a throwing getter still closes all of them
            // (`zipKeyed/padding-iteration-get-abrupt-completion` expects `third return`
            // too). The key is remembered here and resolved below.
            pads.push(Value::Undefined);
            pad_keys.push(key.clone());
            // Kept as a `Value` so a symbol key stays a symbol in the result object.
            keys.push(match &key {
                crate::object::PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
                crate::object::PropertyKey::String(text) => interp.string_wtf8(text.clone()),
            });
        }
        Ok(())
    })();
    if let Err(signal) = outcome {
        // Errors from a closing `return` are ignored: the completion is already abrupt.
        let _ = close_all_except(interp, &records, usize::MAX);
        return Err(signal);
    }
    if let Some(map) = &padding {
        for (index, key) in pad_keys.iter().enumerate() {
            match interp.get_property_key(map, key) {
                Ok(value) => pads[index] = value.unwrap_or(Value::Undefined),
                Err(signal) => {
                    let _ = close_all_except(interp, &records, usize::MAX);
                    return Err(signal);
                }
            }
        }
    }
    finish_zip(interp, KIND_ZIP_KEYED, mode, records, pads, Some(keys))
}

/// The per-source state array, created open on first use.
fn zip_states(interp: &mut Interp<'_>, object: &JsObject, count: usize) -> JsResult<Vec<i32>> {
    let stored = read_hidden(interp, object, ZIP_STATES)?;
    if let Some(array) = stored.as_object() {
        let states: Vec<i32> = array
            .array_elements()
            .unwrap_or_default()
            .iter()
            .map(|value| value.to_number() as i32)
            .collect();
        if states.len() == count {
            return Ok(states);
        }
    }
    // A fresh zip starts with every source open.
    let _ = interp;
    Ok(vec![0i32; count])
}

/// Persist the states, so the next `next()` sees which sources finished.
fn write_zip_states(interp: &mut Interp<'_>, object: &JsObject, states: &[i32]) {
    let values: Vec<Value> = states.iter().map(|state| Value::Int(*state)).collect();
    let array = interp.new_array(values);
    write_hidden(object, ZIP_STATES, Value::Object(array));
}

/// Close every still-open source, in reverse order.
///
/// `pending` is `true` when an exception is already on its way out: §7.4.11 step 6 then
/// keeps that first exception and ignores whatever `return` raises, which is why
/// `iterator-zip-iteration-iterator-close-abrupt-completion` sees `ExpectedError` even though
/// a later `return` threw `Test262Error`.
fn zip_close_open(
    interp: &mut Interp<'_>,
    object: &JsObject,
    records: &[crate::interp::Iterator],
    states: &mut [i32],
    pending: bool,
) -> Option<crate::interp::Signal> {
    let mut failure = None;
    for index in (0..records.len()).rev() {
        if states[index] != 0 {
            continue;
        }
        states[index] = 1;
        if let Err(signal) = close(interp, &records[index])
            && failure.is_none()
            && !pending
        {
            failure = Some(signal);
        }
    }
    write_zip_states(interp, object, states);
    failure
}

/// `IteratorClose` for every source except `skip`, in reverse order.
///
/// Returns the first error raised by a `return`, after finishing the unwind: one source
/// refusing to close must not leave the others open.
fn close_all_except(
    interp: &mut Interp<'_>,
    records: &[crate::interp::Iterator],
    skip: usize,
) -> Option<Signal> {
    let mut first_error = None;
    for (index, record) in records.iter().enumerate().rev() {
        if index == skip {
            continue;
        }
        if let Err(signal) = close(interp, record)
            && first_error.is_none()
        {
            first_error = Some(signal);
        }
    }
    first_error
}

fn finish_zip(
    interp: &mut Interp<'_>,
    kind: i32,
    mode: i32,
    records: Vec<crate::interp::Iterator>,
    pads: Vec<Value>,
    keys: Option<Vec<Value>>,
) -> JsResult<Value> {
    let helper = iterator_object(interp, kind)?;
    if let Value::Object(object) = &helper {
        let flat = pack_records(&records);
        let list = interp.new_array(flat);
        write_hidden(object, LIST, Value::Object(list));
        write_hidden(object, MODE, Value::Int(mode));
        let pads = interp.new_array(pads);
        write_hidden(object, PADDING, Value::Object(pads));
        if let Some(keys) = keys {
            let keys = interp.new_array(keys);
            write_hidden(object, KEYS, Value::Object(keys));
        }
    }
    Ok(helper)
}

/// `options.mode`, read before anything else and validated on the spot.
fn zip_mode(interp: &mut Interp<'_>, options: Option<&Value>) -> JsResult<i32> {
    let Some(options) = options else {
        return Ok(0);
    };
    if matches!(options, Value::Undefined) {
        return Ok(0);
    }
    let Some(object) = options.as_object().cloned() else {
        return Err(interp.type_error("options must be an object"));
    };
    match interp.get_property(&object, "mode")? {
        None | Some(Value::Undefined) => Ok(0),
        Some(Value::String(text)) => match text.to_string_lossy().as_ref() {
            "shortest" => Ok(0),
            "longest" => Ok(1),
            "strict" => Ok(2),
            _ => Err(interp.type_error("invalid mode")),
        },
        Some(_) => Err(interp.type_error("invalid mode")),
    }
}

/// `options.padding`, read only in `longest` mode.
fn zip_padding_option(interp: &mut Interp<'_>, options: Option<&Value>) -> JsResult<Option<Value>> {
    let Some(Value::Object(object)) = options else {
        return Ok(None);
    };
    match interp.get_property(object, "padding")? {
        None | Some(Value::Undefined) => Ok(None),
        Some(value @ Value::Object(_)) => Ok(Some(value)),
        Some(_) => Err(interp.type_error("padding must be an object")),
    }
}

/// Flatten iterator records into a value list so they can live in one array.
///
/// Each record becomes two adjacent entries, `[object, next]`, which
/// [`unpack_records`] reads back.
fn pack_records(records: &[crate::interp::Iterator]) -> Vec<Value> {
    let mut flat = Vec::with_capacity(records.len() * 2);
    for record in records {
        flat.push(record.object.clone());
        flat.push(record.next.clone());
    }
    flat
}

fn unpack_records(
    interp: &mut Interp<'_>,
    object: &JsObject,
) -> JsResult<Vec<crate::interp::Iterator>> {
    let list = read_hidden(interp, object, LIST)?;
    let Some(array) = list.as_object().cloned() else {
        return Ok(Vec::new());
    };
    let elements = array.array_elements().unwrap_or_default();
    let mut records = Vec::with_capacity(elements.len() / 2);
    for pair in elements.chunks(2) {
        if let [object, next] = pair {
            records.push(crate::interp::Iterator {
                object: object.clone(),
                next: next.clone(),
            });
        }
    }
    Ok(records)
}

/// §27.1.3.1's getter: `"Iterator"`, whatever the receiver is.
fn iterator_tag_getter(interp: &mut Interp<'_>, _this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(interp.string("Iterator"))
}

/// §27.1.3.1's setter: `SetterThatIgnoresPrototypeProperties`.
fn iterator_tag_setter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(home) = interp.realm.iterator_proto.clone() else {
        return Err(interp.type_error("Iterator.prototype is not installed"));
    };
    let key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::ToStringTag);
    interp.setter_that_ignores_prototype_properties_key(this, &home, &key, args)
}