Promise.cpp 12 KB

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