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