PromiseConstructor.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /*
  2. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Function.h>
  7. #include <LibJS/Interpreter.h>
  8. #include <LibJS/Runtime/AbstractOperations.h>
  9. #include <LibJS/Runtime/AggregateError.h>
  10. #include <LibJS/Runtime/Array.h>
  11. #include <LibJS/Runtime/Error.h>
  12. #include <LibJS/Runtime/FunctionObject.h>
  13. #include <LibJS/Runtime/GlobalObject.h>
  14. #include <LibJS/Runtime/IteratorOperations.h>
  15. #include <LibJS/Runtime/Promise.h>
  16. #include <LibJS/Runtime/PromiseConstructor.h>
  17. #include <LibJS/Runtime/PromiseReaction.h>
  18. #include <LibJS/Runtime/PromiseResolvingElementFunctions.h>
  19. #include <LibJS/Runtime/TemporaryClearException.h>
  20. namespace JS {
  21. // 27.2.4.1.1 GetPromiseResolve ( promiseConstructor ), https://tc39.es/ecma262/#sec-getpromiseresolve
  22. static ThrowCompletionOr<Value> get_promise_resolve(GlobalObject& global_object, Value constructor)
  23. {
  24. VERIFY(constructor.is_constructor());
  25. auto& vm = global_object.vm();
  26. auto promise_resolve = TRY(constructor.get(global_object, vm.names.resolve));
  27. if (!promise_resolve.is_function())
  28. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, promise_resolve.to_string_without_side_effects());
  29. return promise_resolve;
  30. }
  31. // 27.2.1.1.1 IfAbruptRejectPromise ( value, capability ), https://tc39.es/ecma262/#sec-ifabruptrejectpromise
  32. #define TRY_OR_REJECT(vm, capability, expression) \
  33. ({ \
  34. auto _temporary_result = (expression); \
  35. if (_temporary_result.is_error()) { \
  36. vm.clear_exception(); \
  37. vm.stop_unwind(); \
  38. \
  39. (void)vm.call(*capability.reject, js_undefined(), _temporary_result.release_error().value()); \
  40. return capability.promise; \
  41. } \
  42. _temporary_result.release_value(); \
  43. })
  44. static bool iterator_record_is_complete(GlobalObject& global_object, Object& iterator_record)
  45. {
  46. auto& vm = global_object.vm();
  47. // FIXME: Create a native iterator structure with the [[Done]] internal slot. For now, temporarily clear
  48. // the exception so we can access the "done" property on the iterator object.
  49. TemporaryClearException clear_exception(vm);
  50. return MUST(iterator_complete(global_object, iterator_record));
  51. }
  52. static void set_iterator_record_complete(GlobalObject& global_object, Object& iterator_record)
  53. {
  54. auto& vm = global_object.vm();
  55. // FIXME: Create a native iterator structure with the [[Done]] internal slot. For now, temporarily clear
  56. // the exception so we can access the "done" property on the iterator object.
  57. TemporaryClearException clear_exception(vm);
  58. MUST(iterator_record.set(vm.names.done, Value(true), Object::ShouldThrowExceptions::No));
  59. }
  60. using EndOfElementsCallback = Function<ThrowCompletionOr<Value>(PromiseValueList&)>;
  61. using InvokeElementFunctionCallback = Function<void(PromiseValueList&, RemainingElements&, Value, size_t)>;
  62. static Value perform_promise_common(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve, EndOfElementsCallback end_of_list, InvokeElementFunctionCallback invoke_element_function)
  63. {
  64. auto& vm = global_object.vm();
  65. VERIFY(constructor.is_constructor());
  66. VERIFY(promise_resolve.is_function());
  67. auto* values = vm.heap().allocate_without_global_object<PromiseValueList>();
  68. auto* remaining_elements_count = vm.heap().allocate_without_global_object<RemainingElements>(1);
  69. size_t index = 0;
  70. while (true) {
  71. auto next_or_error = iterator_step(global_object, iterator_record);
  72. if (next_or_error.is_throw_completion()) {
  73. set_iterator_record_complete(global_object, iterator_record);
  74. return {};
  75. }
  76. auto* next = next_or_error.release_value();
  77. if (!next) {
  78. set_iterator_record_complete(global_object, iterator_record);
  79. if (vm.exception())
  80. return {};
  81. if (--remaining_elements_count->value == 0)
  82. return TRY_OR_DISCARD(end_of_list(*values));
  83. return result_capability.promise;
  84. }
  85. auto next_value_or_error = iterator_value(global_object, *next);
  86. if (next_value_or_error.is_throw_completion()) {
  87. set_iterator_record_complete(global_object, iterator_record);
  88. return {};
  89. }
  90. auto next_value = next_value_or_error.release_value();
  91. values->values().append(js_undefined());
  92. auto next_promise = TRY_OR_DISCARD(vm.call(promise_resolve.as_function(), constructor, next_value));
  93. ++remaining_elements_count->value;
  94. invoke_element_function(*values, *remaining_elements_count, next_promise, index);
  95. if (vm.exception())
  96. return {};
  97. ++index;
  98. }
  99. }
  100. // 27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseall
  101. static Value perform_promise_all(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
  102. {
  103. auto& vm = global_object.vm();
  104. return perform_promise_common(
  105. global_object, iterator_record, constructor, result_capability, promise_resolve,
  106. [&](PromiseValueList& values) -> ThrowCompletionOr<Value> {
  107. auto values_array = Array::create_from(global_object, values.values());
  108. TRY(vm.call(*result_capability.resolve, js_undefined(), values_array));
  109. return Value(result_capability.promise);
  110. },
  111. [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  112. auto* on_fulfilled = PromiseAllResolveElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
  113. on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  114. (void)next_promise.invoke(global_object, vm.names.then, on_fulfilled, result_capability.reject);
  115. });
  116. }
  117. // 27.2.4.2.1 PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseallsettled
  118. static Value perform_promise_all_settled(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
  119. {
  120. auto& vm = global_object.vm();
  121. return perform_promise_common(
  122. global_object, iterator_record, constructor, result_capability, promise_resolve,
  123. [&](PromiseValueList& values) -> ThrowCompletionOr<Value> {
  124. auto values_array = Array::create_from(global_object, values.values());
  125. TRY(vm.call(*result_capability.resolve, js_undefined(), values_array));
  126. return Value(result_capability.promise);
  127. },
  128. [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  129. auto* on_fulfilled = PromiseAllSettledResolveElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
  130. on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  131. auto* on_rejected = PromiseAllSettledRejectElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
  132. on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  133. (void)next_promise.invoke(global_object, vm.names.then, on_fulfilled, on_rejected);
  134. });
  135. }
  136. // 27.2.4.3.1 PerformPromiseAny ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseany
  137. static Value perform_promise_any(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
  138. {
  139. auto& vm = global_object.vm();
  140. return perform_promise_common(
  141. global_object, iterator_record, constructor, result_capability, promise_resolve,
  142. [&](PromiseValueList& errors) -> ThrowCompletionOr<Value> {
  143. auto errors_array = Array::create_from(global_object, errors.values());
  144. auto* error = AggregateError::create(global_object);
  145. MUST(error->define_property_or_throw(vm.names.errors, { .value = errors_array, .writable = true, .enumerable = false, .configurable = true }));
  146. vm.throw_exception(global_object, error);
  147. return throw_completion(error);
  148. },
  149. [&](PromiseValueList& errors, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  150. auto* on_rejected = PromiseAnyRejectElementFunction::create(global_object, index, errors, result_capability, remaining_elements_count);
  151. on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  152. (void)next_promise.invoke(global_object, vm.names.then, result_capability.resolve, on_rejected);
  153. });
  154. }
  155. // 27.2.4.5.1 PerformPromiseRace ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiserace
  156. static Value perform_promise_race(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
  157. {
  158. auto& vm = global_object.vm();
  159. return perform_promise_common(
  160. global_object, iterator_record, constructor, result_capability, promise_resolve,
  161. [&](PromiseValueList&) -> ThrowCompletionOr<Value> {
  162. return Value(result_capability.promise);
  163. },
  164. [&](PromiseValueList&, RemainingElements&, Value next_promise, size_t) {
  165. (void)next_promise.invoke(global_object, vm.names.then, result_capability.resolve, result_capability.reject);
  166. });
  167. }
  168. PromiseConstructor::PromiseConstructor(GlobalObject& global_object)
  169. : NativeFunction(vm().names.Promise.as_string(), *global_object.function_prototype())
  170. {
  171. }
  172. void PromiseConstructor::initialize(GlobalObject& global_object)
  173. {
  174. auto& vm = this->vm();
  175. NativeFunction::initialize(global_object);
  176. // 27.2.4.4 Promise.prototype, https://tc39.es/ecma262/#sec-promise.prototype
  177. define_direct_property(vm.names.prototype, global_object.promise_prototype(), 0);
  178. u8 attr = Attribute::Writable | Attribute::Configurable;
  179. define_old_native_function(vm.names.all, all, 1, attr);
  180. define_old_native_function(vm.names.allSettled, all_settled, 1, attr);
  181. define_old_native_function(vm.names.any, any, 1, attr);
  182. define_old_native_function(vm.names.race, race, 1, attr);
  183. define_old_native_function(vm.names.reject, reject, 1, attr);
  184. define_old_native_function(vm.names.resolve, resolve, 1, attr);
  185. define_old_native_accessor(*vm.well_known_symbol_species(), symbol_species_getter, {}, Attribute::Configurable);
  186. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  187. }
  188. // 27.2.3.1 Promise ( executor ), https://tc39.es/ecma262/#sec-promise-executor
  189. ThrowCompletionOr<Value> PromiseConstructor::call()
  190. {
  191. auto& vm = this->vm();
  192. return vm.throw_completion<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.Promise);
  193. }
  194. // 27.2.3.1 Promise ( executor ), https://tc39.es/ecma262/#sec-promise-executor
  195. ThrowCompletionOr<Object*> PromiseConstructor::construct(FunctionObject& new_target)
  196. {
  197. auto& vm = this->vm();
  198. auto& global_object = this->global_object();
  199. auto executor = vm.argument(0);
  200. if (!executor.is_function())
  201. return vm.throw_completion<TypeError>(global_object, ErrorType::PromiseExecutorNotAFunction);
  202. auto* promise = TRY(ordinary_create_from_constructor<Promise>(global_object, new_target, &GlobalObject::promise_prototype));
  203. auto [resolve_function, reject_function] = promise->create_resolving_functions();
  204. (void)vm.call(executor.as_function(), js_undefined(), &resolve_function, &reject_function);
  205. if (auto* exception = vm.exception()) {
  206. vm.clear_exception();
  207. vm.stop_unwind();
  208. TRY(vm.call(reject_function, js_undefined(), exception->value()));
  209. }
  210. return promise;
  211. }
  212. // 27.2.4.1 Promise.all ( iterable ), https://tc39.es/ecma262/#sec-promise.all
  213. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::all)
  214. {
  215. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  216. auto promise_capability = new_promise_capability(global_object, constructor);
  217. if (vm.exception())
  218. return {};
  219. auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
  220. auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
  221. auto result = perform_promise_all(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
  222. if (auto* exception = vm.exception()) {
  223. // FIXME: Once perform_promise_all returns a throw completion, pass that to iterator_close() instead.
  224. auto result_error = throw_completion(exception->value());
  225. if (!iterator_record_is_complete(global_object, *iterator_record)) {
  226. TemporaryClearException clear_exception(vm); // iterator_close() may invoke vm.call(), which VERIFYs no exception.
  227. result_error = iterator_close(*iterator_record, move(result_error));
  228. }
  229. TRY_OR_REJECT(vm, promise_capability, result_error);
  230. }
  231. return result;
  232. }
  233. // 27.2.4.2 Promise.allSettled ( iterable ), https://tc39.es/ecma262/#sec-promise.allsettled
  234. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::all_settled)
  235. {
  236. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  237. auto promise_capability = new_promise_capability(global_object, constructor);
  238. if (vm.exception())
  239. return {};
  240. auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
  241. auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
  242. auto result = perform_promise_all_settled(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
  243. if (auto* exception = vm.exception()) {
  244. // FIXME: Once perform_promise_all_settled returns a throw completion, pass that to iterator_close() instead.
  245. auto result_error = throw_completion(exception->value());
  246. if (!iterator_record_is_complete(global_object, *iterator_record)) {
  247. TemporaryClearException clear_exception(vm); // iterator_close() may invoke vm.call(), which VERIFYs no exception.
  248. result_error = iterator_close(*iterator_record, move(result_error));
  249. }
  250. TRY_OR_REJECT(vm, promise_capability, result_error);
  251. }
  252. return result;
  253. }
  254. // 27.2.4.3 Promise.any ( iterable ), https://tc39.es/ecma262/#sec-promise.any
  255. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::any)
  256. {
  257. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  258. auto promise_capability = new_promise_capability(global_object, constructor);
  259. if (vm.exception())
  260. return {};
  261. auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
  262. auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
  263. auto result = perform_promise_any(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
  264. if (auto* exception = vm.exception()) {
  265. // FIXME: Once perform_promise_any returns a throw completion, pass that to iterator_close() instead.
  266. auto result_error = throw_completion(exception->value());
  267. if (!iterator_record_is_complete(global_object, *iterator_record)) {
  268. TemporaryClearException clear_exception(vm); // iterator_close() may invoke vm.call(), which VERIFYs no exception.
  269. result_error = iterator_close(*iterator_record, move(result_error));
  270. }
  271. TRY_OR_REJECT(vm, promise_capability, result_error);
  272. }
  273. return result;
  274. }
  275. // 27.2.4.5 Promise.race ( iterable ), https://tc39.es/ecma262/#sec-promise.race
  276. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::race)
  277. {
  278. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  279. auto promise_capability = new_promise_capability(global_object, constructor);
  280. if (vm.exception())
  281. return {};
  282. auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
  283. auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
  284. auto result = perform_promise_race(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
  285. if (auto* exception = vm.exception()) {
  286. // FIXME: Once perform_promise_race returns a throw completion, pass that to iterator_close() instead.
  287. auto result_error = throw_completion(exception->value());
  288. if (!iterator_record_is_complete(global_object, *iterator_record)) {
  289. TemporaryClearException clear_exception(vm);
  290. result_error = iterator_close(*iterator_record, move(result_error)); // iterator_close() may invoke vm.call(), which VERIFYs no exception.
  291. }
  292. TRY_OR_REJECT(vm, promise_capability, result_error);
  293. }
  294. return result;
  295. }
  296. // 27.2.4.6 Promise.reject ( r ), https://tc39.es/ecma262/#sec-promise.reject
  297. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::reject)
  298. {
  299. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  300. auto promise_capability = new_promise_capability(global_object, constructor);
  301. if (vm.exception())
  302. return {};
  303. auto reason = vm.argument(0);
  304. [[maybe_unused]] auto result = TRY_OR_DISCARD(vm.call(*promise_capability.reject, js_undefined(), reason));
  305. return promise_capability.promise;
  306. }
  307. // 27.2.4.7 Promise.resolve ( x ), https://tc39.es/ecma262/#sec-promise.resolve
  308. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::resolve)
  309. {
  310. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  311. auto value = vm.argument(0);
  312. return promise_resolve(global_object, *constructor, value);
  313. }
  314. // 27.2.4.8 get Promise [ @@species ], https://tc39.es/ecma262/#sec-get-promise-@@species
  315. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::symbol_species_getter)
  316. {
  317. return vm.this_value(global_object);
  318. }
  319. }