Iterator.cpp 12 KB

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