AbstractOperations.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Concepts.h>
  8. #include <AK/Forward.h>
  9. #include <LibCrypto/Forward.h>
  10. #include <LibGC/MarkedVector.h>
  11. #include <LibJS/Forward.h>
  12. #include <LibJS/Runtime/CanonicalIndex.h>
  13. #include <LibJS/Runtime/FunctionObject.h>
  14. #include <LibJS/Runtime/GlobalObject.h>
  15. #include <LibJS/Runtime/Iterator.h>
  16. #include <LibJS/Runtime/KeyedCollections.h>
  17. #include <LibJS/Runtime/PrivateEnvironment.h>
  18. #include <LibJS/Runtime/VM.h>
  19. #include <LibJS/Runtime/Value.h>
  20. namespace JS {
  21. GC::Ref<DeclarativeEnvironment> new_declarative_environment(Environment&);
  22. GC::Ref<ObjectEnvironment> new_object_environment(Object&, bool is_with_environment, Environment*);
  23. GC::Ref<FunctionEnvironment> new_function_environment(ECMAScriptFunctionObject&, Object* new_target);
  24. GC::Ref<PrivateEnvironment> new_private_environment(VM& vm, PrivateEnvironment* outer);
  25. GC::Ref<Environment> get_this_environment(VM&);
  26. bool can_be_held_weakly(Value);
  27. Object* get_super_constructor(VM&);
  28. ThrowCompletionOr<Value> require_object_coercible(VM&, Value);
  29. ThrowCompletionOr<Value> call_impl(VM&, Value function, Value this_value, ReadonlySpan<Value> arguments = {});
  30. ThrowCompletionOr<Value> call_impl(VM&, FunctionObject& function, Value this_value, ReadonlySpan<Value> arguments = {});
  31. ThrowCompletionOr<GC::Ref<Object>> construct_impl(VM&, FunctionObject&, ReadonlySpan<Value> arguments = {}, FunctionObject* new_target = nullptr);
  32. ThrowCompletionOr<size_t> length_of_array_like(VM&, Object const&);
  33. ThrowCompletionOr<GC::MarkedVector<Value>> create_list_from_array_like(VM&, Value, Function<ThrowCompletionOr<void>(Value)> = {});
  34. ThrowCompletionOr<FunctionObject*> species_constructor(VM&, Object const&, FunctionObject& default_constructor);
  35. ThrowCompletionOr<Realm*> get_function_realm(VM&, FunctionObject const&);
  36. ThrowCompletionOr<void> initialize_bound_name(VM&, DeprecatedFlyString const&, Value, Environment*);
  37. bool is_compatible_property_descriptor(bool extensible, PropertyDescriptor const&, Optional<PropertyDescriptor> const& current);
  38. bool validate_and_apply_property_descriptor(Object*, PropertyKey const&, bool extensible, PropertyDescriptor const&, Optional<PropertyDescriptor> const& current);
  39. ThrowCompletionOr<Object*> get_prototype_from_constructor(VM&, FunctionObject const& constructor, GC::Ref<Object> (Intrinsics::*intrinsic_default_prototype)());
  40. Object* create_unmapped_arguments_object(VM&, ReadonlySpan<Value> arguments);
  41. Object* create_mapped_arguments_object(VM&, FunctionObject&, Vector<FunctionParameter> const&, ReadonlySpan<Value> arguments, Environment&);
  42. struct DisposableResource {
  43. Value resource_value;
  44. GC::Ref<FunctionObject> dispose_method;
  45. };
  46. ThrowCompletionOr<void> add_disposable_resource(VM&, Vector<DisposableResource>& disposable, Value, Environment::InitializeBindingHint, FunctionObject* = nullptr);
  47. ThrowCompletionOr<DisposableResource> create_disposable_resource(VM&, Value, Environment::InitializeBindingHint, FunctionObject* method = nullptr);
  48. ThrowCompletionOr<GC::Ptr<FunctionObject>> get_dispose_method(VM&, Value, Environment::InitializeBindingHint);
  49. Completion dispose(VM& vm, Value, GC::Ref<FunctionObject> method);
  50. Completion dispose_resources(VM& vm, Vector<DisposableResource> const& disposable, Completion completion);
  51. Completion dispose_resources(VM& vm, GC::Ptr<DeclarativeEnvironment> disposable, Completion completion);
  52. ThrowCompletionOr<Value> perform_import_call(VM&, Value specifier, Value options_value);
  53. enum class CanonicalIndexMode {
  54. DetectNumericRoundtrip,
  55. IgnoreNumericRoundtrip,
  56. };
  57. [[nodiscard]] CanonicalIndex canonical_numeric_index_string(PropertyKey const&, CanonicalIndexMode needs_numeric);
  58. ThrowCompletionOr<String> get_substitution(VM&, Utf16View const& matched, Utf16View const& str, size_t position, Span<Value> captures, Value named_captures, Value replacement);
  59. enum class CallerMode {
  60. Strict,
  61. NonStrict
  62. };
  63. ThrowCompletionOr<Value> perform_eval(VM&, Value, CallerMode, EvalMode);
  64. ThrowCompletionOr<void> eval_declaration_instantiation(VM& vm, Program const& program, Environment* variable_environment, Environment* lexical_environment, PrivateEnvironment* private_environment, bool strict);
  65. // 7.3.14 Call ( F, V [ , argumentsList ] ), https://tc39.es/ecma262/#sec-call
  66. ALWAYS_INLINE ThrowCompletionOr<Value> call(VM& vm, Value function, Value this_value, ReadonlySpan<Value> arguments_list)
  67. {
  68. return call_impl(vm, function, this_value, arguments_list);
  69. }
  70. ALWAYS_INLINE ThrowCompletionOr<Value> call(VM& vm, Value function, Value this_value, Span<Value> arguments_list)
  71. {
  72. return call_impl(vm, function, this_value, static_cast<ReadonlySpan<Value>>(arguments_list));
  73. }
  74. template<typename... Args>
  75. ALWAYS_INLINE ThrowCompletionOr<Value> call(VM& vm, Value function, Value this_value, Args&&... args)
  76. {
  77. constexpr auto argument_count = sizeof...(Args);
  78. if constexpr (argument_count > 0) {
  79. AK::Array<Value, argument_count> arguments { forward<Args>(args)... };
  80. return call_impl(vm, function, this_value, static_cast<ReadonlySpan<Value>>(arguments.span()));
  81. }
  82. return call_impl(vm, function, this_value);
  83. }
  84. ALWAYS_INLINE ThrowCompletionOr<Value> call(VM& vm, FunctionObject& function, Value this_value, ReadonlySpan<Value> arguments_list)
  85. {
  86. return call_impl(vm, function, this_value, arguments_list);
  87. }
  88. ALWAYS_INLINE ThrowCompletionOr<Value> call(VM& vm, FunctionObject& function, Value this_value, Span<Value> arguments_list)
  89. {
  90. return call_impl(vm, function, this_value, static_cast<ReadonlySpan<Value>>(arguments_list));
  91. }
  92. template<typename... Args>
  93. ALWAYS_INLINE ThrowCompletionOr<Value> call(VM& vm, FunctionObject& function, Value this_value, Args&&... args)
  94. {
  95. constexpr auto argument_count = sizeof...(Args);
  96. if constexpr (argument_count > 0) {
  97. AK::Array<Value, argument_count> arguments { forward<Args>(args)... };
  98. return call_impl(vm, function, this_value, static_cast<ReadonlySpan<Value>>(arguments.span()));
  99. }
  100. return call_impl(vm, function, this_value);
  101. }
  102. // 7.3.15 Construct ( F [ , argumentsList [ , newTarget ] ] ), https://tc39.es/ecma262/#sec-construct
  103. template<typename... Args>
  104. ALWAYS_INLINE ThrowCompletionOr<GC::Ref<Object>> construct(VM& vm, FunctionObject& function, Args&&... args)
  105. {
  106. constexpr auto argument_count = sizeof...(Args);
  107. if constexpr (argument_count > 0) {
  108. AK::Array<Value, argument_count> arguments { forward<Args>(args)... };
  109. return construct_impl(vm, function, static_cast<ReadonlySpan<Value>>(arguments.span()));
  110. }
  111. return construct_impl(vm, function);
  112. }
  113. ALWAYS_INLINE ThrowCompletionOr<GC::Ref<Object>> construct(VM& vm, FunctionObject& function, ReadonlySpan<Value> arguments_list, FunctionObject* new_target = nullptr)
  114. {
  115. return construct_impl(vm, function, arguments_list, new_target);
  116. }
  117. ALWAYS_INLINE ThrowCompletionOr<GC::Ref<Object>> construct(VM& vm, FunctionObject& function, Span<Value> arguments_list, FunctionObject* new_target = nullptr)
  118. {
  119. return construct_impl(vm, function, static_cast<ReadonlySpan<Value>>(arguments_list), new_target);
  120. }
  121. // 10.1.13 OrdinaryCreateFromConstructor ( constructor, intrinsicDefaultProto [ , internalSlotsList ] ), https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
  122. template<typename T, typename... Args>
  123. ThrowCompletionOr<GC::Ref<T>> ordinary_create_from_constructor(VM& vm, FunctionObject const& constructor, GC::Ref<Object> (Intrinsics::*intrinsic_default_prototype)(), Args&&... args)
  124. {
  125. auto& realm = *vm.current_realm();
  126. auto* prototype = TRY(get_prototype_from_constructor(vm, constructor, intrinsic_default_prototype));
  127. return realm.create<T>(forward<Args>(args)..., *prototype);
  128. }
  129. // 14.1 MergeLists ( a, b ), https://tc39.es/proposal-temporal/#sec-temporal-mergelists
  130. template<typename T>
  131. Vector<T> merge_lists(Vector<T> const& a, Vector<T> const& b)
  132. {
  133. // 1. Let merged be a new empty List.
  134. Vector<T> merged;
  135. // 2. For each element element of a, do
  136. for (auto const& element : a) {
  137. // a. If merged does not contain element, then
  138. if (!merged.contains_slow(element)) {
  139. // i. Append element to merged.
  140. merged.append(element);
  141. }
  142. }
  143. // 3. For each element element of b, do
  144. for (auto const& element : b) {
  145. // a. If merged does not contain element, then
  146. if (!merged.contains_slow(element)) {
  147. // i. Append element to merged.
  148. merged.append(element);
  149. }
  150. }
  151. // 4. Return merged.
  152. return merged;
  153. }
  154. // 7.3.35 AddValueToKeyedGroup ( groups, key, value ), https://tc39.es/ecma262/#sec-add-value-to-keyed-group
  155. template<typename GroupsType, typename KeyType>
  156. void add_value_to_keyed_group(VM& vm, GroupsType& groups, KeyType key, Value value)
  157. {
  158. // 1. For each Record { [[Key]], [[Elements]] } g of groups, do
  159. // a. If SameValue(g.[[Key]], key) is true, then
  160. // NOTE: This is performed in KeyedGroupTraits::equals for groupToMap and Traits<JS::PropertyKey>::equals for group.
  161. auto existing_elements_iterator = groups.find(key);
  162. if (existing_elements_iterator != groups.end()) {
  163. // i. Assert: exactly one element of groups meets this criteria.
  164. // NOTE: This is done on insertion into the hash map, as only `set` tells us if we overrode an entry.
  165. // ii. Append value as the last element of g.[[Elements]].
  166. existing_elements_iterator->value.append(value);
  167. // iii. Return unused.
  168. return;
  169. }
  170. // 2. Let group be the Record { [[Key]]: key, [[Elements]]: « value » }.
  171. GC::MarkedVector<Value> new_elements { vm.heap() };
  172. new_elements.append(value);
  173. // 3. Append group as the last element of groups.
  174. auto result = groups.set(key, move(new_elements));
  175. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  176. // 4. Return unused.
  177. }
  178. // 7.3.36 GroupBy ( items, callbackfn, keyCoercion ), https://tc39.es/ecma262/#sec-groupby
  179. template<typename GroupsType, typename KeyType>
  180. ThrowCompletionOr<GroupsType> group_by(VM& vm, Value items, Value callback_function)
  181. {
  182. // 1. Perform ? RequireObjectCoercible(items).
  183. TRY(require_object_coercible(vm, items));
  184. // 2. If IsCallable(callbackfn) is false, throw a TypeError exception.
  185. if (!callback_function.is_function())
  186. return vm.throw_completion<TypeError>(ErrorType::NotAFunction, callback_function.to_string_without_side_effects());
  187. // 3. Let groups be a new empty List.
  188. GroupsType groups;
  189. // 4. Let iteratorRecord be ? GetIterator(items, sync).
  190. auto iterator_record = TRY(get_iterator(vm, items, IteratorHint::Sync));
  191. // 5. Let k be 0.
  192. u64 k = 0;
  193. // 6. Repeat,
  194. while (true) {
  195. // a. If k ≥ 2^53 - 1, then
  196. if (k >= MAX_ARRAY_LIKE_INDEX) {
  197. // i. Let error be ThrowCompletion(a newly created TypeError object).
  198. auto error = vm.throw_completion<TypeError>(ErrorType::ArrayMaxSize);
  199. // ii. Return ? IteratorClose(iteratorRecord, error).
  200. return iterator_close(vm, iterator_record, move(error));
  201. }
  202. // b. Let next be ? IteratorStepValue(iteratorRecord).
  203. auto next = TRY(iterator_step_value(vm, iterator_record));
  204. // c. If next is DONE, then
  205. if (!next.has_value()) {
  206. // i. Return groups.
  207. return ThrowCompletionOr<GroupsType> { move(groups) };
  208. }
  209. // d. Let value be next.
  210. auto value = next.release_value();
  211. // e. Let key be Completion(Call(callbackfn, undefined, « value, 𝔽(k) »)).
  212. auto key = call(vm, callback_function, js_undefined(), value, Value(k));
  213. // f. IfAbruptCloseIterator(key, iteratorRecord).
  214. if (key.is_error())
  215. return Completion { *TRY(iterator_close(vm, iterator_record, key.release_error())) };
  216. // g. If keyCoercion is property, then
  217. if constexpr (IsSame<KeyType, PropertyKey>) {
  218. // i. Set key to Completion(ToPropertyKey(key)).
  219. auto property_key = key.value().to_property_key(vm);
  220. // ii. IfAbruptCloseIterator(key, iteratorRecord).
  221. if (property_key.is_error())
  222. return Completion { *TRY(iterator_close(vm, iterator_record, property_key.release_error())) };
  223. add_value_to_keyed_group(vm, groups, property_key.release_value(), value);
  224. }
  225. // h. Else,
  226. else {
  227. // i. Assert: keyCoercion is zero.
  228. static_assert(IsSame<KeyType, void>);
  229. // ii. Set key to CanonicalizeKeyedCollectionKey(key).
  230. key = canonicalize_keyed_collection_key(key.value());
  231. add_value_to_keyed_group(vm, groups, make_root(key.release_value()), value);
  232. }
  233. // i. Perform AddValueToKeyedGroup(groups, key, value).
  234. // NOTE: This is dependent on the `key_coercion` template parameter and thus done separately in the branches above.
  235. // j. Set k to k + 1.
  236. ++k;
  237. }
  238. }
  239. // x modulo y, https://tc39.es/ecma262/#eqn-modulo
  240. template<Arithmetic T, Arithmetic U>
  241. auto modulo(T x, U y)
  242. {
  243. // The notation “x modulo y” (y must be finite and non-zero) computes a value k of the same sign as y (or zero) such that abs(k) < abs(y) and x - k = q × y for some integer q.
  244. VERIFY(y != 0);
  245. if constexpr (IsFloatingPoint<T> || IsFloatingPoint<U>) {
  246. if constexpr (IsFloatingPoint<U>)
  247. VERIFY(isfinite(y));
  248. auto r = fmod(x, y);
  249. return r < 0 ? r + y : r;
  250. } else {
  251. return ((x % y) + y) % y;
  252. }
  253. }
  254. auto modulo(Crypto::BigInteger auto const& x, Crypto::BigInteger auto const& y)
  255. {
  256. VERIFY(!y.is_zero());
  257. auto result = x.divided_by(y).remainder;
  258. if (result.is_negative())
  259. result = result.plus(y);
  260. return result;
  261. }
  262. // remainder(x, y), https://tc39.es/proposal-temporal/#eqn-remainder
  263. template<Arithmetic T, Arithmetic U>
  264. auto remainder(T x, U y)
  265. {
  266. // The mathematical function remainder(x, y) produces the mathematical value whose sign is the sign of x and whose magnitude is abs(x) modulo y.
  267. VERIFY(y != 0);
  268. if constexpr (IsFloatingPoint<T> || IsFloatingPoint<U>) {
  269. if constexpr (IsFloatingPoint<U>)
  270. VERIFY(isfinite(y));
  271. return fmod(x, y);
  272. } else {
  273. return x % y;
  274. }
  275. }
  276. auto remainder(Crypto::BigInteger auto const& x, Crypto::BigInteger auto const& y)
  277. {
  278. VERIFY(!y.is_zero());
  279. return x.divided_by(y).remainder;
  280. }
  281. }