Promise.cpp 18 KB

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