AbstractOperations.h 14 KB

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