ps-boa-engine 1.1.2

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
use boa_string::StaticJsStrings;

use crate::{
    Context, JsResult, JsValue,
    builtins::typed_array::{TypedArray, typed_array_get_element},
    js_string,
    object::{internal_methods::InternalMethodPropertyContext, shape::slot::SlotAttributes},
    property::PropertyKey,
    vm::opcode::{IndexOperand, Operation, RegisterOperand},
};

/// `base[index]` for an array's dense element or a typed array element (whose [[Get]] for a valid
/// integer index never reaches the prototype chain), read without taking a reference to `base`.
#[inline(always)]
fn dense_element(base: &JsValue, index: u32) -> JsResult<Option<JsValue>> {
    let Some(base) = base.as_object_ref() else {
        return Ok(None);
    };
    if base.is_array() {
        Ok(base.borrow().properties().get_dense_property(index))
    } else if base.is::<TypedArray>() {
        Ok(Some(
            typed_array_get_element(&base, f64::from(index))?.unwrap_or_default(),
        ))
    } else {
        Ok(None)
    }
}

/// An inline cache hit for a property without a getter on an object, read without taking a
/// reference to the object.
#[inline(always)]
fn cached_property(object: &JsValue, index: IndexOperand, context: &Context) -> Option<JsValue> {
    let object = object.as_object_ref()?;
    let ic = &context.vm.frame().code_block().ic[usize::from(index)];
    let object = object.borrow();
    let slot = ic.get(object.shape())?;
    if slot.attributes.has_get() {
        return None;
    }
    Some(if slot.attributes.contains(SlotAttributes::PROTOTYPE) {
        let prototype = object
            .shape()
            .prototype()
            .expect("prototype should have value");
        let prototype = prototype.borrow();
        prototype.properties().storage[slot.index as usize].clone()
    } else {
        object.properties().storage[slot.index as usize].clone()
    })
}

fn get_by_name<const LENGTH: bool>(
    (dst, object, receiver, index): (RegisterOperand, &JsValue, &JsValue, IndexOperand),
    context: &mut Context,
) -> JsResult<()> {
    if LENGTH {
        if let Some(object) = object.as_object()
            && object.is_array()
        {
            let value = object.borrow().properties().storage[0].clone();
            context.vm.set_register(dst.into(), value);
            return Ok(());
        } else if let Some(string) = object.as_string() {
            // NOTE: Since we’re using the prototype returned directly by `base_class()`,
            //       we need to handle string primitives separately due to the
            //       string exotic internal methods.
            context
                .vm
                .set_register(dst.into(), (string.len() as u32).into());
            return Ok(());
        }
    }

    // OPTIMIZATION:
    //    Instead of calling `to_object()`, which creates a temporary wrapper object for primitive
    //    values (e.g., numbers, strings, booleans) just to query their prototype chain.
    //
    //    To prevent the creation of a temporary JsObject, we directly retrieve the prototype that
    //    `to_object()` would produce, such as `Number.prototype`, `String.prototype`, etc.
    let object = object.base_class(context)?;

    let ic = &context.vm.frame().code_block().ic[usize::from(index)];
    let object_borrowed = object.borrow();
    if let Some(slot) = ic.get(object_borrowed.shape()) {
        let mut result = if slot.attributes.contains(SlotAttributes::PROTOTYPE) {
            let prototype = object_borrowed
                .shape()
                .prototype()
                .expect("prototype should have value");
            let prototype = prototype.borrow();
            prototype.properties().storage[slot.index as usize].clone()
        } else {
            object_borrowed.properties().storage[slot.index as usize].clone()
        };

        drop(object_borrowed);
        if slot.attributes.has_get() && result.is_object() {
            result =
                result
                    .as_object()
                    .expect("should contain getter")
                    .call(receiver, &[], context)?;
        }
        context.vm.set_register(dst.into(), result);
        return Ok(());
    }

    drop(object_borrowed);

    let key: PropertyKey = ic.name.clone().into();
    // A getter may add, remove or redefine a property on its receiver. Cache
    // the slot against the shape that was actually searched, not the shape
    // left behind after user code returns.
    let lookup_shape = object.borrow().shape().clone();

    let context = &mut InternalMethodPropertyContext::new(context);
    let result = object.__get__(&key, receiver.clone(), context)?;

    // Cache the property.
    let slot = *context.slot();
    if slot.is_cacheable() {
        let ic = &context.vm.frame().code_block.ic[usize::from(index)];
        ic.set(&lookup_shape, slot);
    }

    context.vm.set_register(dst.into(), result);
    Ok(())
}

fn get_by_value<const PUSH_KEY: bool>(
    (dst, key, receiver, object): (
        RegisterOperand,
        RegisterOperand,
        RegisterOperand,
        RegisterOperand,
    ),
    context: &mut Context,
) -> JsResult<()> {
    // Fast path: a non-negative int32 key on an array's dense elements or on a typed array (whose
    // [[Get]] for a valid integer index never reaches the prototype chain), before any clone or
    // property key conversion.
    if let Some(index) = context.vm.get_register(key.into()).as_i32()
        && let Ok(index) = u32::try_from(index)
        && let Some(element) = dense_element(context.vm.get_register(object.into()), index)?
    {
        context.vm.set_register(dst.into(), element);
        return Ok(());
    }

    let key_value = context.vm.get_register(key.into()).clone();
    let base = context.vm.get_register(object.into()).clone();
    let object = base.base_class(context)?;
    let key_value = key_value.to_property_key(context)?;

    // Fast Path
    //
    // NOTE: Since we’re using the prototype returned directly by `base_class()`,
    //       we need to handle string primitives separately due to the
    //       string exotic internal methods.
    match &key_value {
        PropertyKey::Index(index) => {
            if object.is_array() {
                let object_borrowed = object.borrow();
                if let Some(element) = object_borrowed.properties().get_dense_property(index.get())
                {
                    if PUSH_KEY {
                        context.vm.set_register(key.into(), key_value.into());
                    }

                    context.vm.set_register(dst.into(), element);
                    return Ok(());
                }
            } else if let Some(string) = base.as_string() {
                let value = string
                    .code_unit_at(index.get() as usize)
                    .map_or_else(JsValue::undefined, |char| {
                        js_string!([char].as_slice()).into()
                    });

                if PUSH_KEY {
                    context.vm.set_register(key.into(), key_value.into());
                }
                context.vm.set_register(dst.into(), value);
                return Ok(());
            }
        }
        PropertyKey::String(string) if *string == StaticJsStrings::LENGTH => {
            if let Some(string) = base.as_string() {
                let value = string.len().into();

                if PUSH_KEY {
                    context.vm.set_register(key.into(), key_value.into());
                }
                context.vm.set_register(dst.into(), value);
                return Ok(());
            }
        }
        _ => {}
    }

    let receiver = context.vm.get_register(receiver.into());

    // Slow path:
    let result = object.__get__(
        &key_value,
        receiver.clone(),
        &mut InternalMethodPropertyContext::new(context),
    )?;

    if PUSH_KEY {
        context.vm.set_register(key.into(), key_value.into());
    }
    context.vm.set_register(dst.into(), result);
    Ok(())
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct GetLengthProperty;

impl GetLengthProperty {
    #[inline(always)]
    pub(crate) fn operation(
        (dst, object, index): (RegisterOperand, RegisterOperand, IndexOperand),
        context: &mut Context,
    ) -> JsResult<()> {
        let value = context.vm.get_register(object.into());
        let length = value.as_object_ref().and_then(|object| {
            object
                .is_array()
                .then(|| object.borrow().properties().storage[0].clone())
        });
        if let Some(length) = length {
            context.vm.set_register(dst.into(), length);
            return Ok(());
        }
        let object = context.vm.get_register(object.into()).clone();
        get_by_name::<true>((dst, &object, &object, index), context)
    }
}

impl Operation for GetLengthProperty {
    const NAME: &'static str = "GetLengthProperty";
    const INSTRUCTION: &'static str = "INST - GetLengthProperty";
    const COST: u8 = 4;
}

/// `GetPropertyByName` implements the Opcode Operation for `Opcode::GetPropertyByName`
///
/// Operation:
///  - Get a property by name from an object.
#[derive(Debug, Clone, Copy)]
pub(crate) struct GetPropertyByName;

impl GetPropertyByName {
    #[inline(always)]
    pub(crate) fn operation(
        (dst, object, index): (RegisterOperand, RegisterOperand, IndexOperand),
        context: &mut Context,
    ) -> JsResult<()> {
        if let Some(result) =
            cached_property(context.vm.get_register(object.into()), index, context)
        {
            context.vm.set_register(dst.into(), result);
            return Ok(());
        }
        let object = context.vm.get_register(object.into()).clone();
        get_by_name::<false>((dst, &object, &object, index), context)
    }
}

impl Operation for GetPropertyByName {
    const NAME: &'static str = "GetPropertyByName";
    const INSTRUCTION: &'static str = "INST - GetPropertyByName";
    const COST: u8 = 4;
}

/// `GetPropertyByNameWithThis` implements the Opcode Operation for `Opcode::GetPropertyByNameWithThis`
///
/// Operation:
///  - Get a property by name from an object with this.
#[derive(Debug, Clone, Copy)]
pub(crate) struct GetPropertyByNameWithThis;

impl GetPropertyByNameWithThis {
    #[inline(always)]
    pub(crate) fn operation(
        (dst, receiver, value, index): (
            RegisterOperand,
            RegisterOperand,
            RegisterOperand,
            IndexOperand,
        ),
        context: &mut Context,
    ) -> JsResult<()> {
        if let Some(result) = cached_property(context.vm.get_register(value.into()), index, context)
        {
            context.vm.set_register(dst.into(), result);
            return Ok(());
        }
        let receiver = context.vm.get_register(receiver.into()).clone();
        let object = context.vm.get_register(value.into()).clone();
        get_by_name::<false>((dst, &object, &receiver, index), context)
    }
}

impl Operation for GetPropertyByNameWithThis {
    const NAME: &'static str = "GetPropertyByNameWithThis";
    const INSTRUCTION: &'static str = "INST - GetPropertyByNameWithThis";
    const COST: u8 = 4;
}

/// `GetPropertyByValue` implements the Opcode Operation for `Opcode::GetPropertyByValue`
///
/// Operation:
///  - Get a property by value from an object and store it in dst.
#[derive(Debug, Clone, Copy)]
pub(crate) struct GetPropertyByValue;

impl GetPropertyByValue {
    #[inline(always)]
    pub(crate) fn operation(
        args: (
            RegisterOperand,
            RegisterOperand,
            RegisterOperand,
            RegisterOperand,
        ),
        context: &mut Context,
    ) -> JsResult<()> {
        get_by_value::<false>(args, context)
    }
}

impl Operation for GetPropertyByValue {
    const NAME: &'static str = "GetPropertyByValue";
    const INSTRUCTION: &'static str = "INST - GetPropertyByValue";
    const COST: u8 = 4;
}

/// `GetPropertyByValuePush` implements the Opcode Operation for `Opcode::GetPropertyByValuePush`
///
/// Operation:
///  - Get a property by value from an object and store the key and value in registers.
#[derive(Debug, Clone, Copy)]
pub(crate) struct GetPropertyByValuePush;

impl GetPropertyByValuePush {
    #[inline(always)]
    pub(crate) fn operation(
        args: (
            RegisterOperand,
            RegisterOperand,
            RegisterOperand,
            RegisterOperand,
        ),
        context: &mut Context,
    ) -> JsResult<()> {
        get_by_value::<true>(args, context)
    }
}

impl Operation for GetPropertyByValuePush {
    const NAME: &'static str = "GetPropertyByValuePush";
    const INSTRUCTION: &'static str = "INST - GetPropertyByValuePush";
    const COST: u8 = 4;
}

/// `GetPropertyByIndex` implements the Opcode Operation for `Opcode::GetPropertyByIndex`
///
/// Operation:
///  - Get a property by a constant array index from an object, like `object[0]`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct GetPropertyByIndex;

impl GetPropertyByIndex {
    #[inline(always)]
    pub(crate) fn operation(
        (dst, object, index): (RegisterOperand, RegisterOperand, IndexOperand),
        context: &mut Context,
    ) -> JsResult<()> {
        let index = u32::from(index);

        // Fast path, as in `GetPropertyByValue`.
        if let Some(element) = dense_element(context.vm.get_register(object.into()), index)? {
            context.vm.set_register(dst.into(), element);
            return Ok(());
        }

        let base = context.vm.get_register(object.into()).clone();
        if let Some(string) = base.as_string() {
            let value = string
                .code_unit_at(index as usize)
                .map_or_else(JsValue::undefined, |char| {
                    js_string!([char].as_slice()).into()
                });
            context.vm.set_register(dst.into(), value);
            return Ok(());
        }

        // Slow path: `object[index]` with the index as the key.
        let object = base.base_class(context)?;
        let result = object.__get__(
            &PropertyKey::from(index),
            base,
            &mut InternalMethodPropertyContext::new(context),
        )?;
        context.vm.set_register(dst.into(), result);
        Ok(())
    }
}

impl Operation for GetPropertyByIndex {
    const NAME: &'static str = "GetPropertyByIndex";
    const INSTRUCTION: &'static str = "INST - GetPropertyByIndex";
    const COST: u8 = 3;
}