nova_vm 1.0.0

Nova Virtual Machine
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Contains code for performing lexical scope entry and exit during bytecode
//! compilation, including generating proper finaliser blocks for various scope
//! exits.
//!
//! This includes:
//! - Entering and exiting declarative scopes.
//! - Entering and exiting variable scopes.
//! - Entering and exiting try-catch blocks.
//! - Closing iterators on for-of loop exit.
//! - Visiting finally blocks on try-finally block exit.

use oxc_ast::ast::LabelIdentifier;

use crate::{ecmascript::Value, engine::Instruction};

use super::{JumpIndex, executable_context::ExecutableContext};

#[derive(Debug, Clone)]
pub(super) struct ControlFlowFinallyEntry<'a> {
    pub(super) continues: Vec<(JumpIndex, Option<&'a LabelIdentifier<'a>>)>,
    pub(super) breaks: Vec<(JumpIndex, Option<&'a LabelIdentifier<'a>>)>,
    pub(super) returns: Vec<JumpIndex>,
}

#[derive(Debug, Clone)]
pub(super) struct ControlFlowLoopEntry {
    continues: Vec<JumpIndex>,
    breaks: Vec<JumpIndex>,
}

#[derive(Debug, Clone)]
pub(super) struct ControlFlowSwitchEntry {
    breaks: Vec<JumpIndex>,
}

#[derive(Debug, Clone)]
pub(super) enum ControlFlowStackEntry<'a> {
    /// A labelled statement was entered.
    LabelledStatement {
        label: &'a LabelIdentifier<'a>,
        incoming_control_flows: Option<Box<ControlFlowSwitchEntry>>,
    },
    /// A lexical scope was entered.
    LexicalScope,
    /// A variable scope was entered.
    VariableScope,
    /// A private environment was scoped.
    PrivateScope,
    /// A variable was pushed onto the stack.
    StackValue,
    /// A result variable was pushed onto the stack.
    StackResultValue,
    /// A try-catch block was entered.
    CatchBlock,
    /// An if-statement was entered.
    IfStatement,
    /// A finally-block was entered. A pending result exists on the stack.
    FinallyBlock,
    /// A try-finally-block was entered.
    TryFinallyBlock {
        jump_to_catch: JumpIndex,
        incoming_control_flows: Option<Box<ControlFlowFinallyEntry<'a>>>,
    },
    /// Traditional for or while loop. Does not require finalisation.
    Loop {
        label_set: Option<Vec<&'a LabelIdentifier<'a>>>,
        incoming_control_flows: Option<Box<ControlFlowLoopEntry>>,
    },
    /// Switch block. Does not require finalisation.
    Switch {
        label_set: Option<Vec<&'a LabelIdentifier<'a>>>,
        incoming_control_flows: Option<Box<ControlFlowSwitchEntry>>,
    },
    /// An iterator stack entry. Requires popping the iterator from the
    /// iterator stack on exit.
    IteratorStackEntry,
    /// An iterator stack entry for array destructuring. Requires closing and
    /// popping the iterator stack on exit.
    ArrayDestructuring,
    /// Synchronous for-of loop. Requires closing the iterator on exit.
    Iterator {
        label_set: Option<Vec<&'a LabelIdentifier<'a>>>,
        incoming_control_flows: Option<Box<ControlFlowLoopEntry>>,
    },
    /// Asynchronous for-await-of loop. Requires closing the iterator and
    /// awaiting the "return" call result, if any, on exit.
    AsyncIterator {
        label_set: Option<Vec<&'a LabelIdentifier<'a>>>,
        incoming_control_flows: Option<Box<ControlFlowLoopEntry>>,
    },
}

impl<'a> ControlFlowStackEntry<'a> {
    pub(super) fn add_break_source(
        &mut self,
        label: Option<&'a LabelIdentifier<'a>>,
        break_source: JumpIndex,
    ) {
        match self {
            ControlFlowStackEntry::TryFinallyBlock {
                incoming_control_flows,
                ..
            } => {
                if let Some(incoming_control_flows) = incoming_control_flows {
                    incoming_control_flows.breaks.push((break_source, label));
                } else {
                    *incoming_control_flows = Some(Box::new(ControlFlowFinallyEntry {
                        continues: vec![],
                        breaks: vec![(break_source, label)],
                        returns: vec![],
                    }));
                }
            }
            ControlFlowStackEntry::Loop {
                incoming_control_flows,
                ..
            }
            | ControlFlowStackEntry::Iterator {
                incoming_control_flows,
                ..
            }
            | ControlFlowStackEntry::AsyncIterator {
                incoming_control_flows,
                ..
            } => {
                if let Some(incoming_control_flows) = incoming_control_flows {
                    incoming_control_flows.breaks.push(break_source);
                } else {
                    *incoming_control_flows = Some(Box::new(ControlFlowLoopEntry {
                        continues: vec![],
                        breaks: vec![break_source],
                    }));
                }
            }
            ControlFlowStackEntry::LabelledStatement {
                incoming_control_flows,
                ..
            }
            | ControlFlowStackEntry::Switch {
                incoming_control_flows,
                ..
            } => {
                if let Some(incoming_control_flows) = incoming_control_flows {
                    incoming_control_flows.breaks.push(break_source);
                } else {
                    *incoming_control_flows = Some(Box::new(ControlFlowSwitchEntry {
                        breaks: vec![break_source],
                    }));
                }
            }
            _ => unreachable!(),
        }
    }

    pub(super) fn add_continue_source(
        &mut self,
        label: Option<&'a LabelIdentifier<'a>>,
        continue_source: JumpIndex,
    ) {
        match self {
            ControlFlowStackEntry::TryFinallyBlock {
                incoming_control_flows,
                ..
            } => {
                if let Some(incoming_control_flows) = incoming_control_flows {
                    incoming_control_flows
                        .continues
                        .push((continue_source, label));
                } else {
                    *incoming_control_flows = Some(Box::new(ControlFlowFinallyEntry {
                        continues: vec![(continue_source, label)],
                        breaks: vec![],
                        returns: vec![],
                    }));
                }
            }
            ControlFlowStackEntry::Loop {
                incoming_control_flows,
                ..
            }
            | ControlFlowStackEntry::Iterator {
                incoming_control_flows,
                ..
            }
            | ControlFlowStackEntry::AsyncIterator {
                incoming_control_flows,
                ..
            } => {
                if let Some(incoming_control_flows) = incoming_control_flows {
                    incoming_control_flows.continues.push(continue_source);
                } else {
                    *incoming_control_flows = Some(Box::new(ControlFlowLoopEntry {
                        continues: vec![continue_source],
                        breaks: vec![],
                    }));
                }
            }
            _ => unreachable!(),
        }
    }

    pub(super) fn add_return_source(&mut self, return_source: JumpIndex) {
        let ControlFlowStackEntry::TryFinallyBlock {
            incoming_control_flows,
            ..
        } = self
        else {
            unreachable!()
        };
        if let Some(incoming_control_flows) = incoming_control_flows {
            incoming_control_flows.returns.push(return_source);
        } else {
            *incoming_control_flows = Some(Box::new(ControlFlowFinallyEntry {
                continues: vec![],
                breaks: vec![],
                returns: vec![return_source],
            }));
        }
    }

    pub(super) fn is_break_target_for(&self, label: Option<&'a LabelIdentifier<'a>>) -> bool {
        match self {
            ControlFlowStackEntry::LabelledStatement { label: l, .. } => {
                label.is_some_and(|label| l.name == label.name)
            }
            ControlFlowStackEntry::LexicalScope
            | ControlFlowStackEntry::VariableScope
            | ControlFlowStackEntry::PrivateScope
            | ControlFlowStackEntry::StackValue
            | ControlFlowStackEntry::StackResultValue
            | ControlFlowStackEntry::CatchBlock
            | ControlFlowStackEntry::IfStatement
            | ControlFlowStackEntry::FinallyBlock
            | ControlFlowStackEntry::IteratorStackEntry { .. }
            | ControlFlowStackEntry::ArrayDestructuring => false,
            // Finally-block needs to intercept every break and continue.
            ControlFlowStackEntry::TryFinallyBlock { .. } => true,
            ControlFlowStackEntry::Loop { label_set, .. }
            | ControlFlowStackEntry::Switch { label_set, .. }
            | ControlFlowStackEntry::Iterator { label_set, .. }
            | ControlFlowStackEntry::AsyncIterator { label_set, .. } => {
                if let Some(label) = label {
                    // Labelled break only matches a breakable statement with
                    // that label.
                    let Some(label_set) = label_set else {
                        return false;
                    };
                    label_set.iter().any(|l| l.name == label.name)
                } else {
                    // Unlabelled break matches any breakable statement.
                    true
                }
            }
        }
    }

    pub(super) fn is_continue_target_for(&self, label: Option<&'a LabelIdentifier<'a>>) -> bool {
        match self {
            ControlFlowStackEntry::LabelledStatement { label: l, .. } => {
                label.is_some_and(|label| l.name == label.name)
            }
            ControlFlowStackEntry::LexicalScope
            | ControlFlowStackEntry::VariableScope
            | ControlFlowStackEntry::PrivateScope
            | ControlFlowStackEntry::StackValue
            | ControlFlowStackEntry::StackResultValue
            | ControlFlowStackEntry::FinallyBlock
            | ControlFlowStackEntry::IfStatement
            | ControlFlowStackEntry::CatchBlock { .. }
            | ControlFlowStackEntry::Switch { .. }
            | ControlFlowStackEntry::IteratorStackEntry
            | ControlFlowStackEntry::ArrayDestructuring => false,
            // Finally-block needs to intercept every break and continue.
            ControlFlowStackEntry::TryFinallyBlock { .. } => true,
            ControlFlowStackEntry::Loop { label_set, .. }
            | ControlFlowStackEntry::Iterator { label_set, .. }
            | ControlFlowStackEntry::AsyncIterator { label_set, .. } => {
                if let Some(label) = label {
                    // Labelled continue only matches a continuable statement
                    // with that label.
                    let Some(label_set) = label_set else {
                        return false;
                    };
                    label_set.iter().any(|l| l.name == label.name)
                } else {
                    // Unlabelled continue matches any continuable statement.
                    true
                }
            }
        }
    }

    /// Return cannot target any block in particular, but finally-blocks do
    /// intercept returns and thus are an indirect target for them.
    pub(super) fn is_return_target(&self) -> bool {
        // Finally-block needs to intercept return.
        matches!(self, ControlFlowStackEntry::TryFinallyBlock { .. })
    }

    /// Returns true if the entry requires finalisation on return.
    pub(super) fn requires_return_finalisation(&self, will_perform_other_finalisers: bool) -> bool {
        match self {
            // Exiting these cannot be observed by users.
            ControlFlowStackEntry::LabelledStatement { .. }
            | ControlFlowStackEntry::LexicalScope
            | ControlFlowStackEntry::VariableScope
            | ControlFlowStackEntry::PrivateScope
            | ControlFlowStackEntry::Loop { .. }
            | ControlFlowStackEntry::Switch { .. } => false,
            // If-statements, finally-blocks results, user-controlled
            // try-finally-blocks, and iterator closes must be called on
            // return.
            ControlFlowStackEntry::StackValue
            | ControlFlowStackEntry::StackResultValue
            | ControlFlowStackEntry::IfStatement
            | ControlFlowStackEntry::FinallyBlock
            | ControlFlowStackEntry::ArrayDestructuring
            | ControlFlowStackEntry::Iterator { .. }
            | ControlFlowStackEntry::AsyncIterator { .. }
            | ControlFlowStackEntry::TryFinallyBlock { .. } => true,
            // Catch blocks and the iterator stack don't require finalisation
            // on their own, but they do affect iterator closing and finally
            // block work.
            ControlFlowStackEntry::CatchBlock | ControlFlowStackEntry::IteratorStackEntry => {
                will_perform_other_finalisers
            }
        }
    }

    /// Returns true if the entry sets a defined value to the result register
    /// in compile_exit.
    pub(super) fn sets_result_during_exit(&self) -> bool {
        matches!(
            self,
            ControlFlowStackEntry::IfStatement
                | ControlFlowStackEntry::Loop { .. }
                | ControlFlowStackEntry::Iterator { .. }
                | ControlFlowStackEntry::AsyncIterator { .. }
        )
    }

    pub(super) fn compile_exit(&self, executable: &mut ExecutableContext, has_result: bool) {
        match self {
            ControlFlowStackEntry::LabelledStatement { .. } => {
                // Labelled statements don't need finalisation.
            }
            ControlFlowStackEntry::LexicalScope => {
                executable.add_instruction(Instruction::ExitDeclarativeEnvironment);
            }
            ControlFlowStackEntry::VariableScope => {
                executable.add_instruction(Instruction::ExitVariableEnvironment);
            }
            ControlFlowStackEntry::PrivateScope => {
                executable.add_instruction(Instruction::ExitPrivateEnvironment);
            }
            ControlFlowStackEntry::StackValue => {
                compile_stack_variable_exit(executable);
            }
            ControlFlowStackEntry::StackResultValue => {}
            ControlFlowStackEntry::IfStatement => {
                if has_result {
                    // OPTIMISATION: if we statically know we have a result,
                    // then we don't need to perform our
                    // `UpdateEmpty(V, undefined)`.
                    return;
                }
                compile_if_statement_exit(executable);
            }
            ControlFlowStackEntry::FinallyBlock => {
                // Exiting a finally-block abruptly should always drop the
                // result from the stack. If we know we have a result, that
                // is easiest with UpdateEmpty.
                if has_result {
                    executable.add_instruction(Instruction::UpdateEmpty);
                } else {
                    // If we might not have a result, we need to improvise.
                    // First ensure we have a result, either the previous one
                    // or a new undefined value.
                    compile_if_statement_exit(executable);
                    // Then perform the UpdateEmpty to functionally drop our
                    // result.
                    executable.add_instruction(Instruction::UpdateEmpty);
                }
            }
            ControlFlowStackEntry::CatchBlock { .. } => {
                executable.add_instruction(Instruction::PopExceptionJumpTarget);
            }
            ControlFlowStackEntry::TryFinallyBlock { .. } => {
                // Finally-blocks should always intercept incoming work.
                unreachable!()
            }
            ControlFlowStackEntry::Switch { .. } => {
                executable.add_instruction(Instruction::UpdateEmpty);
            }
            ControlFlowStackEntry::IteratorStackEntry => {
                // Enumerator loops need to pop the iterator stack.
                compile_iterator_pop(executable);
            }
            ControlFlowStackEntry::ArrayDestructuring => {
                compile_array_destructuring_exit(executable);
            }
            ControlFlowStackEntry::Loop { .. } => {
                compile_loop_exit(executable);
            }
            ControlFlowStackEntry::Iterator { .. } => {
                compile_sync_iterator_exit(executable);
            }
            ControlFlowStackEntry::AsyncIterator { .. } => {
                compile_async_iterator_exit(executable);
            }
        }
    }
}

pub(super) fn compile_iterator_pop(executable: &mut ExecutableContext) {
    executable.add_instruction(Instruction::PopExceptionJumpTarget);
    executable.add_instruction(Instruction::IteratorPop);
}

/// Helper method to compile stack variable exit handling.
pub(super) fn compile_stack_variable_exit(executable: &mut ExecutableContext) {
    executable.add_instruction(Instruction::PopStack);
}

/// Helper method to compile if-statement exit handling.
///
/// If-statements have to perform `UpdateEmpty(V, undefined)` at the end of the
/// statement.
pub(super) fn compile_if_statement_exit(executable: &mut ExecutableContext) {
    executable.add_instruction_with_constant(Instruction::LoadConstant, Value::Undefined);
    executable.add_instruction(Instruction::UpdateEmpty);
}

/// Helper method to compile loop exit handling.
///
/// Loops have an exception handler for exceptional loop exit handling: that
/// needs to be removed. Next, the loop will have placed a JavaScript Value `V`
/// onto the stack: this needs to be popped and it should become our result if
/// the exit was reached with an empty result value.
pub(super) fn compile_loop_exit(executable: &mut ExecutableContext) {
    // When breaking out of a loop its exception handler needs to be removed
    // and the pushed JavaScript stack value popped.
    executable.add_instruction(Instruction::PopExceptionJumpTarget);
    executable.add_instruction(Instruction::UpdateEmpty);
}

/// Helper method to compile array destructuring iterator exit handling.
///
/// Iterators have an exception handler for exceptional loop exit handling:
/// that needs to be removed. Array destructuring iterators must always be
/// closed as well.
pub(super) fn compile_array_destructuring_exit(executable: &mut ExecutableContext) {
    executable.add_instruction(Instruction::PopExceptionJumpTarget);
    executable.add_instruction(Instruction::IteratorClose);
}

/// Helper method to compile sync iterator exit handling.
///
/// Iterators have an exception handler for exceptional loop exit handling:
/// that needs to be removed. Next, the iterator will have placed a JavaScript
/// Value `V` onto the stack: this needs to be popped and it should become our
/// result if the exit was reached with an empty result value. Finally, the
/// iterator's "return" function, if found, must be called and its result
/// ignored.
pub(super) fn compile_sync_iterator_exit(executable: &mut ExecutableContext) {
    compile_loop_exit(executable);
    executable.add_instruction(Instruction::IteratorClose);
}

/// Helper method to compile async iterator exit handling.
///
/// Iterators have an exception handler for exceptional loop exit handling:
/// that needs to be removed. Next, the iterator will have placed a JavaScript
/// Value `V` onto the stack: this needs to be popped and it should become our
/// result if the exit was reached with an empty result value. Finally, the
/// iterator's "return" function, if found, must be called and its result
/// awaited.
pub(super) fn compile_async_iterator_exit(executable: &mut ExecutableContext) {
    compile_loop_exit(executable);
    executable.add_instruction(Instruction::AsyncIteratorClose);
    // If async iterator close returned a Value, then it'll push the previous
    // result value into the stack and perform an implicit Await.
    // We should verify that the result of the await is an object, and then
    // return the original result.
    let error_message = executable.create_string("iterator.return() returned a non-object value");
    executable.add_instruction_with_identifier(
        Instruction::VerifyIsObject,
        error_message.to_property_key(),
    );
    executable.add_instruction(Instruction::Store);
}

impl ControlFlowSwitchEntry {
    pub(super) fn compile(self, ctx: &mut ExecutableContext) {
        // Note: iterate breaks in reverse, in case the last one is our current
        // instruction. If that is the case, we can remove the last Jump and
        // make it a fallthrough.
        for break_source in self.breaks.into_iter().rev() {
            ctx.set_jump_target_here(break_source);
        }
    }
}

impl ControlFlowLoopEntry {
    pub(super) fn compile(
        self,
        continue_target: JumpIndex,
        compile_break: impl FnOnce(&mut ExecutableContext),
        ctx: &mut ExecutableContext,
    ) {
        for continue_source in self.continues {
            ctx.set_jump_target(continue_source, continue_target.clone());
        }
        if ctx.is_unreachable() && self.breaks.is_empty() {
            return;
        }
        // Note: iterate breaks in reverse, in case the last one is our current
        // instruction. If that is the case, we can remove the last Jump and
        // make it a fallthrough.
        for break_source in self.breaks.into_iter().rev() {
            ctx.set_jump_target_here(break_source);
        }
        compile_break(ctx);
    }
}