AsyncFunctionDriverWrapper.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. GC_DEFINE_ALLOCATOR(AsyncFunctionDriverWrapper);
  16. GC::Ref<Promise> AsyncFunctionDriverWrapper::create(Realm& realm, GeneratorObject* generator_object)
  17. {
  18. auto top_level_promise = Promise::create(realm);
  19. // Note: The top_level_promise is also kept alive by this Wrapper
  20. auto wrapper = realm.create<AsyncFunctionDriverWrapper>(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, GC::Ref<GeneratorObject> generator_object, GC::Ref<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. {
  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. if (!m_suspended_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, {}));
  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, {}));
  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. // When returning a promise, we need to unwrap it.
  109. if (promise_value.is_object() && is<Promise>(promise_value.as_object())) {
  110. auto& returned_promise = static_cast<Promise&>(promise_value.as_object());
  111. if (returned_promise.state() == Promise::State::Fulfilled) {
  112. m_top_level_promise->fulfill(returned_promise.result());
  113. return {};
  114. }
  115. if (returned_promise.state() == Promise::State::Rejected)
  116. return throw_completion(returned_promise.result());
  117. // The promise is still pending but there's nothing more to do here.
  118. return {};
  119. }
  120. // We hit a `return value;`
  121. m_top_level_promise->fulfill(promise_value);
  122. return {};
  123. }
  124. // We hit `await Promise`
  125. auto await_result = this->await(promise_value);
  126. if (await_result.is_throw_completion()) {
  127. generator_result = m_generator_object->resume_abrupt(vm, await_result.release_error(), {});
  128. continue;
  129. }
  130. return {};
  131. }
  132. }();
  133. if (result.is_throw_completion()) {
  134. m_top_level_promise->reject(result.throw_completion().value().value_or(js_undefined()));
  135. }
  136. // For the initial execution, the execution context will be popped for us later on by ECMAScriptFunctionObject.
  137. if (is_initial_execution == IsInitialExecution::No)
  138. vm.pop_execution_context();
  139. }
  140. void AsyncFunctionDriverWrapper::visit_edges(Cell::Visitor& visitor)
  141. {
  142. Base::visit_edges(visitor);
  143. visitor.visit(m_generator_object);
  144. visitor.visit(m_top_level_promise);
  145. if (m_current_promise)
  146. visitor.visit(m_current_promise);
  147. if (m_suspended_execution_context)
  148. m_suspended_execution_context->visit_edges(visitor);
  149. }
  150. }