Skip to main content

quickjs/builtins/
iterator.rs

1//! `Iterator` and its helpers (ES2025 §27.1.4 plus the sequencing additions).
2//!
3//! Every helper is *lazy*: `xs.map(f)` does no work until something calls `next`. That is
4//! the whole point of the API — `(function*(){ while (true) yield 1 })().take(3).toArray()`
5//! has to terminate — so the state a helper needs between calls lives on the returned
6//! object and one shared `next` implementation drives all of them.
7//!
8//! The state is ordinary non-enumerable properties rather than a dedicated interior slot
9//! because a `NativeFn` is a plain function pointer and cannot capture. Hidden properties
10//! are also what keeps the collector honest: everything a helper holds is a `Value` in the
11//! property table, so a suspended helper keeps its source iterator and callback alive.
12//!
13//! Two semantics are easy to get wrong and are called out where they matter:
14//!
15//! * **No eager brand check.** `Iterator.prototype.map.call({}, f)` does *not* throw: the
16//!   receiver only has to be an object. The failure comes later, when `next` reads `this`
17//!   as an iterator record and finds no callable `next`.
18//! * **`return` propagates.** Closing a helper closes the iterator underneath it, exactly
19//!   once, which is what makes `using` and `for…of` cleanup visible through a chain.
20
21use crate::builtins::{arg, define_method};
22use crate::interp::{Interp, JsResult, Signal};
23use crate::object::{JsObject, Property};
24use crate::value::Value;
25
26/// Which helper a returned object implements.
27///
28/// Stored as an `int` property so it survives in the property table; the order is private
29/// to this module.
30const KIND_MAP: i32 = 1;
31const KIND_FILTER: i32 = 2;
32const KIND_TAKE: i32 = 3;
33const KIND_DROP: i32 = 4;
34const KIND_FLAT_MAP: i32 = 5;
35const KIND_CHUNKS: i32 = 6;
36const KIND_WINDOWS: i32 = 7;
37const KIND_WRAP: i32 = 8;
38const KIND_CONCAT: i32 = 9;
39const KIND_ZIP: i32 = 10;
40const KIND_ZIP_KEYED: i32 = 11;
41
42/// The hidden properties of a helper object.
43const SOURCE: &str = "_source";
44const SOURCE_NEXT: &str = "_sourceNext";
45const CALLBACK: &str = "_callback";
46const KIND: &str = "_kind";
47const REMAINING: &str = "_remaining";
48const INNER: &str = "_inner";
49const BUFFER: &str = "_buffer";
50const LIST: &str = "_list";
51const CURSOR: &str = "_cursor";
52const CURSOR_INNER: &str = "_cursorInner";
53const MODE: &str = "_mode";
54const KEYS: &str = "_keys";
55const COUNTER: &str = "_counter";
56const PADDING: &str = "_padding";
57const DONE: &str = "_done";
58
59/// Set while a helper's `next` is executing, so a re-entrant call is a `TypeError`.
60const RUNNING: &str = "_running";
61
62/// `windows(size, undersized)`: whether the last, short window is yielded.
63///
64/// §24.5.4.9's `undersized` defaults to `"only-full"`; `"allow-partial"` yields whatever is
65/// left when the source runs out.
66const ALLOW_PARTIAL: &str = "_allow_partial";
67
68/// `2^53 - 1`, the upper bound `ToIntegerOrInfinity`'s callers impose on a count
69/// (§7.1.5 gives the range, and `Iterator.prototype.take` refuses past it).
70const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
71
72/// Install `Iterator`.
73pub fn install(interp: &mut Interp<'_>, object_proto: &js_gc::Gc<JsObject>) {
74    let iterator_proto = interp.new_object(Some(object_proto.clone()));
75    let iterator = interp.new_native("Iterator", 0, iterator_constructor);
76    // `Iterator.prototype.constructor`'s getter is a bare `fn` pointer and cannot capture
77    // this, so the realm holds it (`realm.iterator_ctor`).
78    interp.realm.iterator_ctor = Some(iterator.clone());
79    // `Iterator` is an abstract class: `new` is refused, and calling it says so with a
80    // different message, which is how the reference distinguishes the two mistakes.
81    iterator.set_constructible(true);
82    iterator.set_class_constructor(true);
83    iterator.define(
84        "prototype",
85        Property::with_attributes(Value::Object(iterator_proto.clone()), false, false),
86    );
87    iterator.define("name", Property::name_or_length(interp.string("Iterator")));
88    iterator.define("length", Property::name_or_length(Value::Int(0)));
89
90    define_method(&iterator_proto, "map", 1, map, interp);
91    define_method(&iterator_proto, "filter", 1, filter, interp);
92    define_method(&iterator_proto, "take", 1, take, interp);
93    define_method(&iterator_proto, "drop", 1, drop, interp);
94    define_method(&iterator_proto, "flatMap", 1, flat_map, interp);
95    define_method(&iterator_proto, "reduce", 1, reduce, interp);
96    define_method(&iterator_proto, "toArray", 0, to_array, interp);
97    define_method(&iterator_proto, "forEach", 1, for_each, interp);
98    define_method(&iterator_proto, "some", 1, some, interp);
99    define_method(&iterator_proto, "every", 1, every, interp);
100    define_method(&iterator_proto, "find", 1, find, interp);
101    define_method(&iterator_proto, "join", 1, join, interp);
102    define_method(&iterator_proto, "includes", 1, includes, interp);
103    define_method(&iterator_proto, "chunks", 1, chunks, interp);
104    define_method(&iterator_proto, "windows", 1, windows, interp);
105
106    // `Iterator.prototype[Symbol.iterator]` answers `this`, so an iterator is iterable
107    // and `for (x of it)` consumes it in place rather than copying.
108    let iterator_key = interp
109        .realm
110        .well_known_key(crate::interp::WellKnown::Iterator);
111    let identity = interp.new_native("[Symbol.iterator]", 0, identity_iterator);
112    iterator_proto.define_key(
113        &iterator_key,
114        Property::with_attributes(Value::Object(identity), true, false),
115    );
116    // §27.1.4.1: `Iterator.prototype[@@dispose]` closes the iterator, which is what lets
117    // `using it = xs.values()` clean up.
118    let dispose_key = interp
119        .realm
120        .well_known_key(crate::interp::WellKnown::Disposable);
121    let dispose = interp.new_native("[Symbol.dispose]", 0, dispose_self);
122    iterator_proto.define_key(
123        &dispose_key,
124        Property::with_attributes(Value::Object(dispose), true, false),
125    );
126    // §27.1.3.1: `Iterator.prototype[@@toStringTag]` is an **accessor** pair, not a data
127    // property — the getter answers `"Iterator"` for any receiver (including none), and the
128    // setter is `SetterThatIgnoresPrototypeProperties`, so assigning to it from an ordinary
129    // object shadows the accessor while assigning on the home object throws
130    // (`Symbol.toStringTag/prop-desc`, `…/weird-setter`).
131    let tag_getter = interp.new_native("get [Symbol.toStringTag]", 0, iterator_tag_getter);
132    let tag_setter = interp.new_native("set [Symbol.toStringTag]", 1, iterator_tag_setter);
133    let tag_key = interp
134        .realm
135        .well_known_key(crate::interp::WellKnown::ToStringTag);
136    iterator_proto.define_key(
137        &tag_key,
138        Property {
139            getter: Some(Value::Object(tag_getter)),
140            setter: Some(Value::Object(tag_setter)),
141            enumerable: false,
142            configurable: true,
143            ..Property::default()
144        },
145    );
146
147    // `Iterator.prototype.constructor` is an **accessor**, not a data property
148    // (`sec-set-iteratorprototype-constructor`). Both halves are §7.3.40
149    // `SetterThatIgnoresPrototypeProperties`, the same mechanism `Error.prototype.stack`
150    // needs — so the setter here is one call into it, and the point is the same: assigning
151    // to `Iterator.prototype.constructor` throws instead of shadowing the accessor.
152    //
153    // The getter answers `Iterator` for any object, including `get.call()` with no
154    // receiver at all (`weird-setter` asserts exactly that), which is why it does not read
155    // `this`.
156    let ctor_getter = interp.new_native("get constructor", 0, iterator_constructor_getter);
157    let ctor_setter = interp.new_native("set constructor", 1, iterator_constructor_setter);
158    iterator_proto.define(
159        "constructor",
160        Property {
161            getter: Some(Value::Object(ctor_getter)),
162            setter: Some(Value::Object(ctor_setter)),
163            enumerable: false,
164            configurable: true,
165            ..Property::default()
166        },
167    );
168
169    // The helper prototype sits between a helper object and `Iterator.prototype`, so a
170    // helper *is* an `Iterator` while still being recognisable as one.
171    let helper_proto = interp.new_object(Some(iterator_proto.clone()));
172    define_method(&helper_proto, "next", 0, helper_next, interp);
173    define_method(&helper_proto, "return", 0, helper_return, interp);
174    helper_proto.define_key(
175        &interp
176            .realm
177            .well_known_key(crate::interp::WellKnown::ToStringTag),
178        Property::with_attributes(interp.string("Iterator Helper"), false, false),
179    );
180    interp.realm.iterator_helper_proto = Some(helper_proto);
181
182    // `Iterator.from` wraps an object that is iterable but is not itself an `Iterator`.
183    // Its prototype forwards `next`/`return` verbatim and deliberately does not override
184    // `@@toStringTag`, so such a wrapper still prints `[object Iterator]`.
185    let wrap_proto = interp.new_object(Some(iterator_proto.clone()));
186    define_method(&wrap_proto, "next", 0, wrap_next, interp);
187    define_method(&wrap_proto, "return", 0, wrap_return, interp);
188    interp.realm.iterator_wrap_proto = Some(wrap_proto);
189
190    define_method(&iterator, "from", 1, from, interp);
191    define_method(&iterator, "concat", 0, concat, interp);
192    define_method(&iterator, "zip", 1, zip, interp);
193    define_method(&iterator, "zipKeyed", 1, zip_keyed, interp);
194
195    interp.realm.iterator_proto = Some(iterator_proto);
196    let global = interp.realm.global.clone();
197    global.define(
198        "Iterator",
199        Property::with_attributes(Value::Object(iterator), true, false),
200    );
201}
202
203// ---------------------------------------------------------------------------
204// The abstract constructor
205// ---------------------------------------------------------------------------
206
207fn iterator_constructor(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
208    // §27.1.3.1: `Iterator` may be *subclassed* but not instantiated. `new Sub()` where
209    // `class Sub extends Iterator {}` has to succeed and build a `Sub` — 171 test262 cases
210    // subclass it — while `new Iterator()` itself throws.
211    //
212    // `NewTarget` is what separates the two, and `this` already answers for it: the
213    // runtime pre-created this object from `NewTarget.prototype`, so its prototype is
214    // exactly `Iterator.prototype` when and only when NewTarget was `Iterator` itself.
215    if matches!(this, Value::Undefined) {
216        return Err(Signal::Throw(
217            interp.make_error("TypeError", "constructor requires 'new'"),
218        ));
219    }
220    let own_proto = this
221        .as_object()
222        .and_then(|object| object.proto())
223        .is_some_and(|proto| {
224            interp
225                .realm
226                .iterator_proto
227                .as_ref()
228                .is_some_and(|target| proto.ptr_eq(target))
229        });
230    if own_proto {
231        return Err(Signal::Throw(
232            interp.make_error("TypeError", "abstract class not constructable"),
233        ));
234    }
235    // A subclass: the instance the runtime made is the answer.
236    Ok(this)
237}
238
239fn identity_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
240    Ok(this)
241}
242
243/// `Iterator.prototype.constructor`'s getter: always `Iterator`, whatever `this` is.
244///
245/// `weird-setter` calls `get.call()` with no receiver at all and expects `Iterator` back,
246/// so this deliberately does not validate `this`.
247fn iterator_constructor_getter(
248    interp: &mut Interp<'_>,
249    _this: Value,
250    _args: &[Value],
251) -> JsResult<Value> {
252    match interp.realm.iterator_ctor.clone() {
253        Some(ctor) => Ok(Value::Object(ctor)),
254        None => Ok(Value::Undefined),
255    }
256}
257
258/// `Iterator.prototype.constructor`'s setter: §7.3.40 with `home = Iterator.prototype`.
259fn iterator_constructor_setter(
260    interp: &mut Interp<'_>,
261    this: Value,
262    args: &[Value],
263) -> JsResult<Value> {
264    let Some(home) = interp.realm.iterator_proto.clone() else {
265        return Err(interp.type_error("Iterator.prototype is not installed"));
266    };
267    interp.setter_that_ignores_prototype_properties(this, &home, "constructor", args)
268}
269
270fn dispose_self(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
271    let record = iterator_record(interp, &this)?;
272    close(interp, &record)?;
273    Ok(Value::Undefined)
274}
275
276// ---------------------------------------------------------------------------
277// Iterator records
278// ---------------------------------------------------------------------------
279
280/// `GetIteratorDirect(obj)`: a snapshot of `obj.next`.
281///
282/// Taking `next` once, here, is observable: an iterable whose `next` is a getter sees one
283/// read, not one per step, and replacing `next` after the helper is created has no effect.
284fn iterator_record(interp: &mut Interp<'_>, value: &Value) -> JsResult<crate::interp::Iterator> {
285    let Some(object) = value.as_object().cloned() else {
286        return Err(interp.type_error("not an object"));
287    };
288    // `Get(obj, "next")` and nothing more: §7.3.11 `GetIteratorDirect` does **not** check
289    // that `next` is callable. That check happens when the method is called, which is why
290    // `Iterator.from({return(){}})` — an object with no `next` at all — succeeds, while
291    // `Iterator.prototype.find.call({next: 0}, f)` still throws, just one step later. See
292    // [`step`] for where it happens.
293    let next = interp
294        .get_property(&object, "next")?
295        .unwrap_or(Value::Undefined);
296    Ok(crate::interp::Iterator {
297        object: Value::Object(object),
298        next,
299    })
300}
301
302/// `IteratorStep`: one value, or `None` when the iterator is exhausted.
303///
304/// The callability check lives here rather than in [`iterator_record`], because that is
305/// where the spec puts it: `[[NextMethod]]` is whatever `next` was at record-creation time,
306/// and calling a non-callable is a `TypeError`. `iterator_step` treats a non-callable as
307/// "already exhausted", which is the right reading for a `for…of` over a finished iterator
308/// but not for a helper that was handed garbage.
309fn step(interp: &mut Interp<'_>, record: &crate::interp::Iterator) -> JsResult<Option<Value>> {
310    if !matches!(&record.next, Value::Object(function) if function.is_callable()) {
311        return Err(interp.type_error("not a function"));
312    }
313    let (value, done) = interp.iterator_step(record)?;
314    Ok(if done { None } else { Some(value) })
315}
316
317/// [`step`], on a helper whose source this is: a throw out of the source's own `next`
318/// **completes the helper** without forwarding `return` to the source.
319///
320/// The distinction is `§`27.1.4.4's: an iterator helper's body is a generator, so an
321/// abrupt completion from `next` runs the generator's own completion — which for these
322/// helpers includes `IteratorClose` only for the *steps inside the body*, not for the step
323/// that failed. `take/completed-after-abrupt-completion` asserts `retCalls === 0` after a
324/// throwing source `next`, while `map/mapper-throws` asserts `returnCalls === 1` for a
325/// throwing *callback*. Both are correct; the difference is where the throw came from.
326fn step_source(
327    interp: &mut Interp<'_>,
328    helper: &JsObject,
329    record: &crate::interp::Iterator,
330) -> JsResult<Option<Value>> {
331    match step(interp, record) {
332        Err(signal) => {
333            // Mark done so a later `next()` answers `{done: true}` and a later `return()`
334            // is not forwarded (`helper_return` reads this flag).
335            write_hidden(helper, DONE, Value::Bool(true));
336            Err(signal)
337        }
338        ok => ok,
339    }
340}
341
342/// `IteratorClose`: tell the iterator it will not be read again.
343///
344/// Used when a consumer stops early. Errors from the iterator's own `return` are swallowed
345/// on the "we were already leaving" path, which is what §7.4.11 asks for.
346fn close(interp: &mut Interp<'_>, record: &crate::interp::Iterator) -> JsResult<()> {
347    let Some(source) = record.object.as_object().cloned() else {
348        return Ok(());
349    };
350    let method = interp.get_property(&source, "return")?;
351    match method {
352        // §7.4.11 `IteratorClose` steps 4–6: a missing `return` is a no-op, but a
353        // **non-callable** one is a `TypeError`, and a non-object result is one too. Both
354        // are checked and neither was before, so `concat`'s three close tests saw a clean
355        // exit instead of the error the spec asks for
356        // (`return-method-not-callable`, `return-method-returns-non-object`).
357        None | Some(Value::Undefined) | Some(Value::Null) => Ok(()),
358        Some(Value::Object(function)) if function.is_callable() => {
359            let result =
360                interp.call_value(Value::Object(function), record.object.clone(), Vec::new())?;
361            if !matches!(result, Value::Object(_)) {
362                return Err(interp.type_error("iterator return did not answer an object"));
363            }
364            Ok(())
365        }
366        Some(_) => Err(interp.type_error("iterator return is not a function")),
367    }
368}
369
370// ---------------------------------------------------------------------------
371// Building a helper
372// ---------------------------------------------------------------------------
373
374/// `IfAbruptCloseIterator(this, …)` for a helper whose argument was rejected.
375///
376/// The receiver is closed *without* reading `next`: validation happens before
377/// `GetIteratorDirect`, so a `next` getter that throws must never run — but `return` must,
378/// which is what `argument-validation-failure-closes-underlying` checks.
379fn close_receiver(interp: &mut Interp<'_>, this: &Value) -> JsResult<()> {
380    let Some(object) = this.as_object().cloned() else {
381        return Ok(());
382    };
383    match interp.get_property(&object, "return")? {
384        Some(Value::Object(function)) if function.is_callable() => {
385            interp.call_value(Value::Object(function), this.clone(), Vec::new())?;
386            Ok(())
387        }
388        _ => Ok(()),
389    }
390}
391
392/// `ToIntegerOrInfinity` for a helper's count argument.
393///
394/// `ToNumber` comes first and is *observable*, so it cannot be folded into this: a limit
395/// object's `valueOf` runs before `next` is read, and a test records exactly that order.
396fn count_argument(
397    interp: &mut Interp<'_>,
398    this: &Value,
399    value: &Value,
400    message: &str,
401) -> JsResult<f64> {
402    // §7.2.9: a non-object receiver is a `TypeError` *before* the argument is examined —
403    // `windows.call(null, 0)` must not report the bad count.
404    if !matches!(this, Value::Object(_)) {
405        return Err(interp.type_error("not an object"));
406    }
407    let number = match interp.to_js_number(value) {
408        Ok(number) => number,
409        Err(signal) => {
410            // A close that *itself* throws must not mask the original error: `IteratorClose`
411            // returns the incoming throw completion whatever the `return` call did
412            // (`chunks/argument-validation-failure-close-throws`).
413            let _ = close_receiver(interp, this);
414            return Err(signal);
415        }
416    };
417    // The count is `ToNumber` → truncate, and then **`≥ 0` and `≤ 2^53 - 1`**. Note what
418    // is *not* `ToIntegerOrInfinity`: `NaN` must stay a `RangeError` rather than becoming
419    // `0`, and `undefined` (which `ToNumber`s to `NaN`) is refused for the same reason.
420    // `take/limit-rangeerror` lists all of it, including `Infinity` being *accepted*.
421    let integer = number.trunc();
422    // `Infinity` is accepted (it means "no limit"); only a *finite* value past the bound is
423    // refused, which is what `take/limit-rangeerror` distinguishes by listing both
424    // `Infinity` (ok) and `MAX_SAFE_INTEGER + 1` (`RangeError`).
425    let out_of_range =
426        integer.is_nan() || integer < 0.0 || (integer.is_finite() && integer > MAX_SAFE_INTEGER);
427    if out_of_range {
428        // A close that *itself* throws must not mask the original error: `IteratorClose`
429        // returns the incoming throw completion whatever the `return` call did
430        // (`chunks/argument-validation-failure-close-throws`).
431        let _ = close_receiver(interp, this);
432        return Err(interp.range_error(message));
433    }
434    Ok(integer)
435}
436
437/// The `chunkSize`/`windowSize` argument: it must already be an integral Number.
438///
439/// Unlike `take`/`drop`, these two do **not** run `ToNumber`. `chunks("2")` is a
440/// `TypeError`, not `chunks(2)` — a string that looks like a count is a mistake worth
441/// reporting rather than guessing at. `NaN`, `0.5`, `Infinity` and objects are all
442/// refused for the same reason.
443fn integral_count(
444    interp: &mut Interp<'_>,
445    this: &Value,
446    value: &Value,
447    name: &str,
448) -> JsResult<f64> {
449    if !matches!(this, Value::Object(_)) {
450        return Err(interp.type_error("not an object"));
451    }
452    let rejected = interp.type_error(format!("{name} is not an integral number"));
453    let number = match value {
454        Value::Int(number) => *number as f64,
455        Value::Float(number) if number.is_finite() && number.trunc() == *number => *number,
456        _ => {
457            // A close that *itself* throws must not mask the original error: `IteratorClose`
458            // returns the incoming throw completion whatever the `return` call did
459            // (`chunks/argument-validation-failure-close-throws`).
460            let _ = close_receiver(interp, this);
461            return Err(rejected);
462        }
463    };
464    // §24.5.4.6 step 8 / §24.5.4.9 step 8: `chunkSize < 1 or chunkSize > 2**32 - 1` is a
465    // `RangeError`. The upper bound is `ToUint32`'s, not `MAX_SAFE_INTEGER`'s, which is why
466    // `chunks/chunkSize-out-of-range` accepts `2**32 - 1` and refuses `2**32`.
467    if !(1.0..=MAX_CHUNK_SIZE).contains(&number) {
468        // A close that *itself* throws must not mask the original error: `IteratorClose`
469        // returns the incoming throw completion whatever the `return` call did
470        // (`chunks/argument-validation-failure-close-throws`).
471        let _ = close_receiver(interp, this);
472        return Err(interp.range_error(format!("{name} out of range")));
473    }
474    Ok(number)
475}
476
477/// The largest `chunkSize`/`windowSize` the helpers accept: `2**32 - 1`.
478const MAX_CHUNK_SIZE: f64 = 4_294_967_295.0;
479
480/// Allocate a helper object over `source` with the given `kind`.
481fn helper(
482    interp: &mut Interp<'_>,
483    source: crate::interp::Iterator,
484    kind: i32,
485    callback: Option<Value>,
486) -> JsResult<Value> {
487    let proto = interp
488        .realm
489        .iterator_helper_proto
490        .clone()
491        .ok_or_else(|| interp.type_error("iterator helpers are not installed"))?;
492    let object = interp.new_object(Some(proto));
493    let hidden = |value: Value| Property::with_attributes(value, true, false);
494    object.define(SOURCE, hidden(source.object));
495    object.define(SOURCE_NEXT, hidden(source.next));
496    object.define(KIND, hidden(Value::Int(kind)));
497    object.define(DONE, hidden(Value::Bool(false)));
498    object.define(COUNTER, hidden(Value::Int(0)));
499    if let Some(callback) = callback {
500        object.define(CALLBACK, hidden(callback));
501    }
502    Ok(Value::Object(object))
503}
504
505fn read_hidden(_interp: &mut Interp<'_>, object: &JsObject, name: &str) -> JsResult<Value> {
506    // A hidden property is always an own data property written by `write_hidden`, so the
507    // own-property read is both correct and immune to a script putting a getter named
508    // `_source` on `Object.prototype`.
509    Ok(object
510        .own_property(name)
511        .and_then(|property| property.value)
512        .unwrap_or(Value::Undefined))
513}
514
515fn write_hidden(object: &JsObject, name: &str, value: Value) {
516    object.define(name, Property::with_attributes(value, true, false));
517}
518
519/// The receiver as an iterator record, or the `TypeError` a non-object gets.
520fn source_of(interp: &mut Interp<'_>, this: &Value) -> JsResult<crate::interp::Iterator> {
521    iterator_record(interp, this)
522}
523
524/// The callback argument, which must be callable.
525/// The callback argument, which must be callable.
526///
527/// The receiver is closed on refusal: §7.4.11 applies to a failed *validation* as much as
528/// to a throwing callback, and `argument-validation-failure-closes-underlying` checks it.
529fn require_callback(interp: &mut Interp<'_>, this: &Value, value: &Value) -> JsResult<Value> {
530    match value {
531        Value::Object(object) if object.is_callable() => Ok(value.clone()),
532        _ => {
533            let _ = close_receiver(interp, this);
534            Err(interp.type_error("not a function"))
535        }
536    }
537}
538
539// ---------------------------------------------------------------------------
540// The shared `next`
541// ---------------------------------------------------------------------------
542
543fn helper_next(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
544    // §27.1.4.4 step 1: a helper is a generator, and stepping a generator that is already
545    // running is a `TypeError`. The case that notices is a source `next` which calls back
546    // into the helper: `TestIterator.next` does `iter.next()` on the helper it is feeding
547    // (`throws-typeerror-when-generator-is-running`, every helper).
548    //
549    // Tracked with a plain flag on the helper object rather than by reusing the generator
550    // machinery, because these helpers are native functions with hidden slots, not real
551    // generator frames.
552    if let Some(object) = this.as_object().cloned() {
553        if read_hidden(interp, &object, RUNNING)?.to_boolean() {
554            return Err(interp.type_error("iterator helper is already running"));
555        }
556        write_hidden(&object, RUNNING, Value::Bool(true));
557        let outcome = helper_step(interp, &this, args);
558        write_hidden(&object, RUNNING, Value::Bool(false));
559        // A throw from a *callback* closes the source (§7.4.11): `map/mapper-throws`
560        // counts exactly one `return` call. A throw from the source's own `next` does not
561        // — `step_source` has already marked the helper done in that case, which is what
562        // `completed-after-abrupt-completion` relies on (`retCalls === 0`).
563        if outcome.is_err() && !read_hidden(interp, &object, DONE)?.to_boolean() {
564            // `close_helper` sets `DONE` itself; setting it here first made the helper look
565            // already-closed and the source was never told (`mapper-throws` counts zero
566            // `return` calls instead of one).
567            let _ = close_helper(interp, &object);
568        }
569        return outcome;
570    }
571    helper_step(interp, &this, args)
572}
573
574fn helper_step(interp: &mut Interp<'_>, this: &Value, _args: &[Value]) -> JsResult<Value> {
575    let this = this.clone();
576    let Some(object) = this.as_object().cloned() else {
577        return Err(interp.type_error("not an object"));
578    };
579    if read_hidden(interp, &object, DONE)?.to_boolean() {
580        return Ok(done_result(interp));
581    }
582    let kind = read_hidden(interp, &object, KIND)?.to_number() as i32;
583    match kind {
584        KIND_MAP => {
585            let source = stored_source(&object, interp)?;
586            let Some(value) = step_source(interp, &object, &source)? else {
587                write_hidden(&object, DONE, Value::Bool(true));
588                return Ok(done_result(interp));
589            };
590            let callback = read_hidden(interp, &object, CALLBACK)?;
591            let counter = read_hidden(interp, &object, COUNTER)?.to_number();
592            write_hidden(&object, COUNTER, Value::Float(counter + 1.0));
593            // The mapper gets `(value, counter)`: the second argument is a running index,
594            // and a test checks it counts 0,1,2,… across a generator.
595            let mapped = interp.call_value(
596                callback,
597                Value::Undefined,
598                vec![value, Value::Int(counter as i32)],
599            )?;
600            Ok(value_result(interp, mapped))
601        }
602        KIND_FILTER => {
603            let source = stored_source(&object, interp)?;
604            let callback = read_hidden(interp, &object, CALLBACK)?;
605            // Keep pulling until the predicate says yes; an exhausted source is the only
606            // other way out, so an always-false predicate terminates instead of spinning.
607            loop {
608                let Some(value) = step_source(interp, &object, &source)? else {
609                    write_hidden(&object, DONE, Value::Bool(true));
610                    return Ok(done_result(interp));
611                };
612                let counter = read_hidden(interp, &object, COUNTER)?.to_number();
613                write_hidden(&object, COUNTER, Value::Float(counter + 1.0));
614                let keep = interp.call_value(
615                    callback.clone(),
616                    Value::Undefined,
617                    vec![value.clone(), Value::Int(counter as i32)],
618                )?;
619                if keep.to_boolean() {
620                    return Ok(value_result(interp, value));
621                }
622            }
623        }
624        KIND_TAKE => {
625            let remaining = read_hidden(interp, &object, REMAINING)?.to_number();
626            if remaining <= 0.0 {
627                // `take(0)` never touches the source, and the spec still wants it closed.
628                write_hidden(&object, DONE, Value::Bool(true));
629                let source = stored_source(&object, interp)?;
630                close(interp, &source)?;
631                return Ok(done_result(interp));
632            }
633            let source = stored_source(&object, interp)?;
634            let Some(value) = step_source(interp, &object, &source)? else {
635                write_hidden(&object, DONE, Value::Bool(true));
636                return Ok(done_result(interp));
637            };
638            // The close happens on the call **after** the last value, not during it.
639            // `take` is a generator whose loop re-checks `remaining <= 0` on the next
640            // resume, so `take(1)` yields one value and only the *second* `next` calls
641            // `return` — and if that `return` throws, it is the second call that reports
642            // it (`take/exhaustion-calls-return` asserts the throw and then two quiet
643            // `done` results). Closing eagerly made the first `next` throw instead.
644            write_hidden(&object, REMAINING, Value::Float(remaining - 1.0));
645            Ok(value_result(interp, value))
646        }
647        KIND_DROP => {
648            let source = stored_source(&object, interp)?;
649            let mut left = read_hidden(interp, &object, REMAINING)?.to_number();
650            while left > 0.0 {
651                if step_source(interp, &object, &source)?.is_none() {
652                    write_hidden(&object, DONE, Value::Bool(true));
653                    return Ok(done_result(interp));
654                }
655                left -= 1.0;
656            }
657            write_hidden(&object, REMAINING, Value::Float(0.0));
658            match step_source(interp, &object, &source)? {
659                Some(value) => Ok(value_result(interp, value)),
660                None => {
661                    write_hidden(&object, DONE, Value::Bool(true));
662                    Ok(done_result(interp))
663                }
664            }
665        }
666        KIND_FLAT_MAP => {
667            let callback = read_hidden(interp, &object, CALLBACK)?;
668            loop {
669                // Drain the inner iterator first: `flatMap` flattens one level, so the
670                // outer step only happens once the current inner one is exhausted.
671                let inner = read_hidden(interp, &object, INNER)?;
672                if let Value::Object(_) = &inner {
673                    let inner_record = iterator_record(interp, &inner)?;
674                    if let Some(value) = step(interp, &inner_record)? {
675                        return Ok(value_result(interp, value));
676                    }
677                    write_hidden(&object, INNER, Value::Undefined);
678                }
679                let source = stored_source(&object, interp)?;
680                let Some(value) = step_source(interp, &object, &source)? else {
681                    write_hidden(&object, DONE, Value::Bool(true));
682                    return Ok(done_result(interp));
683                };
684                let counter = read_hidden(interp, &object, COUNTER)?.to_number();
685                write_hidden(&object, COUNTER, Value::Float(counter + 1.0));
686                let produced = interp.call_value(
687                    callback.clone(),
688                    Value::Undefined,
689                    vec![value, Value::Int(counter as i32)],
690                )?;
691                // `flatMap` iterates what the callback returned, and that may be any
692                // iterable — an array is the common case — so it goes through the same
693                // wrapping `Iterator.from` does.
694                // §27.1.4.3 `GetIteratorFlattenable(…, reject-primitives)`: a **string
695                // primitive** is refused, because otherwise every character would be a
696                // separate element — a `String` *wrapper* is a normal iterable and does
697                // flatten (`flatMap/strings-are-not-flattened` checks both halves).
698                if matches!(produced, Value::String(_)) {
699                    let signal = interp.type_error("flatMap callback returned a string");
700                    write_hidden(&object, DONE, Value::Bool(true));
701                    close_helper(interp, &object)?;
702                    return Err(signal);
703                }
704                let wrapped = into_iterator(interp, produced)?;
705                write_hidden(&object, INNER, wrapped);
706            }
707        }
708        KIND_CHUNKS => {
709            let size = read_hidden(interp, &object, REMAINING)?.to_number();
710            let source = stored_source(&object, interp)?;
711            let mut items = Vec::new();
712            while (items.len() as f64) < size {
713                match step_source(interp, &object, &source)? {
714                    Some(value) => items.push(value),
715                    None => break,
716                }
717            }
718            if items.is_empty() {
719                write_hidden(&object, DONE, Value::Bool(true));
720                return Ok(done_result(interp));
721            }
722            let array = interp.new_array(items);
723            Ok(value_result(interp, Value::Object(array)))
724        }
725        KIND_WINDOWS => {
726            let size = read_hidden(interp, &object, REMAINING)?.to_number() as usize;
727            let source = stored_source(&object, interp)?;
728            let buffer = read_hidden(interp, &object, BUFFER)?;
729            let mut items: Vec<Value> = match &buffer {
730                Value::Object(array) => array.array_elements().unwrap_or_default(),
731                _ => Vec::new(),
732            };
733            let allow_partial = read_hidden(interp, &object, ALLOW_PARTIAL)?.to_boolean();
734            // Both arms end up here when the source runs out: `"only-full"` stops, and
735            // `"allow-partial"` yields whatever is left — one short window, once — which
736            // is what `windows/windows-allow-partial` and `windows/undersized-default`
737            // differ on. An empty buffer is `done` either way
738            // (`windows/iterator-already-exhausted`).
739            let mut exhausted = false;
740            if items.is_empty() {
741                // Prime the window, then yield the first one.
742                while items.len() < size {
743                    match step_source(interp, &object, &source)? {
744                        Some(value) => items.push(value),
745                        None => {
746                            exhausted = true;
747                            break;
748                        }
749                    }
750                }
751            } else {
752                // Slide: drop the oldest, take the next.
753                items.remove(0);
754                match step_source(interp, &object, &source)? {
755                    Some(value) => items.push(value),
756                    None => exhausted = true,
757                }
758            }
759            if exhausted {
760                write_hidden(&object, DONE, Value::Bool(true));
761                if !allow_partial || items.is_empty() {
762                    return Ok(done_result(interp));
763                }
764            }
765            let stored = interp.new_array(items.clone());
766            write_hidden(&object, BUFFER, Value::Object(stored));
767            let window = interp.new_array(items);
768            Ok(value_result(interp, Value::Object(window)))
769        }
770        KIND_CONCAT => zip_next_concat(interp, &object),
771        KIND_ZIP => zip_next(interp, &object, false),
772        KIND_ZIP_KEYED => zip_next(interp, &object, true),
773        _ => Err(interp.type_error("not a valid iterator helper")),
774    }
775}
776
777/// `Iterator.concat(...).next()`: drain the current source, then move to the next one.
778fn zip_next_concat(interp: &mut Interp<'_>, object: &JsObject) -> JsResult<Value> {
779    loop {
780        let inner = read_hidden(interp, object, CURSOR_INNER)?;
781        if let Value::Object(_) = &inner {
782            let record = iterator_record(interp, &inner)?;
783            if let Some(value) = step(interp, &record)? {
784                return Ok(value_result(interp, value));
785            }
786            write_hidden(object, CURSOR_INNER, Value::Undefined);
787        }
788        let cursor = read_hidden(interp, object, CURSOR)?.to_number() as usize;
789        let list = read_hidden(interp, object, LIST)?;
790        let Some(array) = list.as_object().cloned() else {
791            write_hidden(object, DONE, Value::Bool(true));
792            return Ok(done_result(interp));
793        };
794        let items = array.array_elements().unwrap_or_default();
795        if cursor >= items.len() {
796            write_hidden(object, DONE, Value::Bool(true));
797            return Ok(done_result(interp));
798        }
799        // Each source's `Symbol.iterator` is read here, not at construction, so a consumer
800        // that stops early never touches the later sources.
801        let record = iterator_flattenable(interp, &items[cursor], false)?;
802        write_hidden(object, CURSOR, Value::Int(cursor as i32 + 1));
803        write_hidden(object, CURSOR_INNER, record.object.clone());
804        // Only the object is kept: the next loop turn re-derives the record from it, so
805        // one canonical `next` is used for every source.
806    }
807}
808
809/// `Iterator.zip(...).next()` / `Iterator.zipKeyed(...).next()`.
810fn zip_next(interp: &mut Interp<'_>, object: &JsObject, keyed: bool) -> JsResult<Value> {
811    let mode = read_hidden(interp, object, MODE)?.to_number() as i32;
812    let records = unpack_records(interp, object)?;
813    if records.is_empty() {
814        // Zero sources: nothing to zip. Answering `done` immediately also keeps the
815        // "all exhausted" test below from being vacuously true forever.
816        write_hidden(object, DONE, Value::Bool(true));
817        return Ok(done_result(interp));
818    }
819    let mut values = Vec::with_capacity(records.len());
820    let mut exhausted = 0usize;
821    // `stop` is the index that ended this round — either the one whose `next` threw, or
822    // the first one that reported `done`. What happens next depends on it, so it is
823    // remembered rather than recomputed.
824    let mut stop: Option<usize> = None;
825    for (index, record) in records.iter().enumerate() {
826        match step(interp, record) {
827            Ok(Some(value)) => values.push(Some(value)),
828            Ok(None) => {
829                values.push(None);
830                exhausted += 1;
831                if stop.is_none() && mode != 1 {
832                    // `shortest` stops *here* — the sources after it are closed, not
833                    // stepped. `strict` has to keep reading the remaining sources to know
834                    // whether they finished too, so it records the index and continues.
835                    stop = Some(index);
836                    if mode == 0 {
837                        break;
838                    }
839                }
840            }
841            Err(signal) => {
842                // A source that threw is *not* closed — it is already the one whose
843                // completion is abrupt. Everything opened after it is, and in reverse:
844                // `iterator-zip-iteration-strict-iterator-step-abrupt-completion` expects
845                // "call fourth return, call third return" after `second.next()` throws.
846                close_after(interp, &records, index);
847                write_hidden(object, DONE, Value::Bool(true));
848                return Err(signal);
849            }
850        }
851    }
852    // Three ways this round can end, and they differ in what gets closed.
853    //
854    //  * every source finished together — a clean end, and nothing is closed: there is no
855    //    live iterator left to tell (`strict-checks-remaining-done` counts zero `return`
856    //    calls);
857    //  * the zip stops early — the sources *after* the one that finished are still live and
858    //    are closed in reverse, while the one that reported `done` is already finished;
859    //  * `strict` sees a mismatch — an error, and the same reverse close.
860    let all_done = exhausted == records.len();
861    match mode {
862        // shortest: the first source to finish ends the zip. Every *other* source is
863        // closed — including ones before it — in reverse order, and a throwing `return`
864        // does not stop the unwind: the first such error is remembered and thrown at the
865        // end (`shortest-iterator-close-abrupt-completion` expects `fourth return` to
866        // throw and still see `third return` and `first return` after it).
867        0 => {
868            if let Some(index) = stop {
869                write_hidden(object, DONE, Value::Bool(true));
870                if let Some(signal) = close_all_except(interp, &records, index) {
871                    return Err(signal);
872                }
873                return Ok(done_result(interp));
874            }
875        }
876        // longest: only when every source is finished.
877        1 => {
878            if all_done {
879                write_hidden(object, DONE, Value::Bool(true));
880                return Ok(done_result(interp));
881            }
882        }
883        // strict: all must agree.
884        _ => {
885            if all_done {
886                write_hidden(object, DONE, Value::Bool(true));
887                return Ok(done_result(interp));
888            }
889            if let Some(index) = stop {
890                write_hidden(object, DONE, Value::Bool(true));
891                close_after(interp, &records, index);
892                return Err(interp.type_error("iterators have different lengths"));
893            }
894        }
895    }
896    // A missing value in `longest` mode comes from the `padding` option, which is what
897    // `{mode:"longest", padding:["pad"]}` means: pad that source with `"pad"`.
898    let pads = read_hidden(interp, object, PADDING)?;
899    let pad_values = pads
900        .as_object()
901        .map(|array| array.array_elements().unwrap_or_default())
902        .unwrap_or_default();
903    let values: Vec<Value> = values
904        .into_iter()
905        .enumerate()
906        .map(|(index, value)| {
907            value.unwrap_or_else(|| pad_values.get(index).cloned().unwrap_or(Value::Undefined))
908        })
909        .collect();
910    let result = if keyed {
911        let keys = read_hidden(interp, object, KEYS)?;
912        let names = keys
913            .as_object()
914            .map(|array| array.array_elements().unwrap_or_default())
915            .unwrap_or_default();
916        // A **null** prototype, not `Object.prototype`: the result is a plain record whose
917        // keys come from script data, so inheriting anything would let a key like
918        // `toString` collide with a method. `results-object-has-default-attributes` and
919        // `results-object-from-array` both check this.
920        let entry = interp.new_object(None);
921        for (index, value) in values.into_iter().enumerate() {
922            let Some(name) = names.get(index).cloned() else {
923                continue;
924            };
925            // The stored key is a `Value` so that a symbol key stays a symbol; turning it
926            // into text here made `zipKeyed({[sym]: xs})` drop the property entirely.
927            let key = match &name {
928                Value::Symbol(symbol) => crate::object::PropertyKey::Symbol(symbol.clone()),
929                Value::String(text) => crate::object::PropertyKey::String(text.wtf8().clone()),
930                _ => continue,
931            };
932            entry.define_key(&key, Property::with_attributes(value, true, true));
933        }
934        Value::Object(entry)
935    } else {
936        Value::Object(interp.new_array(values))
937    };
938    Ok(value_result(interp, result))
939}
940
941/// The source record a helper was built over.
942fn stored_source(object: &JsObject, interp: &mut Interp<'_>) -> JsResult<crate::interp::Iterator> {
943    Ok(crate::interp::Iterator {
944        object: read_hidden(interp, object, SOURCE)?,
945        next: read_hidden(interp, object, SOURCE_NEXT)?,
946    })
947}
948
949fn helper_return(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
950    // Closing a helper closes what is underneath it, once. Without the propagation a
951    // `for…of` over `xs.map(f)` that breaks early would leave `xs` open.
952    //
953    // A helper that is *already* completed does **not** forward: an iterator helper's body
954    // is a generator, so an abrupt completion from it completes the generator, and a later
955    // `return()` on a completed generator answers `{done: true}` without running the body's
956    // `finally`-equivalent — here, the `IteratorClose` of the source.
957    //
958    // `completed-after-abrupt-completion` counts exactly that: after a `next()` whose
959    // source throws, `return()` must not call the source's `return` (`retCalls` stays 0,
960    // while the source is still closed by the abrupt path itself). `close_helper` already
961    // short-circuits on `DONE`; the read here is what makes the *intent* explicit and keeps
962    // the two paths from sharing one flag by accident.
963    if let Some(object) = this.as_object().cloned() {
964        if read_hidden(interp, &object, DONE)?.to_boolean() {
965            return Ok(done_result(interp));
966        }
967        close_helper(interp, &object)?;
968    }
969    Ok(done_result(interp))
970}
971
972/// Close whatever the helper is currently reading, and mark it done.
973///
974/// Which source is "underneath" depends on the kind: `flatMap` has a per-element inner
975/// iterator, `concat` a per-source one, and the rest a single fixed source. All three are
976/// checked, because each is the live one for some helper. The `DONE` flag makes the second
977/// close a no-op — a `return` followed by an abrupt completion must not close twice.
978fn close_helper(interp: &mut Interp<'_>, object: &JsObject) -> JsResult<()> {
979    if read_hidden(interp, object, DONE)?.to_boolean() {
980        return Ok(());
981    }
982    write_hidden(object, DONE, Value::Bool(true));
983    for slot in [INNER, CURSOR_INNER] {
984        let inner = read_hidden(interp, object, slot)?;
985        if let Value::Object(_) = &inner {
986            let record = iterator_record(interp, &inner)?;
987            close(interp, &record)?;
988        }
989    }
990    let source = read_hidden(interp, object, SOURCE)?;
991    if let Value::Object(_) = &source {
992        let record = stored_source(object, interp)?;
993        close(interp, &record)?;
994    }
995    // `Iterator.zip`/`zipKeyed` keep their sources as a flat list rather than a single
996    // `_source`, so neither of the slots above is one of them. `return()` on a zip closes
997    // **every** underlying iterator, in reverse order — that is the `IteratorClose` its
998    // generator body runs when it is returned from
999    // (`zip/suspended-start-iterator-close-calls-next` and the nine beside it).
1000    let kind = read_hidden(interp, object, KIND)?.to_number() as i32;
1001    if kind == KIND_ZIP || kind == KIND_ZIP_KEYED {
1002        let records = unpack_records(interp, object)?;
1003        // Reverse order, **and closing continues** after one of them throws: the first
1004        // exception becomes the completion and the rest are ignored, exactly like an
1005        // `IteratorClose` loop with an already-thrown completion
1006        // (`zip/iterator-zip-iteration-iterator-close-abrupt-completion`: `third` succeeds,
1007        // `second` throws `ExpectedError`, `first` throws `Test262Error`, and the caller
1008        // sees `ExpectedError` — after `first.return` has still been called).
1009        let mut failure: Option<crate::interp::Signal> = None;
1010        for record in records.iter().rev() {
1011            if let Err(signal) = close(interp, record)
1012                && failure.is_none()
1013            {
1014                failure = Some(signal);
1015            }
1016        }
1017        if let Some(signal) = failure {
1018            return Err(signal);
1019        }
1020    }
1021    Ok(())
1022}
1023
1024fn done_result(interp: &Interp<'_>) -> Value {
1025    let object = interp.new_object(Some(interp.realm.object_proto.clone()));
1026    object.define(
1027        "value",
1028        Property::with_attributes(Value::Undefined, true, true),
1029    );
1030    object.define(
1031        "done",
1032        Property::with_attributes(Value::Bool(true), true, true),
1033    );
1034    Value::Object(object)
1035}
1036
1037fn value_result(interp: &Interp<'_>, value: Value) -> Value {
1038    let object = interp.new_object(Some(interp.realm.object_proto.clone()));
1039    object.define("value", Property::with_attributes(value, true, true));
1040    object.define(
1041        "done",
1042        Property::with_attributes(Value::Bool(false), true, true),
1043    );
1044    Value::Object(object)
1045}
1046
1047// ---------------------------------------------------------------------------
1048// The prototype methods
1049// ---------------------------------------------------------------------------
1050
1051/// Close the receiver after a *validation* failure.
1052///
1053/// Only validation closes this way. Once iteration has started, the rule is narrower: a
1054/// throwing callback closes the iterator, a throwing `next`/`done`/`value` does not. The
1055/// first is `IfAbruptCloseIterator`; the second is the iterator failing on its own and is
1056/// propagated untouched.
1057fn rejected(interp: &mut Interp<'_>, this: &Value, signal: Signal) -> Signal {
1058    let _ = close_receiver(interp, this);
1059    signal
1060}
1061
1062fn map(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1063    let callback = require_callback(interp, &this, &arg(args, 0))?;
1064    let source = source_of(interp, &this)?;
1065    helper(interp, source, KIND_MAP, Some(callback))
1066}
1067
1068fn filter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1069    let callback = require_callback(interp, &this, &arg(args, 0))?;
1070    let source = source_of(interp, &this)?;
1071    helper(interp, source, KIND_FILTER, Some(callback))
1072}
1073
1074fn take(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1075    let remaining = count_argument(interp, &this, &arg(args, 0), "must be positive")?;
1076    let source = source_of(interp, &this)?;
1077    let value = helper(interp, source, KIND_TAKE, None)?;
1078    if let Value::Object(object) = &value {
1079        write_hidden(object, REMAINING, Value::Float(remaining));
1080    }
1081    Ok(value)
1082}
1083
1084fn drop(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1085    let remaining = count_argument(interp, &this, &arg(args, 0), "must be positive")?;
1086    let source = source_of(interp, &this)?;
1087    let value = helper(interp, source, KIND_DROP, None)?;
1088    if let Value::Object(object) = &value {
1089        write_hidden(object, REMAINING, Value::Float(remaining));
1090    }
1091    Ok(value)
1092}
1093
1094fn flat_map(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1095    let callback = require_callback(interp, &this, &arg(args, 0))?;
1096    let source = source_of(interp, &this)?;
1097    helper(interp, source, KIND_FLAT_MAP, Some(callback))
1098}
1099
1100fn chunks(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1101    let size = integral_count(interp, &this, &arg(args, 0), "chunkSize")?;
1102    let source = source_of(interp, &this)?;
1103    let value = helper(interp, source, KIND_CHUNKS, None)?;
1104    if let Value::Object(object) = &value {
1105        write_hidden(object, REMAINING, Value::Float(size));
1106    }
1107    Ok(value)
1108}
1109
1110fn windows(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1111    // The order is `windowSize` then `undersized`, and both come before `next` is read
1112    // (`windows/argument-effect-order`). Checking `undersized` first reported a `TypeError`
1113    // where the spec asks for the `RangeError` an out-of-range `windowSize` produces.
1114    let size = integral_count(interp, &this, &arg(args, 0), "windowSize")?;
1115    // §24.5.4.9 steps 9–12: `undersized` is a String, defaulting to `"only-full"`. Anything
1116    // else is a `TypeError` — checked before `next` is read, which is what
1117    // `windows/argument-effect-order` records.
1118    let allow_partial = match args.get(1) {
1119        None | Some(Value::Undefined) => false,
1120        Some(Value::String(text)) => match text.as_str() {
1121            Some("only-full") => false,
1122            Some("allow-partial") => true,
1123            _ => {
1124                let signal = interp.type_error("bad undersized option");
1125                return Err(rejected(interp, &this, signal));
1126            }
1127        },
1128        Some(_) => {
1129            let signal = interp.type_error("bad undersized option");
1130            return Err(rejected(interp, &this, signal));
1131        }
1132    };
1133    let source = source_of(interp, &this)?;
1134    let value = helper(interp, source, KIND_WINDOWS, None)?;
1135    if let Value::Object(object) = &value {
1136        write_hidden(object, REMAINING, Value::Float(size));
1137        write_hidden(object, ALLOW_PARTIAL, Value::Bool(allow_partial));
1138    }
1139    Ok(value)
1140}
1141
1142/// What a consumer does with one element: `Some` stops the walk with that answer.
1143type Consumer<'a> = dyn FnMut(&mut Interp<'_>, usize, Value) -> JsResult<Option<Value>> + 'a;
1144
1145/// Drain the receiver through `f`, passing the index as the second argument.
1146///
1147/// The three ways out are deliberately different. A *natural* end leaves the iterator
1148/// alone: it is already done, and closing it would run a `return` the spec does not ask
1149/// for. An *early* stop closes it and lets a throwing `return` surface. An abrupt
1150/// completion **from the callback** closes it. An abrupt completion from the iterator's
1151/// own `next`/`done`/`value` does *not* — `IfAbruptCloseIterator` only covers the
1152/// callback, which is what all the `underlying-iterator-not-closed-when-step-throws`
1153/// tests check.
1154fn iterate(interp: &mut Interp<'_>, this: &Value, f: &mut Consumer<'_>) -> JsResult<Value> {
1155    let record = source_of(interp, this)?;
1156    let mut index = 0usize;
1157    loop {
1158        // `?` here is the "do not close" path: the iterator itself failed.
1159        let Some(value) = step(interp, &record)? else {
1160            return Ok(Value::Undefined);
1161        };
1162        match f(interp, index, value) {
1163            Ok(Some(result)) => {
1164                close(interp, &record)?;
1165                return Ok(result);
1166            }
1167            Ok(None) => index += 1,
1168            Err(signal) => {
1169                // The callback threw: close, but keep the original error.
1170                let _ = close(interp, &record);
1171                return Err(signal);
1172            }
1173        }
1174    }
1175}
1176
1177fn to_array(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1178    // No `closing` wrapper: `toArray` has no callback, so every way it can fail comes from
1179    // the iterator itself and must propagate without closing it.
1180    let record = source_of(interp, &this)?;
1181    let mut items = Vec::new();
1182    while let Some(value) = step(interp, &record)? {
1183        items.push(value);
1184    }
1185    Ok(Value::Object(interp.new_array(items)))
1186}
1187
1188fn for_each(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1189    let callback = require_callback(interp, &this, &arg(args, 0))?;
1190    iterate(interp, &this, &mut |interp, index, value| {
1191        interp.call_value(
1192            callback.clone(),
1193            Value::Undefined,
1194            vec![value, Value::Int(index as i32)],
1195        )?;
1196        Ok(None)
1197    })?;
1198    Ok(Value::Undefined)
1199}
1200
1201fn some(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1202    let callback = require_callback(interp, &this, &arg(args, 0))?;
1203    let found = iterate(interp, &this, &mut |interp, index, value| {
1204        let answer = interp.call_value(
1205            callback.clone(),
1206            Value::Undefined,
1207            vec![value, Value::Int(index as i32)],
1208        )?;
1209        Ok(answer.to_boolean().then_some(Value::Bool(true)))
1210    })?;
1211    Ok(Value::Bool(matches!(found, Value::Bool(true))))
1212}
1213
1214fn every(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1215    let callback = require_callback(interp, &this, &arg(args, 0))?;
1216    let stopped = iterate(interp, &this, &mut |interp, index, value| {
1217        let answer = interp.call_value(
1218            callback.clone(),
1219            Value::Undefined,
1220            vec![value, Value::Int(index as i32)],
1221        )?;
1222        Ok((!answer.to_boolean()).then_some(Value::Bool(false)))
1223    })?;
1224    Ok(Value::Bool(!matches!(stopped, Value::Bool(false))))
1225}
1226
1227fn find(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1228    let callback = require_callback(interp, &this, &arg(args, 0))?;
1229    iterate(interp, &this, &mut |interp, index, value| {
1230        let answer = interp.call_value(
1231            callback.clone(),
1232            Value::Undefined,
1233            vec![value.clone(), Value::Int(index as i32)],
1234        )?;
1235        Ok(answer.to_boolean().then_some(value))
1236    })
1237}
1238
1239fn reduce(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1240    let callback = require_callback(interp, &this, &arg(args, 0))?;
1241    let record = source_of(interp, &this)?;
1242    (|| -> JsResult<Value> {
1243        let mut accumulator = if args.len() > 1 {
1244            arg(args, 1)
1245        } else {
1246            // No initial value: the first element becomes the accumulator, and an
1247            // empty iterator is a `TypeError` rather than `undefined`.
1248            match step(interp, &record)? {
1249                Some(value) => value,
1250                None => {
1251                    return Err(interp.type_error("reduce of empty iterator with no initial value"));
1252                }
1253            }
1254        };
1255        // The index is the element's position in the *iterator*, so with no initial value
1256        // the first element (already taken as the accumulator) was index 0 and the
1257        // callback's first call is on index 1 (`reduce/reducer-args-no-initial-value`).
1258        let mut index = if args.len() > 1 { 0 } else { 1 };
1259        while let Some(value) = step(interp, &record)? {
1260            // §27.1.4.8 step 6 wraps the reducer call in `IfAbruptCloseIterator`: a throw
1261            // from the callback closes the source (`reduce/reducer-throws` counts one
1262            // `return`), and if that close also throws the **original** error wins
1263            // (`reducer-throws-then-closing-iterator-also-throws`).
1264            match interp.call_value(
1265                callback.clone(),
1266                Value::Undefined,
1267                vec![accumulator, value, Value::Int(index)],
1268            ) {
1269                Ok(next) => accumulator = next,
1270                Err(signal) => {
1271                    let _ = close(interp, &record);
1272                    return Err(signal);
1273                }
1274            }
1275            index += 1;
1276        }
1277        Ok(accumulator)
1278    })()
1279}
1280
1281fn join(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1282    // Like `toArray`, no callback means nothing to close for: `does-not-close-on-*`
1283    // covers a throwing `next`, a protocol violation and a throwing `next` getter.
1284    // §27.1.4.7 step 3: `ToString(separator)` runs **before** `GetIteratorDirect`, and a
1285    // throw from it still closes the receiver — but without ever reading `next`
1286    // (`join/closes-on-separator-coercion-exception` checks both halves).
1287    let separator = match args.first() {
1288        None | Some(Value::Undefined) => ",".to_string(),
1289        Some(value) => match interp.to_js_string(value) {
1290            Ok(text) => text,
1291            // The receiver is closed *without* `next` ever being read — `close_receiver`
1292            // only touches `return`, which is what lets the separator's error win
1293            // (`join/closes-on-separator-coercion-exception` asserts `gotNext === false`)
1294            // and keeps the order `toString` then `get next`
1295            // (`join/next-lookup-after-separator-tostring`).
1296            Err(signal) => {
1297                let _ = close_receiver(interp, &this);
1298                return Err(signal);
1299            }
1300        },
1301    };
1302    let record = source_of(interp, &this)?;
1303    let mut parts = Vec::new();
1304    while let Some(value) = step(interp, &record)? {
1305        // A nullish element joins as the empty string rather than "undefined".
1306        if matches!(value, Value::Undefined | Value::Null) {
1307            parts.push(String::new());
1308        } else {
1309            match interp.to_js_string(&value) {
1310                Ok(text) => parts.push(text),
1311                // `IfAbruptCloseIterator` around the element's `ToString`
1312                // (`join/closes-on-contents-coercion-exception`).
1313                Err(signal) => {
1314                    let _ = close(interp, &record);
1315                    return Err(signal);
1316                }
1317            }
1318        }
1319    }
1320    Ok(interp.string(parts.join(&separator)))
1321}
1322
1323fn includes(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1324    // `includes(searchElement, skippedElements)`: the second argument counts elements
1325    // to pass over first. It must be an integral Number — a string is a `TypeError`
1326    // rather than a coercion, and `1.5`/`NaN` are refused too.
1327    let mut skipped = match args.get(1) {
1328        None | Some(Value::Undefined) => 0.0,
1329        Some(value) => {
1330            let number = match value {
1331                Value::Int(number) => *number as f64,
1332                Value::Float(number) => *number,
1333                _ => {
1334                    // Validation failures close the receiver, and do it without reading
1335                    // `next` — the count is checked before `GetIteratorDirect`.
1336                    let signal = interp.type_error("not a number");
1337                    return Err(rejected(interp, &this, signal));
1338                }
1339            };
1340            // `Infinity` is allowed and simply skips everything.
1341            if number.is_nan() || (number.is_finite() && number.trunc() != number) {
1342                let signal = interp.type_error("not an integral number");
1343                return Err(rejected(interp, &this, signal));
1344            }
1345            if number < 0.0 {
1346                let signal = interp.range_error("must be positive");
1347                return Err(rejected(interp, &this, signal));
1348            }
1349            // Step 8: "if toSkip is finite and toSkip > 2**53 - 1, throw a RangeError" —
1350            // and `IteratorClose` runs first, without reading `next`
1351            // (`includes/skipped-elements-too-large-rangeerror`).
1352            if number.is_finite() && number > MAX_SAFE_INTEGER {
1353                let signal = interp.range_error("skippedElements is too large");
1354                return Err(rejected(interp, &this, signal));
1355            }
1356            number
1357        }
1358    };
1359    let needle = arg(args, 0);
1360    let record = source_of(interp, &this)?;
1361    let outcome = (|| -> JsResult<bool> {
1362        while let Some(value) = step(interp, &record)? {
1363            if skipped > 0.0 {
1364                skipped -= 1.0;
1365                continue;
1366            }
1367            // `SameValueZero`: `NaN` finds `NaN`, and `-0` finds `0`.
1368            if same_value_zero(&value, &needle) {
1369                return Ok(true);
1370            }
1371        }
1372        Ok(false)
1373    })();
1374    let found = outcome?;
1375    if found {
1376        close(interp, &record)?;
1377    }
1378    Ok(Value::Bool(found))
1379}
1380
1381/// `SameValueZero`, which is `===` except that `NaN` matches itself.
1382fn same_value_zero(left: &Value, right: &Value) -> bool {
1383    match (left, right) {
1384        (Value::Float(a), Value::Float(b)) if a.is_nan() && b.is_nan() => true,
1385        (Value::Int(a), Value::Float(b)) => (*a as f64) == *b,
1386        (Value::Float(a), Value::Int(b)) => *a == (*b as f64),
1387        _ => left.strict_equals(right),
1388    }
1389}
1390
1391// ---------------------------------------------------------------------------
1392// The static helpers
1393// ---------------------------------------------------------------------------
1394
1395fn from(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
1396    into_iterator(interp, arg(args, 0))
1397}
1398
1399/// `GetIteratorFlattenable(value, iterateStrings)`.
1400///
1401/// The subtle part is step 3: when the object has **no** `@@iterator`, it is used as the
1402/// iterator record *itself*. That is what makes `Iterator.from({next(){...}})` work — a
1403/// bare iterator with no `Symbol.iterator` — and it is also why such an object has to be
1404/// *wrapped* rather than returned: it is not an `Iterator`, so it has no helper methods.
1405///
1406/// `iterate_strings` is `true` for `Iterator.from`, where a string primitive iterates its
1407/// characters, and `false` for `concat`/`zip`, where `Iterator.concat("ab")` is a
1408/// `TypeError`.
1409fn iterator_flattenable(
1410    interp: &mut Interp<'_>,
1411    value: &Value,
1412    iterate_strings: bool,
1413) -> JsResult<crate::interp::Iterator> {
1414    let allowed_primitive = iterate_strings && matches!(value, Value::String(_));
1415    if !matches!(value, Value::Object(_)) && !allowed_primitive {
1416        return Err(interp.type_error("not an object"));
1417    }
1418    let key = interp
1419        .realm
1420        .well_known_key(crate::interp::WellKnown::Iterator);
1421    // `read_field_key` boxes a primitive receiver, which is how a string primitive finds
1422    // `String.prototype[Symbol.iterator]`.
1423    let method = interp.read_field_key(value, &key)?;
1424    match method {
1425        Value::Undefined | Value::Null => iterator_record(interp, value),
1426        callable if matches!(&callable, Value::Object(object) if object.is_callable()) => {
1427            let produced = interp.call_value(callable, value.clone(), Vec::new())?;
1428            if !matches!(produced, Value::Object(_)) {
1429                return Err(interp.type_error("iterator is not an object"));
1430            }
1431            iterator_record(interp, &produced)
1432        }
1433        _ => Err(interp.type_error("not a function")),
1434    }
1435}
1436
1437/// `Iterator.from(value)`, which `flatMap` also needs.
1438///
1439/// `flatMap` maps each element through the callback and then iterates the *result*, so a
1440/// callback returning a plain array has to work: `[[1,2],[3]].values().flatMap(x => x)`
1441/// is the canonical example. Without wrapping, the array has no `next` and the helper
1442/// died with "not a function".
1443fn into_iterator(interp: &mut Interp<'_>, value: Value) -> JsResult<Value> {
1444    // Already an `Iterator`: hand it back untouched, so `Iterator.from(xs) === xs` holds
1445    // for anything this engine produced. The test is the prototype chain, which is the
1446    // same thing `instanceof Iterator` reports.
1447    if is_iterator(interp, &value) {
1448        return Ok(value);
1449    }
1450    let record = iterator_flattenable(interp, &value, true)?;
1451    let proto = interp
1452        .realm
1453        .iterator_wrap_proto
1454        .clone()
1455        .ok_or_else(|| interp.type_error("iterator helpers are not installed"))?;
1456    let object = interp.new_object(Some(proto));
1457    object.define(
1458        SOURCE,
1459        Property::with_attributes(record.object, true, false),
1460    );
1461    object.define(
1462        SOURCE_NEXT,
1463        Property::with_attributes(record.next, true, false),
1464    );
1465    object.define(
1466        KIND,
1467        Property::with_attributes(Value::Int(KIND_WRAP), true, false),
1468    );
1469    Ok(Value::Object(object))
1470}
1471
1472/// Whether `value`'s prototype chain reaches `Iterator.prototype`.
1473fn is_iterator(interp: &mut Interp<'_>, value: &Value) -> bool {
1474    let Some(target) = interp.realm.iterator_proto.clone() else {
1475        return false;
1476    };
1477    let mut current = value.as_object().cloned();
1478    // Bounded walk: a proxy could answer with a cycle, and `instanceof` has the same
1479    // problem, so this stops rather than hangs.
1480    for _ in 0..10_000 {
1481        match current {
1482            Some(object) => {
1483                if object.ptr_eq(&target) {
1484                    return true;
1485                }
1486                current = object.proto();
1487            }
1488            None => return false,
1489        }
1490    }
1491    false
1492}
1493
1494/// `%WrapForValidIteratorPrototype%.next`: forward to the wrapped iterator untouched.
1495///
1496/// The result object is returned *as the underlying `next` produced it*, not normalised:
1497/// the wrapper is transparent, so a `next` that answers `{value, done}` with extra
1498/// properties keeps them.
1499fn wrap_next(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1500    let Some(object) = this.as_object().cloned() else {
1501        return Err(interp.type_error("not an object"));
1502    };
1503    let next = read_hidden(interp, &object, SOURCE_NEXT)?;
1504    let source = read_hidden(interp, &object, SOURCE)?;
1505    interp.call_value(next, source, Vec::new())
1506}
1507
1508fn wrap_return(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1509    let Some(object) = this.as_object().cloned() else {
1510        return Err(interp.type_error("not an object"));
1511    };
1512    let source = read_hidden(interp, &object, SOURCE)?;
1513    let record = crate::interp::Iterator {
1514        object: source,
1515        next: read_hidden(interp, &object, SOURCE_NEXT)?,
1516    };
1517    close(interp, &record)?;
1518    Ok(done_result(interp))
1519}
1520
1521fn concat(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
1522    // §27.1.3.1 `Iterator.concat(...items)` validates **every** item up front, in order,
1523    // and that is two separate observations:
1524    //
1525    // * a non-object item is a `TypeError` at the call (`Iterator.concat([1], 5)`);
1526    // * `GetIteratorDirect`'s method read — `Get(item, @@iterator)` — happens now too, so a
1527    //   *throwing getter* throws here, and a missing or non-callable method is a
1528    //   `TypeError` here. `arguments-checked-in-order` pins the order: `iterable1`'s getter
1529    //   runs once, then `null` is refused, and `iterable2`'s getter never runs.
1530    //
1531    // The method itself is **not called** until iteration reaches the item
1532    // (`get-iterator-method-only-once` counts one property read and zero calls), so what is
1533    // stored is the iterable, not an iterator.
1534    let mut items = Vec::with_capacity(args.len());
1535    let key = interp
1536        .realm
1537        .well_known_key(crate::interp::WellKnown::Iterator);
1538    for item in args {
1539        if !matches!(item, Value::Object(_)) {
1540            return Err(interp.type_error("not an object"));
1541        }
1542        let method = interp.read_field_key(item, &key)?;
1543        if !matches!(&method, Value::Object(function) if function.is_callable()) {
1544            return Err(interp.type_error("iterable has no iterator method"));
1545        }
1546        items.push(item.clone());
1547    }
1548    let helper = iterator_object(interp, KIND_CONCAT)?;
1549    if let Value::Object(object) = &helper {
1550        let list = interp.new_array(items);
1551        write_hidden(object, LIST, Value::Object(list));
1552        write_hidden(object, CURSOR, Value::Int(0));
1553        write_hidden(object, CURSOR_INNER, Value::Undefined);
1554    }
1555    Ok(helper)
1556}
1557
1558/// An empty helper object with the given kind and no source.
1559///
1560/// `concat`/`zip` have a *list* of sources rather than one, so they cannot go through
1561/// [`helper`] and fill the single-source slots in.
1562fn iterator_object(interp: &mut Interp<'_>, kind: i32) -> JsResult<Value> {
1563    let proto = interp
1564        .realm
1565        .iterator_helper_proto
1566        .clone()
1567        .ok_or_else(|| interp.type_error("iterator helpers are not installed"))?;
1568    let object = interp.new_object(Some(proto));
1569    write_hidden(&object, KIND, Value::Int(kind));
1570    write_hidden(&object, DONE, Value::Bool(false));
1571    Ok(Value::Object(object))
1572}
1573
1574/// `Iterator.zip(iterables, options)`.
1575///
1576/// Three orderings are observable and all three are tested: `mode` is read first, then
1577/// `padding` — but *only* when the mode is `longest`, so a `padding` getter must not fire
1578/// for `shortest` — and only then is the iterables argument opened. Every source is opened
1579/// at call time rather than on the first `next`.
1580///
1581/// `padding` is itself an **iterable**, pulled one value per source position; that is what
1582/// lets `padding: { *[Symbol.iterator]() { while (true) yield 100 + i++ } }` pad an
1583/// unbounded number of sources.
1584fn zip(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
1585    let Some(iterables) = arg(args, 0).as_object().cloned() else {
1586        return Err(interp.type_error("not an object"));
1587    };
1588    let mode = zip_mode(interp, args.get(1))?;
1589    // Only `longest` can pad, so only `longest` reads the option.
1590    let pad_source = if mode == 1 {
1591        match zip_padding_option(interp, args.get(1))? {
1592            Some(value) => Some(interp.get_iterator(&value)?),
1593            None => None,
1594        }
1595    } else {
1596        None
1597    };
1598    let outer = interp.get_iterator(&Value::Object(iterables))?;
1599    let mut records = Vec::new();
1600    let mut pads = Vec::new();
1601    // Collect first, then commit: the sources that were already opened have to be closed
1602    // if a later one fails, and they are closed in reverse order (the most recently opened
1603    // first), which `iterables-iteration-get-iterator-flattenable-abrupt-completion` counts.
1604    let outcome = (|| -> JsResult<()> {
1605        while let Some(item) = step(interp, &outer)? {
1606            if !matches!(item, Value::Object(_)) {
1607                return Err(interp.type_error("not an object"));
1608            }
1609            records.push(iterator_flattenable(interp, &item, false)?);
1610            pads.push(match &pad_source {
1611                Some(source) => step(interp, source)?.unwrap_or(Value::Undefined),
1612                None => Value::Undefined,
1613            });
1614        }
1615        Ok(())
1616    })();
1617    if let Err(signal) = outcome {
1618        for record in records.iter().rev() {
1619            let _ = close(interp, record);
1620        }
1621        let _ = close(interp, &outer);
1622        return Err(signal);
1623    }
1624    finish_zip(interp, KIND_ZIP, mode, records, pads, None)
1625}
1626
1627/// `Iterator.zipKeyed(iterables, options)`.
1628///
1629/// Keyed padding is a plain object read by key, not an iterable: `padding: {a: "pad"}`
1630/// gives `{a: "pad", b: …}`.
1631fn zip_keyed(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
1632    let Some(source) = arg(args, 0).as_object().cloned() else {
1633        return Err(interp.type_error("not an object"));
1634    };
1635    let mode = zip_mode(interp, args.get(1))?;
1636    let padding = if mode == 1 {
1637        match arg(args, 1) {
1638            Value::Object(options) => match interp.get_property(&options, "padding")? {
1639                None | Some(Value::Undefined) => None,
1640                Some(Value::Object(map)) => Some(map),
1641                Some(_) => return Err(interp.type_error("padding must be an object")),
1642            },
1643            _ => None,
1644        }
1645    } else {
1646        None
1647    };
1648    let mut keys = Vec::new();
1649    let mut records = Vec::new();
1650    let mut pads = Vec::new();
1651    // The key list is snapshotted once, but each key's *enumerability* is re-read at the
1652    // moment it is reached. That is observable and tested: `iterables-iteration-enumerable`
1653    // makes `c` non-enumerable from inside `b`'s getter and expects `c` to be skipped, then
1654    // makes `e` enumerable from inside `d`'s getter and expects `e` to be included.
1655    // Through the `[[OwnPropertyKeys]]` / `[[GetOwnProperty]]` internal methods, not the
1656    // object's own tables: a Proxy has to see its traps, and the tests build exactly such
1657    // a proxy to check the read order.
1658    // Collect first, commit second: a key whose `[[Get]]` or `GetIteratorFlattenable`
1659    // throws must leave the already-opened iterators closed, in reverse order — the most
1660    // recently opened one first, which `iterables-iteration-get-abrupt-completion` records.
1661    let outcome = (|| -> JsResult<()> {
1662        for key in interp.object_own_property_keys(&source)? {
1663            let Some(property) = interp.object_get_own_property(&source, &key)? else {
1664                continue;
1665            };
1666            if !property.enumerable {
1667                continue;
1668            }
1669            // `[[GetOwnProperty]]` decides enumerability; the *value* comes from a separate
1670            // `[[Get]]`, which is what runs a getter — readings a `Property` directly would
1671            // miss accessor properties entirely, and they are the common case here.
1672            let item = match interp.get_property_key(&source, &key)? {
1673                // `undefined` is skipped rather than refused, so `{a: undefined, b: xs}` zips
1674                // only `b`. Anything else that is not an object is a `TypeError`.
1675                None | Some(Value::Undefined) => continue,
1676                Some(value) => value,
1677            };
1678            if !matches!(item, Value::Object(_)) {
1679                return Err(interp.type_error("not an object"));
1680            }
1681            records.push(iterator_flattenable(interp, &item, false)?);
1682            pads.push(match &padding {
1683                Some(map) => interp
1684                    .get_property_key(map, &key)?
1685                    .unwrap_or(Value::Undefined),
1686                None => Value::Undefined,
1687            });
1688            // Kept as a `Value` so a symbol key stays a symbol in the result object.
1689            keys.push(match &key {
1690                crate::object::PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
1691                crate::object::PropertyKey::String(text) => interp.string_wtf8(text.clone()),
1692            });
1693        }
1694        Ok(())
1695    })();
1696    if let Err(signal) = outcome {
1697        // Errors from a closing `return` are ignored: the completion is already abrupt.
1698        let _ = close_all_except(interp, &records, usize::MAX);
1699        return Err(signal);
1700    }
1701    finish_zip(interp, KIND_ZIP_KEYED, mode, records, pads, Some(keys))
1702}
1703
1704/// `IteratorClose` for every source except `skip`, in reverse order.
1705///
1706/// Returns the first error raised by a `return`, after finishing the unwind: one source
1707/// refusing to close must not leave the others open.
1708fn close_all_except(
1709    interp: &mut Interp<'_>,
1710    records: &[crate::interp::Iterator],
1711    skip: usize,
1712) -> Option<Signal> {
1713    let mut first_error = None;
1714    for (index, record) in records.iter().enumerate().rev() {
1715        if index == skip {
1716            continue;
1717        }
1718        if let Err(signal) = close(interp, record)
1719            && first_error.is_none()
1720        {
1721            first_error = Some(signal);
1722        }
1723    }
1724    first_error
1725}
1726
1727/// `IteratorClose` for every source after `index`, in reverse order.
1728///
1729/// Reverse because the spec unwinds a partially-built list: the most recently opened
1730/// iterator is the first to be told it will not be read again. Errors are swallowed — the
1731/// completion being propagated is already abrupt, and §7.4.11 step 6 says the original
1732/// error wins.
1733fn close_after(interp: &mut Interp<'_>, records: &[crate::interp::Iterator], index: usize) {
1734    for record in records.iter().skip(index + 1).rev() {
1735        let _ = close(interp, record);
1736    }
1737}
1738
1739fn finish_zip(
1740    interp: &mut Interp<'_>,
1741    kind: i32,
1742    mode: i32,
1743    records: Vec<crate::interp::Iterator>,
1744    pads: Vec<Value>,
1745    keys: Option<Vec<Value>>,
1746) -> JsResult<Value> {
1747    let helper = iterator_object(interp, kind)?;
1748    if let Value::Object(object) = &helper {
1749        let flat = pack_records(&records);
1750        let list = interp.new_array(flat);
1751        write_hidden(object, LIST, Value::Object(list));
1752        write_hidden(object, MODE, Value::Int(mode));
1753        let pads = interp.new_array(pads);
1754        write_hidden(object, PADDING, Value::Object(pads));
1755        if let Some(keys) = keys {
1756            let keys = interp.new_array(keys);
1757            write_hidden(object, KEYS, Value::Object(keys));
1758        }
1759    }
1760    Ok(helper)
1761}
1762
1763/// `options.mode`, read before anything else and validated on the spot.
1764fn zip_mode(interp: &mut Interp<'_>, options: Option<&Value>) -> JsResult<i32> {
1765    let Some(options) = options else {
1766        return Ok(0);
1767    };
1768    if matches!(options, Value::Undefined) {
1769        return Ok(0);
1770    }
1771    let Some(object) = options.as_object().cloned() else {
1772        return Err(interp.type_error("options must be an object"));
1773    };
1774    match interp.get_property(&object, "mode")? {
1775        None | Some(Value::Undefined) => Ok(0),
1776        Some(Value::String(text)) => match text.to_string_lossy().as_ref() {
1777            "shortest" => Ok(0),
1778            "longest" => Ok(1),
1779            "strict" => Ok(2),
1780            _ => Err(interp.type_error("invalid mode")),
1781        },
1782        Some(_) => Err(interp.type_error("invalid mode")),
1783    }
1784}
1785
1786/// `options.padding`, read only in `longest` mode.
1787fn zip_padding_option(interp: &mut Interp<'_>, options: Option<&Value>) -> JsResult<Option<Value>> {
1788    let Some(Value::Object(object)) = options else {
1789        return Ok(None);
1790    };
1791    match interp.get_property(object, "padding")? {
1792        None | Some(Value::Undefined) => Ok(None),
1793        Some(value @ Value::Object(_)) => Ok(Some(value)),
1794        Some(_) => Err(interp.type_error("padding must be an object")),
1795    }
1796}
1797
1798/// Flatten iterator records into a value list so they can live in one array.
1799///
1800/// Each record becomes two adjacent entries, `[object, next]`, which
1801/// [`unpack_records`] reads back.
1802fn pack_records(records: &[crate::interp::Iterator]) -> Vec<Value> {
1803    let mut flat = Vec::with_capacity(records.len() * 2);
1804    for record in records {
1805        flat.push(record.object.clone());
1806        flat.push(record.next.clone());
1807    }
1808    flat
1809}
1810
1811fn unpack_records(
1812    interp: &mut Interp<'_>,
1813    object: &JsObject,
1814) -> JsResult<Vec<crate::interp::Iterator>> {
1815    let list = read_hidden(interp, object, LIST)?;
1816    let Some(array) = list.as_object().cloned() else {
1817        return Ok(Vec::new());
1818    };
1819    let elements = array.array_elements().unwrap_or_default();
1820    let mut records = Vec::with_capacity(elements.len() / 2);
1821    for pair in elements.chunks(2) {
1822        if let [object, next] = pair {
1823            records.push(crate::interp::Iterator {
1824                object: object.clone(),
1825                next: next.clone(),
1826            });
1827        }
1828    }
1829    Ok(records)
1830}
1831
1832/// §27.1.3.1's getter: `"Iterator"`, whatever the receiver is.
1833fn iterator_tag_getter(interp: &mut Interp<'_>, _this: Value, _args: &[Value]) -> JsResult<Value> {
1834    Ok(interp.string("Iterator"))
1835}
1836
1837/// §27.1.3.1's setter: `SetterThatIgnoresPrototypeProperties`.
1838fn iterator_tag_setter(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1839    let Some(home) = interp.realm.iterator_proto.clone() else {
1840        return Err(interp.type_error("Iterator.prototype is not installed"));
1841    };
1842    let key = interp
1843        .realm
1844        .well_known_key(crate::interp::WellKnown::ToStringTag);
1845    interp.setter_that_ignores_prototype_properties_key(this, &home, &key, args)
1846}