Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion nova_vm/src/engine/bytecode/bytecode_compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -880,7 +880,9 @@ impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::Identi
while decl_id < node {
node = nodes.parent_id(node);
}
if decl_id == node {
if decl_id == node
&& is_declaration_tdz(nodes, decl_id, ref_id, scoping.symbol_span(s))
{
// Self-referential declaration.
VariableKind::TemporalDeadZone
} else {
Expand Down Expand Up @@ -944,6 +946,50 @@ fn is_parameter_tdz(nodes: &oxc_semantic::AstNodes, decl_id: NodeId, ref_id: Nod
false
}

/// Checks if a reference that is found inside its own declaration is in the
/// TDZ of the binding.
///
/// A binding in a declaration's pattern is initialised once its own pattern
/// element has been destructured, so a reference to it is in the TDZ only if
/// it comes before the binding in the pattern, or if it is in the initializer
/// or default value whose result the binding is destructured from. Eg. in
/// `const { a, b = a } = o` the reference in `b = a` is not in the TDZ, while
/// in `const { a = a } = o` and `const [a] = a` it is.
fn is_declaration_tdz(
nodes: &oxc_semantic::AstNodes,
decl_id: NodeId,
ref_id: NodeId,
binding_span: oxc_span::Span,
) -> bool {
use oxc_ast::AstKind;
use oxc_span::GetSpan;
let ref_span = nodes.get_node(ref_id).kind().span();
if ref_span.start < binding_span.start {
// Reference comes before the binding.
return true;
}
let mut node = ref_id;
while node != decl_id {
node = nodes.parent_id(node);
let (pattern, init) = match nodes.get_node(node).kind() {
AstKind::AssignmentPattern(p) => (p.left.span(), Some(p.right.span())),
AstKind::FormalParameter(p) => {
(p.pattern.span(), p.initializer.as_ref().map(|i| i.span()))
}
AstKind::VariableDeclarator(d) => (d.id.span(), d.init.as_ref().map(|i| i.span())),
_ => continue,
};
if init.is_some_and(|init| init.contains_inclusive(ref_span))
&& pattern.contains_inclusive(binding_span)
{
// Reference is in the value that the binding gets destructured
// from.
return true;
}
}
false
}

impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::BindingIdentifier<'s> {
type Output = Place<'s, 'gc>;
/// Compile variable binding. This is used to create a variable.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,21 @@ pub(super) fn instantiation<'s, 'gc>(
// 1. Let declarations be the LexicallyScopedDeclarations of code.
// 2. Let privateEnv be the running execution context's PrivateEnvironment.
// 3. For each element d of declarations, do
// Note: function declarations are instantiated after all other
// declarations so that the function objects capture the block's
// environment even when the bindings that need it come later in the
// block. The order is not observable otherwise.
let mut functions = Vec::new();
code.lexically_scoped_declarations(&mut |d| {
handle_block_lexically_scoped_declaration(ctx, &mut block_prep, d);
if let LexicallyScopedDeclaration::Function(_) = d {
functions.push(d);
} else {
handle_block_lexically_scoped_declaration(ctx, &mut block_prep, d);
}
});
for d in functions {
handle_block_lexically_scoped_declaration(ctx, &mut block_prep, d);
}

// 4. Return unused.
let result = cb(ctx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,13 +281,20 @@ impl<'a, 's, 'gc, 'scope> CompileEvaluation<'a, 's, 'gc, 'scope> for ast::Class<
instance_private_fields.push((dn, prop.value.as_ref()));
}
} else if let ast::ClassElement::MethodDefinition(method) = class_element {
// Note: a getter/setter pair shares one Private Name, so
// only the first half of the pair takes a new index.
let is_new_name = !private_name_lookup_map.contains_key(dn);
if class_element.r#static() {
i = static_private_method_count;
static_private_method_count += 1;
if is_new_name {
static_private_method_count += 1;
}
static_private_methods.push((dn, &**method));
} else {
i = instance_private_method_count;
instance_private_method_count += 1;
if is_new_name {
instance_private_method_count += 1;
}
instance_private_methods.push((dn, &**method));
}
} else {
Expand Down
49 changes: 49 additions & 0 deletions nova_vm/tests/language_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// 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::{fs, path::PathBuf};

use nova_vm::{
ecmascript::{
AgentOptions, DefaultHostHooks, GcAgent, String, parse_script, script_evaluation,
},
engine::Bindable,
};

fn run_test_file(file_name: &str) {
let d: PathBuf = [env!("CARGO_MANIFEST_DIR"), "tests", "sources", file_name]
.iter()
.collect();
let contents = fs::read_to_string(d.clone()).expect("Should have been able to read the file");

let mut agent = GcAgent::new(AgentOptions::default(), &DefaultHostHooks);
let realm = agent.create_default_realm();
agent.run_in_realm(&realm, |agent, mut gc| {
let realm = agent.current_realm(gc.nogc());
let source_text = String::from_string(agent, contents, gc.nogc());
let script = parse_script(agent, source_text, realm, false, None, gc.nogc()).unwrap();
if let Err(err) = script_evaluation(agent, script.unbind(), gc.reborrow()) {
panic!(
"Test '{}' failed: {:?}",
d.display(),
err.unbind().to_string(agent, gc).to_string_lossy(agent)
)
}
});
}

#[test]
fn destructuring_default_tests() {
run_test_file("destructuringDefault.test.js");
}

#[test]
fn block_function_declaration_tests() {
run_test_file("blockFunctionDeclaration.test.js");
}

#[test]
fn class_private_accessor_tests() {
run_test_file("classPrivateAccessor.test.js");
}
64 changes: 64 additions & 0 deletions nova_vm/tests/sources/blockFunctionDeclaration.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// 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/.

function assertEquals(actual, expected, message) {
if (actual !== expected) {
throw new Error(`${message}: expected ${expected}, got ${actual}`);
}
}

// A function declared in a block can see lexical declarations that come
// later in the same block.
{
function h() {
return c;
}
const c = 2;
assertEquals(h(), 2, "const after function");
}
{
function h2() {
return d + e;
}
let d = 3;
class K {}
const e = 4;
assertEquals(h2(), 7, "let and const after function");
}
assertEquals(
(() => {
{
function f() {
return x;
}
let x = 5;
return f();
}
})(),
5,
"block in function",
);
switch (1) {
case 1:
function sw() {
return w;
}
let w = 8;
assertEquals(sw(), 8, "case block");
}

// Calling the function before the binding is initialised is a TDZ error.
{
function early() {
return y;
}
let threw = false;
try {
early();
} catch (err) {
threw = err instanceof ReferenceError;
}
assertEquals(threw, true, "TDZ before initialisation");
let y = 1;
}
60 changes: 60 additions & 0 deletions nova_vm/tests/sources/classPrivateAccessor.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// 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/.

function assertEquals(actual, expected, message) {
if (actual !== expected) {
throw new Error(`${message}: expected ${expected}, got ${actual}`);
}
}

// A private getter/setter pair shares one Private Name, so static private
// fields that come after it must not be offset by two.
class A {
static #a = 1;
get #b() {
return 2;
}
set #b(v) {}
static getA() {
return A.#a;
}
getB() {
return this.#b;
}
}
assertEquals(A.getA(), 1, "static field after accessor pair");
assertEquals(new A().getB(), 2, "instance accessor pair");

class B {
#f = 1;
get #b() {
return 10;
}
set #b(v) {
this.#f = v;
}
static #s = 3;
static #t = 4;
static sum() {
return B.#s + B.#t;
}
bump() {
this.#b = 5;
return this.#f;
}
}
assertEquals(B.sum(), 7, "two static fields after accessor pair");
assertEquals(new B().bump(), 5, "setter writes instance field");

class C {
static get #p() {
return 1;
}
static set #p(v) {}
static #q = 6;
static q() {
return C.#q + C.#p;
}
}
assertEquals(C.q(), 7, "static accessor pair");
103 changes: 103 additions & 0 deletions nova_vm/tests/sources/destructuringDefault.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// 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/.

function assertEquals(actual, expected, message) {
if (actual !== expected) {
throw new Error(`${message}: expected ${expected}, got ${actual}`);
}
}

function assertThrowsReferenceError(fn, message) {
try {
fn();
} catch (err) {
if (err instanceof ReferenceError) {
return;
}
throw new Error(`${message}: expected ReferenceError, got ${err}`);
}
throw new Error(`${message}: expected ReferenceError, got no error`);
}

// A default value can read a binding that was destructured before it.
assertEquals(
(() => {
const { a, b = a } = { a: 1 };
return b;
})(),
1,
"const object pattern",
);
assertEquals(
(() => {
let [a, b = a] = [2];
return b;
})(),
2,
"let array pattern",
);
assertEquals(
(() => {
var { a, b = a } = { a: 3 };
return b;
})(),
3,
"var object pattern",
);
assertEquals(
(({ width, height = width }) => height)({ width: 4 }),
4,
"parameter pattern",
);
assertEquals(((a, b = a) => b)(5), 5, "parameter default");
assertEquals(
(() => {
const { a, b = a + 1, c = b * 2 } = { a: 1 };
return c;
})(),
4,
"chained defaults",
);
assertEquals(
(() => {
const [[a, b = a] = [7]] = [];
return b;
})(),
7,
"nested pattern with outer default",
);
assertEquals(
(() => {
const { a, c = (() => a)() } = { a: 9 };
return c;
})(),
9,
"closure in default",
);

// Reading a binding before it is destructured is still a TDZ error.
assertThrowsReferenceError(() => {
const { b = a, a } = {};
}, "default before binding");
assertThrowsReferenceError(() => {
const { a = a } = {};
}, "own default");
assertThrowsReferenceError(() => {
const [a] = [a];
}, "initializer");
assertThrowsReferenceError(() => {
const [{ a } = { a: a }] = [];
}, "default of enclosing pattern");
assertThrowsReferenceError(() => {
const { [a]: a } = {};
}, "computed key");
assertThrowsReferenceError(() => {
((x = x) => x)();
}, "own parameter default");
assertThrowsReferenceError(() => {
(({ x } = { x: x }) => x)();
}, "parameter pattern default");
assertThrowsReferenceError(() => {
const x = x;
}, "self-referencing initializer");