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