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("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("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    ] {
89        define_method(&proto, name, length, func, interp);
90    }
91    install_size(&proto, interp);
92    install_iterable(&proto, interp, false);
93    interp.realm.set_proto = Some(proto);
94    let global = interp.realm.global.clone();
95    global.define(
96        "Set",
97        Property::with_attributes(Value::Object(constructor), true, false),
98    );
99}
100
101/// `size` is an accessor, so it cannot be assigned and always reflects the entries.
102fn install_size(proto: &Gc<JsObject>, interp: &Interp<'_>) {
103    let getter = interp.new_native("get size", 0, size);
104    proto.define(
105        "size",
106        Property {
107            getter: Some(Value::Object(getter)),
108            enumerable: false,
109            configurable: true,
110            ..Property::default()
111        },
112    );
113}
114
115/// `Symbol.iterator`, plus the `Symbol.toStringTag` the tag question needs.
116///
117/// The default iterator differs by collection, and it is easy to get wrong in a way that
118/// looks almost right: a `Map` iterates `[key, value]` pairs (the same as `entries`), but
119/// a `Set` iterates its *values*. Wiring both to `entries` made `[...new Set([3])]`
120/// produce `[[3, 3]]` — one pair — instead of `[3]`.
121fn install_iterable(proto: &Gc<JsObject>, interp: &mut Interp<'_>, is_map: bool) {
122    let func = if is_map {
123        entries as crate::object::NativeFn
124    } else {
125        values
126    };
127    let iterator_fn = method(interp, "[Symbol.iterator]", 0, func).expect("a method");
128    let key = interp.realm.well_known_key(WellKnown::Iterator);
129    proto.define_key(&key, Property::data(iterator_fn));
130}
131
132/// A collection's entries, named so the signatures below stay readable.
133type Entries = Vec<(Value, Value)>;
134
135/// The entries of `this`, which must be a `Map` or a `Set`.
136fn entries_of(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, Entries)> {
137    let object = this
138        .as_object()
139        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
140    let entries = object
141        .collection_entries()
142        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
143    Ok((object.clone(), entries))
144}
145
146fn is_set(interp: &Interp<'_>, this: &Value) -> JsResult<bool> {
147    let object = this
148        .as_object()
149        .ok_or_else(|| interp.type_error("method called on a non-collection"))?;
150    object
151        .collection_is_set()
152        .ok_or_else(|| interp.type_error("method called on a non-collection"))
153}
154
155/// Build a `Map` or a `Set`, filling it from an iterable argument.
156fn make_collection(
157    interp: &mut Interp<'_>,
158    this: &Value,
159    args: &[Value],
160    is_set_form: bool,
161) -> JsResult<Value> {
162    let object = match this.as_object() {
163        Some(object) => object.clone(),
164        None => {
165            let proto = if is_set_form {
166                interp.realm.set_proto.clone()
167            } else {
168                interp.realm.map_proto.clone()
169            };
170            interp.new_object(proto.or(Some(interp.realm.object_proto.clone())))
171        }
172    };
173    object.set_collection(Vec::new(), is_set_form);
174    let source = arg(args, 0);
175    if !matches!(source, Value::Undefined | Value::Null) {
176        for entry in interp.array_like_to_args(&source)? {
177            if is_set_form {
178                set_entry(interp, &object, entry)?;
179            } else {
180                // A `Map` source yields `[key, value]` pairs.
181                let pair = interp.array_like_to_args(&entry)?;
182                set_entry(interp, &object, arg(&pair, 0))?;
183                if let Some(object) = this.as_object() {
184                    let mut entries = object.collection_entries().unwrap_or_default();
185                    if let Some(last) = entries.last_mut() {
186                        last.1 = arg(&pair, 1);
187                    }
188                    object.set_collection(entries, false);
189                }
190            }
191        }
192    }
193    Ok(Value::Object(object))
194}
195
196/// Insert or update one key.
197fn set_entry(interp: &Interp<'_>, object: &Gc<JsObject>, key: Value) -> JsResult<()> {
198    let mut entries = object.collection_entries().unwrap_or_default();
199    let is_set = object.collection_is_set().unwrap_or(false);
200    match entries
201        .iter_mut()
202        .find(|(existing, _)| existing.same_value_zero(&key))
203    {
204        // An existing key keeps its position and only its value changes, which is what
205        // makes `map.set(k, 1); map.set(k, 2)` iterate `k` once.
206        Some((_, value)) => *value = key.clone(),
207        // Both classes start the value at `undefined`: a `Set` never reads it, and a `Map`
208        // overwrites it as soon as the pair is known.
209        None => entries.push((key.clone(), Value::Undefined)),
210    }
211    let _ = (interp, is_set);
212    object.set_collection(entries, is_set);
213    Ok(())
214}
215
216/// `new Map(iterable)`.
217fn map_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
218    make_collection(interp, &this, args, false)
219}
220
221/// `new Set(iterable)`.
222fn set_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
223    make_collection(interp, &this, args, true)
224}
225
226fn size(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
227    let (_, entries) = entries_of(interp, &this)?;
228    Ok(Value::Int(entries.len() as i32))
229}
230
231fn get(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
232    let key = arg(args, 0);
233    let (_, entries) = entries_of(interp, &this)?;
234    Ok(entries
235        .into_iter()
236        .find(|(existing, _)| existing.same_value_zero(&key))
237        .map(|(_, value)| value)
238        .unwrap_or(Value::Undefined))
239}
240
241fn set(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
242    let (object, mut entries) = entries_of(interp, &this)?;
243    let key = arg(args, 0);
244    let value = arg(args, 1);
245    match entries
246        .iter_mut()
247        .find(|(existing, _)| existing.same_value_zero(&key))
248    {
249        Some((_, slot)) => *slot = value,
250        None => entries.push((key, value)),
251    }
252    object.set_collection(entries, false);
253    Ok(this)
254}
255
256/// `set.add(value)`, which answers the set itself.
257fn add(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
258    let (object, mut entries) = entries_of(interp, &this)?;
259    let value = arg(args, 0);
260    if !entries
261        .iter()
262        .any(|(existing, _)| existing.same_value_zero(&value))
263    {
264        entries.push((value, Value::Undefined));
265    }
266    object.set_collection(entries, true);
267    Ok(this)
268}
269
270fn has(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
271    let key = arg(args, 0);
272    let (_, entries) = entries_of(interp, &this)?;
273    Ok(Value::Bool(
274        entries
275            .into_iter()
276            .any(|(existing, _)| existing.same_value_zero(&key)),
277    ))
278}
279
280fn delete(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
281    let key = arg(args, 0);
282    let (object, mut entries) = entries_of(interp, &this)?;
283    let before = entries.len();
284    entries.retain(|(existing, _)| !existing.same_value_zero(&key));
285    let removed = entries.len() != before;
286    let is_set = object.collection_is_set().unwrap_or(false);
287    object.set_collection(entries, is_set);
288    Ok(Value::Bool(removed))
289}
290
291fn clear(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
292    let (object, _) = entries_of(interp, &this)?;
293    let is_set = object.collection_is_set().unwrap_or(false);
294    object.set_collection(Vec::new(), is_set);
295    Ok(Value::Undefined)
296}
297
298/// `forEach(callback, thisArg)`, called with `(value, key, collection)`.
299fn for_each(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
300    let callback = arg(args, 0);
301    if !callback
302        .as_object()
303        .is_some_and(|function| function.is_callable())
304    {
305        return Err(interp.type_error("forEach needs a callback"));
306    }
307    let this_arg = arg(args, 1);
308    let (_, entries) = entries_of(interp, &this)?;
309    // A snapshot, so a callback that deletes the current entry does not disturb the walk —
310    // which is what the spec's "visited" bookkeeping amounts to for the common cases.
311    for (key, value) in entries {
312        let payload = if is_set(interp, &this)? {
313            vec![key.clone(), key, this.clone()]
314        } else {
315            vec![value, key, this.clone()]
316        };
317        interp.call_value(callback.clone(), this_arg.clone(), payload)?;
318    }
319    Ok(Value::Undefined)
320}
321
322fn keys(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
323    let (_, entries) = entries_of(interp, &this)?;
324    let values: Vec<Value> = entries.into_iter().map(|(key, _)| key).collect();
325    let array = interp.new_array(values);
326    iterator(interp, Value::Object(array.clone()), IteratorKind::Value)
327}
328
329fn values(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
330    let is_set_form = is_set(interp, &this)?;
331    let (_, entries) = entries_of(interp, &this)?;
332    let values: Vec<Value> = entries
333        .into_iter()
334        .map(|(key, value)| if is_set_form { key } else { value })
335        .collect();
336    let array = interp.new_array(values);
337    iterator(interp, Value::Object(array.clone()), IteratorKind::Value)
338}
339
340fn entries(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
341    let is_set_form = is_set(interp, &this)?;
342    let (_, entries) = entries_of(interp, &this)?;
343    let values: Vec<Value> = entries
344        .into_iter()
345        .map(|(key, value)| {
346            // A `Set`'s entries are `[value, value]`, which is what makes
347            // `for (const [a, b] of set)` give the same value twice.
348            let pair = if is_set_form {
349                vec![key.clone(), key]
350            } else {
351                vec![key, value]
352            };
353            Value::Object(interp.new_array(pair))
354        })
355        .collect();
356    let array = interp.new_array(values);
357    iterator(interp, Value::Object(array.clone()), IteratorKind::Value)
358}