AsyncFunctionDriverWrapper.cpp 8.4 KB

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