AbstractOperations.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. /*
  2. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/Function.h>
  9. #include <AK/Optional.h>
  10. #include <AK/TemporaryChange.h>
  11. #include <AK/Utf16View.h>
  12. #include <LibJS/Interpreter.h>
  13. #include <LibJS/Parser.h>
  14. #include <LibJS/Runtime/AbstractOperations.h>
  15. #include <LibJS/Runtime/Accessor.h>
  16. #include <LibJS/Runtime/ArgumentsObject.h>
  17. #include <LibJS/Runtime/Array.h>
  18. #include <LibJS/Runtime/BoundFunction.h>
  19. #include <LibJS/Runtime/Completion.h>
  20. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  21. #include <LibJS/Runtime/ErrorTypes.h>
  22. #include <LibJS/Runtime/FunctionEnvironment.h>
  23. #include <LibJS/Runtime/FunctionObject.h>
  24. #include <LibJS/Runtime/GlobalObject.h>
  25. #include <LibJS/Runtime/Object.h>
  26. #include <LibJS/Runtime/ObjectEnvironment.h>
  27. #include <LibJS/Runtime/PropertyDescriptor.h>
  28. #include <LibJS/Runtime/PropertyName.h>
  29. #include <LibJS/Runtime/ProxyObject.h>
  30. #include <LibJS/Runtime/Reference.h>
  31. namespace JS {
  32. // 7.2.1 RequireObjectCoercible ( argument ), https://tc39.es/ecma262/#sec-requireobjectcoercible
  33. ThrowCompletionOr<Value> require_object_coercible(GlobalObject& global_object, Value value)
  34. {
  35. auto& vm = global_object.vm();
  36. if (value.is_nullish())
  37. return vm.throw_completion<TypeError>(global_object, ErrorType::NotObjectCoercible, value.to_string_without_side_effects());
  38. return value;
  39. }
  40. // 7.3.18 LengthOfArrayLike ( obj ), https://tc39.es/ecma262/#sec-lengthofarraylike
  41. size_t length_of_array_like(GlobalObject& global_object, Object const& object)
  42. {
  43. auto& vm = global_object.vm();
  44. auto result = object.get(vm.names.length);
  45. if (vm.exception())
  46. return {};
  47. return result.to_length(global_object);
  48. }
  49. // 7.3.19 CreateListFromArrayLike ( obj [ , elementTypes ] ), https://tc39.es/ecma262/#sec-createlistfromarraylike
  50. ThrowCompletionOr<MarkedValueList> create_list_from_array_like(GlobalObject& global_object, Value value, Function<ThrowCompletionOr<void>(Value)> check_value)
  51. {
  52. auto& vm = global_object.vm();
  53. auto& heap = global_object.heap();
  54. // 1. If elementTypes is not present, set elementTypes to « Undefined, Null, Boolean, String, Symbol, Number, BigInt, Object ».
  55. // 2. If Type(obj) is not Object, throw a TypeError exception.
  56. if (!value.is_object())
  57. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, value.to_string_without_side_effects());
  58. auto& array_like = value.as_object();
  59. // 3. Let len be ? LengthOfArrayLike(obj).
  60. auto length = length_of_array_like(global_object, array_like);
  61. if (auto* exception = vm.exception())
  62. return throw_completion(exception->value());
  63. // 4. Let list be a new empty List.
  64. auto list = MarkedValueList { heap };
  65. // 5. Let index be 0.
  66. // 6. Repeat, while index < len,
  67. for (size_t i = 0; i < length; ++i) {
  68. // a. Let indexName be ! ToString(𝔽(index)).
  69. auto index_name = String::number(i);
  70. // b. Let next be ? Get(obj, indexName).
  71. auto next = array_like.get(index_name);
  72. if (auto* exception = vm.exception())
  73. return throw_completion(exception->value());
  74. // c. If Type(next) is not an element of elementTypes, throw a TypeError exception.
  75. if (check_value)
  76. TRY(check_value(next));
  77. // d. Append next as the last element of list.
  78. list.append(next);
  79. }
  80. // 7. Return list.
  81. return list;
  82. }
  83. // 7.3.22 SpeciesConstructor ( O, defaultConstructor ), https://tc39.es/ecma262/#sec-speciesconstructor
  84. ThrowCompletionOr<FunctionObject*> species_constructor(GlobalObject& global_object, Object const& object, FunctionObject& default_constructor)
  85. {
  86. auto& vm = global_object.vm();
  87. // 1. Let C be ? Get(O, "constructor").
  88. auto constructor = object.get(vm.names.constructor);
  89. if (auto* exception = vm.exception())
  90. return throw_completion(exception->value());
  91. // 2. If C is undefined, return defaultConstructor.
  92. if (constructor.is_undefined())
  93. return &default_constructor;
  94. // 3. If Type(C) is not Object, throw a TypeError exception.
  95. if (!constructor.is_object())
  96. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, constructor.to_string_without_side_effects());
  97. // 4. Let S be ? Get(C, @@species).
  98. auto species = constructor.as_object().get(*vm.well_known_symbol_species());
  99. if (auto* exception = vm.exception())
  100. return throw_completion(exception->value());
  101. // 5. If S is either undefined or null, return defaultConstructor.
  102. if (species.is_nullish())
  103. return &default_constructor;
  104. // 6. If IsConstructor(S) is true, return S.
  105. if (species.is_constructor())
  106. return &species.as_function();
  107. // 7. Throw a TypeError exception.
  108. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, species.to_string_without_side_effects());
  109. }
  110. // 7.3.24 GetFunctionRealm ( obj ), https://tc39.es/ecma262/#sec-getfunctionrealm
  111. ThrowCompletionOr<Realm*> get_function_realm(GlobalObject& global_object, FunctionObject const& function)
  112. {
  113. auto& vm = global_object.vm();
  114. // 1. Assert: ! IsCallable(obj) is true.
  115. // 2. If obj has a [[Realm]] internal slot, then
  116. if (function.realm()) {
  117. // a. Return obj.[[Realm]].
  118. return function.realm();
  119. }
  120. // 3. If obj is a bound function exotic object, then
  121. if (is<BoundFunction>(function)) {
  122. auto& bound_function = static_cast<BoundFunction const&>(function);
  123. // a. Let target be obj.[[BoundTargetFunction]].
  124. auto& target = bound_function.target_function();
  125. // b. Return ? GetFunctionRealm(target).
  126. return get_function_realm(global_object, target);
  127. }
  128. // 4. If obj is a Proxy exotic object, then
  129. if (is<ProxyObject>(function)) {
  130. auto& proxy = static_cast<ProxyObject const&>(function);
  131. // a. If obj.[[ProxyHandler]] is null, throw a TypeError exception.
  132. if (proxy.is_revoked())
  133. return vm.throw_completion<TypeError>(global_object, ErrorType::ProxyRevoked);
  134. // b. Let proxyTarget be obj.[[ProxyTarget]].
  135. auto& proxy_target = proxy.target();
  136. // c. Return ? GetFunctionRealm(proxyTarget).
  137. VERIFY(proxy_target.is_function());
  138. return get_function_realm(global_object, static_cast<FunctionObject const&>(proxy_target));
  139. }
  140. // 5. Return the current Realm Record.
  141. return vm.current_realm();
  142. }
  143. // 10.1.6.2 IsCompatiblePropertyDescriptor ( Extensible, Desc, Current ), https://tc39.es/ecma262/#sec-iscompatiblepropertydescriptor
  144. bool is_compatible_property_descriptor(bool extensible, PropertyDescriptor const& descriptor, Optional<PropertyDescriptor> const& current)
  145. {
  146. // 1. Return ValidateAndApplyPropertyDescriptor(undefined, undefined, Extensible, Desc, Current).
  147. return validate_and_apply_property_descriptor(nullptr, {}, extensible, descriptor, current);
  148. }
  149. // 10.1.6.3 ValidateAndApplyPropertyDescriptor ( O, P, extensible, Desc, current ), https://tc39.es/ecma262/#sec-validateandapplypropertydescriptor
  150. bool validate_and_apply_property_descriptor(Object* object, PropertyName const& property_name, bool extensible, PropertyDescriptor const& descriptor, Optional<PropertyDescriptor> const& current)
  151. {
  152. // 1. Assert: If O is not undefined, then IsPropertyKey(P) is true.
  153. if (object)
  154. VERIFY(property_name.is_valid());
  155. // 2. If current is undefined, then
  156. if (!current.has_value()) {
  157. // a. If extensible is false, return false.
  158. if (!extensible)
  159. return false;
  160. // b. Assert: extensible is true.
  161. // c. If IsGenericDescriptor(Desc) is true or IsDataDescriptor(Desc) is true, then
  162. if (descriptor.is_generic_descriptor() || descriptor.is_data_descriptor()) {
  163. // i. If O is not undefined, create an own data property named P of object O whose [[Value]], [[Writable]],
  164. // [[Enumerable]], and [[Configurable]] attribute values are described by Desc.
  165. // If the value of an attribute field of Desc is absent, the attribute of the newly created property is set
  166. // to its default value.
  167. if (object) {
  168. auto value = descriptor.value.value_or(js_undefined());
  169. object->storage_set(property_name, { value, descriptor.attributes() });
  170. }
  171. }
  172. // d. Else,
  173. else {
  174. // i. Assert: ! IsAccessorDescriptor(Desc) is true.
  175. VERIFY(descriptor.is_accessor_descriptor());
  176. // ii. If O is not undefined, create an own accessor property named P of object O whose [[Get]], [[Set]],
  177. // [[Enumerable]], and [[Configurable]] attribute values are described by Desc.
  178. // If the value of an attribute field of Desc is absent, the attribute of the newly created property is set
  179. // to its default value.
  180. if (object) {
  181. auto accessor = Accessor::create(object->vm(), descriptor.get.value_or(nullptr), descriptor.set.value_or(nullptr));
  182. object->storage_set(property_name, { accessor, descriptor.attributes() });
  183. }
  184. }
  185. // e. Return true.
  186. return true;
  187. }
  188. // 3. If every field in Desc is absent, return true.
  189. if (descriptor.is_empty())
  190. return true;
  191. // 4. If current.[[Configurable]] is false, then
  192. if (!*current->configurable) {
  193. // a. If Desc.[[Configurable]] is present and its value is true, return false.
  194. if (descriptor.configurable.has_value() && *descriptor.configurable)
  195. return false;
  196. // b. If Desc.[[Enumerable]] is present and ! SameValue(Desc.[[Enumerable]], current.[[Enumerable]]) is false, return false.
  197. if (descriptor.enumerable.has_value() && *descriptor.enumerable != *current->enumerable)
  198. return false;
  199. }
  200. // 5. If ! IsGenericDescriptor(Desc) is true, then
  201. if (descriptor.is_generic_descriptor()) {
  202. // a. NOTE: No further validation is required.
  203. }
  204. // 6. Else if ! SameValue(! IsDataDescriptor(current), ! IsDataDescriptor(Desc)) is false, then
  205. else if (current->is_data_descriptor() != descriptor.is_data_descriptor()) {
  206. // a. If current.[[Configurable]] is false, return false.
  207. if (!*current->configurable)
  208. return false;
  209. // b. If IsDataDescriptor(current) is true, then
  210. if (current->is_data_descriptor()) {
  211. // If O is not undefined, convert the property named P of object O from a data property to an accessor property.
  212. // Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes and
  213. // set the rest of the property's attributes to their default values.
  214. if (object) {
  215. auto accessor = Accessor::create(object->vm(), nullptr, nullptr);
  216. object->storage_set(property_name, { accessor, current->attributes() });
  217. }
  218. }
  219. // c. Else,
  220. else {
  221. // If O is not undefined, convert the property named P of object O from an accessor property to a data property.
  222. // Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes and
  223. // set the rest of the property's attributes to their default values.
  224. if (object) {
  225. auto value = js_undefined();
  226. object->storage_set(property_name, { value, current->attributes() });
  227. }
  228. }
  229. }
  230. // 7. Else if IsDataDescriptor(current) and IsDataDescriptor(Desc) are both true, then
  231. else if (current->is_data_descriptor() && descriptor.is_data_descriptor()) {
  232. // a. If current.[[Configurable]] is false and current.[[Writable]] is false, then
  233. if (!*current->configurable && !*current->writable) {
  234. // i. If Desc.[[Writable]] is present and Desc.[[Writable]] is true, return false.
  235. if (descriptor.writable.has_value() && *descriptor.writable)
  236. return false;
  237. // ii. If Desc.[[Value]] is present and SameValue(Desc.[[Value]], current.[[Value]]) is false, return false.
  238. if (descriptor.value.has_value() && !same_value(*descriptor.value, *current->value))
  239. return false;
  240. // iii. Return true.
  241. return true;
  242. }
  243. }
  244. // 8. Else,
  245. else {
  246. // a. Assert: ! IsAccessorDescriptor(current) and ! IsAccessorDescriptor(Desc) are both true.
  247. VERIFY(current->is_accessor_descriptor());
  248. VERIFY(descriptor.is_accessor_descriptor());
  249. // b. If current.[[Configurable]] is false, then
  250. if (!*current->configurable) {
  251. // i. If Desc.[[Set]] is present and SameValue(Desc.[[Set]], current.[[Set]]) is false, return false.
  252. if (descriptor.set.has_value() && *descriptor.set != *current->set)
  253. return false;
  254. // ii. If Desc.[[Get]] is present and SameValue(Desc.[[Get]], current.[[Get]]) is false, return false.
  255. if (descriptor.get.has_value() && *descriptor.get != *current->get)
  256. return false;
  257. // iii. Return true.
  258. return true;
  259. }
  260. }
  261. // 9. If O is not undefined, then
  262. if (object) {
  263. // a. For each field of Desc that is present, set the corresponding attribute of the property named P of object O to the value of the field.
  264. Value value;
  265. if (descriptor.is_accessor_descriptor() || (current->is_accessor_descriptor() && !descriptor.is_data_descriptor())) {
  266. auto* getter = descriptor.get.value_or(current->get.value_or(nullptr));
  267. auto* setter = descriptor.set.value_or(current->set.value_or(nullptr));
  268. value = Accessor::create(object->vm(), getter, setter);
  269. } else {
  270. value = descriptor.value.value_or(current->value.value_or({}));
  271. }
  272. PropertyAttributes attributes;
  273. attributes.set_writable(descriptor.writable.value_or(current->writable.value_or(false)));
  274. attributes.set_enumerable(descriptor.enumerable.value_or(current->enumerable.value_or(false)));
  275. attributes.set_configurable(descriptor.configurable.value_or(current->configurable.value_or(false)));
  276. object->storage_set(property_name, { value, attributes });
  277. }
  278. // 10. Return true.
  279. return true;
  280. }
  281. // 10.1.14 GetPrototypeFromConstructor ( constructor, intrinsicDefaultProto ), https://tc39.es/ecma262/#sec-getprototypefromconstructor
  282. ThrowCompletionOr<Object*> get_prototype_from_constructor(GlobalObject& global_object, FunctionObject const& constructor, Object* (GlobalObject::*intrinsic_default_prototype)())
  283. {
  284. auto& vm = global_object.vm();
  285. // 1. Assert: intrinsicDefaultProto is this specification's name of an intrinsic object. The corresponding object must be an intrinsic that is intended to be used as the [[Prototype]] value of an object.
  286. // 2. Let proto be ? Get(constructor, "prototype").
  287. auto prototype = constructor.get(vm.names.prototype);
  288. if (auto* exception = vm.exception())
  289. return throw_completion(exception->value());
  290. // 3. If Type(proto) is not Object, then
  291. if (!prototype.is_object()) {
  292. // a. Let realm be ? GetFunctionRealm(constructor).
  293. auto* realm = TRY(get_function_realm(global_object, constructor));
  294. // b. Set proto to realm's intrinsic object named intrinsicDefaultProto.
  295. prototype = (realm->global_object().*intrinsic_default_prototype)();
  296. }
  297. // 4. Return proto.
  298. return &prototype.as_object();
  299. }
  300. // 9.1.2.2 NewDeclarativeEnvironment ( E ), https://tc39.es/ecma262/#sec-newdeclarativeenvironment
  301. DeclarativeEnvironment* new_declarative_environment(Environment& environment)
  302. {
  303. auto& global_object = environment.global_object();
  304. return global_object.heap().allocate<DeclarativeEnvironment>(global_object, &environment);
  305. }
  306. // 9.1.2.3 NewObjectEnvironment ( O, W, E ), https://tc39.es/ecma262/#sec-newobjectenvironment
  307. ObjectEnvironment* new_object_environment(Object& object, bool is_with_environment, Environment* environment)
  308. {
  309. auto& global_object = object.global_object();
  310. return global_object.heap().allocate<ObjectEnvironment>(global_object, object, is_with_environment ? ObjectEnvironment::IsWithEnvironment::Yes : ObjectEnvironment::IsWithEnvironment::No, environment);
  311. }
  312. // 9.4.3 GetThisEnvironment ( ), https://tc39.es/ecma262/#sec-getthisenvironment
  313. Environment& get_this_environment(VM& vm)
  314. {
  315. for (auto* env = vm.lexical_environment(); env; env = env->outer_environment()) {
  316. if (env->has_this_binding())
  317. return *env;
  318. }
  319. VERIFY_NOT_REACHED();
  320. }
  321. // 13.3.7.2 GetSuperConstructor ( ), https://tc39.es/ecma262/#sec-getsuperconstructor
  322. Object* get_super_constructor(VM& vm)
  323. {
  324. auto& env = get_this_environment(vm);
  325. auto& active_function = verify_cast<FunctionEnvironment>(env).function_object();
  326. auto* super_constructor = active_function.internal_get_prototype_of();
  327. return super_constructor;
  328. }
  329. // 13.3.7.3 MakeSuperPropertyReference ( actualThis, propertyKey, strict ), https://tc39.es/ecma262/#sec-makesuperpropertyreference
  330. Reference make_super_property_reference(GlobalObject& global_object, Value actual_this, StringOrSymbol const& property_key, bool strict)
  331. {
  332. auto& vm = global_object.vm();
  333. // 1. Let env be GetThisEnvironment().
  334. auto& env = verify_cast<FunctionEnvironment>(get_this_environment(vm));
  335. // 2. Assert: env.HasSuperBinding() is true.
  336. VERIFY(env.has_super_binding());
  337. // 3. Let baseValue be ? env.GetSuperBase().
  338. auto base_value = env.get_super_base();
  339. // 4. Let bv be ? RequireObjectCoercible(baseValue).
  340. auto bv = TRY_OR_DISCARD(require_object_coercible(global_object, base_value));
  341. // 5. Return the Reference Record { [[Base]]: bv, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  342. // 6. NOTE: This returns a Super Reference Record.
  343. return Reference { bv, property_key, actual_this, strict };
  344. }
  345. // 19.2.1.1 PerformEval ( x, callerRealm, strictCaller, direct ), https://tc39.es/ecma262/#sec-performeval
  346. Value perform_eval(Value x, GlobalObject& caller_realm, CallerMode strict_caller, EvalMode direct)
  347. {
  348. VERIFY(direct == EvalMode::Direct || strict_caller == CallerMode::NonStrict);
  349. if (!x.is_string())
  350. return x;
  351. auto& vm = caller_realm.vm();
  352. auto& code_string = x.as_string();
  353. Parser parser { Lexer { code_string.string() } };
  354. auto program = parser.parse_program(strict_caller == CallerMode::Strict);
  355. if (parser.has_errors()) {
  356. auto& error = parser.errors()[0];
  357. vm.throw_exception<SyntaxError>(caller_realm, error.to_string());
  358. return {};
  359. }
  360. auto& interpreter = vm.interpreter();
  361. if (direct == EvalMode::Direct)
  362. return interpreter.execute_statement(caller_realm, program).value_or(js_undefined());
  363. TemporaryChange scope_change(vm.running_execution_context().lexical_environment, static_cast<Environment*>(&interpreter.realm().global_environment()));
  364. TemporaryChange scope_change_strict(vm.running_execution_context().is_strict_mode, strict_caller == CallerMode::Strict);
  365. return interpreter.execute_statement(caller_realm, program).value_or(js_undefined());
  366. }
  367. // 10.4.4.6 CreateUnmappedArgumentsObject ( argumentsList ), https://tc39.es/ecma262/#sec-createunmappedargumentsobject
  368. Object* create_unmapped_arguments_object(GlobalObject& global_object, Span<Value> arguments)
  369. {
  370. auto& vm = global_object.vm();
  371. // 1. Let len be the number of elements in argumentsList.
  372. auto length = arguments.size();
  373. // 2. Let obj be ! OrdinaryObjectCreate(%Object.prototype%, « [[ParameterMap]] »).
  374. // 3. Set obj.[[ParameterMap]] to undefined.
  375. auto* object = Object::create(global_object, global_object.object_prototype());
  376. object->set_has_parameter_map();
  377. // 4. Perform DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  378. object->define_property_or_throw(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = true });
  379. VERIFY(!vm.exception());
  380. // 5. Let index be 0.
  381. // 6. Repeat, while index < len,
  382. for (size_t index = 0; index < length; ++index) {
  383. // a. Let val be argumentsList[index].
  384. auto value = arguments[index];
  385. // b. Perform ! CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), val).
  386. object->create_data_property_or_throw(index, value);
  387. VERIFY(!vm.exception());
  388. // c. Set index to index + 1.
  389. }
  390. // 7. Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  391. auto* array_prototype_values = global_object.array_prototype_values_function();
  392. object->define_property_or_throw(*vm.well_known_symbol_iterator(), { .value = array_prototype_values, .writable = true, .enumerable = false, .configurable = true });
  393. VERIFY(!vm.exception());
  394. // 8. Perform ! DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Get]]: %ThrowTypeError%, [[Set]]: %ThrowTypeError%, [[Enumerable]]: false, [[Configurable]]: false }).
  395. auto* throw_type_error = global_object.throw_type_error_function();
  396. object->define_property_or_throw(vm.names.callee, { .get = throw_type_error, .set = throw_type_error, .enumerable = false, .configurable = false });
  397. VERIFY(!vm.exception());
  398. // 9. Return obj.
  399. return object;
  400. }
  401. // 10.4.4.7 CreateMappedArgumentsObject ( func, formals, argumentsList, env ), https://tc39.es/ecma262/#sec-createmappedargumentsobject
  402. Object* create_mapped_arguments_object(GlobalObject& global_object, FunctionObject& function, Vector<FunctionNode::Parameter> const& formals, Span<Value> arguments, Environment& environment)
  403. {
  404. auto& vm = global_object.vm();
  405. // 1. Assert: formals does not contain a rest parameter, any binding patterns, or any initializers. It may contain duplicate identifiers.
  406. // 2. Let len be the number of elements in argumentsList.
  407. VERIFY(arguments.size() <= NumericLimits<i32>::max());
  408. i32 length = static_cast<i32>(arguments.size());
  409. // 3. Let obj be ! MakeBasicObject(« [[Prototype]], [[Extensible]], [[ParameterMap]] »).
  410. // 4. Set obj.[[GetOwnProperty]] as specified in 10.4.4.1.
  411. // 5. Set obj.[[DefineOwnProperty]] as specified in 10.4.4.2.
  412. // 6. Set obj.[[Get]] as specified in 10.4.4.3.
  413. // 7. Set obj.[[Set]] as specified in 10.4.4.4.
  414. // 8. Set obj.[[Delete]] as specified in 10.4.4.5.
  415. // 9. Set obj.[[Prototype]] to %Object.prototype%.
  416. auto* object = vm.heap().allocate<ArgumentsObject>(global_object, global_object, environment);
  417. if (vm.exception())
  418. return nullptr;
  419. // 14. Let index be 0.
  420. // 15. Repeat, while index < len,
  421. for (i32 index = 0; index < length; ++index) {
  422. // a. Let val be argumentsList[index].
  423. auto value = arguments[index];
  424. // b. Perform ! CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), val).
  425. object->create_data_property_or_throw(index, value);
  426. VERIFY(!vm.exception());
  427. // c. Set index to index + 1.
  428. }
  429. // 16. Perform ! DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  430. object->define_property_or_throw(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = true });
  431. VERIFY(!vm.exception());
  432. // 17. Let mappedNames be a new empty List.
  433. HashTable<FlyString> mapped_names;
  434. // 18. Set index to numberOfParameters - 1.
  435. // 19. Repeat, while index ≥ 0,
  436. VERIFY(formals.size() <= NumericLimits<i32>::max());
  437. for (i32 index = static_cast<i32>(formals.size()) - 1; index >= 0; --index) {
  438. // a. Let name be parameterNames[index].
  439. auto const& name = formals[index].binding.get<FlyString>();
  440. // b. If name is not an element of mappedNames, then
  441. if (mapped_names.contains(name))
  442. continue;
  443. // i. Add name as an element of the list mappedNames.
  444. mapped_names.set(name);
  445. // ii. If index < len, then
  446. if (index < length) {
  447. // 1. Let g be MakeArgGetter(name, env).
  448. // 2. Let p be MakeArgSetter(name, env).
  449. // 3. Perform map.[[DefineOwnProperty]](! ToString(𝔽(index)), PropertyDescriptor { [[Set]]: p, [[Get]]: g, [[Enumerable]]: false, [[Configurable]]: true }).
  450. object->parameter_map().define_native_accessor(
  451. String::number(index),
  452. [&environment, name](VM&, GlobalObject&) -> Value {
  453. auto variable = environment.get_from_environment(name);
  454. if (!variable.has_value())
  455. return {};
  456. return variable->value;
  457. },
  458. [&environment, name](VM& vm, GlobalObject&) {
  459. auto value = vm.argument(0);
  460. environment.put_into_environment(name, Variable { value, DeclarationKind::Var });
  461. return js_undefined();
  462. },
  463. Attribute::Configurable);
  464. }
  465. }
  466. // 20. Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  467. auto* array_prototype_values = global_object.array_prototype_values_function();
  468. object->define_property_or_throw(*vm.well_known_symbol_iterator(), { .value = array_prototype_values, .writable = true, .enumerable = false, .configurable = true });
  469. VERIFY(!vm.exception());
  470. // 21. Perform ! DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Value]]: func, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  471. object->define_property_or_throw(vm.names.callee, { .value = &function, .writable = true, .enumerable = false, .configurable = true });
  472. VERIFY(!vm.exception());
  473. // 22. Return obj.
  474. return object;
  475. }
  476. // 7.1.21 CanonicalNumericIndexString ( argument ), https://tc39.es/ecma262/#sec-canonicalnumericindexstring
  477. Value canonical_numeric_index_string(GlobalObject& global_object, PropertyName const& property_name)
  478. {
  479. // NOTE: If the property name is a number type (An implementation-defined optimized
  480. // property key type), it can be treated as a string property that has already been
  481. // converted successfully into a canonical numeric index.
  482. VERIFY(property_name.is_string() || property_name.is_number());
  483. if (property_name.is_number())
  484. return Value(property_name.as_number());
  485. // 1. Assert: Type(argument) is String.
  486. auto argument = Value(js_string(global_object.vm(), property_name.as_string()));
  487. // 2. If argument is "-0", return -0𝔽.
  488. if (argument.as_string().string() == "-0")
  489. return Value(-0.0);
  490. // 3. Let n be ! ToNumber(argument).
  491. auto n = argument.to_number(global_object);
  492. // 4. If SameValue(! ToString(n), argument) is false, return undefined.
  493. if (!same_value(n.to_primitive_string(global_object), argument))
  494. return js_undefined();
  495. // 5. Return n.
  496. return n;
  497. }
  498. // 22.1.3.17.1 GetSubstitution ( matched, str, position, captures, namedCaptures, replacement ), https://tc39.es/ecma262/#sec-getsubstitution
  499. String get_substitution(GlobalObject& global_object, Utf16View const& matched, Utf16View const& str, size_t position, Span<Value> captures, Value named_captures, Value replacement)
  500. {
  501. auto& vm = global_object.vm();
  502. auto replace_string = replacement.to_utf16_string(global_object);
  503. if (vm.exception())
  504. return {};
  505. auto replace_view = replace_string.view();
  506. StringBuilder result;
  507. for (size_t i = 0; i < replace_view.length_in_code_units(); ++i) {
  508. u16 curr = replace_view.code_unit_at(i);
  509. if ((curr != '$') || (i + 1 >= replace_view.length_in_code_units())) {
  510. result.append(curr);
  511. continue;
  512. }
  513. u16 next = replace_view.code_unit_at(i + 1);
  514. if (next == '$') {
  515. result.append('$');
  516. ++i;
  517. } else if (next == '&') {
  518. result.append(matched);
  519. ++i;
  520. } else if (next == '`') {
  521. auto substring = str.substring_view(0, position);
  522. result.append(substring);
  523. ++i;
  524. } else if (next == '\'') {
  525. auto tail_pos = position + matched.length_in_code_units();
  526. if (tail_pos < str.length_in_code_units()) {
  527. auto substring = str.substring_view(tail_pos);
  528. result.append(substring);
  529. }
  530. ++i;
  531. } else if (is_ascii_digit(next)) {
  532. bool is_two_digits = (i + 2 < replace_view.length_in_code_units()) && is_ascii_digit(replace_view.code_unit_at(i + 2));
  533. auto capture_postition_string = replace_view.substring_view(i + 1, is_two_digits ? 2 : 1).to_utf8();
  534. auto capture_position = capture_postition_string.to_uint();
  535. if (capture_position.has_value() && (*capture_position > 0) && (*capture_position <= captures.size())) {
  536. auto& value = captures[*capture_position - 1];
  537. if (!value.is_undefined()) {
  538. auto value_string = value.to_string(global_object);
  539. if (vm.exception())
  540. return {};
  541. result.append(value_string);
  542. }
  543. i += is_two_digits ? 2 : 1;
  544. } else {
  545. result.append(curr);
  546. }
  547. } else if (next == '<') {
  548. auto start_position = i + 2;
  549. Optional<size_t> end_position;
  550. for (size_t j = start_position; j < replace_view.length_in_code_units(); ++j) {
  551. if (replace_view.code_unit_at(j) == '>') {
  552. end_position = j;
  553. break;
  554. }
  555. }
  556. if (named_captures.is_undefined() || !end_position.has_value()) {
  557. result.append(curr);
  558. } else {
  559. auto group_name_view = replace_view.substring_view(start_position, *end_position - start_position);
  560. auto group_name = group_name_view.to_utf8(Utf16View::AllowInvalidCodeUnits::Yes);
  561. auto capture = named_captures.as_object().get(group_name);
  562. if (vm.exception())
  563. return {};
  564. if (!capture.is_undefined()) {
  565. auto capture_string = capture.to_string(global_object);
  566. if (vm.exception())
  567. return {};
  568. result.append(capture_string);
  569. }
  570. i = *end_position;
  571. }
  572. } else {
  573. result.append(curr);
  574. }
  575. }
  576. return result.build();
  577. }
  578. }