quickjs-pure 0.16.8

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
//! `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::array::{IteratorKind, iterator};
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),
        ("keys", 0, keys),
        ("values", 0, values),
        ("entries", 0, entries),
    ] {
        define_collection_method(&proto, name, length, func, true, interp);
    }
    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) {
    let func = if is_map {
        entries as crate::object::NativeFn
    } else {
        values
    };
    let iterator_fn = method(interp, "[Symbol.iterator]", 0, func).expect("a method");
    let key = interp.realm.well_known_key(WellKnown::Iterator);
    proto.define_key(&key, Property::data(iterator_fn));
}

/// A collection's entries, named so the signatures below stay readable.
type Entries = Vec<(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)),
    }
}

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"))
}

/// Build a `Map` or a `Set`, filling it from an iterable argument.
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) {
        for entry in interp.array_like_to_args(&source)? {
            if is_set_form {
                set_entry(interp, &object, entry)?;
            } else {
                // A `Map` source yields `[key, value]` pairs.
                let pair = interp.array_like_to_args(&entry)?;
                set_entry(interp, &object, arg(&pair, 0))?;
                if let Some(object) = this.as_object() {
                    let mut entries = object.collection_entries().unwrap_or_default();
                    if let Some(last) = entries.last_mut() {
                        last.1 = arg(&pair, 1);
                    }
                    object.set_collection(interp.heap, entries, false);
                }
            }
        }
    }
    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);
    let mut entries = object.collection_entries().unwrap_or_default();
    let is_set = object.collection_is_set().unwrap_or(false);
    match entries
        .iter_mut()
        .find(|(existing, _)| existing.same_value_zero(&key))
    {
        // 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((_, value)) => *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 => entries.push((key.clone(), Value::Undefined)),
    }
    let _ = (interp, is_set);
    object.set_collection(interp.heap, entries, 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> {
    make_collection(interp, &this, args, false)
}

/// `new Set(iterable)`.
fn set_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    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))
}

fn set(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (object, mut entries) = entries_of_method(interp, &this)?;
    let key = normalize_key(arg(args, 0));
    let value = arg(args, 1);
    match entries
        .iter_mut()
        .find(|(existing, _)| existing.same_value_zero(&key))
    {
        Some((_, slot)) => *slot = value,
        None => entries.push((key, value)),
    }
    object.set_collection(interp.heap, entries, false);
    Ok(this)
}

/// `set.add(value)`, which answers the set itself.
fn add(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let (object, mut entries) = entries_of_method(interp, &this)?;
    // §24.2.3.1 step 5 stores `-0` as `+0`. `normalize_key` is the one place that knows
    // this, and `add` was the caller that forgot it: `new Set().add(-0)` answered `-0` under
    // `Object.is` while the constructor's own path (through `set_entry`) answered `+0`.
    let value = normalize_key(arg(args, 0));
    if !entries
        .iter()
        .any(|(existing, _)| existing.same_value_zero(&value))
    {
        entries.push((value, Value::Undefined));
    }
    object.set_collection(interp.heap, entries, true);
    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 entries) = entries_of_method(interp, &this)?;
    let before = entries.len();
    entries.retain(|(existing, _)| !existing.same_value_zero(&key));
    let removed = entries.len() != before;
    let is_set = object.collection_is_set().unwrap_or(false);
    object.set_collection(interp.heap, entries, 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 (_, entries) = entries_of_method(interp, &this)?;
    // A snapshot, so a callback that deletes the current entry does not disturb the walk —
    // which is what the spec's "visited" bookkeeping amounts to for the common cases.
    for (key, value) in entries {
        let payload = if is_set(interp, &this)? {
            vec![key.clone(), key, this.clone()]
        } else {
            vec![value, key, this.clone()]
        };
        interp.call_value(callback.clone(), this_arg.clone(), payload)?;
    }
    Ok(Value::Undefined)
}

fn keys(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let (_, entries) = entries_of_method(interp, &this)?;
    let values: Vec<Value> = entries.into_iter().map(|(key, _)| key).collect();
    let array = interp.new_array(values);
    iterator(interp, Value::Object(array.clone()), IteratorKind::Value)
}

fn values(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let (_, entries) = entries_of_method(interp, &this)?;
    let is_set_form = is_set(interp, &this)?;
    let values: Vec<Value> = entries
        .into_iter()
        .map(|(key, value)| if is_set_form { key } else { value })
        .collect();
    let array = interp.new_array(values);
    iterator(interp, Value::Object(array.clone()), IteratorKind::Value)
}

fn entries(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let (_, entries) = entries_of_method(interp, &this)?;
    let is_set_form = is_set(interp, &this)?;
    let values: Vec<Value> = entries
        .into_iter()
        .map(|(key, value)| {
            // 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]
            } else {
                vec![key, value]
            };
            Value::Object(interp.new_array(pair))
        })
        .collect();
    let array = interp.new_array(values);
    iterator(interp, Value::Object(array.clone()), IteratorKind::Value)
}