From 3f08b43d380df907d09ae94e6fb397affeb563ae Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Fri, 13 Nov 2026 04:44:42 +0530 Subject: [PATCH 1/3] fix(engine): destructuring default reading an earlier binding A reference to a binding from inside its own declaration was always treated as a TDZ access, so `const { a, b = a } = o` (and the same with let, var and parameter patterns) threw a ReferenceError. Now the reference is only in the TDZ if it comes before the binding, or if it is in the initializer or default value that the binding gets destructured from. --- .../src/engine/bytecode/bytecode_compiler.rs | 48 +++++++- nova_vm/tests/language_tests.rs | 49 +++++++++ .../sources/destructuringDefault.test.js | 103 ++++++++++++++++++ 3 files changed, 199 insertions(+), 1 deletion(-) create mode 100644 nova_vm/tests/language_tests.rs create mode 100644 nova_vm/tests/sources/destructuringDefault.test.js diff --git a/nova_vm/src/engine/bytecode/bytecode_compiler.rs b/nova_vm/src/engine/bytecode/bytecode_compiler.rs index a3929e690..d93e7d8da 100644 --- a/nova_vm/src/engine/bytecode/bytecode_compiler.rs +++ b/nova_vm/src/engine/bytecode/bytecode_compiler.rs @@ -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 { @@ -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. diff --git a/nova_vm/tests/language_tests.rs b/nova_vm/tests/language_tests.rs new file mode 100644 index 000000000..91bdc8fd8 --- /dev/null +++ b/nova_vm/tests/language_tests.rs @@ -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"); +} diff --git a/nova_vm/tests/sources/destructuringDefault.test.js b/nova_vm/tests/sources/destructuringDefault.test.js new file mode 100644 index 000000000..bd1efcc89 --- /dev/null +++ b/nova_vm/tests/sources/destructuringDefault.test.js @@ -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"); From d022b51337adb4c5142a2f2547d247d12e10d625 Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Fri, 13 Nov 2026 04:44:43 +0530 Subject: [PATCH 2/3] fix(engine): block function declarations see later lexical bindings Block function declarations were instantiated in source order, before the block's lexical environment was entered for a later escaping let or const. The function then captured the outer environment and could not see the binding. Instantiate function declarations after the other declarations of the block. --- .../block_declaration_instantiation.rs | 14 +++- .../sources/blockFunctionDeclaration.test.js | 64 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 nova_vm/tests/sources/blockFunctionDeclaration.test.js diff --git a/nova_vm/src/engine/bytecode/bytecode_compiler/block_declaration_instantiation.rs b/nova_vm/src/engine/bytecode/bytecode_compiler/block_declaration_instantiation.rs index 0b9ca8be9..5cd60414b 100644 --- a/nova_vm/src/engine/bytecode/bytecode_compiler/block_declaration_instantiation.rs +++ b/nova_vm/src/engine/bytecode/bytecode_compiler/block_declaration_instantiation.rs @@ -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); diff --git a/nova_vm/tests/sources/blockFunctionDeclaration.test.js b/nova_vm/tests/sources/blockFunctionDeclaration.test.js new file mode 100644 index 000000000..480b31ff8 --- /dev/null +++ b/nova_vm/tests/sources/blockFunctionDeclaration.test.js @@ -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; +} From 8d748f9a7e390c9be0523caa56480a7dca0aad36 Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Fri, 13 Nov 2026 04:44:43 +0530 Subject: [PATCH 3/3] fix(engine): private name offsets with private getter/setter pairs A private getter/setter pair shares one Private Name but was counted twice, so static private fields after it got an offset past the end of the class's Private Environment and the engine panicked. --- .../class_definition_evaluation.rs | 11 +++- .../sources/classPrivateAccessor.test.js | 60 +++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) create mode 100644 nova_vm/tests/sources/classPrivateAccessor.test.js diff --git a/nova_vm/src/engine/bytecode/bytecode_compiler/class_definition_evaluation.rs b/nova_vm/src/engine/bytecode/bytecode_compiler/class_definition_evaluation.rs index ed9c4531b..b96cfd336 100644 --- a/nova_vm/src/engine/bytecode/bytecode_compiler/class_definition_evaluation.rs +++ b/nova_vm/src/engine/bytecode/bytecode_compiler/class_definition_evaluation.rs @@ -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 { diff --git a/nova_vm/tests/sources/classPrivateAccessor.test.js b/nova_vm/tests/sources/classPrivateAccessor.test.js new file mode 100644 index 000000000..ccd92c21c --- /dev/null +++ b/nova_vm/tests/sources/classPrivateAccessor.test.js @@ -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");