AbstractOperations.cpp 29 KB

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