AsyncFunctionDriverWrapper.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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/VM.h>
  12. namespace JS {
  13. ThrowCompletionOr<Value> AsyncFunctionDriverWrapper::create(Realm& realm, GeneratorObject* generator_object)
  14. {
  15. auto top_level_promise = Promise::create(realm);
  16. // Note: This generates a handle to itself, which it clears upon completing its execution
  17. // The top_level_promise is also kept alive by this Wrapper
  18. auto wrapper = MUST_OR_THROW_OOM(realm.heap().allocate<AsyncFunctionDriverWrapper>(realm, realm, *generator_object, *top_level_promise));
  19. // Prime the generator:
  20. // This runs until the first `await value;`
  21. wrapper->continue_async_execution(realm.vm(), js_undefined(), true);
  22. return top_level_promise;
  23. }
  24. AsyncFunctionDriverWrapper::AsyncFunctionDriverWrapper(Realm& realm, NonnullGCPtr<GeneratorObject> generator_object, NonnullGCPtr<Promise> top_level_promise)
  25. : Promise(realm.intrinsics().promise_prototype())
  26. , m_generator_object(generator_object)
  27. , m_on_fulfillment(*NativeFunction::create(realm, "async.on_fulfillment"sv, [this](VM& vm) -> ThrowCompletionOr<Value> {
  28. auto arg = vm.argument(0);
  29. if (m_expect_promise) {
  30. continue_async_execution(vm, arg, true);
  31. m_expect_promise = false;
  32. return js_undefined();
  33. }
  34. return arg;
  35. }))
  36. , m_on_rejection(*NativeFunction::create(realm, "async.on_rejection"sv, [this](VM& vm) -> ThrowCompletionOr<Value> {
  37. auto arg = vm.argument(0);
  38. if (m_expect_promise) {
  39. continue_async_execution(vm, arg, false);
  40. m_expect_promise = false;
  41. return js_undefined();
  42. }
  43. return throw_completion(arg);
  44. }))
  45. , m_top_level_promise(top_level_promise)
  46. , m_self_handle(make_handle(*this))
  47. {
  48. }
  49. void AsyncFunctionDriverWrapper::continue_async_execution(VM& vm, Value value, bool is_successful)
  50. {
  51. auto generator_result = is_successful
  52. ? m_generator_object->resume(vm, value, {})
  53. : m_generator_object->resume_abrupt(vm, throw_completion(value), {});
  54. auto result = [&, this]() -> ThrowCompletionOr<void> {
  55. // This loop is for the trivial case of awaiting a non-Promise value,
  56. // and pseudo promises, that are actually resolved in a synchronous manner
  57. // It's either this, a goto, or a needles indirection
  58. while (true) {
  59. if (generator_result.is_throw_completion())
  60. return generator_result.throw_completion();
  61. auto result = generator_result.release_value();
  62. VERIFY(result.is_object());
  63. auto promise_value = TRY(result.get(vm, vm.names.value));
  64. if (TRY(result.get(vm, vm.names.done)).to_boolean()) {
  65. // We should not execute anymore, so we are safe to allow ourselves to be GC'd.
  66. m_self_handle = {};
  67. // When returning a promise, we need to unwrap it.
  68. if (promise_value.is_object() && is<Promise>(promise_value.as_object())) {
  69. auto& returned_promise = static_cast<Promise&>(promise_value.as_object());
  70. if (returned_promise.state() == Promise::State::Fulfilled) {
  71. m_top_level_promise->fulfill(returned_promise.result());
  72. return {};
  73. }
  74. if (returned_promise.state() == Promise::State::Rejected)
  75. return throw_completion(returned_promise.result());
  76. // The promise is still pending but there's nothing more to do here.
  77. return {};
  78. }
  79. // We hit a `return value;`
  80. m_top_level_promise->fulfill(promise_value);
  81. return {};
  82. }
  83. if (!promise_value.is_object() || !is<Promise>(promise_value.as_object())) {
  84. // We hit the trivial case of `await value`, where value is not a
  85. // Promise, so we can just continue the execution
  86. generator_result = m_generator_object->resume(vm, promise_value, {});
  87. continue;
  88. }
  89. // We hit `await Promise`
  90. m_current_promise = static_cast<Promise*>(&promise_value.as_object());
  91. // FIXME: We need to be a bit explicit here,
  92. // because for non async promises we arrive late to register us as handlers,
  93. // so we need to just pretend we are early and do the main logic ourselves,
  94. // Boon: This allows us to short-circuit to immediately continuing the execution
  95. // FIXME: This then causes a warning to be printed to the console, that we supposedly did not handle the promise
  96. if (m_current_promise->state() == Promise::State::Fulfilled) {
  97. generator_result = m_generator_object->resume(vm, m_current_promise->result(), {});
  98. continue;
  99. }
  100. if (m_current_promise->state() == Promise::State::Rejected) {
  101. generator_result = m_generator_object->resume_abrupt(vm, throw_completion(m_current_promise->result()), {});
  102. continue;
  103. }
  104. // Due to the nature of promise capabilities we might get called on either one path,
  105. // so we use a flag to make sure only accept one call
  106. // FIXME: There might be a cleaner way to accomplish this
  107. m_expect_promise = true;
  108. auto promise_capability = PromiseCapability::create(vm, *m_current_promise,
  109. m_on_fulfillment,
  110. m_on_rejection);
  111. m_current_promise->perform_then(
  112. m_on_fulfillment,
  113. m_on_rejection,
  114. promise_capability);
  115. return {};
  116. }
  117. }();
  118. if (result.is_throw_completion()) {
  119. m_top_level_promise->reject(result.throw_completion().value().value_or(js_undefined()));
  120. // We should not execute anymore, so we are safe to allow our selfs to be GC'd
  121. m_self_handle = {};
  122. }
  123. }
  124. void AsyncFunctionDriverWrapper::visit_edges(Cell::Visitor& visitor)
  125. {
  126. Base::visit_edges(visitor);
  127. visitor.visit(m_generator_object);
  128. visitor.visit(m_on_fulfillment);
  129. visitor.visit(m_on_rejection);
  130. visitor.visit(m_top_level_promise);
  131. if (m_current_promise)
  132. visitor.visit(m_current_promise);
  133. }
  134. }