Promise.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Function.h>
  8. #include <AK/Optional.h>
  9. #include <AK/TypeCasts.h>
  10. #include <LibJS/Runtime/Error.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/JobCallback.h>
  13. #include <LibJS/Runtime/Promise.h>
  14. #include <LibJS/Runtime/PromiseCapability.h>
  15. #include <LibJS/Runtime/PromiseJobs.h>
  16. #include <LibJS/Runtime/PromiseReaction.h>
  17. #include <LibJS/Runtime/PromiseResolvingFunction.h>
  18. namespace JS {
  19. // 27.2.4.7.1 PromiseResolve ( C, x ), https://tc39.es/ecma262/#sec-promise-resolve
  20. ThrowCompletionOr<Object*> promise_resolve(VM& vm, Object& constructor, Value value)
  21. {
  22. // 1. If IsPromise(x) is true, then
  23. if (value.is_object() && is<Promise>(value.as_object())) {
  24. // a. Let xConstructor be ? Get(x, "constructor").
  25. auto value_constructor = TRY(value.as_object().get(vm.names.constructor));
  26. // b. If SameValue(xConstructor, C) is true, return x.
  27. if (same_value(value_constructor, &constructor))
  28. return &static_cast<Promise&>(value.as_object());
  29. }
  30. // 2. Let promiseCapability be ? NewPromiseCapability(C).
  31. auto promise_capability = TRY(new_promise_capability(vm, &constructor));
  32. // 3. Perform ? Call(promiseCapability.[[Resolve]], undefined, « x »).
  33. (void)TRY(call(vm, *promise_capability->resolve(), js_undefined(), value));
  34. // 4. Return promiseCapability.[[Promise]].
  35. return promise_capability->promise().ptr();
  36. }
  37. NonnullGCPtr<Promise> Promise::create(Realm& realm)
  38. {
  39. return *realm.heap().allocate<Promise>(realm, *realm.intrinsics().promise_prototype());
  40. }
  41. // 27.2 Promise Objects, https://tc39.es/ecma262/#sec-promise-objects
  42. Promise::Promise(Object& prototype)
  43. : Object(prototype)
  44. {
  45. }
  46. // 27.2.1.3 CreateResolvingFunctions ( promise ), https://tc39.es/ecma262/#sec-createresolvingfunctions
  47. Promise::ResolvingFunctions Promise::create_resolving_functions()
  48. {
  49. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / create_resolving_functions()]", this);
  50. auto& vm = this->vm();
  51. auto& realm = *vm.current_realm();
  52. // 1. Let alreadyResolved be the Record { [[Value]]: false }.
  53. auto* already_resolved = vm.heap().allocate_without_realm<AlreadyResolved>();
  54. // 2. Let stepsResolve be the algorithm steps defined in Promise Resolve Functions.
  55. // 3. Let lengthResolve be the number of non-optional parameters of the function definition in Promise Resolve Functions.
  56. // 4. Let resolve be CreateBuiltinFunction(stepsResolve, lengthResolve, "", « [[Promise]], [[AlreadyResolved]] »).
  57. // 5. Set resolve.[[Promise]] to promise.
  58. // 6. Set resolve.[[AlreadyResolved]] to alreadyResolved.
  59. // 27.2.1.3.2 Promise Resolve Functions, https://tc39.es/ecma262/#sec-promise-resolve-functions
  60. auto* resolve_function = PromiseResolvingFunction::create(realm, *this, *already_resolved, [](auto& vm, auto& promise, auto& already_resolved) {
  61. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolve function was called", &promise);
  62. auto& realm = *vm.current_realm();
  63. auto resolution = vm.argument(0);
  64. // 1. Let F be the active function object.
  65. // 2. Assert: F has a [[Promise]] internal slot whose value is an Object.
  66. // 3. Let promise be F.[[Promise]].
  67. // 4. Let alreadyResolved be F.[[AlreadyResolved]].
  68. // 5. If alreadyResolved.[[Value]] is true, return undefined.
  69. if (already_resolved.value) {
  70. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise is already resolved, returning undefined", &promise);
  71. return js_undefined();
  72. }
  73. // 6. Set alreadyResolved.[[Value]] to true.
  74. already_resolved.value = true;
  75. // 7. If SameValue(resolution, promise) is true, then
  76. if (resolution.is_object() && &resolution.as_object() == &promise) {
  77. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise can't be resolved with itself, rejecting with error", &promise);
  78. // a. Let selfResolutionError be a newly created TypeError object.
  79. auto self_resolution_error = TypeError::create(realm, "Cannot resolve promise with itself");
  80. // b. Perform RejectPromise(promise, selfResolutionError).
  81. promise.reject(self_resolution_error);
  82. // c. Return undefined.
  83. return js_undefined();
  84. }
  85. // 8. If Type(resolution) is not Object, then
  86. if (!resolution.is_object()) {
  87. // a. Perform FulfillPromise(promise, resolution).
  88. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolution is not an object, fulfilling with {}", &promise, resolution);
  89. promise.fulfill(resolution);
  90. // b. Return undefined.
  91. return js_undefined();
  92. }
  93. // 9. Let then be Completion(Get(resolution, "then")).
  94. auto then = resolution.as_object().get(vm.names.then);
  95. // 10. If then is an abrupt completion, then
  96. if (then.is_throw_completion()) {
  97. // a. Perform RejectPromise(promise, then.[[Value]]).
  98. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Exception while getting 'then' property, rejecting with error", &promise);
  99. promise.reject(*then.throw_completion().value());
  100. // b. Return undefined.
  101. return js_undefined();
  102. }
  103. // 11. Let thenAction be then.[[Value]].
  104. auto then_action = then.release_value();
  105. // 12. If IsCallable(thenAction) is false, then
  106. if (!then_action.is_function()) {
  107. // a. Perform FulfillPromise(promise, resolution).
  108. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Then action is not a function, fulfilling with {}", &promise, resolution);
  109. promise.fulfill(resolution);
  110. // b. Return undefined.
  111. return js_undefined();
  112. }
  113. // 13. Let thenJobCallback be HostMakeJobCallback(thenAction).
  114. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating JobCallback for then action @ {}", &promise, &then_action.as_function());
  115. auto then_job_callback = vm.host_make_job_callback(then_action.as_function());
  116. // 14. Let job be NewPromiseResolveThenableJob(promise, resolution, thenJobCallback).
  117. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating PromiseJob for thenable {}", &promise, resolution);
  118. auto job = create_promise_resolve_thenable_job(vm, promise, resolution, move(then_job_callback));
  119. // 15. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
  120. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Enqueuing job @ {} in realm {}", &promise, &job.job, job.realm);
  121. vm.host_enqueue_promise_job(move(job.job), job.realm);
  122. // 16. Return undefined.
  123. return js_undefined();
  124. });
  125. resolve_function->define_direct_property(vm.names.name, PrimitiveString::create(vm, DeprecatedString::empty()), Attribute::Configurable);
  126. // 7. Let stepsReject be the algorithm steps defined in Promise Reject Functions.
  127. // 8. Let lengthReject be the number of non-optional parameters of the function definition in Promise Reject Functions.
  128. // 9. Let reject be CreateBuiltinFunction(stepsReject, lengthReject, "", « [[Promise]], [[AlreadyResolved]] »).
  129. // 10. Set reject.[[Promise]] to promise.
  130. // 11. Set reject.[[AlreadyResolved]] to alreadyResolved.
  131. // 27.2.1.3.1 Promise Reject Functions, https://tc39.es/ecma262/#sec-promise-reject-functions
  132. auto* reject_function = PromiseResolvingFunction::create(realm, *this, *already_resolved, [](auto& vm, auto& promise, auto& already_resolved) {
  133. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Reject function was called", &promise);
  134. auto reason = vm.argument(0);
  135. // 1. Let F be the active function object.
  136. // 2. Assert: F has a [[Promise]] internal slot whose value is an Object.
  137. // 3. Let promise be F.[[Promise]].
  138. // 4. Let alreadyResolved be F.[[AlreadyResolved]].
  139. // 5. If alreadyResolved.[[Value]] is true, return undefined.
  140. if (already_resolved.value)
  141. return js_undefined();
  142. // 6. Set alreadyResolved.[[Value]] to true.
  143. already_resolved.value = true;
  144. // 7. Perform RejectPromise(promise, reason).
  145. promise.reject(reason);
  146. // 8. Return undefined.
  147. return js_undefined();
  148. });
  149. reject_function->define_direct_property(vm.names.name, PrimitiveString::create(vm, DeprecatedString::empty()), Attribute::Configurable);
  150. // 12. Return the Record { [[Resolve]]: resolve, [[Reject]]: reject }.
  151. return { *resolve_function, *reject_function };
  152. }
  153. // 27.2.1.4 FulfillPromise ( promise, value ), https://tc39.es/ecma262/#sec-fulfillpromise
  154. void Promise::fulfill(Value value)
  155. {
  156. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / fulfill()]: Fulfilling promise with value {}", this, value);
  157. // 1. Assert: The value of promise.[[PromiseState]] is pending.
  158. VERIFY(m_state == State::Pending);
  159. VERIFY(!value.is_empty());
  160. // 2. Let reactions be promise.[[PromiseFulfillReactions]].
  161. // NOTE: This is a noop, we do these steps in a slightly different order.
  162. // 3. Set promise.[[PromiseResult]] to value.
  163. m_result = value;
  164. // 4. Set promise.[[PromiseFulfillReactions]] to undefined.
  165. // 5. Set promise.[[PromiseRejectReactions]] to undefined.
  166. // 6. Set promise.[[PromiseState]] to fulfilled.
  167. m_state = State::Fulfilled;
  168. // 7. Perform TriggerPromiseReactions(reactions, value).
  169. trigger_reactions();
  170. m_fulfill_reactions.clear();
  171. m_reject_reactions.clear();
  172. // 8. Return unused.
  173. }
  174. // 27.2.1.7 RejectPromise ( promise, reason ), https://tc39.es/ecma262/#sec-rejectpromise
  175. void Promise::reject(Value reason)
  176. {
  177. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / reject()]: Rejecting promise with reason {}", this, reason);
  178. auto& vm = this->vm();
  179. // 1. Assert: The value of promise.[[PromiseState]] is pending.
  180. VERIFY(m_state == State::Pending);
  181. VERIFY(!reason.is_empty());
  182. // 2. Let reactions be promise.[[PromiseRejectReactions]].
  183. // NOTE: This is a noop, we do these steps in a slightly different order.
  184. // 3. Set promise.[[PromiseResult]] to reason.
  185. m_result = reason;
  186. // 4. Set promise.[[PromiseFulfillReactions]] to undefined.
  187. // 5. Set promise.[[PromiseRejectReactions]] to undefined.
  188. // 6. Set promise.[[PromiseState]] to rejected.
  189. m_state = State::Rejected;
  190. // 7. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "reject").
  191. if (!m_is_handled)
  192. vm.host_promise_rejection_tracker(*this, RejectionOperation::Reject);
  193. // 8. Perform TriggerPromiseReactions(reactions, reason).
  194. trigger_reactions();
  195. m_fulfill_reactions.clear();
  196. m_reject_reactions.clear();
  197. // 9. Return unused.
  198. }
  199. // 27.2.1.8 TriggerPromiseReactions ( reactions, argument ), https://tc39.es/ecma262/#sec-triggerpromisereactions
  200. void Promise::trigger_reactions() const
  201. {
  202. VERIFY(is_settled());
  203. auto& vm = this->vm();
  204. auto& reactions = m_state == State::Fulfilled
  205. ? m_fulfill_reactions
  206. : m_reject_reactions;
  207. // 1. For each element reaction of reactions, do
  208. for (auto& reaction : reactions) {
  209. // a. Let job be NewPromiseReactionJob(reaction, argument).
  210. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Creating PromiseJob for PromiseReaction @ {} with argument {}", this, &reaction, m_result);
  211. auto [job, realm] = create_promise_reaction_job(vm, *reaction, m_result);
  212. // b. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
  213. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Enqueuing job @ {} in realm {}", this, &job, realm);
  214. vm.host_enqueue_promise_job(move(job), realm);
  215. }
  216. if constexpr (PROMISE_DEBUG) {
  217. if (reactions.is_empty())
  218. dbgln("[Promise @ {} / trigger_reactions()]: No reactions!", this);
  219. }
  220. // 2. Return unused.
  221. }
  222. // 27.2.5.4.1 PerformPromiseThen ( promise, onFulfilled, onRejected [ , resultCapability ] ), https://tc39.es/ecma262/#sec-performpromisethen
  223. Value Promise::perform_then(Value on_fulfilled, Value on_rejected, GCPtr<PromiseCapability> result_capability)
  224. {
  225. auto& vm = this->vm();
  226. // 1. Assert: IsPromise(promise) is true.
  227. // 2. If resultCapability is not present, then
  228. // a. Set resultCapability to undefined.
  229. // 3. If IsCallable(onFulfilled) is false, then
  230. // a. Let onFulfilledJobCallback be empty.
  231. Optional<JobCallback> on_fulfilled_job_callback;
  232. // 4. Else,
  233. if (on_fulfilled.is_function()) {
  234. // a. Let onFulfilledJobCallback be HostMakeJobCallback(onFulfilled).
  235. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_fulfilled function @ {}", this, &on_fulfilled.as_function());
  236. on_fulfilled_job_callback = vm.host_make_job_callback(on_fulfilled.as_function());
  237. }
  238. // 5. If IsCallable(onRejected) is false, then
  239. // a. Let onRejectedJobCallback be empty.
  240. Optional<JobCallback> on_rejected_job_callback;
  241. // 6. Else,
  242. if (on_rejected.is_function()) {
  243. // a. Let onRejectedJobCallback be HostMakeJobCallback(onRejected).
  244. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_rejected function @ {}", this, &on_rejected.as_function());
  245. on_rejected_job_callback = vm.host_make_job_callback(on_rejected.as_function());
  246. }
  247. // 7. Let fulfillReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: Fulfill, [[Handler]]: onFulfilledJobCallback }.
  248. auto* fulfill_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Fulfill, result_capability, move(on_fulfilled_job_callback));
  249. // 8. Let rejectReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: Reject, [[Handler]]: onRejectedJobCallback }.
  250. auto* reject_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Reject, result_capability, move(on_rejected_job_callback));
  251. switch (m_state) {
  252. // 9. If promise.[[PromiseState]] is pending, then
  253. case Promise::State::Pending:
  254. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: state is State::Pending, adding fulfill/reject reactions", this);
  255. // a. Append fulfillReaction as the last element of the List that is promise.[[PromiseFulfillReactions]].
  256. m_fulfill_reactions.append(fulfill_reaction);
  257. // b. Append rejectReaction as the last element of the List that is promise.[[PromiseRejectReactions]].
  258. m_reject_reactions.append(reject_reaction);
  259. break;
  260. // 10. Else if promise.[[PromiseState]] is fulfilled, then
  261. case Promise::State::Fulfilled: {
  262. // a. Let value be promise.[[PromiseResult]].
  263. auto value = m_result;
  264. // b. Let fulfillJob be NewPromiseReactionJob(fulfillReaction, value).
  265. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Fulfilled, creating PromiseJob for PromiseReaction @ {} with argument {}", this, fulfill_reaction, value);
  266. auto [fulfill_job, realm] = create_promise_reaction_job(vm, *fulfill_reaction, value);
  267. // c. Perform HostEnqueuePromiseJob(fulfillJob.[[Job]], fulfillJob.[[Realm]]).
  268. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {} in realm {}", this, &fulfill_job, realm);
  269. vm.host_enqueue_promise_job(move(fulfill_job), realm);
  270. break;
  271. }
  272. // 11. Else,
  273. case Promise::State::Rejected: {
  274. // a. Assert: The value of promise.[[PromiseState]] is rejected.
  275. // b. Let reason be promise.[[PromiseResult]].
  276. auto reason = m_result;
  277. // c. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "handle").
  278. if (!m_is_handled)
  279. vm.host_promise_rejection_tracker(*this, RejectionOperation::Handle);
  280. // d. Let rejectJob be NewPromiseReactionJob(rejectReaction, reason).
  281. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Rejected, creating PromiseJob for PromiseReaction @ {} with argument {}", this, reject_reaction, reason);
  282. auto [reject_job, realm] = create_promise_reaction_job(vm, *reject_reaction, reason);
  283. // e. Perform HostEnqueuePromiseJob(rejectJob.[[Job]], rejectJob.[[Realm]]).
  284. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {} in realm {}", this, &reject_job, realm);
  285. vm.host_enqueue_promise_job(move(reject_job), realm);
  286. break;
  287. }
  288. default:
  289. VERIFY_NOT_REACHED();
  290. }
  291. // 12. Set promise.[[PromiseIsHandled]] to true.
  292. m_is_handled = true;
  293. // 13. If resultCapability is undefined, then
  294. if (result_capability == nullptr) {
  295. // a. Return undefined.
  296. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: No result PromiseCapability, returning undefined", this);
  297. return js_undefined();
  298. }
  299. // 14. Else,
  300. // a. Return resultCapability.[[Promise]].
  301. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Returning Promise @ {} from result PromiseCapability @ {}", this, result_capability->promise().ptr(), result_capability.ptr());
  302. return result_capability->promise();
  303. }
  304. void Promise::visit_edges(Cell::Visitor& visitor)
  305. {
  306. Base::visit_edges(visitor);
  307. visitor.visit(m_result);
  308. for (auto& reaction : m_fulfill_reactions)
  309. visitor.visit(reaction);
  310. for (auto& reaction : m_reject_reactions)
  311. visitor.visit(reaction);
  312. }
  313. }