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