quickjs-pure 0.17.40

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
//! `Map` and `Set`.
//!
//! Both are an insertion-ordered list of entries with `SameValueZero` key equality, so one
//! implementation serves both: a `Set` is a `Map` whose value is unused. Keeping a list
//! rather than a hash table is what makes the *order* free and exact — a `Map` iterates in
//! insertion order, and a deleted-then-reinserted key moves to the end — at the cost of
//! linear lookup, which the sizes this engine is used at do not notice.
//!
//! # Why `SameValueZero` and not `===`
//!
//! `map.set(NaN, 1)` then `map.get(NaN)` has to work, and `NaN === NaN` is false. The other
//! difference is that `+0` and `-0` are one key, which `===` already gives.
//!
//! # Iterators
//!
//! `keys`/`values`/`entries` snapshot the entries into an array and hand it to the shared
//! array iterator. The spec makes those iterators *live* — an entry added while iterating is
//! visited — and a snapshot is not. That is a documented simplification: it keeps one
//! iterator implementation in the engine, and no test here distinguishes the two.

use crate::builtins::{arg, define_method, install_species_accessor, method};
use crate::interp::{Interp, JsResult, WellKnown};
use crate::object::{JsObject, Property};
use crate::value::Value;
use js_gc::Gc;

/// `Map.prototype` methods, installed once for both classes.
pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
    install_map(interp, object_proto);
    install_set(interp, object_proto);
}

fn install_map(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
    let proto = interp.new_object(Some(object_proto.clone()));
    let constructor = interp.new_native_constructor("Map", 0, map_constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(proto.clone()), false, false),
    );
    proto.define(
        "constructor",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );
    for (name, length, func) in [
        ("get", 1, get as crate::object::NativeFn),
        ("getOrInsert", 2, get_or_insert),
        ("getOrInsertComputed", 2, get_or_insert_computed),
        ("set", 2, set),
        ("has", 1, has),
        ("delete", 1, delete),
        ("clear", 0, clear),
        ("forEach", 1, for_each),
        ("keys", 0, keys),
        ("values", 0, values),
        ("entries", 0, entries),
    ] {
        define_collection_method(&proto, name, length, func, false, interp);
    }
    install_size(&proto, interp, false);
    // §24.1.3.15: `Map.prototype[Symbol.toStringTag]` — a data property, and the reason
    // `Object.prototype.toString.call(Map.prototype)` is `[object Map]` rather than
    // `[object Object]`. The instance tag came from `_class` and worked; the prototype one
    // had nothing, which is exactly what `Map/prototype/Symbol.toStringTag.js` reads.
    crate::builtins::install_tag(&proto, "Map", interp);
    install_iterable(&proto, interp, true);
    install_species_accessor(&constructor, interp);
    // ES2024 `Map.groupBy`. The `Object` counterpart lives in `object.rs`; this one
    // answers a real `Map` so keys keep their type and `SameValueZero` identity.
    define_method(&constructor, "groupBy", 2, group_by, interp);
    interp.realm.map_proto = Some(proto);
    let global = interp.realm.global.clone();
    global.define(
        "Map",
        Property::with_attributes(Value::Object(constructor), true, false),
    );
}

fn install_set(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
    let proto = interp.new_object(Some(object_proto.clone()));
    let constructor = interp.new_native_constructor("Set", 0, set_constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(proto.clone()), false, false),
    );
    proto.define(
        "constructor",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );
    for (name, length, func) in [
        ("add", 1, add as crate::object::NativeFn),
        ("has", 1, has),
        ("delete", 1, delete),
        ("clear", 0, clear),
        ("forEach", 1, for_each),
        ("values", 0, values),
        ("entries", 0, entries),
    ] {
        define_collection_method(&proto, name, length, func, true, interp);
    }
    // §24.2.3.9: `Set.prototype.keys` **is** `Set.prototype.values` — the same function
    // object, so `Set.prototype.keys === Set.prototype.values` and its `name` is `"values"`
    // (`Set/prototype/keys/keys.js`). Installing a second native would answer the same
    // values and fail the identity.
    if let Some(values_fn) = proto
        .own_property("values")
        .and_then(|property| property.value)
    {
        let value = values_fn.clone();
        if let Value::Object(function) = &values_fn {
            interp.internal_set(function, "_collection_is_set", Value::Bool(true));
        }
        proto.define("keys", Property::with_attributes(value, true, false));
    }
    for (name, length, func) in [
        // The seven ES2025 set methods (§24.2.3.13–.19). All of them take a
        // `SetRecord` — an arbitrary object read through `size`/`has`/`keys` — not just
        // another `Set`, which is why they are not implemented in terms of each other.
        ("union", 1, union as crate::object::NativeFn),
        ("intersection", 1, intersection),
        ("difference", 1, difference),
        ("symmetricDifference", 1, symmetric_difference),
        ("isSubsetOf", 1, is_subset_of),
        ("isSupersetOf", 1, is_superset_of),
        ("isDisjointFrom", 1, is_disjoint_from),
    ] {
        // These seven take a *SetRecord* (any object read through `size`/`has`/`keys`), so
        // the receiver is still checked by `entries_of` alone; what they must not accept is
        // a `Map` on the receiver side, which `define_collection_method` cannot express for
        // them because they are not installed on `Map.prototype` at all.
        define_collection_method(&proto, name, length, func, true, interp);
    }
    install_size(&proto, interp, true);
    crate::builtins::install_tag(&proto, "Set", interp);
    install_iterable(&proto, interp, false);
    install_species_accessor(&constructor, interp);
    // ES2024 `Set.groupBy` (§24.2.2.2). The algorithm is the one `Map.groupBy` uses, which
    // is why this reuses `group_by` rather than wrapping it — the two sections are
    // word-for-word the same and the result is a `Map` from both, so `Set.groupBy(xs, f)`
    // and `Map.groupBy(xs, f)` must agree bucket for bucket.
    //
    // It is on `Set` at all because the proposal's readme gives the pair a home on both
    // constructors: "groupBy" lives next to the collection you hold the *values* in, and
    // which constructor you call determines nothing but discoverability. Missing it here
    // was the same shape as the missing `String.prototype.toLocaleLowerCase`
    // (`docs/test262-status.md` §4.42) — one line in a table, invisible until the surface
    // gate compared property by property.
    define_method(&constructor, "groupBy", 2, group_by, interp);
    interp.realm.set_proto = Some(proto);
    let global = interp.realm.global.clone();
    global.define(
        "Set",
        Property::with_attributes(Value::Object(constructor), true, false),
    );
}

/// `size` is an accessor, so it cannot be assigned and always reflects the entries.
///
/// Installed once per prototype with the flavour stamped on, exactly like the methods: a
/// `Map`'s `size` getter must reject a `Set` receiver and vice versa (§24.1.3.10 /
/// §24.2.3.9 both say `RequireInternalSlot`), and one shared getter cannot know which.
fn install_size(proto: &Gc<JsObject>, interp: &Interp<'_>, is_set: bool) {
    let getter = interp.new_native("get size", 0, size);
    interp.internal_set(&getter, "_collection_is_set", Value::Bool(is_set));
    proto.define(
        "size",
        Property {
            getter: Some(Value::Object(getter)),
            enumerable: false,
            configurable: true,
            ..Property::default()
        },
    );
}

/// `Symbol.iterator`, plus the `Symbol.toStringTag` the tag question needs.
///
/// The default iterator differs by collection, and it is easy to get wrong in a way that
/// looks almost right: a `Map` iterates `[key, value]` pairs (the same as `entries`), but
/// a `Set` iterates its *values*. Wiring both to `entries` made `[...new Set([3])]`
/// produce `[[3, 3]]` — one pair — instead of `[3]`.
fn install_iterable(proto: &Gc<JsObject>, interp: &mut Interp<'_>, is_map: bool) {
    // The identity, not just the behaviour: `Map.prototype[@@iterator]` **is**
    // `Map.prototype.entries` and `Set.prototype[@@iterator]` **is** `Set.prototype.values`
    // — one function object, so `===` holds (`Map/prototype/Symbol.iterator.js`). Building a
    // second native with the same body answers the same results and fails that assertion.
    let name = if is_map { "entries" } else { "values" };
    let Some(iterator_fn) = proto.own_property(name).and_then(|property| property.value) else {
        return;
    };
    let key = interp.realm.well_known_key(WellKnown::Iterator);
    // `{ writable: true, enumerable: false, configurable: true }` — `Property::data` makes
    // every property enumerable, and `Symbol.iterator/prop-desc` reads the flag back.
    proto.define_key(&key, Property::with_attributes(iterator_fn, true, false));
}

/// A collection's entries, named so the signatures below stay readable.
type Entries = Vec<(Value, Value)>;

/// `[[MapData]]` with its positions: `None` is a deleted entry, kept so a running
/// iterator's index still points at the entry it meant.
type Slots = Vec<Option<(Value, Value)>>;

/// The entries of `this`, which must be a `Map` or a `Set`.
fn entries_of(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
    let object = this
        .as_object()
        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
    let entries = object
        .collection_entries()
        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
    Ok((object.clone(), entries))
}

/// [`entries_of`] for the `Map.prototype` methods that must reject a `Set`.
///
/// `Set` and `Map` share one representation here, so `RequireInternalSlot(M, [[MapData]])`
/// has to be checked explicitly — otherwise `Map.prototype.getOrInsert.call(new Set(), …)`
/// silently works on the Set. The two test262 cases that catch this
/// (`getOrInsert{,Computed}/does-not-have-mapdata-internal-slot-set.js`) were passing
/// *vacuously* before the methods existed: `undefined` also throws a `TypeError`.
fn map_entries_of(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
    let (object, entries) = entries_of(interp, this)?;
    if object.collection_is_set() != Some(false) {
        return Err(interp.type_error("method called on a non-map"));
    }
    Ok((object, entries))
}

/// Define a `Map`/`Set` prototype method that must reject the *other* collection.
///
/// `Set` and `Map` share one representation here (`collection_entries` + a `is_set` flag),
/// so `RequireInternalSlot(M, [[MapData]])` cannot be answered from the receiver alone:
/// `Map.prototype.has.call(new Set())` has a perfectly good collection on its hands. The
/// missing fact is **which prototype the method came from**, so it is stamped onto the
/// function object here and read back in [`entries_of_method`].
///
/// A hidden slot rather than a wrapper per method: the shared bodies (`has`, `delete`,
/// `forEach`, `keys`, `values`, `entries`, `size`) are installed on both prototypes, and
/// duplicating each one into a `map_*`/`set_*` pair would be fourteen near-identical stubs.
fn define_collection_method(
    proto: &Gc<JsObject>,
    name: &str,
    length: u32,
    func: crate::object::NativeFn,
    is_set: bool,
    interp: &mut Interp<'_>,
) {
    let value = method(interp, name, length, func).expect("a method");
    if let Value::Object(function) = &value {
        interp.internal_set(function, "_collection_is_set", Value::Bool(is_set));
    }
    proto.define(name, Property::with_attributes(value, true, false));
}

/// [`entries_of`] for a method installed by [`define_collection_method`].
///
/// The expected flavour comes from the *callee*, and is `None` when the function was
/// reached some other way (a bound function, say) — permissive in that case, because the
/// spec's guarantee is about the intrinsic method and guessing would break callers who
/// legitimately borrowed it.
fn entries_of_method(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
    let (object, entries) = entries_of(interp, this)?;
    let expected = interp
        .current_native()
        .and_then(|callee| interp.internal_get(&callee, "_collection_is_set"))
        .map(|value| value.to_boolean());
    match expected {
        Some(expected) if object.collection_is_set() != Some(expected) => {
            let wants = if expected { "Set" } else { "Map" };
            Err(interp.type_error(format!("method called on a non-{wants}")))
        }
        _ => Ok((object, entries)),
    }
}

/// [`entries_of_method`], keeping positions (tombstones included).
///
/// Only `delete` needs this: everything else either reads live entries or rebuilds the
/// collection whole, and a rebuild legitimately discards the tombstones.
fn entries_of_method_slots(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Slots)> {
    let object = this
        .as_object()
        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
    let slots = object
        .collection_slots()
        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
    let expected = interp
        .current_native()
        .and_then(|callee| interp.internal_get(&callee, "_collection_is_set"))
        .map(|value| value.to_boolean());
    match expected {
        Some(expected) if object.collection_is_set() != Some(expected) => {
            let wants = if expected { "Set" } else { "Map" };
            Err(interp.type_error(format!("method called on a non-{wants}")))
        }
        _ => Ok((object.clone(), slots)),
    }
}

fn is_set(interp: &Interp<'_>, this: &Value) -> JsResult<bool> {
    let object = this
        .as_object()
        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
    object
        .collection_is_set()
        .ok_or_else(|| interp.type_error("method called on a non-collection"))
}

/// `new Map(iterable)` / `new Set(iterable)` — §24.1.1.1 and §24.2.1.1.
///
/// The iterable path is the specification's, not a snapshot of it:
///
/// * `Get(map, "set")` (resp. `"add"`) is read **once**, and a non-callable method is a
///   `TypeError` before the iterator is even created;
/// * each entry goes through `Call(set, map, «k, v»)`, so a subclass's override runs —
///   `constructor-from-iterable` counts the calls (`Map/iterable-calls-set`,
///   `Set/set-iterable-calls-add`), and a throwing one propagates;
/// * an abrupt completion anywhere in the loop runs `IteratorClose`
///   (`iterator-close-after-set-failure`), and a `return` that throws does not replace the
///   original error;
/// * a non-object entry is a `TypeError`, again after closing.
fn make_collection(
    interp: &mut Interp<'_>,
    this: &Value,
    args: &[Value],
    is_set_form: bool,
) -> JsResult<Value> {
    let object = match this.as_object() {
        Some(object) => object.clone(),
        None => {
            let proto = if is_set_form {
                interp.realm.set_proto.clone()
            } else {
                interp.realm.map_proto.clone()
            };
            interp.new_object(proto.or(Some(interp.realm.object_proto.clone())))
        }
    };
    object.set_collection(interp.heap, Vec::new(), is_set_form);
    let source = arg(args, 0);
    if !matches!(source, Value::Undefined | Value::Null) {
        let adder_key = if is_set_form { "add" } else { "set" };
        let adder = interp.get_property(&object, adder_key)?;
        let adder = match adder {
            Some(Value::Object(function)) if function.is_callable() => Value::Object(function),
            _ => {
                return Err(interp.type_error(format!("{adder_key} is not a function")));
            }
        };
        let iterator = interp.get_iterator(&source)?;
        loop {
            let step = (|interp: &mut Interp<'_>| -> JsResult<Option<Value>> {
                let (entry, done) = interp.iterator_step(&iterator)?;
                Ok((!done).then_some(entry))
            })(interp);
            let entry = match step {
                Ok(Some(entry)) => entry,
                Ok(None) => break,
                Err(signal) => {
                    let _ = interp.close_iterator(&iterator);
                    return Err(signal);
                }
            };
            let outcome = (|interp: &mut Interp<'_>| -> JsResult<()> {
                if is_set_form {
                    interp.call_value(adder.clone(), Value::Object(object.clone()), vec![entry])?;
                    return Ok(());
                }
                let Some(pair) = entry.as_object().cloned() else {
                    return Err(interp.type_error("iterator value is not an entry object"));
                };
                let key = interp.get_property(&pair, "0")?.unwrap_or(Value::Undefined);
                let value = interp.get_property(&pair, "1")?.unwrap_or(Value::Undefined);
                interp.call_value(
                    adder.clone(),
                    Value::Object(object.clone()),
                    vec![key, value],
                )?;
                Ok(())
            })(interp);
            if let Err(signal) = outcome {
                let _ = interp.close_iterator(&iterator);
                return Err(signal);
            }
        }
    }
    Ok(Value::Object(object))
}

/// Insert or update one key.
/// `-0` becomes `+0` on the way into a collection (§24.1.1.2 `normalize-I-if-zero`).
///
/// Lookup already treated the two as one key (`SameValueZero`), so only *storage* was
/// wrong: `new Set([-0])` iterated `-0`, and `[...new Map([[-0, 1]]).keys()][0]` was `-0`.
/// Silent, and observable through `Object.is`. Found while adding `getOrInsert`, whose
/// test262 cases check exactly this (`returns-value-normalized-zero-key.js`).
fn normalize_key(value: Value) -> Value {
    match value {
        // The float pattern compares with `==`, so this arm catches `-0.0` too — which is
        // the whole point; `Object.is([...new Set([-0])][0], -0)` must be false.
        Value::Float(0.0) => Value::Int(0),
        other => other,
    }
}

fn set_entry(interp: &Interp<'_>, object: &Gc<JsObject>, key: Value) -> JsResult<()> {
    let key = normalize_key(key);
    // The **slots**, not the live entries: a rebuild would compact away the tombstones a
    // running `forEach` or iterator is using as positions. `Set/prototype/forEach/
    // iterates-values-deleted-then-readded` is exactly that: delete `2`, then re-add it,
    // and the re-added entry has to land *after* the walk's current index.
    let mut slots = object.collection_slots().unwrap_or_default();
    let is_set = object.collection_is_set().unwrap_or(false);
    let existing = slots.iter_mut().find_map(|slot| match slot {
        Some((existing, _)) if existing.same_value_zero(&key) => Some(slot),
        _ => None,
    });
    match existing {
        // An existing key keeps its position and only its value changes, which is what
        // makes `map.set(k, 1); map.set(k, 2)` iterate `k` once.
        Some(slot) => {
            if let Some((_, value)) = slot {
                *value = key.clone();
            }
        }
        // Both classes start the value at `undefined`: a `Set` never reads it, and a `Map`
        // overwrites it as soon as the pair is known.
        None => slots.push(Some((key.clone(), Value::Undefined))),
    }
    let _ = interp;
    object.set_collection_slots(interp.heap, slots, is_set);
    Ok(())
}

/// `Map.groupBy(items, callback)` — ES2024 §24.1.2.4.
///
/// Buckets go into a real `Map`, so unlike `Object.groupBy` the keys are *not* coerced
/// to property keys: `1` and `"1"` are different buckets, and an object key stays the
/// object. Grouping order follows first appearance, as does the order inside a bucket.
fn group_by(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    let items = arg(args, 0);
    let callback = arg(args, 1);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("not a function"));
    }
    let proto = interp.realm.map_proto.clone();
    let result = interp.new_object(proto.or(Some(interp.realm.object_proto.clone())));
    result.set_collection(interp.heap, Vec::new(), false);

    let iterator = interp.get_iterator(&items)?;
    let mut index = 0i32;
    loop {
        let (value, done) = interp.iterator_step(&iterator)?;
        if done {
            break;
        }
        let key = interp.call_value(
            callback.clone(),
            Value::Undefined,
            vec![value.clone(), Value::Int(index)],
        )?;
        // One mutable pass over the entries: find the bucket by `SameValueZero`, else
        // start a new one at the end.
        let mut entries = result.collection_entries().unwrap_or_default();
        let slot = entries
            .iter()
            .position(|(existing, _)| existing.same_value_zero(&key));
        let position = match slot {
            Some(position) => position,
            None => {
                let bucket = Value::Object(interp.new_array(Vec::new()));
                entries.push((key, bucket));
                entries.len() - 1
            }
        };
        if let Value::Object(array) = &entries[position].1 {
            let length = array.array_length().unwrap_or(0);
            array.array_set(interp.heap, length, value);
            array.array_set_length(interp.heap, length + 1);
        }
        result.set_collection(interp.heap, entries, false);
        index += 1;
    }
    Ok(Value::Object(result))
}

/// `new Map(iterable)`.
fn map_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // §24.1.1.1 step 1 / §24.2.1.1 step 1: `If NewTarget is undefined, throw a TypeError`.
    if !interp.is_constructing() {
        return Err(interp.type_error("Constructor Map requires 'new'"));
    }
    make_collection(interp, &this, args, false)
}

/// `new Set(iterable)`.
fn set_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    if !interp.is_constructing() {
        return Err(interp.type_error("Constructor Set requires 'new'"));
    }
    make_collection(interp, &this, args, true)
}

fn size(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let (_, entries) = entries_of_method(interp, &this)?;
    Ok(Value::Int(entries.len() as i32))
}

/// `Map.prototype.getOrInsert(key, value)` — the Map upsert proposal.
///
/// Present in the reference, absent here, and invisible in the test262 number because the
/// runner counted the 40 cases as `TypeError` rather than as a missing method.
fn get_or_insert(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (object, mut entries) = map_entries_of(interp, &this)?;
    let key = normalize_key(arg(args, 0));
    if let Some((_, existing)) = entries
        .iter()
        .find(|(candidate, _)| candidate.same_value_zero(&key))
    {
        return Ok(existing.clone());
    }
    let value = arg(args, 1);
    entries.push((key, value.clone()));
    object.set_collection(interp.heap, entries, false);
    Ok(value)
}

/// `Map.prototype.getOrInsertComputed(key, callbackfn)` — the same, with the default made
/// on demand.
///
/// Three orderings matter and each has a test262 case:
///
/// * `IsCallable(callbackfn)` is checked **before** the lookup (step 3 vs step 5), so a
///   non-callable callback throws even when the key is already present;
/// * the key is normalized before it is handed to the callback
///   (`canonical-key-passed-to-callback.js`);
/// * the map is **re-scanned after the call** (step 7), so a callback that sets the key
///   itself has its value overwritten in place rather than the key being appended twice
///   (`overwrites-mutation-from-callbackfn.js`). If the callback throws, nothing was
///   written and the map is unchanged (`check-state-after-callback-fn-throws.js`).
fn get_or_insert_computed(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (object, mut entries) = map_entries_of(interp, &this)?;
    let key = normalize_key(arg(args, 0));
    let callback = arg(args, 1);
    if !matches!(&callback, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("not a function"));
    }
    if let Some((_, existing)) = entries
        .iter()
        .find(|(candidate, _)| candidate.same_value_zero(&key))
    {
        return Ok(existing.clone());
    }
    let value = interp.call_value(callback.clone(), Value::Undefined, vec![key.clone()])?;
    match entries
        .iter_mut()
        .find(|(candidate, _)| candidate.same_value_zero(&key))
    {
        Some((_, slot)) => *slot = value.clone(),
        None => entries.push((key, value.clone())),
    }
    object.set_collection(interp.heap, entries, false);
    Ok(value)
}

fn get(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let key = arg(args, 0);
    let (_, entries) = entries_of_method(interp, &this)?;
    Ok(entries
        .into_iter()
        .find(|(existing, _)| existing.same_value_zero(&key))
        .map(|(_, value)| value)
        .unwrap_or(Value::Undefined))
}

/// §24.1.3.9 `Map.prototype.set`.
///
/// Over the **slots**, like [`set_entry`], so a `forEach` that deletes a key and puts it
/// back sees it again at the new position rather than having the list compacted under its
/// index (`Map/prototype/forEach/iterates-values-deleted-then-readded`).
fn set(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (object, mut slots) = entries_of_method_slots(interp, &this)?;
    let key = normalize_key(arg(args, 0));
    let value = arg(args, 1);
    let existing = slots.iter_mut().find_map(|slot| match slot {
        Some((existing, _)) if existing.same_value_zero(&key) => Some(slot),
        _ => None,
    });
    match existing {
        Some(slot) => {
            if let Some((_, held)) = slot {
                *held = value;
            }
        }
        None => slots.push(Some((key, value))),
    }
    object.set_collection_slots(interp.heap, slots, false);
    Ok(this)
}

/// `set.add(value)`, which answers the set itself.
/// §24.2.3.1 `Set.prototype.add`.
///
/// Goes through [`set_entry`] rather than a `Vec::push` of its own: that is the one place
/// that both normalises `-0` and **appends without compacting** the tombstone list, which a
/// running `forEach` depends on (`Set/prototype/forEach/
/// iterates-values-deleted-then-readded` visits the re-added entry at its new position).
fn add(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (object, _) = entries_of_method(interp, &this)?;
    set_entry(interp, &object, arg(args, 0))?;
    Ok(this)
}

/// A `SetRecord` (§24.2.1.2): the *shape* the set methods accept, not a `Set`.
///
/// `union`/`intersection`/`difference`/`symmetricDifference`/`isSubsetOf`/`isSupersetOf`/
/// `isDisjointFrom` all take "a set-like object", so any object with a numeric `size`, a
/// `has` method and a `keys` method works. That is why they cannot be written in terms of
/// `Set.prototype.has` — the argument need not be a `Set`.
///
/// The reads are *observable and ordered*: `size` first (and it must be a number, else a
/// `TypeError`), then `has`, and `keys` only where the algorithm needs to iterate. Getting
/// the order wrong is visible to a test that logs each access.
struct SetRecord {
    size: f64,
    has: Value,
    /// `keys`, read and validated here even though `difference`/`isSubsetOf` never call it.
    /// `GetSetRecord` (§24.2.1.2) validates all three members up front, so a non-callable
    /// `keys` is a `TypeError` from `difference` too.
    keys: Value,
    /// The object the `has`/`keys` methods were read from, which is their `this`.
    receiver: Value,
}

fn set_record(interp: &mut Interp<'_>, value: &Value) -> JsResult<SetRecord> {
    let Some(object) = value.as_object().cloned() else {
        return Err(interp.type_error("the argument is not a set-like object"));
    };
    let key = interp.property_key(&interp.string("size"))?;
    let size = interp.get_property_key(&object, &key)?;
    let size = match size {
        None | Some(Value::Undefined) => {
            return Err(interp.type_error("the argument has no size property"));
        }
        // §24.2.1.2 step 4: `ToNumber` first, *then* the two refusals. `NaN` is not "0" and
        // a negative `size` is not an empty set — a set-like object whose `size` is either is
        // malformed, and every method must say `TypeError` before reading `has` or `keys`.
        // Both were accepted, which is `size-is-a-number` in all seven methods.
        Some(value) => {
            let number = interp.to_js_number(&value)?;
            if number.is_nan() {
                return Err(interp.type_error("the argument's size is NaN"));
            }
            if number < 0.0 {
                return Err(interp.type_error("the argument's size is negative"));
            }
            number
        }
    };
    let key = interp.property_key(&interp.string("has"))?;
    let has = interp.get_property_key(&object, &key)?;
    let has = match has {
        Some(value) if value.as_object().is_some_and(|object| object.is_callable()) => value,
        _ => return Err(interp.type_error("the argument's has property is not callable")),
    };
    let key = interp.property_key(&interp.string("keys"))?;
    let keys = interp.get_property_key(&object, &key)?;
    let keys = match keys {
        Some(value) if value.as_object().is_some_and(|object| object.is_callable()) => value,
        _ => return Err(interp.type_error("the argument's keys property is not callable")),
    };
    Ok(SetRecord {
        size,
        has,
        keys,
        receiver: Value::Object(object),
    })
}

impl SetRecord {
    /// `SetRecord.has(key)`, which is `[[Call]]` on the user's method.
    fn has(&self, interp: &mut Interp<'_>, key: &Value) -> JsResult<bool> {
        let answer =
            interp.call_value(self.has.clone(), self.receiver.clone(), vec![key.clone()])?;
        Ok(answer.to_boolean())
    }
}

/// The keys a set-like object yields: `record.keys()` then iterate it to exhaustion.
///
/// Only for the methods that have to see *every* key (`union`, `symmetricDifference`). The
/// ones that may stop early (`intersection`, `isSupersetOf`, `isDisjointFrom`) walk
/// incrementally instead — see [`set_record_keys_until`] — because stopping is observable:
/// the iterator's `return` runs, and `isDisjointFrom/set-like-iter-return` counts both
/// `next` and `return` calls.
fn set_record_keys(interp: &mut Interp<'_>, record: &SetRecord) -> JsResult<Vec<Value>> {
    // The receiver, not `undefined`: `keys` is a method on the *argument*, so it needs the
    // argument as `this` — passing `undefined` made `Set.prototype.keys` report "method
    // called on a non-collection" for a perfectly good Set.
    let iterator = interp.call_value(record.keys.clone(), record.receiver.clone(), Vec::new())?;
    // `GetIteratorFromMethod` (§7.4.2), not an `@@iterator` lookup: `keys()` has already
    // answered with the iterator itself.
    let iterator = interp.iterator_from_method(iterator)?;
    let mut out = Vec::new();
    loop {
        let (key, done) = interp.iterator_step(&iterator)?;
        if done {
            return Ok(out);
        }
        out.push(key);
    }
}

/// Walk `record.keys()` one key at a time, letting the caller stop early.
///
/// `visit` returning `false` stops the walk and closes the iterator (§7.4.6), which is the
/// spec's `If …, return …` inside a `ForIn/OfBodyEvaluation`: the abrupt exit runs
/// `IteratorClose`, so the underlying iterator's `return` must be called exactly once.
fn set_record_keys_until(
    interp: &mut Interp<'_>,
    record: &SetRecord,
    mut visit: impl FnMut(&mut Interp<'_>, &Value) -> JsResult<bool>,
) -> JsResult<()> {
    let iterator = interp.call_value(record.keys.clone(), record.receiver.clone(), Vec::new())?;
    let iterator = interp.iterator_from_method(iterator)?;
    loop {
        let (key, done) = interp.iterator_step(&iterator)?;
        if done {
            return Ok(());
        }
        if !visit(interp, &key)? {
            // `IteratorClose` with a normal completion, so an error from `return` *does*
            // propagate — unlike the throwing path, which keeps the original error.
            return interp.close_iterator(&iterator);
        }
    }
}

/// A fresh `Set` holding `keys`, which every "answer with a new set" method needs.
fn set_of(interp: &mut Interp<'_>, keys: Vec<Value>) -> JsResult<Value> {
    let proto = interp.realm.set_proto.clone();
    let object = interp.new_object(proto.or(Some(interp.realm.object_proto.clone())));
    let mut entries: Entries = Vec::with_capacity(keys.len());
    for key in keys {
        // A key that arrived through `keys()` was never normalised — a `Set` built here has
        // to apply the same `-0` → `+0` rule `add` does, or `union` of `[-0]` answers `-0`.
        let key = normalize_key(key);
        if !entries
            .iter()
            .any(|(existing, _)| existing.same_value_zero(&key))
        {
            entries.push((key, Value::Undefined));
        }
    }
    object.set_collection(interp.heap, entries, true);
    Ok(Value::Object(object))
}

/// The receiver as a set's entries, refusing anything that is not one.
fn this_set(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
    if !is_set(interp, this)? {
        return Err(interp.type_error("method called on a non-Set"));
    }
    entries_of(interp, this)
}

/// `SameValueZero` membership over a bare list of keys.
///
/// Separate from [`has_entry`] because three of the seven methods compare *two key lists*
/// (the receiver's keys and what `keys()` yielded), and round-tripping those through
/// `(key, undefined)` pairs to reuse the tuple version was both slower and harder to read.
fn contains_key(keys: &[Value], key: &Value) -> bool {
    keys.iter().any(|existing| existing.same_value_zero(key))
}

fn has_entry(entries: &Entries, key: &Value) -> bool {
    entries
        .iter()
        .any(|(existing, _)| existing.same_value_zero(key))
}

/// Whether the receiver holds `key` **right now**, by `SameValueZero`.
///
/// The seven set methods all interleave with user code, and that code may mutate the
/// receiver. The spec's `SetDataHas(O.[[SetData]], e)` reads the internal slot at the
/// moment it is reached, so a cached snapshot of the receiver's entries is wrong for every
/// method that has already called into `other`: `symmetricDifference`, `difference` and
/// `intersection` each answer differently when the entries are re-read
/// (`set-like-class-mutation`).
fn receiver_has(interp: &Interp<'_>, this: &Value, key: &Value) -> JsResult<bool> {
    let (_, entries) = entries_of(interp, this)?;
    Ok(has_entry(&entries, key))
}

/// `Set.prototype.intersection(other)` — §24.2.3.10.
///
/// The `size` comparison decides **everything observable**, which is why it cannot be
/// folded away as an optimisation:
///
/// * `this.size ≤ other.size` — walk the *receiver* and ask `other.has`. `keys()` is
///   never called, so a set-like object may omit it entirely; the result keeps the
///   receiver's order.
/// * `this.size > other.size` — iterate `other.keys()` and keep what the receiver holds.
///   Now the result keeps *`other`*'s order, and `has` is not called at all.
///
/// `result-order.js` pins both halves, and `set-like-array` makes `keys` throw to prove the
/// first half never touches it.
fn intersection(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (_, _) = this_set(interp, &this)?;
    // §24.2.3.x runs `GetSetRecord(other)` **first**, then re-reads `this`: a set-like
    // object's `size` getter may mutate the receiver, and the algorithm must see that.
    let record = set_record(interp, &arg(args, 0))?;
    let (_, entries) = this_set(interp, &this)?;
    let mut kept = Vec::new();
    if (entries.len() as f64) <= record.size {
        for (key, _) in &entries {
            if record.has(interp, key)? {
                // `SetDataHas` again after the user call: `has` may have deleted `key`.
                if receiver_has(interp, &this, key)? {
                    kept.push(key.clone());
                }
            }
        }
    } else {
        // `keys` order, but each key checked against the *current* receiver.
        set_record_keys_until(interp, &record, |interp, key| {
            if receiver_has(interp, &this, key)? && !contains_key(&kept, key) {
                kept.push(key.clone());
            }
            Ok(true)
        })?;
    }
    set_of(interp, kept)
}

/// `Set.prototype.difference(other)` — §24.2.3.8: receiver keys `other` lacks.
///
/// Also `size`-driven, and *not* the one-sided loop it looks like:
///
/// * `this.size ≤ other.size` — ask `other.has` once per receiver key.
/// * `this.size > other.size` — iterate `other.keys()` and **delete** the hits from a copy
///   of the receiver, so `has` is never called (`difference/set-like-class-mutation` throws
///   from `has` to prove it).
///
/// `keys` is read up front either way (§24.2.1.2 does that), which is why a non-callable
/// `keys` is a `TypeError` even on the first branch.
fn difference(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (_, _) = this_set(interp, &this)?;
    let record = set_record(interp, &arg(args, 0))?;
    let (_, entries) = this_set(interp, &this)?;
    if (entries.len() as f64) <= record.size {
        let mut kept = Vec::new();
        for (key, _) in entries {
            if !record.has(interp, &key)? {
                kept.push(key);
            }
        }
        return set_of(interp, kept);
    }
    let mut kept: Vec<Value> = entries.into_iter().map(|(key, _)| key).collect();
    set_record_keys_until(interp, &record, |_, key| {
        kept.retain(|existing| !existing.same_value_zero(key));
        Ok(true)
    })?;
    set_of(interp, kept)
}

/// `Set.prototype.union(other)` — §24.2.3.17: every key of both, receiver's order first.
fn union(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (_, _) = this_set(interp, &this)?;
    let record = set_record(interp, &arg(args, 0))?;
    let (_, entries) = this_set(interp, &this)?;
    let mut keys: Vec<Value> = entries.into_iter().map(|(key, _)| key).collect();
    for key in set_record_keys(interp, &record)? {
        if !contains_key(&keys, &key) {
            keys.push(key);
        }
    }
    set_of(interp, keys)
}

/// `Set.prototype.symmetricDifference(other)` — §24.2.3.16.
///
/// The shape is "start from the receiver, then toggle each key `other` yields":
///
/// 1. seed the result with the receiver's entries, in the receiver's order;
/// 2. for each key of `other.keys()`: if the receiver holds it *right now*, remove it from
///    the result; otherwise append it.
///
/// Neither `other.has` nor `Set.prototype.add`/`delete` is used — `add-not-called` and
/// `delete-not-called` assert that. And the membership test is against the **live**
/// receiver, not a snapshot: a `next` that deletes `b` and re-adds it makes `b` present, so
/// `b` is *removed* from the result rather than appended
/// (`symmetricDifference/set-like-class-mutation` answers `["a","c","d","e","x"]`).
fn symmetric_difference(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (_, _) = this_set(interp, &this)?;
    let record = set_record(interp, &arg(args, 0))?;
    let (_, entries) = this_set(interp, &this)?;
    let mut kept: Vec<Value> = entries.into_iter().map(|(key, _)| key).collect();
    set_record_keys_until(interp, &record, |interp, key| {
        if receiver_has(interp, &this, key)? {
            kept.retain(|existing| !existing.same_value_zero(key));
        } else if !contains_key(&kept, key) {
            kept.push(key.clone());
        }
        Ok(true)
    })?;
    set_of(interp, kept)
}

/// `Set.prototype.isSubsetOf(other)` — §24.2.3.12: every receiver key is in `other`.
fn is_subset_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (_, _) = this_set(interp, &this)?;
    let record = set_record(interp, &arg(args, 0))?;
    let (_, entries) = this_set(interp, &this)?;
    if (entries.len() as f64) > record.size {
        return Ok(Value::Bool(false));
    }
    for (key, _) in entries {
        // Re-read before each probe and again after it. The order is
        // `Has(O, key)` *after* `has` — so a key `has` deleted is skipped, not asked
        // about, and the answer is still `true`
        // (`isSubsetOf/set-like-class-mutation`: `has("a")` deletes `c`, and `c` must never
        // be passed to `has`).
        if !receiver_has(interp, &this, &key)? {
            continue;
        }
        if !record.has(interp, &key)? {
            return Ok(Value::Bool(false));
        }
    }
    Ok(Value::Bool(true))
}

/// `Set.prototype.isSupersetOf(other)` — §24.2.3.14.
///
/// The size check comes first *and* `keys` is only iterated when it passes, so a set-like
/// object whose `keys` throws still answers `false` for an oversized receiver.
fn is_superset_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (_, _) = this_set(interp, &this)?;
    let record = set_record(interp, &arg(args, 0))?;
    let (_, entries) = this_set(interp, &this)?;
    if (entries.len() as f64) < record.size {
        return Ok(Value::Bool(false));
    }
    let mut answer = true;
    set_record_keys_until(interp, &record, |interp, key| {
        if !receiver_has(interp, &this, key)? {
            answer = false;
            return Ok(false);
        }
        Ok(true)
    })?;
    Ok(Value::Bool(answer))
}

/// `Set.prototype.isDisjointFrom(other)` — §24.2.3.15.
///
/// Like `intersection`, the smaller side drives the probe, and the two directions are not
/// interchangeable: one calls `other.has`, the other iterates `other.keys()`. The
/// receiver is re-read for every probe, so a key `has` just deleted is not asked about
/// again (`isDisjointFrom/set-like-class-mutation`).
fn is_disjoint_from(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (_, _) = this_set(interp, &this)?;
    let record = set_record(interp, &arg(args, 0))?;
    let (_, entries) = this_set(interp, &this)?;
    if entries.len() as f64 <= record.size {
        for (key, _) in &entries {
            // Re-read: the previous `has` call may have removed this key.
            if !receiver_has(interp, &this, key)? {
                continue;
            }
            if record.has(interp, key)? {
                return Ok(Value::Bool(false));
            }
        }
        return Ok(Value::Bool(true));
    }
    let mut answer = true;
    set_record_keys_until(interp, &record, |interp, key| {
        if receiver_has(interp, &this, key)? {
            answer = false;
            return Ok(false);
        }
        Ok(true)
    })?;
    Ok(Value::Bool(answer))
}

fn has(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let key = arg(args, 0);
    let (_, entries) = entries_of_method(interp, &this)?;
    Ok(Value::Bool(
        entries
            .into_iter()
            .any(|(existing, _)| existing.same_value_zero(&key)),
    ))
}

fn delete(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let key = arg(args, 0);
    let (object, mut slots) = entries_of_method_slots(interp, &this)?;
    // `[[MapData]]` is emptied in place, not compacted: a `forEach` or an iterator that is
    // mid-walk holds an index into this list, and shifting the neighbours down would make it
    // skip one (`Map/prototype/forEach/deleted-values-during-foreach`).
    let mut removed = false;
    for slot in slots.iter_mut() {
        if let Some((existing, _)) = slot
            && existing.same_value_zero(&key)
        {
            *slot = None;
            removed = true;
            break;
        }
    }
    let is_set = object.collection_is_set().unwrap_or(false);
    object.set_collection_slots(interp.heap, slots, is_set);
    Ok(Value::Bool(removed))
}

fn clear(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let (object, _) = entries_of_method(interp, &this)?;
    let is_set = object.collection_is_set().unwrap_or(false);
    object.set_collection(interp.heap, Vec::new(), is_set);
    Ok(Value::Undefined)
}

/// `forEach(callback, thisArg)`, called with `(value, key, collection)`.
fn for_each(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let callback = arg(args, 0);
    if !callback
        .as_object()
        .is_some_and(|function| function.is_callable())
    {
        return Err(interp.type_error("forEach needs a callback"));
    }
    let this_arg = arg(args, 1);
    let (object, _) = entries_of_method(interp, &this)?;
    let is_set_form = is_set(interp, &this)?;
    // §24.1.3.6 step 6: `entries` is re-read **every iteration**, and `index` only advances
    // past an entry that is still there. That is what makes the three mutation cases work:
    // an entry appended by the callback is visited, one deleted before its turn is not, and
    // one deleted and re-added is visited again at its new position. A snapshot got all
    // three wrong (`iterates-values-added-after-foreach-begins`,
    // `iterates-values-deleted-then-readded`, `deleted-values-during-foreach`).
    let mut index = 0usize;
    loop {
        let slots = object.collection_slots().unwrap_or_default();
        let Some(slot) = slots.get(index) else {
            break;
        };
        index += 1;
        let Some((key, value)) = slot.clone() else {
            continue;
        };
        let payload = if is_set_form {
            vec![key.clone(), key, this.clone()]
        } else {
            vec![value, key, this.clone()]
        };
        interp.call_value(callback.clone(), this_arg.clone(), payload)?;
    }
    Ok(Value::Undefined)
}

/// What a `Map`/`Set` iterator yields, numbered as §24.1.5.1 numbers it.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CollectionKind {
    /// `entries()` and `[Symbol.iterator]`: a `[key, value]` pair.
    KeyValue = 1,
    /// `keys()`.
    Key = 2,
    /// `values()`.
    Value = 3,
}

/// `CreateMapIterator(map, kind)` / `CreateSetIterator(set, kind)`.
///
/// The three fields are **internal slots**, not properties: `[[IteratedMap]]`,
/// `[[MapNextIndex]]` and `[[MapIterationKind]]`. They have to be invisible, because
/// `iterator.next.call({})` is a `TypeError` (`does-not-have-mapiterator-internal-slots`)
/// and so is `Object.create(iterator).next()` — an inherited copy of the state is not the
/// state (`ArrayIteratorPrototype/next/non-own-slots` checks the same for arrays).
///
/// The iterator is **live**: it holds the collection and an index, and each `next` reads
/// the entries as they stand *now*. That is why `set.add(3)` after a `next()` is visible
/// (`SetIteratorPrototype/next/iteration-mutable`), and why the collection's deleted
/// entries stay as empty slots instead of being compacted away.
fn collection_iterator(
    interp: &mut Interp<'_>,
    this: &Value,
    kind: CollectionKind,
    tag: &str,
) -> JsResult<Value> {
    let (object, _) = entries_of_method(interp, this)?;
    let proto = interp.new_iterator_prototype(tag, collection_iterator_next);
    let iterator = interp.new_object(Some(proto));
    interp.internal_set(&iterator, "_iterated_collection", Value::Object(object));
    interp.internal_set(&iterator, "_iterated_index", Value::Int(0));
    interp.internal_set(&iterator, "_iterated_kind", Value::Int(kind as i32));
    Ok(Value::Object(iterator))
}

/// `%MapIteratorPrototype%.next`, shared by both collections and all three kinds.
fn collection_iterator_next(
    interp: &mut Interp<'_>,
    this: Value,
    _args: &[Value],
) -> JsResult<Value> {
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("next called on an object that is not a Map or Set iterator"));
    };
    let Some(collection) = interp.internal_get(&object, "_iterated_collection") else {
        return Err(interp.type_error("next called on an object that is not a Map or Set iterator"));
    };
    let Some(collection) = collection.as_object().cloned() else {
        // `[[IteratedMap]]` is `undefined` once exhausted; the spec returns `done` there
        // *before* touching `[[MapData]]`, which is what keeps a `set.add()` afterwards
        // from reviving the iterator.
        return interp.iterator_result(Value::Undefined, true);
    };
    let mut index = interp
        .internal_get(&object, "_iterated_index")
        .map(|value| value.to_number() as usize)
        .unwrap_or(0);
    let kind = interp
        .internal_get(&object, "_iterated_kind")
        .map(|value| value.to_number() as i32)
        .unwrap_or(1);
    let is_set_form = collection.collection_is_set().unwrap_or(false);
    let Some(slots) = collection.collection_slots() else {
        return Err(interp.type_error("next called on an object that is not a Map or Set iterator"));
    };
    while let Some(slot) = slots.get(index) {
        index += 1;
        // An empty slot is a deleted entry: the index has moved past it, but nothing is
        // yielded, so the walk continues rather than pairing it with `undefined`.
        let Some((key, value)) = slot else {
            continue;
        };
        interp.internal_set(&object, "_iterated_index", Value::Int(index as i32));
        let result = match kind {
            2 => key.clone(),
            3 => {
                if is_set_form {
                    key.clone()
                } else {
                    value.clone()
                }
            }
            // §24.4.4.4: a `Set`'s `entries` are `[value, value]`, which is what makes
            // `for (const [a, b] of set)` give the same value twice.
            _ => {
                let pair = if is_set_form {
                    vec![key.clone(), key.clone()]
                } else {
                    vec![key.clone(), value.clone()]
                };
                Value::Object(interp.new_array(pair))
            }
        };
        return interp.iterator_result(result, false);
    }
    interp.internal_set(&object, "_iterated_index", Value::Int(index as i32));
    // `Set [[IteratedMap]] to undefined`: sticky exhaustion.
    interp.internal_set(&object, "_iterated_collection", Value::Undefined);
    interp.iterator_result(Value::Undefined, true)
}

/// `%MapIteratorPrototype%` and `%SetIteratorPrototype%` are two different objects, so the
/// tag is decided per receiver rather than per method.
fn collection_iterator_tag<'a>(interp: &Interp<'_>, this: &Value) -> JsResult<&'a str> {
    Ok(if is_set(interp, this)? {
        "Set Iterator"
    } else {
        "Map Iterator"
    })
}

fn keys(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let tag = collection_iterator_tag(interp, &this)?;
    collection_iterator(interp, &this, CollectionKind::Key, tag)
}

fn values(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let tag = collection_iterator_tag(interp, &this)?;
    collection_iterator(interp, &this, CollectionKind::Value, tag)
}

fn entries(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let tag = collection_iterator_tag(interp, &this)?;
    collection_iterator(interp, &this, CollectionKind::KeyValue, tag)
}