Skip to main content

quickjs/builtins/
iterator.rs

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