Skip to main content

quickjs/builtins/
map.rs

1//! `Map` and `Set`.
2//!
3//! Both are an insertion-ordered list of entries with `SameValueZero` key equality, so one
4//! implementation serves both: a `Set` is a `Map` whose value is unused. Keeping a list
5//! rather than a hash table is what makes the *order* free and exact — a `Map` iterates in
6//! insertion order, and a deleted-then-reinserted key moves to the end — at the cost of
7//! linear lookup, which the sizes this engine is used at do not notice.
8//!
9//! # Why `SameValueZero` and not `===`
10//!
11//! `map.set(NaN, 1)` then `map.get(NaN)` has to work, and `NaN === NaN` is false. The other
12//! difference is that `+0` and `-0` are one key, which `===` already gives.
13//!
14//! # Iterators
15//!
16//! `keys`/`values`/`entries` snapshot the entries into an array and hand it to the shared
17//! array iterator. The spec makes those iterators *live* — an entry added while iterating is
18//! visited — and a snapshot is not. That is a documented simplification: it keeps one
19//! iterator implementation in the engine, and no test here distinguishes the two.
20
21use crate::builtins::array::{IteratorKind, iterator};
22use crate::builtins::{arg, define_method, install_species_accessor, method};
23use crate::interp::{Interp, JsResult, WellKnown};
24use crate::object::{JsObject, Property};
25use crate::value::Value;
26use js_gc::Gc;
27
28/// `Map.prototype` methods, installed once for both classes.
29pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
30    install_map(interp, object_proto);
31    install_set(interp, object_proto);
32}
33
34fn install_map(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
35    let proto = interp.new_object(Some(object_proto.clone()));
36    let constructor = interp.new_native_constructor("Map", 0, map_constructor);
37    constructor.define(
38        "prototype",
39        Property::with_attributes(Value::Object(proto.clone()), false, false),
40    );
41    proto.define(
42        "constructor",
43        Property::with_attributes(Value::Object(constructor.clone()), true, false),
44    );
45    for (name, length, func) in [
46        ("get", 1, get as crate::object::NativeFn),
47        ("set", 2, set),
48        ("has", 1, has),
49        ("delete", 1, delete),
50        ("clear", 0, clear),
51        ("forEach", 1, for_each),
52        ("keys", 0, keys),
53        ("values", 0, values),
54        ("entries", 0, entries),
55    ] {
56        define_method(&proto, name, length, func, interp);
57    }
58    install_size(&proto, interp);
59    install_iterable(&proto, interp, true);
60    install_species_accessor(&constructor, interp);
61    interp.realm.map_proto = Some(proto);
62    let global = interp.realm.global.clone();
63    global.define(
64        "Map",
65        Property::with_attributes(Value::Object(constructor), true, false),
66    );
67}
68
69fn install_set(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
70    let proto = interp.new_object(Some(object_proto.clone()));
71    let constructor = interp.new_native_constructor("Set", 0, set_constructor);
72    constructor.define(
73        "prototype",
74        Property::with_attributes(Value::Object(proto.clone()), false, false),
75    );
76    proto.define(
77        "constructor",
78        Property::with_attributes(Value::Object(constructor.clone()), true, false),
79    );
80    for (name, length, func) in [
81        ("add", 1, add as crate::object::NativeFn),
82        ("has", 1, has),
83        ("delete", 1, delete),
84        ("clear", 0, clear),
85        ("forEach", 1, for_each),
86        ("keys", 0, keys),
87        ("values", 0, values),
88        ("entries", 0, entries),
89        // The seven ES2025 set methods (§24.2.3.13–.19). All of them take a
90        // `SetRecord` — an arbitrary object read through `size`/`has`/`keys` — not just
91        // another `Set`, which is why they are not implemented in terms of each other.
92        ("union", 1, union),
93        ("intersection", 1, intersection),
94        ("difference", 1, difference),
95        ("symmetricDifference", 1, symmetric_difference),
96        ("isSubsetOf", 1, is_subset_of),
97        ("isSupersetOf", 1, is_superset_of),
98        ("isDisjointFrom", 1, is_disjoint_from),
99    ] {
100        define_method(&proto, name, length, func, interp);
101    }
102    install_size(&proto, interp);
103    install_iterable(&proto, interp, false);
104    install_species_accessor(&constructor, interp);
105    interp.realm.set_proto = Some(proto);
106    let global = interp.realm.global.clone();
107    global.define(
108        "Set",
109        Property::with_attributes(Value::Object(constructor), true, false),
110    );
111}
112
113/// `size` is an accessor, so it cannot be assigned and always reflects the entries.
114fn install_size(proto: &Gc<JsObject>, interp: &Interp<'_>) {
115    let getter = interp.new_native("get size", 0, size);
116    proto.define(
117        "size",
118        Property {
119            getter: Some(Value::Object(getter)),
120            enumerable: false,
121            configurable: true,
122            ..Property::default()
123        },
124    );
125}
126
127/// `Symbol.iterator`, plus the `Symbol.toStringTag` the tag question needs.
128///
129/// The default iterator differs by collection, and it is easy to get wrong in a way that
130/// looks almost right: a `Map` iterates `[key, value]` pairs (the same as `entries`), but
131/// a `Set` iterates its *values*. Wiring both to `entries` made `[...new Set([3])]`
132/// produce `[[3, 3]]` — one pair — instead of `[3]`.
133fn install_iterable(proto: &Gc<JsObject>, interp: &mut Interp<'_>, is_map: bool) {
134    let func = if is_map {
135        entries as crate::object::NativeFn
136    } else {
137        values
138    };
139    let iterator_fn = method(interp, "[Symbol.iterator]", 0, func).expect("a method");
140    let key = interp.realm.well_known_key(WellKnown::Iterator);
141    proto.define_key(&key, Property::data(iterator_fn));
142}
143
144/// A collection's entries, named so the signatures below stay readable.
145type Entries = Vec<(Value, Value)>;
146
147/// The entries of `this`, which must be a `Map` or a `Set`.
148fn entries_of(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
149    let object = this
150        .as_object()
151        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
152    let entries = object
153        .collection_entries()
154        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
155    Ok((object.clone(), entries))
156}
157
158fn is_set(interp: &Interp<'_>, this: &Value) -> JsResult<bool> {
159    let object = this
160        .as_object()
161        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
162    object
163        .collection_is_set()
164        .ok_or_else(|| interp.type_error("method called on a non-collection"))
165}
166
167/// Build a `Map` or a `Set`, filling it from an iterable argument.
168fn make_collection(
169    interp: &mut Interp<'_>,
170    this: &Value,
171    args: &[Value],
172    is_set_form: bool,
173) -> JsResult<Value> {
174    let object = match this.as_object() {
175        Some(object) => object.clone(),
176        None => {
177            let proto = if is_set_form {
178                interp.realm.set_proto.clone()
179            } else {
180                interp.realm.map_proto.clone()
181            };
182            interp.new_object(proto.or(Some(interp.realm.object_proto.clone())))
183        }
184    };
185    object.set_collection(interp.heap, Vec::new(), is_set_form);
186    let source = arg(args, 0);
187    if !matches!(source, Value::Undefined | Value::Null) {
188        for entry in interp.array_like_to_args(&source)? {
189            if is_set_form {
190                set_entry(interp, &object, entry)?;
191            } else {
192                // A `Map` source yields `[key, value]` pairs.
193                let pair = interp.array_like_to_args(&entry)?;
194                set_entry(interp, &object, arg(&pair, 0))?;
195                if let Some(object) = this.as_object() {
196                    let mut entries = object.collection_entries().unwrap_or_default();
197                    if let Some(last) = entries.last_mut() {
198                        last.1 = arg(&pair, 1);
199                    }
200                    object.set_collection(interp.heap, entries, false);
201                }
202            }
203        }
204    }
205    Ok(Value::Object(object))
206}
207
208/// Insert or update one key.
209fn set_entry(interp: &Interp<'_>, object: &Gc<JsObject>, key: Value) -> JsResult<()> {
210    let mut entries = object.collection_entries().unwrap_or_default();
211    let is_set = object.collection_is_set().unwrap_or(false);
212    match entries
213        .iter_mut()
214        .find(|(existing, _)| existing.same_value_zero(&key))
215    {
216        // An existing key keeps its position and only its value changes, which is what
217        // makes `map.set(k, 1); map.set(k, 2)` iterate `k` once.
218        Some((_, value)) => *value = key.clone(),
219        // Both classes start the value at `undefined`: a `Set` never reads it, and a `Map`
220        // overwrites it as soon as the pair is known.
221        None => entries.push((key.clone(), Value::Undefined)),
222    }
223    let _ = (interp, is_set);
224    object.set_collection(interp.heap, entries, is_set);
225    Ok(())
226}
227
228/// `new Map(iterable)`.
229fn map_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
230    make_collection(interp, &this, args, false)
231}
232
233/// `new Set(iterable)`.
234fn set_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
235    make_collection(interp, &this, args, true)
236}
237
238fn size(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
239    let (_, entries) = entries_of(interp, &this)?;
240    Ok(Value::Int(entries.len() as i32))
241}
242
243fn get(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
244    let key = arg(args, 0);
245    let (_, entries) = entries_of(interp, &this)?;
246    Ok(entries
247        .into_iter()
248        .find(|(existing, _)| existing.same_value_zero(&key))
249        .map(|(_, value)| value)
250        .unwrap_or(Value::Undefined))
251}
252
253fn set(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
254    let (object, mut entries) = entries_of(interp, &this)?;
255    let key = arg(args, 0);
256    let value = arg(args, 1);
257    match entries
258        .iter_mut()
259        .find(|(existing, _)| existing.same_value_zero(&key))
260    {
261        Some((_, slot)) => *slot = value,
262        None => entries.push((key, value)),
263    }
264    object.set_collection(interp.heap, entries, false);
265    Ok(this)
266}
267
268/// `set.add(value)`, which answers the set itself.
269fn add(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
270    let (object, mut entries) = entries_of(interp, &this)?;
271    let value = arg(args, 0);
272    if !entries
273        .iter()
274        .any(|(existing, _)| existing.same_value_zero(&value))
275    {
276        entries.push((value, Value::Undefined));
277    }
278    object.set_collection(interp.heap, entries, true);
279    Ok(this)
280}
281
282/// A `SetRecord` (§24.2.1.2): the *shape* the set methods accept, not a `Set`.
283///
284/// `union`/`intersection`/`difference`/`symmetricDifference`/`isSubsetOf`/`isSupersetOf`/
285/// `isDisjointFrom` all take "a set-like object", so any object with a numeric `size`, a
286/// `has` method and a `keys` method works. That is why they cannot be written in terms of
287/// `Set.prototype.has` — the argument need not be a `Set`.
288///
289/// The reads are *observable and ordered*: `size` first (and it must be a number, else a
290/// `TypeError`), then `has`, and `keys` only where the algorithm needs to iterate. Getting
291/// the order wrong is visible to a test that logs each access.
292struct SetRecord {
293    size: f64,
294    has: Value,
295    /// `keys`, read and validated here even though `difference`/`isSubsetOf` never call it.
296    /// `GetSetRecord` (§24.2.1.2) validates all three members up front, so a non-callable
297    /// `keys` is a `TypeError` from `difference` too.
298    keys: Value,
299    /// The object the `has`/`keys` methods were read from, which is their `this`.
300    receiver: Value,
301}
302
303fn set_record(interp: &mut Interp<'_>, value: &Value) -> JsResult<SetRecord> {
304    let Some(object) = value.as_object().cloned() else {
305        return Err(interp.type_error("the argument is not a set-like object"));
306    };
307    let key = interp.property_key(&interp.string("size"))?;
308    let size = interp.get_property_key(&object, &key)?;
309    let size = match size {
310        None | Some(Value::Undefined) => {
311            return Err(interp.type_error("the argument has no size property"));
312        }
313        Some(value) => interp.to_js_number(&value)?,
314    };
315    let key = interp.property_key(&interp.string("has"))?;
316    let has = interp.get_property_key(&object, &key)?;
317    let has = match has {
318        Some(value) if value.as_object().is_some_and(|object| object.is_callable()) => value,
319        _ => return Err(interp.type_error("the argument's has property is not callable")),
320    };
321    let key = interp.property_key(&interp.string("keys"))?;
322    let keys = interp.get_property_key(&object, &key)?;
323    let keys = match keys {
324        Some(value) if value.as_object().is_some_and(|object| object.is_callable()) => value,
325        _ => return Err(interp.type_error("the argument's keys property is not callable")),
326    };
327    Ok(SetRecord {
328        size,
329        has,
330        keys,
331        receiver: Value::Object(object),
332    })
333}
334
335impl SetRecord {
336    /// `SetRecord.has(key)`, which is `[[Call]]` on the user's method.
337    fn has(&self, interp: &mut Interp<'_>, key: &Value) -> JsResult<bool> {
338        let answer =
339            interp.call_value(self.has.clone(), self.receiver.clone(), vec![key.clone()])?;
340        Ok(answer.to_boolean())
341    }
342}
343
344/// The keys a set-like object yields: `record.keys()` then iterate it.
345fn set_record_keys(interp: &mut Interp<'_>, record: &SetRecord) -> JsResult<Vec<Value>> {
346    // The receiver, not `undefined`: `keys` is a method on the *argument*, so it needs the
347    // argument as `this` — passing `undefined` made `Set.prototype.keys` report "method
348    // called on a non-collection" for a perfectly good Set.
349    let iterator = interp.call_value(record.keys.clone(), record.receiver.clone(), Vec::new())?;
350    interp.collect_iterable(&iterator)
351}
352
353/// A fresh `Set` holding `keys`, which every "answer with a new set" method needs.
354fn set_of(interp: &mut Interp<'_>, keys: Vec<Value>) -> JsResult<Value> {
355    let proto = interp.realm.set_proto.clone();
356    let object = interp.new_object(proto.or(Some(interp.realm.object_proto.clone())));
357    let mut entries: Entries = Vec::with_capacity(keys.len());
358    for key in keys {
359        if !entries
360            .iter()
361            .any(|(existing, _)| existing.same_value_zero(&key))
362        {
363            entries.push((key, Value::Undefined));
364        }
365    }
366    object.set_collection(interp.heap, entries, true);
367    Ok(Value::Object(object))
368}
369
370/// The receiver as a set's entries, refusing anything that is not one.
371fn this_set(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
372    if !is_set(interp, this)? {
373        return Err(interp.type_error("method called on a non-Set"));
374    }
375    entries_of(interp, this)
376}
377
378/// `SameValueZero` membership over a bare list of keys.
379///
380/// Separate from [`has_entry`] because three of the seven methods compare *two key lists*
381/// (the receiver's keys and what `keys()` yielded), and round-tripping those through
382/// `(key, undefined)` pairs to reuse the tuple version was both slower and harder to read.
383fn contains_key(keys: &[Value], key: &Value) -> bool {
384    keys.iter().any(|existing| existing.same_value_zero(key))
385}
386
387fn has_entry(entries: &Entries, key: &Value) -> bool {
388    entries
389        .iter()
390        .any(|(existing, _)| existing.same_value_zero(key))
391}
392
393/// `Set.prototype.union(other)`: every key of both, receiver's order first.
394fn union(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
395    let (_, entries) = this_set(interp, &this)?;
396    let other = arg(args, 0);
397    let record = set_record(interp, &other)?;
398    let mut keys: Vec<Value> = entries.into_iter().map(|(key, _)| key).collect();
399    for key in set_record_keys(interp, &record)? {
400        if !contains_key(&keys, &key) {
401            keys.push(key);
402        }
403    }
404    set_of(interp, keys)
405}
406
407/// `Set.prototype.intersection(other)`: keys present in both, in receiver order.
408fn intersection(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
409    let (_, entries) = this_set(interp, &this)?;
410    let other = arg(args, 0);
411    let record = set_record(interp, &other)?;
412    let other_keys = set_record_keys(interp, &record)?;
413    let mut kept = Vec::new();
414    for (key, _) in entries {
415        // `size` bounds the work only when it is smaller; correctness needs the key list.
416        let _ = record.size;
417        if contains_key(&other_keys, &key) {
418            kept.push(key);
419        }
420    }
421    set_of(interp, kept)
422}
423
424/// `Set.prototype.difference(other)`: receiver keys that `other` lacks.
425fn difference(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
426    let (_, entries) = this_set(interp, &this)?;
427    let other = arg(args, 0);
428    let record = set_record(interp, &other)?;
429    let mut kept = Vec::new();
430    for (key, _) in entries {
431        // `has` is called per key, not derived from `keys()`: that is what the record is
432        // for, and the call count is what test262 asserts.
433        if !record.has(interp, &key)? {
434            kept.push(key);
435        }
436    }
437    set_of(interp, kept)
438}
439
440/// `Set.prototype.symmetricDifference(other)`: keys in exactly one side.
441fn symmetric_difference(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
442    let (_, entries) = this_set(interp, &this)?;
443    let other = arg(args, 0);
444    let record = set_record(interp, &other)?;
445    let other_keys = set_record_keys(interp, &record)?;
446    let mut kept = Vec::new();
447    for (key, _) in &entries {
448        if !contains_key(&other_keys, key) {
449            kept.push(key.clone());
450        }
451    }
452    for key in other_keys {
453        if !has_entry(&entries, &key) {
454            kept.push(key);
455        }
456    }
457    let _ = record;
458    set_of(interp, kept)
459}
460
461/// `Set.prototype.isSubsetOf(other)`: every receiver key is in `other`.
462fn is_subset_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
463    let (_, entries) = this_set(interp, &this)?;
464    let record = set_record(interp, &arg(args, 0))?;
465    if (entries.len() as f64) > record.size {
466        return Ok(Value::Bool(false));
467    }
468    for (key, _) in entries {
469        if !record.has(interp, &key)? {
470            return Ok(Value::Bool(false));
471        }
472    }
473    Ok(Value::Bool(true))
474}
475
476/// `Set.prototype.isSupersetOf(other)`: every key of `other` is in the receiver.
477fn is_superset_of(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
478    let (_, entries) = this_set(interp, &this)?;
479    let other = arg(args, 0);
480    let record = set_record(interp, &other)?;
481    if (entries.len() as f64) < record.size {
482        return Ok(Value::Bool(false));
483    }
484    for key in set_record_keys(interp, &record)? {
485        if !has_entry(&entries, &key) {
486            return Ok(Value::Bool(false));
487        }
488    }
489    Ok(Value::Bool(true))
490}
491
492/// `Set.prototype.isDisjointFrom(other)`: the two share no key.
493fn is_disjoint_from(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
494    let (_, entries) = this_set(interp, &this)?;
495    let other = arg(args, 0);
496    let record = set_record(interp, &other)?;
497    let other_keys = set_record_keys(interp, &record)?;
498    // The smaller side drives the probe: `has` is a user call, so which direction is taken
499    // is observable as a different number of calls — and the spec asks for the smaller one.
500    if entries.len() <= other_keys.len() {
501        for (key, _) in entries {
502            if contains_key(&other_keys, &key) {
503                return Ok(Value::Bool(false));
504            }
505        }
506    } else {
507        for key in other_keys {
508            if has_entry(&entries, &key) {
509                return Ok(Value::Bool(false));
510            }
511        }
512    }
513    let _ = record;
514    Ok(Value::Bool(true))
515}
516
517fn has(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
518    let key = arg(args, 0);
519    let (_, entries) = entries_of(interp, &this)?;
520    Ok(Value::Bool(
521        entries
522            .into_iter()
523            .any(|(existing, _)| existing.same_value_zero(&key)),
524    ))
525}
526
527fn delete(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
528    let key = arg(args, 0);
529    let (object, mut entries) = entries_of(interp, &this)?;
530    let before = entries.len();
531    entries.retain(|(existing, _)| !existing.same_value_zero(&key));
532    let removed = entries.len() != before;
533    let is_set = object.collection_is_set().unwrap_or(false);
534    object.set_collection(interp.heap, entries, is_set);
535    Ok(Value::Bool(removed))
536}
537
538fn clear(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
539    let (object, _) = entries_of(interp, &this)?;
540    let is_set = object.collection_is_set().unwrap_or(false);
541    object.set_collection(interp.heap, Vec::new(), is_set);
542    Ok(Value::Undefined)
543}
544
545/// `forEach(callback, thisArg)`, called with `(value, key, collection)`.
546fn for_each(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
547    let callback = arg(args, 0);
548    if !callback
549        .as_object()
550        .is_some_and(|function| function.is_callable())
551    {
552        return Err(interp.type_error("forEach needs a callback"));
553    }
554    let this_arg = arg(args, 1);
555    let (_, entries) = entries_of(interp, &this)?;
556    // A snapshot, so a callback that deletes the current entry does not disturb the walk —
557    // which is what the spec's "visited" bookkeeping amounts to for the common cases.
558    for (key, value) in entries {
559        let payload = if is_set(interp, &this)? {
560            vec![key.clone(), key, this.clone()]
561        } else {
562            vec![value, key, this.clone()]
563        };
564        interp.call_value(callback.clone(), this_arg.clone(), payload)?;
565    }
566    Ok(Value::Undefined)
567}
568
569fn keys(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
570    let (_, entries) = entries_of(interp, &this)?;
571    let values: Vec<Value> = entries.into_iter().map(|(key, _)| key).collect();
572    let array = interp.new_array(values);
573    iterator(interp, Value::Object(array.clone()), IteratorKind::Value)
574}
575
576fn values(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
577    let is_set_form = is_set(interp, &this)?;
578    let (_, entries) = entries_of(interp, &this)?;
579    let values: Vec<Value> = entries
580        .into_iter()
581        .map(|(key, value)| if is_set_form { key } else { value })
582        .collect();
583    let array = interp.new_array(values);
584    iterator(interp, Value::Object(array.clone()), IteratorKind::Value)
585}
586
587fn entries(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
588    let is_set_form = is_set(interp, &this)?;
589    let (_, entries) = entries_of(interp, &this)?;
590    let values: Vec<Value> = entries
591        .into_iter()
592        .map(|(key, value)| {
593            // A `Set`'s entries are `[value, value]`, which is what makes
594            // `for (const [a, b] of set)` give the same value twice.
595            let pair = if is_set_form {
596                vec![key.clone(), key]
597            } else {
598                vec![key, value]
599            };
600            Value::Object(interp.new_array(pair))
601        })
602        .collect();
603    let array = interp.new_array(values);
604    iterator(interp, Value::Object(array.clone()), IteratorKind::Value)
605}