IteratorOperations.cpp 9.6 KB

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