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
// 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/.

use std::collections::VecDeque;

use crate::{
    ecmascript::{
        Agent, ArgumentsList, AsyncGeneratorHeapData, AsyncGeneratorState, AwaitReactionRecord,
        BUILTIN_STRING_MEMORY, ECMAScriptFunction, Environment, FunctionAstRef, GeneratorHeapData,
        GeneratorState, JsResult, OrdinaryFunctionCreateParams, PrivateEnvironment, Promise,
        PromiseCapability, PromiseReactionHandler, PropertyDescriptor, PropertyKey,
        ProtoIntrinsics, SourceCode, SuspendedGeneratorState, ThisMode, Value, inner_promise_then,
        make_constructor, ordinary_function_create, ordinary_object_create_with_intrinsics,
        ordinary_populate_from_constructor, set_function_name, try_define_property_or_throw,
        unwrap_try,
    },
    engine::{Bindable, Executable, ExecutionResult, GcScope, NoGcScope, Scopable, Vm},
    heap::{ArenaAccess, ArenaAccessMut, CreateHeapData},
};
use oxc_ast::ast::{self};

/// ### [15.1.2 Static Semantics: ContainsExpression](https://tc39.es/ecma262/#sec-static-semantics-containsexpression)
/// The syntax-directed operation ContainsExpression takes no arguments and returns a Boolean.
pub(crate) trait ContainsExpression {
    fn contains_expression(&self) -> bool;
}

impl ContainsExpression for ast::FormalParameters<'_> {
    fn contains_expression(&self) -> bool {
        self.items.iter().any(|p| p.contains_expression())
            || self
                .rest
                .as_ref()
                .is_some_and(|rest| rest.contains_expression())
    }
}

impl ContainsExpression for ast::FormalParameter<'_> {
    fn contains_expression(&self) -> bool {
        //  SingleNameBinding : BindingIdentifier Initializer
        // 1. Return true.
        self.initializer.is_some() ||
        // Patterns
        self.pattern.contains_expression()
    }
}

impl ContainsExpression for ast::FormalParameterRest<'_> {
    fn contains_expression(&self) -> bool {
        self.rest.argument.contains_expression()
    }
}

impl ContainsExpression for ast::BindingPattern<'_> {
    fn contains_expression(&self) -> bool {
        match &self {
            ast::BindingPattern::BindingIdentifier(_) => false,
            ast::BindingPattern::ObjectPattern(pattern) => pattern.contains_expression(),
            ast::BindingPattern::ArrayPattern(pattern) => pattern.contains_expression(),
            ast::BindingPattern::AssignmentPattern(_) => true,
        }
    }
}

impl ContainsExpression for ast::ObjectPattern<'_> {
    fn contains_expression(&self) -> bool {
        for property in &self.properties {
            if property.computed || property.value.contains_expression() {
                return true;
            }
        }

        if let Some(rest) = &self.rest {
            debug_assert!(!rest.argument.contains_expression());
        }

        false
    }
}

impl ContainsExpression for ast::ArrayPattern<'_> {
    fn contains_expression(&self) -> bool {
        for pattern in self.elements.iter().flatten() {
            if pattern.contains_expression() {
                return true;
            }
        }
        if let Some(rest) = &self.rest {
            rest.argument.contains_expression()
        } else {
            false
        }
    }
}

/// ### [15.2.4 Runtime Semantics: InstantiateOrdinaryFunctionObject](https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionobject)
///
/// The syntax-directed operation InstantiateOrdinaryFunctionObject takes
/// arguments env (an Environment Record) and privateEnv (a PrivateEnvironment
/// Record or null) and returns an ECMAScript function object.
pub(crate) fn instantiate_ordinary_function_object<'a>(
    agent: &mut Agent,
    function: &ast::Function<'_>,
    env: Environment<'a>,
    private_env: Option<PrivateEnvironment<'a>>,
    gc: NoGcScope<'a, '_>,
) -> ECMAScriptFunction<'a> {
    // FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
    let pk_name = if let Some(id) = &function.id {
        // 1. Let name be StringValue of BindingIdentifier.
        let name = &id.name;
        // 4. Perform SetFunctionName(F, name).
        PropertyKey::from_str(agent, name, gc)
    } else {
        // 3. Perform SetFunctionName(F, "default").
        PropertyKey::from(BUILTIN_STRING_MEMORY.default)
    };

    // 2. Let sourceText be the source text matched by FunctionDeclaration.
    let source_text = function.span;
    // 3. Let F be OrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, NON-LEXICAL-THIS, env, privateEnv).
    let params = OrdinaryFunctionCreateParams {
        function_prototype: None,
        source_code: None,
        source_text,
        ast: FunctionAstRef::from(function),
        lexical_this: false,
        env,
        private_env,
    };
    let f = ordinary_function_create(agent, params, gc);

    // 4. Perform SetFunctionName(F, name).
    set_function_name(agent, f, pk_name, None, gc);
    // 5. Perform MakeConstructor(F).
    if !function.r#async && !function.generator {
        make_constructor(agent, f, None, None, gc);
    }

    if function.generator {
        // InstantiateGeneratorFunctionObject
        // 5. Let prototype be OrdinaryObjectCreate(%GeneratorFunction.prototype.prototype%).

        // InstantiateAsyncGeneratorFunctionObject
        // 5. Let prototype be OrdinaryObjectCreate(%AsyncGeneratorPrototype%).

        // NOTE: Although `prototype` has the generator prototype, it doesn't have the generator
        // internals slots, so it's created as an ordinary object.
        let prototype = ordinary_object_create_with_intrinsics(
            agent,
            ProtoIntrinsics::Object,
            Some(if function.r#async {
                agent
                    .current_realm_record()
                    .intrinsics()
                    .async_generator_prototype()
                    .into()
            } else {
                agent
                    .current_realm_record()
                    .intrinsics()
                    .generator_prototype()
                    .into()
            }),
            gc,
        );
        // 6. Perform ! DefinePropertyOrThrow(F, "prototype", PropertyDescriptor {
        unwrap_try(try_define_property_or_throw(
            agent,
            f,
            BUILTIN_STRING_MEMORY.prototype.to_property_key(),
            PropertyDescriptor {
                // [[Value]]: prototype,
                value: Some(prototype.unbind().into()),
                // [[Writable]]: true,
                writable: Some(true),
                // [[Enumerable]]: false,
                enumerable: Some(false),
                // [[Configurable]]: false
                configurable: Some(false),
                ..Default::default()
            },
            None,
            gc,
        ));
        // }).
    }

    // 6. Return F.
    f
    // NOTE
    // An anonymous FunctionDeclaration can only occur as part of an export
    // default declaration, and its function code is therefore always strict
    // mode code.
}

pub(crate) struct CompileFunctionBodyData<'a> {
    pub(crate) ast: FunctionAstRef<'a>,
    pub(crate) source_code: SourceCode<'a>,
    pub(crate) is_strict: bool,
    pub(crate) is_lexical: bool,
}

impl<'a> CompileFunctionBodyData<'a> {
    fn new(agent: &mut Agent, function: ECMAScriptFunction<'a>, gc: NoGcScope<'a, '_>) -> Self {
        let ast = function.get_ast(agent, gc);
        let source_code = function.get_source_code(agent);
        let is_strict = function.is_strict(agent);
        let this_mode = function.get_this_mode(agent);
        CompileFunctionBodyData {
            ast,
            source_code,
            is_strict,
            is_lexical: this_mode == ThisMode::Lexical,
        }
    }
}

/// ### [15.2.3 Runtime Semantics: EvaluateFunctionBody](https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbody)
/// The syntax-directed operation EvaluateFunctionBody takes arguments
/// functionObject (an ECMAScript function object) and argumentsList (a List of
/// ECMAScript language values) and returns either a normal completion
/// containing an ECMAScript language value or an abrupt completion.
pub(crate) fn evaluate_function_body<'gc>(
    agent: &mut Agent,
    function_object: ECMAScriptFunction,
    arguments_list: ArgumentsList,
    gc: GcScope<'gc, '_>,
) -> JsResult<'gc, Value<'gc>> {
    let arguments_list = arguments_list.bind(gc.nogc());
    let function_object = function_object.bind(gc.nogc());
    // 1. Perform ? FunctionDeclarationInstantiation(functionObject, argumentsList).
    //function_declaration_instantiation(agent, function_object, arguments_list).unbind()?.bind(gc.nogc());
    // 2. Return ? Evaluation of FunctionStatementList.
    let exe = if let Some(exe) = function_object.get(agent).compiled_bytecode {
        exe.bind(gc.nogc())
    } else {
        let data = CompileFunctionBodyData::new(agent, function_object, gc.nogc());
        let exe = Executable::compile_function_body(agent, data, gc.nogc());
        function_object.get_mut(agent).compiled_bytecode = Some(exe.unbind());
        exe
    };
    let exe = exe.scope(agent, gc.nogc());
    Vm::execute(agent, exe, Some(arguments_list.unbind().as_mut_slice()), gc).into_js_result()
}

/// ### [15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody](https://tc39.es/ecma262/#sec-runtime-semantics-evaluateasyncfunctionbody)
pub(crate) fn evaluate_async_function_body<'a>(
    agent: &mut Agent,
    function_object: ECMAScriptFunction,
    arguments_list: ArgumentsList,
    mut gc: GcScope<'a, '_>,
) -> Promise<'a> {
    let arguments_list = arguments_list.bind(gc.nogc());
    let function_object = function_object.bind(gc.nogc());
    let scoped_function_object = function_object.scope(agent, gc.nogc());
    // 1. Let promiseCapability be ! NewPromiseCapability(%Promise%).
    let PromiseCapability {
        promise,
        must_be_unresolved,
    } = PromiseCapability::new(agent, gc.nogc());
    let promise = promise.scope(agent, gc.nogc());
    // 2. Let declResult be Completion(FunctionDeclarationInstantiation(functionObject, argumentsList)).
    // 3. If declResult is an abrupt completion, then
    // 4. Else,
    // a. Perform AsyncFunctionStart(promiseCapability, FunctionBody).
    // Note: FunctionDeclarationInstantiation is performed as the first part of
    // the compiled function body; we do not need to run it and
    // AsyncFunctionStart separately.
    let exe = if let Some(exe) = function_object.get(agent).compiled_bytecode {
        exe.bind(gc.nogc())
    } else {
        let data = CompileFunctionBodyData::new(agent, function_object, gc.nogc());
        let exe = Executable::compile_function_body(agent, data, gc.nogc());
        function_object.get_mut(agent).compiled_bytecode = Some(exe.unbind());
        exe
    };
    let exe = exe.scope(agent, gc.nogc());

    let result = Vm::execute(
        agent,
        exe,
        Some(arguments_list.unbind().as_mut_slice()),
        gc.reborrow(),
    )
    .unbind();
    let gc = gc.into_nogc();
    let result = result.bind(gc);
    // SAFETY: not shared.
    let promise = unsafe { promise.take(agent) }.bind(gc);
    // AsyncFunctionStart will run the function until it returns, throws or gets
    // suspended with an await.
    match result {
        ExecutionResult::Return(result) => {
            let promise_capability = PromiseCapability::from_promise(promise, must_be_unresolved);
            // [27.7.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext )](https://tc39.es/ecma262/#sec-asyncblockstart)
            // 2. e. If result is a normal completion, then
            //       i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « undefined »).
            //    f. Else if result is a return completion, then
            //       i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »).
            unwrap_try(promise_capability.try_resolve(agent, result, gc));
        }
        ExecutionResult::Throw(err) => {
            let promise_capability = PromiseCapability::from_promise(promise, must_be_unresolved);
            // [27.7.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext )](https://tc39.es/ecma262/#sec-asyncblockstart)
            // 2. g. i. Assert: result is a throw completion.
            //       ii. Perform ! Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »).
            promise_capability.reject(agent, err.value(), gc);
        }
        ExecutionResult::Await {
            vm,
            promise: resolve_promise,
        } => {
            // [27.7.5.3 Await ( value )](https://tc39.es/ecma262/#await)
            // `handler` corresponds to the `fulfilledClosure` and `rejectedClosure` functions,
            // which resume execution of the function.
            // 2. Let promise be ? PromiseResolve(%Promise%, value).

            let promise_capability = PromiseCapability::from_promise(promise, must_be_unresolved);

            // NOTE: the execution context has to be cloned because it will be popped when we
            // return to `ECMAScriptFunction::internal_call`. Popping it here rather than
            // cloning it would mess up the execution context stack.
            let handler = PromiseReactionHandler::Await(agent.heap.create(AwaitReactionRecord {
                vm: Some(vm),
                async_executable: Some(scoped_function_object.get(agent).into()),
                execution_context: Some(agent.running_execution_context().clone()),
                return_promise_capability: promise_capability,
            }));

            // 7. Perform PerformPromiseThen(promise, onFulfilled, onRejected).
            inner_promise_then(agent, resolve_promise, handler, handler, None, gc);
        }
        ExecutionResult::Yield { .. } => unreachable!(),
    }
    //}

    // 5. Return Completion Record { [[Type]]: return, [[Value]]: promiseCapability.[[Promise]], [[Target]]: empty }.
    promise
}

/// ### [15.5.2 Runtime Semantics: EvaluateGeneratorBody](https://tc39.es/ecma262/#sec-runtime-semantics-evaluategeneratorbody)
/// The syntax-directed operation EvaluateGeneratorBody takes arguments
/// functionObject (an ECMAScript function object) and argumentsList (a List of
/// ECMAScript language values) and returns a throw completion or a return
/// completion.
pub(crate) fn evaluate_generator_body<'gc>(
    agent: &mut Agent,
    function_object: ECMAScriptFunction,
    arguments_list: ArgumentsList,
    mut gc: GcScope<'gc, '_>,
) -> JsResult<'gc, Value<'gc>> {
    let arguments_list = arguments_list.bind(gc.nogc());
    let function_object = function_object.bind(gc.nogc());

    let exe = if let Some(exe) = function_object.get(agent).compiled_bytecode {
        exe.scope(agent, gc.nogc())
    } else {
        let data = CompileFunctionBodyData::new(agent, function_object, gc.nogc());
        let exe = Executable::compile_function_body(agent, data, gc.nogc());
        function_object.get_mut(agent).compiled_bytecode = Some(exe.unbind());
        exe.scope(agent, gc.nogc())
    };

    let function_object = function_object.scope(agent, gc.nogc());

    // 1. Perform ? FunctionDeclarationInstantiation(functionObject, argumentsList).
    // Note: FunctionDeclarationInstantiation is done at the beginning of the
    // bytecode, followed by a Yield.
    let vm = match Vm::execute(
        agent,
        exe.clone(),
        Some(arguments_list.unbind().as_mut_slice()),
        gc.reborrow(),
    ) {
        ExecutionResult::Throw(err) => {
            return Err(err.unbind().bind(gc.into_nogc()));
        }
        ExecutionResult::Yield { vm, yielded_value } => {
            debug_assert!(yielded_value.is_undefined());
            vm
        }
        _ => unreachable!(),
    };

    // 2. Let G be ? OrdinaryCreateFromConstructor(functionObject,
    // "%GeneratorFunction.prototype.prototype%", « [[GeneratorState]],
    // [[GeneratorContext]], [[GeneratorBrand]] »).
    // 3. Set G.[[GeneratorBrand]] to empty.
    // 4. Perform GeneratorStart(G, FunctionBody).
    // 5. Return Completion Record { [[Type]]: return, [[Value]]: G, [[Target]]: empty }.
    let g = agent
        .heap
        .create(GeneratorHeapData {
            object_index: None,
            generator_state: Some(GeneratorState::SuspendedStart(SuspendedGeneratorState {
                vm,
                // SAFETY: exe is not shared.
                executable: unsafe { exe.take(agent) },
                execution_context: agent.running_execution_context().clone(),
            })),
        })
        .bind(gc.nogc());
    ordinary_populate_from_constructor(
        agent,
        g.unbind().into(),
        // SAFETY: not shared.
        unsafe { function_object.take(agent) }.into(),
        ProtoIntrinsics::Generator,
        gc,
    )
    .map(Into::into)
}

/// ### [15.6.2 Runtime Semantics: EvaluateAsyncGeneratorBody](https://tc39.es/ecma262/#sec-runtime-semantics-evaluateasyncgeneratorbody)
///
/// The syntax-directed operation EvaluateAsyncGeneratorBody takes arguments
/// functionObject (an ECMAScript function object) and argumentsList (a List of
/// ECMAScript language values) and returns a throw completion or a return
/// completion.
pub(crate) fn evaluate_async_generator_body<'gc>(
    agent: &mut Agent,
    function_object: ECMAScriptFunction,
    arguments_list: ArgumentsList,
    mut gc: GcScope<'gc, '_>,
) -> JsResult<'gc, Value<'gc>> {
    let function_object = function_object.bind(gc.nogc());
    let arguments_list = arguments_list.bind(gc.nogc());

    let exe = if let Some(exe) = function_object.get(agent).compiled_bytecode {
        exe.scope(agent, gc.nogc())
    } else {
        let data = CompileFunctionBodyData::new(agent, function_object, gc.nogc());
        let exe = Executable::compile_function_body(agent, data, gc.nogc());
        function_object.get_mut(agent).compiled_bytecode = Some(exe.unbind());
        exe.scope(agent, gc.nogc())
    };

    let function_object = function_object.scope(agent, gc.nogc());

    // 1. Perform ? FunctionDeclarationInstantiation(functionObject, argumentsList).
    // Note: FunctionDeclarationInstantiation is done at the beginning of the
    // bytecode, followed by a Yield.
    let vm = match Vm::execute(
        agent,
        exe.clone(),
        Some(arguments_list.unbind().as_mut_slice()),
        gc.reborrow(),
    ) {
        ExecutionResult::Throw(err) => {
            return Err(err.unbind().bind(gc.into_nogc()));
        }
        ExecutionResult::Yield { vm, yielded_value } => {
            debug_assert!(yielded_value.is_undefined());
            vm
        }
        _ => unreachable!(),
    };

    // 2. Let generator be ? OrdinaryCreateFromConstructor(functionObject,
    //    "%AsyncGeneratorPrototype%", « [[AsyncGeneratorState]],
    //    [[AsyncGeneratorContext]], [[AsyncGeneratorQueue]],
    //    [[GeneratorBrand]] »).
    // 3. Set generator.[[GeneratorBrand]] to empty.
    // 4. Set generator.[[AsyncGeneratorState]] to suspended-start.
    // 5. Perform AsyncGeneratorStart(generator, FunctionBody).
    // 6. Return ReturnCompletion(generator).
    let generator = agent
        .heap
        .create(AsyncGeneratorHeapData {
            object_index: None,
            // SAFETY: exe is not shared.
            executable: Some(unsafe { exe.take(agent) }),
            async_generator_state: Some(AsyncGeneratorState::SuspendedStart {
                vm,
                execution_context: agent.running_execution_context().clone(),
                queue: VecDeque::new(),
            }),
        })
        .bind(gc.nogc());
    ordinary_populate_from_constructor(
        agent,
        generator.unbind().into(),
        // SAFETY: not shared.
        unsafe { function_object.take(agent) }.into(),
        ProtoIntrinsics::AsyncGenerator,
        gc,
    )
    .map(Into::into)
}