AsyncFunctionDriverWrapper.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/TypeCasts.h>
  7. #include <LibJS/Runtime/AsyncFunctionDriverWrapper.h>
  8. #include <LibJS/Runtime/GlobalObject.h>
  9. #include <LibJS/Runtime/NativeFunction.h>
  10. #include <LibJS/Runtime/PromiseCapability.h>
  11. #include <LibJS/Runtime/PromiseConstructor.h>
  12. #include <LibJS/Runtime/VM.h>
  13. namespace JS {
  14. ThrowCompletionOr<Value> AsyncFunctionDriverWrapper::create(Realm& realm, GeneratorObject* generator_object)
  15. {
  16. auto top_level_promise = Promise::create(realm);
  17. // Note: This generates a handle to itself, which it clears upon completing its execution
  18. // The top_level_promise is also kept alive by this Wrapper
  19. auto wrapper = MUST_OR_THROW_OOM(realm.heap().allocate<AsyncFunctionDriverWrapper>(realm, realm, *generator_object, *top_level_promise));
  20. // Prime the generator:
  21. // This runs until the first `await value;`
  22. wrapper->continue_async_execution(realm.vm(), js_undefined(), true, IsInitialExecution::Yes);
  23. return top_level_promise;
  24. }
  25. AsyncFunctionDriverWrapper::AsyncFunctionDriverWrapper(Realm& realm, NonnullGCPtr<GeneratorObject> generator_object, NonnullGCPtr<Promise> top_level_promise)
  26. : Promise(realm.intrinsics().promise_prototype())
  27. , m_generator_object(generator_object)
  28. , m_top_level_promise(top_level_promise)
  29. , m_self_handle(make_handle(*this))
  30. {
  31. }
  32. // 27.7.5.3 Await ( value ), https://tc39.es/ecma262/#await
  33. ThrowCompletionOr<void> AsyncFunctionDriverWrapper::await(JS::Value value)
  34. {
  35. auto& vm = this->vm();
  36. auto& realm = *vm.current_realm();
  37. // 1. Let asyncContext be the running execution context.
  38. m_suspended_execution_context = vm.running_execution_context().copy();
  39. // 2. Let promise be ? PromiseResolve(%Promise%, value).
  40. auto* promise_object = TRY(promise_resolve(vm, realm.intrinsics().promise_constructor(), value));
  41. // 3. Let fulfilledClosure be a new Abstract Closure with parameters (v) that captures asyncContext and performs the
  42. // following steps when called:
  43. auto fulfilled_closure = [this](VM& vm) -> ThrowCompletionOr<Value> {
  44. auto value = vm.argument(0);
  45. // a. Let prevContext be the running execution context.
  46. auto& prev_context = vm.running_execution_context();
  47. // FIXME: b. Suspend prevContext.
  48. // c. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  49. TRY(vm.push_execution_context(m_suspended_execution_context.value(), {}));
  50. // d. Resume the suspended evaluation of asyncContext using NormalCompletion(v) as the result of the operation that
  51. // suspended it.
  52. continue_async_execution(vm, value, true);
  53. // e. Assert: When we reach this step, asyncContext has already been removed from the execution context stack and
  54. // prevContext is the currently running execution context.
  55. VERIFY(&vm.running_execution_context() == &prev_context);
  56. // f. Return undefined.
  57. return js_undefined();
  58. };
  59. // 4. Let onFulfilled be CreateBuiltinFunction(fulfilledClosure, 1, "", « »).
  60. auto on_fulfilled = NativeFunction::create(realm, move(fulfilled_closure), 1, "");
  61. // 5. Let rejectedClosure be a new Abstract Closure with parameters (reason) that captures asyncContext and performs the
  62. // following steps when called:
  63. auto rejected_closure = [this](VM& vm) -> ThrowCompletionOr<Value> {
  64. auto reason = vm.argument(0);
  65. // a. Let prevContext be the running execution context.
  66. auto& prev_context = vm.running_execution_context();
  67. // FIXME: b. Suspend prevContext.
  68. // c. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  69. TRY(vm.push_execution_context(m_suspended_execution_context.value(), {}));
  70. // d. Resume the suspended evaluation of asyncContext using ThrowCompletion(reason) as the result of the operation that
  71. // suspended it.
  72. continue_async_execution(vm, reason, false);
  73. // e. Assert: When we reach this step, asyncContext has already been removed from the execution context stack and
  74. // prevContext is the currently running execution context.
  75. VERIFY(&vm.running_execution_context() == &prev_context);
  76. // f. Return undefined.
  77. return js_undefined();
  78. };
  79. // 6. Let onRejected be CreateBuiltinFunction(rejectedClosure, 1, "", « »).
  80. auto on_rejected = NativeFunction::create(realm, move(rejected_closure), 1, "");
  81. // 7. Perform PerformPromiseThen(promise, onFulfilled, onRejected).
  82. m_current_promise = verify_cast<Promise>(promise_object);
  83. m_current_promise->perform_then(on_fulfilled, on_rejected, {});
  84. // 8. Remove asyncContext from the execution context stack and restore the execution context that is at the top of the
  85. // execution context stack as the running execution context.
  86. // NOTE: This is done later on for us in continue_async_execution.
  87. // NOTE: None of these are necessary. 10-12 are handled by step d of the above lambdas.
  88. // 9. Let callerContext be the running execution context.
  89. // 10. Resume callerContext passing empty. If asyncContext is ever resumed again, let completion be the Completion Record with which it is resumed.
  90. // 11. Assert: If control reaches here, then asyncContext is the running execution context again.
  91. // 12. Return completion.
  92. return {};
  93. }
  94. void AsyncFunctionDriverWrapper::continue_async_execution(VM& vm, Value value, bool is_successful, IsInitialExecution is_initial_execution)
  95. {
  96. auto generator_result = is_successful
  97. ? m_generator_object->resume(vm, value, {})
  98. : m_generator_object->resume_abrupt(vm, throw_completion(value), {});
  99. auto result = [&, this]() -> ThrowCompletionOr<void> {
  100. while (true) {
  101. if (generator_result.is_throw_completion())
  102. return generator_result.throw_completion();
  103. auto result = generator_result.release_value();
  104. VERIFY(result.is_object());
  105. auto promise_value = TRY(result.get(vm, vm.names.value));
  106. if (TRY(result.get(vm, vm.names.done)).to_boolean()) {
  107. // We should not execute anymore, so we are safe to allow ourselves to be GC'd.
  108. m_self_handle = {};
  109. // When returning a promise, we need to unwrap it.
  110. if (promise_value.is_object() && is<Promise>(promise_value.as_object())) {
  111. auto& returned_promise = static_cast<Promise&>(promise_value.as_object());
  112. if (returned_promise.state() == Promise::State::Fulfilled) {
  113. m_top_level_promise->fulfill(returned_promise.result());
  114. return {};
  115. }
  116. if (returned_promise.state() == Promise::State::Rejected)
  117. return throw_completion(returned_promise.result());
  118. // The promise is still pending but there's nothing more to do here.
  119. return {};
  120. }
  121. // We hit a `return value;`
  122. m_top_level_promise->fulfill(promise_value);
  123. return {};
  124. }
  125. // We hit `await Promise`
  126. auto await_result = this->await(promise_value);
  127. if (await_result.is_throw_completion()) {
  128. generator_result = m_generator_object->resume_abrupt(vm, await_result.release_error(), {});
  129. continue;
  130. }
  131. return {};
  132. }
  133. }();
  134. if (result.is_throw_completion()) {
  135. m_top_level_promise->reject(result.throw_completion().value().value_or(js_undefined()));
  136. // We should not execute anymore, so we are safe to allow our selfs to be GC'd
  137. m_self_handle = {};
  138. }
  139. // For the initial execution, the execution context will be popped for us later on by ECMAScriptFunctionObject.
  140. if (is_initial_execution == IsInitialExecution::No)
  141. vm.pop_execution_context();
  142. }
  143. void AsyncFunctionDriverWrapper::visit_edges(Cell::Visitor& visitor)
  144. {
  145. Base::visit_edges(visitor);
  146. visitor.visit(m_generator_object);
  147. visitor.visit(m_top_level_promise);
  148. if (m_current_promise)
  149. visitor.visit(m_current_promise);
  150. if (m_suspended_execution_context.has_value())
  151. m_suspended_execution_context->visit_edges(visitor);
  152. }
  153. }