boa_engine 0.21.1

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
use super::{Display, HashSet, JsValue, JsVariant, fmt};
use crate::{
    JsError, JsObject, JsString,
    builtins::{
        Array, Promise, error::Error, map::ordered_map::OrderedMap, promise::PromiseState,
        set::ordered_set::OrderedSet,
    },
    js_string,
    property::{PropertyDescriptor, PropertyKey},
};
use std::borrow::Cow;
use std::fmt::Write;

/// This object is used for displaying a `Value`.
#[derive(Debug, Clone, Copy)]
pub struct ValueDisplay<'value> {
    pub(super) value: &'value JsValue,
    pub(super) internals: bool,
}

impl ValueDisplay<'_> {
    /// Display internal information about value.
    ///
    /// By default this is `false`.
    #[inline]
    #[must_use]
    pub const fn internals(mut self, yes: bool) -> Self {
        self.internals = yes;
        self
    }
}

fn print_obj_value_internals(
    f: &mut fmt::Formatter<'_>,
    obj: &JsObject,
    indent: usize,
    encounters: &mut HashSet<usize>,
) -> fmt::Result {
    let object = obj.borrow();
    write!(f, "{:>indent$}__proto__: ", "")?;
    if let Some(object) = object.prototype() {
        log_object_to_internal(
            f,
            &object.clone().into(),
            encounters,
            indent.wrapping_add(4),
            true,
        )?;
    } else {
        write!(f, "{}", JsValue::null().display())?;
    }
    f.write_char(',')?;
    f.write_char('\n')
}

fn print_obj_value_props(
    f: &mut fmt::Formatter<'_>,
    obj: &JsObject,
    indent: usize,
    encounters: &mut HashSet<usize>,
    print_internals: bool,
) -> fmt::Result {
    let mut keys: Vec<_> = obj
        .borrow()
        .properties()
        .index_property_keys()
        .map(PropertyKey::from)
        .collect();
    keys.extend(obj.borrow().properties().shape.keys());

    let mut first = true;
    for key in keys {
        if first {
            first = false;
        } else {
            f.write_char(',')?;
            f.write_char('\n')?;
        }
        let val = obj
            .borrow()
            .properties()
            .get(&key)
            .expect("There should be a value");

        write!(f, "{:>width$}{}: ", "", key, width = indent)?;
        if val.is_data_descriptor() {
            let v = val.expect_value();
            log_object_to_internal(f, v, encounters, indent.wrapping_add(4), print_internals)?;
        } else {
            let display = match (val.set().is_some(), val.get().is_some()) {
                (true, true) => "Getter & Setter",
                (true, false) => "Setter",
                (false, true) => "Getter",
                _ => "No Getter/Setter",
            };
            write!(f, "{key}: {display}")?;
        }
    }
    f.write_char('\n')?;
    Ok(())
}

fn log_array_to(
    f: &mut fmt::Formatter<'_>,
    x: &JsObject,
    print_internals: bool,
    print_children: bool,
) -> fmt::Result {
    let len = x
        .borrow()
        .properties()
        .get(&js_string!("length").into())
        .expect("array object must have 'length' property")
        // FIXME: handle accessor descriptors
        .expect_value()
        .as_number()
        .map(|n| n as i32)
        .unwrap_or_default();

    if print_children {
        if len == 0 {
            return f.write_str("[]");
        }

        f.write_str("[ ")?;
        let mut first = true;
        for i in 0..len {
            if first {
                first = false;
            } else {
                f.write_str(", ")?;
            }

            // Introduce recursive call to stringify any objects
            // which are part of the Array

            // FIXME: handle accessor descriptors
            if let Some(value) = x
                .borrow()
                .properties()
                .get(&i.into())
                .and_then(|x| x.value().cloned())
            {
                log_value_to(f, &value, print_internals, false)?;
            } else {
                f.write_str("<empty>")?;
            }
        }
        write!(f, " ]")
    } else {
        write!(f, "Array({len})")
    }
}

pub(crate) fn log_value_to(
    f: &mut fmt::Formatter<'_>,
    x: &JsValue,
    print_internals: bool,
    print_children: bool,
) -> fmt::Result {
    match x.variant() {
        // We don't want to print private (compiler) or prototype properties
        JsVariant::Object(v) => {
            // Can use the private "type" field of an Object to match on
            // which type of Object it represents for special printing
            if let Some(s) = v.downcast_ref::<JsString>() {
                write!(f, "String {{ {:?} }}", s.to_std_string_escaped())
            } else if let Some(b) = v.downcast_ref::<bool>() {
                write!(f, "Boolean {{ {b} }}")
            } else if let Some(r) = v.downcast_ref::<f64>() {
                f.write_str("Number { ")?;
                format_rational(*r, f)?;
                f.write_str(" }")
            } else if v.is::<Array>() {
                log_array_to(f, &v, print_internals, print_children)
            } else if let Some(map) = v.downcast_ref::<OrderedMap<JsValue>>() {
                let size = map.len();
                if size == 0 {
                    return f.write_str("Map(0)");
                }

                if print_children {
                    f.write_str("Map { ")?;
                    let mut first = true;
                    for (key, value) in map.iter() {
                        if first {
                            first = false;
                        } else {
                            f.write_str(", ")?;
                        }
                        log_value_to(f, key, print_internals, false)?;
                        f.write_str(" → ")?;
                        log_value_to(f, value, print_internals, false)?;
                    }
                    f.write_str(" }")
                } else {
                    write!(f, "Map({size})")
                }
            } else if let Some(set) = v.downcast_ref::<OrderedSet>() {
                let size = set.len();

                if size == 0 {
                    return f.write_str("Set(0)");
                }

                if print_children {
                    f.write_str("Set { ")?;
                    let mut first = true;
                    for value in set.iter() {
                        if first {
                            first = false;
                        } else {
                            f.write_str(", ")?;
                        }
                        log_value_to(f, value, print_internals, false)?;
                    }
                    f.write_str(" }")
                } else {
                    write!(f, "Set({size})")
                }
            } else if v.is::<Error>() {
                let name: Cow<'static, str> = v
                    .get_property(&js_string!("name").into())
                    .as_ref()
                    .and_then(PropertyDescriptor::value)
                    .map_or_else(
                        || "<error>".into(),
                        |v| {
                            v.as_string()
                                .as_ref()
                                .map_or_else(
                                    || v.display().to_string(),
                                    JsString::to_std_string_escaped,
                                )
                                .into()
                        },
                    );
                let message = v
                    .get_property(&js_string!("message").into())
                    .as_ref()
                    .and_then(PropertyDescriptor::value)
                    .map(|v| {
                        v.as_string().as_ref().map_or_else(
                            || v.display().to_string(),
                            JsString::to_std_string_escaped,
                        )
                    })
                    .unwrap_or_default();
                if name.is_empty() {
                    f.write_str(&message)?;
                } else if message.is_empty() {
                    f.write_str(name.as_ref())?;
                } else {
                    write!(f, "{name}: {message}")?;
                }
                let data = v
                    .downcast_ref::<Error>()
                    .expect("already checked object type");

                if let Some(position) = &data.position.0 {
                    write!(f, "{position}")?;
                }
                Ok(())
            } else if let Some(promise) = v.downcast_ref::<Promise>() {
                f.write_str("Promise { ")?;
                match promise.state() {
                    PromiseState::Pending => f.write_str("<pending>")?,
                    PromiseState::Fulfilled(val) => Display::fmt(&val.display(), f)?,
                    PromiseState::Rejected(reason) => {
                        write!(f, "<rejected> {}", JsError::from_opaque(reason.clone()))?;
                    }
                }
                f.write_str(" }")
            } else if v.is_constructor() {
                // FIXME: ArrayBuffer is not [class ArrayBuffer] but we cannot distinguish it.
                let name = v
                    .get_property(&PropertyKey::from(js_string!("name")))
                    .and_then(|d| Some(d.value()?.as_string()?.to_std_string_escaped()));
                match name {
                    Some(name) => write!(f, "[class {name}]"),
                    None => f.write_str("[class (anonymous)]"),
                }
            } else if v.is_callable() {
                let name = v
                    .get_property(&PropertyKey::from(js_string!("name")))
                    .and_then(|d| Some(d.value()?.as_string()?.to_std_string_escaped()));
                match name {
                    Some(name) => write!(f, "[Function: {name}]"),
                    None => f.write_str("[Function (anonymous)]"),
                }
            } else {
                Display::fmt(&x.display_obj(print_internals), f)
            }
        }
        JsVariant::Null => write!(f, "null"),
        JsVariant::Undefined => write!(f, "undefined"),
        JsVariant::Boolean(v) => write!(f, "{v}"),
        JsVariant::Symbol(symbol) => {
            write!(f, "{}", symbol.descriptive_string().to_std_string_escaped())
        }
        JsVariant::String(v) => write!(f, "{:?}", v.to_std_string_escaped()),
        JsVariant::Float64(v) => format_rational(v, f),
        JsVariant::Integer32(v) => write!(f, "{v}"),
        JsVariant::BigInt(num) => write!(f, "{num}n"),
    }
}

fn log_object_to_internal(
    f: &mut fmt::Formatter<'_>,
    data: &JsValue,
    encounters: &mut HashSet<usize>,
    indent: usize,
    print_internals: bool,
) -> fmt::Result {
    if let Some(v) = data.as_object() {
        // The in-memory address of the current object
        let addr = std::ptr::from_ref(v.as_ref()).addr();

        // We need not continue if this object has already been
        // printed up the current chain
        if encounters.contains(&addr) {
            return f.write_str("[Cycle]");
        }

        // Mark the current object as encountered
        encounters.insert(addr);

        if v.is::<Array>() {
            return log_array_to(f, &v, print_internals, false);
        }

        let constructor_name = get_constructor_name_of(&v);
        if let Some(name) = constructor_name {
            write!(f, "{} ", name.to_std_string_lossy())?;
        }
        f.write_str("{\n")?;

        if print_internals {
            print_obj_value_internals(f, &v, indent, encounters)?;
        }
        print_obj_value_props(f, &v, indent, encounters, print_internals)?;
        write!(f, "{:>indent$}}}", "", indent = indent.saturating_sub(4))?;

        // If the current object is referenced in a different branch,
        // it will not cause an infinite printing loop, so it is safe to be printed again
        encounters.remove(&addr);
        Ok(())
    } else {
        // Every other type of data is printed with the display method
        log_value_to(f, data, print_internals, false)
    }
}

/// The constructor can be retrieved as `Object.getPrototypeOf(obj).constructor`.
///
/// Returns `None` if the constructor is `Object` as plain objects don't need a name.
fn get_constructor_name_of(obj: &JsObject) -> Option<JsString> {
    let prototype = obj.prototype()?;

    // To neglect out plain object
    // `Object.getPrototypeOf(Object.prototype)` => null.
    // For user created `Object.create(Object.create(null))`,
    // we also don't need to display its name.
    prototype.prototype()?;

    let constructor_property = prototype
        .borrow()
        .properties()
        .get(&PropertyKey::from(js_string!("constructor")))?;
    let constructor = constructor_property.value()?;

    let name = constructor
        .as_object()?
        .borrow()
        .properties()
        .get(&PropertyKey::from(js_string!("name")))?
        .value()?
        .as_string()?;

    Some(name)
}

impl JsValue {
    /// A helper function for specifically printing object values
    #[must_use]
    pub fn display_obj(&self, print_internals: bool) -> String {
        struct DisplayObj<'a>(&'a JsValue, bool);
        impl Display for DisplayObj<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                log_object_to_internal(f, self.0, &mut HashSet::new(), 4, self.1)
            }
        }

        DisplayObj(self, print_internals).to_string()
    }
}

impl Display for ValueDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        log_value_to(f, self.value, self.internals, true)
    }
}

/// This is different from the ECMAScript compliant number to string, in the printing of `-0`.
///
/// This function prints `-0` as `-0` instead of positive `0` as the specification says.
/// This is done to make it easier for the user of the REPL to identify what is a `-0` vs `0`,
/// since the REPL is not bound to the ECMAScript specification, we can do this.
fn format_rational(v: f64, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    if v.is_sign_negative() && v == 0.0 {
        f.write_str("-0")
    } else {
        let mut buffer = ryu_js::Buffer::new();
        f.write_str(buffer.format(v))
    }
}