Truly independent web browser
LibJS: Implement await using declarations
Andreas Kling2b5e05b46c24
diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.Sindex 3ce83334b36..abd772952d1 100644--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S@@ -184,6 +184,7 @@ asm_dispatch_table:.quad asm_handler_NewDisposableResourceStack.quad asm_handler_AddDisposableResource.quad asm_handler_DisposeResources+ .quad asm_handler_AsyncDisposeResourcesStep.quad asm_handler_GetCompletionFields.quad asm_handler_SetCompletionType.quad asm_handler_GetTemplateObject@@ -268,7 +269,6 @@ asm_dispatch_table:.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):@@ -1217,6 +1217,10 @@ CSYM(js_interpreter_handler_ranges):.quad asm_handler_DisposeResources_hot_end.quad asm_handler_DisposeResources_cold.quad asm_handler_DisposeResources_cold_end+ .quad asm_handler_AsyncDisposeResourcesStep+ .quad asm_handler_AsyncDisposeResourcesStep_hot_end+ .quad asm_handler_AsyncDisposeResourcesStep_cold+ .quad asm_handler_AsyncDisposeResourcesStep_cold_end.quad asm_handler_GetCompletionFields.quad asm_handler_GetCompletionFields_hot_end.quad asm_handler_GetCompletionFields_cold@@ -1553,10 +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.text@@ -17359,6 +17359,77 @@ asm_handler_DisposeResources_hot_end:asm_handler_DisposeResources_cold:asm_handler_DisposeResources_cold_end:+.p2align 4+asm_handler_AsyncDisposeResourcesStep:+ mov x0, x20+ sub w1, w21, w26+ str w1, [x28, #64]+ sub sp, sp, #80+ ldr w12, [x21, #12]+ ldr x11, [x27, x12, lsl #3]+.Lasm_AsyncDisposeResourcesStep.value_ready_1:+ mov x4, x11+ ldr w12, [x21, #16]+ ldr x11, [x27, x12, lsl #3]+.Lasm_AsyncDisposeResourcesStep.value_ready_2:+ mov x5, x11+ ldr w12, [x21, #20]+ ldr x11, [x27, x12, lsl #3]+.Lasm_AsyncDisposeResourcesStep.value_ready_3:+ mov x6, x11+ ldr w12, [x21, #24]+ ldr x11, [x27, x12, lsl #3]+.Lasm_AsyncDisposeResourcesStep.value_ready_4:+ mov x7, x11+ ldr w12, [x21, #28]+ ldr x11, [x27, x12, lsl #3]+.Lasm_AsyncDisposeResourcesStep.value_ready_5:+ str x11, [sp]+ mov x0, x20+ sub w1, w21, w26+ mov x2, x21+ add x3, sp, #16+ bl CSYM(asm_slow_path_async_dispose_resources_step)+ tbnz x0, #63, .Lasm_AsyncDisposeResourcesStep.values_exceptional_outputs_7+ tbz x0, #32, .Lasm_AsyncDisposeResourcesStep.values_exceptional_outputs_7+ ldr w12, [x21, #4]+ ldr x11, [sp, #16]+ str x11, [x27, x12, lsl #3]+.Lasm_AsyncDisposeResourcesStep.skip_output_value_8:+ ldr w12, [x21, #8]+ ldr x11, [sp, #24]+ str x11, [x27, x12, lsl #3]+.Lasm_AsyncDisposeResourcesStep.skip_output_value_9:+ add sp, sp, #80+ add x21, x26, w0, uxtw+ ldrb w9, [x21]+ ldr x10, [x19, x9, lsl #3]+ br x10+.Lasm_AsyncDisposeResourcesStep.values_exceptional_outputs_7:+.Lasm_AsyncDisposeResourcesStep.values_restore_stack_6:+ add sp, sp, #80+.Lasm_AsyncDisposeResourcesStep.values_call_done_0:+ tbz x0, #63, 1f+ b .Lexit+1:+ tbz x0, #32, .Lasm_AsyncDisposeResourcesStep.slow_path_transfer_10+ add x21, x26, w0, uxtw+ ldrb w9, [x21]+ ldr x10, [x19, x9, lsl #3]+ br x10+.Lasm_AsyncDisposeResourcesStep.slow_path_transfer_10:+ 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_AsyncDisposeResourcesStep_hot_end:+asm_handler_AsyncDisposeResourcesStep_cold:+asm_handler_AsyncDisposeResourcesStep_cold_end:+.p2align 4asm_handler_GetCompletionFields:mov x0, x20diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.Sindex e82a255a8e9..6869cc41b16 100644--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S@@ -185,6 +185,7 @@ asm_dispatch_table:.quad asm_handler_NewDisposableResourceStack.quad asm_handler_AddDisposableResource.quad asm_handler_DisposeResources+ .quad asm_handler_AsyncDisposeResourcesStep.quad asm_handler_GetCompletionFields.quad asm_handler_SetCompletionType.quad asm_handler_GetTemplateObject@@ -269,7 +270,6 @@ asm_dispatch_table:.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):@@ -1218,6 +1218,10 @@ CSYM(js_interpreter_handler_ranges):.quad asm_handler_DisposeResources_hot_end.quad asm_handler_DisposeResources_cold.quad asm_handler_DisposeResources_cold_end+ .quad asm_handler_AsyncDisposeResourcesStep+ .quad asm_handler_AsyncDisposeResourcesStep_hot_end+ .quad asm_handler_AsyncDisposeResourcesStep_cold+ .quad asm_handler_AsyncDisposeResourcesStep_cold_end.quad asm_handler_GetCompletionFields.quad asm_handler_GetCompletionFields_hot_end.quad asm_handler_GetCompletionFields_cold@@ -1554,10 +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.text@@ -16972,6 +16972,77 @@ asm_handler_DisposeResources_hot_end:asm_handler_DisposeResources_cold:asm_handler_DisposeResources_cold_end:+.p2align 4+asm_handler_AsyncDisposeResourcesStep:+ mov DWORD PTR [rbx + -64], r13d+ lea rcx, [r14 + r13]+ sub rsp, 96+ mov r10d, DWORD PTR [rcx + 12]+ mov rax, QWORD PTR [rbx + r10 * 8]+.Lasm_AsyncDisposeResourcesStep.value_ready_1:+ mov r8, rax+ mov r10d, DWORD PTR [rcx + 16]+ mov rax, QWORD PTR [rbx + r10 * 8]+.Lasm_AsyncDisposeResourcesStep.value_ready_2:+ mov r9, rax+ mov r10d, DWORD PTR [rcx + 20]+ mov rax, QWORD PTR [rbx + r10 * 8]+.Lasm_AsyncDisposeResourcesStep.value_ready_3:+ mov QWORD PTR [rsp], rax+ mov r10d, DWORD PTR [rcx + 24]+ mov rax, QWORD PTR [rbx + r10 * 8]+.Lasm_AsyncDisposeResourcesStep.value_ready_4:+ mov QWORD PTR [rsp + 8], rax+ mov r10d, DWORD PTR [rcx + 28]+ mov rax, QWORD PTR [rbx + r10 * 8]+.Lasm_AsyncDisposeResourcesStep.value_ready_5:+ mov QWORD PTR [rsp + 16], rax+ mov rdi, QWORD PTR [rbp - 48]+ mov esi, r13d+ lea rdx, [r14 + r13]+ lea rcx, [rsp + 32]+ call CSYM(asm_slow_path_async_dispose_resources_step)+ test rax, rax+ js .Lasm_AsyncDisposeResourcesStep.values_exceptional_outputs_7+ bt rax, 32+ jnc .Lasm_AsyncDisposeResourcesStep.values_exceptional_outputs_7+ lea rcx, [r14 + r13]+ mov r10d, DWORD PTR [rcx + 4]+ mov r11, QWORD PTR [rsp + 32]+ mov QWORD PTR [rbx + r10 * 8], r11+.Lasm_AsyncDisposeResourcesStep.skip_output_value_8:+ mov r10d, DWORD PTR [rcx + 8]+ mov r11, QWORD PTR [rsp + 40]+ mov QWORD PTR [rbx + r10 * 8], r11+.Lasm_AsyncDisposeResourcesStep.skip_output_value_9:+ add rsp, 96+ mov r13d, eax+ movzx eax, BYTE PTR [r14 + r13]+ jmp [r12 + rax * 8]+.Lasm_AsyncDisposeResourcesStep.values_exceptional_outputs_7:+.Lasm_AsyncDisposeResourcesStep.values_restore_stack_6:+ add rsp, 96+.Lasm_AsyncDisposeResourcesStep.values_call_done_0:+ test rax, rax+ js .Lexit+ bt rax, 32+ jnc .Lasm_AsyncDisposeResourcesStep.slow_path_transfer_10+ mov r13d, eax+ movzx eax, BYTE PTR [r14 + r13]+ jmp [r12 + rax * 8]+.Lasm_AsyncDisposeResourcesStep.slow_path_transfer_10:+ 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_AsyncDisposeResourcesStep_hot_end:+asm_handler_AsyncDisposeResourcesStep_cold:+asm_handler_AsyncDisposeResourcesStep_cold_end:+.p2align 4asm_handler_GetCompletionFields:mov DWORD PTR [rbx + -64], r13ddiff --git a/Libraries/LibJS/Interpreter/interpreter.flap b/Libraries/LibJS/Interpreter/interpreter.flapindex b06076104db..f24cb5ebce6 100644--- a/Libraries/LibJS/Interpreter/interpreter.flap+++ b/Libraries/LibJS/Interpreter/interpreter.flap@@ -4464,6 +4464,16 @@ handler DisposeResources(completion_value: Operand) @cold = call_slow_path(dispose_resources);+handler AsyncDisposeResourcesStep(+ done: out Operand,+ awaited_value: out Operand,+ stack: Operand,+ completion_type: Operand,+ completion_value: Operand,+ await_completion_type: Operand,+ await_completion_value: Operand+) @cold = call_slow_path(async_dispose_resources_step);+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.rsindex 61820e457a3..04562c907b9 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs@@ -344,6 +344,7 @@ pub fn handling(opcode: OpCode) -> Handling {| O::PutPrivateById| O::AddDisposableResource| O::DisposeResources+ | O::AsyncDisposeResourcesStep| O::ExpRhsInt32 => GENERIC,}}diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen.rs b/Libraries/LibJS/Rust/src/bytecode/codegen.rsindex 171cf87998e..eb9953ca861 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen.rs@@ -2668,12 +2668,12 @@ fn generate_for_statement(preferred_dst: Option<&ScopedOperand>,) -> Option<ScopedOperand> {// ForStatement : `for` `(` LexicalDeclaration Expression? `;` Expression? `)` Statement- // NB: The resources of a `using` declaration in the head are disposed of when the loop ends,+ // NB: The resources of a `using` or `await 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()))+ && let Some(kind) = disposal_kind_of_statements(core::iter::once(declaration.as_ref())){- return generate_with_disposable_resource_stack(generator, |generator| {+ return generate_with_disposable_resource_stack(generator, kind, |generator| {generate_for_statement_without_disposal(generator, init, test, update, body, preferred_dst)});}@@ -2948,25 +2948,40 @@ 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))+/// How the resources of a scope are disposed of, if the scope has `using` or `await using` declarations.+#[derive(Clone, Copy, PartialEq, Eq)]+enum DisposalKind {+ Sync,+ Async,+}++/// The disposal kind of a statement list, from the `using` and `await using` declarations directly in it.+fn disposal_kind_of_statements<'a>(statements: impl Iterator<Item = &'a Statement>) -> Option<DisposalKind> {+ let mut kind = None;+ for statement in statements {+ if let StatementKind::UsingDeclaration(data) = &statement.inner {+ if data.is_await {+ return Some(DisposalKind::Async);+ }+ kind = Some(DisposalKind::Sync);+ }+ }+ kind}-/// 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.+/// Generate the children of a scope, disposing of the resources of the `using` and `await 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);+ match disposal_kind_of_statements(scope.children.iter()) {+ None => generate_scope_children(generator, scope, preferred_dst),+ Some(kind) => generate_with_disposable_resource_stack(generator, kind, |generator| {+ 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@@ -2974,6 +2989,7 @@ fn generate_scope_children_with_disposal(// https://tc39.es/ecma262/#sec-disposeresourcesfn generate_with_disposable_resource_stack(generator: &mut Generator,+ kind: DisposalKind,body: impl FnOnce(&mut Generator) -> Option<ScopedOperand>,) -> Option<ScopedOperand> {let stack = generator.allocate_register();@@ -3039,11 +3055,66 @@ fn generate_with_disposable_resource_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(),- });+ match kind {+ DisposalKind::Sync => {+ generator.emit(Instruction::DisposeResources {+ stack: stack.operand(),+ completion_type: completion_type.operand(),+ completion_value: completion_value.operand(),+ });+ }+ DisposalKind::Async => {+ // NB: DisposeResources awaits between some of its steps here, so the bytecode performs it one step at a+ // time, with an Await after each step that asks for one.+ let await_completion = generator.allocate_register();+ let await_completion_type = generator.allocate_register();+ let await_completion_value = generator.allocate_register();+ let done = generator.allocate_register();+ let awaited_value = generator.allocate_register();+ let normal_type = generator.add_constant_number(f64::from(CompletionType::Normal as u32));+ let undefined = generator.add_constant_undefined();+ generator.emit_mov(&await_completion_type, &normal_type);+ generator.emit_mov(&await_completion_value, &undefined);++ let step_block = generator.make_block();+ let await_block = generator.make_block();+ let continuation_block = generator.make_block();+ let done_block = generator.make_block();+ generator.emit(Instruction::Jump { target: step_block });++ generator.switch_to_basic_block(step_block);+ generator.emit(Instruction::AsyncDisposeResourcesStep {+ done: done.operand(),+ awaited_value: awaited_value.operand(),+ stack: stack.operand(),+ completion_type: completion_type.operand(),+ completion_value: completion_value.operand(),+ await_completion_type: await_completion_type.operand(),+ await_completion_value: await_completion_value.operand(),+ });+ generator.emit_jump_if(&done, done_block, await_block);++ generator.switch_to_basic_block(await_block);+ let acc = generator.accumulator();+ generator.emit_mov(&await_completion, &acc);+ generator.emit(Instruction::Await {+ continuation_label: continuation_block,+ argument: awaited_value.operand(),+ });++ generator.switch_to_basic_block(continuation_block);+ let acc = generator.accumulator();+ generator.emit_mov(&await_completion, &acc);+ generator.emit(Instruction::GetCompletionFields {+ type_dst: await_completion_type.operand(),+ value_dst: await_completion_value.operand(),+ completion: await_completion.operand(),+ });+ generator.emit(Instruction::Jump { target: step_block });++ generator.switch_to_basic_block(done_block);+ }+ }let next_block = generator.make_block();emit_finally_dispatch(generator, ctx_index, &completion_type, &completion_value, next_block);@@ -3061,13 +3132,15 @@ fn generate_with_disposable_resource_stack(// 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;+ // UsingDeclaration:+ // 1. Perform ? BindingEvaluation of BindingList with argument sync-dispose.+ // AwaitUsingDeclaration:+ // 1. Perform ? BindingEvaluation of BindingList with argument async-dispose.+ let kind = if data.is_await {+ DisposableResourceKind::AsyncDispose+ } else {+ DisposableResourceKind::SyncDispose+ };for declaration in &data.declarations {let VariableDeclaratorTarget::Identifier(id) = &declaration.target else {unreachable!("using declarations only bind identifiers");@@ -3078,21 +3151,6 @@ fn generate_using_declaration(generator: &mut Generator, data: &UsingDeclaration// 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(@@ -7771,19 +7829,19 @@ fn generate_for_of_statement_inner(None};- let has_using_declaration = match lhs {- ForInOfLhs::Declaration(statement) => contains_using_declaration(core::iter::once(statement.as_ref())),- _ => false,+ let disposal_kind = match lhs {+ ForInOfLhs::Declaration(statement) => disposal_kind_of_statements(core::iter::once(statement.as_ref())),+ _ => None,};- if has_using_declaration {- // NB: The resource of a `using` declaration is disposed of at the end of each iteration,+ if let Some(disposal_kind) = disposal_kind {+ // NB: The resource of a `using` or `await 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| {+ generate_with_disposable_resource_stack(generator, disposal_kind, |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);@@ -8087,7 +8145,7 @@ 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) => {- // NB: For a `using` declaration, these are steps 8.h.vii.4 and 8.h.vii.6 of+ // NB: For a `using` or `await 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@@ -8100,16 +8158,12 @@ fn assign_to_for_in_of_lhs(generator: &mut Generator, lhs: &ForInOfLhs, value: &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,- );+ let kind = if data.is_await {+ DisposableResourceKind::AsyncDispose+ } else {+ DisposableResourceKind::SyncDispose+ };+ emit_add_disposable_resource_and_initialize_binding(generator, *id, value, kind);return;}// The declaration is a VariableDeclaration with a single declaratordiff --git a/Libraries/LibJS/Rust/src/bytecode/generator.rs b/Libraries/LibJS/Rust/src/bytecode/generator.rsindex afea70fb2a6..4adab42755a 100644--- a/Libraries/LibJS/Rust/src/bytecode/generator.rs+++ b/Libraries/LibJS/Rust/src/bytecode/generator.rs@@ -297,6 +297,7 @@ impl FinallyContext {#[repr(u32)]pub enum DisposableResourceKind {SyncDispose = 0,+ AsyncDispose = 1,}/// A break/continue target registered with a FinallyContext.diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rsindex e9648ad46d5..429cfe27eaa 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs@@ -26,7 +26,7 @@ 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, CompletionType, Must, ThrowCompletionOr, completion_type_from_bytecode};-use crate::runtime::disposable_resource_stack::DisposableResourceStack;+use crate::runtime::disposable_resource_stack::{AsyncDisposeResourcesStep, DisposableResourceStack};use crate::runtime::environment::InitializeBindingHint;use crate::runtime::error::ErrorKind;use crate::runtime::error_types::ErrorType;@@ -650,8 +650,11 @@ pub fn add_disposable_resource(instruction: &op::AddDisposableResource,values: &mut op::AddDisposableResourceValues,) -> SlowPathControl {- debug_assert_eq!(instruction.hint, DisposableResourceKind::SyncDispose as u32);- let hint = InitializeBindingHint::SyncDispose;+ let hint = if instruction.hint == DisposableResourceKind::AsyncDispose as u32 {+ InitializeBindingHint::AsyncDispose+ } else {+ 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)@@ -678,6 +681,37 @@ pub fn dispose_resources(vm: &Vm, pc: u32, values: &mut op::DisposeResourcesValuSlowPathControl::continue_at(pc + op::DisposeResources::LENGTH)}+pub fn async_dispose_resources_step(+ vm: &Vm,+ pc: u32,+ values: &mut op::AsyncDisposeResourcesStepValues,+) -> SlowPathControl {+ let stack = DisposableResourceStack::from_value(values.stack);+ let completion = completion_of_scope(values.completion_type, values.completion_value);+ let await_completion = if values.await_completion_type.is_int32()+ && values.await_completion_type.as_i32() == CompletionType::Throw as i32+ {+ Completion::new(CompletionType::Throw, values.await_completion_value)+ } else {+ Completion::normal(values.await_completion_value)+ };+ match asm_try!(+ vm,+ pc,+ stack.async_dispose_resources_step(vm, completion, await_completion)+ ) {+ AsyncDisposeResourcesStep::Await(value) => {+ values.done = Value::from_bool(false);+ values.awaited_value = value;+ }+ AsyncDisposeResourcesStep::Done => {+ values.done = Value::from_bool(true);+ values.awaited_value = Value::UNDEFINED;+ }+ }+ SlowPathControl::continue_at(pc + op::AsyncDisposeResourcesStep::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.rsindex 9103c8498b5..48628c1d53b 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs@@ -1390,6 +1390,15 @@ impl RuntimeFunctions for Runtime {control::dispose_resources(vm, pc, values)}+ fn async_dispose_resources_step(+ vm: &Vm,+ pc: u32,+ _instruction: &op::AsyncDisposeResourcesStep,+ values: &mut op::AsyncDisposeResourcesStepValues,+ ) -> SlowPathControl {+ control::async_dispose_resources_step(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.rsindex aa481a3a893..67635d81cc1 100644--- a/Libraries/LibJS/Rust/src/runtime/disposable_resource_stack.rs+++ b/Libraries/LibJS/Rust/src/runtime/disposable_resource_stack.rs@@ -4,6 +4,8 @@* SPDX-License-Identifier: BSD-2-Clause*/+use core::cell::Cell;+use libjs_runtime_macros::Trace;use crate::gc::class::{Finalize, GcCell, class_of, define_cell};@@ -12,20 +14,30 @@ 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,+ DisposeCapability, add_disposable_resource, call_function_object, dispose_resources, new_dispose_capability,};-use crate::runtime::completion::{Completion, ThrowCompletionOr};+use crate::runtime::completion::{Completion, Throw, ThrowCompletionOr};use crate::runtime::environment::InitializeBindingHint;+use crate::runtime::suppressed_error::SuppressedError;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.+/// contains `using` or `await 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.+///+/// It also keeps the state of a DisposeResources of an `await using` scope, which the bytecode performs one step at a+/// time so that it can await between the steps.#[repr(C)]#[derive(Trace)]pub struct DisposableResourceStack {header: CellHeader,dispose_capability: GcRefCell<DisposeCapability>,+ async_disposal_started: Cell<bool>,+ needs_await: Cell<bool>,+ has_awaited: Cell<bool>,+ is_awaiting_dispose_result: Cell<bool>,+ // The [[Value]] of outputCompletion while it is a throw completion, and empty while it is a normal completion.+ output_completion_value: Cell<Value>,}define_cell!(DisposableResourceStack, Other, finalize: finalize);@@ -36,11 +48,24 @@ impl Finalize for DisposableResourceStack {}}+/// What the bytecode does after a step of an asynchronous DisposeResources.+pub enum AsyncDisposeResourcesStep {+ /// Await the value, then perform the next step with the completion of the await.+ Await(Value),+ /// The resources are disposed of, and the completion of the scope stays as it was.+ Done,+}+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()),+ async_disposal_started: Cell::new(false),+ needs_await: Cell::new(false),+ has_awaited: Cell::new(false),+ is_awaiting_dispose_result: Cell::new(false),+ output_completion_value: Cell::new(Value::EMPTY),})}@@ -66,7 +91,163 @@ impl DisposableResourceStack {}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.+ // NB: Every resource of a scope without `await using` declarations has the sync-dispose kind, so this never+ // awaits.dispose_resources(vm, &self.dispose_capability, completion)}++ /// Performs DisposeResources up to its next Await, or to its end.+ ///+ /// The first step receives the completion of the scope, and each later step the completion of the Await that the+ /// previous step asked for. Throws the completion of the DisposeResources if it is a throw completion.+ // https://tc39.es/ecma262/#sec-disposeresources+ pub fn async_dispose_resources_step(+ &self,+ vm: &Vm,+ completion: Completion,+ await_completion: Completion,+ ) -> ThrowCompletionOr<AsyncDisposeResourcesStep> {+ if !self.async_disposal_started.get() {+ self.async_disposal_started.set(true);++ // 1. Let needsAwait be false.+ // 2. Let hasAwaited be false.+ // NB: These are the initial values of the fields.++ // 3. Let outputCompletion be completion.+ if completion.is_error() {+ self.output_completion_value.set(completion.value());+ }+ } else if self.is_awaiting_dispose_result.get() {+ self.is_awaiting_dispose_result.set(false);++ // NB: This is the completion of the Await of step 4.e.ii.1, which continues at step 4.e.iii.+ if await_completion.is_error() {+ self.dispose_method_threw(vm, await_completion.value());+ }+ }++ // 4. For each element resource of disposableResourceStack, in reverse List order, do+ // NB: Each resource is taken off the stack when it is disposed of, which leaves the next one at its end.+ loop {+ let Some(resource) = self+ .dispose_capability+ .borrow()+ .disposable_resource_stack+ .as_ref()+ .and_then(|stack| stack.last().copied())+ else {+ break;+ };++ // a. Let value be resource.[[ResourceValue]].+ let value = resource.resource_value;++ // b. Let kind be resource.[[Kind]].+ let kind = resource.hint;++ // c. Let method be resource.[[DisposeMethod]].+ let method = resource.dispose_method;++ // d. If kind is sync-dispose, needsAwait is true, and hasAwaited is false, then+ if kind == InitializeBindingHint::SyncDispose && self.needs_await.get() && !self.has_awaited.get() {+ // i. Perform ! Await(undefined).+ // ii. Set needsAwait to false.+ // NB: The bytecode performs the Await after this step. The resource stays on the stack, so the next+ // step disposes of it.+ self.needs_await.set(false);+ return Ok(AsyncDisposeResourcesStep::Await(Value::UNDEFINED));+ }++ self.dispose_capability+ .borrow_mut()+ .disposable_resource_stack+ .as_mut()+ .expect("the stack has the resource")+ .pop();++ // e. If method is not undefined, then+ if let Some(method) = method {+ // i. Let result be Completion(Call(method, value)).+ let result = call_function_object(vm, method, value, &[]);++ match result {+ // ii. If result is a normal completion and kind is async-dispose, then+ Ok(result_value) if kind == InitializeBindingHint::AsyncDispose => {+ // 1. Set result to Completion(Await(result.[[Value]])).+ // 2. Set hasAwaited to true.+ // NB: The bytecode performs the Await after this step, and the next step continues at step+ // 4.e.iii with its completion.+ self.is_awaiting_dispose_result.set(true);+ self.has_awaited.set(true);+ return Ok(AsyncDisposeResourcesStep::Await(result_value));+ }+ Ok(_) => {}+ // iii. If result is a throw completion, then+ Err(throw) => self.dispose_method_threw(vm, throw.value()),+ }+ }+ // f. Else,+ else {+ // i. Assert: kind is async-dispose.+ assert!(kind == InitializeBindingHint::AsyncDispose);++ // ii. Set needsAwait to true.+ self.needs_await.set(true);++ // iii. NOTE: This can only indicate a case where either null or undefined was the initialized value of+ // an await using declaration.+ }+ }++ // 5. If needsAwait is true and hasAwaited is false, then+ if self.needs_await.get() && !self.has_awaited.get() {+ // NB: The next step comes back here with an empty stack, and must not await again.+ self.needs_await.set(false);++ // a. Perform ! Await(undefined).+ return Ok(AsyncDisposeResourcesStep::Await(Value::UNDEFINED));+ }++ // 6. NOTE: At this point disposableResourceStack will never be used again. The contents of+ // disposableResourceStack can be discarded in implementations, such as by garbage collection.+ self.dispose_capability.borrow_mut().disposable_resource_stack = None;++ // 7. Return ? outputCompletion.+ let output_completion_value = self.output_completion_value.get();+ if !output_completion_value.is_empty() {+ return Err(Throw::new(output_completion_value));+ }+ Ok(AsyncDisposeResourcesStep::Done)+ }++ // Steps 4.e.iii.1-2 of DisposeResources, for a result that is a throw completion.+ fn dispose_method_threw(&self, vm: &Vm, result: Value) {+ let output_completion_value = self.output_completion_value.get();++ // 1. If outputCompletion is a throw completion, then+ if !output_completion_value.is_empty() {+ // a. Set result to result.[[Value]].+ // b. Let suppressed be outputCompletion.[[Value]].+ let suppressed = output_completion_value;++ // c. Let error be a newly created SuppressedError object.+ let error = SuppressedError::create(vm, vm.current_realm().expect("DisposeResources runs in a realm"));++ // d. Perform CreateNonEnumerableDataPropertyOrThrow(error, "error", result).+ error.create_non_enumerable_data_property_or_throw(vm, &vm.names.error, result);++ // e. Perform CreateNonEnumerableDataPropertyOrThrow(error, "suppressed", suppressed).+ error.create_non_enumerable_data_property_or_throw(vm, &vm.names.suppressed, suppressed);++ // f. Set outputCompletion to ThrowCompletion(error).+ crate::embedding::completion::log_exception_if_enabled(vm, Value::from_object(error));+ self.output_completion_value.set(Value::from_object(error));+ }+ // 2. Else,+ else {+ // a. Set outputCompletion to result.+ self.output_completion_value.set(result);+ }+ }}diff --git a/Tests/LibJS/Runtime/await-using-declaration.js b/Tests/LibJS/Runtime/await-using-declaration.jsnew file mode 100644index 00000000000..2295526971d--- /dev/null+++ b/Tests/LibJS/Runtime/await-using-declaration.js@@ -0,0 +1,167 @@+describe("basic usage", () => {+ asyncTest("disposes asynchronously in reverse order after block exit", async () => {+ const disposed = [];+ {+ await using a = {+ async [Symbol.asyncDispose]() {+ disposed.push("a");+ },+ };+ using b = {+ [Symbol.dispose]() {+ disposed.push("b");+ },+ };+ await using c = {+ [Symbol.dispose]() {+ disposed.push("c");+ },+ };+ expect(disposed).toEqual([]);+ }+ expect(disposed).toEqual(["c", "b", "a"]);+ });++ asyncTest("waits for the promise of the dispose method", async () => {+ let resolved = false;+ {+ await using a = {+ [Symbol.asyncDispose]() {+ return Promise.resolve().then(() => {+ resolved = true;+ });+ },+ };+ }+ expect(resolved).toBeTrue();+ });++ asyncTest("disposes at the end of each iteration of a for-of loop", async () => {+ const disposed = [];+ for (await using x of [{ [Symbol.asyncDispose]: async () => disposed.push(1) }, null]) {+ disposed.push("body");+ }+ expect(disposed).toEqual(["body", 1, "body"]);+ });++ asyncTest("disposes after return", async () => {+ const disposed = [];+ async function f() {+ await using a = {+ async [Symbol.asyncDispose]() {+ disposed.push("a");+ },+ };+ return "result";+ }+ expect(await f()).toBe("result");+ expect(disposed).toEqual(["a"]);+ });+});++describe("behavior with exceptions", () => {+ asyncTest("rejected dispose promise is thrown", async () => {+ const error = new Error("dispose");+ let caught;+ try {+ await using a = {+ [Symbol.asyncDispose]() {+ return Promise.reject(error);+ },+ };+ } catch (e) {+ caught = e;+ }+ expect(caught).toBe(error);+ });++ asyncTest("errors of the block and of the dispose methods give chained suppressed errors", async () => {+ let caught;+ try {+ await using a = {+ async [Symbol.asyncDispose]() {+ throw 1;+ },+ };+ using b = {+ [Symbol.dispose]() {+ throw 2;+ },+ };+ throw 3;+ } catch (e) {+ caught = e;+ }+ expect(caught).toBeInstanceOf(SuppressedError);+ expect(caught.error).toBe(1);+ expect(caught.suppressed).toBeInstanceOf(SuppressedError);+ expect(caught.suppressed.error).toBe(2);+ expect(caught.suppressed.suppressed).toBe(3);+ });++ asyncTest("object without dispose method throws", async () => {+ let caught;+ try {+ await using a = {};+ } catch (e) {+ caught = e;+ }+ expect(caught).toBeInstanceOf(TypeError);+ });+});++describe("async generators", () => {+ asyncTest("return() while suspended in a scope disposes of its resources", async () => {+ const log = [];+ async function* generator() {+ await using a = {+ async [Symbol.asyncDispose]() {+ log.push("a");+ await null;+ log.push("a done");+ },+ };+ try {+ await using b = {+ [Symbol.dispose]() {+ log.push("b");+ },+ };+ yield 1;+ } finally {+ log.push("finally");+ }+ }++ let iterator = generator();+ await iterator.next();+ expect(await iterator.return(5)).toEqual({ value: 5, done: true });+ expect(log).toEqual(["b", "finally", "a", "a done"]);++ log.length = 0;+ iterator = generator();+ await iterator.next();+ let caught;+ try {+ await iterator.throw("thrown");+ } catch (error) {+ caught = error;+ }+ expect(caught).toBe("thrown");+ expect(log).toEqual(["b", "finally", "a", "a done"]);+ });+});++describe("syntax", () => {+ test("is only a declaration in async code", () => {+ expect("async function f() { await using a = null; }").toEval();+ expect("function f() { await using a = null; }").not.toEval();+ expect("async function f() { await using\na = null; }").toEval();+ expect("async function f() { await\nusing a = null; }").not.toEval();+ });++ test("cannot be used directly in switch cases", () => {+ expect("async function f() { switch (1) { case 1: await using a = null; } }").not.toEval();+ expect("async function f() { switch (1) { case 1: { await using a = null; } } }").toEval();+ });+});