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