Iterator.cpp 12 KB

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