AsyncFunctionDriverWrapper.cpp 8.4 KB

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