boa_engine 0.17.0

Boa is a Javascript lexer, parser and compiler written in Rust. Currently, it has support for some of the language.
Documentation
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
use boa_macros::utf16;

use crate::{
    builtins::{array_buffer::SharedMemoryOrder, typed_array::integer_indexed_object::ContentType},
    object::JsObject,
    property::{PropertyDescriptor, PropertyKey},
    Context, JsResult, JsValue,
};

use super::{InternalObjectMethods, ORDINARY_INTERNAL_METHODS};

/// Definitions of the internal object methods for integer-indexed exotic objects.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-integer-indexed-exotic-objects
pub(crate) static INTEGER_INDEXED_EXOTIC_INTERNAL_METHODS: InternalObjectMethods =
    InternalObjectMethods {
        __get_own_property__: integer_indexed_exotic_get_own_property,
        __has_property__: integer_indexed_exotic_has_property,
        __define_own_property__: integer_indexed_exotic_define_own_property,
        __get__: integer_indexed_exotic_get,
        __set__: integer_indexed_exotic_set,
        __delete__: integer_indexed_exotic_delete,
        __own_property_keys__: integer_indexed_exotic_own_property_keys,
        ..ORDINARY_INTERNAL_METHODS
    };

/// `[[GetOwnProperty]]` internal method for Integer-Indexed exotic objects.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-integer-indexed-exotic-objects-getownproperty-p
pub(crate) fn integer_indexed_exotic_get_own_property(
    obj: &JsObject,
    key: &PropertyKey,
    context: &mut Context<'_>,
) -> JsResult<Option<PropertyDescriptor>> {
    // 1. If Type(P) is String, then
    // a. Let numericIndex be ! CanonicalNumericIndexString(P).
    // b. If numericIndex is not undefined, then
    match key {
        PropertyKey::Index(index) => {
            // i. Let value be ! IntegerIndexedElementGet(O, numericIndex).
            // ii. If value is undefined, return undefined.
            // iii. Return the PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.
            Ok(
                integer_indexed_element_get(obj, u64::from(*index)).map(|v| {
                    PropertyDescriptor::builder()
                        .value(v)
                        .writable(true)
                        .enumerable(true)
                        .configurable(true)
                        .build()
                }),
            )
        }
        // The following step is taken from https://tc39.es/ecma262/#sec-isvalidintegerindex :
        //     Step 3. If index is -0𝔽, return false.
        PropertyKey::String(string) if string == utf16!("-0") => Ok(None),
        key => {
            // 2. Return OrdinaryGetOwnProperty(O, P).
            super::ordinary_get_own_property(obj, key, context)
        }
    }
}

/// `[[HasProperty]]` internal method for Integer-Indexed exotic objects.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-integer-indexed-exotic-objects-hasproperty-p
pub(crate) fn integer_indexed_exotic_has_property(
    obj: &JsObject,
    key: &PropertyKey,
    context: &mut Context<'_>,
) -> JsResult<bool> {
    // 1. If Type(P) is String, then
    // a. Let numericIndex be ! CanonicalNumericIndexString(P).
    match key {
        PropertyKey::Index(index) => {
            // b. If numericIndex is not undefined, return ! IsValidIntegerIndex(O, numericIndex).
            Ok(is_valid_integer_index(obj, u64::from(*index)))
        }
        // The following step is taken from https://tc39.es/ecma262/#sec-isvalidintegerindex :
        //     Step 3. If index is -0𝔽, return false.
        PropertyKey::String(string) if string == utf16!("-0") => Ok(false),
        key => {
            // 2. Return ? OrdinaryHasProperty(O, P).
            super::ordinary_has_property(obj, key, context)
        }
    }
}

/// `[[DefineOwnProperty]]` internal method for Integer-Indexed exotic objects.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-integer-indexed-exotic-objects-defineownproperty-p-desc
pub(crate) fn integer_indexed_exotic_define_own_property(
    obj: &JsObject,
    key: &PropertyKey,
    desc: PropertyDescriptor,
    context: &mut Context<'_>,
) -> JsResult<bool> {
    // 1. If Type(P) is String, then
    // a. Let numericIndex be ! CanonicalNumericIndexString(P).
    // b. If numericIndex is not undefined, then
    match key {
        &PropertyKey::Index(index) => {
            // i. If ! IsValidIntegerIndex(O, numericIndex) is false, return false.
            // ii. If Desc has a [[Configurable]] field and if Desc.[[Configurable]] is false, return false.
            // iii. If Desc has an [[Enumerable]] field and if Desc.[[Enumerable]] is false, return false.
            // v. If Desc has a [[Writable]] field and if Desc.[[Writable]] is false, return false.
            // iv. If ! IsAccessorDescriptor(Desc) is true, return false.
            if !is_valid_integer_index(obj, u64::from(index))
                || !desc
                    .configurable()
                    .or_else(|| desc.enumerable())
                    .or_else(|| desc.writable())
                    .unwrap_or(true)
                || desc.is_accessor_descriptor()
            {
                return Ok(false);
            }

            // vi. If Desc has a [[Value]] field, perform ? IntegerIndexedElementSet(O, numericIndex, Desc.[[Value]]).
            if let Some(value) = desc.value() {
                integer_indexed_element_set(obj, index as usize, value, context)?;
            }

            // vii. Return true.
            Ok(true)
        }
        PropertyKey::String(string) if string == utf16!("-0") => Ok(false),
        key => {
            // 2. Return ! OrdinaryDefineOwnProperty(O, P, Desc).
            super::ordinary_define_own_property(obj, key, desc, context)
        }
    }
}

/// Internal method `[[Get]]` for Integer-Indexed exotic objects.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-integer-indexed-exotic-objects-get-p-receiver
pub(crate) fn integer_indexed_exotic_get(
    obj: &JsObject,
    key: &PropertyKey,
    receiver: JsValue,
    context: &mut Context<'_>,
) -> JsResult<JsValue> {
    // 1. If Type(P) is String, then
    // a. Let numericIndex be ! CanonicalNumericIndexString(P).
    // b. If numericIndex is not undefined, then
    match key {
        PropertyKey::Index(index) => {
            // i. Return ! IntegerIndexedElementGet(O, numericIndex).
            Ok(integer_indexed_element_get(obj, u64::from(*index)).unwrap_or_default())
        }
        // The following step is taken from https://tc39.es/ecma262/#sec-isvalidintegerindex :
        //     Step 3. If index is -0𝔽, return false.
        PropertyKey::String(string) if string == utf16!("-0") => Ok(JsValue::undefined()),
        key => {
            // 2. Return ? OrdinaryGet(O, P, Receiver).
            super::ordinary_get(obj, key, receiver, context)
        }
    }
}

/// Internal method `[[Set]]` for Integer-Indexed exotic objects.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-integer-indexed-exotic-objects-set-p-v-receiver
pub(crate) fn integer_indexed_exotic_set(
    obj: &JsObject,
    key: PropertyKey,
    value: JsValue,
    receiver: JsValue,
    context: &mut Context<'_>,
) -> JsResult<bool> {
    // 1. If Type(P) is String, then
    // a. Let numericIndex be ! CanonicalNumericIndexString(P).
    // b. If numericIndex is not undefined, then
    match key {
        PropertyKey::Index(index) => {
            // i. Perform ? IntegerIndexedElementSet(O, numericIndex, V).
            integer_indexed_element_set(obj, index as usize, &value, context)?;

            // ii. Return true.
            Ok(true)
        }
        // The following step is taken from https://tc39.es/ecma262/#sec-isvalidintegerindex :
        //     Step 3. If index is -0𝔽, return false.
        PropertyKey::String(string) if &string == utf16!("-0") => Ok(false),
        key => {
            // 2. Return ? OrdinarySet(O, P, V, Receiver).
            super::ordinary_set(obj, key, value, receiver, context)
        }
    }
}

/// Internal method `[[Delete]]` for Integer-Indexed exotic objects.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-integer-indexed-exotic-objects-delete-p
pub(crate) fn integer_indexed_exotic_delete(
    obj: &JsObject,
    key: &PropertyKey,
    context: &mut Context<'_>,
) -> JsResult<bool> {
    // 1. If Type(P) is String, then
    // a. Let numericIndex be ! CanonicalNumericIndexString(P).
    // b. If numericIndex is not undefined, then
    match key {
        PropertyKey::Index(index) => {
            // i. If ! IsValidIntegerIndex(O, numericIndex) is false, return true; else return false.
            Ok(!is_valid_integer_index(obj, u64::from(*index)))
        }
        // The following step is taken from https://tc39.es/ecma262/#sec-isvalidintegerindex :
        //     Step 3. If index is -0𝔽, return false.
        PropertyKey::String(string) if string == utf16!("-0") => {
            let obj = obj.borrow();
            let inner = obj.as_typed_array().expect(
                "integer indexed exotic method should only be callable from integer indexed objects",
            );
            // 1. If IsValidIntegerIndex(O, numericIndex) is false, return true; else return false.
            //    From IsValidIntegerIndex:
            //        1. If IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is true, return false.
            //        3. If index is -0𝔽, return false.
            //
            // NOTE: They are negated, so it should return true.
            if inner.is_detached() {
                return Ok(true);
            }
            Ok(true)
        }
        key => {
            // 2. Return ? OrdinaryDelete(O, P).
            super::ordinary_delete(obj, key, context)
        }
    }
}

/// Internal method `[[OwnPropertyKeys]]` for Integer-Indexed exotic objects.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-integer-indexed-exotic-objects-ownpropertykeys
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn integer_indexed_exotic_own_property_keys(
    obj: &JsObject,
    _context: &mut Context<'_>,
) -> JsResult<Vec<PropertyKey>> {
    let obj = obj.borrow();
    let inner = obj.as_typed_array().expect(
        "integer indexed exotic method should only be callable from integer indexed objects",
    );

    // 1. Let keys be a new empty List.
    let mut keys = if inner.is_detached() {
        vec![]
    } else {
        // 2. If IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is false, then
        //     a. For each integer i starting with 0 such that i < O.[[ArrayLength]], in ascending order, do
        //         i. Add ! ToString(𝔽(i)) as the last element of keys.
        (0..inner.array_length())
            .map(|index| PropertyKey::Index(index as u32))
            .collect()
    };

    // 3. For each own property key P of O such that Type(P) is String and P is not an array index, in ascending chronological order of property creation, do
    //     a. Add P as the last element of keys.
    //
    // 4. For each own property key P of O such that Type(P) is Symbol, in ascending chronological order of property creation, do
    //     a. Add P as the last element of keys.
    keys.extend(obj.properties.shape.keys());

    // 5. Return keys.
    Ok(keys)
}

/// Abstract operation `IsValidIntegerIndex ( O, index )`.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-isvalidintegerindex
pub(crate) fn is_valid_integer_index(obj: &JsObject, index: u64) -> bool {
    let obj = obj.borrow();
    let inner = obj.as_typed_array().expect(
        "integer indexed exotic method should only be callable from integer indexed objects",
    );
    // 1. If IsDetachedBuffer(O.[[ViewedArrayBuffer]]) is true, return false.
    //
    // SKIPPED: 2. If ! IsIntegralNumber(index) is false, return false.
    // NOTE: This step has already been done when we construct a PropertyKey.
    //
    // MOVED: 3. If index is -0𝔽, return false.
    // NOTE: This step has been moved into the callers of this functions,
    //       once we get the index it is already converted into unsigned integer
    //       index, it cannot be `-0`.

    // 4. If ℝ(index) < 0 or ℝ(index) ≥ O.[[ArrayLength]], return false.
    // 5. Return true.

    !inner.is_detached() && index < inner.array_length()
}

/// Abstract operation `IntegerIndexedElementGet ( O, index )`.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-integerindexedelementget
fn integer_indexed_element_get(obj: &JsObject, index: u64) -> Option<JsValue> {
    // 1. If ! IsValidIntegerIndex(O, index) is false, return undefined.
    if !is_valid_integer_index(obj, index) {
        return None;
    }

    let obj = obj.borrow();
    let inner = obj
        .as_typed_array()
        .expect("Already checked for detached buffer");
    let buffer_obj = inner
        .viewed_array_buffer()
        .expect("Already checked for detached buffer");
    let buffer_obj_borrow = buffer_obj.borrow();
    let buffer = buffer_obj_borrow
        .as_array_buffer()
        .expect("Already checked for detached buffer");

    // 2. Let offset be O.[[ByteOffset]].
    let offset = inner.byte_offset();

    // 3. Let arrayTypeName be the String value of O.[[TypedArrayName]].
    // 6. Let elementType be the Element Type value in Table 73 for arrayTypeName.
    let elem_type = inner.typed_array_name();

    // 4. Let elementSize be the Element Size value specified in Table 73 for arrayTypeName.
    let size = elem_type.element_size();

    // 5. Let indexedPosition be (ℝ(index) × elementSize) + offset.
    let indexed_position = (index * size) + offset;

    // 7. Return GetValueFromBuffer(O.[[ViewedArrayBuffer]], indexedPosition, elementType, true, Unordered).
    Some(buffer.get_value_from_buffer(
        indexed_position,
        elem_type,
        true,
        SharedMemoryOrder::Unordered,
        None,
    ))
}

/// Abstract operation `IntegerIndexedElementSet ( O, index, value )`.
///
/// More information:
///  - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-integerindexedelementset
fn integer_indexed_element_set(
    obj: &JsObject,
    index: usize,
    value: &JsValue,
    context: &mut Context<'_>,
) -> JsResult<()> {
    let obj_borrow = obj.borrow();
    let inner = obj_borrow.as_typed_array().expect(
        "integer indexed exotic method should only be callable from integer indexed objects",
    );

    let num_value = if inner.typed_array_name().content_type() == ContentType::BigInt {
        // 1. If O.[[ContentType]] is BigInt, let numValue be ? ToBigInt(value).
        value.to_bigint(context)?.into()
    } else {
        // 2. Otherwise, let numValue be ? ToNumber(value).
        value.to_number(context)?.into()
    };

    // 3. If ! IsValidIntegerIndex(O, index) is true, then
    if is_valid_integer_index(obj, index as u64) {
        // a. Let offset be O.[[ByteOffset]].
        let offset = inner.byte_offset();

        // b. Let arrayTypeName be the String value of O.[[TypedArrayName]].
        // e. Let elementType be the Element Type value in Table 73 for arrayTypeName.
        let elem_type = inner.typed_array_name();

        // c. Let elementSize be the Element Size value specified in Table 73 for arrayTypeName.
        let size = elem_type.element_size();

        // d. Let indexedPosition be (ℝ(index) × elementSize) + offset.
        let indexed_position = (index as u64 * size) + offset;

        let buffer_obj = inner
            .viewed_array_buffer()
            .expect("Already checked for detached buffer");
        let mut buffer_obj_borrow = buffer_obj.borrow_mut();
        let buffer = buffer_obj_borrow
            .as_array_buffer_mut()
            .expect("Already checked for detached buffer");

        // f. Perform SetValueInBuffer(O.[[ViewedArrayBuffer]], indexedPosition, elementType, numValue, true, Unordered).
        buffer
            .set_value_in_buffer(
                indexed_position,
                elem_type,
                &num_value,
                SharedMemoryOrder::Unordered,
                None,
                context,
            )
            .expect("SetValueInBuffer cannot fail here");
    }

    // 4. Return NormalCompletion(undefined).
    Ok(())
}