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
//! Boa's implementation of ECMAScript's `WeakMap` builtin object.
//!
//! More information:
//! - [ECMAScript reference][spec]
//! - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-weakmap-objects
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
use crate::{
Context, JsArgs, JsNativeError, JsResult, JsString, JsValue,
builtins::{
BuiltInBuilder, BuiltInConstructor, BuiltInObject, IntrinsicObject,
map::add_entries_from_iterable,
},
context::intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
js_string,
object::{ErasedVTableObject, JsObject, internal_methods::get_prototype_from_constructor},
property::Attribute,
realm::Realm,
string::StaticJsStrings,
symbol::JsSymbol,
};
use boa_gc::{Finalize, Trace};
type NativeWeakMap = boa_gc::WeakMap<ErasedVTableObject, JsValue>;
#[derive(Debug, Trace, Finalize)]
pub(crate) struct WeakMap;
#[cfg(test)]
mod tests;
impl IntrinsicObject for WeakMap {
fn get(intrinsics: &Intrinsics) -> JsObject {
Self::STANDARD_CONSTRUCTOR(intrinsics.constructors()).constructor()
}
fn init(realm: &Realm) {
BuiltInBuilder::from_standard_constructor::<Self>(realm)
.property(
JsSymbol::to_string_tag(),
Self::NAME,
Attribute::READONLY | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.method(Self::delete, js_string!("delete"), 1)
.method(Self::get, js_string!("get"), 1)
.method(Self::has, js_string!("has"), 1)
.method(Self::set, js_string!("set"), 2)
.method(Self::get_or_insert, js_string!("getOrInsert"), 2)
.method(
Self::get_or_insert_computed,
js_string!("getOrInsertComputed"),
2,
)
.build();
}
}
impl BuiltInObject for WeakMap {
const NAME: JsString = StaticJsStrings::WEAK_MAP;
const ATTRIBUTE: Attribute = Attribute::WRITABLE.union(Attribute::CONFIGURABLE);
}
impl BuiltInConstructor for WeakMap {
/// The amount of arguments the `WeakMap` constructor takes.
const CONSTRUCTOR_ARGUMENTS: usize = 0;
const PROTOTYPE_STORAGE_SLOTS: usize = 7;
const CONSTRUCTOR_STORAGE_SLOTS: usize = 0;
const STANDARD_CONSTRUCTOR: fn(&StandardConstructors) -> &StandardConstructor =
StandardConstructors::weak_map;
/// `WeakMap ( [ iterable ] )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-weakmap-iterable
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/WeakMap
fn constructor(
new_target: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. If NewTarget is undefined, throw a TypeError exception.
if new_target.is_undefined() {
return Err(JsNativeError::typ()
.with_message("WeakMap: cannot call constructor without `new`")
.into());
}
// 2. Let map be ? OrdinaryCreateFromConstructor(NewTarget, "%WeakMap.prototype%", « [[WeakMapData]] »).
// 3. Set map.[[WeakMapData]] to a new empty List.
let prototype =
get_prototype_from_constructor(new_target, StandardConstructors::weak_map, context)?;
let map = JsObject::from_proto_and_data_with_shared_shape(
context.root_shape(),
prototype,
NativeWeakMap::new(),
);
// 4. If iterable is either undefined or null, return map.
let iterable = args.get_or_undefined(0);
if iterable.is_null_or_undefined() {
return Ok(map.into());
}
// 5. Let adder be ? Get(map, "set").
// 6. If IsCallable(adder) is false, throw a TypeError exception.
let adder = map
.get(js_string!("set"), context)?
.as_function()
.ok_or_else(|| JsNativeError::typ().with_message("WeakMap: 'add' is not a function"))?;
// 7. Return ? AddEntriesFromIterable(map, iterable, adder).
add_entries_from_iterable(&map, iterable, &adder, context)
}
}
impl WeakMap {
/// `WeakMap.prototype.delete ( key )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-weakmap.prototype.delete
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/delete
pub(crate) fn delete(
this: &JsValue,
args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let M be the this value.
// 2. Perform ? RequireInternalSlot(M, [[WeakMapData]]).
let object = this.as_object();
let mut map = object
.as_ref()
.and_then(JsObject::downcast_mut::<NativeWeakMap>)
.ok_or_else(|| {
JsNativeError::typ().with_message("WeakMap.delete: called with non-object value")
})?;
// 3. Let entries be M.[[WeakMapData]].
// 4. If key is not an Object, return false.
let Some(key) = args.get_or_undefined(0).as_object() else {
return Ok(false.into());
};
// 5. For each Record { [[Key]], [[Value]] } p of entries, do
// a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, then
// i. Set p.[[Key]] to empty.
// ii. Set p.[[Value]] to empty.
// iii. Return true.
// 6. Return false.
Ok(map.remove(key.inner()).is_some().into())
}
/// `WeakMap.prototype.get ( key )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-weakmap.prototype.get
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/get
pub(crate) fn get(
this: &JsValue,
args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let M be the this value.
// 2. Perform ? RequireInternalSlot(M, [[WeakMapData]]).
let object = this.as_object();
let map = object
.as_ref()
.and_then(JsObject::downcast_ref::<NativeWeakMap>)
.ok_or_else(|| {
JsNativeError::typ().with_message("WeakMap.get: called with non-object value")
})?;
// 3. Let entries be M.[[WeakMapData]].
// 4. If key is not an Object, return undefined.
let Some(key) = args.get_or_undefined(0).as_object() else {
return Ok(JsValue::undefined());
};
// 5. For each Record { [[Key]], [[Value]] } p of entries, do
// a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return p.[[Value]].
// 6. Return undefined.
Ok(map.get(key.inner()).unwrap_or_default())
}
/// `WeakMap.prototype.has ( key )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-weakmap.prototype.has
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/has
pub(crate) fn has(
this: &JsValue,
args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let M be the this value.
// 2. Perform ? RequireInternalSlot(M, [[WeakMapData]]).
let object = this.as_object();
let map = object
.as_ref()
.and_then(JsObject::downcast_ref::<NativeWeakMap>)
.ok_or_else(|| {
JsNativeError::typ().with_message("WeakMap.has: called with non-object value")
})?;
// 3. Let entries be M.[[WeakMapData]].
// 4. If key is not an Object, return false.
let Some(key) = args.get_or_undefined(0).as_object() else {
return Ok(false.into());
};
// 5. For each Record { [[Key]], [[Value]] } p of entries, do
// a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return true.
// 6. Return false.
Ok(map.contains_key(key.inner()).into())
}
/// `WeakMap.prototype.set ( key, value )`
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-weakmap.prototype.set
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/set
pub(crate) fn set(
this: &JsValue,
args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let M be the this value.
// 2. Perform ? RequireInternalSlot(M, [[WeakMapData]]).
let object = this.as_object();
let mut map = object
.as_ref()
.and_then(JsObject::downcast_mut::<NativeWeakMap>)
.ok_or_else(|| {
JsNativeError::typ().with_message("WeakMap.set: called with non-object value")
})?;
// 3. Let entries be M.[[WeakMapData]].
// 4. If key is not an Object, throw a TypeError exception.
let key = args.get_or_undefined(0);
let Some(key) = key.as_object() else {
return Err(JsNativeError::typ()
.with_message(format!(
"WeakMap.set: expected target argument of type `object`, got target of type `{}`",
key.type_of()
)).into());
};
// 5. For each Record { [[Key]], [[Value]] } p of entries, do
// a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, then
// i. Set p.[[Value]] to value.
// ii. Return M.
// 6. Let p be the Record { [[Key]]: key, [[Value]]: value }.
// 7. Append p to entries.
map.insert(key.inner(), args.get_or_undefined(1).clone());
// 8. Return M.
Ok(this.clone())
}
/// `WeakMap.prototype.getOrInsert ( key, value )`
///
/// Given a key and a value, returns the existing value if it exists; otherwise inserts the
/// provided default value and returns that value.
///
/// More information:
/// - [Upsert proposal reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/proposal-upsert/#sec-weakmap.prototype.getOrInsert
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/getOrInsert
pub(crate) fn get_or_insert(
this: &JsValue,
args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let M be the this value.
// 2. Perform ? RequireInternalSlot(M, [[WeakMapData]]).
let object = this.as_object();
let map = object
.and_then(|obj| obj.clone().downcast::<NativeWeakMap>().ok())
.ok_or_else(|| {
JsNativeError::typ()
.with_message("WeakMap.getOrInsert: called with non-object value")
})?;
// 3. If CanBeHeldWeakly(key) is false, throw a TypeError exception.
// TODO: Implement proper CanBeHeldWeakly once available. For now, only
// objects are accepted as keys; symbols should be allowed in the
// future according to the proposal.
let key_val = args.get_or_undefined(0);
let Some(key) = key_val.as_object() else {
return Err(JsNativeError::typ()
.with_message(format!(
"WeakMap.getOrInsert: expected target argument of type `object`, got target of type `{}`",
key_val.type_of()
))
.into());
};
// 4. For each Record { [[Key]], [[Value]] } p of M.[[WeakMapData]]
if let Some(existing) = map.borrow().data().get(key.inner()) {
// a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return p.[[Value]].
return Ok(existing);
}
// 5-6. Insert the new record with provided value and return it.
let value = args.get_or_undefined(1).clone();
map.borrow_mut()
.data_mut()
.insert(key.inner(), value.clone());
Ok(value)
}
/// `WeakMap.prototype.getOrInsertComputed ( key, callback )`
///
/// If the key exists, returns the existing value. Otherwise computes a new value by calling
/// `callback` with the key, inserts it into the `WeakMap`, and returns it.
///
/// More information:
/// - [Upsert proposal reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/proposal-upsert/#sec-weakmap.prototype.getOrInsertComputed
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/getOrInsertComputed
pub(crate) fn get_or_insert_computed(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let M be the this value.
// 2. Perform ? RequireInternalSlot(M, [[WeakMapData]]).
let object = this.as_object();
let map = object
.and_then(|obj| obj.clone().downcast::<NativeWeakMap>().ok())
.ok_or_else(|| {
JsNativeError::typ()
.with_message("WeakMap.getOrInsertComputed: called with non-object value")
})?;
// 3. If CanBeHeldWeakly(key) is false, throw a TypeError exception.
// TODO: Implement proper CanBeHeldWeakly once available. For now, only
// objects are accepted as keys; symbols should be allowed in the
// future according to the proposal.
let key_value = args.get_or_undefined(0).clone();
let Some(key_obj) = key_value.as_object() else {
return Err(JsNativeError::typ()
.with_message(format!(
"WeakMap.getOrInsertComputed: expected target argument of type `object`, got target of type `{}`",
key_value.type_of()
))
.into());
};
// 4. If IsCallable(callback) is false, throw a TypeError exception.
let Some(callback_fn) = args.get_or_undefined(1).as_callable() else {
return Err(JsNativeError::typ()
.with_message("Method WeakMap.prototype.getOrInsertComputed called with non-callable callback function")
.into());
};
// 5. For each Record { [[Key]], [[Value]] } p of M.[[WeakMapData]]
if let Some(existing) = map.borrow().data().get(key_obj.inner()) {
// a. If p.[[Key]] is not empty and SameValue(p.[[Key]], key) is true, return p.[[Value]].
return Ok(existing);
}
// 6. Let value be ? Call(callback, undefined, « key »).
// 7. NOTE: The WeakMap may have been modified during execution of callback.
let value = callback_fn.call(
&JsValue::undefined(),
std::slice::from_ref(&key_value),
context,
)?;
// 8-10. Insert or update the entry and return value.
map.borrow_mut()
.data_mut()
.insert(key_obj.inner(), value.clone());
Ok(value)
}
}