Truly independent web browser
LibJS: Run an async function's body in its call until it first awaits
Andreas Kling5b578d39f039
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex f0191818737..c2c0021f11b 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -297,7 +297,8 @@ which enters compiled code at the resume entry if the executable has code with ointerprets it otherwise. A continuation starts by reading the completion the generator resumedwith (`GetCompletionFields`), which compiled code loads from the generator object; an asyncgenerator's completion comes from its `AsyncGenerator` through the slow path. The function's start-(its `Enter` and the initial `Yield`) is compiled like any function's.+is compiled like any function's: its `Enter`, and for generators and async generators the initial+`Yield`. Async functions have no initial `Yield`; their call runs the body until it first awaits.## 5. Dependencies and invalidationdiff --git a/Libraries/LibJS/Rust/src/bytecode_cache.rs b/Libraries/LibJS/Rust/src/bytecode_cache.rsindex ccbcaa8ef8d..97b05dfc4fe 100644--- a/Libraries/LibJS/Rust/src/bytecode_cache.rs+++ b/Libraries/LibJS/Rust/src/bytecode_cache.rs@@ -50,7 +50,7 @@ use crate::compile::CompiledProgramBytecode;use crate::u32_from_usize;const MAGIC: &[u8; 8] = b"LBJSBC\0\0";-const FORMAT_VERSION: u32 = 28;+const FORMAT_VERSION: u32 = 29;/// The size of the source hash a blob is keyed by.pub(crate) const SOURCE_HASH_SIZE: usize = 32;const BYTECODE_ALIGNMENT: usize = 8;diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rsindex 2c12eba051d..f9f492d9488 100644--- a/Libraries/LibJS/Rust/src/compile.rs+++ b/Libraries/LibJS/Rust/src/compile.rs@@ -750,8 +750,8 @@ pub(crate) fn collect_module_var_names(/// Compile a module body as an async function (for TLA modules).///-/// Emits async-function wrapping (initial Yield, final Yield) around the-/// module body statements.+/// Emits async-function wrapping (a final Yield, which completes it) around+/// the module body statements.pub(crate) fn new_module_async_generator(source_len: usize,function_table: ast::FunctionTable,@@ -783,14 +783,8 @@ pub(crate) fn compile_module_as_async_to_bytecode(generator.switch_to_basic_block(entry_block);generator.emit(Instruction::Enter {});- // Async function start: emit initial Yield before GetLexicalEnvironment.- let start_block = generator.make_block();- let undef = generator.add_constant_undefined();- generator.emit(Instruction::Yield {- continuation_label: Some(start_block),- value: undef.operand(),- });- generator.switch_to_basic_block(start_block);+ // NB: Like an async function's, the module body runs in the call until it first awaits, without an initial Yield+ // (see AsyncFunctionDriverWrapper::start()).generator.capture_saved_lexical_environment_with_coordinates(true);// Generate module body statements.@@ -1936,19 +1930,9 @@ pub(crate) fn compile_function_payload_to_bytecode(generator.switch_to_basic_block(entry_block);generator.emit(bytecode::instruction::Instruction::Enter {});- // https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start- // For async (non-generator) functions, emit the initial Yield BEFORE- // GetLexicalEnvironment so that parameter evaluation errors are caught- // by the async promise wrapper.- if generator.is_in_async_function() && !generator.is_in_generator_function() {- let start_block = generator.make_block();- let undef = generator.add_constant_undefined();- generator.emit(bytecode::instruction::Instruction::Yield {- continuation_label: Some(start_block),- value: undef.operand(),- });- generator.switch_to_basic_block(start_block);- }+ // NB: Async (non-generator) functions run FunctionDeclarationInstantiation and their body in the call until they+ // first await, and have no initial Yield. The call rejects their promise if that throws (see+ // AsyncFunctionDriverWrapper::start()).generator.capture_saved_lexical_environment_with_coordinates(sfd_metadata.function_environment_needed);diff --git a/Libraries/LibJS/Rust/src/interpreter/execution_context.rs b/Libraries/LibJS/Rust/src/interpreter/execution_context.rsindex 0ee485c239c..a66820d3321 100644--- a/Libraries/LibJS/Rust/src/interpreter/execution_context.rs+++ b/Libraries/LibJS/Rust/src/interpreter/execution_context.rs@@ -119,6 +119,31 @@ impl ExecutionContext {}copy}++ /// A copy of the context that runs nothing: an uninitialized frame of the same function, realm, script and+ /// environments, whose slots hold no values. It keeps none of the values the context's frame held alive.+ pub fn copy_without_values(&self) -> OwnedExecutionContext {+ let slot_count = self.registers_and_constants_and_locals_and_arguments_count.get();+ let argument_count = self.argument_count.get();+ let copy = OwnedExecutionContext::create(slot_count - argument_count, 0, argument_count);+ copy.function.set(self.function.get());+ copy.realm.set(self.realm.get());+ copy.script_or_module.set(self.script_or_module.get());+ copy.lexical_environment.set(self.lexical_environment.get());+ copy.variable_environment.set(self.variable_environment.get());+ copy.private_environment.set(self.private_environment.get());+ copy.program_counter.set(self.program_counter.get());+ copy.frame_id.set(self.frame_id.get());+ copy.caller_is_construct.set(self.caller_is_construct.get());+ copy.this_value.set(self.this_value.get());+ copy.executable.set(self.executable.get());+ // NB: An uninitialized frame holds values only in its reserved registers, which the new context starts with+ // empty, and its arguments.+ for argument in copy.arguments() {+ argument.set(Value::EMPTY);+ }+ copy+ }}// SAFETY: Visits every cell a frame can reach. Until the frame is initialized only its reserved registers and itsdiff --git a/Libraries/LibJS/Rust/src/runtime/async_function_driver_wrapper.rs b/Libraries/LibJS/Rust/src/runtime/async_function_driver_wrapper.rsindex 1cee2de2323..55351b7c3cf 100644--- a/Libraries/LibJS/Rust/src/runtime/async_function_driver_wrapper.rs+++ b/Libraries/LibJS/Rust/src/runtime/async_function_driver_wrapper.rs@@ -21,7 +21,7 @@ use crate::layout::object::Object;use crate::layout::value::Value;use crate::runtime::abstract_operations::call_function_object;use crate::runtime::completion::{Completion, CompletionType, Must, ThrowCompletionOr};-use crate::runtime::generator_object::{GeneratorObject, IterationResult};+use crate::runtime::generator_object::{GeneratingFunction, GeneratorObject, GeneratorState, IterationResult};use crate::runtime::native_function::NativeFunction;use crate::runtime::promise::{Promise, PromiseState, promise_resolve};use crate::runtime::realm::Realm;@@ -60,8 +60,47 @@ fn is_settled_intrinsic_promise(vm: &Vm, realm: Gc<Realm>, promise: &Promise) ->}impl AsyncFunctionDriverWrapper {- pub fn create(vm: &Vm, realm: Gc<Realm>, generator_object: Gc<GeneratorObject>) -> Gc<Promise> {+ // 15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluateasyncfunctionbody+ // 27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody ), https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start+ /// Starts an async function whose bytecode just ran in its call's execution context `context`, from+ /// FunctionDeclarationInstantiation until it first awaited, returned or threw (`result`), and returns its promise.+ ///+ /// OPTIMIZATION: The spec runs the body in a copy of the call's execution context (asyncContext). The bytecode runs+ /// it in the call's own context until it first awaits, and the async function gets its copy and a+ /// driver only then, since nothing resumes the call's context. A function that never awaits needs+ /// neither.+ pub fn start(+ vm: &Vm,+ realm: Gc<Realm>,+ generating_function: GeneratingFunction,+ context: &ExecutionContext,+ result: Result<Value, Value>,+ ) -> Gc<Promise> {+ // 1. Let promiseCapability be ! NewPromiseCapability(%Promise%).let top_level_promise = Promise::create(vm, realm);++ let value = match result {+ // 3. If completion is an abrupt completion, then+ // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »).+ // NB: The same goes for a throw completion of the body (AsyncBlockStart).+ Err(exception) => {+ top_level_promise.reject(vm, exception);+ return top_level_promise;+ }+ Ok(value) if value.is_empty() => Value::UNDEFINED,+ Ok(value) => value,+ };++ // NB: The body returned without awaiting.+ if context.yield_continuation.get() == ExecutionContext::NO_YIELD_CONTINUATION {+ let resolving_functions = top_level_promise.create_resolving_functions(vm);+ call_function_object(vm, resolving_functions.resolve, Value::UNDEFINED, &[value]).must();+ return top_level_promise;+ }++ // NB: The body awaits `value`, suspended like a generator at a yield.+ let generator_object = GeneratorObject::create(vm, realm, generating_function, context.copy());+ generator_object.set_generator_state(GeneratorState::SuspendedYield);// Note: The top_level_promise is also kept alive by this Wrapperlet wrapper = realm.create_object(vm,@@ -75,9 +114,7 @@ impl AsyncFunctionDriverWrapper {is_initial_execution: Cell::new(true),},);- // Prime the generator:- // This runs until the first `await value;`- Self::continue_async_execution(wrapper, vm, Value::UNDEFINED, true);+ Self::run(wrapper, vm, Ok(IterationResult::new(value, false)));top_level_promise}@@ -95,11 +132,14 @@ impl AsyncFunctionDriverWrapper {let realm = vm.current_realm().expect("there is a current realm");// 1. Let asyncContext be the running execution context.+ // NB: The generator object keeps the context the async function resumes in. This one only runs the steps that+ // settle what it awaits, as the running context of the function's realm and script, so it holds none of+ // the values of the function's frame.if this.suspended_execution_context.borrow().is_none() {let copy = vm.running_execution_context_if_any().expect("an async function awaits in an execution context")- .copy();+ .copy_without_values();*this.suspended_execution_context.borrow_mut() = Some(copy);}@@ -217,13 +257,19 @@ impl AsyncFunctionDriverWrapper {fn continue_async_execution(this: Gc<AsyncFunctionDriverWrapper>, vm: &Vm, value: Value, is_successful: bool) {let generator_object = this.generator_object.get();- let mut generator_result = if is_successful {+ let generator_result = if is_successful {generator_object.resume(vm, value, None)} else {crate::embedding::completion::log_exception_if_enabled(vm, value);generator_object.resume_abrupt(vm, Completion::new(CompletionType::Throw, value), None)};+ Self::run(this, vm, generator_result);+ }+ /// Continues the async function from what its generator last returned (`generator_result`): settles its promise if+ /// it completed, and awaits the value it awaits otherwise, resuming it right away where it can.+ fn run(this: Gc<AsyncFunctionDriverWrapper>, vm: &Vm, mut generator_result: ThrowCompletionOr<IterationResult>) {+ let generator_object = this.generator_object.get();let result: ThrowCompletionOr<()> = loop {let result: IterationResult = match generator_result {Err(throw) => break Err(throw),diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rsindex f4c1ebbc58f..2939af9fa43 100644--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs@@ -636,16 +636,25 @@ impl EcmascriptFunctionObject {let executable = self.bytecode_executable().expect("a function is compiled before it is called");- let result = vm- .run_executable(NonNull::from(context), executable, 0)- .map_err(Throw::new)?;+ let result = vm.run_executable(NonNull::from(context), executable, 0);// NOTE: Running the bytecode should eventually return a completion.// Until it does, we assume "return" and include the undefined fallback from the call site.if self.kind() == FunctionKind::Normal {- return Ok(result);+ return result.map_err(Throw::new);}+ if self.kind() == FunctionKind::Async {+ return Ok(Value::from_object(AsyncFunctionDriverWrapper::start(+ vm,+ context.realm.get().expect("a function runs in a realm"),+ GeneratingFunction::Ecmascript(self.as_ecmascript_function_gc()),+ context,+ result,+ )));+ }+ result.map_err(Throw::new)?;+let realm = context.realm.get().expect("a function runs in a realm");if self.kind() == FunctionKind::AsyncGenerator {return Ok(Value::from_object(AsyncGenerator::create(@@ -656,24 +665,13 @@ impl EcmascriptFunctionObject {)));}- let generator_object = GeneratorObject::create(+ debug_assert!(self.kind() == FunctionKind::Generator);+ Ok(Value::from_object(GeneratorObject::create(vm,realm,GeneratingFunction::Ecmascript(self.as_ecmascript_function_gc()),context.copy(),- );-- // NOTE: Async functions are entirely transformed to generator functions, and wrapped in a custom driver that returns a promise.- if self.kind() == FunctionKind::Async {- return Ok(Value::from_object(AsyncFunctionDriverWrapper::create(- vm,- realm,- generator_object,- )));- }-- debug_assert!(self.kind() == FunctionKind::Generator);- Ok(Value::from_object(generator_object))+ )))}pub fn set_name(&self, vm: &Vm, name: &Utf16FlyString) {diff --git a/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rs b/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rsindex b316999fa83..2c7bf14565b 100644--- a/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/native_javascript_backed_function.rs@@ -145,13 +145,11 @@ impl NativeJavaScriptBackedFunction {let running_execution_context = vm.running_execution_context().expect("a NativeJavaScriptBackedFunction runs in its own execution context");- let result = vm- .run_executable(running_execution_context, function.bytecode_executable(vm), 0)- .map_err(Throw::new)?;+ let result = vm.run_executable(running_execution_context, function.bytecode_executable(vm), 0);let kind = function.kind();if kind == FunctionKind::Normal {- return Ok(result);+ return result.map_err(Throw::new);}let realm = vm@@ -161,29 +159,33 @@ impl NativeJavaScriptBackedFunction {GeneratingFunction::NativeJavaScriptBacked(function.as_native_javascript_backed_function_gc());// SAFETY: The running execution context is live.let running_execution_context = unsafe { running_execution_context.as_ref() };- if kind == FunctionKind::AsyncGenerator {- return Ok(Value::from_object(AsyncGenerator::create(+ if kind == FunctionKind::Async {+ return Ok(Value::from_object(AsyncFunctionDriverWrapper::start(vm,realm,generating_function,- running_execution_context.copy(),+ running_execution_context,+ result,)));}+ result.map_err(Throw::new)?;- let generator_object =- GeneratorObject::create(vm, realm, generating_function, running_execution_context.copy());-- // NOTE: Async functions are entirely transformed to generator functions, and wrapped in a custom driver that returns a promise.- if kind == FunctionKind::Async {- return Ok(Value::from_object(AsyncFunctionDriverWrapper::create(+ if kind == FunctionKind::AsyncGenerator {+ return Ok(Value::from_object(AsyncGenerator::create(vm,realm,- generator_object,+ generating_function,+ running_execution_context.copy(),)));}assert!(kind == FunctionKind::Generator);- Ok(Value::from_object(generator_object))+ Ok(Value::from_object(GeneratorObject::create(+ vm,+ realm,+ generating_function,+ running_execution_context.copy(),+ )))}pub fn bytecode_executable(&self, vm: &Vm) -> Gc<Executable> {diff --git a/Tests/LibJS/Bytecode/expected/async-await-in-try-catch.txt b/Tests/LibJS/Bytecode/expected/async-await-in-try-catch.txtindex 6c8a5c67c24..70b56cac22a 100644--- a/Tests/LibJS/Bytecode/expected/async-await-in-try-catch.txt+++ b/Tests/LibJS/Bytecode/expected/async-await-in-try-catch.txt@@ -12,47 +12,44 @@ block0:[ 50] End value:reg5-f$0298e68c async-await-in-try-catch.js:2:5+f$0ae4b9bc async-await-in-try-catch.js:2:5Registers: 10- Blocks: 8+ Blocks: 7Locals: e~0Constants:- [0] = Undefined- [1] = Int32(1)+ [0] = Int32(1)+ [1] = Undefinedblock0:[ 0] Enter- [ 8] Yield continuation_label:block1, value:Undefined+ [ 8] GetLexicalEnvironment dst:reg4+ [ 10] Jump target:block3block1:- [ 18] GetLexicalEnvironment dst:reg4- [ 20] Jump target:block4+ [ 18] Catch dst:reg5+ [ 20] SetLexicalEnvironment environment:reg4+ [ 28] Mov dst:e~0, src:reg5block2:- [ 28] Catch dst:reg5- [ 30] SetLexicalEnvironment environment:reg4- [ 38] Mov dst:e~0, src:reg5+ [ 38] Yield value:Undefinedblock3:- [ 48] Yield value:Undefined+ [ 48] EnterObjectEnvironment dst:reg5, object:arg0+ [ 58] Mov dst:reg6, src:reg0+ [ 68] Await continuation_label:block4, argument:Int32(1)block4:- [ 58] EnterObjectEnvironment dst:reg5, object:arg0- [ 68] Mov dst:reg6, src:reg0- [ 78] Await continuation_label:block5, argument:Int32(1)+ [ 78] Mov dst:reg6, src:reg0+ [ 88] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6+ [ 98] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg7, rhs:1, true_target:block5, false_target:block6block5:- [ 88] Mov dst:reg6, src:reg0- [ 98] GetCompletionFields type_dst:reg7, value_dst:reg8, completion:reg6- [ a8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg7, rhs:1, true_target:block6, false_target:block7+ [ b0] SetLexicalEnvironment environment:reg4+ [ b8] JumpLoop target:block2block6:[ c0] SetLexicalEnvironment environment:reg4- [ c8] JumpLoop target:block3--block7:- [ d0] SetLexicalEnvironment environment:reg4- [ d8] Throw src:reg8+ [ c8] Throw src:reg8Exception handlers:- [ 58 .. e0] => handler block2+ [ 48 .. d0] => handler block1diff --git a/Tests/LibJS/Bytecode/expected/async-await.txt b/Tests/LibJS/Bytecode/expected/async-await.txtindex b9c0c9f7b3b..4e3acd53f63 100644--- a/Tests/LibJS/Bytecode/expected/async-await.txt+++ b/Tests/LibJS/Bytecode/expected/async-await.txt@@ -11,32 +11,28 @@ block0:[ 38] End value:reg5-f$d3dfd701 async-await.js:7:5+f$d11be5f1 async-await.js:7:5Registers: 10- Blocks: 5+ Blocks: 4Constants:- [0] = Undefined- [1] = Int32(42)- [2] = Int32(1)+ [0] = Int32(42)+ [1] = Int32(1)block0:[ 0] Enter- [ 8] Yield continuation_label:block1, value:Undefined+ [ 8] GetGlobal value_feedback:0, dst:reg6, `Promise`+ [ 18] GetById value_feedback:1, dst:reg7, base:reg6, `resolve` (Promise.resolve)+ [ 30] Call value_feedback:2, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, Promise.resolve, arguments:[Int32(42)]+ [ 58] Mov dst:reg7, src:reg0+ [ 68] Await continuation_label:block1, argument:reg5block1:- [ 18] GetGlobal value_feedback:0, dst:reg6, `Promise`- [ 28] GetById value_feedback:1, dst:reg7, base:reg6, `resolve` (Promise.resolve)- [ 40] Call value_feedback:2, call_feedback:0, dst:reg5, callee:reg7, this_value:reg6, Promise.resolve, arguments:[Int32(42)]- [ 68] Mov dst:reg7, src:reg0- [ 78] Await continuation_label:block2, argument:reg5+ [ 78] Mov dst:reg7, src:reg0+ [ 88] GetCompletionFields type_dst:reg6, value_dst:reg8, completion:reg7+ [ 98] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg6, rhs:1, true_target:block2, false_target:block3block2:- [ 88] Mov dst:reg7, src:reg0- [ 98] GetCompletionFields type_dst:reg6, value_dst:reg8, completion:reg7- [ a8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg6, rhs:1, true_target:block3, false_target:block4+ [ b0] Yield value:reg8block3:- [ c0] Yield value:reg8--block4:- [ d0] Throw src:reg8+ [ c0] Throw src:reg8diff --git a/Tests/LibJS/Bytecode/expected/async-return-bare.txt b/Tests/LibJS/Bytecode/expected/async-return-bare.txtindex b8ae5cffd37..ef12578fe97 100644--- a/Tests/LibJS/Bytecode/expected/async-return-bare.txt+++ b/Tests/LibJS/Bytecode/expected/async-return-bare.txt@@ -11,15 +11,12 @@ block0:[ 38] End value:reg5-f$6007a144 async-return-bare.js:2:5+f$68537474 async-return-bare.js:2:5Registers: 5- Blocks: 2+ Blocks: 1Constants:[0] = Undefinedblock0:[ 0] Enter- [ 8] Yield continuation_label:block1, value:Undefined--block1:- [ 18] Yield value:Undefined+ [ 8] Yield value:Undefineddiff --git a/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txt b/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txtindex c0969a86c1b..8a37788f95d 100644--- a/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txt+++ b/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txt@@ -133,130 +133,127 @@ Exception handlers:[ c8 .. f0] => handler block3-forAwaitOfBreak$86d2e55f for-of-iterator-close.js:16:24+forAwaitOfBreak$8996d66f for-of-iterator-close.js:16:24Registers: 18- Blocks: 30+ Blocks: 29Locals: x~0Constants:- [0] = Undefined- [1] = Int32(1)- [2] = Int32(2)- [3] = Int32(3)+ [0] = Int32(1)+ [1] = Int32(2)+ [2] = Int32(3)+ [3] = Undefinedblock0:[ 0] Enter- [ 8] Yield continuation_label:block1, value:Undefined+ [ 8] GetLexicalEnvironment dst:reg4+ [ 10] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg6, dst_iterator_done:reg7, iterable:arg0, fast_array_mode_allowed:false+ [ 30] Jump target:block2block1:- [ 18] GetLexicalEnvironment dst:reg4- [ 20] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg6, dst_iterator_done:reg7, iterable:arg0, fast_array_mode_allowed:false- [ 40] Jump target:block3+ [ 38] Yield value:Undefinedblock2:- [ 48] Yield value:Undefined+ [ 48] IteratorNext dst:reg12, iterator_object:reg5, iterator_next:reg6, iterator_done:reg7+ [ 60] Mov dst:reg13, src:reg0+ [ 70] Await continuation_label:block5, argument:reg12block3:- [ 58] IteratorNext dst:reg12, iterator_object:reg5, iterator_next:reg6, iterator_done:reg7- [ 70] Mov dst:reg13, src:reg0- [ 80] Await continuation_label:block6, argument:reg12+ [ 80] Catch dst:reg9+ [ 88] SetLexicalEnvironment environment:reg4+ [ 90] Mov dst:reg8, src:Int32(1)block4:- [ 90] Catch dst:reg9- [ 98] SetLexicalEnvironment environment:reg4- [ a0] Mov dst:reg8, src:Int32(1)+ [ a0] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg8, rhs:1, true_target:block12, false_target:block13block5:- [ b0] JumpStrictlyEqualsRhsInt32 arith_feedback:2, lhs:reg8, rhs:1, true_target:block13, false_target:block14+ [ b8] Mov dst:reg13, src:reg0+ [ c8] GetCompletionFields type_dst:reg14, value_dst:reg15, completion:reg13+ [ d8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg14, rhs:1, true_target:block6, false_target:block7block6:- [ c8] Mov dst:reg13, src:reg0- [ d8] GetCompletionFields type_dst:reg14, value_dst:reg15, completion:reg13- [ e8] JumpStrictlyEqualsRhsInt32 arith_feedback:0, lhs:reg14, rhs:1, true_target:block7, false_target:block8+ [ f0] Mov dst:reg12, src:reg15+ [ 100] ThrowIfNotObject src:reg12+ [ 108] GetById value_feedback:0, dst:reg11, base:reg12, `done`+ [ 120] JumpIfLoop condition:reg11, true_target:block1, false_target:block8block7:- [ 100] Mov dst:reg12, src:reg15- [ 110] ThrowIfNotObject src:reg12- [ 118] GetById value_feedback:0, dst:reg11, base:reg12, `done`- [ 130] JumpIfLoop condition:reg11, true_target:block2, false_target:block9+ [ 130] Throw src:reg15block8:- [ 140] Throw src:reg15+ [ 138] GetById value_feedback:1, dst:reg10, base:reg12, `value`block9:- [ 148] GetById value_feedback:1, dst:reg10, base:reg12, `value`+ [ 150] Mov dst:x~0, src:reg10+ [ 160] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:x~0, rhs:2, true_target:block10, false_target:block11block10:- [ 160] Mov dst:x~0, src:reg10- [ 170] JumpStrictlyEqualsRhsInt32 arith_feedback:1, lhs:x~0, rhs:2, true_target:block11, false_target:block12+ [ 178] Mov dst:reg8, src:Int32(3)+ [ 188] JumpLoop target:block4block11:- [ 188] Mov dst:reg8, src:Int32(3)- [ 198] JumpLoop target:block5+ [ 190] JumpLoop target:block2block12:- [ 1a0] JumpLoop target:block3+ [ 198] Jump target:block24block13:- [ 1a8] Jump target:block25+ [ 1a0] GetMethod dst:reg12, object:reg5, `return`+ [ 1b8] JumpUndefined condition:reg12, true_target:block14, false_target:block15block14:- [ 1b0] GetMethod dst:reg12, object:reg5, `return`- [ 1c8] JumpUndefined condition:reg12, true_target:block15, false_target:block16+ [ 1c8] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:4, lhs:reg8, rhs:3, true_target:block1, false_target:block19block15:- [ 1d8] JumpStrictlyEqualsLoopRhsInt32 arith_feedback:4, lhs:reg8, rhs:3, true_target:block2, false_target:block20+ [ 1e0] Call value_feedback:2, call_feedback:0, dst:reg13, callee:reg12, this_value:reg5+ [ 200] Await continuation_label:block16, argument:reg13block16:- [ 1f0] Call value_feedback:2, call_feedback:0, dst:reg13, callee:reg12, this_value:reg5- [ 210] Await continuation_label:block17, argument:reg13+ [ 210] Mov dst:reg14, src:reg0+ [ 220] GetCompletionFields type_dst:reg15, value_dst:reg16, completion:reg14+ [ 230] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg15, rhs:1, true_target:block17, false_target:block18block17:- [ 220] Mov dst:reg14, src:reg0- [ 230] GetCompletionFields type_dst:reg15, value_dst:reg16, completion:reg14- [ 240] JumpStrictlyEqualsRhsInt32 arith_feedback:3, lhs:reg15, rhs:1, true_target:block18, false_target:block19+ [ 248] ThrowIfNotObject src:reg16+ [ 250] JumpLoop target:block14block18:- [ 258] ThrowIfNotObject src:reg16- [ 260] JumpLoop target:block15+ [ 258] Throw src:reg16block19:- [ 268] Throw src:reg16+ [ 260] JumpStrictlyEqualsRhsInt32 arith_feedback:5, lhs:reg8, rhs:2, true_target:block20, false_target:block21block20:- [ 270] JumpStrictlyEqualsRhsInt32 arith_feedback:5, lhs:reg8, rhs:2, true_target:block21, false_target:block22+ [ 278] Return value:reg9block21:- [ 288] Return value:reg9+ [ 280] Throw src:reg9block22:- [ 290] Throw src:reg9+ [ 288] Throw src:reg9block23:- [ 298] Throw src:reg9+ [ 290] Catch dst:reg12+ [ 298] JumpLoop target:block22block24:- [ 2a0] Catch dst:reg12- [ 2a8] JumpLoop target:block23+ [ 2a0] GetMethod dst:reg12, object:reg5, `return`+ [ 2b8] JumpUndefined condition:reg12, true_target:block22, false_target:block25block25:- [ 2b0] GetMethod dst:reg12, object:reg5, `return`- [ 2c8] JumpUndefined condition:reg12, true_target:block23, false_target:block26+ [ 2c8] Call value_feedback:3, call_feedback:1, dst:reg13, callee:reg12, this_value:reg5+ [ 2e8] Await continuation_label:block26, argument:reg13block26:- [ 2d8] Call value_feedback:3, call_feedback:1, dst:reg13, callee:reg12, this_value:reg5- [ 2f8] Await continuation_label:block27, argument:reg13+ [ 2f8] Mov dst:reg14, src:reg0+ [ 308] GetCompletionFields type_dst:reg15, value_dst:reg16, completion:reg14+ [ 318] JumpStrictlyEqualsRhsInt32 arith_feedback:6, lhs:reg15, rhs:1, true_target:block27, false_target:block28block27:- [ 308] Mov dst:reg14, src:reg0- [ 318] GetCompletionFields type_dst:reg15, value_dst:reg16, completion:reg14- [ 328] JumpStrictlyEqualsRhsInt32 arith_feedback:6, lhs:reg15, rhs:1, true_target:block28, false_target:block29+ [ 330] JumpLoop target:block22block28:- [ 340] JumpLoop target:block23--block29:- [ 348] Throw src:reg16+ [ 338] Throw src:reg16Exception handlers:- [ 160 .. 1a8] => handler block4- [ 2b0 .. 350] => handler block24+ [ 150 .. 198] => handler block3+ [ 2a0 .. 340] => handler block23diff --git a/Tests/LibJS/JIT/ir/async-functions.js b/Tests/LibJS/JIT/ir/async-functions.jsindex ebe1ccc1dd8..93a783898c5 100644--- a/Tests/LibJS/JIT/ir/async-functions.js+++ b/Tests/LibJS/JIT/ir/async-functions.js@@ -1,7 +1,8 @@-// An async function suspends at an await in compiled code like the interpreter's Await: it writes the slots live at-// the continuation to its frame, records the continuation and that the value is awaited, and returns the value. It-// resumes at an entry block of the continuation, which loads those slots from the frame like a generator's resume-// entry, and reads the completion it resumed with from its generator object.+// An async function runs from its start into its body, which has no initial suspension. It suspends at an await in+// compiled code like the interpreter's Await: it writes the slots live at the continuation to its frame, records the+// continuation and that the value is awaited, and returns the value. It resumes at an entry block of the continuation,+// which loads those slots from the frame like a generator's resume entry, and reads the completion it resumed with+// from its generator object.async function sum(values) {let total = 0;@@ -20,9 +21,7 @@ for (let i = 0; i < 10; ++i) warm_up.push(sum([1, 2, 3]));// CHECK-NEXT: LoadSlot r12// CHECK-NEXT: Jump [[CONTINUATION:b[0-9]+]]// CHECK: InitializeFrame-// CHECK-NEXT: LoadSlot r2-// CHECK-NEXT: Suspend pc [[START:[0-9]+]]-// CHECK-NEXT: Return (#undefined)+// CHECK-NOT: Suspend// CHECK: [[VALUE:v[0-9]+]] = EmptyToUndefined// CHECK-NEXT: Suspend pc [[NEXT:[0-9]+]] await// CHECK-NEXT: Return ([[VALUE]])@@ -34,8 +33,9 @@ for (let i = 0; i < 10; ++i) warm_up.push(sum([1, 2, 3]));// CHECK-NOT: Exit NoFeedback// CHECK: Suspend completed// CHECK-NEXT: Return-// CHECK: osr entry at pc [[START]]: {{b[0-9]+}}-// CHECK-NEXT: osr entry at pc [[NEXT]]: [[RESUME]]+// CHECK-NOT: osr entry+// CHECK: osr entry at pc [[NEXT]]: [[RESUME]]+// CHECK-NOT: osr entryPromise.all(warm_up).then(() => {jit.compile(sum);diff --git a/Tests/LibJS/Runtime/jit/async-functions.js b/Tests/LibJS/Runtime/jit/async-functions.jsindex 9ab23a26e56..1ec3a82c59f 100644--- a/Tests/LibJS/Runtime/jit/async-functions.js+++ b/Tests/LibJS/Runtime/jit/async-functions.js@@ -162,6 +162,73 @@ describe("async functions in compiled code", () => {});});+describe("async functions run in their call until they first await", () => {+ test("reject when evaluating a parameter throws", () => {+ const parameters = prepared(AsyncFunction, "a = (() => { throw new TypeError('parameter'); })()", "return a;");+ compile(parameters, () => parameters(1));+ let promise;+ expect(() => (promise = parameters())).not.toThrow();+ const { error } = settle(promise);+ expect(error).toBeInstanceOf(TypeError);+ expect(error.message).toBe("parameter");+ expect(settle(parameters(5))).toEqual({ value: 5 });+ });++ test("run synchronously up to the first await, and reject when they throw before it", () => {+ const steps = [];+ const make = new Function(+ "steps",+ "jit",+ "const f = async function (fail) { steps.push('body'); if (fail) throw new RangeError('before'); await 0; steps.push('after'); }; jit.prepare(f); return f;"+ );+ const f = make(steps, jit);+ compile(f, () => f(false));+ steps.length = 0;+ const promise = f(false);+ steps.push("returned");+ runQueuedPromiseJobs();+ expect(steps).toEqual(["body", "returned", "after"]);+ let thrown;+ expect(() => (thrown = f(true))).not.toThrow();+ const { error } = settle(thrown);+ expect(error).toBeInstanceOf(RangeError);+ expect(error.message).toBe("before");+ expect(settle(promise)).toEqual({ value: undefined });+ });++ test("resolve when they return without awaiting, adopting returned thenables", () => {+ const identity = prepared(AsyncFunction, "value", "return value;");+ compile(identity, () => identity(1));+ expect(settle(identity(7))).toEqual({ value: 7 });+ expect(settle(identity())).toEqual({ value: undefined });+ const thenable = { then: resolve => resolve("adopted") };+ expect(settle(identity(thenable))).toEqual({ value: "adopted" });+ expect(settle(identity(Promise.resolve("promise")))).toEqual({ value: "promise" });+ const rejected = settle(identity(Promise.reject(new SyntaxError("rejected"))));+ expect(rejected.error).toBeInstanceOf(SyntaxError);+ });++ test("catch a rejection of their first await", () => {+ const guarded = prepared(+ AsyncFunction,+ "promise",+ "try { await promise; return 'resolved'; } catch (error) { return 'caught ' + error; }"+ );+ expect(settle(guarded(Promise.reject("oops")))).toEqual({ value: "caught oops" });+ expect(settle(guarded(Promise.resolve()))).toEqual({ value: "resolved" });+ });++ test("show up once in stack traces before their first await", () => {+ async function listsItselfOnce() {+ const stack = new Error().stack;+ await 0;+ return stack;+ }+ const { value } = settle(listsItselfOnce());+ expect(value.split("\n").filter(line => line.includes("listsItselfOnce"))).toHaveLength(1);+ });+});+describe("async generators in compiled code", () => {test("yield and await with the values live across both", () => {const values = prepared(diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-error-objects.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-error-objects.txtindex 4dccd208bea..e222715cfb5 100644--- a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-error-objects.txt+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-error-objects.txt@@ -25,7 +25,7 @@ new with message and cause: CompileError: problemError.isError: truename: CompileError, message: "problem"stack head: CompileError: problem- stack frames: CompileError > <script> > <script> > <script>+ stack frames: CompileError > <script> > <script>message: problem (writable=true, enumerable=false, configurable=true)cause: 42 (writable=true, enumerable=false, configurable=true)called without new: CompileError: called@@ -37,7 +37,7 @@ called without new: CompileError: calledError.isError: truename: CompileError, message: "called"stack head: CompileError: called- stack frames: CompileError > <script> > <script> > <script>+ stack frames: CompileError > <script> > <script>new without arguments: CompileErrorown keys:prototype is CompileError.prototype: true@@ -47,7 +47,7 @@ new without arguments: CompileErrorError.isError: truename: CompileError, message: ""stack head: CompileError- stack frames: CompileError > <script> > <script> > <script>+ stack frames: CompileError > <script> > <script>undefined message and no cause: CompileErrorown keys:prototype is CompileError.prototype: true@@ -57,7 +57,7 @@ undefined message and no cause: CompileErrorError.isError: truename: CompileError, message: ""stack head: CompileError- stack frames: CompileError > <script> > <script> > <script>+ stack frames: CompileError > <script> > <script>coerced message: CompileError: coercedown keys: messageprototype is CompileError.prototype: true@@ -67,7 +67,7 @@ coerced message: CompileError: coercedError.isError: truename: CompileError, message: "coerced"stack head: CompileError: coerced- stack frames: CompileError > <script> > <script> > <script>+ stack frames: CompileError > <script> > <script>argument evaluation order: message,causethrowing message: TypeError: from toStringthrowing cause: RangeError: from cause@@ -80,7 +80,7 @@ subclass: CompileError: derivedError.isError: truename: CompileError, message: "derived"stack head: CompileError: derived- stack frames: CompileError > Subclass > <script> > <script> > <script>+ stack frames: CompileError > Subclass > <script> > <script>instanceof CompileError: true, extra: trueReflect.construct with Object as new.target: prototype is Object.prototype: trueObject.prototype.toString: [object Error], Error.isError: true@@ -115,7 +115,7 @@ new with message and cause: LinkError: problemError.isError: truename: LinkError, message: "problem"stack head: LinkError: problem- stack frames: LinkError > <script> > <script> > <script>+ stack frames: LinkError > <script> > <script>message: problem (writable=true, enumerable=false, configurable=true)cause: 42 (writable=true, enumerable=false, configurable=true)called without new: LinkError: called@@ -127,7 +127,7 @@ called without new: LinkError: calledError.isError: truename: LinkError, message: "called"stack head: LinkError: called- stack frames: LinkError > <script> > <script> > <script>+ stack frames: LinkError > <script> > <script>new without arguments: LinkErrorown keys:prototype is LinkError.prototype: true@@ -137,7 +137,7 @@ new without arguments: LinkErrorError.isError: truename: LinkError, message: ""stack head: LinkError- stack frames: LinkError > <script> > <script> > <script>+ stack frames: LinkError > <script> > <script>undefined message and no cause: LinkErrorown keys:prototype is LinkError.prototype: true@@ -147,7 +147,7 @@ undefined message and no cause: LinkErrorError.isError: truename: LinkError, message: ""stack head: LinkError- stack frames: LinkError > <script> > <script> > <script>+ stack frames: LinkError > <script> > <script>coerced message: LinkError: coercedown keys: messageprototype is LinkError.prototype: true@@ -157,7 +157,7 @@ coerced message: LinkError: coercedError.isError: truename: LinkError, message: "coerced"stack head: LinkError: coerced- stack frames: LinkError > <script> > <script> > <script>+ stack frames: LinkError > <script> > <script>argument evaluation order: message,causethrowing message: TypeError: from toStringthrowing cause: RangeError: from cause@@ -170,7 +170,7 @@ subclass: LinkError: derivedError.isError: truename: LinkError, message: "derived"stack head: LinkError: derived- stack frames: LinkError > Subclass > <script> > <script> > <script>+ stack frames: LinkError > Subclass > <script> > <script>instanceof LinkError: true, extra: trueReflect.construct with Object as new.target: prototype is Object.prototype: trueObject.prototype.toString: [object Error], Error.isError: true@@ -205,7 +205,7 @@ new with message and cause: RuntimeError: problemError.isError: truename: RuntimeError, message: "problem"stack head: RuntimeError: problem- stack frames: RuntimeError > <script> > <script> > <script>+ stack frames: RuntimeError > <script> > <script>message: problem (writable=true, enumerable=false, configurable=true)cause: 42 (writable=true, enumerable=false, configurable=true)called without new: RuntimeError: called@@ -217,7 +217,7 @@ called without new: RuntimeError: calledError.isError: truename: RuntimeError, message: "called"stack head: RuntimeError: called- stack frames: RuntimeError > <script> > <script> > <script>+ stack frames: RuntimeError > <script> > <script>new without arguments: RuntimeErrorown keys:prototype is RuntimeError.prototype: true@@ -227,7 +227,7 @@ new without arguments: RuntimeErrorError.isError: truename: RuntimeError, message: ""stack head: RuntimeError- stack frames: RuntimeError > <script> > <script> > <script>+ stack frames: RuntimeError > <script> > <script>undefined message and no cause: RuntimeErrorown keys:prototype is RuntimeError.prototype: true@@ -237,7 +237,7 @@ undefined message and no cause: RuntimeErrorError.isError: truename: RuntimeError, message: ""stack head: RuntimeError- stack frames: RuntimeError > <script> > <script> > <script>+ stack frames: RuntimeError > <script> > <script>coerced message: RuntimeError: coercedown keys: messageprototype is RuntimeError.prototype: true@@ -247,7 +247,7 @@ coerced message: RuntimeError: coercedError.isError: truename: RuntimeError, message: "coerced"stack head: RuntimeError: coerced- stack frames: RuntimeError > <script> > <script> > <script>+ stack frames: RuntimeError > <script> > <script>argument evaluation order: message,causethrowing message: TypeError: from toStringthrowing cause: RangeError: from cause@@ -260,7 +260,7 @@ subclass: RuntimeError: derivedError.isError: truename: RuntimeError, message: "derived"stack head: RuntimeError: derived- stack frames: RuntimeError > Subclass > <script> > <script> > <script>+ stack frames: RuntimeError > Subclass > <script> > <script>instanceof RuntimeError: true, extra: trueReflect.construct with Object as new.target: prototype is Object.prototype: trueObject.prototype.toString: [object Error], Error.isError: true@@ -278,7 +278,7 @@ invalid module: CompileError: Unexpected end-of-fileError.isError: truename: CompileError, message: "Unexpected end-of-file"stack head: CompileError: Unexpected end-of-file- stack frames: Module > <script> > thrownBy > <script> > <script> > <script>+ stack frames: Module > <script> > thrownBy > <script> > <script>rejected compile: CompileError: Unexpected end-of-fileown keys: messageprototype is CompileError.prototype: true