Iterator.cpp 13 KB

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