Iterator.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 IteratorStepValue ( iteratorRecord ), https://tc39.es/ecma262/#sec-iteratorstepvalue
  161. ThrowCompletionOr<Optional<Value>> iterator_step_value(VM& vm, IteratorRecord& iterator_record)
  162. {
  163. // 1. Let result be Completion(IteratorNext(iteratorRecord)).
  164. auto result = iterator_next(vm, iterator_record);
  165. // 2. If result is a throw completion, then
  166. if (result.is_throw_completion()) {
  167. // a. Set iteratorRecord.[[Done]] to true.
  168. iterator_record.done = true;
  169. // b. Return ? result.
  170. return result.release_error();
  171. }
  172. // 3. Set result to ! result.
  173. auto result_value = result.release_value();
  174. // 4. Let done be Completion(IteratorComplete(result)).
  175. auto done = iterator_complete(vm, result_value);
  176. // 5. If done is a throw completion, then
  177. if (done.is_throw_completion()) {
  178. // a. Set iteratorRecord.[[Done]] to true.
  179. iterator_record.done = true;
  180. // b. Return ? done.
  181. return done.release_error();
  182. }
  183. // 6. Set done to ! done.
  184. auto done_value = done.release_value();
  185. // 7. If done is true, then
  186. if (done_value) {
  187. // a. Set iteratorRecord.[[Done]] to true.
  188. iterator_record.done = true;
  189. // b. Return DONE.
  190. return OptionalNone {};
  191. }
  192. // 8. Let value be Completion(Get(result, "value")).
  193. auto value = result_value->get(vm.names.value);
  194. // 9. If value is a throw completion, then
  195. if (value.is_throw_completion()) {
  196. // a. Set iteratorRecord.[[Done]] to true.
  197. iterator_record.done = true;
  198. }
  199. // 10. Return ? value.
  200. return TRY(value);
  201. }
  202. // 7.4.9 IteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-iteratorclose
  203. // 7.4.11 AsyncIteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-asynciteratorclose
  204. // NOTE: These only differ in that async awaits the inner value after the call.
  205. static Completion iterator_close_impl(VM& vm, IteratorRecord const& iterator_record, Completion completion, IteratorHint iterator_hint)
  206. {
  207. // 1. Assert: Type(iteratorRecord.[[Iterator]]) is Object.
  208. // 2. Let iterator be iteratorRecord.[[Iterator]].
  209. auto iterator = iterator_record.iterator;
  210. // 3. Let innerResult be Completion(GetMethod(iterator, "return")).
  211. auto inner_result = ThrowCompletionOr<Value> { js_undefined() };
  212. auto get_method_result = Value(iterator).get_method(vm, vm.names.return_);
  213. if (get_method_result.is_error())
  214. inner_result = get_method_result.release_error();
  215. // 4. If innerResult.[[Type]] is normal, then
  216. if (!inner_result.is_error()) {
  217. // a. Let return be innerResult.[[Value]].
  218. auto return_method = get_method_result.value();
  219. // b. If return is undefined, return ? completion.
  220. if (!return_method)
  221. return completion;
  222. // c. Set innerResult to Completion(Call(return, iterator)).
  223. inner_result = call(vm, return_method, iterator);
  224. // Note: If this is AsyncIteratorClose perform one extra step.
  225. if (iterator_hint == IteratorHint::Async && !inner_result.is_error()) {
  226. // d. If innerResult.[[Type]] is normal, set innerResult to Completion(Await(innerResult.[[Value]])).
  227. inner_result = await(vm, inner_result.value());
  228. }
  229. }
  230. // 5. If completion.[[Type]] is throw, return ? completion.
  231. if (completion.is_error())
  232. return completion;
  233. // 6. If innerResult.[[Type]] is throw, return ? innerResult.
  234. if (inner_result.is_throw_completion())
  235. return inner_result;
  236. // 7. If Type(innerResult.[[Value]]) is not Object, throw a TypeError exception.
  237. if (!inner_result.value().is_object())
  238. return vm.throw_completion<TypeError>(ErrorType::IterableReturnBadReturn);
  239. // 8. Return ? completion.
  240. return completion;
  241. }
  242. // 7.4.9 IteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-iteratorclose
  243. Completion iterator_close(VM& vm, IteratorRecord const& iterator_record, Completion completion)
  244. {
  245. return iterator_close_impl(vm, iterator_record, move(completion), IteratorHint::Sync);
  246. }
  247. // 7.4.11 AsyncIteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-asynciteratorclose
  248. Completion async_iterator_close(VM& vm, IteratorRecord const& iterator_record, Completion completion)
  249. {
  250. return iterator_close_impl(vm, iterator_record, move(completion), IteratorHint::Async);
  251. }
  252. // 7.4.12 CreateIterResultObject ( value, done ), https://tc39.es/ecma262/#sec-createiterresultobject
  253. NonnullGCPtr<Object> create_iterator_result_object(VM& vm, Value value, bool done)
  254. {
  255. auto& realm = *vm.current_realm();
  256. // 1. Let obj be OrdinaryObjectCreate(%Object.prototype%).
  257. auto object = Object::create_with_premade_shape(realm.intrinsics().iterator_result_object_shape());
  258. // 2. Perform ! CreateDataPropertyOrThrow(obj, "value", value).
  259. object->put_direct(realm.intrinsics().iterator_result_object_value_offset(), value);
  260. // 3. Perform ! CreateDataPropertyOrThrow(obj, "done", done).
  261. object->put_direct(realm.intrinsics().iterator_result_object_done_offset(), Value(done));
  262. // 4. Return obj.
  263. return object;
  264. }
  265. // 7.4.14 IteratorToList ( iteratorRecord ), https://tc39.es/ecma262/#sec-iteratortolist
  266. ThrowCompletionOr<MarkedVector<Value>> iterator_to_list(VM& vm, IteratorRecord& iterator_record)
  267. {
  268. // 1. Let values be a new empty List.
  269. MarkedVector<Value> values(vm.heap());
  270. // 2. Repeat,
  271. while (true) {
  272. // a. Let next be ? IteratorStepValue(iteratorRecord).
  273. auto next = TRY(iterator_step_value(vm, iterator_record));
  274. // b. If next is DONE, then
  275. if (!next.has_value()) {
  276. // i. Return values.
  277. return values;
  278. }
  279. // c. Append next to values.
  280. values.append(next.release_value());
  281. }
  282. }
  283. // Non-standard
  284. Completion get_iterator_values(VM& vm, Value iterable, IteratorValueCallback callback)
  285. {
  286. auto iterator_record = TRY(get_iterator(vm, iterable, IteratorHint::Sync));
  287. while (true) {
  288. auto next = TRY(iterator_step_value(vm, iterator_record));
  289. if (!next.has_value())
  290. return {};
  291. if (auto completion = callback(next.release_value()); completion.has_value())
  292. return iterator_close(vm, iterator_record, completion.release_value());
  293. }
  294. }
  295. void Iterator::visit_edges(Cell::Visitor& visitor)
  296. {
  297. Base::visit_edges(visitor);
  298. visitor.visit(m_iterated);
  299. }
  300. void IteratorRecord::visit_edges(Cell::Visitor& visitor)
  301. {
  302. Base::visit_edges(visitor);
  303. visitor.visit(iterator);
  304. visitor.visit(next_method);
  305. }
  306. }