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
// 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 crate::{
    ecmascript::{
        Agent, DeclarativeEnvironment, DeclarativeEnvironmentRecord, ECMAScriptFunction,
        Environment, ExceptionType, Function, FunctionEnvironment, InternalMethods, JsResult,
        Object, String, ThisMode, Value, unwrap_try,
    },
    engine::{Bindable, NoGcScope},
    heap::{ArenaAccess, ArenaAccessMut, CompactionLists, HeapMarkAndSweep, WorkQueues},
};

#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum ThisBindingStatus {
    /// Function is an ArrowFunction and does not have a local `this` value.
    Lexical,
    /// Function is a normal function and does not have a bound `this` value.
    Initialized,
    /// Function is a normal function and has a bound `this` value.
    Uninitialized,
}

/// ### [9.1.1.3 Function Environment Records](https://tc39.es/ecma262/#sec-function-environment-records)
///
/// A Function Environment Record is a Declarative Environment Record that is
/// used to represent the top-level scope of a function and, if the function is
/// not an ArrowFunction, provides a this binding. If a function is not an
/// ArrowFunction function and references super, its Function Environment
/// Record also contains the state that is used to perform super method
/// invocations from within the function.
#[derive(Debug)]
pub(crate) struct FunctionEnvironmentRecord {
    /// ### \[\[ThisValue\]\]
    ///
    /// This is the this value used for this invocation of the function.
    this_value: Option<Value<'static>>,

    /// ### \[\[ThisBindingStatus\]\]
    ///
    /// If the value is LEXICAL, this is an ArrowFunction and does not have a
    /// local this value.
    this_binding_status: ThisBindingStatus,

    /// ### \[\[FunctionObject\]\]
    ///
    /// The function object whose invocation caused this Environment Record to
    /// be created.
    function_object: Function<'static>,

    /// ### \[\[NewTarget\]\]
    ///
    /// If this Environment Record was created by the \[\[Construct\]\]
    /// internal method, \[\[NewTarget\]\] is the value of the
    /// \[\[Construct\]\] newTarget parameter. Otherwise, its value is
    /// undefined.
    new_target: Option<Object<'static>>,

    /// Function Environment Records support all of the Declarative Environment
    /// Record methods listed in Table 16 and share the same specifications for
    /// all of those methods except for HasThisBinding and HasSuperBinding.
    ///
    /// TODO: Use Struct of Arrays to keep the DeclarativeEnvironment alignside
    /// FunctionEnvironment
    declarative_environment: DeclarativeEnvironment<'static>,
}

impl HeapMarkAndSweep for FunctionEnvironmentRecord {
    fn mark_values(&self, queues: &mut WorkQueues) {
        let Self {
            this_value,
            this_binding_status: _,
            function_object,
            new_target,
            declarative_environment,
        } = self;
        declarative_environment.mark_values(queues);
        function_object.mark_values(queues);
        new_target.mark_values(queues);
        this_value.mark_values(queues);
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        let Self {
            this_value,
            this_binding_status: _,
            function_object,
            new_target,
            declarative_environment,
        } = self;
        declarative_environment.sweep_values(compactions);
        function_object.sweep_values(compactions);
        new_target.sweep_values(compactions);
        this_value.sweep_values(compactions);
    }
}

/// ### [9.1.2.4 NewFunctionEnvironment ( F, newTarget )](https://tc39.es/ecma262/#sec-newfunctionenvironment)
///
/// The abstract operation NewFunctionEnvironment takes arguments F (an
/// ECMAScript function object) and newTarget (an Object or undefined) and
/// returns a Function Environment Record.
pub(crate) fn new_function_environment<'a>(
    agent: &mut Agent,
    f: ECMAScriptFunction,
    new_target: Option<Object>,
    gc: NoGcScope<'a, '_>,
) -> FunctionEnvironment<'a> {
    let ecmascript_function_object = &f.get(agent).ecmascript_function;
    let this_mode = ecmascript_function_object.this_mode;
    // 1. Let env be a new Function Environment Record containing no bindings.
    let dcl_env = DeclarativeEnvironmentRecord::new(Some(ecmascript_function_object.environment));
    let declarative_environment = agent
        .heap
        .environments
        .push_declarative_environment(dcl_env, gc);
    // 2. Set env.[[FunctionObject]] to F.
    let function_object = f.unbind().into();
    // 3. If F.[[ThisMode]] is LEXICAL, set env.[[ThisBindingStatus]] to LEXICAL.
    let this_binding_status = if this_mode == ThisMode::Lexical {
        ThisBindingStatus::Lexical
    } else {
        // 4. Else, set env.[[ThisBindingStatus]] to UNINITIALIZED.
        ThisBindingStatus::Uninitialized
    };
    let env = FunctionEnvironmentRecord {
        this_value: None,

        function_object,

        this_binding_status,

        // 5. Set env.[[NewTarget]] to newTarget.
        new_target: new_target.unbind(),

        // 6. Set env.[[OuterEnv]] to F.[[Environment]].
        declarative_environment: declarative_environment.unbind(),
    };
    // 7. Return env.
    agent.heap.alloc_counter += core::mem::size_of::<Option<FunctionEnvironmentRecord>>()
        + core::mem::size_of::<Option<DeclarativeEnvironmentRecord>>();
    agent.heap.environments.push_function_environment(env, gc)
}

/// ### NewClassStaticElementEnvironment ( classConstructor )
///
/// This is a non-standard abstract operation that performs the same steps as
/// NewFunctionEnvironment, but for a class static element's evaluation
/// function. These functions are never visible to ECMAScript code and thus we
/// avoid creating them entirely. The only parameter is the class constructor,
/// which is used as both the this value and the \[\[FunctionObject]] of the
/// new function environment.
pub(crate) fn new_class_static_element_environment<'a>(
    agent: &mut Agent,
    class_constructor: Function,
    gc: NoGcScope<'a, '_>,
) -> FunctionEnvironment<'a> {
    // 1. Let env be a new Function Environment Record containing no bindings.
    let dcl_env = DeclarativeEnvironmentRecord::new(Some(agent.current_lexical_environment(gc)));
    let declarative_environment = agent
        .heap
        .environments
        .push_declarative_environment(dcl_env, gc);

    let env = FunctionEnvironmentRecord {
        this_value: Some(class_constructor.unbind().into()),

        function_object: class_constructor.unbind(),

        this_binding_status: ThisBindingStatus::Initialized,

        // 5. Set env.[[NewTarget]] to newTarget.
        new_target: None,

        // 6. Set env.[[OuterEnv]] to F.[[Environment]].
        declarative_environment: declarative_environment.unbind(),
    };
    // 7. Return env.
    agent.heap.alloc_counter += core::mem::size_of::<Option<FunctionEnvironmentRecord>>()
        + core::mem::size_of::<Option<DeclarativeEnvironmentRecord>>();
    agent.heap.environments.push_function_environment(env, gc)
}

pub(crate) fn new_class_field_initializer_environment<'a>(
    agent: &mut Agent,
    class_constructor: Function,
    class_instance: Object,
    outer_env: Environment,
    gc: NoGcScope<'a, '_>,
) -> FunctionEnvironment<'a> {
    let declarative_environment = agent
        .heap
        .environments
        .push_declarative_environment(DeclarativeEnvironmentRecord::new(Some(outer_env)), gc);
    agent.heap.alloc_counter += core::mem::size_of::<Option<FunctionEnvironmentRecord>>()
        + core::mem::size_of::<Option<DeclarativeEnvironmentRecord>>();
    agent.heap.environments.push_function_environment(
        FunctionEnvironmentRecord {
            this_value: Some(class_instance.unbind().into()),
            this_binding_status: ThisBindingStatus::Initialized,
            function_object: class_constructor.unbind(),
            new_target: None,
            declarative_environment: declarative_environment.unbind(),
        },
        gc,
    )
}

impl<'e> FunctionEnvironment<'e> {
    pub(crate) fn get_function_object(self, agent: &Agent) -> Function<'e> {
        self.get(agent).function_object
    }

    pub(crate) fn get_new_target(self, agent: &Agent) -> Option<Object<'e>> {
        self.get(agent).new_target
    }

    pub(crate) fn get_outer_env(self, agent: &Agent) -> Option<Environment<'e>> {
        self.get(agent).declarative_environment.get_outer_env(agent)
    }

    pub(crate) fn get_this_binding_status(self, agent: &Agent) -> ThisBindingStatus {
        self.get(agent).this_binding_status
    }

    /// ### [9.1.1.3.4 GetThisBinding ( )](https://tc39.es/ecma262/#sec-function-environment-records-getthisbinding)
    /// The GetThisBinding concrete method of a Function Environment Record
    /// envRec takes no arguments and returns either a normal completion
    /// containing an ECMAScript language value or a throw completion.
    pub(crate) fn get_this_binding<'a>(
        self,
        agent: &mut Agent,
        gc: NoGcScope<'a, '_>,
    ) -> JsResult<'a, Value<'a>> {
        // 1. Assert: envRec.[[ThisBindingStatus]] is not lexical.
        // 2. If envRec.[[ThisBindingStatus]] is uninitialized, throw a ReferenceError exception.
        // 3. Return envRec.[[ThisValue]].
        let env_rec = &self.get(agent);
        match env_rec.this_binding_status {
            ThisBindingStatus::Lexical => unreachable!(),
            ThisBindingStatus::Initialized => Ok(env_rec.this_value.unwrap()),
            ThisBindingStatus::Uninitialized => Err(agent.throw_exception_with_static_message(
                ExceptionType::ReferenceError,
                "Uninitialized this binding",
                gc,
            )),
        }
    }

    /// ### [9.1.1.1.1 HasBinding ( N )](https://tc39.es/ecma262/#sec-declarative-environment-records-hasbinding-n)
    pub(crate) fn has_binding(self, agent: &Agent, name: String) -> bool {
        self.get(agent)
            .declarative_environment
            .has_binding(agent, name)
    }

    /// ### [9.1.1.1.2 CreateMutableBinding ( N, D )](https://tc39.es/ecma262/#sec-declarative-environment-records-createmutablebinding-n-d)
    pub(crate) fn create_mutable_binding(
        self,
        agent: &mut Agent,
        name: String,
        is_deletable: bool,
    ) {
        self.get(agent)
            .declarative_environment
            .create_mutable_binding(agent, name, is_deletable)
    }

    /// ### [9.1.1.1.3 CreateImmutableBinding ( N, S )](https://tc39.es/ecma262/#sec-declarative-environment-records-createimmutablebinding-n-s)
    pub(crate) fn create_immutable_binding(self, agent: &mut Agent, name: String, is_strict: bool) {
        self.get(agent)
            .declarative_environment
            .create_immutable_binding(agent, name, is_strict)
    }

    /// ### [9.1.1.1.4 InitializeBinding ( N, V )](https://tc39.es/ecma262/#sec-declarative-environment-records-initializebinding-n-v)
    pub(crate) fn initialize_binding(self, agent: &mut Agent, name: String, value: Value) {
        self.get(agent)
            .declarative_environment
            .initialize_binding(agent, name, value)
    }

    /// ### [9.1.1.1.5 SetMutableBinding ( N, V, S )](https://tc39.es/ecma262/#sec-declarative-environment-records-setmutablebinding-n-v-s)
    pub(crate) fn set_mutable_binding<'a>(
        self,
        agent: &mut Agent,
        name: String,
        value: Value,
        mut is_strict: bool,
        gc: NoGcScope<'a, '_>,
    ) -> JsResult<'a, ()> {
        let env_rec = &self.get(agent);
        let dcl_rec = env_rec.declarative_environment;
        // 1. If envRec does not have a binding for N, then
        if !dcl_rec.has_binding(agent, name) {
            // a. If S is true, throw a ReferenceError exception.
            if is_strict {
                let error_message = format!(
                    "Could not set mutable binding '{}'.",
                    name.to_string_lossy_(agent)
                );
                return Err(agent.throw_exception(
                    ExceptionType::ReferenceError,
                    error_message,
                    gc,
                ));
            }

            // b. Perform ! envRec.CreateMutableBinding(N, true).
            dcl_rec.create_mutable_binding(agent, name, true);

            // c. Perform ! envRec.InitializeBinding(N, V).
            dcl_rec.initialize_binding(agent, name, value);

            // d. Return UNUSED.
            return Ok(());
        };

        let binding = dcl_rec.get_binding_mut(agent, name).unwrap();

        // 2. If the binding for N in envRec is a strict binding, set S to true.
        if binding.strict {
            is_strict = true;
        }

        // 3. If the binding for N in envRec has not yet been initialized, then
        if binding.value.is_none() {
            // a. Throw a ReferenceError exception.
            let error_message = format!(
                "Identifier '{}' has not been initialized.",
                name.to_string_lossy_(agent)
            );
            return Err(agent.throw_exception(ExceptionType::ReferenceError, error_message, gc));
        }

        // 4. Else if the binding for N in envRec is a mutable binding, then
        if binding.mutable {
            // a. Change its bound value to V.
            binding.value = Some(value.unbind());
        }
        // 5. Else,
        else {
            // a. Assert: This is an attempt to change the value of an immutable binding.
            debug_assert!(!binding.mutable);

            // b. If S is true, throw a TypeError exception.
            if is_strict {
                let error_message = format!(
                    "invalid assignment to const '{}'",
                    name.to_string_lossy_(agent)
                );
                return Err(agent.throw_exception(ExceptionType::TypeError, error_message, gc));
            }
        }

        // 6. Return UNUSED.
        Ok(())
    }

    /// ### [9.1.1.1.6 GetBindingValue ( N, S )](https://tc39.es/ecma262/#sec-declarative-environment-records-getbindingvalue-n-s)
    pub(crate) fn get_binding_value(
        self,
        agent: &mut Agent,
        name: String,
        is_strict: bool,
        gc: NoGcScope<'e, '_>,
    ) -> JsResult<'e, Value<'e>> {
        self.get(agent)
            .declarative_environment
            .get_binding_value(agent, name, is_strict, gc)
    }

    /// ### [9.1.1.1.7 DeleteBinding ( N )](https://tc39.es/ecma262/#sec-declarative-environment-records-deletebinding-n)
    pub(crate) fn delete_binding(self, agent: &mut Agent, name: String) -> bool {
        self.get(agent)
            .declarative_environment
            .delete_binding(agent, name)
    }

    /// ### [9.1.1.3.1 BindThisValue ( V )](https://tc39.es/ecma262/#sec-bindthisvalue)
    ///
    /// The BindThisValue concrete method of a Function Environment Record
    /// envRec takes argument V (an ECMAScript language value) and returns
    /// either a normal completion containing an ECMAScript language value or a
    /// throw completion.
    pub(crate) fn bind_this_value<'a>(
        self,
        agent: &mut Agent,
        value: Value,
        gc: NoGcScope<'a, '_>,
    ) -> JsResult<'a, Value<'a>> {
        let env_rec = self.get_mut(agent);
        // 1. Assert: envRec.[[ThisBindingStatus]] is not LEXICAL.
        debug_assert!(env_rec.this_binding_status != ThisBindingStatus::Lexical);

        // 2. If envRec.[[ThisBindingStatus]] is INITIALIZED, throw a
        // ReferenceError exception.
        if env_rec.this_binding_status == ThisBindingStatus::Initialized {
            return Err(agent.throw_exception_with_static_message(
                ExceptionType::ReferenceError,
                "[[ThisBindingStatus]] is INITIALIZED",
                gc,
            ));
        }

        // 3. Set envRec.[[ThisValue]] to V.
        env_rec.this_value = Some(value.unbind());

        // 4. Set envRec.[[ThisBindingStatus]] to INITIALIZED.
        env_rec.this_binding_status = ThisBindingStatus::Initialized;

        // 5. Return V.
        Ok(value.bind(gc))
    }

    /// ### [9.1.1.3.2 HasThisBinding ( )](https://tc39.es/ecma262/#sec-function-environment-records-hasthisbinding)
    ///
    /// The HasThisBinding concrete method of a Function Environment Record
    /// envRec takes no arguments and returns a Boolean.
    pub(crate) fn has_this_binding(self, agent: &Agent) -> bool {
        let env_rec = &self.get(agent);
        // 1. If envRec.[[ThisBindingStatus]] is LEXICAL, return false;
        // otherwise, return true.
        env_rec.this_binding_status != ThisBindingStatus::Lexical
    }

    /// ### [9.1.1.3.3 HasSuperBinding ( )](https://tc39.es/ecma262/#sec-function-environment-records-hassuperbinding)
    ///
    /// The HasSuperBinding concrete method of a Function Environment Record
    /// envRec takes no arguments and returns a Boolean.
    pub(crate) fn has_super_binding(self, agent: &Agent) -> bool {
        let env_rec = &self.get(agent);
        // 1. If envRec.[[ThisBindingStatus]] is LEXICAL, return false.
        if env_rec.this_binding_status == ThisBindingStatus::Lexical {
            return false;
        }

        // 2. If envRec.[[FunctionObject]].[[HomeObject]] is undefined, return
        //    false; otherwise, return true.
        match env_rec.function_object {
            Function::ECMAScriptFunction(func) => {
                func.get(agent).ecmascript_function.home_object.is_some()
            }
            _ => false,
        }
    }

    /// ### [9.1.1.3.5 GetSuperBase ( )](https://tc39.es/ecma262/#sec-getsuperbase)
    ///
    /// The GetSuperBase concrete method of a Function Environment Record
    /// envRec takes no arguments and returns either a normal completion
    /// containing either an Object, null, or undefined.
    pub(crate) fn get_super_base<'a>(self, agent: &mut Agent, gc: NoGcScope<'a, '_>) -> Value<'a> {
        let env_rec: &FunctionEnvironmentRecord = self.get(agent);

        // 1. Let home be envRec.[[FunctionObject]].[[HomeObject]].
        let home = match env_rec.function_object {
            Function::ECMAScriptFunction(func) => func.get(agent).ecmascript_function.home_object,
            _ => None,
        };
        // 2. If home is undefined, return undefined.
        let Some(home) = home else {
            return Value::Undefined;
        };
        // 3. Assert: home is an ordinary object.
        // 4. Return ! home.[[GetPrototypeOf]]().
        unwrap_try(home.try_get_prototype_of(agent, gc)).map_or(Value::Undefined, |o| o.into())
    }
}

impl HeapMarkAndSweep for FunctionEnvironment<'static> {
    fn mark_values(&self, queues: &mut WorkQueues) {
        queues.function_environments.push(*self);
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        compactions.function_environments.shift_index(&mut self.0);
    }
}