IteratorOperations.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/AsyncFromSyncIteratorPrototype.h>
  9. #include <LibJS/Runtime/Error.h>
  10. #include <LibJS/Runtime/FunctionObject.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/IteratorOperations.h>
  13. namespace JS {
  14. // 7.4.2 GetIteratorFromMethod ( obj, method ), https://tc39.es/ecma262/#sec-getiteratorfrommethod
  15. ThrowCompletionOr<IteratorRecord> get_iterator_from_method(VM& vm, Value object, NonnullGCPtr<FunctionObject> method)
  16. {
  17. // 1. Let iterator be ? Call(method, obj).
  18. auto iterator = TRY(call(vm, *method, object));
  19. // 2. If iterator is not an Object, throw a TypeError exception.
  20. if (!iterator.is_object())
  21. return vm.throw_completion<TypeError>(ErrorType::NotIterable, TRY_OR_THROW_OOM(vm, object.to_string_without_side_effects()));
  22. // 3. Let nextMethod be ? Get(iterator, "next").
  23. auto next_method = TRY(iterator.get(vm, vm.names.next));
  24. // 4. Let iteratorRecord be the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
  25. auto iterator_record = IteratorRecord { .iterator = &iterator.as_object(), .next_method = next_method, .done = false };
  26. // 5. Return iteratorRecord.
  27. return iterator_record;
  28. }
  29. // 7.4.3 GetIterator ( obj, kind ), https://tc39.es/ecma262/#sec-getiterator
  30. ThrowCompletionOr<IteratorRecord> get_iterator(VM& vm, Value object, IteratorHint kind)
  31. {
  32. JS::GCPtr<FunctionObject> method;
  33. // 1. If kind is async, then
  34. if (kind == IteratorHint::Async) {
  35. // a. Let method be ? GetMethod(obj, @@asyncIterator).
  36. method = TRY(object.get_method(vm, vm.well_known_symbol_async_iterator()));
  37. // b. If method is undefined, then
  38. if (!method) {
  39. // i. Let syncMethod be ? GetMethod(obj, @@iterator).
  40. auto sync_method = TRY(object.get_method(vm, vm.well_known_symbol_iterator()));
  41. // ii. If syncMethod is undefined, throw a TypeError exception.
  42. if (!sync_method)
  43. return vm.throw_completion<TypeError>(ErrorType::NotIterable, TRY_OR_THROW_OOM(vm, object.to_string_without_side_effects()));
  44. // iii. Let syncIteratorRecord be ? GetIteratorFromMethod(obj, syncMethod).
  45. auto sync_iterator_record = TRY(get_iterator_from_method(vm, object, *sync_method));
  46. // iv. Return CreateAsyncFromSyncIterator(syncIteratorRecord).
  47. return create_async_from_sync_iterator(vm, sync_iterator_record);
  48. }
  49. }
  50. // 2. Else,
  51. else {
  52. // a. Let method be ? GetMethod(obj, @@iterator).
  53. method = TRY(object.get_method(vm, vm.well_known_symbol_iterator()));
  54. }
  55. // 3. If method is undefined, throw a TypeError exception.
  56. if (!method)
  57. return vm.throw_completion<TypeError>(ErrorType::NotIterable, TRY_OR_THROW_OOM(vm, object.to_string_without_side_effects()));
  58. // 4. Return ? GetIteratorFromMethod(obj, method).
  59. return TRY(get_iterator_from_method(vm, object, *method));
  60. }
  61. // 7.4.4 IteratorNext ( iteratorRecord [ , value ] ), https://tc39.es/ecma262/#sec-iteratornext
  62. ThrowCompletionOr<NonnullGCPtr<Object>> iterator_next(VM& vm, IteratorRecord const& iterator_record, Optional<Value> value)
  63. {
  64. Value result;
  65. // 1. If value is not present, then
  66. if (!value.has_value()) {
  67. // a. Let result be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
  68. result = TRY(call(vm, iterator_record.next_method, iterator_record.iterator));
  69. } else {
  70. // a. Let result be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « value »).
  71. result = TRY(call(vm, iterator_record.next_method, iterator_record.iterator, *value));
  72. }
  73. // 3. If Type(result) is not Object, throw a TypeError exception.
  74. if (!result.is_object())
  75. return vm.throw_completion<TypeError>(ErrorType::IterableNextBadReturn);
  76. // 4. Return result.
  77. return result.as_object();
  78. }
  79. // 7.4.5 IteratorComplete ( iterResult ), https://tc39.es/ecma262/#sec-iteratorcomplete
  80. ThrowCompletionOr<bool> iterator_complete(VM& vm, Object& iterator_result)
  81. {
  82. // 1. Return ToBoolean(? Get(iterResult, "done")).
  83. return TRY(iterator_result.get(vm.names.done)).to_boolean();
  84. }
  85. // 7.4.6 IteratorValue ( iterResult ), https://tc39.es/ecma262/#sec-iteratorvalue
  86. ThrowCompletionOr<Value> iterator_value(VM& vm, Object& iterator_result)
  87. {
  88. // 1. Return ? Get(iterResult, "value").
  89. return TRY(iterator_result.get(vm.names.value));
  90. }
  91. // 7.4.7 IteratorStep ( iteratorRecord ), https://tc39.es/ecma262/#sec-iteratorstep
  92. ThrowCompletionOr<GCPtr<Object>> iterator_step(VM& vm, IteratorRecord const& iterator_record)
  93. {
  94. // 1. Let result be ? IteratorNext(iteratorRecord).
  95. auto result = TRY(iterator_next(vm, iterator_record));
  96. // 2. Let done be ? IteratorComplete(result).
  97. auto done = TRY(iterator_complete(vm, result));
  98. // 3. If done is true, return false.
  99. if (done)
  100. return nullptr;
  101. // 4. Return result.
  102. return result;
  103. }
  104. // 7.4.8 IteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-iteratorclose
  105. // 7.4.10 AsyncIteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-asynciteratorclose
  106. // NOTE: These only differ in that async awaits the inner value after the call.
  107. static Completion iterator_close_impl(VM& vm, IteratorRecord const& iterator_record, Completion completion, IteratorHint iterator_hint)
  108. {
  109. // 1. Assert: Type(iteratorRecord.[[Iterator]]) is Object.
  110. // 2. Let iterator be iteratorRecord.[[Iterator]].
  111. auto iterator = iterator_record.iterator;
  112. // 3. Let innerResult be Completion(GetMethod(iterator, "return")).
  113. auto inner_result = ThrowCompletionOr<Value> { js_undefined() };
  114. auto get_method_result = Value(iterator).get_method(vm, vm.names.return_);
  115. if (get_method_result.is_error())
  116. inner_result = get_method_result.release_error();
  117. // 4. If innerResult.[[Type]] is normal, then
  118. if (!inner_result.is_error()) {
  119. // a. Let return be innerResult.[[Value]].
  120. auto return_method = get_method_result.value();
  121. // b. If return is undefined, return ? completion.
  122. if (!return_method)
  123. return completion;
  124. // c. Set innerResult to Completion(Call(return, iterator)).
  125. inner_result = call(vm, return_method, iterator);
  126. // Note: If this is AsyncIteratorClose perform one extra step.
  127. if (iterator_hint == IteratorHint::Async && !inner_result.is_error()) {
  128. // d. If innerResult.[[Type]] is normal, set innerResult to Completion(Await(innerResult.[[Value]])).
  129. inner_result = await(vm, inner_result.value());
  130. }
  131. }
  132. // 5. If completion.[[Type]] is throw, return ? completion.
  133. if (completion.is_error())
  134. return completion;
  135. // 6. If innerResult.[[Type]] is throw, return ? innerResult.
  136. if (inner_result.is_throw_completion())
  137. return inner_result;
  138. // 7. If Type(innerResult.[[Value]]) is not Object, throw a TypeError exception.
  139. if (!inner_result.value().is_object())
  140. return vm.throw_completion<TypeError>(ErrorType::IterableReturnBadReturn);
  141. // 8. Return ? completion.
  142. return completion;
  143. }
  144. // 7.4.8 IteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-iteratorclose
  145. Completion iterator_close(VM& vm, IteratorRecord const& iterator_record, Completion completion)
  146. {
  147. return iterator_close_impl(vm, iterator_record, move(completion), IteratorHint::Sync);
  148. }
  149. // 7.4.10 AsyncIteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-asynciteratorclose
  150. Completion async_iterator_close(VM& vm, IteratorRecord const& iterator_record, Completion completion)
  151. {
  152. return iterator_close_impl(vm, iterator_record, move(completion), IteratorHint::Async);
  153. }
  154. // 7.4.11 CreateIterResultObject ( value, done ), https://tc39.es/ecma262/#sec-createiterresultobject
  155. NonnullGCPtr<Object> create_iterator_result_object(VM& vm, Value value, bool done)
  156. {
  157. auto& realm = *vm.current_realm();
  158. // 1. Let obj be OrdinaryObjectCreate(%Object.prototype%).
  159. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  160. // 2. Perform ! CreateDataPropertyOrThrow(obj, "value", value).
  161. MUST(object->create_data_property_or_throw(vm.names.value, value));
  162. // 3. Perform ! CreateDataPropertyOrThrow(obj, "done", done).
  163. MUST(object->create_data_property_or_throw(vm.names.done, Value(done)));
  164. // 4. Return obj.
  165. return object;
  166. }
  167. // 7.4.13 IteratorToList ( iteratorRecord ), https://tc39.es/ecma262/#sec-iteratortolist
  168. ThrowCompletionOr<MarkedVector<Value>> iterator_to_list(VM& vm, IteratorRecord const& iterator_record)
  169. {
  170. // 1. Let values be a new empty List.
  171. MarkedVector<Value> values(vm.heap());
  172. // 2. Let next be true.
  173. GCPtr<Object> next;
  174. // 3. Repeat, while next is not false,
  175. do {
  176. // a. Set next to ? IteratorStep(iteratorRecord).
  177. next = TRY(iterator_step(vm, iterator_record));
  178. // b. If next is not false, then
  179. if (next) {
  180. // i. Let nextValue be ? IteratorValue(next).
  181. auto next_value = TRY(iterator_value(vm, *next));
  182. // ii. Append nextValue to values.
  183. TRY_OR_THROW_OOM(vm, values.try_append(next_value));
  184. }
  185. } while (next);
  186. // 4. Return values.
  187. return values;
  188. }
  189. // Non-standard
  190. Completion get_iterator_values(VM& vm, Value iterable, IteratorValueCallback callback)
  191. {
  192. auto iterator_record = TRY(get_iterator(vm, iterable, IteratorHint::Sync));
  193. while (true) {
  194. auto next_object = TRY(iterator_step(vm, iterator_record));
  195. if (!next_object)
  196. return {};
  197. auto next_value = TRY(iterator_value(vm, *next_object));
  198. if (auto completion = callback(next_value); completion.has_value())
  199. return iterator_close(vm, iterator_record, completion.release_value());
  200. }
  201. }
  202. }