Skip to main content

quickjs/builtins/
map.rs

1//! `Map` and `Set`.
2//!
3//! Both are an insertion-ordered list of entries with `SameValueZero` key equality, so one
4//! implementation serves both: a `Set` is a `Map` whose value is unused. Keeping a list
5//! rather than a hash table is what makes the *order* free and exact — a `Map` iterates in
6//! insertion order, and a deleted-then-reinserted key moves to the end — at the cost of
7//! linear lookup, which the sizes this engine is used at do not notice.
8//!
9//! # Why `SameValueZero` and not `===`
10//!
11//! `map.set(NaN, 1)` then `map.get(NaN)` has to work, and `NaN === NaN` is false. The other
12//! difference is that `+0` and `-0` are one key, which `===` already gives.
13//!
14//! # Iterators
15//!
16//! `keys`/`values`/`entries` snapshot the entries into an array and hand it to the shared
17//! array iterator. The spec makes those iterators *live* — an entry added while iterating is
18//! visited — and a snapshot is not. That is a documented simplification: it keeps one
19//! iterator implementation in the engine, and no test here distinguishes the two.
20
21use crate::builtins::{arg, define_method, install_species_accessor, method};
22use crate::interp::{Interp, JsResult, WellKnown};
23use crate::object::{JsObject, Property};
24use crate::value::Value;
25use js_gc::Gc;
26
27/// `Map.prototype` methods, installed once for both classes.
28pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
29    install_map(interp, object_proto);
30    install_set(interp, object_proto);
31}
32
33fn install_map(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
34    let proto = interp.new_object(Some(object_proto.clone()));
35    let constructor = interp.new_native_constructor("Map", 0, map_constructor);
36    constructor.define(
37        "prototype",
38        Property::with_attributes(Value::Object(proto.clone()), false, false),
39    );
40    proto.define(
41        "constructor",
42        Property::with_attributes(Value::Object(constructor.clone()), true, false),
43    );
44    for (name, length, func) in [
45        ("get", 1, get as crate::object::NativeFn),
46        ("getOrInsert", 2, get_or_insert),
47        ("getOrInsertComputed", 2, get_or_insert_computed),
48        ("set", 2, set),
49        ("has", 1, has),
50        ("delete", 1, delete),
51        ("clear", 0, clear),
52        ("forEach", 1, for_each),
53        ("keys", 0, keys),
54        ("values", 0, values),
55        ("entries", 0, entries),
56    ] {
57        define_collection_method(&proto, name, length, func, false, interp);
58    }
59    install_size(&proto, interp, false);
60    // §24.1.3.15: `Map.prototype[Symbol.toStringTag]` — a data property, and the reason
61    // `Object.prototype.toString.call(Map.prototype)` is `[object Map]` rather than
62    // `[object Object]`. The instance tag came from `_class` and worked; the prototype one
63    // had nothing, which is exactly what `Map/prototype/Symbol.toStringTag.js` reads.
64    crate::builtins::install_tag(&proto, "Map", interp);
65    install_iterable(&proto, interp, true);
66    install_species_accessor(&constructor, interp);
67    // ES2024 `Map.groupBy`. The `Object` counterpart lives in `object.rs`; this one
68    // answers a real `Map` so keys keep their type and `SameValueZero` identity.
69    define_method(&constructor, "groupBy", 2, group_by, interp);
70    interp.realm.map_proto = Some(proto);
71    let global = interp.realm.global.clone();
72    global.define(
73        "Map",
74        Property::with_attributes(Value::Object(constructor), true, false),
75    );
76}
77
78fn install_set(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
79    let proto = interp.new_object(Some(object_proto.clone()));
80    let constructor = interp.new_native_constructor("Set", 0, set_constructor);
81    constructor.define(
82        "prototype",
83        Property::with_attributes(Value::Object(proto.clone()), false, false),
84    );
85    proto.define(
86        "constructor",
87        Property::with_attributes(Value::Object(constructor.clone()), true, false),
88    );
89    for (name, length, func) in [
90        ("add", 1, add as crate::object::NativeFn),
91        ("has", 1, has),
92        ("delete", 1, delete),
93        ("clear", 0, clear),
94        ("forEach", 1, for_each),
95        ("values", 0, values),
96        ("entries", 0, entries),
97    ] {
98        define_collection_method(&proto, name, length, func, true, interp);
99    }
100    // §24.2.3.9: `Set.prototype.keys` **is** `Set.prototype.values` — the same function
101    // object, so `Set.prototype.keys === Set.prototype.values` and its `name` is `"values"`
102    // (`Set/prototype/keys/keys.js`). Installing a second native would answer the same
103    // values and fail the identity.
104    if let Some(values_fn) = proto
105        .own_property("values")
106        .and_then(|property| property.value)
107    {
108        let value = values_fn.clone();
109        if let Value::Object(function) = &values_fn {
110            interp.internal_set(function, "_collection_is_set", Value::Bool(true));
111        }
112        proto.define("keys", Property::with_attributes(value, true, false));
113    }
114    for (name, length, func) in [
115        // The seven ES2025 set methods (§24.2.3.13–.19). All of them take a
116        // `SetRecord` — an arbitrary object read through `size`/`has`/`keys` — not just
117        // another `Set`, which is why they are not implemented in terms of each other.
118        ("union", 1, union as crate::object::NativeFn),
119        ("intersection", 1, intersection),
120        ("difference", 1, difference),
121        ("symmetricDifference", 1, symmetric_difference),
122        ("isSubsetOf", 1, is_subset_of),
123        ("isSupersetOf", 1, is_superset_of),
124        ("isDisjointFrom", 1, is_disjoint_from),
125    ] {
126        // These seven take a *SetRecord* (any object read through `size`/`has`/`keys`), so
127        // the receiver is still checked by `entries_of` alone; what they must not accept is
128        // a `Map` on the receiver side, which `define_collection_method` cannot express for
129        // them because they are not installed on `Map.prototype` at all.
130        define_collection_method(&proto, name, length, func, true, interp);
131    }
132    install_size(&proto, interp, true);
133    crate::builtins::install_tag(&proto, "Set", interp);
134    install_iterable(&proto, interp, false);
135    install_species_accessor(&constructor, interp);
136    // ES2024 `Set.groupBy` (§24.2.2.2). The algorithm is the one `Map.groupBy` uses, which
137    // is why this reuses `group_by` rather than wrapping it — the two sections are
138    // word-for-word the same and the result is a `Map` from both, so `Set.groupBy(xs, f)`
139    // and `Map.groupBy(xs, f)` must agree bucket for bucket.
140    //
141    // It is on `Set` at all because the proposal's readme gives the pair a home on both
142    // constructors: "groupBy" lives next to the collection you hold the *values* in, and
143    // which constructor you call determines nothing but discoverability. Missing it here
144    // was the same shape as the missing `String.prototype.toLocaleLowerCase`
145    // (`docs/test262-status.md` §4.42) — one line in a table, invisible until the surface
146    // gate compared property by property.
147    define_method(&constructor, "groupBy", 2, group_by, interp);
148    interp.realm.set_proto = Some(proto);
149    let global = interp.realm.global.clone();
150    global.define(
151        "Set",
152        Property::with_attributes(Value::Object(constructor), true, false),
153    );
154}
155
156/// `size` is an accessor, so it cannot be assigned and always reflects the entries.
157///
158/// Installed once per prototype with the flavour stamped on, exactly like the methods: a
159/// `Map`'s `size` getter must reject a `Set` receiver and vice versa (§24.1.3.10 /
160/// §24.2.3.9 both say `RequireInternalSlot`), and one shared getter cannot know which.
161fn install_size(proto: &Gc<JsObject>, interp: &Interp<'_>, is_set: bool) {
162    let getter = interp.new_native("get size", 0, size);
163    interp.internal_set(&getter, "_collection_is_set", Value::Bool(is_set));
164    proto.define(
165        "size",
166        Property {
167            getter: Some(Value::Object(getter)),
168            enumerable: false,
169            configurable: true,
170            ..Property::default()
171        },
172    );
173}
174
175/// `Symbol.iterator`, plus the `Symbol.toStringTag` the tag question needs.
176///
177/// The default iterator differs by collection, and it is easy to get wrong in a way that
178/// looks almost right: a `Map` iterates `[key, value]` pairs (the same as `entries`), but
179/// a `Set` iterates its *values*. Wiring both to `entries` made `[...new Set([3])]`
180/// produce `[[3, 3]]` — one pair — instead of `[3]`.
181fn install_iterable(proto: &Gc<JsObject>, interp: &mut Interp<'_>, is_map: bool) {
182    // The identity, not just the behaviour: `Map.prototype[@@iterator]` **is**
183    // `Map.prototype.entries` and `Set.prototype[@@iterator]` **is** `Set.prototype.values`
184    // — one function object, so `===` holds (`Map/prototype/Symbol.iterator.js`). Building a
185    // second native with the same body answers the same results and fails that assertion.
186    let name = if is_map { "entries" } else { "values" };
187    let Some(iterator_fn) = proto.own_property(name).and_then(|property| property.value) else {
188        return;
189    };
190    let key = interp.realm.well_known_key(WellKnown::Iterator);
191    // `{ writable: true, enumerable: false, configurable: true }` — `Property::data` makes
192    // every property enumerable, and `Symbol.iterator/prop-desc` reads the flag back.
193    proto.define_key(&key, Property::with_attributes(iterator_fn, true, false));
194}
195
196/// A collection's entries, named so the signatures below stay readable.
197type Entries = Vec<(Value, Value)>;
198
199/// `[[MapData]]` with its positions: `None` is a deleted entry, kept so a running
200/// iterator's index still points at the entry it meant.
201type Slots = Vec<Option<(Value, Value)>>;
202
203/// The entries of `this`, which must be a `Map` or a `Set`.
204fn entries_of(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
205    let object = this
206        .as_object()
207        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
208    let entries = object
209        .collection_entries()
210        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
211    Ok((object.clone(), entries))
212}
213
214/// [`entries_of`] for the `Map.prototype` methods that must reject a `Set`.
215///
216/// `Set` and `Map` share one representation here, so `RequireInternalSlot(M, [[MapData]])`
217/// has to be checked explicitly — otherwise `Map.prototype.getOrInsert.call(new Set(), …)`
218/// silently works on the Set. The two test262 cases that catch this
219/// (`getOrInsert{,Computed}/does-not-have-mapdata-internal-slot-set.js`) were passing
220/// *vacuously* before the methods existed: `undefined` also throws a `TypeError`.
221fn map_entries_of(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
222    let (object, entries) = entries_of(interp, this)?;
223    if object.collection_is_set() != Some(false) {
224        return Err(interp.type_error("method called on a non-map"));
225    }
226    Ok((object, entries))
227}
228
229/// Define a `Map`/`Set` prototype method that must reject the *other* collection.
230///
231/// `Set` and `Map` share one representation here (`collection_entries` + a `is_set` flag),
232/// so `RequireInternalSlot(M, [[MapData]])` cannot be answered from the receiver alone:
233/// `Map.prototype.has.call(new Set())` has a perfectly good collection on its hands. The
234/// missing fact is **which prototype the method came from**, so it is stamped onto the
235/// function object here and read back in [`entries_of_method`].
236///
237/// A hidden slot rather than a wrapper per method: the shared bodies (`has`, `delete`,
238/// `forEach`, `keys`, `values`, `entries`, `size`) are installed on both prototypes, and
239/// duplicating each one into a `map_*`/`set_*` pair would be fourteen near-identical stubs.
240fn define_collection_method(
241    proto: &Gc<JsObject>,
242    name: &str,
243    length: u32,
244    func: crate::object::NativeFn,
245    is_set: bool,
246    interp: &mut Interp<'_>,
247) {
248    let value = method(interp, name, length, func).expect("a method");
249    if let Value::Object(function) = &value {
250        interp.internal_set(function, "_collection_is_set", Value::Bool(is_set));
251    }
252    proto.define(name, Property::with_attributes(value, true, false));
253}
254
255/// [`entries_of`] for a method installed by [`define_collection_method`].
256///
257/// The expected flavour comes from the *callee*, and is `None` when the function was
258/// reached some other way (a bound function, say) — permissive in that case, because the
259/// spec's guarantee is about the intrinsic method and guessing would break callers who
260/// legitimately borrowed it.
261fn entries_of_method(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
262    let (object, entries) = entries_of(interp, this)?;
263    let expected = interp
264        .current_native()
265        .and_then(|callee| interp.internal_get(&callee, "_collection_is_set"))
266        .map(|value| value.to_boolean());
267    match expected {
268        Some(expected) if object.collection_is_set() != Some(expected) => {
269            let wants = if expected { "Set" } else { "Map" };
270            Err(interp.type_error(format!("method called on a non-{wants}")))
271        }
272        _ => Ok((object, entries)),
273    }
274}
275
276/// [`entries_of_method`], keeping positions (tombstones included).
277///
278/// Only `delete` needs this: everything else either reads live entries or rebuilds the
279/// collection whole, and a rebuild legitimately discards the tombstones.
280fn entries_of_method_slots(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Slots)> {
281    let object = this
282        .as_object()
283        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
284    let slots = object
285        .collection_slots()
286        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
287    let expected = interp
288        .current_native()
289        .and_then(|callee| interp.internal_get(&callee, "_collection_is_set"))
290        .map(|value| value.to_boolean());
291    match expected {
292        Some(expected) if object.collection_is_set() != Some(expected) => {
293            let wants = if expected { "Set" } else { "Map" };
294            Err(interp.type_error(format!("method called on a non-{wants}")))
295        }
296        _ => Ok((object.clone(), slots)),
297    }
298}
299
300fn is_set(interp: &Interp<'_>, this: &Value) -> JsResult<bool> {
301    let object = this
302        .as_object()
303        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
304    object
305        .collection_is_set()
306        .ok_or_else(|| interp.type_error("method called on a non-collection"))
307}
308
309/// `new Map(iterable)` / `new Set(iterable)` — §24.1.1.1 and §24.2.1.1.
310///
311/// The iterable path is the specification's, not a snapshot of it:
312///
313/// * `Get(map, "set")` (resp. `"add"`) is read **once**, and a non-callable method is a
314///   `TypeError` before the iterator is even created;
315/// * each entry goes through `Call(set, map, «k, v»)`, so a subclass's override runs —
316///   `constructor-from-iterable` counts the calls (`Map/iterable-calls-set`,
317///   `Set/set-iterable-calls-add`), and a throwing one propagates;
318/// * an abrupt completion anywhere in the loop runs `IteratorClose`
319///   (`iterator-close-after-set-failure`), and a `return` that throws does not replace the
320///   original error;
321/// * a non-object entry is a `TypeError`, again after closing.
322fn make_collection(
323    interp: &mut Interp<'_>,
324    this: &Value,
325    args: &[Value],
326    is_set_form: bool,
327) -> JsResult<Value> {
328    let object = match this.as_object() {
329        Some(object) => object.clone(),
330        None => {
331            let proto = if is_set_form {
332                interp.realm.set_proto.clone()
333            } else {
334                interp.realm.map_proto.clone()
335            };
336            interp.new_object(proto.or(Some(interp.realm.object_proto.clone())))
337        }
338    };
339    object.set_collection(interp.heap, Vec::new(), is_set_form);
340    let source = arg(args, 0);
341    if !matches!(source, Value::Undefined | Value::Null) {
342        let adder_key = if is_set_form { "add" } else { "set" };
343        let adder = interp.get_property(&object, adder_key)?;
344        let adder = match adder {
345            Some(Value::Object(function)) if function.is_callable() => Value::Object(function),
346            _ => {
347                return Err(interp.type_error(format!("{adder_key} is not a function")));
348            }
349        };
350        let iterator = interp.get_iterator(&source)?;
351        loop {
352            let step = (|interp: &mut Interp<'_>| -> JsResult<Option<Value>> {
353                let (entry, done) = interp.iterator_step(&iterator)?;
354                Ok((!done).then_some(entry))
355            })(interp);
356            let entry = match step {
357                Ok(Some(entry)) => entry,
358                Ok(None) => break,
359                Err(signal) => {
360                    let _ = interp.close_iterator(&iterator);
361                    return Err(signal);
362                }
363            };
364            let outcome = (|interp: &mut Interp<'_>| -> JsResult<()> {
365                if is_set_form {
366                    interp.call_value(adder.clone(), Value::Object(object.clone()), vec![entry])?;
367                    return Ok(());
368                }
369                let Some(pair) = entry.as_object().cloned() else {
370                    return Err(interp.type_error("iterator value is not an entry object"));
371                };
372                let key = interp.get_property(&pair, "0")?.unwrap_or(Value::Undefined);
373                let value = interp.get_property(&pair, "1")?.unwrap_or(Value::Undefined);
374                interp.call_value(
375                    adder.clone(),
376                    Value::Object(object.clone()),
377                    vec![key, value],
378                )?;
379                Ok(())
380            })(interp);
381            if let Err(signal) = outcome {
382                let _ = interp.close_iterator(&iterator);
383                return Err(signal);
384            }
385        }
386    }
387    Ok(Value::Object(object))
388}
389
390/// Insert or update one key.
391/// `-0` becomes `+0` on the way into a collection (§24.1.1.2 `normalize-I-if-zero`).
392///
393/// Lookup already treated the two as one key (`SameValueZero`), so only *storage* was
394/// wrong: `new Set([-0])` iterated `-0`, and `[...new Map([[-0, 1]]).keys()][0]` was `-0`.
395/// Silent, and observable through `Object.is`. Found while adding `getOrInsert`, whose
396/// test262 cases check exactly this (`returns-value-normalized-zero-key.js`).
397fn normalize_key(value: Value) -> Value {
398    match value {
399        // The float pattern compares with `==`, so this arm catches `-0.0` too — which is
400        // the whole point; `Object.is([...new Set([-0])][0], -0)` must be false.
401        Value::Float(0.0) => Value::Int(0),
402        other => other,
403    }
404}
405
406fn set_entry(interp: &Interp<'_>, object: &Gc<JsObject>, key: Value) -> JsResult<()> {
407    let key = normalize_key(key);
408    // The **slots**, not the live entries: a rebuild would compact away the tombstones a
409    // running `forEach` or iterator is using as positions. `Set/prototype/forEach/
410    // iterates-values-deleted-then-readded` is exactly that: delete `2`, then re-add it,
411    // and the re-added entry has to land *after* the walk's current index.
412    let mut slots = object.collection_slots().unwrap_or_default();
413    let is_set = object.collection_is_set().unwrap_or(false);
414    let existing = slots.iter_mut().find_map(|slot| match slot {
415        Some((existing, _)) if existing.same_value_zero(&key) => Some(slot),
416        _ => None,
417    });
418    match existing {
419        // An existing key keeps its position and only its value changes, which is what
420        // makes `map.set(k, 1); map.set(k, 2)` iterate `k` once.
421        Some(slot) => {
422            if let Some((_, value)) = slot {
423                *value = key.clone();
424            }
425        }
426        // Both classes start the value at `undefined`: a `Set` never reads it, and a `Map`
427        // overwrites it as soon as the pair is known.
428        None => slots.push(Some((key.clone(), Value::Undefined))),
429    }
430    let _ = interp;
431    object.set_collection_slots(interp.heap, slots, is_set);
432    Ok(())
433}
434
435/// `Map.groupBy(items, callback)` — ES2024 §24.1.2.4.
436///
437/// Buckets go into a real `Map`, so unlike `Object.groupBy` the keys are *not* coerced
438/// to property keys: `1` and `"1"` are different buckets, and an object key stays the
439/// object. Grouping order follows first appearance, as does the order inside a bucket.
440fn group_by(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
441    let items = arg(args, 0);
442    let callback = arg(args, 1);
443    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
444        return Err(interp.type_error("not a function"));
445    }
446    let proto = interp.realm.map_proto.clone();
447    let result = interp.new_object(proto.or(Some(interp.realm.object_proto.clone())));
448    result.set_collection(interp.heap, Vec::new(), false);
449
450    let iterator = interp.get_iterator(&items)?;
451    let mut index = 0i32;
452    loop {
453        let (value, done) = interp.iterator_step(&iterator)?;
454        if done {
455            break;
456        }
457        let key = interp.call_value(
458            callback.clone(),
459            Value::Undefined,
460            vec![value.clone(), Value::Int(index)],
461        )?;
462        // One mutable pass over the entries: find the bucket by `SameValueZero`, else
463        // start a new one at the end.
464        let mut entries = result.collection_entries().unwrap_or_default();
465        let slot = entries
466            .iter()
467            .position(|(existing, _)| existing.same_value_zero(&key));
468        let position = match slot {
469            Some(position) => position,
470            None => {
471                let bucket = Value::Object(interp.new_array(Vec::new()));
472                entries.push((key, bucket));
473                entries.len() - 1
474            }
475        };
476        if let Value::Object(array) = &entries[position].1 {
477            let length = array.array_length().unwrap_or(0);
478            array.array_set(interp.heap, length, value);
479            array.array_set_length(interp.heap, length + 1);
480        }
481        result.set_collection(interp.heap, entries, false);
482        index += 1;
483    }
484    Ok(Value::Object(result))
485}
486
487/// `new Map(iterable)`.
488fn map_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
489    // §24.1.1.1 step 1 / §24.2.1.1 step 1: `If NewTarget is undefined, throw a TypeError`.
490    if !interp.is_constructing() {
491        return Err(interp.type_error("Constructor Map requires 'new'"));
492    }
493    make_collection(interp, &this, args, false)
494}
495
496/// `new Set(iterable)`.
497fn set_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
498    if !interp.is_constructing() {
499        return Err(interp.type_error("Constructor Set requires 'new'"));
500    }
501    make_collection(interp, &this, args, true)
502}
503
504fn size(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
505    let (_, entries) = entries_of_method(interp, &this)?;
506    Ok(Value::Int(entries.len() as i32))
507}
508
509/// `Map.prototype.getOrInsert(key, value)` — the Map upsert proposal.
510///
511/// Present in the reference, absent here, and invisible in the test262 number because the
512/// runner counted the 40 cases as `TypeError` rather than as a missing method.
513fn get_or_insert(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
514    let (object, mut entries) = map_entries_of(interp, &this)?;
515    let key = normalize_key(arg(args, 0));
516    if let Some((_, existing)) = entries
517        .iter()
518        .find(|(candidate, _)| candidate.same_value_zero(&key))
519    {
520        return Ok(existing.clone());
521    }
522    let value = arg(args, 1);
523    entries.push((key, value.clone()));
524    object.set_collection(interp.heap, entries, false);
525    Ok(value)
526}
527
528/// `Map.prototype.getOrInsertComputed(key, callbackfn)` — the same, with the default made
529/// on demand.
530///
531/// Three orderings matter and each has a test262 case:
532///
533/// * `IsCallable(callbackfn)` is checked **before** the lookup (step 3 vs step 5), so a
534///   non-callable callback throws even when the key is already present;
535/// * the key is normalized before it is handed to the callback
536///   (`canonical-key-passed-to-callback.js`);
537/// * the map is **re-scanned after the call** (step 7), so a callback that sets the key
538///   itself has its value overwritten in place rather than the key being appended twice
539///   (`overwrites-mutation-from-callbackfn.js`). If the callback throws, nothing was
540///   written and the map is unchanged (`check-state-after-callback-fn-throws.js`).
541fn get_or_insert_computed(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
542    let (object, mut entries) = map_entries_of(interp, &this)?;
543    let key = normalize_key(arg(args, 0));
544    let callback = arg(args, 1);
545    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
546        return Err(interp.type_error("not a function"));
547    }
548    if let Some((_, existing)) = entries
549        .iter()
550        .find(|(candidate, _)| candidate.same_value_zero(&key))
551    {
552        return Ok(existing.clone());
553    }
554    let value = interp.call_value(callback.clone(), Value::Undefined, vec![key.clone()])?;
555    match entries
556        .iter_mut()
557        .find(|(candidate, _)| candidate.same_value_zero(&key))
558    {
559        Some((_, slot)) => *slot = value.clone(),
560        None => entries.push((key, value.clone())),
561    }
562    object.set_collection(interp.heap, entries, false);
563    Ok(value)
564}
565
566fn get(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
567    let key = arg(args, 0);
568    let (_, entries) = entries_of_method(interp, &this)?;
569    Ok(entries
570        .into_iter()
571        .find(|(existing, _)| existing.same_value_zero(&key))
572        .map(|(_, value)| value)
573        .unwrap_or(Value::Undefined))
574}
575
576/// §24.1.3.9 `Map.prototype.set`.
577///
578/// Over the **slots**, like [`set_entry`], so a `forEach` that deletes a key and puts it
579/// back sees it again at the new position rather than having the list compacted under its
580/// index (`Map/prototype/forEach/iterates-values-deleted-then-readded`).
581fn set(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
582    let (object, mut slots) = entries_of_method_slots(interp, &this)?;
583    let key = normalize_key(arg(args, 0));
584    let value = arg(args, 1);
585    let existing = slots.iter_mut().find_map(|slot| match slot {
586        Some((existing, _)) if existing.same_value_zero(&key) => Some(slot),
587        _ => None,
588    });
589    match existing {
590        Some(slot) => {
591            if let Some((_, held)) = slot {
592                *held = value;
593            }
594        }
595        None => slots.push(Some((key, value))),
596    }
597    object.set_collection_slots(interp.heap, slots, false);
598    Ok(this)
599}
600
601/// `set.add(value)`, which answers the set itself.
602/// §24.2.3.1 `Set.prototype.add`.
603///
604/// Goes through [`set_entry`] rather than a `Vec::push` of its own: that is the one place
605/// that both normalises `-0` and **appends without compacting** the tombstone list, which a
606/// running `forEach` depends on (`Set/prototype/forEach/
607/// iterates-values-deleted-then-readded` visits the re-added entry at its new position).
608fn add(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
609    let (object, _) = entries_of_method(interp, &this)?;
610    set_entry(interp, &object, arg(args, 0))?;
611    Ok(this)
612}
613
614/// A `SetRecord` (§24.2.1.2): the *shape* the set methods accept, not a `Set`.
615///
616/// `union`/`intersection`/`difference`/`symmetricDifference`/`isSubsetOf`/`isSupersetOf`/
617/// `isDisjointFrom` all take "a set-like object", so any object with a numeric `size`, a
618/// `has` method and a `keys` method works. That is why they cannot be written in terms of
619/// `Set.prototype.has` — the argument need not be a `Set`.
620///
621/// The reads are *observable and ordered*: `size` first (and it must be a number, else a
622/// `TypeError`), then `has`, and `keys` only where the algorithm needs to iterate. Getting
623/// the order wrong is visible to a test that logs each access.
624struct SetRecord {
625    size: f64,
626    has: Value,
627    /// `keys`, read and validated here even though `difference`/`isSubsetOf` never call it.
628    /// `GetSetRecord` (§24.2.1.2) validates all three members up front, so a non-callable
629    /// `keys` is a `TypeError` from `difference` too.
630    keys: Value,
631    /// The object the `has`/`keys` methods were read from, which is their `this`.
632    receiver: Value,
633}
634
635fn set_record(interp: &mut Interp<'_>, value: &Value) -> JsResult<SetRecord> {
636    let Some(object) = value.as_object().cloned() else {
637        return Err(interp.type_error("the argument is not a set-like object"));
638    };
639    let key = interp.property_key(&interp.string("size"))?;
640    let size = interp.get_property_key(&object, &key)?;
641    let size = match size {
642        None | Some(Value::Undefined) => {
643            return Err(interp.type_error("the argument has no size property"));
644        }
645        // §24.2.1.2 step 4: `ToNumber` first, *then* the two refusals. `NaN` is not "0" and
646        // a negative `size` is not an empty set — a set-like object whose `size` is either is
647        // malformed, and every method must say `TypeError` before reading `has` or `keys`.
648        // Both were accepted, which is `size-is-a-number` in all seven methods.
649        Some(value) => {
650            let number = interp.to_js_number(&value)?;
651            if number.is_nan() {
652                return Err(interp.type_error("the argument's size is NaN"));
653            }
654            if number < 0.0 {
655                return Err(interp.type_error("the argument's size is negative"));
656            }
657            number
658        }
659    };
660    let key = interp.property_key(&interp.string("has"))?;
661    let has = interp.get_property_key(&object, &key)?;
662    let has = match has {
663        Some(value) if value.as_object().is_some_and(|object| object.is_callable()) => value,
664        _ => return Err(interp.type_error("the argument's has property is not callable")),
665    };
666    let key = interp.property_key(&interp.string("keys"))?;
667    let keys = interp.get_property_key(&object, &key)?;
668    let keys = match keys {
669        Some(value) if value.as_object().is_some_and(|object| object.is_callable()) => value,
670        _ => return Err(interp.type_error("the argument's keys property is not callable")),
671    };
672    Ok(SetRecord {
673        size,
674        has,
675        keys,
676        receiver: Value::Object(object),
677    })
678}
679
680impl SetRecord {
681    /// `SetRecord.has(key)`, which is `[[Call]]` on the user's method.
682    fn has(&self, interp: &mut Interp<'_>, key: &Value) -> JsResult<bool> {
683        let answer =
684            interp.call_value(self.has.clone(), self.receiver.clone(), vec![key.clone()])?;
685        Ok(answer.to_boolean())
686    }
687}
688
689/// The keys a set-like object yields: `record.keys()` then iterate it to exhaustion.
690///
691/// Only for the methods that have to see *every* key (`union`, `symmetricDifference`). The
692/// ones that may stop early (`intersection`, `isSupersetOf`, `isDisjointFrom`) walk
693/// incrementally instead — see [`set_record_keys_until`] — because stopping is observable:
694/// the iterator's `return` runs, and `isDisjointFrom/set-like-iter-return` counts both
695/// `next` and `return` calls.
696fn set_record_keys(interp: &mut Interp<'_>, record: &SetRecord) -> JsResult<Vec<Value>> {
697    // The receiver, not `undefined`: `keys` is a method on the *argument*, so it needs the
698    // argument as `this` — passing `undefined` made `Set.prototype.keys` report "method
699    // called on a non-collection" for a perfectly good Set.
700    let iterator = interp.call_value(record.keys.clone(), record.receiver.clone(), Vec::new())?;
701    // `GetIteratorFromMethod` (§7.4.2), not an `@@iterator` lookup: `keys()` has already
702    // answered with the iterator itself.
703    let iterator = interp.iterator_from_method(iterator)?;
704    let mut out = Vec::new();
705    loop {
706        let (key, done) = interp.iterator_step(&iterator)?;
707        if done {
708            return Ok(out);
709        }
710        out.push(key);
711    }
712}
713
714/// Walk `record.keys()` one key at a time, letting the caller stop early.
715///
716/// `visit` returning `false` stops the walk and closes the iterator (§7.4.6), which is the
717/// spec's `If …, return …` inside a `ForIn/OfBodyEvaluation`: the abrupt exit runs
718/// `IteratorClose`, so the underlying iterator's `return` must be called exactly once.
719fn set_record_keys_until(
720    interp: &mut Interp<'_>,
721    record: &SetRecord,
722    mut visit: impl FnMut(&mut Interp<'_>, &Value) -> JsResult<bool>,
723) -> JsResult<()> {
724    let iterator = interp.call_value(record.keys.clone(), record.receiver.clone(), Vec::new())?;
725    let iterator = interp.iterator_from_method(iterator)?;
726    loop {
727        let (key, done) = interp.iterator_step(&iterator)?;
728        if done {
729            return Ok(());
730        }
731        if !visit(interp, &key)? {
732            // `IteratorClose` with a normal completion, so an error from `return` *does*
733            // propagate — unlike the throwing path, which keeps the original error.
734            return interp.close_iterator(&iterator);
735        }
736    }
737}
738
739/// A fresh `Set` holding `keys`, which every "answer with a new set" method needs.
740fn set_of(interp: &mut Interp<'_>, keys: Vec<Value>) -> JsResult<Value> {
741    let proto = interp.realm.set_proto.clone();
742    let object = interp.new_object(proto.or(Some(interp.realm.object_proto.clone())));
743    let mut entries: Entries = Vec::with_capacity(keys.len());
744    for key in keys {
745        // A key that arrived through `keys()` was never normalised — a `Set` built here has
746        // to apply the same `-0` → `+0` rule `add` does, or `union` of `[-0]` answers `-0`.
747        let key = normalize_key(key);
748        if !entries
749            .iter()
750            .any(|(existing, _)| existing.same_value_zero(&key))
751        {
752            entries.push((key, Value::Undefined));
753        }
754    }
755    object.set_collection(interp.heap, entries, true);
756    Ok(Value::Object(object))
757}
758
759/// The receiver as a set's entries, refusing anything that is not one.
760fn this_set(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
761    if !is_set(interp, this)? {
762        return Err(interp.type_error("method called on a non-Set"));
763    }
764    entries_of(interp, this)
765}
766
767/// `SameValueZero` membership over a bare list of keys.
768///
769/// Separate from [`has_entry`] because three of the seven methods compare *two key lists*
770/// (the receiver's keys and what `keys()` yielded), and round-tripping those through
771/// `(key, undefined)` pairs to reuse the tuple version was both slower and harder to read.
772fn contains_key(keys: &[Value], key: &Value) -> bool {
773    keys.iter().any(|existing| existing.same_value_zero(key))
774}
775
776fn has_entry(entries: &Entries, key: &Value) -> bool {
777    entries
778        .iter()
779        .any(|(existing, _)| existing.same_value_zero(key))
780}
781
782/// Whether the receiver holds `key` **right now**, by `SameValueZero`.
783///
784/// The seven set methods all interleave with user code, and that code may mutate the
785/// receiver. The spec's `SetDataHas(O.[[SetData]], e)` reads the internal slot at the
786/// moment it is reached, so a cached snapshot of the receiver's entries is wrong for every
787/// method that has already called into `other`: `symmetricDifference`, `difference` and
788/// `intersection` each answer differently when the entries are re-read
789/// (`set-like-class-mutation`).
790fn receiver_has(interp: &Interp<'_>, this: &Value, key: &Value) -> JsResult<bool> {
791    let (_, entries) = entries_of(interp, this)?;
792    Ok(has_entry(&entries, key))
793}
794
795/// `Set.prototype.intersection(other)` — §24.2.3.10.
796///
797/// The `size` comparison decides **everything observable**, which is why it cannot be
798/// folded away as an optimisation:
799///
800/// * `this.size ≤ other.size` — walk the *receiver* and ask `other.has`. `keys()` is
801///   never called, so a set-like object may omit it entirely; the result keeps the
802///   receiver's order.
803/// * `this.size > other.size` — iterate `other.keys()` and keep what the receiver holds.
804///   Now the result keeps *`other`*'s order, and `has` is not called at all.
805///
806/// `result-order.js` pins both halves, and `set-like-array` makes `keys` throw to prove the
807/// first half never touches it.
808fn intersection(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
809    let (_, _) = this_set(interp, &this)?;
810    // §24.2.3.x runs `GetSetRecord(other)` **first**, then re-reads `this`: a set-like
811    // object's `size` getter may mutate the receiver, and the algorithm must see that.
812    let record = set_record(interp, &arg(args, 0))?;
813    let (_, entries) = this_set(interp, &this)?;
814    let mut kept = Vec::new();
815    if (entries.len() as f64) <= record.size {
816        for (key, _) in &entries {
817            if record.has(interp, key)? {
818                // `SetDataHas` again after the user call: `has` may have deleted `key`.
819                if receiver_has(interp, &this, key)? {
820                    kept.push(key.clone());
821                }
822            }
823        }
824    } else {
825        // `keys` order, but each key checked against the *current* receiver.
826        set_record_keys_until(interp, &record, |interp, key| {
827            if receiver_has(interp, &this, key)? && !contains_key(&kept, key) {
828                kept.push(key.clone());
829            }
830            Ok(true)
831        })?;
832    }
833    set_of(interp, kept)
834}
835
836/// `Set.prototype.difference(other)` — §24.2.3.8: receiver keys `other` lacks.
837///
838/// Also `size`-driven, and *not* the one-sided loop it looks like:
839///
840/// * `this.size ≤ other.size` — ask `other.has` once per receiver key.
841/// * `this.size > other.size` — iterate `other.keys()` and **delete** the hits from a copy
842///   of the receiver, so `has` is never called (`difference/set-like-class-mutation` throws
843///   from `has` to prove it).
844///
845/// `keys` is read up front either way (§24.2.1.2 does that), which is why a non-callable
846/// `keys` is a `TypeError` even on the first branch.
847fn difference(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
848    let (_, _) = this_set(interp, &this)?;
849    let record = set_record(interp, &arg(args, 0))?;
850    let (_, entries) = this_set(interp, &this)?;
851    if (entries.len() as f64) <= record.size {
852        let mut kept = Vec::new();
853        for (key, _) in entries {
854            if !record.has(interp, &key)? {
855                kept.push(key);
856            }
857        }
858        return set_of(interp, kept);
859    }
860    let mut kept: Vec<Value> = entries.into_iter().map(|(key, _)| key).collect();
861    set_record_keys_until(interp, &record, |_, key| {
862        kept.retain(|existing| !existing.same_value_zero(key));
863        Ok(true)
864    })?;
865    set_of(interp, kept)
866}
867
868/// `Set.prototype.union(other)` — §24.2.3.17: every key of both, receiver's order first.
869fn union(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
870    let (_, _) = this_set(interp, &this)?;
871    let record = set_record(interp, &arg(args, 0))?;
872    let (_, entries) = this_set(interp, &this)?;
873    let mut keys: Vec<Value> = entries.into_iter().map(|(key, _)| key).collect();
874    for key in set_record_keys(interp, &record)? {
875        if !contains_key(&keys, &key) {
876            keys.push(key);
877        }
878    }
879    set_of(interp, keys)
880}
881
882/// `Set.prototype.symmetricDifference(other)` — §24.2.3.16.
883///
884/// The shape is "start from the receiver, then toggle each key `other` yields":
885///
886/// 1. seed the result with the receiver's entries, in the receiver's order;
887/// 2. for each key of `other.keys()`: if the receiver holds it *right now*, remove it from
888///    the result; otherwise append it.
889///
890/// Neither `other.has` nor `Set.prototype.add`/`delete` is used — `add-not-called` and
891/// `delete-not-called` assert that. And the membership test is against the **live**
892/// receiver, not a snapshot: a `next` that deletes `b` and re-adds it makes `b` present, so
893/// `b` is *removed* from the result rather than appended
894/// (`symmetricDifference/set-like-class-mutation` answers `["a","c","d","e","x"]`).
895fn symmetric_difference(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
896    let (_, _) = this_set(interp, &this)?;
897    let record = set_record(interp, &arg(args, 0))?;
898    let (_, entries) = this_set(interp, &this)?;
899    let mut kept: Vec<Value> = entries.into_iter().map(|(key, _)| key).collect();
900    set_record_keys_until(interp, &record, |interp, key| {
901        if receiver_has(interp, &this, key)? {
902            kept.retain(|existing| !existing.same_value_zero(key));
903        } else if !contains_key(&kept, key) {
904            kept.push(key.clone());
905        }
906        Ok(true)
907    })?;
908    set_of(interp, kept)
909}
910
911/// `Set.prototype.isSubsetOf(other)` — §24.2.3.12: every receiver key is in `other`.
912fn is_subset_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
913    let (_, _) = this_set(interp, &this)?;
914    let record = set_record(interp, &arg(args, 0))?;
915    let (_, entries) = this_set(interp, &this)?;
916    if (entries.len() as f64) > record.size {
917        return Ok(Value::Bool(false));
918    }
919    for (key, _) in entries {
920        // Re-read before each probe and again after it. The order is
921        // `Has(O, key)` *after* `has` — so a key `has` deleted is skipped, not asked
922        // about, and the answer is still `true`
923        // (`isSubsetOf/set-like-class-mutation`: `has("a")` deletes `c`, and `c` must never
924        // be passed to `has`).
925        if !receiver_has(interp, &this, &key)? {
926            continue;
927        }
928        if !record.has(interp, &key)? {
929            return Ok(Value::Bool(false));
930        }
931    }
932    Ok(Value::Bool(true))
933}
934
935/// `Set.prototype.isSupersetOf(other)` — §24.2.3.14.
936///
937/// The size check comes first *and* `keys` is only iterated when it passes, so a set-like
938/// object whose `keys` throws still answers `false` for an oversized receiver.
939fn is_superset_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
940    let (_, _) = this_set(interp, &this)?;
941    let record = set_record(interp, &arg(args, 0))?;
942    let (_, entries) = this_set(interp, &this)?;
943    if (entries.len() as f64) < record.size {
944        return Ok(Value::Bool(false));
945    }
946    let mut answer = true;
947    set_record_keys_until(interp, &record, |interp, key| {
948        if !receiver_has(interp, &this, key)? {
949            answer = false;
950            return Ok(false);
951        }
952        Ok(true)
953    })?;
954    Ok(Value::Bool(answer))
955}
956
957/// `Set.prototype.isDisjointFrom(other)` — §24.2.3.15.
958///
959/// Like `intersection`, the smaller side drives the probe, and the two directions are not
960/// interchangeable: one calls `other.has`, the other iterates `other.keys()`. The
961/// receiver is re-read for every probe, so a key `has` just deleted is not asked about
962/// again (`isDisjointFrom/set-like-class-mutation`).
963fn is_disjoint_from(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
964    let (_, _) = this_set(interp, &this)?;
965    let record = set_record(interp, &arg(args, 0))?;
966    let (_, entries) = this_set(interp, &this)?;
967    if entries.len() as f64 <= record.size {
968        for (key, _) in &entries {
969            // Re-read: the previous `has` call may have removed this key.
970            if !receiver_has(interp, &this, key)? {
971                continue;
972            }
973            if record.has(interp, key)? {
974                return Ok(Value::Bool(false));
975            }
976        }
977        return Ok(Value::Bool(true));
978    }
979    let mut answer = true;
980    set_record_keys_until(interp, &record, |interp, key| {
981        if receiver_has(interp, &this, key)? {
982            answer = false;
983            return Ok(false);
984        }
985        Ok(true)
986    })?;
987    Ok(Value::Bool(answer))
988}
989
990fn has(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
991    let key = arg(args, 0);
992    let (_, entries) = entries_of_method(interp, &this)?;
993    Ok(Value::Bool(
994        entries
995            .into_iter()
996            .any(|(existing, _)| existing.same_value_zero(&key)),
997    ))
998}
999
1000fn delete(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1001    let key = arg(args, 0);
1002    let (object, mut slots) = entries_of_method_slots(interp, &this)?;
1003    // `[[MapData]]` is emptied in place, not compacted: a `forEach` or an iterator that is
1004    // mid-walk holds an index into this list, and shifting the neighbours down would make it
1005    // skip one (`Map/prototype/forEach/deleted-values-during-foreach`).
1006    let mut removed = false;
1007    for slot in slots.iter_mut() {
1008        if let Some((existing, _)) = slot
1009            && existing.same_value_zero(&key)
1010        {
1011            *slot = None;
1012            removed = true;
1013            break;
1014        }
1015    }
1016    let is_set = object.collection_is_set().unwrap_or(false);
1017    object.set_collection_slots(interp.heap, slots, is_set);
1018    Ok(Value::Bool(removed))
1019}
1020
1021fn clear(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1022    let (object, _) = entries_of_method(interp, &this)?;
1023    let is_set = object.collection_is_set().unwrap_or(false);
1024    object.set_collection(interp.heap, Vec::new(), is_set);
1025    Ok(Value::Undefined)
1026}
1027
1028/// `forEach(callback, thisArg)`, called with `(value, key, collection)`.
1029fn for_each(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
1030    let callback = arg(args, 0);
1031    if !callback
1032        .as_object()
1033        .is_some_and(|function| function.is_callable())
1034    {
1035        return Err(interp.type_error("forEach needs a callback"));
1036    }
1037    let this_arg = arg(args, 1);
1038    let (object, _) = entries_of_method(interp, &this)?;
1039    let is_set_form = is_set(interp, &this)?;
1040    // §24.1.3.6 step 6: `entries` is re-read **every iteration**, and `index` only advances
1041    // past an entry that is still there. That is what makes the three mutation cases work:
1042    // an entry appended by the callback is visited, one deleted before its turn is not, and
1043    // one deleted and re-added is visited again at its new position. A snapshot got all
1044    // three wrong (`iterates-values-added-after-foreach-begins`,
1045    // `iterates-values-deleted-then-readded`, `deleted-values-during-foreach`).
1046    let mut index = 0usize;
1047    loop {
1048        let slots = object.collection_slots().unwrap_or_default();
1049        let Some(slot) = slots.get(index) else {
1050            break;
1051        };
1052        index += 1;
1053        let Some((key, value)) = slot.clone() else {
1054            continue;
1055        };
1056        let payload = if is_set_form {
1057            vec![key.clone(), key, this.clone()]
1058        } else {
1059            vec![value, key, this.clone()]
1060        };
1061        interp.call_value(callback.clone(), this_arg.clone(), payload)?;
1062    }
1063    Ok(Value::Undefined)
1064}
1065
1066/// What a `Map`/`Set` iterator yields, numbered as §24.1.5.1 numbers it.
1067#[derive(Clone, Copy, PartialEq, Eq)]
1068enum CollectionKind {
1069    /// `entries()` and `[Symbol.iterator]`: a `[key, value]` pair.
1070    KeyValue = 1,
1071    /// `keys()`.
1072    Key = 2,
1073    /// `values()`.
1074    Value = 3,
1075}
1076
1077/// `CreateMapIterator(map, kind)` / `CreateSetIterator(set, kind)`.
1078///
1079/// The three fields are **internal slots**, not properties: `[[IteratedMap]]`,
1080/// `[[MapNextIndex]]` and `[[MapIterationKind]]`. They have to be invisible, because
1081/// `iterator.next.call({})` is a `TypeError` (`does-not-have-mapiterator-internal-slots`)
1082/// and so is `Object.create(iterator).next()` — an inherited copy of the state is not the
1083/// state (`ArrayIteratorPrototype/next/non-own-slots` checks the same for arrays).
1084///
1085/// The iterator is **live**: it holds the collection and an index, and each `next` reads
1086/// the entries as they stand *now*. That is why `set.add(3)` after a `next()` is visible
1087/// (`SetIteratorPrototype/next/iteration-mutable`), and why the collection's deleted
1088/// entries stay as empty slots instead of being compacted away.
1089fn collection_iterator(
1090    interp: &mut Interp<'_>,
1091    this: &Value,
1092    kind: CollectionKind,
1093    tag: &str,
1094) -> JsResult<Value> {
1095    let (object, _) = entries_of_method(interp, this)?;
1096    let proto = interp.new_iterator_prototype(tag, collection_iterator_next);
1097    let iterator = interp.new_object(Some(proto));
1098    interp.internal_set(&iterator, "_iterated_collection", Value::Object(object));
1099    interp.internal_set(&iterator, "_iterated_index", Value::Int(0));
1100    interp.internal_set(&iterator, "_iterated_kind", Value::Int(kind as i32));
1101    Ok(Value::Object(iterator))
1102}
1103
1104/// `%MapIteratorPrototype%.next`, shared by both collections and all three kinds.
1105fn collection_iterator_next(
1106    interp: &mut Interp<'_>,
1107    this: Value,
1108    _args: &[Value],
1109) -> JsResult<Value> {
1110    let Some(object) = this.as_object().cloned() else {
1111        return Err(interp.type_error("next called on an object that is not a Map or Set iterator"));
1112    };
1113    let Some(collection) = interp.internal_get(&object, "_iterated_collection") else {
1114        return Err(interp.type_error("next called on an object that is not a Map or Set iterator"));
1115    };
1116    let Some(collection) = collection.as_object().cloned() else {
1117        // `[[IteratedMap]]` is `undefined` once exhausted; the spec returns `done` there
1118        // *before* touching `[[MapData]]`, which is what keeps a `set.add()` afterwards
1119        // from reviving the iterator.
1120        return interp.iterator_result(Value::Undefined, true);
1121    };
1122    let mut index = interp
1123        .internal_get(&object, "_iterated_index")
1124        .map(|value| value.to_number() as usize)
1125        .unwrap_or(0);
1126    let kind = interp
1127        .internal_get(&object, "_iterated_kind")
1128        .map(|value| value.to_number() as i32)
1129        .unwrap_or(1);
1130    let is_set_form = collection.collection_is_set().unwrap_or(false);
1131    let Some(slots) = collection.collection_slots() else {
1132        return Err(interp.type_error("next called on an object that is not a Map or Set iterator"));
1133    };
1134    while let Some(slot) = slots.get(index) {
1135        index += 1;
1136        // An empty slot is a deleted entry: the index has moved past it, but nothing is
1137        // yielded, so the walk continues rather than pairing it with `undefined`.
1138        let Some((key, value)) = slot else {
1139            continue;
1140        };
1141        interp.internal_set(&object, "_iterated_index", Value::Int(index as i32));
1142        let result = match kind {
1143            2 => key.clone(),
1144            3 => {
1145                if is_set_form {
1146                    key.clone()
1147                } else {
1148                    value.clone()
1149                }
1150            }
1151            // §24.4.4.4: a `Set`'s `entries` are `[value, value]`, which is what makes
1152            // `for (const [a, b] of set)` give the same value twice.
1153            _ => {
1154                let pair = if is_set_form {
1155                    vec![key.clone(), key.clone()]
1156                } else {
1157                    vec![key.clone(), value.clone()]
1158                };
1159                Value::Object(interp.new_array(pair))
1160            }
1161        };
1162        return interp.iterator_result(result, false);
1163    }
1164    interp.internal_set(&object, "_iterated_index", Value::Int(index as i32));
1165    // `Set [[IteratedMap]] to undefined`: sticky exhaustion.
1166    interp.internal_set(&object, "_iterated_collection", Value::Undefined);
1167    interp.iterator_result(Value::Undefined, true)
1168}
1169
1170/// `%MapIteratorPrototype%` and `%SetIteratorPrototype%` are two different objects, so the
1171/// tag is decided per receiver rather than per method.
1172fn collection_iterator_tag<'a>(interp: &Interp<'_>, this: &Value) -> JsResult<&'a str> {
1173    Ok(if is_set(interp, this)? {
1174        "Set Iterator"
1175    } else {
1176        "Map Iterator"
1177    })
1178}
1179
1180fn keys(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1181    let tag = collection_iterator_tag(interp, &this)?;
1182    collection_iterator(interp, &this, CollectionKind::Key, tag)
1183}
1184
1185fn values(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1186    let tag = collection_iterator_tag(interp, &this)?;
1187    collection_iterator(interp, &this, CollectionKind::Value, tag)
1188}
1189
1190fn entries(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
1191    let tag = collection_iterator_tag(interp, &this)?;
1192    collection_iterator(interp, &this, CollectionKind::KeyValue, tag)
1193}