AbstractOperations.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. /*
  2. * Copyright (c) 2020-2022, 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/Bytecode/Interpreter.h>
  13. #include <LibJS/Interpreter.h>
  14. #include <LibJS/Parser.h>
  15. #include <LibJS/Runtime/AbstractOperations.h>
  16. #include <LibJS/Runtime/Accessor.h>
  17. #include <LibJS/Runtime/ArgumentsObject.h>
  18. #include <LibJS/Runtime/Array.h>
  19. #include <LibJS/Runtime/BoundFunction.h>
  20. #include <LibJS/Runtime/Completion.h>
  21. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  22. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  23. #include <LibJS/Runtime/ErrorTypes.h>
  24. #include <LibJS/Runtime/FunctionEnvironment.h>
  25. #include <LibJS/Runtime/FunctionObject.h>
  26. #include <LibJS/Runtime/GlobalObject.h>
  27. #include <LibJS/Runtime/Object.h>
  28. #include <LibJS/Runtime/ObjectEnvironment.h>
  29. #include <LibJS/Runtime/PropertyDescriptor.h>
  30. #include <LibJS/Runtime/PropertyKey.h>
  31. #include <LibJS/Runtime/ProxyObject.h>
  32. #include <LibJS/Runtime/Reference.h>
  33. namespace JS {
  34. // 7.2.1 RequireObjectCoercible ( argument ), https://tc39.es/ecma262/#sec-requireobjectcoercible
  35. ThrowCompletionOr<Value> require_object_coercible(GlobalObject& global_object, Value value)
  36. {
  37. auto& vm = global_object.vm();
  38. if (value.is_nullish())
  39. return vm.throw_completion<TypeError>(global_object, ErrorType::NotObjectCoercible, value.to_string_without_side_effects());
  40. return value;
  41. }
  42. // 7.3.14 Call ( F, V [ , argumentsList ] ), https://tc39.es/ecma262/#sec-call
  43. ThrowCompletionOr<Value> call_impl(GlobalObject& global_object, Value function, Value this_value, Optional<MarkedVector<Value>> arguments_list)
  44. {
  45. auto& vm = global_object.vm();
  46. // 1. If argumentsList is not present, set argumentsList to a new empty List.
  47. if (!arguments_list.has_value())
  48. arguments_list = MarkedVector<Value> { global_object.heap() };
  49. // 2. If IsCallable(F) is false, throw a TypeError exception.
  50. if (!function.is_function())
  51. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, function.to_string_without_side_effects());
  52. // 3. Return ? F.[[Call]](V, argumentsList).
  53. return function.as_function().internal_call(this_value, move(*arguments_list));
  54. }
  55. ThrowCompletionOr<Value> call_impl(GlobalObject& global_object, FunctionObject& function, Value this_value, Optional<MarkedVector<Value>> arguments_list)
  56. {
  57. // 1. If argumentsList is not present, set argumentsList to a new empty List.
  58. if (!arguments_list.has_value())
  59. arguments_list = MarkedVector<Value> { global_object.heap() };
  60. // 2. If IsCallable(F) is false, throw a TypeError exception.
  61. // Note: Called with a FunctionObject ref
  62. // 3. Return ? F.[[Call]](V, argumentsList).
  63. return function.internal_call(this_value, move(*arguments_list));
  64. }
  65. // 7.3.15 Construct ( F [ , argumentsList [ , newTarget ] ] ), https://tc39.es/ecma262/#sec-construct
  66. ThrowCompletionOr<Object*> construct_impl(GlobalObject& global_object, FunctionObject& function, Optional<MarkedVector<Value>> arguments_list, FunctionObject* new_target)
  67. {
  68. // 1. If newTarget is not present, set newTarget to F.
  69. if (!new_target)
  70. new_target = &function;
  71. // 2. If argumentsList is not present, set argumentsList to a new empty List.
  72. if (!arguments_list.has_value())
  73. arguments_list = MarkedVector<Value> { global_object.heap() };
  74. // 3. Return ? F.[[Construct]](argumentsList, newTarget).
  75. return function.internal_construct(move(*arguments_list), *new_target);
  76. }
  77. // 7.3.19 LengthOfArrayLike ( obj ), https://tc39.es/ecma262/#sec-lengthofarraylike
  78. ThrowCompletionOr<size_t> length_of_array_like(GlobalObject& global_object, Object const& object)
  79. {
  80. auto& vm = global_object.vm();
  81. auto result = TRY(object.get(vm.names.length));
  82. return result.to_length(global_object);
  83. }
  84. // 7.3.20 CreateListFromArrayLike ( obj [ , elementTypes ] ), https://tc39.es/ecma262/#sec-createlistfromarraylike
  85. ThrowCompletionOr<MarkedVector<Value>> create_list_from_array_like(GlobalObject& global_object, Value value, Function<ThrowCompletionOr<void>(Value)> check_value)
  86. {
  87. auto& vm = global_object.vm();
  88. auto& heap = global_object.heap();
  89. // 1. If elementTypes is not present, set elementTypes to « Undefined, Null, Boolean, String, Symbol, Number, BigInt, Object ».
  90. // 2. If Type(obj) is not Object, throw a TypeError exception.
  91. if (!value.is_object())
  92. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObject, value.to_string_without_side_effects());
  93. auto& array_like = value.as_object();
  94. // 3. Let len be ? LengthOfArrayLike(obj).
  95. auto length = TRY(length_of_array_like(global_object, array_like));
  96. // 4. Let list be a new empty List.
  97. auto list = MarkedVector<Value> { heap };
  98. // 5. Let index be 0.
  99. // 6. Repeat, while index < len,
  100. for (size_t i = 0; i < length; ++i) {
  101. // a. Let indexName be ! ToString(𝔽(index)).
  102. auto index_name = PropertyKey { i };
  103. // b. Let next be ? Get(obj, indexName).
  104. auto next = TRY(array_like.get(index_name));
  105. // c. If Type(next) is not an element of elementTypes, throw a TypeError exception.
  106. if (check_value)
  107. TRY(check_value(next));
  108. // d. Append next as the last element of list.
  109. list.append(next);
  110. }
  111. // 7. Return list.
  112. return ThrowCompletionOr(move(list));
  113. }
  114. // 7.3.23 SpeciesConstructor ( O, defaultConstructor ), https://tc39.es/ecma262/#sec-speciesconstructor
  115. ThrowCompletionOr<FunctionObject*> species_constructor(GlobalObject& global_object, Object const& object, FunctionObject& default_constructor)
  116. {
  117. auto& vm = global_object.vm();
  118. // 1. Let C be ? Get(O, "constructor").
  119. auto constructor = TRY(object.get(vm.names.constructor));
  120. // 2. If C is undefined, return defaultConstructor.
  121. if (constructor.is_undefined())
  122. return &default_constructor;
  123. // 3. If Type(C) is not Object, throw a TypeError exception.
  124. if (!constructor.is_object())
  125. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, constructor.to_string_without_side_effects());
  126. // 4. Let S be ? Get(C, @@species).
  127. auto species = TRY(constructor.as_object().get(*vm.well_known_symbol_species()));
  128. // 5. If S is either undefined or null, return defaultConstructor.
  129. if (species.is_nullish())
  130. return &default_constructor;
  131. // 6. If IsConstructor(S) is true, return S.
  132. if (species.is_constructor())
  133. return &species.as_function();
  134. // 7. Throw a TypeError exception.
  135. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, species.to_string_without_side_effects());
  136. }
  137. // 7.3.25 GetFunctionRealm ( obj ), https://tc39.es/ecma262/#sec-getfunctionrealm
  138. ThrowCompletionOr<Realm*> get_function_realm(GlobalObject& global_object, FunctionObject const& function)
  139. {
  140. auto& vm = global_object.vm();
  141. // 1. Assert: ! IsCallable(obj) is true.
  142. // 2. If obj has a [[Realm]] internal slot, then
  143. if (function.realm()) {
  144. // a. Return obj.[[Realm]].
  145. return function.realm();
  146. }
  147. // 3. If obj is a bound function exotic object, then
  148. if (is<BoundFunction>(function)) {
  149. auto& bound_function = static_cast<BoundFunction const&>(function);
  150. // a. Let target be obj.[[BoundTargetFunction]].
  151. auto& target = bound_function.bound_target_function();
  152. // b. Return ? GetFunctionRealm(target).
  153. return get_function_realm(global_object, target);
  154. }
  155. // 4. If obj is a Proxy exotic object, then
  156. if (is<ProxyObject>(function)) {
  157. auto& proxy = static_cast<ProxyObject const&>(function);
  158. // a. If obj.[[ProxyHandler]] is null, throw a TypeError exception.
  159. if (proxy.is_revoked())
  160. return vm.throw_completion<TypeError>(global_object, ErrorType::ProxyRevoked);
  161. // b. Let proxyTarget be obj.[[ProxyTarget]].
  162. auto& proxy_target = proxy.target();
  163. // c. Return ? GetFunctionRealm(proxyTarget).
  164. VERIFY(proxy_target.is_function());
  165. return get_function_realm(global_object, static_cast<FunctionObject const&>(proxy_target));
  166. }
  167. // 5. Return the current Realm Record.
  168. return vm.current_realm();
  169. }
  170. // 8.5.2.1 InitializeBoundName ( name, value, environment ), https://tc39.es/ecma262/#sec-initializeboundname
  171. ThrowCompletionOr<void> initialize_bound_name(GlobalObject& global_object, FlyString const& name, Value value, Environment* environment)
  172. {
  173. auto& vm = global_object.vm();
  174. // 1. If environment is not undefined, then
  175. if (environment) {
  176. // a. Perform environment.InitializeBinding(name, value).
  177. MUST(environment->initialize_binding(global_object, name, value));
  178. // b. Return NormalCompletion(undefined).
  179. return {};
  180. }
  181. // 2. Else,
  182. else {
  183. // a. Let lhs be ResolveBinding(name).
  184. // NOTE: Although the spec pretends resolve_binding cannot fail it can just not in this case.
  185. auto lhs = MUST(vm.resolve_binding(name));
  186. // b. Return ? PutValue(lhs, value).
  187. return TRY(lhs.put_value(global_object, value));
  188. }
  189. VERIFY_NOT_REACHED();
  190. }
  191. // 10.1.6.2 IsCompatiblePropertyDescriptor ( Extensible, Desc, Current ), https://tc39.es/ecma262/#sec-iscompatiblepropertydescriptor
  192. bool is_compatible_property_descriptor(bool extensible, PropertyDescriptor const& descriptor, Optional<PropertyDescriptor> const& current)
  193. {
  194. // 1. Return ValidateAndApplyPropertyDescriptor(undefined, undefined, Extensible, Desc, Current).
  195. return validate_and_apply_property_descriptor(nullptr, {}, extensible, descriptor, current);
  196. }
  197. // 10.1.6.3 ValidateAndApplyPropertyDescriptor ( O, P, extensible, Desc, current ), https://tc39.es/ecma262/#sec-validateandapplypropertydescriptor
  198. bool validate_and_apply_property_descriptor(Object* object, PropertyKey const& property_key, bool extensible, PropertyDescriptor const& descriptor, Optional<PropertyDescriptor> const& current)
  199. {
  200. // 1. Assert: If O is not undefined, then IsPropertyKey(P) is true.
  201. if (object)
  202. VERIFY(property_key.is_valid());
  203. // 2. If current is undefined, then
  204. if (!current.has_value()) {
  205. // a. If extensible is false, return false.
  206. if (!extensible)
  207. return false;
  208. // b. Assert: extensible is true.
  209. // c. If IsGenericDescriptor(Desc) is true or IsDataDescriptor(Desc) is true, then
  210. if (descriptor.is_generic_descriptor() || descriptor.is_data_descriptor()) {
  211. // i. If O is not undefined, create an own data property named P of object O whose [[Value]], [[Writable]],
  212. // [[Enumerable]], and [[Configurable]] attribute values are described by Desc.
  213. // If the value of an attribute field of Desc is absent, the attribute of the newly created property is set
  214. // to its default value.
  215. if (object) {
  216. auto value = descriptor.value.value_or(js_undefined());
  217. object->storage_set(property_key, { value, descriptor.attributes() });
  218. }
  219. }
  220. // d. Else,
  221. else {
  222. // i. Assert: ! IsAccessorDescriptor(Desc) is true.
  223. VERIFY(descriptor.is_accessor_descriptor());
  224. // ii. If O is not undefined, create an own accessor property named P of object O whose [[Get]], [[Set]],
  225. // [[Enumerable]], and [[Configurable]] attribute values are described by Desc.
  226. // If the value of an attribute field of Desc is absent, the attribute of the newly created property is set
  227. // to its default value.
  228. if (object) {
  229. auto accessor = Accessor::create(object->vm(), descriptor.get.value_or(nullptr), descriptor.set.value_or(nullptr));
  230. object->storage_set(property_key, { accessor, descriptor.attributes() });
  231. }
  232. }
  233. // e. Return true.
  234. return true;
  235. }
  236. // 3. If every field in Desc is absent, return true.
  237. if (descriptor.is_empty())
  238. return true;
  239. // 4. If current.[[Configurable]] is false, then
  240. if (!*current->configurable) {
  241. // a. If Desc.[[Configurable]] is present and its value is true, return false.
  242. if (descriptor.configurable.has_value() && *descriptor.configurable)
  243. return false;
  244. // b. If Desc.[[Enumerable]] is present and ! SameValue(Desc.[[Enumerable]], current.[[Enumerable]]) is false, return false.
  245. if (descriptor.enumerable.has_value() && *descriptor.enumerable != *current->enumerable)
  246. return false;
  247. }
  248. // 5. If ! IsGenericDescriptor(Desc) is true, then
  249. if (descriptor.is_generic_descriptor()) {
  250. // a. NOTE: No further validation is required.
  251. }
  252. // 6. Else if ! SameValue(! IsDataDescriptor(current), ! IsDataDescriptor(Desc)) is false, then
  253. else if (current->is_data_descriptor() != descriptor.is_data_descriptor()) {
  254. // a. If current.[[Configurable]] is false, return false.
  255. if (!*current->configurable)
  256. return false;
  257. // b. If IsDataDescriptor(current) is true, then
  258. if (current->is_data_descriptor()) {
  259. // If O is not undefined, convert the property named P of object O from a data property to an accessor property.
  260. // Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes and
  261. // set the rest of the property's attributes to their default values.
  262. if (object) {
  263. auto accessor = Accessor::create(object->vm(), nullptr, nullptr);
  264. object->storage_set(property_key, { accessor, current->attributes() });
  265. }
  266. }
  267. // c. Else,
  268. else {
  269. // If O is not undefined, convert the property named P of object O from an accessor property to a data property.
  270. // Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes and
  271. // set the rest of the property's attributes to their default values.
  272. if (object) {
  273. auto value = js_undefined();
  274. object->storage_set(property_key, { value, current->attributes() });
  275. }
  276. }
  277. }
  278. // 7. Else if IsDataDescriptor(current) and IsDataDescriptor(Desc) are both true, then
  279. else if (current->is_data_descriptor() && descriptor.is_data_descriptor()) {
  280. // a. If current.[[Configurable]] is false and current.[[Writable]] is false, then
  281. if (!*current->configurable && !*current->writable) {
  282. // i. If Desc.[[Writable]] is present and Desc.[[Writable]] is true, return false.
  283. if (descriptor.writable.has_value() && *descriptor.writable)
  284. return false;
  285. // ii. If Desc.[[Value]] is present and SameValue(Desc.[[Value]], current.[[Value]]) is false, return false.
  286. if (descriptor.value.has_value() && !same_value(*descriptor.value, *current->value))
  287. return false;
  288. // iii. Return true.
  289. return true;
  290. }
  291. }
  292. // 8. Else,
  293. else {
  294. // a. Assert: ! IsAccessorDescriptor(current) and ! IsAccessorDescriptor(Desc) are both true.
  295. VERIFY(current->is_accessor_descriptor());
  296. VERIFY(descriptor.is_accessor_descriptor());
  297. // b. If current.[[Configurable]] is false, then
  298. if (!*current->configurable) {
  299. // i. If Desc.[[Set]] is present and SameValue(Desc.[[Set]], current.[[Set]]) is false, return false.
  300. if (descriptor.set.has_value() && *descriptor.set != *current->set)
  301. return false;
  302. // ii. If Desc.[[Get]] is present and SameValue(Desc.[[Get]], current.[[Get]]) is false, return false.
  303. if (descriptor.get.has_value() && *descriptor.get != *current->get)
  304. return false;
  305. // iii. Return true.
  306. return true;
  307. }
  308. }
  309. // 9. If O is not undefined, then
  310. if (object) {
  311. // 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.
  312. Value value;
  313. if (descriptor.is_accessor_descriptor() || (current->is_accessor_descriptor() && !descriptor.is_data_descriptor())) {
  314. auto* getter = descriptor.get.value_or(current->get.value_or(nullptr));
  315. auto* setter = descriptor.set.value_or(current->set.value_or(nullptr));
  316. value = Accessor::create(object->vm(), getter, setter);
  317. } else {
  318. value = descriptor.value.value_or(current->value.value_or({}));
  319. }
  320. PropertyAttributes attributes;
  321. attributes.set_writable(descriptor.writable.value_or(current->writable.value_or(false)));
  322. attributes.set_enumerable(descriptor.enumerable.value_or(current->enumerable.value_or(false)));
  323. attributes.set_configurable(descriptor.configurable.value_or(current->configurable.value_or(false)));
  324. object->storage_set(property_key, { value, attributes });
  325. }
  326. // 10. Return true.
  327. return true;
  328. }
  329. // 10.1.14 GetPrototypeFromConstructor ( constructor, intrinsicDefaultProto ), https://tc39.es/ecma262/#sec-getprototypefromconstructor
  330. ThrowCompletionOr<Object*> get_prototype_from_constructor(GlobalObject& global_object, FunctionObject const& constructor, Object* (GlobalObject::*intrinsic_default_prototype)())
  331. {
  332. auto& vm = global_object.vm();
  333. // 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.
  334. // 2. Let proto be ? Get(constructor, "prototype").
  335. auto prototype = TRY(constructor.get(vm.names.prototype));
  336. // 3. If Type(proto) is not Object, then
  337. if (!prototype.is_object()) {
  338. // a. Let realm be ? GetFunctionRealm(constructor).
  339. auto* realm = TRY(get_function_realm(global_object, constructor));
  340. // b. Set proto to realm's intrinsic object named intrinsicDefaultProto.
  341. prototype = (realm->global_object().*intrinsic_default_prototype)();
  342. }
  343. // 4. Return proto.
  344. return &prototype.as_object();
  345. }
  346. // 9.1.2.2 NewDeclarativeEnvironment ( E ), https://tc39.es/ecma262/#sec-newdeclarativeenvironment
  347. DeclarativeEnvironment* new_declarative_environment(Environment& environment)
  348. {
  349. return environment.heap().allocate_without_global_object<DeclarativeEnvironment>(&environment);
  350. }
  351. // 9.1.2.3 NewObjectEnvironment ( O, W, E ), https://tc39.es/ecma262/#sec-newobjectenvironment
  352. ObjectEnvironment* new_object_environment(Object& object, bool is_with_environment, Environment* environment)
  353. {
  354. auto& heap = object.heap();
  355. return heap.allocate_without_global_object<ObjectEnvironment>(object, is_with_environment ? ObjectEnvironment::IsWithEnvironment::Yes : ObjectEnvironment::IsWithEnvironment::No, environment);
  356. }
  357. // 9.1.2.4 NewFunctionEnvironment ( F, newTarget ), https://tc39.es/ecma262/#sec-newfunctionenvironment
  358. FunctionEnvironment* new_function_environment(ECMAScriptFunctionObject& function, Object* new_target)
  359. {
  360. auto& heap = function.heap();
  361. // 1. Let env be a new function Environment Record containing no bindings.
  362. auto* env = heap.allocate_without_global_object<FunctionEnvironment>(function.environment());
  363. // 2. Set env.[[FunctionObject]] to F.
  364. env->set_function_object(function);
  365. // 3. If F.[[ThisMode]] is lexical, set env.[[ThisBindingStatus]] to lexical.
  366. if (function.this_mode() == ECMAScriptFunctionObject::ThisMode::Lexical)
  367. env->set_this_binding_status(FunctionEnvironment::ThisBindingStatus::Lexical);
  368. // 4. Else, set env.[[ThisBindingStatus]] to uninitialized.
  369. else
  370. env->set_this_binding_status(FunctionEnvironment::ThisBindingStatus::Uninitialized);
  371. // 5. Set env.[[NewTarget]] to newTarget.
  372. env->set_new_target(new_target ?: js_undefined());
  373. // 6. Set env.[[OuterEnv]] to F.[[Environment]].
  374. // NOTE: Done in step 1 via the FunctionEnvironment constructor.
  375. // 7. Return env.
  376. return env;
  377. }
  378. // 9.2.1.1 NewPrivateEnvironment ( outerPrivEnv ), https://tc39.es/ecma262/#sec-newprivateenvironment
  379. PrivateEnvironment* new_private_environment(VM& vm, PrivateEnvironment* outer)
  380. {
  381. // 1. Let names be a new empty List.
  382. // 2. Return the PrivateEnvironment Record { [[OuterPrivateEnvironment]]: outerPrivEnv, [[Names]]: names }.
  383. return vm.heap().allocate_without_global_object<PrivateEnvironment>(outer);
  384. }
  385. // 9.4.3 GetThisEnvironment ( ), https://tc39.es/ecma262/#sec-getthisenvironment
  386. Environment& get_this_environment(VM& vm)
  387. {
  388. for (auto* env = vm.lexical_environment(); env; env = env->outer_environment()) {
  389. if (env->has_this_binding())
  390. return *env;
  391. }
  392. VERIFY_NOT_REACHED();
  393. }
  394. // 13.3.7.2 GetSuperConstructor ( ), https://tc39.es/ecma262/#sec-getsuperconstructor
  395. Object* get_super_constructor(VM& vm)
  396. {
  397. // 1. Let envRec be GetThisEnvironment().
  398. auto& env = get_this_environment(vm);
  399. // 2. Assert: envRec is a function Environment Record.
  400. // 3. Let activeFunction be envRec.[[FunctionObject]].
  401. // 4. Assert: activeFunction is an ECMAScript function object.
  402. auto& active_function = verify_cast<FunctionEnvironment>(env).function_object();
  403. // 5. Let superConstructor be ! activeFunction.[[GetPrototypeOf]]().
  404. auto* super_constructor = MUST(active_function.internal_get_prototype_of());
  405. // 6. Return superConstructor.
  406. return super_constructor;
  407. }
  408. // 13.3.7.3 MakeSuperPropertyReference ( actualThis, propertyKey, strict ), https://tc39.es/ecma262/#sec-makesuperpropertyreference
  409. ThrowCompletionOr<Reference> make_super_property_reference(GlobalObject& global_object, Value actual_this, PropertyKey const& property_key, bool strict)
  410. {
  411. auto& vm = global_object.vm();
  412. // 1. Let env be GetThisEnvironment().
  413. auto& env = verify_cast<FunctionEnvironment>(get_this_environment(vm));
  414. // 2. Assert: env.HasSuperBinding() is true.
  415. VERIFY(env.has_super_binding());
  416. // 3. Let baseValue be ? env.GetSuperBase().
  417. auto base_value = TRY(env.get_super_base());
  418. // 4. Let bv be ? RequireObjectCoercible(baseValue).
  419. auto bv = TRY(require_object_coercible(global_object, base_value));
  420. // 5. Return the Reference Record { [[Base]]: bv, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  421. // 6. NOTE: This returns a Super Reference Record.
  422. return Reference { bv, property_key, actual_this, strict };
  423. }
  424. // 19.2.1.1 PerformEval ( x, callerRealm, strictCaller, direct ), https://tc39.es/ecma262/#sec-performeval
  425. ThrowCompletionOr<Value> perform_eval(Value x, GlobalObject& caller_realm, CallerMode strict_caller, EvalMode direct)
  426. {
  427. VERIFY(direct == EvalMode::Direct || strict_caller == CallerMode::NonStrict);
  428. if (!x.is_string())
  429. return x;
  430. auto& vm = caller_realm.vm();
  431. auto& eval_realm = vm.running_execution_context().realm;
  432. auto& code_string = x.as_string();
  433. Parser parser { Lexer { code_string.string() } };
  434. auto program = parser.parse_program(strict_caller == CallerMode::Strict);
  435. if (parser.has_errors()) {
  436. auto& error = parser.errors()[0];
  437. return vm.throw_completion<SyntaxError>(caller_realm, error.to_string());
  438. }
  439. auto strict_eval = strict_caller == CallerMode::Strict;
  440. if (program->is_strict_mode())
  441. strict_eval = true;
  442. auto& running_context = vm.running_execution_context();
  443. Environment* lexical_environment;
  444. Environment* variable_environment;
  445. PrivateEnvironment* private_environment;
  446. if (direct == EvalMode::Direct) {
  447. lexical_environment = new_declarative_environment(*running_context.lexical_environment);
  448. variable_environment = running_context.variable_environment;
  449. private_environment = running_context.private_environment;
  450. } else {
  451. lexical_environment = new_declarative_environment(eval_realm->global_environment());
  452. variable_environment = &eval_realm->global_environment();
  453. private_environment = nullptr;
  454. }
  455. if (strict_eval)
  456. variable_environment = lexical_environment;
  457. if (direct == EvalMode::Direct && !strict_eval) {
  458. // NOTE: Non-strict direct eval() forces us to deoptimize variable accesses.
  459. // Mark the variable environment chain as screwed since we will not be able
  460. // to rely on cached environment coordinates from this point on.
  461. variable_environment->set_permanently_screwed_by_eval();
  462. }
  463. // 18. If runningContext is not already suspended, suspend runningContext.
  464. // FIXME: We don't have this concept yet.
  465. ExecutionContext eval_context(vm.heap());
  466. eval_context.realm = eval_realm;
  467. eval_context.variable_environment = variable_environment;
  468. eval_context.lexical_environment = lexical_environment;
  469. eval_context.private_environment = private_environment;
  470. TRY(vm.push_execution_context(eval_context, eval_realm->global_object()));
  471. ScopeGuard pop_guard = [&] {
  472. vm.pop_execution_context();
  473. };
  474. TRY(eval_declaration_instantiation(vm, eval_realm->global_object(), program, variable_environment, lexical_environment, private_environment, strict_eval));
  475. TemporaryChange scope_change_strict(vm.running_execution_context().is_strict_mode, strict_eval);
  476. Optional<Value> eval_result;
  477. if (auto* bytecode_interpreter = Bytecode::Interpreter::current()) {
  478. auto executable = JS::Bytecode::Generator::generate(program);
  479. executable->name = "eval"sv;
  480. if (JS::Bytecode::g_dump_bytecode)
  481. executable->dump();
  482. eval_result = TRY(bytecode_interpreter->run(*executable));
  483. // Turn potentially empty JS::Value from the bytecode interpreter into an empty Optional
  484. if (eval_result.has_value() && eval_result->is_empty())
  485. eval_result = {};
  486. } else {
  487. auto& ast_interpreter = vm.interpreter();
  488. eval_result = TRY(program->execute(ast_interpreter, caller_realm));
  489. }
  490. return eval_result.value_or(js_undefined());
  491. }
  492. // 19.2.1.3 EvalDeclarationInstantiation ( body, varEnv, lexEnv, privateEnv, strict ), https://tc39.es/ecma262/#sec-evaldeclarationinstantiation
  493. ThrowCompletionOr<void> eval_declaration_instantiation(VM& vm, GlobalObject& global_object, Program const& program, Environment* variable_environment, Environment* lexical_environment, PrivateEnvironment* private_environment, bool strict)
  494. {
  495. GlobalEnvironment* global_var_environment = variable_environment->is_global_environment() ? static_cast<GlobalEnvironment*>(variable_environment) : nullptr;
  496. // 1. Let varNames be the VarDeclaredNames of body.
  497. // 2. Let varDeclarations be the VarScopedDeclarations of body.
  498. // 3. If strict is false, then
  499. if (!strict) {
  500. // a. If varEnv is a global Environment Record, then
  501. if (global_var_environment) {
  502. // i. For each element name of varNames, do
  503. TRY(program.for_each_var_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
  504. // 1. If varEnv.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  505. if (global_var_environment->has_lexical_declaration(name))
  506. return vm.throw_completion<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  507. // 2. NOTE: eval will not create a global var declaration that would be shadowed by a global lexical declaration.
  508. return {};
  509. }));
  510. }
  511. // b. Let thisEnv be lexEnv.
  512. auto* this_environment = lexical_environment;
  513. // c. Assert: The following loop will terminate.
  514. // d. Repeat, while thisEnv is not the same as varEnv,
  515. while (this_environment != variable_environment) {
  516. // i. If thisEnv is not an object Environment Record, then
  517. if (!is<ObjectEnvironment>(*this_environment)) {
  518. // 1. NOTE: The environment of with statements cannot contain any lexical declaration so it doesn't need to be checked for var/let hoisting conflicts.
  519. // 2. For each element name of varNames, do
  520. TRY(program.for_each_var_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
  521. // a. If thisEnv.HasBinding(name) is true, then
  522. if (MUST(this_environment->has_binding(name))) {
  523. // i. Throw a SyntaxError exception.
  524. return vm.throw_completion<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  525. // FIXME: ii. NOTE: Annex B.3.4 defines alternate semantics for the above step.
  526. // In particular it only throw the syntax error if it is not an environment from a catchclause.
  527. }
  528. // b. NOTE: A direct eval will not hoist var declaration over a like-named lexical declaration.
  529. return {};
  530. }));
  531. }
  532. // ii. Set thisEnv to thisEnv.[[OuterEnv]].
  533. this_environment = this_environment->outer_environment();
  534. VERIFY(this_environment);
  535. }
  536. }
  537. // 4. Let privateIdentifiers be a new empty List.
  538. // 5. Let pointer be privateEnv.
  539. // 6. Repeat, while pointer is not null,
  540. // a. For each Private Name binding of pointer.[[Names]], do
  541. // i. If privateIdentifiers does not contain binding.[[Description]], append binding.[[Description]] to privateIdentifiers.
  542. // b. Set pointer to pointer.[[OuterPrivateEnvironment]].
  543. // 7. If AllPrivateIdentifiersValid of body with argument privateIdentifiers is false, throw a SyntaxError exception.
  544. // FIXME: Add Private identifiers check here.
  545. // 8. Let functionsToInitialize be a new empty List.
  546. Vector<FunctionDeclaration const&> functions_to_initialize;
  547. // 9. Let declaredFunctionNames be a new empty List.
  548. HashTable<FlyString> declared_function_names;
  549. // 10. For each element d of varDeclarations, in reverse List order, do
  550. TRY(program.for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) -> ThrowCompletionOr<void> {
  551. // a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then
  552. // i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
  553. // Note: This is done by for_each_var_function_declaration_in_reverse_order.
  554. // ii. NOTE: If there are multiple function declarations for the same name, the last declaration is used.
  555. // iii. Let fn be the sole element of the BoundNames of d.
  556. // iv. If fn is not an element of declaredFunctionNames, then
  557. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  558. return {};
  559. // 1. If varEnv is a global Environment Record, then
  560. if (global_var_environment) {
  561. // a. Let fnDefinable be ? varEnv.CanDeclareGlobalFunction(fn).
  562. auto function_definable = TRY(global_var_environment->can_declare_global_function(function.name()));
  563. // b. If fnDefinable is false, throw a TypeError exception.
  564. if (!function_definable)
  565. return vm.throw_completion<TypeError>(global_object, ErrorType::CannotDeclareGlobalFunction, function.name());
  566. }
  567. // 2. Append fn to declaredFunctionNames.
  568. // Note: Already done in step iv.
  569. // 3. Insert d as the first element of functionsToInitialize.
  570. functions_to_initialize.append(function);
  571. return {};
  572. }));
  573. // 11. NOTE: Annex B.3.2.3 adds additional steps at this point.
  574. // B.3.2.3 Changes to EvalDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-evaldeclarationinstantiation
  575. // 11. If strict is false, then
  576. if (!strict) {
  577. // a. Let declaredFunctionOrVarNames be the list-concatenation of declaredFunctionNames and declaredVarNames.
  578. // The spec here uses 'declaredVarNames' but that has not been declared yet.
  579. HashTable<FlyString> hoisted_functions;
  580. // b. For each FunctionDeclaration f that is directly contained in the StatementList of a Block, CaseClause, or DefaultClause Contained within body, do
  581. TRY(program.for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) -> ThrowCompletionOr<void> {
  582. // i. Let F be StringValue of the BindingIdentifier of f.
  583. auto& function_name = function_declaration.name();
  584. // ii. If replacing the FunctionDeclaration f with a VariableStatement that has F as a BindingIdentifier would not produce any Early Errors for body, then
  585. // Note: This is checked during parsing and for_each_function_hoistable_with_annexB_extension so it always passes here.
  586. // 1. Let bindingExists be false.
  587. // 2. Let thisEnv be lexEnv.
  588. auto* this_environment = lexical_environment;
  589. // 3. Assert: The following loop will terminate.
  590. // 4. Repeat, while thisEnv is not the same as varEnv,
  591. while (this_environment != variable_environment) {
  592. // a. If thisEnv is not an object Environment Record, then
  593. if (!is<ObjectEnvironment>(*this_environment)) {
  594. // i. If thisEnv.HasBinding(F) is true, then
  595. if (MUST(this_environment->has_binding(function_name))) {
  596. // i. Let bindingExists be true.
  597. // Note: When bindingExists is true we skip all the other steps.
  598. return {};
  599. }
  600. }
  601. // b. Set thisEnv to thisEnv.[[OuterEnv]].
  602. this_environment = this_environment->outer_environment();
  603. VERIFY(this_environment);
  604. }
  605. // Note: At this point bindingExists is false.
  606. // 5. If bindingExists is false and varEnv is a global Environment Record, then
  607. if (global_var_environment) {
  608. // a. If varEnv.HasLexicalDeclaration(F) is false, then
  609. if (!global_var_environment->has_lexical_declaration(function_name)) {
  610. // i. Let fnDefinable be ? varEnv.CanDeclareGlobalVar(F).
  611. if (!TRY(global_var_environment->can_declare_global_var(function_name)))
  612. return {};
  613. }
  614. // b. Else,
  615. else {
  616. // i. Let fnDefinable be false.
  617. return {};
  618. }
  619. }
  620. // 6. Else,
  621. // a. Let fnDefinable be true.
  622. // Note: At this point fnDefinable is true.
  623. // 7. If bindingExists is false and fnDefinable is true, then
  624. // a. If declaredFunctionOrVarNames does not contain F, then
  625. if (!declared_function_names.contains(function_name) && !hoisted_functions.contains(function_name)) {
  626. // i. If varEnv is a global Environment Record, then
  627. if (global_var_environment) {
  628. // i. Perform ? varEnv.CreateGlobalVarBinding(F, true).
  629. TRY(global_var_environment->create_global_var_binding(function_name, true));
  630. }
  631. // ii. Else,
  632. else {
  633. // i. Let bindingExists be varEnv.HasBinding(F).
  634. // ii. If bindingExists is false, then
  635. if (!MUST(variable_environment->has_binding(function_name))) {
  636. // i. Perform ! varEnv.CreateMutableBinding(F, true).
  637. // ii. Perform ! varEnv.InitializeBinding(F, undefined).
  638. MUST(variable_environment->create_mutable_binding(global_object, function_name, true));
  639. MUST(variable_environment->initialize_binding(global_object, function_name, js_undefined()));
  640. }
  641. }
  642. }
  643. // iii. Append F to declaredFunctionOrVarNames.
  644. hoisted_functions.set(function_name);
  645. // b. When the FunctionDeclaration f is evaluated, perform the following steps in place of the FunctionDeclaration Evaluation algorithm provided in 15.2.6:
  646. // i. Let genv be the running execution context's VariableEnvironment.
  647. // ii. Let benv be the running execution context's LexicalEnvironment.
  648. // iii. Let fobj be ! benv.GetBindingValue(F, false).
  649. // iv. Perform ? genv.SetMutableBinding(F, fobj, false).
  650. // v. Return NormalCompletion(empty).
  651. function_declaration.set_should_do_additional_annexB_steps();
  652. return {};
  653. }));
  654. }
  655. // 12. Let declaredVarNames be a new empty List.
  656. HashTable<FlyString> declared_var_names;
  657. // 13. For each element d of varDeclarations, do
  658. TRY(program.for_each_var_scoped_variable_declaration([&](VariableDeclaration const& declaration) {
  659. // a. If d is a VariableDeclaration, a ForBinding, or a BindingIdentifier, then
  660. // Note: This is handled by for_each_var_scoped_variable_declaration.
  661. // i. For each String vn of the BoundNames of d, do
  662. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  663. // 1. If vn is not an element of declaredFunctionNames, then
  664. if (!declared_function_names.contains(name)) {
  665. // a. If varEnv is a global Environment Record, then
  666. if (global_var_environment) {
  667. // i. Let vnDefinable be ? varEnv.CanDeclareGlobalVar(vn).
  668. auto variable_definable = TRY(global_var_environment->can_declare_global_var(name));
  669. // ii. If vnDefinable is false, throw a TypeError exception.
  670. if (!variable_definable)
  671. return vm.throw_completion<TypeError>(global_object, ErrorType::CannotDeclareGlobalVariable, name);
  672. }
  673. // b. If vn is not an element of declaredVarNames, then
  674. // i. Append vn to declaredVarNames.
  675. declared_var_names.set(name);
  676. }
  677. return {};
  678. });
  679. }));
  680. // 14. NOTE: No abnormal terminations occur after this algorithm step unless varEnv is a global Environment Record and the global object is a Proxy exotic object.
  681. // 15. Let lexDeclarations be the LexicallyScopedDeclarations of body.
  682. // 16. For each element d of lexDeclarations, do
  683. TRY(program.for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  684. // a. NOTE: Lexically declared names are only instantiated here but not initialized.
  685. // b. For each element dn of the BoundNames of d, do
  686. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  687. // i. If IsConstantDeclaration of d is true, then
  688. if (declaration.is_constant_declaration()) {
  689. // 1. Perform ? lexEnv.CreateImmutableBinding(dn, true).
  690. TRY(lexical_environment->create_immutable_binding(global_object, name, true));
  691. }
  692. // ii. Else,
  693. else {
  694. // 1. Perform ? lexEnv.CreateMutableBinding(dn, false).
  695. TRY(lexical_environment->create_mutable_binding(global_object, name, false));
  696. }
  697. return {};
  698. });
  699. }));
  700. // 17. For each Parse Node f of functionsToInitialize, do
  701. for (auto& declaration : functions_to_initialize) {
  702. // a. Let fn be the sole element of the BoundNames of f.
  703. // b. Let fo be InstantiateFunctionObject of f with arguments lexEnv and privateEnv.
  704. auto* function = ECMAScriptFunctionObject::create(global_object, declaration.name(), declaration.source_text(), declaration.body(), declaration.parameters(), declaration.function_length(), lexical_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object());
  705. // c. If varEnv is a global Environment Record, then
  706. if (global_var_environment) {
  707. // i. Perform ? varEnv.CreateGlobalFunctionBinding(fn, fo, true).
  708. TRY(global_var_environment->create_global_function_binding(declaration.name(), function, true));
  709. }
  710. // d. Else,
  711. else {
  712. // i. Let bindingExists be varEnv.HasBinding(fn).
  713. auto binding_exists = MUST(variable_environment->has_binding(declaration.name()));
  714. // ii. If bindingExists is false, then
  715. if (!binding_exists) {
  716. // 1. Let status be ! varEnv.CreateMutableBinding(fn, true).
  717. // 2. Assert: status is not an abrupt completion because of validation preceding step 14.
  718. MUST(variable_environment->create_mutable_binding(global_object, declaration.name(), true));
  719. // 3. Perform ! varEnv.InitializeBinding(fn, fo).
  720. MUST(variable_environment->initialize_binding(global_object, declaration.name(), function));
  721. }
  722. // iii. Else,
  723. else {
  724. // 1. Perform ! varEnv.SetMutableBinding(fn, fo, false).
  725. MUST(variable_environment->set_mutable_binding(global_object, declaration.name(), function, false));
  726. }
  727. }
  728. }
  729. // 18. For each String vn of declaredVarNames, do
  730. for (auto& var_name : declared_var_names) {
  731. // a. If varEnv is a global Environment Record, then
  732. if (global_var_environment) {
  733. // i. Perform ? varEnv.CreateGlobalVarBinding(vn, true).
  734. TRY(global_var_environment->create_global_var_binding(var_name, true));
  735. }
  736. // b. Else,
  737. else {
  738. // i. Let bindingExists be varEnv.HasBinding(vn).
  739. auto binding_exists = MUST(variable_environment->has_binding(var_name));
  740. // ii. If bindingExists is false, then
  741. if (!binding_exists) {
  742. // 1. Let status be ! varEnv.CreateMutableBinding(vn, true).
  743. // 2. Assert: status is not an abrupt completion because of validation preceding step 14.
  744. MUST(variable_environment->create_mutable_binding(global_object, var_name, true));
  745. // 3. Perform ! varEnv.InitializeBinding(vn, undefined).
  746. MUST(variable_environment->initialize_binding(global_object, var_name, js_undefined()));
  747. }
  748. }
  749. }
  750. // 19. Return NormalCompletion(empty).
  751. return {};
  752. }
  753. // 10.4.4.6 CreateUnmappedArgumentsObject ( argumentsList ), https://tc39.es/ecma262/#sec-createunmappedargumentsobject
  754. Object* create_unmapped_arguments_object(GlobalObject& global_object, Span<Value> arguments)
  755. {
  756. auto& vm = global_object.vm();
  757. // 1. Let len be the number of elements in argumentsList.
  758. auto length = arguments.size();
  759. // 2. Let obj be ! OrdinaryObjectCreate(%Object.prototype%, « [[ParameterMap]] »).
  760. // 3. Set obj.[[ParameterMap]] to undefined.
  761. auto* object = Object::create(global_object, global_object.object_prototype());
  762. object->set_has_parameter_map();
  763. // 4. Perform DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  764. MUST(object->define_property_or_throw(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = true }));
  765. // 5. Let index be 0.
  766. // 6. Repeat, while index < len,
  767. for (size_t index = 0; index < length; ++index) {
  768. // a. Let val be argumentsList[index].
  769. auto value = arguments[index];
  770. // b. Perform ! CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), val).
  771. MUST(object->create_data_property_or_throw(index, value));
  772. // c. Set index to index + 1.
  773. }
  774. // 7. Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  775. auto* array_prototype_values = global_object.array_prototype_values_function();
  776. MUST(object->define_property_or_throw(*vm.well_known_symbol_iterator(), { .value = array_prototype_values, .writable = true, .enumerable = false, .configurable = true }));
  777. // 8. Perform ! DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Get]]: %ThrowTypeError%, [[Set]]: %ThrowTypeError%, [[Enumerable]]: false, [[Configurable]]: false }).
  778. auto* throw_type_error = global_object.throw_type_error_function();
  779. MUST(object->define_property_or_throw(vm.names.callee, { .get = throw_type_error, .set = throw_type_error, .enumerable = false, .configurable = false }));
  780. // 9. Return obj.
  781. return object;
  782. }
  783. // 10.4.4.7 CreateMappedArgumentsObject ( func, formals, argumentsList, env ), https://tc39.es/ecma262/#sec-createmappedargumentsobject
  784. Object* create_mapped_arguments_object(GlobalObject& global_object, FunctionObject& function, Vector<FunctionNode::Parameter> const& formals, Span<Value> arguments, Environment& environment)
  785. {
  786. auto& vm = global_object.vm();
  787. // 1. Assert: formals does not contain a rest parameter, any binding patterns, or any initializers. It may contain duplicate identifiers.
  788. // 2. Let len be the number of elements in argumentsList.
  789. VERIFY(arguments.size() <= NumericLimits<i32>::max());
  790. i32 length = static_cast<i32>(arguments.size());
  791. // 3. Let obj be ! MakeBasicObject(« [[Prototype]], [[Extensible]], [[ParameterMap]] »).
  792. // 4. Set obj.[[GetOwnProperty]] as specified in 10.4.4.1.
  793. // 5. Set obj.[[DefineOwnProperty]] as specified in 10.4.4.2.
  794. // 6. Set obj.[[Get]] as specified in 10.4.4.3.
  795. // 7. Set obj.[[Set]] as specified in 10.4.4.4.
  796. // 8. Set obj.[[Delete]] as specified in 10.4.4.5.
  797. // 9. Set obj.[[Prototype]] to %Object.prototype%.
  798. auto* object = vm.heap().allocate<ArgumentsObject>(global_object, global_object, environment);
  799. // 14. Let index be 0.
  800. // 15. Repeat, while index < len,
  801. for (i32 index = 0; index < length; ++index) {
  802. // a. Let val be argumentsList[index].
  803. auto value = arguments[index];
  804. // b. Perform ! CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), val).
  805. MUST(object->create_data_property_or_throw(index, value));
  806. // c. Set index to index + 1.
  807. }
  808. // 16. Perform ! DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  809. MUST(object->define_property_or_throw(vm.names.length, { .value = Value(length), .writable = true, .enumerable = false, .configurable = true }));
  810. // 17. Let mappedNames be a new empty List.
  811. HashTable<FlyString> mapped_names;
  812. // 18. Set index to numberOfParameters - 1.
  813. // 19. Repeat, while index ≥ 0,
  814. VERIFY(formals.size() <= NumericLimits<i32>::max());
  815. for (i32 index = static_cast<i32>(formals.size()) - 1; index >= 0; --index) {
  816. // a. Let name be parameterNames[index].
  817. auto const& name = formals[index].binding.get<FlyString>();
  818. // b. If name is not an element of mappedNames, then
  819. if (mapped_names.contains(name))
  820. continue;
  821. // i. Add name as an element of the list mappedNames.
  822. mapped_names.set(name);
  823. // ii. If index < len, then
  824. if (index < length) {
  825. // 1. Let g be MakeArgGetter(name, env).
  826. // 2. Let p be MakeArgSetter(name, env).
  827. // 3. Perform map.[[DefineOwnProperty]](! ToString(𝔽(index)), PropertyDescriptor { [[Set]]: p, [[Get]]: g, [[Enumerable]]: false, [[Configurable]]: true }).
  828. object->parameter_map().define_native_accessor(
  829. PropertyKey { index },
  830. [&environment, name](VM&, GlobalObject& global_object_getter) -> JS::ThrowCompletionOr<Value> {
  831. return MUST(environment.get_binding_value(global_object_getter, name, false));
  832. },
  833. [&environment, name](VM& vm, GlobalObject& global_object_setter) {
  834. MUST(environment.set_mutable_binding(global_object_setter, name, vm.argument(0), false));
  835. return js_undefined();
  836. },
  837. Attribute::Configurable);
  838. }
  839. }
  840. // 20. Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  841. auto* array_prototype_values = global_object.array_prototype_values_function();
  842. MUST(object->define_property_or_throw(*vm.well_known_symbol_iterator(), { .value = array_prototype_values, .writable = true, .enumerable = false, .configurable = true }));
  843. // 21. Perform ! DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Value]]: func, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
  844. MUST(object->define_property_or_throw(vm.names.callee, { .value = &function, .writable = true, .enumerable = false, .configurable = true }));
  845. // 22. Return obj.
  846. return object;
  847. }
  848. // 7.1.21 CanonicalNumericIndexString ( argument ), https://tc39.es/ecma262/#sec-canonicalnumericindexstring
  849. Value canonical_numeric_index_string(GlobalObject& global_object, PropertyKey const& property_key)
  850. {
  851. // NOTE: If the property name is a number type (An implementation-defined optimized
  852. // property key type), it can be treated as a string property that has already been
  853. // converted successfully into a canonical numeric index.
  854. VERIFY(property_key.is_string() || property_key.is_number());
  855. if (property_key.is_number())
  856. return Value(property_key.as_number());
  857. // 1. Assert: Type(argument) is String.
  858. auto argument = Value(js_string(global_object.vm(), property_key.as_string()));
  859. // 2. If argument is "-0", return -0𝔽.
  860. if (argument.as_string().string() == "-0")
  861. return Value(-0.0);
  862. // 3. Let n be ! ToNumber(argument).
  863. auto n = MUST(argument.to_number(global_object));
  864. // 4. If SameValue(! ToString(n), argument) is false, return undefined.
  865. if (!same_value(MUST(n.to_primitive_string(global_object)), argument))
  866. return js_undefined();
  867. // 5. Return n.
  868. return n;
  869. }
  870. // 22.1.3.17.1 GetSubstitution ( matched, str, position, captures, namedCaptures, replacement ), https://tc39.es/ecma262/#sec-getsubstitution
  871. ThrowCompletionOr<String> get_substitution(GlobalObject& global_object, Utf16View const& matched, Utf16View const& str, size_t position, Span<Value> captures, Value named_captures, Value replacement)
  872. {
  873. auto replace_string = TRY(replacement.to_utf16_string(global_object));
  874. auto replace_view = replace_string.view();
  875. StringBuilder result;
  876. for (size_t i = 0; i < replace_view.length_in_code_units(); ++i) {
  877. u16 curr = replace_view.code_unit_at(i);
  878. if ((curr != '$') || (i + 1 >= replace_view.length_in_code_units())) {
  879. result.append(curr);
  880. continue;
  881. }
  882. u16 next = replace_view.code_unit_at(i + 1);
  883. if (next == '$') {
  884. result.append('$');
  885. ++i;
  886. } else if (next == '&') {
  887. result.append(matched);
  888. ++i;
  889. } else if (next == '`') {
  890. auto substring = str.substring_view(0, position);
  891. result.append(substring);
  892. ++i;
  893. } else if (next == '\'') {
  894. auto tail_pos = position + matched.length_in_code_units();
  895. if (tail_pos < str.length_in_code_units()) {
  896. auto substring = str.substring_view(tail_pos);
  897. result.append(substring);
  898. }
  899. ++i;
  900. } else if (is_ascii_digit(next)) {
  901. bool is_two_digits = (i + 2 < replace_view.length_in_code_units()) && is_ascii_digit(replace_view.code_unit_at(i + 2));
  902. auto capture_postition_string = replace_view.substring_view(i + 1, is_two_digits ? 2 : 1).to_utf8();
  903. auto capture_position = capture_postition_string.to_uint();
  904. if (capture_position.has_value() && (*capture_position > 0) && (*capture_position <= captures.size())) {
  905. auto& value = captures[*capture_position - 1];
  906. if (!value.is_undefined()) {
  907. auto value_string = TRY(value.to_string(global_object));
  908. result.append(value_string);
  909. }
  910. i += is_two_digits ? 2 : 1;
  911. } else {
  912. result.append(curr);
  913. }
  914. } else if (next == '<') {
  915. auto start_position = i + 2;
  916. Optional<size_t> end_position;
  917. for (size_t j = start_position; j < replace_view.length_in_code_units(); ++j) {
  918. if (replace_view.code_unit_at(j) == '>') {
  919. end_position = j;
  920. break;
  921. }
  922. }
  923. if (named_captures.is_undefined() || !end_position.has_value()) {
  924. result.append(curr);
  925. } else {
  926. auto group_name_view = replace_view.substring_view(start_position, *end_position - start_position);
  927. auto group_name = group_name_view.to_utf8(Utf16View::AllowInvalidCodeUnits::Yes);
  928. auto capture = TRY(named_captures.as_object().get(group_name));
  929. if (!capture.is_undefined()) {
  930. auto capture_string = TRY(capture.to_string(global_object));
  931. result.append(capture_string);
  932. }
  933. i = *end_position;
  934. }
  935. } else {
  936. result.append(curr);
  937. }
  938. }
  939. return result.build();
  940. }
  941. }