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