Skip to content

Truly independent web browser

LibJS: Implement using declarations

Andreas Kling822f207bce9e
diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S
index e5beedfcbfd..3ce83334b36 100644
--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S
+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S
@@ -181,6 +181,9 @@ asm_dispatch_table:
.quad asm_handler_DeleteById
.quad asm_handler_DeleteByValue
.quad asm_handler_DeleteVariable
+ .quad asm_handler_NewDisposableResourceStack
+ .quad asm_handler_AddDisposableResource
+ .quad asm_handler_DisposeResources
.quad asm_handler_GetCompletionFields
.quad asm_handler_SetCompletionType
.quad asm_handler_GetTemplateObject
@@ -266,9 +269,6 @@ asm_dispatch_table:
.quad asm_handler_fallback
.quad asm_handler_fallback
.quad asm_handler_fallback
- .quad asm_handler_fallback
- .quad asm_handler_fallback
- .quad asm_handler_fallback
.globl CSYM(js_interpreter_debug_dispatch_table)
CSYM(js_interpreter_debug_dispatch_table):
@@ -1205,6 +1205,18 @@ CSYM(js_interpreter_handler_ranges):
.quad asm_handler_DeleteVariable_hot_end
.quad asm_handler_DeleteVariable_cold
.quad asm_handler_DeleteVariable_cold_end
+ .quad asm_handler_NewDisposableResourceStack
+ .quad asm_handler_NewDisposableResourceStack_hot_end
+ .quad asm_handler_NewDisposableResourceStack_cold
+ .quad asm_handler_NewDisposableResourceStack_cold_end
+ .quad asm_handler_AddDisposableResource
+ .quad asm_handler_AddDisposableResource_hot_end
+ .quad asm_handler_AddDisposableResource_cold
+ .quad asm_handler_AddDisposableResource_cold_end
+ .quad asm_handler_DisposeResources
+ .quad asm_handler_DisposeResources_hot_end
+ .quad asm_handler_DisposeResources_cold
+ .quad asm_handler_DisposeResources_cold_end
.quad asm_handler_GetCompletionFields
.quad asm_handler_GetCompletionFields_hot_end
.quad asm_handler_GetCompletionFields_cold
@@ -1545,18 +1557,6 @@ CSYM(js_interpreter_handler_ranges):
.quad asm_handler_fallback_hot_end
.quad asm_handler_fallback_cold
.quad asm_handler_fallback_cold_end
- .quad asm_handler_fallback
- .quad asm_handler_fallback_hot_end
- .quad asm_handler_fallback_cold
- .quad asm_handler_fallback_cold_end
- .quad asm_handler_fallback
- .quad asm_handler_fallback_hot_end
- .quad asm_handler_fallback_cold
- .quad asm_handler_fallback_cold_end
- .quad asm_handler_fallback
- .quad asm_handler_fallback_hot_end
- .quad asm_handler_fallback_cold
- .quad asm_handler_fallback_cold_end
.text
@@ -17226,6 +17226,139 @@ asm_handler_DeleteVariable_hot_end:
asm_handler_DeleteVariable_cold:
asm_handler_DeleteVariable_cold_end:
+.p2align 4
+asm_handler_NewDisposableResourceStack:
+ mov x0, x20
+ sub w1, w21, w26
+ str w1, [x28, #64]
+ mov x0, x20
+ sub w1, w21, w26
+ mov x2, x21
+ bl CSYM(asm_slow_path_new_disposable_resource_stack)
+ tbnz x0, #63, .Lasm_NewDisposableResourceStack.scalar_result_done_0
+ tbz x0, #32, .Lasm_NewDisposableResourceStack.scalar_result_done_0
+ ldr w9, [x21, #4]
+ str x1, [x27, x9, lsl #3]
+ add x21, x26, w0, uxtw
+ ldrb w9, [x21]
+ ldr x10, [x19, x9, lsl #3]
+ br x10
+.Lasm_NewDisposableResourceStack.scalar_result_done_0:
+ tbz x0, #63, 1f
+ b .Lexit
+1:
+ tbz x0, #32, .Lasm_NewDisposableResourceStack.slow_path_transfer_1
+ add x21, x26, w0, uxtw
+ ldrb w9, [x21]
+ ldr x10, [x19, x9, lsl #3]
+ br x10
+.Lasm_NewDisposableResourceStack.slow_path_transfer_1:
+ ldr x28, [x20]
+ ldr x9, [x28, #88]
+ ldr x26, [x9, #40]
+ add x27, x28, #128
+ add x21, x26, w0, uxtw
+ ldrb w9, [x21]
+ ldr x10, [x19, x9, lsl #3]
+ br x10
+asm_handler_NewDisposableResourceStack_hot_end:
+asm_handler_NewDisposableResourceStack_cold:
+asm_handler_NewDisposableResourceStack_cold_end:
+
+.p2align 4
+asm_handler_AddDisposableResource:
+ mov x0, x20
+ sub w1, w21, w26
+ str w1, [x28, #64]
+ ldr w9, [x21, #4]
+ ldr x10, [x27, x9, lsl #3]
+.Lasm_AddDisposableResource.scalar_value_ready_0:
+ mov x3, x10
+ ldr w9, [x21, #8]
+ ldr x10, [x27, x9, lsl #3]
+.Lasm_AddDisposableResource.scalar_value_ready_1:
+ mov x4, x10
+ mov x0, x20
+ sub w1, w21, w26
+ mov x2, x21
+ bl CSYM(asm_slow_path_add_disposable_resource)
+ tbnz x0, #63, .Lasm_AddDisposableResource.scalar_result_done_2
+ tbz x0, #32, .Lasm_AddDisposableResource.scalar_result_done_2
+ add x21, x26, w0, uxtw
+ ldrb w9, [x21]
+ ldr x10, [x19, x9, lsl #3]
+ br x10
+.Lasm_AddDisposableResource.scalar_result_done_2:
+ tbz x0, #63, 1f
+ b .Lexit
+1:
+ tbz x0, #32, .Lasm_AddDisposableResource.slow_path_transfer_3
+ add x21, x26, w0, uxtw
+ ldrb w9, [x21]
+ ldr x10, [x19, x9, lsl #3]
+ br x10
+.Lasm_AddDisposableResource.slow_path_transfer_3:
+ ldr x28, [x20]
+ ldr x9, [x28, #88]
+ ldr x26, [x9, #40]
+ add x27, x28, #128
+ add x21, x26, w0, uxtw
+ ldrb w9, [x21]
+ ldr x10, [x19, x9, lsl #3]
+ br x10
+asm_handler_AddDisposableResource_hot_end:
+asm_handler_AddDisposableResource_cold:
+asm_handler_AddDisposableResource_cold_end:
+
+.p2align 4
+asm_handler_DisposeResources:
+ mov x0, x20
+ sub w1, w21, w26
+ str w1, [x28, #64]
+ ldr w9, [x21, #4]
+ ldr x10, [x27, x9, lsl #3]
+.Lasm_DisposeResources.scalar_value_ready_0:
+ mov x3, x10
+ ldr w9, [x21, #8]
+ ldr x10, [x27, x9, lsl #3]
+.Lasm_DisposeResources.scalar_value_ready_1:
+ mov x4, x10
+ ldr w9, [x21, #12]
+ ldr x10, [x27, x9, lsl #3]
+.Lasm_DisposeResources.scalar_value_ready_2:
+ mov x5, x10
+ mov x0, x20
+ sub w1, w21, w26
+ mov x2, x21
+ bl CSYM(asm_slow_path_dispose_resources)
+ tbnz x0, #63, .Lasm_DisposeResources.scalar_result_done_3
+ tbz x0, #32, .Lasm_DisposeResources.scalar_result_done_3
+ add x21, x26, w0, uxtw
+ ldrb w9, [x21]
+ ldr x10, [x19, x9, lsl #3]
+ br x10
+.Lasm_DisposeResources.scalar_result_done_3:
+ tbz x0, #63, 1f
+ b .Lexit
+1:
+ tbz x0, #32, .Lasm_DisposeResources.slow_path_transfer_4
+ add x21, x26, w0, uxtw
+ ldrb w9, [x21]
+ ldr x10, [x19, x9, lsl #3]
+ br x10
+.Lasm_DisposeResources.slow_path_transfer_4:
+ ldr x28, [x20]
+ ldr x9, [x28, #88]
+ ldr x26, [x9, #40]
+ add x27, x28, #128
+ add x21, x26, w0, uxtw
+ ldrb w9, [x21]
+ ldr x10, [x19, x9, lsl #3]
+ br x10
+asm_handler_DisposeResources_hot_end:
+asm_handler_DisposeResources_cold:
+asm_handler_DisposeResources_cold_end:
+
.p2align 4
asm_handler_GetCompletionFields:
mov x0, x20
diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S
index da7c696f466..e82a255a8e9 100644
--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S
+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S
@@ -182,6 +182,9 @@ asm_dispatch_table:
.quad asm_handler_DeleteById
.quad asm_handler_DeleteByValue
.quad asm_handler_DeleteVariable
+ .quad asm_handler_NewDisposableResourceStack
+ .quad asm_handler_AddDisposableResource
+ .quad asm_handler_DisposeResources
.quad asm_handler_GetCompletionFields
.quad asm_handler_SetCompletionType
.quad asm_handler_GetTemplateObject
@@ -267,9 +270,6 @@ asm_dispatch_table:
.quad asm_handler_fallback
.quad asm_handler_fallback
.quad asm_handler_fallback
- .quad asm_handler_fallback
- .quad asm_handler_fallback
- .quad asm_handler_fallback
.globl CSYM(js_interpreter_debug_dispatch_table)
CSYM(js_interpreter_debug_dispatch_table):
@@ -1206,6 +1206,18 @@ CSYM(js_interpreter_handler_ranges):
.quad asm_handler_DeleteVariable_hot_end
.quad asm_handler_DeleteVariable_cold
.quad asm_handler_DeleteVariable_cold_end
+ .quad asm_handler_NewDisposableResourceStack
+ .quad asm_handler_NewDisposableResourceStack_hot_end
+ .quad asm_handler_NewDisposableResourceStack_cold
+ .quad asm_handler_NewDisposableResourceStack_cold_end
+ .quad asm_handler_AddDisposableResource
+ .quad asm_handler_AddDisposableResource_hot_end
+ .quad asm_handler_AddDisposableResource_cold
+ .quad asm_handler_AddDisposableResource_cold_end
+ .quad asm_handler_DisposeResources
+ .quad asm_handler_DisposeResources_hot_end
+ .quad asm_handler_DisposeResources_cold
+ .quad asm_handler_DisposeResources_cold_end
.quad asm_handler_GetCompletionFields
.quad asm_handler_GetCompletionFields_hot_end
.quad asm_handler_GetCompletionFields_cold
@@ -1546,18 +1558,6 @@ CSYM(js_interpreter_handler_ranges):
.quad asm_handler_fallback_hot_end
.quad asm_handler_fallback_cold
.quad asm_handler_fallback_cold_end
- .quad asm_handler_fallback
- .quad asm_handler_fallback_hot_end
- .quad asm_handler_fallback_cold
- .quad asm_handler_fallback_cold_end
- .quad asm_handler_fallback
- .quad asm_handler_fallback_hot_end
- .quad asm_handler_fallback_cold
- .quad asm_handler_fallback_cold_end
- .quad asm_handler_fallback
- .quad asm_handler_fallback_hot_end
- .quad asm_handler_fallback_cold
- .quad asm_handler_fallback_cold_end
.text
@@ -16841,6 +16841,137 @@ asm_handler_DeleteVariable_hot_end:
asm_handler_DeleteVariable_cold:
asm_handler_DeleteVariable_cold_end:
+.p2align 4
+asm_handler_NewDisposableResourceStack:
+ mov DWORD PTR [rbx + -64], r13d
+ lea r11, [r14 + r13]
+ mov rdi, QWORD PTR [rbp - 48]
+ mov esi, r13d
+ lea rdx, [r14 + r13]
+ call CSYM(asm_slow_path_new_disposable_resource_stack)
+ test rax, rax
+ js .Lasm_NewDisposableResourceStack.scalar_result_done_0
+ bt rax, 32
+ jnc .Lasm_NewDisposableResourceStack.scalar_result_done_0
+ lea rcx, [r14 + r13]
+ mov r10d, DWORD PTR [rcx + 4]
+ mov QWORD PTR [rbx + r10 * 8], rdx
+ mov r13d, eax
+ movzx eax, BYTE PTR [r14 + r13]
+ jmp [r12 + rax * 8]
+.Lasm_NewDisposableResourceStack.scalar_result_done_0:
+ test rax, rax
+ js .Lexit
+ bt rax, 32
+ jnc .Lasm_NewDisposableResourceStack.slow_path_transfer_1
+ mov r13d, eax
+ movzx eax, BYTE PTR [r14 + r13]
+ jmp [r12 + rax * 8]
+.Lasm_NewDisposableResourceStack.slow_path_transfer_1:
+ mov rcx, QWORD PTR [rbp - 48]
+ mov rbx, QWORD PTR [rcx]
+ add rbx, 128
+ mov rcx, QWORD PTR [rbx + -40]
+ mov r14, QWORD PTR [rcx + 40]
+ mov r13d, eax
+ movzx eax, BYTE PTR [r14 + r13]
+ jmp [r12 + rax * 8]
+asm_handler_NewDisposableResourceStack_hot_end:
+asm_handler_NewDisposableResourceStack_cold:
+asm_handler_NewDisposableResourceStack_cold_end:
+
+.p2align 4
+asm_handler_AddDisposableResource:
+ mov DWORD PTR [rbx + -64], r13d
+ lea r11, [r14 + r13]
+ mov r10d, DWORD PTR [r11 + 4]
+ mov rax, QWORD PTR [rbx + r10 * 8]
+.Lasm_AddDisposableResource.scalar_value_ready_0:
+ mov rcx, rax
+ mov r10d, DWORD PTR [r11 + 8]
+ mov rax, QWORD PTR [rbx + r10 * 8]
+.Lasm_AddDisposableResource.scalar_value_ready_1:
+ mov r8, rax
+ mov rdi, QWORD PTR [rbp - 48]
+ mov esi, r13d
+ lea rdx, [r14 + r13]
+ call CSYM(asm_slow_path_add_disposable_resource)
+ test rax, rax
+ js .Lasm_AddDisposableResource.scalar_result_done_2
+ bt rax, 32
+ jnc .Lasm_AddDisposableResource.scalar_result_done_2
+ mov r13d, eax
+ movzx eax, BYTE PTR [r14 + r13]
+ jmp [r12 + rax * 8]
+.Lasm_AddDisposableResource.scalar_result_done_2:
+ test rax, rax
+ js .Lexit
+ bt rax, 32
+ jnc .Lasm_AddDisposableResource.slow_path_transfer_3
+ mov r13d, eax
+ movzx eax, BYTE PTR [r14 + r13]
+ jmp [r12 + rax * 8]
+.Lasm_AddDisposableResource.slow_path_transfer_3:
+ mov rcx, QWORD PTR [rbp - 48]
+ mov rbx, QWORD PTR [rcx]
+ add rbx, 128
+ mov rcx, QWORD PTR [rbx + -40]
+ mov r14, QWORD PTR [rcx + 40]
+ mov r13d, eax
+ movzx eax, BYTE PTR [r14 + r13]
+ jmp [r12 + rax * 8]
+asm_handler_AddDisposableResource_hot_end:
+asm_handler_AddDisposableResource_cold:
+asm_handler_AddDisposableResource_cold_end:
+
+.p2align 4
+asm_handler_DisposeResources:
+ mov DWORD PTR [rbx + -64], r13d
+ lea r11, [r14 + r13]
+ mov r10d, DWORD PTR [r11 + 4]
+ mov rax, QWORD PTR [rbx + r10 * 8]
+.Lasm_DisposeResources.scalar_value_ready_0:
+ mov rcx, rax
+ mov r10d, DWORD PTR [r11 + 8]
+ mov rax, QWORD PTR [rbx + r10 * 8]
+.Lasm_DisposeResources.scalar_value_ready_1:
+ mov r8, rax
+ mov r10d, DWORD PTR [r11 + 12]
+ mov rax, QWORD PTR [rbx + r10 * 8]
+.Lasm_DisposeResources.scalar_value_ready_2:
+ mov r9, rax
+ mov rdi, QWORD PTR [rbp - 48]
+ mov esi, r13d
+ lea rdx, [r14 + r13]
+ call CSYM(asm_slow_path_dispose_resources)
+ test rax, rax
+ js .Lasm_DisposeResources.scalar_result_done_3
+ bt rax, 32
+ jnc .Lasm_DisposeResources.scalar_result_done_3
+ mov r13d, eax
+ movzx eax, BYTE PTR [r14 + r13]
+ jmp [r12 + rax * 8]
+.Lasm_DisposeResources.scalar_result_done_3:
+ test rax, rax
+ js .Lexit
+ bt rax, 32
+ jnc .Lasm_DisposeResources.slow_path_transfer_4
+ mov r13d, eax
+ movzx eax, BYTE PTR [r14 + r13]
+ jmp [r12 + rax * 8]
+.Lasm_DisposeResources.slow_path_transfer_4:
+ mov rcx, QWORD PTR [rbp - 48]
+ mov rbx, QWORD PTR [rcx]
+ add rbx, 128
+ mov rcx, QWORD PTR [rbx + -40]
+ mov r14, QWORD PTR [rcx + 40]
+ mov r13d, eax
+ movzx eax, BYTE PTR [r14 + r13]
+ jmp [r12 + rax * 8]
+asm_handler_DisposeResources_hot_end:
+asm_handler_DisposeResources_cold:
+asm_handler_DisposeResources_cold_end:
+
.p2align 4
asm_handler_GetCompletionFields:
mov DWORD PTR [rbx + -64], r13d
diff --git a/Libraries/LibJS/Interpreter/interpreter.flap b/Libraries/LibJS/Interpreter/interpreter.flap
index fc35810f127..b06076104db 100644
--- a/Libraries/LibJS/Interpreter/interpreter.flap
+++ b/Libraries/LibJS/Interpreter/interpreter.flap
@@ -4448,6 +4448,22 @@ handler DeleteVariable(
identifier: IdentifierTableIndex
) @cold = call_slow_path(delete_variable);
+handler NewDisposableResourceStack(
+ dst: out Operand
+) @cold = call_slow_path(new_disposable_resource_stack);
+
+handler AddDisposableResource(
+ stack: Operand,
+ value: Operand,
+ hint: u32
+) @cold = call_slow_path(add_disposable_resource);
+
+handler DisposeResources(
+ stack: Operand,
+ completion_type: Operand,
+ completion_value: Operand
+) @cold = call_slow_path(dispose_resources);
+
handler GetCompletionFields(
type_dst: out Operand,
value_dst: out Operand,
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
index 6aa92fa144b..61820e457a3 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs
@@ -150,7 +150,8 @@ pub fn handling(opcode: OpCode) -> Handling {
| O::CreatePrivateEnvironment
| O::Typeof
| O::IsConstructor
- | O::GetNewTarget => GENERIC_NO_THROW,
+ | O::GetNewTarget
+ | O::NewDisposableResourceStack => GENERIC_NO_THROW,
// Comparisons and conditional jumps, built as IR (see `speculation`).
// The slow paths of the jumps return the next pc.
@@ -341,6 +342,8 @@ pub fn handling(opcode: OpCode) -> Handling {
| O::GetTemplateObject
| O::GetPrivateById
| O::PutPrivateById
+ | O::AddDisposableResource
+ | O::DisposeResources
| O::ExpRhsInt32 => GENERIC,
}
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen.rs b/Libraries/LibJS/Rust/src/bytecode/codegen.rs
index 266f93330f7..171cf87998e 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen.rs
@@ -64,6 +64,7 @@ use super::constant::WellKnownSymbolKind;
use super::generator::BindingLocation;
use super::generator::BlockBoundaryType;
use super::generator::ConstantValue;
+use super::generator::DisposableResourceKind;
use super::generator::FinallyContext;
use super::generator::Generator;
use super::generator::PendingClassBlueprint;
@@ -1139,7 +1140,7 @@ pub fn generate_statement(
// === FunctionBody ===
StatementKind::FunctionBody { scope, .. } => {
let arena = generator.arena.clone();
- generate_scope_children(generator, &arena.scopes[*scope], preferred_dst)
+ generate_scope_children_with_disposal(generator, &arena.scopes[*scope], preferred_dst)
}
// === Program ===
@@ -1156,7 +1157,7 @@ pub fn generate_statement(
for name in &scope.annexb_function_names {
generator.annexb_function_names.insert(name.clone());
}
- generate_scope_children(generator, scope, preferred_dst)
+ generate_scope_children_with_disposal(generator, scope, preferred_dst)
}
// === If ===
@@ -1291,20 +1292,9 @@ pub fn generate_statement(
generate_for_in_of_statement(generator, data.kind, &data.lhs, &data.rhs, &data.body, preferred_dst)
}
- // === UsingDeclaration ===
- StatementKind::UsingDeclaration(_) => {
- // Disposal semantics are not yet implemented.
- let error = generator.allocate_register();
- let msg = generator.intern_string(utf16!("TODO: UsingDeclaration"));
- generator.emit(Instruction::NewTypeError {
- dst: error.operand(),
- error_string: msg,
- });
- generator.perform_needed_unwinds();
- generator.emit(Instruction::Throw { src: error.operand() });
- // Switch to a dead block so subsequent codegen doesn't crash.
- let dead = generator.make_block();
- generator.switch_to_basic_block(dead);
+ // === UsingDeclaration / AwaitUsingDeclaration ===
+ StatementKind::UsingDeclaration(data) => {
+ generate_using_declaration(generator, data);
None
}
@@ -2677,23 +2667,56 @@ fn generate_for_statement(
body: &Statement,
preferred_dst: Option<&ScopedOperand>,
) -> Option<ScopedOperand> {
- // Check if init is a lexical declaration (let/const) with non-local variables.
+ // ForStatement : `for` `(` LexicalDeclaration Expression? `;` Expression? `)` Statement
+ // NB: The resources of a `using` declaration in the head are disposed of when the loop ends,
+ // including when its declaration is abrupt.
+ if let Some(ForInit::Declaration(declaration)) = init
+ && contains_using_declaration(core::iter::once(declaration.as_ref()))
+ {
+ return generate_with_disposable_resource_stack(generator, |generator| {
+ generate_for_statement_without_disposal(generator, init, test, update, body, preferred_dst)
+ });
+ }
+ generate_for_statement_without_disposal(generator, init, test, update, body, preferred_dst)
+}
+
+/// The declarators of a lexical declaration (`let`, `const`, `using` or `await using`), and whether it is a constant
+/// declaration.
+fn lexical_declarators(statement: &Statement) -> Option<(&[VariableDeclarator], bool)> {
+ match &statement.inner {
+ StatementKind::VariableDeclaration(vd)
+ if vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const =>
+ {
+ Some((&vd.declarations, vd.kind == DeclarationKind::Const))
+ }
+ StatementKind::UsingDeclaration(data) => Some((&data.declarations, true)),
+ _ => None,
+ }
+}
+
+fn generate_for_statement_without_disposal(
+ generator: &mut Generator,
+ init: Option<&ForInit>,
+ test: Option<&Expression>,
+ update: Option<&Expression>,
+ body: &Statement,
+ preferred_dst: Option<&ScopedOperand>,
+) -> Option<ScopedOperand> {
+ // Check if init is a lexical declaration (let/const/using) with non-local variables.
// If so, we need to create a lexical environment for the loop variables and
// implement per-iteration copy semantics (CreatePerIterationEnvironment).
let mut has_lexical_environment = false;
let mut per_iteration_binding_names: Vec<Utf16String> = Vec::new();
if let Some(ForInit::Declaration(init)) = init
- && let StatementKind::VariableDeclaration(vd) = &init.inner
- && (vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const)
+ && let Some((declarations, is_const)) = lexical_declarators(init)
{
let mut non_local_names: Vec<(Utf16String, bool)> = Vec::new();
- for declaration in &vd.declarations {
+ for declaration in declarations {
collect_target_names(&declaration.target, &mut non_local_names, &generator.arena);
}
if !non_local_names.is_empty() {
has_lexical_environment = true;
- let is_const = vd.kind == DeclarationKind::Const;
// begin_variable_scope: CreateLexicalEnvironment + boundary
generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
@@ -2916,7 +2939,7 @@ fn generate_block_statement(
let result = if !did_create_env && scope.children.len() == 1 && is_for_loop(&scope.children[0]) {
generate_statement(&scope.children[0], generator, preferred_dst)
} else {
- generate_scope_children(generator, scope, preferred_dst)
+ generate_scope_children_with_disposal(generator, scope, preferred_dst)
};
if did_create_env {
@@ -2925,6 +2948,202 @@ fn generate_block_statement(
result
}
+/// Whether a statement list has `using` declarations directly in it.
+fn contains_using_declaration<'a>(mut statements: impl Iterator<Item = &'a Statement>) -> bool {
+ // FIXME: Dispose of the resources of `await using` declarations.
+ statements.any(|statement| matches!(&statement.inner, StatementKind::UsingDeclaration(data) if !data.is_await))
+}
+
+/// Generate the children of a scope, disposing of the resources of the `using` declarations in it when control
+/// leaves it. Scopes without such declarations are generated exactly like generate_scope_children.
+fn generate_scope_children_with_disposal(
+ generator: &mut Generator,
+ scope: &ScopeData,
+ preferred_dst: Option<&ScopedOperand>,
+) -> Option<ScopedOperand> {
+ if !contains_using_declaration(scope.children.iter()) {
+ return generate_scope_children(generator, scope, preferred_dst);
+ }
+ generate_with_disposable_resource_stack(generator, |generator| {
+ generate_scope_children(generator, scope, preferred_dst)
+ })
+}
+
+/// Generate code that has a new [[DisposableResourceStack]], whose resources are disposed of however control leaves
+/// the code, like a try statement whose finally block performs DisposeResources.
+// https://tc39.es/ecma262/#sec-disposeresources
+fn generate_with_disposable_resource_stack(
+ generator: &mut Generator,
+ body: impl FnOnce(&mut Generator) -> Option<ScopedOperand>,
+) -> Option<ScopedOperand> {
+ let stack = generator.allocate_register();
+ generator.emit(Instruction::NewDisposableResourceStack { dst: stack.operand() });
+ let saved_stack = generator.current_disposable_resource_stack.replace(stack.clone());
+
+ let old_handler = generator.current_unwind_handler;
+ let saved_block = generator.current_block_index();
+ let saved_env = generator.current_lexical_environment();
+
+ let completion_type = generator.allocate_register();
+ let completion_value = generator.allocate_register();
+ let exception_preamble_block = generator.make_block();
+ let dispose_block = generator.make_block();
+
+ let parent_index = generator.current_finally_context;
+ let ctx_index = generator.push_finally_context(FinallyContext {
+ completion_type: completion_type.clone(),
+ completion_value: completion_value.clone(),
+ finally_body: dispose_block,
+ exception_preamble: exception_preamble_block,
+ parent_index,
+ registered_jumps: Vec::new(),
+ next_jump_index: FinallyContext::FIRST_JUMP_INDEX,
+ lexical_environment_at_entry: Some(saved_env.clone()),
+ saved_unwind_handler: None,
+ });
+
+ // Exception preamble: record the throw completion and dispose of the resources.
+ generator.switch_to_basic_block(exception_preamble_block);
+ let value_feedback = generator.next_value_feedback();
+ generator.emit(Instruction::Catch {
+ value_feedback,
+ dst: completion_value.operand(),
+ });
+ generator.emit(Instruction::SetLexicalEnvironment {
+ environment: saved_env.operand(),
+ });
+ let throw_const = generator.add_constant_i32(FinallyContext::THROW);
+ generator.emit_mov(&completion_type, &throw_const);
+ generator.emit(Instruction::Jump { target: dispose_block });
+
+ // Body.
+ generator.current_unwind_handler = Some(exception_preamble_block);
+ let body_block = generator.make_block();
+ generator.switch_to_basic_block(saved_block);
+ generator.emit(Instruction::Jump { target: body_block });
+ generator.start_boundary(BlockBoundaryType::ReturnToFinally);
+ generator.switch_to_basic_block(body_block);
+
+ let result = body(generator);
+
+ if !generator.is_current_block_terminated() {
+ let normal_const = generator.add_constant_i32(FinallyContext::NORMAL);
+ generator.emit_mov(&completion_type, &normal_const);
+ generator.emit(Instruction::Jump { target: dispose_block });
+ }
+ generator.end_boundary(BlockBoundaryType::ReturnToFinally);
+
+ generator.current_unwind_handler = old_handler;
+ generator.current_finally_context = parent_index;
+ generator.current_disposable_resource_stack = saved_stack;
+
+ // Dispose of the resources, which replaces the completion with a throw completion if a dispose method throws.
+ generator.switch_to_basic_block(dispose_block);
+ generator.emit(Instruction::DisposeResources {
+ stack: stack.operand(),
+ completion_type: completion_type.operand(),
+ completion_value: completion_value.operand(),
+ });
+
+ let next_block = generator.make_block();
+ emit_finally_dispatch(generator, ctx_index, &completion_type, &completion_value, next_block);
+
+ let dummy = generator.add_constant_undefined();
+ generator.finally_contexts[ctx_index].lexical_environment_at_entry = None;
+ generator.finally_contexts[ctx_index].completion_value = dummy.clone();
+ generator.finally_contexts[ctx_index].completion_type = dummy;
+
+ generator.switch_to_basic_block(next_block);
+ result
+}
+
+// https://tc39.es/ecma262/#sec-let-and-const-declarations-runtime-semantics-evaluation
+// UsingDeclaration : `using` BindingList `;`
+// AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList `;`
+fn generate_using_declaration(generator: &mut Generator, data: &UsingDeclarationData) {
+ if data.is_await {
+ emit_await_using_declaration_todo(generator);
+ return;
+ }
+
+ // 1. Perform ? BindingEvaluation of BindingList with argument sync-dispose.
+ let kind = DisposableResourceKind::SyncDispose;
+ for declaration in &data.declarations {
+ let VariableDeclaratorTarget::Identifier(id) = &declaration.target else {
+ unreachable!("using declarations only bind identifiers");
+ };
+ let value = generate_expression_or_undefined_with_lhs_name(generator, *id, declaration.init.as_ref());
+ emit_add_disposable_resource_and_initialize_binding(generator, *id, &value, kind);
+ }
+ // 2. Return empty.
+}
+
+// FIXME: Dispose of the resources of `await using` declarations.
+fn emit_await_using_declaration_todo(generator: &mut Generator) {
+ let error = generator.allocate_register();
+ let msg = generator.intern_string(utf16!("TODO: AwaitUsingDeclaration"));
+ generator.emit(Instruction::NewTypeError {
+ dst: error.operand(),
+ error_string: msg,
+ });
+ generator.perform_needed_unwinds();
+ generator.emit(Instruction::Throw { src: error.operand() });
+ // Switch to a dead block so subsequent codegen doesn't crash.
+ let dead = generator.make_block();
+ generator.switch_to_basic_block(dead);
+}
+
+/// Evaluates the Initializer of a LexicalBinding, as NamedEvaluation with the name of the binding if it is an
+/// anonymous function definition.
+fn generate_expression_or_undefined_with_lhs_name(
+ generator: &mut Generator,
+ id: IdentifierId,
+ init: Option<&Expression>,
+) -> ScopedOperand {
+ let arena = generator.arena.clone();
+ generator.pending_lhs_name = Some(generator.intern_identifier_id(arena.identifiers[id].name));
+ let value = init.and_then(|init| generate_expression(init, generator, None));
+ generator.pending_lhs_name = None;
+ value.unwrap_or_else(|| generator.add_constant_undefined())
+}
+
+// https://tc39.es/ecma262/#sec-bindingevaluation
+// LexicalBinding : BindingIdentifier Initializer
+fn emit_add_disposable_resource_and_initialize_binding(
+ generator: &mut Generator,
+ id: IdentifierId,
+ value: &ScopedOperand,
+ kind: DisposableResourceKind,
+) {
+ // 5. If kind is not normal, then
+ // a. Assert: IsUnresolvableReference(lhs) is false.
+ // b. Let base be lhs.[[Base]].
+ // c. Assert: base is a Declarative Environment Record.
+ // d. Perform ? AddDisposableResource(base.[[DisposableResourceStack]], value, kind).
+ let stack = generator
+ .current_disposable_resource_stack
+ .clone()
+ .expect("a using declaration is in a scope with a disposable resource stack");
+ generator.emit(Instruction::AddDisposableResource {
+ stack: stack.operand(),
+ value: value.operand(),
+ hint: kind as u32,
+ });
+
+ // 6. Perform ? InitializeReferencedBinding(lhs, value).
+ let arena = generator.arena.clone();
+ let ident = &arena.identifiers[id];
+ if ident.is_local() {
+ let local_index = ident.local_index;
+ let local = generator.resolve_local(local_index, ident.local_type.unwrap());
+ generator.emit_mov(&local, value);
+ generator.mark_local_initialized(local_index);
+ } else {
+ let identifier = generator.intern_identifier_id(ident.name);
+ emit_initialize_lexical_binding(generator, identifier, value.operand());
+ }
+}
+
/// Create lexical bindings and instantiate function declarations for a block.
/// All bindings are created before any function is instantiated, so every
/// function closes over the complete binding layout of the block.
@@ -7048,11 +7267,10 @@ fn get_private_identifier_name(key: &Expression) -> Option<Utf16String> {
/// meaning we need a per-iteration lexical environment.
fn for_in_of_needs_lexical_env(lhs: &ForInOfLhs, arena: &crate::ast::AstArena) -> bool {
if let ForInOfLhs::Declaration(statement) = lhs
- && let StatementKind::VariableDeclaration(vd) = &statement.inner
- && (vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const)
+ && let Some((declarations, _)) = lexical_declarators(statement)
{
let mut names = Vec::new();
- for declaration in &vd.declarations {
+ for declaration in declarations {
collect_target_names(&declaration.target, &mut names, arena);
}
return !names.is_empty();
@@ -7118,10 +7336,10 @@ fn create_for_in_of_lexical_env(generator: &mut Generator, lhs: &ForInOfLhs) ->
let mut binding_names: Vec<(Utf16String, bool)> = Vec::new();
let mut is_constant = false;
if let ForInOfLhs::Declaration(statement) = lhs
- && let StatementKind::VariableDeclaration(vd) = &statement.inner
+ && let Some((declarations, is_constant_declaration)) = lexical_declarators(statement)
{
- is_constant = vd.kind == DeclarationKind::Const;
- for declaration in &vd.declarations {
+ is_constant = is_constant_declaration;
+ for declaration in declarations {
collect_target_names(&declaration.target, &mut binding_names, &generator.arena);
}
}
@@ -7151,11 +7369,10 @@ fn create_for_in_of_lexical_env(generator: &mut Generator, lhs: &ForInOfLhs) ->
/// Returns true if a TDZ scope was entered (must call leave_for_in_of_head_tdz after RHS eval).
fn enter_for_in_of_head_tdz(generator: &mut Generator, lhs: &ForInOfLhs) -> bool {
if let ForInOfLhs::Declaration(statement) = lhs
- && let StatementKind::VariableDeclaration(vd) = &statement.inner
- && (vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const)
+ && let Some((declarations, _)) = lexical_declarators(statement)
{
let mut names = Vec::new();
- for declaration in &vd.declarations {
+ for declaration in declarations {
collect_target_names(&declaration.target, &mut names, &generator.arena);
}
if !names.is_empty() {
@@ -7554,17 +7771,38 @@ fn generate_for_of_statement_inner(
None
};
- // Assign to LHS
- assign_to_for_in_of_lhs(generator, lhs, &next_value);
+ let has_using_declaration = match lhs {
+ ForInOfLhs::Declaration(statement) => contains_using_declaration(core::iter::once(statement.as_ref())),
+ _ => false,
+ };
- // Body
- generator.begin_continuable_scope(update_block, labels, completion.clone());
- if needs_lexical_env {
- generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
- }
+ if has_using_declaration {
+ // NB: The resource of a `using` declaration is disposed of at the end of each iteration,
+ // including when the declaration is abrupt, and before the iterator is closed.
+ generator.begin_continuable_scope(update_block, labels, completion.clone());
+ if needs_lexical_env {
+ generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
+ }
+ generate_with_disposable_resource_stack(generator, |generator| {
+ assign_to_for_in_of_lhs(generator, lhs, &next_value);
+ if !generator.is_current_block_terminated() {
+ generate_with_completion(body, generator, completion.as_ref(), preferred_dst);
+ }
+ None
+ });
+ } else {
+ // Assign to LHS
+ assign_to_for_in_of_lhs(generator, lhs, &next_value);
- if !generator.is_current_block_terminated() {
- generate_with_completion(body, generator, completion.as_ref(), preferred_dst);
+ // Body
+ generator.begin_continuable_scope(update_block, labels, completion.clone());
+ if needs_lexical_env {
+ generator.start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
+ }
+
+ if !generator.is_current_block_terminated() {
+ generate_with_completion(body, generator, completion.as_ref(), preferred_dst);
+ }
}
// Restore lexical env before continuing
@@ -7849,23 +8087,29 @@ fn generate_for_of_statement_inner(
fn assign_to_for_in_of_lhs(generator: &mut Generator, lhs: &ForInOfLhs, value: &ScopedOperand) {
match lhs {
ForInOfLhs::Declaration(statement) => {
- // UsingDeclaration: disposal semantics not yet implemented.
- // UsingDeclaration is not recognized as a VariableDeclaration
- // in for_in_of_head_evaluation, so it is treated as Assignment
- // lhs_kind. This produces NewTypeError + Throw for the using
- // declaration, followed by NewReferenceError + Throw (dead code).
- if matches!(statement.inner, StatementKind::UsingDeclaration(_)) {
- generate_statement(statement, generator, None);
- let exception = generator.allocate_register();
- let error_string = generator.intern_string(utf16!("Invalid left-hand side in assignment"));
- generator.emit(Instruction::NewReferenceError {
- dst: exception.operand(),
- error_string,
- });
- generator.perform_needed_unwinds();
- generator.emit(Instruction::Throw {
- src: exception.operand(),
- });
+ // NB: For a `using` declaration, these are steps 8.h.vii.4 and 8.h.vii.6 of
+ // ForIn/OfBodyEvaluation.
+ if let StatementKind::UsingDeclaration(data) = &statement.inner {
+ // 4. If declKind is not normal, then
+ // a. Assert: IsUnresolvableReference(lhsRef) is false.
+ // b. Let base be lhsRef.[[Base]].
+ // c. Assert: base is a Declarative Environment Record.
+ // d. Let status be Completion(AddDisposableResource(base.[[DisposableResourceStack]], nextValue, declKind)).
+ // 6. If status is a normal completion, then
+ // a. Set status to Completion(InitializeReferencedBinding(lhsRef, nextValue)).
+ let VariableDeclaratorTarget::Identifier(id) = &data.declarations[0].target else {
+ unreachable!("using declarations only bind identifiers");
+ };
+ if data.is_await {
+ emit_await_using_declaration_todo(generator);
+ return;
+ }
+ emit_add_disposable_resource_and_initialize_binding(
+ generator,
+ *id,
+ value,
+ DisposableResourceKind::SyncDispose,
+ );
return;
}
// The declaration is a VariableDeclaration with a single declarator
@@ -8830,68 +9074,7 @@ fn generate_try_statement(
}
let nb = next_block.expect("next_block must be set");
- // After-finally dispatch chain:
- // 1. NORMAL → next block
- let after_normal_check = generator.make_block();
- let normal_const = generator.add_constant_i32(FinallyContext::NORMAL);
- let arith_feedback = generator.next_arith_feedback();
- generator.emit(Instruction::JumpStrictlyEquals {
- arith_feedback,
- lhs: ctx_ct.operand(),
- rhs: normal_const.operand(),
- true_target: nb,
- false_target: after_normal_check,
- });
- generator.switch_to_basic_block(after_normal_check);
-
- // 2. Registered break/continue jumps
- let registered_jumps = std::mem::take(&mut generator.finally_contexts[ctx_index].registered_jumps);
- for jump in &registered_jumps {
- let after_jump_check = generator.make_block();
- let jump_const = generator.add_constant_i32(jump.index);
- let arith_feedback = generator.next_arith_feedback();
- generator.emit(Instruction::JumpStrictlyEquals {
- arith_feedback,
- lhs: ctx_ct.operand(),
- rhs: jump_const.operand(),
- true_target: jump.target,
- false_target: after_jump_check,
- });
- generator.switch_to_basic_block(after_jump_check);
- }
-
- // 3. RETURN → actually return the completion_value
- let return_block = generator.make_block();
- let rethrow_block = generator.make_block();
- let return_const = generator.add_constant_i32(FinallyContext::RETURN);
- let arith_feedback = generator.next_arith_feedback();
- generator.emit(Instruction::JumpStrictlyEquals {
- arith_feedback,
- lhs: ctx_ct.operand(),
- rhs: return_const.operand(),
- true_target: return_block,
- false_target: rethrow_block,
- });
-
- // Generate return block.
- generator.switch_to_basic_block(return_block);
- if let Some(outer_index) = generator.current_finally_context {
- // Nested finally: copy completion record to outer and jump to outer finally.
- generator.forward_completion_to_outer_finally(outer_index, &ctx_ct, &ctx_cv);
- } else if generator.is_in_generator_function() {
- generator.emit(Instruction::Yield {
- continuation_label: None,
- value: ctx_cv.operand(),
- });
- } else {
- generator.emit(Instruction::Return {
- value: ctx_cv.operand(),
- });
- }
-
- // 4. Default → rethrow the exception.
- generator.switch_to_basic_block(rethrow_block);
- generator.emit(Instruction::Throw { src: ctx_cv.operand() });
+ emit_finally_dispatch(generator, ctx_index, &ctx_ct, &ctx_cv, nb);
}
generator.finally_contexts[ctx_index].lexical_environment_at_entry = None;
@@ -8911,6 +9094,79 @@ fn generate_try_statement(
completion
}
+/// Emit the jumps that continue after the body of a finally context, according to the type of the completion it
+/// recorded: to the next block, to a registered break or continue target, to a return, or to a rethrow.
+fn emit_finally_dispatch(
+ generator: &mut Generator,
+ ctx_index: usize,
+ ctx_ct: &ScopedOperand,
+ ctx_cv: &ScopedOperand,
+ nb: Label,
+) {
+ // After-finally dispatch chain:
+ // 1. NORMAL → next block
+ let after_normal_check = generator.make_block();
+ let normal_const = generator.add_constant_i32(FinallyContext::NORMAL);
+ let arith_feedback = generator.next_arith_feedback();
+ generator.emit(Instruction::JumpStrictlyEquals {
+ arith_feedback,
+ lhs: ctx_ct.operand(),
+ rhs: normal_const.operand(),
+ true_target: nb,
+ false_target: after_normal_check,
+ });
+ generator.switch_to_basic_block(after_normal_check);
+
+ // 2. Registered break/continue jumps
+ let registered_jumps = std::mem::take(&mut generator.finally_contexts[ctx_index].registered_jumps);
+ for jump in &registered_jumps {
+ let after_jump_check = generator.make_block();
+ let jump_const = generator.add_constant_i32(jump.index);
+ let arith_feedback = generator.next_arith_feedback();
+ generator.emit(Instruction::JumpStrictlyEquals {
+ arith_feedback,
+ lhs: ctx_ct.operand(),
+ rhs: jump_const.operand(),
+ true_target: jump.target,
+ false_target: after_jump_check,
+ });
+ generator.switch_to_basic_block(after_jump_check);
+ }
+
+ // 3. RETURN → actually return the completion_value
+ let return_block = generator.make_block();
+ let rethrow_block = generator.make_block();
+ let return_const = generator.add_constant_i32(FinallyContext::RETURN);
+ let arith_feedback = generator.next_arith_feedback();
+ generator.emit(Instruction::JumpStrictlyEquals {
+ arith_feedback,
+ lhs: ctx_ct.operand(),
+ rhs: return_const.operand(),
+ true_target: return_block,
+ false_target: rethrow_block,
+ });
+
+ // Generate return block.
+ generator.switch_to_basic_block(return_block);
+ if let Some(outer_index) = generator.current_finally_context {
+ // Nested finally: copy completion record to outer and jump to outer finally.
+ generator.forward_completion_to_outer_finally(outer_index, ctx_ct, ctx_cv);
+ } else if generator.is_in_generator_function() {
+ generator.emit(Instruction::Yield {
+ continuation_label: None,
+ value: ctx_cv.operand(),
+ });
+ } else {
+ generator.emit(Instruction::Return {
+ value: ctx_cv.operand(),
+ });
+ }
+
+ // 4. Default → rethrow the exception.
+ generator.switch_to_basic_block(rethrow_block);
+ generator.emit(Instruction::Throw { src: ctx_cv.operand() });
+}
+
/// Create a SharedFunctionInstanceData for a function expression/declaration
/// and register it with the generator.
///
@@ -9330,44 +9586,39 @@ pub fn emit_function_declaration_instantiation(
// --- Step 8: Create lexical bindings ---
for child in &body_scope.children {
- match &child.inner {
- StatementKind::VariableDeclaration(vd)
- if vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const =>
- {
- let is_constant = vd.kind == DeclarationKind::Const;
- for declaration in &vd.declarations {
- let mut names = Vec::new();
- collect_target_names(&declaration.target, &mut names, &generator.arena);
- for (name, _) in names {
- let id = generator.intern_identifier(&name);
- generator.emit(Instruction::CreateVariable {
- identifier: id,
- mode: EnvironmentMode::Lexical as u32,
- is_immutable: is_constant,
- is_global: false,
- is_strict: is_constant,
- });
- }
+ if let Some((declarations, is_constant)) = lexical_declarators(child) {
+ for declaration in declarations {
+ let mut names = Vec::new();
+ collect_target_names(&declaration.target, &mut names, &generator.arena);
+ for (name, _) in names {
+ let id = generator.intern_identifier(&name);
+ generator.emit(Instruction::CreateVariable {
+ identifier: id,
+ mode: EnvironmentMode::Lexical as u32,
+ is_immutable: is_constant,
+ is_global: false,
+ is_strict: is_constant,
+ });
}
}
- StatementKind::ClassDeclaration(class_data) => {
- // Class declarations are lexically scoped (like const).
- if let Some(name_ident_id) = class_data.name {
- let arena = generator.arena.clone();
- let name_ident = &arena.identifiers[name_ident_id];
- if !name_ident.is_local() {
- let id = generator.intern_identifier_id(name_ident.name);
- generator.emit(Instruction::CreateVariable {
- identifier: id,
- mode: EnvironmentMode::Lexical as u32,
- is_immutable: false,
- is_global: false,
- is_strict: false,
- });
- }
+ continue;
+ }
+ if let StatementKind::ClassDeclaration(class_data) = &child.inner {
+ // Class declarations are lexically scoped (like const).
+ if let Some(name_ident_id) = class_data.name {
+ let arena = generator.arena.clone();
+ let name_ident = &arena.identifiers[name_ident_id];
+ if !name_ident.is_local() {
+ let id = generator.intern_identifier_id(name_ident.name);
+ generator.emit(Instruction::CreateVariable {
+ identifier: id,
+ mode: EnvironmentMode::Lexical as u32,
+ is_immutable: false,
+ is_global: false,
+ is_strict: false,
+ });
}
}
- _ => {}
}
}
@@ -9507,16 +9758,15 @@ fn count_lexical_declarations_for_block<'a>(
fn count_non_local_lexical_bindings(scope: &ScopeData, arena: &crate::ast::AstArena) -> u32 {
let mut count = 0u32;
for child in &scope.children {
- match &child.inner {
- StatementKind::VariableDeclaration(vd)
- if vd.kind == DeclarationKind::Let || vd.kind == DeclarationKind::Const =>
- {
- for declaration in &vd.declarations {
- let mut names = Vec::new();
- collect_target_names(&declaration.target, &mut names, arena);
- count += u32_from_usize(names.len());
- }
+ if let Some((declarations, _)) = lexical_declarators(child) {
+ for declaration in declarations {
+ let mut names = Vec::new();
+ collect_target_names(&declaration.target, &mut names, arena);
+ count += u32_from_usize(names.len());
}
+ continue;
+ }
+ match &child.inner {
StatementKind::ClassDeclaration(class_data)
if class_data.name.is_some_and(|n| !arena.identifiers[n].is_local()) =>
{
diff --git a/Libraries/LibJS/Rust/src/bytecode/generator.rs b/Libraries/LibJS/Rust/src/bytecode/generator.rs
index a63ab1fb618..afea70fb2a6 100644
--- a/Libraries/LibJS/Rust/src/bytecode/generator.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/generator.rs
@@ -292,6 +292,13 @@ impl FinallyContext {
pub const FIRST_JUMP_INDEX: i32 = 3;
}
+/// The kind of a disposable resource, as the hint operand of AddDisposableResource encodes it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u32)]
+pub enum DisposableResourceKind {
+ SyncDispose = 0,
+}
+
/// A break/continue target registered with a FinallyContext.
pub struct FinallyJump {
pub index: i32,
@@ -367,6 +374,8 @@ pub struct Generator {
// This avoids the deep-clone issues of an owned Box parent chain.
pub finally_contexts: Vec<FinallyContext>,
pub current_finally_context: Option<usize>,
+ /// The [[DisposableResourceStack]] of the innermost scope that has `using` or `await using` declarations.
+ pub current_disposable_resource_stack: Option<ScopedOperand>,
// --- Various counters ---
pub next_property_lookup_cache: u32,
@@ -554,6 +563,7 @@ impl Generator {
home_objects: Vec::new(),
finally_contexts: Vec::new(),
current_finally_context: None,
+ current_disposable_resource_stack: None,
next_property_lookup_cache: 0,
next_global_variable_cache: 0,
next_environment_coordinate_cache: 0,
diff --git a/Libraries/LibJS/Rust/src/bytecode_cache.rs b/Libraries/LibJS/Rust/src/bytecode_cache.rs
index 6183923fd98..aaa257ccbd1 100644
--- a/Libraries/LibJS/Rust/src/bytecode_cache.rs
+++ b/Libraries/LibJS/Rust/src/bytecode_cache.rs
@@ -1302,7 +1302,7 @@ fn collect_script_lexical_bindings(
for_each_bound_name(&declarator.target, arena, &mut |name| {
bindings.push(LexicalBindingRecord {
name: name.to_vec().into(),
- is_constant: false,
+ is_constant: true,
});
});
}
@@ -1516,7 +1516,7 @@ fn collect_module_declaration(
for_each_bound_name(&declarator.target, arena, &mut |name| {
metadata.lexical_bindings.push(ModuleLexicalBindingRecord {
name: name.to_vec().into(),
- is_constant: false,
+ is_constant: true,
function_index: -1,
});
});
diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rs
index 35c00378297..116862090fe 100644
--- a/Libraries/LibJS/Rust/src/compile.rs
+++ b/Libraries/LibJS/Rust/src/compile.rs
@@ -1237,7 +1237,7 @@ pub fn collect_module_declarations(
for_each_bound_name(&declarator.target, arena, &mut |name| {
declarations.lexical_bindings.push(ModuleLexicalBinding {
name: name.to_vec().into(),
- is_constant: false,
+ is_constant: true,
function_index: None,
});
});
@@ -1852,7 +1852,7 @@ fn collect_var_scoped_declarations(
for_each_bound_name(&declaration.target, arena, &mut |name| {
lexical_bindings.push(LexicalBinding {
name: name.into(),
- is_constant: false,
+ is_constant: true,
});
});
}
diff --git a/Libraries/LibJS/Rust/src/gc/class_id.rs b/Libraries/LibJS/Rust/src/gc/class_id.rs
index b603e275715..a1df63031be 100644
--- a/Libraries/LibJS/Rust/src/gc/class_id.rs
+++ b/Libraries/LibJS/Rust/src/gc/class_id.rs
@@ -250,6 +250,7 @@ define_class_ids! {
AtomicsObject,
IteratorHelper,
FlatMapIterator,
+ DisposableResourceStack,
ConcatIterator,
ZipIterator,
DisposableStack,
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs
index 9d9232b9efd..e9648ad46d5 100644
--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs
@@ -9,6 +9,7 @@
use ak::{Utf16FlyString, Utf16String};
use crate::bytecode::executable::StaticPropertyLookupCacheSite;
+use crate::bytecode::generator::{DisposableResourceKind, FinallyContext};
use crate::bytecode::op;
use crate::debugger::PauseReason;
use crate::interpreter::runtime_functions::{SlowPathControl, asm_try, handle_asm_exception};
@@ -24,7 +25,9 @@ use crate::runtime::array_iterator::{
};
use crate::runtime::async_from_sync_iterator_prototype::create_async_from_sync_iterator;
use crate::runtime::async_generator::AsyncGenerator;
-use crate::runtime::completion::{Completion, Must, ThrowCompletionOr, completion_type_from_bytecode};
+use crate::runtime::completion::{Completion, CompletionType, Must, ThrowCompletionOr, completion_type_from_bytecode};
+use crate::runtime::disposable_resource_stack::DisposableResourceStack;
+use crate::runtime::environment::InitializeBindingHint;
use crate::runtime::error::ErrorKind;
use crate::runtime::error_types::ErrorType;
use crate::runtime::generator_object::GeneratorObject;
@@ -632,6 +635,49 @@ pub fn create_async_from_sync_iterator_slow_path(
SlowPathControl::continue_at(pc + op::CreateAsyncFromSyncIterator::LENGTH)
}
+pub fn new_disposable_resource_stack(
+ vm: &Vm,
+ pc: u32,
+ values: &mut op::NewDisposableResourceStackValues,
+) -> SlowPathControl {
+ values.dst = DisposableResourceStack::to_value(DisposableResourceStack::create(vm));
+ SlowPathControl::continue_at(pc + op::NewDisposableResourceStack::LENGTH)
+}
+
+pub fn add_disposable_resource(
+ vm: &Vm,
+ pc: u32,
+ instruction: &op::AddDisposableResource,
+ values: &mut op::AddDisposableResourceValues,
+) -> SlowPathControl {
+ debug_assert_eq!(instruction.hint, DisposableResourceKind::SyncDispose as u32);
+ let hint = InitializeBindingHint::SyncDispose;
+ let stack = DisposableResourceStack::from_value(values.stack);
+ asm_try!(vm, pc, stack.add_disposable_resource(vm, values.value, hint));
+ SlowPathControl::continue_at(pc + op::AddDisposableResource::LENGTH)
+}
+
+/// The completion of a scope as the bytecode keeps it while it disposes of the resources of the scope: a throw
+/// completion if its type is the throw type of a finally context, and a normal one otherwise. The resources are
+/// disposed of the same way for every other type.
+fn completion_of_scope(completion_type: Value, completion_value: Value) -> Completion {
+ if completion_type.is_int32() && completion_type.as_i32() == FinallyContext::THROW {
+ Completion::new(CompletionType::Throw, completion_value)
+ } else {
+ Completion::normal(Value::UNDEFINED)
+ }
+}
+
+pub fn dispose_resources(vm: &Vm, pc: u32, values: &mut op::DisposeResourcesValues) -> SlowPathControl {
+ let stack = DisposableResourceStack::from_value(values.stack);
+ let completion = completion_of_scope(values.completion_type, values.completion_value);
+ let result = stack.dispose_resources(vm, completion);
+ if result.is_error() {
+ return handle_asm_exception(vm, pc, result.value());
+ }
+ SlowPathControl::continue_at(pc + op::DisposeResources::LENGTH)
+}
+
pub fn get_completion_fields(_vm: &Vm, pc: u32, values: &mut op::GetCompletionFieldsValues) -> SlowPathControl {
let completion_source = values.completion.as_object();
if let Some(generator) = completion_source.downcast::<GeneratorObject>() {
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs
index ee5c35b3ec5..9103c8498b5 100644
--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs
@@ -1363,6 +1363,33 @@ impl RuntimeFunctions for Runtime {
control::create_async_from_sync_iterator_slow_path(vm, pc, values)
}
+ fn new_disposable_resource_stack(
+ vm: &Vm,
+ pc: u32,
+ _instruction: &op::NewDisposableResourceStack,
+ values: &mut op::NewDisposableResourceStackValues,
+ ) -> SlowPathControl {
+ control::new_disposable_resource_stack(vm, pc, values)
+ }
+
+ fn add_disposable_resource(
+ vm: &Vm,
+ pc: u32,
+ instruction: &op::AddDisposableResource,
+ values: &mut op::AddDisposableResourceValues,
+ ) -> SlowPathControl {
+ control::add_disposable_resource(vm, pc, instruction, values)
+ }
+
+ fn dispose_resources(
+ vm: &Vm,
+ pc: u32,
+ _instruction: &op::DisposeResources,
+ values: &mut op::DisposeResourcesValues,
+ ) -> SlowPathControl {
+ control::dispose_resources(vm, pc, values)
+ }
+
fn get_completion_fields(
vm: &Vm,
pc: u32,
diff --git a/Libraries/LibJS/Rust/src/runtime/disposable_resource_stack.rs b/Libraries/LibJS/Rust/src/runtime/disposable_resource_stack.rs
new file mode 100644
index 00000000000..aa481a3a893
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/runtime/disposable_resource_stack.rs
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use libjs_runtime_macros::Trace;
+
+use crate::gc::class::{Finalize, GcCell, class_of, define_cell};
+use crate::gc::gc_ref_cell::GcRefCell;
+use crate::interpreter::vm::Vm;
+use crate::layout::cell::{CellHeader, Gc};
+use crate::layout::value::Value;
+use crate::runtime::abstract_operations::{
+ DisposeCapability, add_disposable_resource, dispose_resources, new_dispose_capability,
+};
+use crate::runtime::completion::{Completion, ThrowCompletionOr};
+use crate::runtime::environment::InitializeBindingHint;
+use libjs_abi::value as nan_box;
+
+/// The [[DisposableResourceStack]] of a Block, ForStatement, ForInOfStatement iteration, function body or module that
+/// contains `using` declarations. The bytecode keeps it in a register rather than in an environment, since the
+/// bindings of these declarations are often locals that live in no environment.
+#[repr(C)]
+#[derive(Trace)]
+pub struct DisposableResourceStack {
+ header: CellHeader,
+ dispose_capability: GcRefCell<DisposeCapability>,
+}
+
+define_cell!(DisposableResourceStack, Other, finalize: finalize);
+
+impl Finalize for DisposableResourceStack {
+ fn finalize(&self) {
+ drop(self.dispose_capability.replace(new_dispose_capability()));
+ }
+}
+
+impl DisposableResourceStack {
+ pub fn create(vm: &Vm) -> Gc<DisposableResourceStack> {
+ vm.heap().allocate(DisposableResourceStack {
+ header: CellHeader::for_class(Self::CLASS),
+ dispose_capability: GcRefCell::new(new_dispose_capability()),
+ })
+ }
+
+ /// The stack as the interpreter keeps it in a register: a cell value without a more specific tag.
+ pub fn to_value(stack: Gc<DisposableResourceStack>) -> Value {
+ Value::with_cell_tag(nan_box::IS_CELL_BIT, stack)
+ }
+
+ /// The stack a register holds, which must be one.
+ pub fn from_value(value: Value) -> Gc<DisposableResourceStack> {
+ assert!(value.is_cell());
+ // SAFETY: The value holds a cell, and every cell starts with its class, which is checked below.
+ let stack = unsafe { value.cell::<DisposableResourceStack>() };
+ assert!(
+ class_of(stack).is_subclass_of(Self::CLASS),
+ "the cell is not a disposable resource stack"
+ );
+ stack
+ }
+
+ pub fn add_disposable_resource(&self, vm: &Vm, value: Value, hint: InitializeBindingHint) -> ThrowCompletionOr<()> {
+ add_disposable_resource(vm, &self.dispose_capability, value, hint, None)
+ }
+
+ pub fn dispose_resources(&self, vm: &Vm, completion: Completion) -> Completion {
+ // NB: Every resource of the stack has the sync-dispose kind, so this never awaits.
+ dispose_resources(vm, &self.dispose_capability, completion)
+ }
+}
diff --git a/Libraries/LibJS/Rust/src/runtime/mod.rs b/Libraries/LibJS/Rust/src/runtime/mod.rs
index 33e403acd97..ee51d26d0b9 100644
--- a/Libraries/LibJS/Rust/src/runtime/mod.rs
+++ b/Libraries/LibJS/Rust/src/runtime/mod.rs
@@ -64,6 +64,7 @@ pub mod date_parser;
pub mod date_prototype;
pub mod declarative_environment;
pub mod descriptor_array;
+pub mod disposable_resource_stack;
pub mod disposable_stack;
pub mod disposable_stack_constructor;
pub mod disposable_stack_prototype;
diff --git a/Tests/LibJS/Bytecode/expected/using-declaration-non-local-env.txt b/Tests/LibJS/Bytecode/expected/using-declaration-non-local-env.txt
index 31228774202..c5ae0486ed6 100644
--- a/Tests/LibJS/Bytecode/expected/using-declaration-non-local-env.txt
+++ b/Tests/LibJS/Bytecode/expected/using-declaration-non-local-env.txt
@@ -25,23 +25,53 @@ Exception handlers:
[ 40 .. a0] => handler block1
-$dd396d91 using-declaration-non-local-env.js:1:21
- Registers: 8
- Blocks: 2
+$9b8ec936 using-declaration-non-local-env.js:1:21
+ Registers: 11
+ Blocks: 8
Constants:
- [0] = Undefined
+ [0] = Int32(1)
+ [1] = Undefined
+ [2] = Int32(0)
+ [3] = Int32(2)
block0:
[ 0] Enter
[ 8] GetLexicalEnvironment dst:reg4
[ 10] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false
[ 28] CreateImmutableBinding environment:reg5, `x`, strict_binding:true
- [ 38] NewTypeError dst:reg6, TODO: UsingDeclaration
- [ 48] SetLexicalEnvironment environment:reg4
- [ 50] Throw src:reg6
+ [ 38] NewDisposableResourceStack dst:reg6
+ [ 40] Jump target:block3
block1:
- [ 58] NewFunction dst:reg7, shared_function_data_index:0
- [ 70] Call value_feedback:0, call_feedback:0, dst:reg6, callee:reg7, this_value:Undefined
- [ 90] SetLexicalEnvironment environment:reg4
- [ 98] End value:Undefined
+ [ 48] Catch value_feedback:0, dst:reg8
+ [ 50] SetLexicalEnvironment environment:reg5
+ [ 58] Mov dst:reg7, src:Int32(1)
+
+block2:
+ [ 68] DisposeResources stack:reg6, completion_type:reg7, completion_value:reg8
+ [ 78] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg7, rhs:0, true_target:block4, false_target:block5
+
+block3:
+ [ 90] NewObject dst:reg9
+ [ a0] AddDisposableResource stack:reg6, value:reg9, hint:0
+ [ b0] InitializeLexicalBinding `x`, src:reg9
+ [ c8] NewFunction dst:reg10, shared_function_data_index:0
+ [ e0] Call value_feedback:1, call_feedback:0, dst:reg9, callee:reg10, this_value:Undefined
+ [ 100] Mov dst:reg7, src:Int32(0)
+ [ 110] JumpLoop target:block2
+
+block4:
+ [ 118] SetLexicalEnvironment environment:reg4
+ [ 120] End value:Undefined
+
+block5:
+ [ 128] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:reg7, rhs:2, true_target:block6, false_target:block7
+
+block6:
+ [ 140] Return value:reg8
+
+block7:
+ [ 148] Throw src:reg8
+
+Exception handlers:
+ [ 90 .. 118] => handler block1
diff --git a/Tests/LibJS/Runtime/builtins/DisposableStack/DisposableStack.prototype.@@dispose.js b/Tests/LibJS/Runtime/builtins/DisposableStack/DisposableStack.prototype.@@dispose.js
index 1199c8c0d96..62c76f8e770 100644
--- a/Tests/LibJS/Runtime/builtins/DisposableStack/DisposableStack.prototype.@@dispose.js
+++ b/Tests/LibJS/Runtime/builtins/DisposableStack/DisposableStack.prototype.@@dispose.js
@@ -7,7 +7,7 @@ test("is the same as dispose", () => {
});
describe("used in using functionality", () => {
- test.xfail("make the stack marked as disposed", () => {
+ test("make the stack marked as disposed", () => {
let innerStack;
{
using stack = new DisposableStack();
diff --git a/Tests/LibJS/Runtime/modules/basic-modules.js b/Tests/LibJS/Runtime/modules/basic-modules.js
index 0664854cd2a..5c2cb071f4b 100644
--- a/Tests/LibJS/Runtime/modules/basic-modules.js
+++ b/Tests/LibJS/Runtime/modules/basic-modules.js
@@ -224,7 +224,7 @@ describe("in- and exports", () => {
expectModulePassed("./anon-func-decl-default-export.mjs");
});
- test.xfail("can have top level using declarations which trigger at the end of running a module", () => {
+ test("can have top level using declarations which trigger at the end of running a module", () => {
expectModulePassed("./top-level-dispose.mjs");
});
diff --git a/Tests/LibJS/Runtime/using-declaration.js b/Tests/LibJS/Runtime/using-declaration.js
index 50318d58550..80867c8d6b0 100644
--- a/Tests/LibJS/Runtime/using-declaration.js
+++ b/Tests/LibJS/Runtime/using-declaration.js
@@ -1,5 +1,5 @@
describe("basic usage", () => {
- test.xfail("disposes after block exit", () => {
+ test("disposes after block exit", () => {
let disposed = false;
let inBlock = false;
{
@@ -17,7 +17,7 @@ describe("basic usage", () => {
expect(disposed).toBeTrue();
});
- test.xfail("disposes in reverse order after block exit", () => {
+ test("disposes in reverse order after block exit", () => {
const disposed = [];
{
expect(disposed).toHaveLength(0);
@@ -37,7 +37,7 @@ describe("basic usage", () => {
expect(disposed).toEqual(["b", "a"]);
});
- test.xfail("disposes in reverse order after block exit even in same declaration", () => {
+ test("disposes in reverse order after block exit even in same declaration", () => {
const disposed = [];
{
expect(disposed).toHaveLength(0);
@@ -63,7 +63,7 @@ describe("behavior with exceptions", () => {
this.name = name;
}
- test.xfail("is run even after throw", () => {
+ test("is run even after throw", () => {
let disposed = false;
let inBlock = false;
let inCatch = false;
@@ -88,7 +88,7 @@ describe("behavior with exceptions", () => {
expect(inCatch).toBeTrue();
});
- test.xfail("throws error if dispose method does", () => {
+ test("throws error if dispose method does", () => {
let disposed = false;
let endOfTry = false;
let inCatch = false;
@@ -112,7 +112,7 @@ describe("behavior with exceptions", () => {
expect(inCatch).toBeTrue();
});
- test.xfail("if block and using throw get suppressed error", () => {
+ test("if block and using throw get suppressed error", () => {
let disposed = false;
let inCatch = false;
try {
@@ -138,7 +138,7 @@ describe("behavior with exceptions", () => {
expect(inCatch).toBeTrue();
});
- test.xfail("multiple throwing disposes give suppressed error", () => {
+ test("multiple throwing disposes give suppressed error", () => {
let inCatch = false;
try {
{
@@ -167,7 +167,7 @@ describe("behavior with exceptions", () => {
expect(inCatch).toBeTrue();
});
- test.xfail("3 throwing disposes give chaining suppressed error", () => {
+ test("3 throwing disposes give chaining suppressed error", () => {
let inCatch = false;
try {
{
@@ -208,7 +208,7 @@ describe("behavior with exceptions", () => {
expect(inCatch).toBeTrue();
});
- test.xfail("normal error and multiple disposing errors give chaining suppressed errors", () => {
+ test("normal error and multiple disposing errors give chaining suppressed errors", () => {
let inCatch = false;
try {
using a = {
@@ -243,7 +243,7 @@ describe("behavior with exceptions", () => {
});
describe("works in a bunch of scopes", () => {
- test.xfail("works in block", () => {
+ test("works in block", () => {
let dispose = false;
expect(dispose).toBeFalse();
{
@@ -258,7 +258,7 @@ describe("works in a bunch of scopes", () => {
expect(dispose).toBeTrue();
});
- test.xfail("works in static class block", () => {
+ test("works in static class block", () => {
let dispose = false;
expect(dispose).toBeFalse();
class A {
@@ -275,7 +275,7 @@ describe("works in a bunch of scopes", () => {
expect(dispose).toBeTrue();
});
- test.xfail("works in function", () => {
+ test("works in function", () => {
let dispose = [];
function f(val) {
const disposeLength = dispose.length;
@@ -293,7 +293,7 @@ describe("works in a bunch of scopes", () => {
expect(dispose).toEqual([0, 1]);
});
- test.xfail("switch block is treated as full block in function", () => {
+ test("blocks in switch cases dispose at their end", () => {
let disposeFull = [];
let disposeInner = false;
@@ -328,7 +328,7 @@ describe("works in a bunch of scopes", () => {
// fallthrough
case 1:
{
- expect(disposeFull).toEqual([]);
+ expect(disposeFull).toEqual(["b", "a"]);
expect(disposeInner).toBeFalse();
using inner = {
@@ -355,19 +355,19 @@ describe("works in a bunch of scopes", () => {
}
expect(disposeInner).toBeTrue();
- expect(disposeFull).toEqual(["c", "b", "a"]);
+ expect(disposeFull).toEqual(["b", "a", "c"]);
});
});
describe("invalid using bindings", () => {
- test.xfail("nullish values do not throw", () => {
+ test("nullish values do not throw", () => {
using a = null,
b = undefined;
expect(a).toBeNull();
expect(b).toBeUndefined();
});
- test.xfail("non-object throws", () => {
+ test("non-object throws", () => {
[0, "a", true, NaN, 4n, Symbol.dispose].forEach(value => {
expect(() => {
using v = value;
@@ -375,13 +375,13 @@ describe("invalid using bindings", () => {
});
});
- test.xfail("object without dispose throws", () => {
+ test("object without dispose throws", () => {
expect(() => {
using a = {};
}).toThrowWithMessage(TypeError, "does not have dispose method");
});
- test.xfail("object with non callable dispose throws", () => {
+ test("object with non callable dispose throws", () => {
[0, "a", true, NaN, 4n, Symbol.dispose, [], {}].forEach(value => {
expect(() => {
using a = { [Symbol.dispose]: value };
@@ -409,7 +409,7 @@ describe("using is still a valid variable name", () => {
expect(using).toBe(1);
});
- test.xfail("using", () => {
+ test("using", () => {
"use strict";
using using = null;
expect(using).toBeNull();
@@ -463,3 +463,151 @@ describe("syntax errors / weird artifacts which remain valid", () => {
expect("using let = null").not.toEval();
});
});
+
+describe("control flow", () => {
+ const disposable = (log, name) => ({
+ [Symbol.dispose]() {
+ log.push(name);
+ },
+ });
+
+ test("break and continue to labels dispose of every scope they leave", () => {
+ const log = [];
+ outer: for (let i = 0; i < 2; i++) {
+ using a = disposable(log, `a${i}`);
+ for (let j = 0; j < 2; j++) {
+ using b = disposable(log, `b${i}${j}`);
+ {
+ using c = disposable(log, `c${i}${j}`);
+ if (i === 0) continue outer;
+ break outer;
+ }
+ }
+ }
+ expect(log).toEqual(["c00", "b00", "a0", "c10", "b10", "a1"]);
+
+ log.length = 0;
+ block: {
+ using a = disposable(log, "a");
+ {
+ using b = disposable(log, "b");
+ break block;
+ }
+ }
+ expect(log).toEqual(["b", "a"]);
+ });
+
+ test("return from a finally block disposes of every scope it leaves", () => {
+ const log = [];
+ function f() {
+ using a = disposable(log, "a");
+ try {
+ using b = disposable(log, "b");
+ return 1;
+ } finally {
+ using c = disposable(log, "c");
+ return 2;
+ }
+ }
+ expect(f()).toBe(2);
+ expect(log).toEqual(["b", "c", "a"]);
+ });
+
+ test("completion value of a block", () => {
+ const log = [];
+ expect(eval("{ using a = disposable(log, 'a'); 42; }")).toBe(42);
+ expect(eval("1; { using b = disposable(log, 'b'); }")).toBe(1);
+ expect(eval("l: { using c = disposable(log, 'c'); 3; break l; }")).toBe(3);
+ expect(log).toEqual(["a", "b", "c"]);
+ });
+
+ test("generator return() and throw() while suspended in a scope", () => {
+ const log = [];
+ function* generator() {
+ using a = disposable(log, "a");
+ try {
+ using b = disposable(log, "b");
+ yield 1;
+ log.push("resumed");
+ } finally {
+ log.push("finally");
+ }
+ }
+
+ let iterator = generator();
+ iterator.next();
+ expect(iterator.return(5)).toEqual({ value: 5, done: true });
+ expect(log).toEqual(["b", "finally", "a"]);
+
+ log.length = 0;
+ iterator = generator();
+ iterator.next();
+ expect(() => iterator.throw(new Error("thrown"))).toThrowWithMessage(Error, "thrown");
+ expect(log).toEqual(["b", "finally", "a"]);
+
+ log.length = 0;
+ iterator = generator();
+ iterator.next();
+ gc();
+ expect(iterator.next()).toEqual({ value: undefined, done: true });
+ expect(log).toEqual(["resumed", "b", "finally", "a"]);
+ });
+
+ test("for-of disposes of the resource before closing the iterator", () => {
+ const log = [];
+ function makeIterator(values) {
+ let index = 0;
+ return {
+ [Symbol.iterator]() {
+ return this;
+ },
+ next() {
+ return index < values.length ? { value: values[index++], done: false } : { done: true };
+ },
+ return() {
+ log.push("return");
+ return {};
+ },
+ };
+ }
+
+ const throwing = {
+ [Symbol.dispose]() {
+ log.push("dispose");
+ throw new Error("dispose");
+ },
+ };
+ expect(() => {
+ for (using x of makeIterator([throwing])) break;
+ }).toThrowWithMessage(Error, "dispose");
+ expect(log).toEqual(["dispose", "return"]);
+
+ log.length = 0;
+ expect(() => {
+ for (using x of makeIterator([1])) log.push("body");
+ }).toThrow(TypeError);
+ expect(log).toEqual(["return"]);
+
+ log.length = 0;
+ function* generator() {
+ for (using x of makeIterator([disposable(log, "x")])) yield 1;
+ }
+ const iterator = generator();
+ iterator.next();
+ iterator.return();
+ expect(log).toEqual(["x", "return"]);
+ });
+});
+
+describe("parsing", () => {
+ test("using followed by a reserved word is an expression", () => {
+ expect("{ var using, x = {}; using in x; using instanceof Object; }").toEval();
+ });
+
+ test("using declarations are allowed in the body of a dynamic function", () => {
+ const log = [];
+ const f = new Function("log", "using a = { [Symbol.dispose]() { log.push('a'); } }; log.push('body');");
+ f(log);
+ expect(log).toEqual(["body", "a"]);
+ });
+});
diff --git a/Tests/LibJS/Runtime/using-for-loops.js b/Tests/LibJS/Runtime/using-for-loops.js
index de44ffd794e..d6e2f3e2daf 100644
--- a/Tests/LibJS/Runtime/using-for-loops.js
+++ b/Tests/LibJS/Runtime/using-for-loops.js
@@ -1,5 +1,5 @@
describe("basic usage", () => {
- test.xfail("using in normal for loop", () => {
+ test("using in normal for loop", () => {
let isDisposed = false;
let lastI = -1;
for (
@@ -27,7 +27,7 @@ describe("basic usage", () => {
expect(lastI).toBe(2);
});
- test.xfail("using in normal for loop with expression body", () => {
+ test("using in normal for loop with expression body", () => {
let isDisposed = false;
let outerI = 0;
for (
@@ -53,7 +53,7 @@ describe("basic usage", () => {
expect(outerI).toBe(3);
});
- test.xfail("using in for of loop", () => {
+ test("using in for of loop", () => {
const disposable = [];
const values = [];
@@ -75,7 +75,7 @@ describe("basic usage", () => {
expect(disposable).toEqual(["a", "b", "c"]);
});
- test.xfail("using in for of loop with expression body", () => {
+ test("using in for of loop with expression body", () => {
let disposableCalls = 0;
let i = 0;
@@ -92,7 +92,7 @@ describe("basic usage", () => {
expect(disposableCalls).toBe(3);
});
- test.xfail("can have multiple declaration in normal for loop", () => {
+ test("can have multiple declaration in normal for loop", () => {
let disposed = 0;
const a = {
[Symbol.dispose]() {
@@ -108,7 +108,7 @@ describe("basic usage", () => {
expect(disposed).toBe(2);
});
- test.xfail("can have using in block in for loop", () => {
+ test("can have using in block in for loop", () => {
const disposed = [];
const values = [];
for (let i = 0; i < 3; i++) {
@@ -125,7 +125,7 @@ describe("basic usage", () => {
expect(disposed).toEqual([0, 1, 2]);
});
- test.xfail("can have using in block in for-in loop", () => {
+ test("can have using in block in for-in loop", () => {
const disposed = [];
const values = [];
for (const i in ["a", "b", "c"]) {
@@ -142,7 +142,7 @@ describe("basic usage", () => {
expect(disposed).toEqual(["0", "1", "2"]);
});
- test.xfail("dispose is called even if throw in for of loop", () => {
+ test("dispose is called even if throw in for of loop", () => {
let disposableCalls = 0;
const obj = {
@@ -212,7 +212,7 @@ describe("using is still a valid variable in loops", () => {
expect(enteredLoop).toBeTrue();
});
- test.xfail("using using of", () => {
+ test("using using of", () => {
let enteredLoop = false;
for (using using of [null]) {
enteredLoop = true;