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
#![allow(clippy::mutable_key_type)]
use super::function::{make_builtin_fn, make_constructor_fn};
use crate::{
object::{ObjectData, PROTOTYPE},
property::{Attribute, Property},
BoaProfiler, Context, Result, Value,
};
use ordered_map::OrderedMap;
pub mod ordered_map;
#[cfg(test)]
mod tests;
#[derive(Debug, Clone)]
pub(crate) struct Map(OrderedMap<Value, Value>);
impl Map {
pub(crate) const NAME: &'static str = "Map";
pub(crate) const LENGTH: usize = 1;
/// Helper function to set the size property.
fn set_size(this: &Value, size: usize) {
let size = Property::data_descriptor(
size.into(),
Attribute::READONLY | Attribute::NON_ENUMERABLE | Attribute::PERMANENT,
);
this.set_property("size".to_string(), size);
}
/// `Map.prototype.set( key, value )`
///
/// This method associates the value with the key. Returns the map object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-map.prototype.set
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set
pub(crate) fn set(this: &Value, args: &[Value], ctx: &mut Context) -> Result<Value> {
let (key, value) = match args.len() {
0 => (Value::Undefined, Value::Undefined),
1 => (args[0].clone(), Value::Undefined),
_ => (args[0].clone(), args[1].clone()),
};
let size = if let Value::Object(ref object) = this {
let mut object = object.borrow_mut();
if let Some(map) = object.as_map_mut() {
map.insert(key, value);
map.len()
} else {
return Err(ctx.construct_type_error("'this' is not a Map"));
}
} else {
return Err(ctx.construct_type_error("'this' is not a Map"));
};
Self::set_size(this, size);
Ok(this.clone())
}
/// `Map.prototype.delete( key )`
///
/// This method removes the element associated with the key, if it exists. Returns true if there was an element, false otherwise.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-map.prototype.delete
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete
pub(crate) fn delete(this: &Value, args: &[Value], ctx: &mut Context) -> Result<Value> {
let undefined = Value::Undefined;
let key = match args.len() {
0 => &undefined,
_ => &args[0],
};
let (deleted, size) = if let Value::Object(ref object) = this {
let mut object = object.borrow_mut();
if let Some(map) = object.as_map_mut() {
let deleted = map.remove(key).is_some();
(deleted, map.len())
} else {
return Err(ctx.construct_type_error("'this' is not a Map"));
}
} else {
return Err(ctx.construct_type_error("'this' is not a Map"));
};
Self::set_size(this, size);
Ok(deleted.into())
}
/// `Map.prototype.get( key )`
///
/// This method returns the value associated with the key, or undefined if there is none.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-map.prototype.get
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
pub(crate) fn get(this: &Value, args: &[Value], ctx: &mut Context) -> Result<Value> {
let undefined = Value::Undefined;
let key = match args.len() {
0 => &undefined,
_ => &args[0],
};
if let Value::Object(ref object) = this {
let object = object.borrow();
if let Some(map) = object.as_map_ref() {
return Ok(if let Some(result) = map.get(key) {
result.clone()
} else {
Value::Undefined
});
}
}
Err(ctx.construct_type_error("'this' is not a Map"))
}
/// `Map.prototype.clear( )`
///
/// This method removes all entries from the map.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-map.prototype.clear
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear
pub(crate) fn clear(this: &Value, _: &[Value], _: &mut Context) -> Result<Value> {
this.set_data(ObjectData::Map(OrderedMap::new()));
Self::set_size(this, 0);
Ok(Value::Undefined)
}
/// `Map.prototype.has( key )`
///
/// This method checks if the map contains an entry with the given key.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-map.prototype.has
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has
pub(crate) fn has(this: &Value, args: &[Value], ctx: &mut Context) -> Result<Value> {
let undefined = Value::Undefined;
let key = match args.len() {
0 => &undefined,
_ => &args[0],
};
if let Value::Object(ref object) = this {
let object = object.borrow();
if let Some(map) = object.as_map_ref() {
return Ok(map.contains_key(key).into());
}
}
Err(ctx.construct_type_error("'this' is not a Map"))
}
/// `Map.prototype.forEach( callbackFn [ , thisArg ] )`
///
/// This method executes the provided callback function for each key-value pair in the map.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-map.prototype.foreach
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach
pub(crate) fn for_each(
this: &Value,
args: &[Value],
interpreter: &mut Context,
) -> Result<Value> {
if args.is_empty() {
return Err(Value::from("Missing argument for Map.prototype.forEach"));
}
let callback_arg = &args[0];
let this_arg = args.get(1).cloned().unwrap_or_else(Value::undefined);
if let Value::Object(ref object) = this {
let object = object.borrow();
if let Some(map) = object.as_map_ref().cloned() {
for (key, value) in map {
let arguments = [value, key, this.clone()];
interpreter.call(callback_arg, &this_arg, &arguments)?;
}
}
}
Ok(Value::Undefined)
}
/// Helper function to get a key-value pair from an array.
fn get_key_value(value: &Value) -> Option<(Value, Value)> {
if let Value::Object(object) = value {
if object.borrow().is_array() {
let (key, value) = match value.get_field("length").as_number().unwrap() as i32 {
0 => (Value::Undefined, Value::Undefined),
1 => (value.get_field("0"), Value::Undefined),
_ => (value.get_field("0"), value.get_field("1")),
};
return Some((key, value));
}
}
None
}
/// Create a new map
pub(crate) fn make_map(this: &Value, args: &[Value], ctx: &mut Context) -> Result<Value> {
// Make a new Object which will internally represent the Array (mapping
// between indices and values): this creates an Object with no prototype
// Set Prototype
let prototype = ctx.global_object().get_field("Map").get_field(PROTOTYPE);
this.as_object_mut()
.expect("this is array object")
.set_prototype_instance(prototype);
// This value is used by console.log and other routines to match Object type
// to its Javascript Identifier (global constructor method name)
// add our arguments in
let data = match args.len() {
0 => OrderedMap::new(),
_ => match &args[0] {
Value::Object(object) => {
let object = object.borrow();
if let Some(map) = object.as_map_ref().cloned() {
map
} else if object.is_array() {
let mut map = OrderedMap::new();
let len = args[0].get_field("length").to_integer(ctx)? as i32;
for i in 0..len {
let val = &args[0].get_field(i.to_string());
let (key, value) = Self::get_key_value(val).ok_or_else(|| {
ctx.construct_type_error(
"iterable for Map should have array-like objects",
)
})?;
map.insert(key, value);
}
map
} else {
return Err(ctx.construct_type_error(
"iterable for Map should have array-like objects",
));
}
}
_ => {
return Err(
ctx.construct_type_error("iterable for Map should have array-like objects")
)
}
},
};
// finally create length property
Self::set_size(this, data.len());
this.set_data(ObjectData::Map(data));
Ok(this.clone())
}
/// Initialise the `Map` object on the global object.
pub(crate) fn init(interpreter: &mut Context) -> (&'static str, Value) {
let global = interpreter.global_object();
let _timer = BoaProfiler::global().start_event(Self::NAME, "init");
// Create prototype
let prototype = Value::new_object(Some(global));
make_builtin_fn(Self::set, "set", &prototype, 2, interpreter);
make_builtin_fn(Self::delete, "delete", &prototype, 1, interpreter);
make_builtin_fn(Self::get, "get", &prototype, 1, interpreter);
make_builtin_fn(Self::clear, "clear", &prototype, 0, interpreter);
make_builtin_fn(Self::has, "has", &prototype, 1, interpreter);
make_builtin_fn(Self::for_each, "forEach", &prototype, 1, interpreter);
let map_object = make_constructor_fn(
Self::NAME,
Self::LENGTH,
Self::make_map,
global,
prototype,
true,
false,
);
(Self::NAME, map_object)
}
}