AbstractOperations.cpp 44 KB

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