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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! A Rust API wrapper for Boa's `Map` Builtin ECMAScript Object
use crate::{
    builtins::map::{add_entries_from_iterable, ordered_map::OrderedMap},
    builtins::Map,
    error::JsNativeError,
    object::{JsFunction, JsMapIterator, JsObject, JsObjectType},
    string::utf16,
    value::TryFromJs,
    Context, JsResult, JsValue,
};

use boa_gc::{Finalize, Trace};
use std::ops::Deref;

/// `JsMap` provides a wrapper for Boa's implementation of the ECMAScript `Map` object.
///
/// # Examples
///
/// Create a `JsMap` and set a new entry
/// ```
/// # use boa_engine::{
/// #  object::builtins::JsMap,
/// #  Context, JsValue, JsResult, js_string
/// # };
/// # fn main() -> JsResult<()> {
/// // Create default `Context`
/// let context = &mut Context::default();
///
/// // Create a new empty `JsMap`.
/// let map = JsMap::new(context);
///
/// // Set key-value pairs for the `JsMap`.
/// map.set(js_string!("Key-1"), js_string!("Value-1"), context)?;
/// map.set(js_string!("Key-2"), 10, context)?;
///
/// assert_eq!(map.get_size(context)?, 2.into());
/// # Ok(())
/// # }
/// ```
///
/// Create a `JsMap` from a `JsArray`
/// ```
/// # use boa_engine::{
/// #    object::builtins::{JsArray, JsMap},
/// #    Context, JsValue, JsResult, js_string
/// # };
/// # fn main() -> JsResult<()> {
/// // Create a default `Context`
/// let context = &mut Context::default();
///
/// // Create an array of two `[key, value]` pairs
/// let js_array = JsArray::new(context);
///
/// // Create a `[key, value]` pair of JsValues
/// let vec_one: Vec<JsValue> = vec![
///     js_string!("first-key").into(),
///     js_string!("first-value").into()
/// ];
///
/// // We create an push our `[key, value]` pair onto our array as a `JsArray`
/// js_array.push(JsArray::from_iter(vec_one, context), context)?;
///
/// // Create a `JsMap` from the `JsArray` using it's iterable property.
/// let js_iterable_map = JsMap::from_js_iterable(&js_array.into(), context)?;
///
/// assert_eq!(
///     js_iterable_map.get(js_string!("first-key"), context)?,
///     js_string!("first-value").into()
/// );
///
/// # Ok(())
/// }
/// ```
#[derive(Debug, Clone, Trace, Finalize)]
pub struct JsMap {
    inner: JsObject,
}

impl JsMap {
    /// Creates a new empty [`JsMap`] object.
    ///
    /// # Example
    /// ```
    /// # use boa_engine::{
    /// #    object::builtins::JsMap,
    /// #    Context, JsValue,
    /// # };
    /// # // Create a new context.
    /// # let context = &mut Context::default();
    /// // Create a new empty `JsMap`.
    /// let map = JsMap::new(context);
    /// ```
    #[inline]
    pub fn new(context: &mut Context) -> Self {
        let map = Self::create_map(context);
        Self { inner: map }
    }

    /// Create a new [`JsMap`] object from a [`JsObject`] that has an `@@Iterator` field.
    ///
    /// # Examples
    /// ```
    /// # use boa_engine::{
    /// #    object::builtins::{JsArray, JsMap},
    /// #    Context, JsResult, JsValue, js_string
    /// # };
    /// # fn main() -> JsResult<()> {
    /// # // Create a default `Context`
    /// # let context = &mut Context::default();
    /// // Create an array of two `[key, value]` pairs
    /// let js_array = JsArray::new(context);
    ///
    /// // Create a `[key, value]` pair of JsValues and add it to the `JsArray` as a `JsArray`
    /// let vec_one: Vec<JsValue> = vec![
    ///     js_string!("first-key").into(),
    ///     js_string!("first-value").into()
    /// ];
    /// js_array.push(JsArray::from_iter(vec_one, context), context)?;
    ///
    /// // Create a `JsMap` from the `JsArray` using it's iterable property.
    /// let js_iterable_map = JsMap::from_js_iterable(&js_array.into(), context)?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_js_iterable(iterable: &JsValue, context: &mut Context) -> JsResult<Self> {
        // Create a new map object.
        let map = Self::create_map(context);

        // Let adder be Get(map, "set") per spec. This action should not fail with default map.
        let adder = map
            .get(utf16!("set"), context)
            .expect("creating a map with the default prototype must not fail");

        let _completion_record = add_entries_from_iterable(&map, iterable, &adder, context)?;

        Ok(Self { inner: map })
    }

    /// Creates a [`JsMap`] from a valid [`JsObject`], or returns a `TypeError` if the provided object is not a [`JsMap`]
    ///
    /// # Examples
    ///
    /// ### Valid Example - returns a `JsMap` object
    /// ```
    /// # use boa_engine::{
    /// #    builtins::map::ordered_map::OrderedMap,
    /// #    object::{builtins::JsMap, JsObject},
    /// #    Context, JsValue, JsResult,
    /// # };
    /// # fn main() -> JsResult<()> {
    /// # let context = &mut Context::default();
    /// // `some_object` can be any JavaScript `Map` object.
    /// let some_object = JsObject::from_proto_and_data(
    ///     context.intrinsics().constructors().map().prototype(),
    ///     OrderedMap::<JsValue>::new(),
    /// );
    ///
    /// // Create `JsMap` object with incoming object.
    /// let js_map = JsMap::from_object(some_object)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ### Invalid Example - returns a `TypeError` with the message "object is not a Map"
    /// ```
    /// # use boa_engine::{
    /// #    object::{JsObject, builtins::{JsArray, JsMap}},
    /// #    Context, JsResult, JsValue,
    /// # };
    /// # let context = &mut Context::default();
    /// let some_object = JsArray::new(context);
    ///
    /// // `some_object` is an Array object, not a map object
    /// assert!(JsMap::from_object(some_object.into()).is_err());
    /// ```
    #[inline]
    pub fn from_object(object: JsObject) -> JsResult<Self> {
        if object.is::<OrderedMap<JsValue>>() {
            Ok(Self { inner: object })
        } else {
            Err(JsNativeError::typ()
                .with_message("object is not a Map")
                .into())
        }
    }

    // Utility function to generate the default `Map` object.
    fn create_map(context: &mut Context) -> JsObject {
        // Get default Map prototype
        let prototype = context.intrinsics().constructors().map().prototype();

        // Create a default map object with [[MapData]] as a new empty list
        JsObject::from_proto_and_data_with_shared_shape(
            context.root_shape(),
            prototype,
            <OrderedMap<JsValue>>::new(),
        )
    }

    /// Returns a new [`JsMapIterator`] object that yields the `[key, value]` pairs within the [`JsMap`] in insertion order.
    #[inline]
    pub fn entries(&self, context: &mut Context) -> JsResult<JsMapIterator> {
        let iterator_record = Map::entries(&self.inner.clone().into(), &[], context)?
            .get_iterator(context, None, None)?;
        let map_iterator_object = iterator_record.iterator();
        JsMapIterator::from_object(map_iterator_object.clone())
    }

    /// Returns a new [`JsMapIterator`] object that yields the `key` for each element within the [`JsMap`] in insertion order.
    #[inline]
    pub fn keys(&self, context: &mut Context) -> JsResult<JsMapIterator> {
        let iterator_record = Map::keys(&self.inner.clone().into(), &[], context)?
            .get_iterator(context, None, None)?;
        let map_iterator_object = iterator_record.iterator();
        JsMapIterator::from_object(map_iterator_object.clone())
    }

    /// Inserts a new entry into the [`JsMap`] object
    ///
    /// # Example
    ///
    /// ```
    /// # use boa_engine::{
    /// #    object::builtins::JsMap,
    /// #    Context, JsValue, JsResult, js_string
    /// # };
    /// # fn main() -> JsResult<()> {
    /// # let context = &mut Context::default();
    /// let js_map = JsMap::new(context);
    ///
    /// js_map.set(js_string!("foo"), js_string!("bar"), context)?;
    /// js_map.set(2, 4, context)?;
    ///
    /// assert_eq!(
    ///     js_map.get(js_string!("foo"), context)?,
    ///     js_string!("bar").into()
    /// );
    /// assert_eq!(js_map.get(2, context)?, 4.into());
    /// # Ok(())
    /// # }
    /// ```
    pub fn set<K, V>(&self, key: K, value: V, context: &mut Context) -> JsResult<JsValue>
    where
        K: Into<JsValue>,
        V: Into<JsValue>,
    {
        Map::set(
            &self.inner.clone().into(),
            &[key.into(), value.into()],
            context,
        )
    }

    /// Gets the size of the [`JsMap`] object.
    ///
    /// # Example
    ///
    /// ```
    /// # use boa_engine::{
    /// #    object::builtins::JsMap,
    /// #    Context, JsValue, JsResult, js_string
    /// # };
    /// # fn main() -> JsResult<()> {
    /// # let context = &mut Context::default();
    /// let js_map = JsMap::new(context);
    ///
    /// js_map.set(js_string!("foo"), js_string!("bar"), context)?;
    ///
    /// let map_size = js_map.get_size(context)?;
    ///
    /// assert_eq!(map_size, 1.into());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn get_size(&self, context: &mut Context) -> JsResult<JsValue> {
        Map::get_size(&self.inner.clone().into(), &[], context)
    }

    /// Removes element from [`JsMap`] with a matching `key` value.
    ///
    /// # Example
    ///
    /// ```
    /// # use boa_engine::{
    /// #    object::builtins::JsMap,
    /// #    Context, JsValue, JsResult, js_string
    /// # };
    /// # fn main() -> JsResult<()> {
    /// # let context = &mut Context::default();
    /// let js_map = JsMap::new(context);
    /// js_map.set(js_string!("foo"), js_string!("bar"), context)?;
    /// js_map.set(js_string!("hello"), js_string!("world"), context)?;
    ///
    /// js_map.delete(js_string!("foo"), context)?;
    ///
    /// assert_eq!(js_map.get_size(context)?, 1.into());
    /// assert_eq!(
    ///     js_map.get(js_string!("foo"), context)?,
    ///     JsValue::undefined()
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete<T>(&self, key: T, context: &mut Context) -> JsResult<JsValue>
    where
        T: Into<JsValue>,
    {
        Map::delete(&self.inner.clone().into(), &[key.into()], context)
    }

    /// Gets the value associated with the specified key within the [`JsMap`], or `undefined` if the key does not exist.
    ///
    /// # Example
    ///
    /// ```
    /// # use boa_engine::{
    /// #    object::builtins::JsMap,
    /// #    Context, JsValue, JsResult, js_string
    /// # };
    /// # fn main() -> JsResult<()> {
    /// # let context = &mut Context::default();
    /// let js_map = JsMap::new(context);
    /// js_map.set(js_string!("foo"), js_string!("bar"), context)?;
    ///
    /// let retrieved_value = js_map.get(js_string!("foo"), context)?;
    ///
    /// assert_eq!(retrieved_value, js_string!("bar").into());
    /// # Ok(())
    /// # }
    /// ```
    pub fn get<T>(&self, key: T, context: &mut Context) -> JsResult<JsValue>
    where
        T: Into<JsValue>,
    {
        Map::get(&self.inner.clone().into(), &[key.into()], context)
    }

    /// Removes all entries from the [`JsMap`].
    ///
    /// # Example
    ///
    /// ```
    /// # use boa_engine::{
    /// #    object::builtins::JsMap,
    /// #    Context, JsValue, JsResult, js_string
    /// # };
    /// # fn main() -> JsResult<()> {
    /// # let context = &mut Context::default();
    /// let js_map = JsMap::new(context);
    /// js_map.set(js_string!("foo"), js_string!("bar"), context)?;
    /// js_map.set(js_string!("hello"), js_string!("world"), context)?;
    ///
    /// js_map.clear(context)?;
    ///
    /// assert_eq!(js_map.get_size(context)?, 0.into());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn clear(&self, context: &mut Context) -> JsResult<JsValue> {
        Map::clear(&self.inner.clone().into(), &[], context)
    }

    /// Checks if [`JsMap`] has an entry with the provided `key` value.
    ///
    /// # Example
    ///
    /// ```
    /// # use boa_engine::{
    /// #    object::builtins::JsMap,
    /// #    Context, JsValue, JsResult, js_string
    /// # };
    /// # fn main() -> JsResult<()> {
    /// # let context = &mut Context::default();
    /// let js_map = JsMap::new(context);
    /// js_map.set(js_string!("foo"), js_string!("bar"), context)?;
    ///
    /// let has_key = js_map.has(js_string!("foo"), context)?;
    ///
    /// assert_eq!(has_key, true.into());
    /// # Ok(())
    /// # }
    /// ```
    pub fn has<T>(&self, key: T, context: &mut Context) -> JsResult<JsValue>
    where
        T: Into<JsValue>,
    {
        Map::has(&self.inner.clone().into(), &[key.into()], context)
    }

    /// Executes the provided callback function for each key-value pair within the [`JsMap`].
    #[inline]
    pub fn for_each(
        &self,
        callback: JsFunction,
        this_arg: JsValue,
        context: &mut Context,
    ) -> JsResult<JsValue> {
        Map::for_each(
            &self.inner.clone().into(),
            &[callback.into(), this_arg],
            context,
        )
    }

    /// Returns a new [`JsMapIterator`] object that yields the `value` for each element within the [`JsMap`] in insertion order.
    #[inline]
    pub fn values(&self, context: &mut Context) -> JsResult<JsMapIterator> {
        let iterator_record = Map::values(&self.inner.clone().into(), &[], context)?
            .get_iterator(context, None, None)?;
        let map_iterator_object = iterator_record.iterator();
        JsMapIterator::from_object(map_iterator_object.clone())
    }
}

impl From<JsMap> for JsObject {
    #[inline]
    fn from(o: JsMap) -> Self {
        o.inner.clone()
    }
}

impl From<JsMap> for JsValue {
    #[inline]
    fn from(o: JsMap) -> Self {
        o.inner.clone().into()
    }
}

impl Deref for JsMap {
    type Target = JsObject;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl JsObjectType for JsMap {}

impl TryFromJs for JsMap {
    fn try_from_js(value: &JsValue, _context: &mut Context) -> JsResult<Self> {
        match value {
            JsValue::Object(o) => Self::from_object(o.clone()),
            _ => Err(JsNativeError::typ()
                .with_message("value is not a Map object")
                .into()),
        }
    }
}