AbstractOperations.cpp 42 KB

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