AsyncFunctionDriverWrapper.cpp 8.4 KB

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