IteratorOperations.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/AsyncFromSyncIteratorPrototype.h>
  9. #include <LibJS/Runtime/Error.h>
  10. #include <LibJS/Runtime/FunctionObject.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/IteratorOperations.h>
  13. namespace JS {
  14. // 7.4.2 GetIterator ( obj [ , hint [ , method ] ] ), https://tc39.es/ecma262/#sec-getiterator
  15. ThrowCompletionOr<Iterator> get_iterator(VM& vm, Value value, IteratorHint hint, Optional<Value> method)
  16. {
  17. // 1. If hint is not present, set hint to sync.
  18. // 2. If method is not present, then
  19. if (!method.has_value()) {
  20. // a. If hint is async, then
  21. if (hint == IteratorHint::Async) {
  22. // i. Set method to ? GetMethod(obj, @@asyncIterator).
  23. auto async_method = TRY(value.get_method(vm, vm.well_known_symbol_async_iterator()));
  24. // ii. If method is undefined, then
  25. if (async_method == nullptr) {
  26. // 1. Let syncMethod be ? GetMethod(obj, @@iterator).
  27. auto sync_method = TRY(value.get_method(vm, vm.well_known_symbol_iterator()));
  28. // 2. Let syncIteratorRecord be ? GetIterator(obj, sync, syncMethod).
  29. auto sync_iterator_record = TRY(get_iterator(vm, value, IteratorHint::Sync, sync_method));
  30. // 3. Return CreateAsyncFromSyncIterator(syncIteratorRecord).
  31. return create_async_from_sync_iterator(vm, sync_iterator_record);
  32. }
  33. method = Value(async_method);
  34. }
  35. // b. Otherwise, set method to ? GetMethod(obj, @@iterator).
  36. else {
  37. method = TRY(value.get_method(vm, vm.well_known_symbol_iterator()));
  38. }
  39. }
  40. // NOTE: Additional type check to produce a better error message than Call().
  41. if (!method->is_function())
  42. return vm.throw_completion<TypeError>(ErrorType::NotIterable, TRY_OR_THROW_OOM(vm, value.to_string_without_side_effects()));
  43. // 3. Let iterator be ? Call(method, obj).
  44. auto iterator = TRY(call(vm, *method, value));
  45. // 4. If Type(iterator) is not Object, throw a TypeError exception.
  46. if (!iterator.is_object())
  47. return vm.throw_completion<TypeError>(ErrorType::NotIterable, TRY_OR_THROW_OOM(vm, value.to_string_without_side_effects()));
  48. // 5. Let nextMethod be ? GetV(iterator, "next").
  49. auto next_method = TRY(iterator.get(vm, vm.names.next));
  50. // 6. Let iteratorRecord be the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
  51. auto iterator_record = Iterator { .iterator = &iterator.as_object(), .next_method = next_method, .done = false };
  52. // 7. Return iteratorRecord.
  53. return iterator_record;
  54. }
  55. // 7.4.3 IteratorNext ( iteratorRecord [ , value ] ), https://tc39.es/ecma262/#sec-iteratornext
  56. ThrowCompletionOr<NonnullGCPtr<Object>> iterator_next(VM& vm, Iterator const& iterator_record, Optional<Value> value)
  57. {
  58. Value result;
  59. // 1. If value is not present, then
  60. if (!value.has_value()) {
  61. // a. Let result be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
  62. result = TRY(call(vm, iterator_record.next_method, iterator_record.iterator));
  63. } else {
  64. // a. Let result be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « value »).
  65. result = TRY(call(vm, iterator_record.next_method, iterator_record.iterator, *value));
  66. }
  67. // 3. If Type(result) is not Object, throw a TypeError exception.
  68. if (!result.is_object())
  69. return vm.throw_completion<TypeError>(ErrorType::IterableNextBadReturn);
  70. // 4. Return result.
  71. return result.as_object();
  72. }
  73. // 7.4.4 IteratorComplete ( iterResult ), https://tc39.es/ecma262/#sec-iteratorcomplete
  74. ThrowCompletionOr<bool> iterator_complete(VM& vm, Object& iterator_result)
  75. {
  76. // 1. Return ToBoolean(? Get(iterResult, "done")).
  77. return TRY(iterator_result.get(vm.names.done)).to_boolean();
  78. }
  79. // 7.4.5 IteratorValue ( iterResult ), https://tc39.es/ecma262/#sec-iteratorvalue
  80. ThrowCompletionOr<Value> iterator_value(VM& vm, Object& iterator_result)
  81. {
  82. // 1. Return ? Get(iterResult, "value").
  83. return TRY(iterator_result.get(vm.names.value));
  84. }
  85. // 7.4.6 IteratorStep ( iteratorRecord ), https://tc39.es/ecma262/#sec-iteratorstep
  86. ThrowCompletionOr<GCPtr<Object>> iterator_step(VM& vm, Iterator const& iterator_record)
  87. {
  88. // 1. Let result be ? IteratorNext(iteratorRecord).
  89. auto result = TRY(iterator_next(vm, iterator_record));
  90. // 2. Let done be ? IteratorComplete(result).
  91. auto done = TRY(iterator_complete(vm, result));
  92. // 3. If done is true, return false.
  93. if (done)
  94. return nullptr;
  95. // 4. Return result.
  96. return result;
  97. }
  98. // 7.4.7 IteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-iteratorclose
  99. // 7.4.9 AsyncIteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-asynciteratorclose
  100. // NOTE: These only differ in that async awaits the inner value after the call.
  101. static Completion iterator_close_impl(VM& vm, Iterator const& iterator_record, Completion completion, IteratorHint iterator_hint)
  102. {
  103. // 1. Assert: Type(iteratorRecord.[[Iterator]]) is Object.
  104. // 2. Let iterator be iteratorRecord.[[Iterator]].
  105. auto iterator = iterator_record.iterator;
  106. // 3. Let innerResult be Completion(GetMethod(iterator, "return")).
  107. auto inner_result = ThrowCompletionOr<Value> { js_undefined() };
  108. auto get_method_result = Value(iterator).get_method(vm, vm.names.return_);
  109. if (get_method_result.is_error())
  110. inner_result = get_method_result.release_error();
  111. // 4. If innerResult.[[Type]] is normal, then
  112. if (!inner_result.is_error()) {
  113. // a. Let return be innerResult.[[Value]].
  114. auto return_method = get_method_result.value();
  115. // b. If return is undefined, return ? completion.
  116. if (!return_method)
  117. return completion;
  118. // c. Set innerResult to Completion(Call(return, iterator)).
  119. inner_result = call(vm, return_method, iterator);
  120. // Note: If this is AsyncIteratorClose perform one extra step.
  121. if (iterator_hint == IteratorHint::Async && !inner_result.is_error()) {
  122. // d. If innerResult.[[Type]] is normal, set innerResult to Completion(Await(innerResult.[[Value]])).
  123. inner_result = await(vm, inner_result.value());
  124. }
  125. }
  126. // 5. If completion.[[Type]] is throw, return ? completion.
  127. if (completion.is_error())
  128. return completion;
  129. // 6. If innerResult.[[Type]] is throw, return ? innerResult.
  130. if (inner_result.is_throw_completion())
  131. return inner_result;
  132. // 7. If Type(innerResult.[[Value]]) is not Object, throw a TypeError exception.
  133. if (!inner_result.value().is_object())
  134. return vm.throw_completion<TypeError>(ErrorType::IterableReturnBadReturn);
  135. // 8. Return ? completion.
  136. return completion;
  137. }
  138. // 7.4.7 IteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-iteratorclose
  139. Completion iterator_close(VM& vm, Iterator const& iterator_record, Completion completion)
  140. {
  141. return iterator_close_impl(vm, iterator_record, move(completion), IteratorHint::Sync);
  142. }
  143. // 7.4.9 AsyncIteratorClose ( iteratorRecord, completion ), https://tc39.es/ecma262/#sec-asynciteratorclose
  144. Completion async_iterator_close(VM& vm, Iterator const& iterator_record, Completion completion)
  145. {
  146. return iterator_close_impl(vm, iterator_record, move(completion), IteratorHint::Async);
  147. }
  148. // 7.4.10 CreateIterResultObject ( value, done ), https://tc39.es/ecma262/#sec-createiterresultobject
  149. Object* create_iterator_result_object(VM& vm, Value value, bool done)
  150. {
  151. auto& realm = *vm.current_realm();
  152. // 1. Let obj be OrdinaryObjectCreate(%Object.prototype%).
  153. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  154. // 2. Perform ! CreateDataPropertyOrThrow(obj, "value", value).
  155. MUST(object->create_data_property_or_throw(vm.names.value, value));
  156. // 3. Perform ! CreateDataPropertyOrThrow(obj, "done", done).
  157. MUST(object->create_data_property_or_throw(vm.names.done, Value(done)));
  158. // 4. Return obj.
  159. return object;
  160. }
  161. // 7.4.12 IterableToList ( items [ , method ] ), https://tc39.es/ecma262/#sec-iterabletolist
  162. ThrowCompletionOr<MarkedVector<Value>> iterable_to_list(VM& vm, Value iterable, Optional<Value> method)
  163. {
  164. MarkedVector<Value> values(vm.heap());
  165. (void)TRY(get_iterator_values(
  166. vm, iterable, [&](auto value) -> Optional<Completion> {
  167. values.append(value);
  168. return {};
  169. },
  170. move(method)));
  171. return { move(values) };
  172. }
  173. // Non-standard
  174. Completion get_iterator_values(VM& vm, Value iterable, IteratorValueCallback callback, Optional<Value> method)
  175. {
  176. auto iterator_record = TRY(get_iterator(vm, iterable, IteratorHint::Sync, move(method)));
  177. while (true) {
  178. auto next_object = TRY(iterator_step(vm, iterator_record));
  179. if (!next_object)
  180. return {};
  181. auto next_value = TRY(iterator_value(vm, *next_object));
  182. if (auto completion = callback(next_value); completion.has_value())
  183. return iterator_close(vm, iterator_record, completion.release_value());
  184. }
  185. }
  186. }