Promise.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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, JS::GCPtr<ReactionSteps> on_fulfilled_callback, JS::GCPtr<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
  84. ? TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return on_fulfilled_callback->function()(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
  97. ? TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return on_rejected_callback->function()(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, JS::NonnullGCPtr<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. // 1. Perform steps with v.
  121. steps,
  122. {});
  123. }
  124. // https://webidl.spec.whatwg.org/#upon-rejection
  125. JS::NonnullGCPtr<JS::Promise> upon_rejection(Promise const& promise, JS::NonnullGCPtr<ReactionSteps> steps)
  126. {
  127. // 1. Return the result of reacting to promise:
  128. return react_to_promise(promise, {},
  129. // - If promise was rejected with reason r, then:
  130. // 1. Perform steps with r.
  131. steps);
  132. }
  133. // https://webidl.spec.whatwg.org/#mark-a-promise-as-handled
  134. void mark_promise_as_handled(Promise const& promise)
  135. {
  136. // To mark as handled a Promise<T> promise, set promise.[[Promise]].[[PromiseIsHandled]] to true.
  137. auto promise_object = verify_cast<JS::Promise>(promise.promise().ptr());
  138. promise_object->set_is_handled();
  139. }
  140. struct WaitForAllResults : JS::Cell {
  141. JS_CELL(WaitForAllResults, JS::Cell);
  142. JS_DECLARE_ALLOCATOR(WaitForAllResults);
  143. WaitForAllResults(JS::NonnullGCPtr<JS::HeapFunction<void(Vector<JS::Value> const&)>> s, size_t t)
  144. : success_steps(s)
  145. , total(t)
  146. {
  147. // 8. Let result be a list containing total null values.
  148. result.ensure_capacity(total);
  149. for (size_t i = 0; i < total; ++i)
  150. result.unchecked_append(JS::js_null());
  151. }
  152. virtual void visit_edges(JS::Cell::Visitor& visitor) override
  153. {
  154. Base::visit_edges(visitor);
  155. visitor.visit(success_steps);
  156. visitor.visit(result);
  157. }
  158. JS::NonnullGCPtr<JS::HeapFunction<void(Vector<JS::Value> const&)>> success_steps;
  159. Vector<JS::Value> result;
  160. size_t total = 0;
  161. size_t fulfilled_count = 0;
  162. };
  163. JS_DEFINE_ALLOCATOR(WaitForAllResults);
  164. // https://webidl.spec.whatwg.org/#wait-for-all
  165. 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)
  166. {
  167. // FIXME: Fix spec typo, fullfilled --> fulfilled
  168. // 1. Let fullfilledCount be 0.
  169. // Handled later in WaitForAllResults
  170. // 2. Let rejected be false.
  171. auto rejected = false;
  172. // 3. Let rejectionHandlerSteps be the following steps given arg:
  173. auto rejection_handler_steps = [rejected, failure_steps = JS::create_heap_function(realm.heap(), move(failure_steps))](JS::VM& vm) mutable -> JS::ThrowCompletionOr<JS::Value> {
  174. // 1. If rejected is true, abort these steps.
  175. if (rejected)
  176. return JS::js_undefined();
  177. // 2. Set rejected to true.
  178. rejected = true;
  179. // 3. Perform failureSteps given arg.
  180. failure_steps->function()(vm.argument(0));
  181. return JS::js_undefined();
  182. };
  183. // 4. Let rejectionHandler be CreateBuiltinFunction(rejectionHandlerSteps, « »):
  184. auto rejection_handler = JS::NativeFunction::create(realm, move(rejection_handler_steps), 1, "");
  185. // 5. Let total be promises’s size.
  186. auto total = promises.size();
  187. // 6. If total is 0, then:
  188. if (total == 0) {
  189. // 1. Queue a microtask to perform successSteps given « ».
  190. HTML::queue_a_microtask(nullptr, JS::create_heap_function(realm.heap(), [success_steps = JS::create_heap_function(realm.heap(), move(success_steps))] {
  191. success_steps->function()({});
  192. }));
  193. // 2. Return.
  194. return;
  195. }
  196. // 7. Let index be 0.
  197. auto index = 0;
  198. // 8. Let result be a list containing total null values.
  199. // Handled in WaitForAllResults
  200. auto results = realm.heap().allocate<WaitForAllResults>(realm, JS::create_heap_function(realm.heap(), move(success_steps)), total);
  201. // 9. For each promise of promises:
  202. for (auto const& promise : promises) {
  203. // 1. Let promiseIndex be index.
  204. auto promise_index = index;
  205. // FIXME: This should be fulfillmentHandlerSteps
  206. // 2. Let fulfillmentHandler be the following steps given arg:
  207. auto fulfillment_handler_steps = [results, promise_index](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  208. auto arg = vm.argument(0);
  209. // 1. Set result[promiseIndex] to arg.
  210. results->result[promise_index] = arg;
  211. // 2. Set fullfilledCount to fullfilledCount + 1.
  212. ++results->fulfilled_count;
  213. // 3. If fullfilledCount equals total, then perform successSteps given result.
  214. if (results->fulfilled_count == results->total)
  215. results->success_steps->function()(results->result);
  216. return JS::js_undefined();
  217. };
  218. // 3. Let fulfillmentHandler be CreateBuiltinFunction(fulfillmentHandler, « »):
  219. auto fulfillment_handler = JS::NativeFunction::create(realm, move(fulfillment_handler_steps), 1, "");
  220. // 4. Perform PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler).
  221. static_cast<JS::Promise&>(*promise->promise()).perform_then(fulfillment_handler, rejection_handler, nullptr);
  222. // 5. Set index to index + 1.
  223. ++index;
  224. }
  225. }
  226. JS::NonnullGCPtr<JS::Promise> create_rejected_promise_from_exception(JS::Realm& realm, Exception exception)
  227. {
  228. auto throw_completion = Bindings::dom_exception_to_throw_completion(realm.vm(), move(exception));
  229. auto promise_capability = WebIDL::create_rejected_promise(realm, *throw_completion.value());
  230. return JS::NonnullGCPtr { verify_cast<JS::Promise>(*promise_capability->promise().ptr()) };
  231. }
  232. }