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