Iterator.cpp 12 KB

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