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
432
433
434
435
436
437
438
439
440
441
442
//! Boa's ECMAScript Virtual Machine
//!
//! The Virtual Machine (VM) handles generating instructions, then executing them.
//! This module will provide an instruction set for the AST to use, various traits,
//! plus an interpreter to execute those instructions

#[cfg(feature = "fuzz")]
use crate::JsNativeError;
use crate::{
    builtins::async_generator::{AsyncGenerator, AsyncGeneratorState},
    environments::{DeclarativeEnvironment, EnvironmentStack},
    script::Script,
    vm::code_block::Readable,
    Context, JsError, JsObject, JsResult, JsValue, Module,
};

use boa_gc::{custom_trace, Finalize, Gc, Trace};
use boa_profiler::Profiler;
use std::mem::size_of;

#[cfg(feature = "trace")]
use boa_interner::ToInternedString;
#[cfg(feature = "trace")]
use std::time::Instant;

mod call_frame;
mod code_block;
mod completion_record;
mod opcode;

mod runtime_limits;

#[cfg(feature = "flowgraph")]
pub mod flowgraph;

pub use runtime_limits::RuntimeLimits;
pub use {call_frame::CallFrame, code_block::CodeBlock, opcode::Opcode};

pub(crate) use {
    call_frame::GeneratorResumeKind,
    code_block::{
        create_function_object, create_function_object_fast, create_generator_function_object,
        CodeBlockFlags,
    },
    completion_record::CompletionRecord,
    opcode::BindingOpcode,
};

#[cfg(test)]
mod tests;

/// Virtual Machine.
#[derive(Debug)]
pub struct Vm {
    pub(crate) frames: Vec<CallFrame>,
    pub(crate) stack: Vec<JsValue>,
    pub(crate) err: Option<JsError>,
    pub(crate) environments: EnvironmentStack,
    #[cfg(feature = "trace")]
    pub(crate) trace: bool,
    pub(crate) runtime_limits: RuntimeLimits,
    pub(crate) active_function: Option<JsObject>,
    pub(crate) active_runnable: Option<ActiveRunnable>,
}

/// Active runnable in the current vm context.
#[derive(Debug, Clone, Finalize)]
pub(crate) enum ActiveRunnable {
    Script(Script),
    Module(Module),
}

unsafe impl Trace for ActiveRunnable {
    custom_trace!(this, {
        match this {
            Self::Script(script) => mark(script),
            Self::Module(module) => mark(module),
        }
    });
}

impl Vm {
    /// Creates a new virtual machine.
    pub(crate) fn new(global: Gc<DeclarativeEnvironment>) -> Self {
        Self {
            frames: Vec::with_capacity(16),
            stack: Vec::with_capacity(1024),
            environments: EnvironmentStack::new(global),
            err: None,
            #[cfg(feature = "trace")]
            trace: false,
            runtime_limits: RuntimeLimits::default(),
            active_function: None,
            active_runnable: None,
        }
    }

    /// Push a value on the stack.
    pub(crate) fn push<T>(&mut self, value: T)
    where
        T: Into<JsValue>,
    {
        self.stack.push(value.into());
    }

    /// Pop a value off the stack.
    ///
    /// # Panics
    ///
    /// If there is nothing to pop, then this will panic.
    #[track_caller]
    pub(crate) fn pop(&mut self) -> JsValue {
        self.stack.pop().expect("stack was empty")
    }

    #[track_caller]
    pub(crate) fn read<T: Readable>(&mut self) -> T {
        let value = self.frame().code_block.read::<T>(self.frame().pc as usize);
        self.frame_mut().pc += size_of::<T>() as u32;
        value
    }

    /// Retrieves the VM frame
    ///
    /// # Panics
    ///
    /// If there is no frame, then this will panic.
    #[track_caller]
    pub(crate) fn frame(&self) -> &CallFrame {
        self.frames.last().expect("no frame found")
    }

    /// Retrieves the VM frame mutably
    ///
    /// # Panics
    ///
    /// If there is no frame, then this will panic.
    #[track_caller]
    pub(crate) fn frame_mut(&mut self) -> &mut CallFrame {
        self.frames.last_mut().expect("no frame found")
    }

    pub(crate) fn push_frame(&mut self, frame: CallFrame) {
        self.frames.push(frame);
    }

    pub(crate) fn pop_frame(&mut self) -> Option<CallFrame> {
        self.frames.pop()
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum CompletionType {
    Normal,
    Return,
    Throw,
}

impl Context<'_> {
    fn execute_instruction(&mut self) -> JsResult<CompletionType> {
        let opcode: Opcode = {
            let _timer = Profiler::global().start_event("Opcode retrieval", "vm");

            let frame = self.vm.frame_mut();

            let pc = frame.pc;
            let opcode = Opcode::from(frame.code_block.bytecode[pc as usize]);
            frame.pc += 1;
            opcode
        };

        let _timer = Profiler::global().start_event(opcode.as_instruction_str(), "vm");

        opcode.execute(self)
    }

    pub(crate) fn run(&mut self) -> CompletionRecord {
        #[cfg(feature = "trace")]
        const COLUMN_WIDTH: usize = 26;
        #[cfg(feature = "trace")]
        const TIME_COLUMN_WIDTH: usize = COLUMN_WIDTH / 2;
        #[cfg(feature = "trace")]
        const OPCODE_COLUMN_WIDTH: usize = COLUMN_WIDTH;
        #[cfg(feature = "trace")]
        const OPERAND_COLUMN_WIDTH: usize = COLUMN_WIDTH;
        #[cfg(feature = "trace")]
        const NUMBER_OF_COLUMNS: usize = 4;

        let _timer = Profiler::global().start_event("run", "vm");

        #[cfg(feature = "trace")]
        if self.vm.trace {
            let msg = if self.vm.frames.last().is_some() {
                " Call Frame "
            } else {
                " VM Start "
            };

            println!(
                "{}\n",
                self.vm
                    .frame()
                    .code_block
                    .to_interned_string(self.interner())
            );
            println!(
                "{msg:-^width$}",
                width = COLUMN_WIDTH * NUMBER_OF_COLUMNS - 10
            );
            println!(
                "{:<TIME_COLUMN_WIDTH$} {:<OPCODE_COLUMN_WIDTH$} {:<OPERAND_COLUMN_WIDTH$} Top Of Stack\n",
                "Time",
                "Opcode",
                "Operands",
            );
        }

        let current_stack_length = self.vm.stack.len();
        self.vm
            .frame_mut()
            .set_frame_pointer(current_stack_length as u32);

        // If the current executing function is an async function we have to resolve/reject it's promise at the end.
        // The relevant spec section is 3. in [AsyncBlockStart](https://tc39.es/ecma262/#sec-asyncblockstart).
        let promise_capability = self.vm.frame().promise_capability.clone();

        let execution_completion = loop {
            // 1. Exit the execution loop if program counter ever is equal to or exceeds the amount of instructions
            if self.vm.frame().code_block.bytecode.len() <= self.vm.frame().pc as usize {
                break CompletionType::Normal;
            }

            #[cfg(feature = "fuzz")]
            {
                if self.instructions_remaining == 0 {
                    let err = JsError::from_native(JsNativeError::no_instructions_remain());
                    self.vm.err = Some(err);
                    break CompletionType::Throw;
                }
                self.instructions_remaining -= 1;
            }

            // 1. Run the next instruction.
            #[cfg(feature = "trace")]
            let result = if self.vm.trace || self.vm.frame().code_block.traceable() {
                let mut pc = self.vm.frame().pc as usize;
                let opcode: Opcode = self
                    .vm
                    .frame()
                    .code_block
                    .read::<u8>(pc)
                    .try_into()
                    .expect("invalid opcode");
                let operands = self
                    .vm
                    .frame()
                    .code_block
                    .instruction_operands(&mut pc, self.interner());

                let instant = Instant::now();
                let result = self.execute_instruction();

                let duration = instant.elapsed();
                println!(
                    "{:<TIME_COLUMN_WIDTH$} {:<OPCODE_COLUMN_WIDTH$} {operands:<OPERAND_COLUMN_WIDTH$} {}",
                    format!("{}μs", duration.as_micros()),
                    opcode.as_str(),
                    match self.vm.stack.last() {
                        Some(value) if value.is_callable() => "[function]".to_string(),
                        Some(value) if value.is_object() => "[object]".to_string(),
                        Some(value) => value.display().to_string(),
                        None => "<empty>".to_string(),
                    },
                );

                result
            } else {
                self.execute_instruction()
            };

            #[cfg(not(feature = "trace"))]
            let result = self.execute_instruction();

            // 2. Evaluate the result of executing the instruction.
            match result {
                Ok(CompletionType::Normal) => {}
                Ok(CompletionType::Return) => {
                    break CompletionType::Return;
                }
                Ok(CompletionType::Throw) => {
                    break CompletionType::Throw;
                }
                Err(err) => {
                    #[cfg(feature = "fuzz")]
                    {
                        if let Some(native_error) = err.as_native() {
                            // If we hit the execution step limit, bubble up the error to the
                            // (Rust) caller instead of trying to handle as an exception.
                            if native_error.is_no_instructions_remain() {
                                self.vm.err = Some(err);
                                break CompletionType::Throw;
                            }
                        }
                    }

                    if let Some(native_error) = err.as_native() {
                        // If we hit the execution step limit, bubble up the error to the
                        // (Rust) caller instead of trying to handle as an exception.
                        if native_error.is_runtime_limit() {
                            self.vm.err = Some(err);
                            break CompletionType::Throw;
                        }
                    }

                    self.vm.err = Some(err);

                    // If this frame has not evaluated the throw as an AbruptCompletion, then evaluate it
                    let evaluation = Opcode::Throw
                        .execute(self)
                        .expect("Opcode::Throw cannot return Err");

                    if evaluation == CompletionType::Normal {
                        continue;
                    }

                    break CompletionType::Throw;
                }
            }
        };

        // Early return immediately after loop.
        if self.vm.frame().r#yield {
            self.vm.frame_mut().r#yield = false;
            let result = self.vm.pop();
            return CompletionRecord::Return(result);
        }

        #[cfg(feature = "trace")]
        if self.vm.trace {
            println!("\nStack:");
            if self.vm.stack.is_empty() {
                println!("    <empty>");
            } else {
                for (i, value) in self.vm.stack.iter().enumerate() {
                    println!(
                        "{i:04}{:<width$} {}",
                        "",
                        if value.is_callable() {
                            "[function]".to_string()
                        } else if value.is_object() {
                            "[object]".to_string()
                        } else {
                            value.display().to_string()
                        },
                        width = COLUMN_WIDTH / 2 - 4,
                    );
                }
            }
            println!("\n");
        }

        if execution_completion == CompletionType::Throw
            || execution_completion == CompletionType::Return
        {
            self.vm.frame_mut().abrupt_completion = None;
        }
        self.vm.stack.truncate(self.vm.frame().fp as usize);

        // Determine the execution result
        let execution_result = self.vm.frame_mut().return_value.clone();

        if let Some(promise) = promise_capability {
            match execution_completion {
                CompletionType::Normal => {
                    promise
                        .resolve()
                        .call(&JsValue::undefined(), &[], self)
                        .expect("cannot fail per spec");
                }
                CompletionType::Return => {
                    promise
                        .resolve()
                        .call(&JsValue::undefined(), &[execution_result.clone()], self)
                        .expect("cannot fail per spec");
                }
                CompletionType::Throw => {
                    let err = self.vm.err.take().expect("Take must exist on a Throw");
                    promise
                        .reject()
                        .call(&JsValue::undefined(), &[err.to_opaque(self)], self)
                        .expect("cannot fail per spec");
                    self.vm.err = Some(err);
                }
            }
        } else if let Some(generator_object) = self.vm.frame().async_generator.clone() {
            // Step 3.e-g in [AsyncGeneratorStart](https://tc39.es/ecma262/#sec-asyncgeneratorstart)
            let mut generator_object_mut = generator_object.borrow_mut();
            let generator = generator_object_mut
                .as_async_generator_mut()
                .expect("must be async generator");

            generator.state = AsyncGeneratorState::Completed;
            generator.context = None;

            let next = generator
                .queue
                .pop_front()
                .expect("must have item in queue");
            drop(generator_object_mut);

            if execution_completion == CompletionType::Throw {
                AsyncGenerator::complete_step(
                    &next,
                    Err(self
                        .vm
                        .err
                        .take()
                        .expect("err must exist on a Completion::Throw")),
                    true,
                    None,
                    self,
                );
            } else {
                AsyncGenerator::complete_step(&next, Ok(execution_result), true, None, self);
            }
            AsyncGenerator::drain_queue(&generator_object, self);

            return CompletionRecord::Normal(JsValue::undefined());
        }

        // Any valid return statement is re-evaluated as a normal completion vs. return (yield).
        if execution_completion == CompletionType::Throw {
            return CompletionRecord::Throw(
                self.vm
                    .err
                    .take()
                    .expect("Err must exist for a CompletionType::Throw"),
            );
        }
        CompletionRecord::Normal(execution_result)
    }
}