Promise.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Function.h>
  7. #include <AK/TypeCasts.h>
  8. #include <LibGC/Function.h>
  9. #include <LibJS/Runtime/PromiseCapability.h>
  10. #include <LibJS/Runtime/PromiseConstructor.h>
  11. #include <LibJS/Runtime/Realm.h>
  12. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  13. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  14. #include <LibWeb/WebIDL/Promise.h>
  15. namespace Web::WebIDL {
  16. // https://webidl.spec.whatwg.org/#a-new-promise
  17. GC::Ref<Promise> create_promise(JS::Realm& realm)
  18. {
  19. auto& vm = realm.vm();
  20. // 1. Let constructor be realm.[[Intrinsics]].[[%Promise%]].
  21. auto constructor = realm.intrinsics().promise_constructor();
  22. // Return ? NewPromiseCapability(constructor).
  23. // NOTE: When called with %Promise%, NewPromiseCapability can't throw.
  24. return MUST(JS::new_promise_capability(vm, constructor));
  25. }
  26. // https://webidl.spec.whatwg.org/#a-promise-resolved-with
  27. GC::Ref<Promise> create_resolved_promise(JS::Realm& realm, JS::Value value)
  28. {
  29. auto& vm = realm.vm();
  30. // 1. Let value be the result of converting x to an ECMAScript value.
  31. // 2. Let constructor be realm.[[Intrinsics]].[[%Promise%]].
  32. auto constructor = realm.intrinsics().promise_constructor();
  33. // 3. Let promiseCapability be ? NewPromiseCapability(constructor).
  34. // NOTE: When called with %Promise%, NewPromiseCapability can't throw.
  35. auto promise_capability = MUST(JS::new_promise_capability(vm, constructor));
  36. // 4. Perform ! Call(promiseCapability.[[Resolve]], undefined, « value »).
  37. MUST(JS::call(vm, *promise_capability->resolve(), JS::js_undefined(), value));
  38. // 5. Return promiseCapability.
  39. return promise_capability;
  40. }
  41. // https://webidl.spec.whatwg.org/#a-promise-rejected-with
  42. GC::Ref<Promise> create_rejected_promise(JS::Realm& realm, JS::Value reason)
  43. {
  44. auto& vm = realm.vm();
  45. // 1. Let constructor be realm.[[Intrinsics]].[[%Promise%]].
  46. auto constructor = realm.intrinsics().promise_constructor();
  47. // 2. Let promiseCapability be ? NewPromiseCapability(constructor).
  48. // NOTE: When called with %Promise%, NewPromiseCapability can't throw.
  49. auto promise_capability = MUST(JS::new_promise_capability(vm, constructor));
  50. // 3. Perform ! Call(promiseCapability.[[Reject]], undefined, « r »).
  51. MUST(JS::call(vm, *promise_capability->reject(), JS::js_undefined(), reason));
  52. // 4. Return promiseCapability.
  53. return promise_capability;
  54. }
  55. // https://webidl.spec.whatwg.org/#resolve
  56. void resolve_promise(JS::Realm& realm, Promise const& promise, JS::Value value)
  57. {
  58. auto& vm = realm.vm();
  59. // 1. If x is not given, then let it be the undefined value.
  60. // NOTE: This is done via the default argument.
  61. // 2. Let value be the result of converting x to an ECMAScript value.
  62. // 3. Perform ! Call(p.[[Resolve]], undefined, « value »).
  63. MUST(JS::call(vm, *promise.resolve(), JS::js_undefined(), value));
  64. }
  65. // https://webidl.spec.whatwg.org/#reject
  66. void reject_promise(JS::Realm& realm, Promise const& promise, JS::Value reason)
  67. {
  68. auto& vm = realm.vm();
  69. // 1. Perform ! Call(p.[[Reject]], undefined, « r »).
  70. MUST(JS::call(vm, *promise.reject(), JS::js_undefined(), reason));
  71. }
  72. // https://webidl.spec.whatwg.org/#dfn-perform-steps-once-promise-is-settled
  73. GC::Ref<Promise> react_to_promise(Promise const& promise, GC::Ptr<ReactionSteps> on_fulfilled_callback, GC::Ptr<ReactionSteps> on_rejected_callback)
  74. {
  75. auto& realm = promise.promise()->shape().realm();
  76. auto& vm = realm.vm();
  77. // 1. Let onFulfilledSteps be the following steps given argument V:
  78. auto on_fulfilled_steps = [on_fulfilled_callback = move(on_fulfilled_callback)](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  79. // 1. Let value be the result of converting V to an IDL value of type T.
  80. auto value = vm.argument(0);
  81. // 2. If there is a set of steps to be run if the promise was fulfilled, then let result be the result of performing them, given value if T is not undefined. Otherwise, let result be value.
  82. auto result = on_fulfilled_callback
  83. ? TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return on_fulfilled_callback->function()(value); }))
  84. : value;
  85. // 3. Return result, converted to an ECMAScript value.
  86. return result;
  87. };
  88. // 2. Let onFulfilled be CreateBuiltinFunction(onFulfilledSteps, « »):
  89. auto on_fulfilled = JS::NativeFunction::create(realm, move(on_fulfilled_steps), 1, "");
  90. // 3. Let onRejectedSteps be the following steps given argument R:
  91. auto on_rejected_steps = [&realm, on_rejected_callback = move(on_rejected_callback)](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  92. // 1. Let reason be the result of converting R to an IDL value of type any.
  93. auto reason = vm.argument(0);
  94. // 2. If there is a set of steps to be run if the promise was rejected, then let result be the result of performing them, given reason. Otherwise, let result be a promise rejected with reason.
  95. auto result = on_rejected_callback
  96. ? TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return on_rejected_callback->function()(reason); }))
  97. : WebIDL::create_rejected_promise(realm, reason)->promise();
  98. // 3. Return result, converted to an ECMAScript value.
  99. return result;
  100. };
  101. // 4. Let onRejected be CreateBuiltinFunction(onRejectedSteps, « »):
  102. auto on_rejected = JS::NativeFunction::create(realm, move(on_rejected_steps), 1, "");
  103. // 5. Let constructor be promise.[[Promise]].[[Realm]].[[Intrinsics]].[[%Promise%]].
  104. auto constructor = realm.intrinsics().promise_constructor();
  105. // 6. Let newCapability be ? NewPromiseCapability(constructor).
  106. // NOTE: When called with %Promise%, NewPromiseCapability can't throw.
  107. auto new_capability = MUST(JS::new_promise_capability(vm, constructor));
  108. // 7. Return PerformPromiseThen(promise.[[Promise]], onFulfilled, onRejected, newCapability).
  109. // FIXME: https://github.com/whatwg/webidl/issues/1443
  110. // Returning newCapability instead of newCapability.[[Promise].
  111. auto promise_object = verify_cast<JS::Promise>(promise.promise().ptr());
  112. auto value = promise_object->perform_then(on_fulfilled, on_rejected, new_capability);
  113. VERIFY(value == new_capability->promise());
  114. return new_capability;
  115. }
  116. // https://webidl.spec.whatwg.org/#upon-fulfillment
  117. GC::Ref<Promise> upon_fulfillment(Promise const& promise, GC::Ref<ReactionSteps> steps)
  118. {
  119. // 1. Return the result of reacting to promise:
  120. return react_to_promise(promise,
  121. // - If promise was fulfilled with value v, then:
  122. // 1. Perform steps with v.
  123. steps,
  124. {});
  125. }
  126. // https://webidl.spec.whatwg.org/#upon-rejection
  127. GC::Ref<Promise> upon_rejection(Promise const& promise, GC::Ref<ReactionSteps> steps)
  128. {
  129. // 1. Return the result of reacting to promise:
  130. return react_to_promise(promise, {},
  131. // - If promise was rejected with reason r, then:
  132. // 1. Perform steps with r.
  133. steps);
  134. }
  135. // https://webidl.spec.whatwg.org/#mark-a-promise-as-handled
  136. void mark_promise_as_handled(Promise const& promise)
  137. {
  138. // To mark as handled a Promise<T> promise, set promise.[[Promise]].[[PromiseIsHandled]] to true.
  139. auto promise_object = verify_cast<JS::Promise>(promise.promise().ptr());
  140. promise_object->set_is_handled();
  141. }
  142. struct WaitForAllResults : JS::Cell {
  143. GC_CELL(WaitForAllResults, JS::Cell);
  144. GC_DECLARE_ALLOCATOR(WaitForAllResults);
  145. WaitForAllResults(GC::Ref<GC::Function<void(Vector<JS::Value> const&)>> s, size_t t)
  146. : success_steps(s)
  147. , total(t)
  148. {
  149. // 8. Let result be a list containing total null values.
  150. result.ensure_capacity(total);
  151. for (size_t i = 0; i < total; ++i)
  152. result.unchecked_append(JS::js_null());
  153. }
  154. virtual void visit_edges(JS::Cell::Visitor& visitor) override
  155. {
  156. Base::visit_edges(visitor);
  157. visitor.visit(success_steps);
  158. visitor.visit(result);
  159. }
  160. GC::Ref<GC::Function<void(Vector<JS::Value> const&)>> success_steps;
  161. Vector<JS::Value> result;
  162. size_t total = 0;
  163. size_t fulfilled_count = 0;
  164. };
  165. GC_DEFINE_ALLOCATOR(WaitForAllResults);
  166. // https://webidl.spec.whatwg.org/#wait-for-all
  167. void wait_for_all(JS::Realm& realm, Vector<GC::Ref<Promise>> const& promises, Function<void(Vector<JS::Value> const&)> success_steps, Function<void(JS::Value)> failure_steps)
  168. {
  169. // FIXME: Fix spec typo, fullfilled --> fulfilled
  170. // 1. Let fullfilledCount be 0.
  171. // Handled later in WaitForAllResults
  172. // 2. Let rejected be false.
  173. auto rejected = false;
  174. // 3. Let rejectionHandlerSteps be the following steps given arg:
  175. auto rejection_handler_steps = [rejected, failure_steps = GC::create_function(realm.heap(), move(failure_steps))](JS::VM& vm) mutable -> JS::ThrowCompletionOr<JS::Value> {
  176. // 1. If rejected is true, abort these steps.
  177. if (rejected)
  178. return JS::js_undefined();
  179. // 2. Set rejected to true.
  180. rejected = true;
  181. // 3. Perform failureSteps given arg.
  182. failure_steps->function()(vm.argument(0));
  183. return JS::js_undefined();
  184. };
  185. // 4. Let rejectionHandler be CreateBuiltinFunction(rejectionHandlerSteps, « »):
  186. auto rejection_handler = JS::NativeFunction::create(realm, move(rejection_handler_steps), 1, "");
  187. // 5. Let total be promises’s size.
  188. auto total = promises.size();
  189. // 6. If total is 0, then:
  190. if (total == 0) {
  191. // 1. Queue a microtask to perform successSteps given « ».
  192. HTML::queue_a_microtask(nullptr, GC::create_function(realm.heap(), [success_steps = GC::create_function(realm.heap(), move(success_steps))] {
  193. success_steps->function()({});
  194. }));
  195. // 2. Return.
  196. return;
  197. }
  198. // 7. Let index be 0.
  199. auto index = 0;
  200. // 8. Let result be a list containing total null values.
  201. // Handled in WaitForAllResults
  202. auto results = realm.create<WaitForAllResults>(GC::create_function(realm.heap(), move(success_steps)), total);
  203. // 9. For each promise of promises:
  204. for (auto const& promise : promises) {
  205. // 1. Let promiseIndex be index.
  206. auto promise_index = index;
  207. // FIXME: This should be fulfillmentHandlerSteps
  208. // 2. Let fulfillmentHandler be the following steps given arg:
  209. auto fulfillment_handler_steps = [results, promise_index](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  210. auto arg = vm.argument(0);
  211. // 1. Set result[promiseIndex] to arg.
  212. results->result[promise_index] = arg;
  213. // 2. Set fullfilledCount to fullfilledCount + 1.
  214. ++results->fulfilled_count;
  215. // 3. If fullfilledCount equals total, then perform successSteps given result.
  216. if (results->fulfilled_count == results->total)
  217. results->success_steps->function()(results->result);
  218. return JS::js_undefined();
  219. };
  220. // 3. Let fulfillmentHandler be CreateBuiltinFunction(fulfillmentHandler, « »):
  221. auto fulfillment_handler = JS::NativeFunction::create(realm, move(fulfillment_handler_steps), 1, "");
  222. // 4. Perform PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler).
  223. static_cast<JS::Promise&>(*promise->promise()).perform_then(fulfillment_handler, rejection_handler, nullptr);
  224. // 5. Set index to index + 1.
  225. ++index;
  226. }
  227. }
  228. GC::Ref<Promise> create_rejected_promise_from_exception(JS::Realm& realm, Exception exception)
  229. {
  230. auto throw_completion = Bindings::dom_exception_to_throw_completion(realm.vm(), move(exception));
  231. return WebIDL::create_rejected_promise(realm, *throw_completion.value());
  232. }
  233. }