CommonImplementations.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. /*
  2. * Copyright (c) 2021-2023, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Bytecode/CommonImplementations.h>
  7. #include <LibJS/Bytecode/Interpreter.h>
  8. #include <LibJS/Bytecode/Op.h>
  9. #include <LibJS/Runtime/Array.h>
  10. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  11. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  12. #include <LibJS/Runtime/FunctionEnvironment.h>
  13. #include <LibJS/Runtime/GlobalEnvironment.h>
  14. #include <LibJS/Runtime/NativeFunction.h>
  15. #include <LibJS/Runtime/ObjectEnvironment.h>
  16. #include <LibJS/Runtime/RegExpObject.h>
  17. namespace JS::Bytecode {
  18. ThrowCompletionOr<NonnullGCPtr<Object>> base_object_for_get(Bytecode::Interpreter& interpreter, Value base_value)
  19. {
  20. auto& vm = interpreter.vm();
  21. if (base_value.is_object())
  22. return base_value.as_object();
  23. // OPTIMIZATION: For various primitives we can avoid actually creating a new object for them.
  24. if (base_value.is_string())
  25. return vm.current_realm()->intrinsics().string_prototype();
  26. if (base_value.is_number())
  27. return vm.current_realm()->intrinsics().number_prototype();
  28. if (base_value.is_boolean())
  29. return vm.current_realm()->intrinsics().boolean_prototype();
  30. return base_value.to_object(vm);
  31. }
  32. ThrowCompletionOr<Value> get_by_id(Bytecode::Interpreter& interpreter, IdentifierTableIndex property, Value base_value, Value this_value, u32 cache_index)
  33. {
  34. auto& vm = interpreter.vm();
  35. auto const& name = interpreter.current_executable().get_identifier(property);
  36. auto& cache = interpreter.current_executable().property_lookup_caches[cache_index];
  37. if (base_value.is_string()) {
  38. auto string_value = TRY(base_value.as_string().get(vm, name));
  39. if (string_value.has_value())
  40. return *string_value;
  41. }
  42. auto base_obj = TRY(base_object_for_get(interpreter, base_value));
  43. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  44. // NOTE: Unique shapes don't change identity, so we compare their serial numbers instead.
  45. auto& shape = base_obj->shape();
  46. if (&shape == cache.shape
  47. && (!shape.is_unique() || shape.unique_shape_serial_number() == cache.unique_shape_serial_number)) {
  48. return base_obj->get_direct(cache.property_offset.value());
  49. }
  50. CacheablePropertyMetadata cacheable_metadata;
  51. auto value = TRY(base_obj->internal_get(name, this_value, &cacheable_metadata));
  52. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  53. cache.shape = shape;
  54. cache.property_offset = cacheable_metadata.property_offset.value();
  55. cache.unique_shape_serial_number = shape.unique_shape_serial_number();
  56. }
  57. return value;
  58. }
  59. ThrowCompletionOr<Value> get_by_value(Bytecode::Interpreter& interpreter, Value base_value, Value property_key_value)
  60. {
  61. auto& vm = interpreter.vm();
  62. auto object = TRY(base_object_for_get(interpreter, base_value));
  63. // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects.
  64. if (property_key_value.is_int32()
  65. && property_key_value.as_i32() >= 0
  66. && !object->may_interfere_with_indexed_property_access()
  67. && object->indexed_properties().has_index(property_key_value.as_i32())) {
  68. auto value = object->indexed_properties().get(property_key_value.as_i32())->value;
  69. if (!value.is_accessor())
  70. return value;
  71. }
  72. auto property_key = TRY(property_key_value.to_property_key(vm));
  73. if (base_value.is_string()) {
  74. auto string_value = TRY(base_value.as_string().get(vm, property_key));
  75. if (string_value.has_value())
  76. return *string_value;
  77. }
  78. return TRY(object->internal_get(property_key, base_value));
  79. }
  80. ThrowCompletionOr<Value> get_global(Bytecode::Interpreter& interpreter, IdentifierTableIndex identifier, u32 cache_index)
  81. {
  82. auto& vm = interpreter.vm();
  83. auto& realm = *vm.current_realm();
  84. auto& cache = interpreter.current_executable().global_variable_caches[cache_index];
  85. auto& binding_object = realm.global_environment().object_record().binding_object();
  86. auto& declarative_record = realm.global_environment().declarative_record();
  87. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  88. // NOTE: Unique shapes don't change identity, so we compare their serial numbers instead.
  89. auto& shape = binding_object.shape();
  90. if (cache.environment_serial_number == declarative_record.environment_serial_number()
  91. && &shape == cache.shape
  92. && (!shape.is_unique() || shape.unique_shape_serial_number() == cache.unique_shape_serial_number)) {
  93. return binding_object.get_direct(cache.property_offset.value());
  94. }
  95. cache.environment_serial_number = declarative_record.environment_serial_number();
  96. auto const& name = interpreter.current_executable().get_identifier(identifier);
  97. if (vm.running_execution_context().script_or_module.has<NonnullGCPtr<Module>>()) {
  98. // NOTE: GetGlobal is used to access variables stored in the module environment and global environment.
  99. // The module environment is checked first since it precedes the global environment in the environment chain.
  100. auto& module_environment = *vm.running_execution_context().script_or_module.get<NonnullGCPtr<Module>>()->environment();
  101. if (TRY(module_environment.has_binding(name))) {
  102. // TODO: Cache offset of binding value
  103. return TRY(module_environment.get_binding_value(vm, name, vm.in_strict_mode()));
  104. }
  105. }
  106. if (TRY(declarative_record.has_binding(name))) {
  107. // TODO: Cache offset of binding value
  108. return TRY(declarative_record.get_binding_value(vm, name, vm.in_strict_mode()));
  109. }
  110. if (TRY(binding_object.has_property(name))) {
  111. CacheablePropertyMetadata cacheable_metadata;
  112. auto value = TRY(binding_object.internal_get(name, js_undefined(), &cacheable_metadata));
  113. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  114. cache.shape = shape;
  115. cache.property_offset = cacheable_metadata.property_offset.value();
  116. cache.unique_shape_serial_number = shape.unique_shape_serial_number();
  117. }
  118. return value;
  119. }
  120. return vm.throw_completion<ReferenceError>(ErrorType::UnknownIdentifier, name);
  121. }
  122. ThrowCompletionOr<void> put_by_property_key(VM& vm, Value base, Value this_value, Value value, PropertyKey name, Op::PropertyKind kind)
  123. {
  124. // Better error message than to_object would give
  125. if (vm.in_strict_mode() && base.is_nullish())
  126. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, base.to_string_without_side_effects());
  127. // a. Let baseObj be ? ToObject(V.[[Base]]).
  128. auto object = TRY(base.to_object(vm));
  129. if (kind == Op::PropertyKind::Getter || kind == Op::PropertyKind::Setter) {
  130. // The generator should only pass us functions for getters and setters.
  131. VERIFY(value.is_function());
  132. }
  133. switch (kind) {
  134. case Op::PropertyKind::Getter: {
  135. auto& function = value.as_function();
  136. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  137. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(DeprecatedString::formatted("get {}", name));
  138. object->define_direct_accessor(name, &function, nullptr, Attribute::Configurable | Attribute::Enumerable);
  139. break;
  140. }
  141. case Op::PropertyKind::Setter: {
  142. auto& function = value.as_function();
  143. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  144. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(DeprecatedString::formatted("set {}", name));
  145. object->define_direct_accessor(name, nullptr, &function, Attribute::Configurable | Attribute::Enumerable);
  146. break;
  147. }
  148. case Op::PropertyKind::KeyValue: {
  149. bool succeeded = TRY(object->internal_set(name, value, this_value));
  150. if (!succeeded && vm.in_strict_mode()) {
  151. if (base.is_object())
  152. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, base.to_string_without_side_effects());
  153. return vm.throw_completion<TypeError>(ErrorType::ReferencePrimitiveSetProperty, name, base.typeof(), base.to_string_without_side_effects());
  154. }
  155. break;
  156. }
  157. case Op::PropertyKind::DirectKeyValue:
  158. object->define_direct_property(name, value, Attribute::Enumerable | Attribute::Writable | Attribute::Configurable);
  159. break;
  160. case Op::PropertyKind::Spread:
  161. TRY(object->copy_data_properties(vm, value, {}));
  162. break;
  163. case Op::PropertyKind::ProtoSetter:
  164. if (value.is_object() || value.is_null())
  165. MUST(object->internal_set_prototype_of(value.is_object() ? &value.as_object() : nullptr));
  166. break;
  167. }
  168. return {};
  169. }
  170. ThrowCompletionOr<Value> perform_call(Interpreter& interpreter, Value this_value, Op::CallType call_type, Value callee, MarkedVector<Value> argument_values)
  171. {
  172. auto& vm = interpreter.vm();
  173. auto& function = callee.as_function();
  174. Value return_value;
  175. if (call_type == Op::CallType::DirectEval) {
  176. if (callee == interpreter.realm().intrinsics().eval_function())
  177. return_value = TRY(perform_eval(vm, !argument_values.is_empty() ? argument_values[0].value_or(JS::js_undefined()) : js_undefined(), vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct));
  178. else
  179. return_value = TRY(JS::call(vm, function, this_value, move(argument_values)));
  180. } else if (call_type == Op::CallType::Call)
  181. return_value = TRY(JS::call(vm, function, this_value, move(argument_values)));
  182. else
  183. return_value = TRY(construct(vm, function, move(argument_values)));
  184. return return_value;
  185. }
  186. static Completion throw_type_error_for_callee(Bytecode::Interpreter& interpreter, Value callee, StringView callee_type, Optional<StringTableIndex> const& expression_string)
  187. {
  188. auto& vm = interpreter.vm();
  189. if (expression_string.has_value())
  190. return vm.throw_completion<TypeError>(ErrorType::IsNotAEvaluatedFrom, callee.to_string_without_side_effects(), callee_type, interpreter.current_executable().get_string(expression_string->value()));
  191. return vm.throw_completion<TypeError>(ErrorType::IsNotA, callee.to_string_without_side_effects(), callee_type);
  192. }
  193. ThrowCompletionOr<void> throw_if_needed_for_call(Interpreter& interpreter, Value callee, Op::CallType call_type, Optional<StringTableIndex> const& expression_string)
  194. {
  195. if (call_type == Op::CallType::Call && !callee.is_function())
  196. return throw_type_error_for_callee(interpreter, callee, "function"sv, expression_string);
  197. if (call_type == Op::CallType::Construct && !callee.is_constructor())
  198. return throw_type_error_for_callee(interpreter, callee, "constructor"sv, expression_string);
  199. return {};
  200. }
  201. ThrowCompletionOr<Value> typeof_variable(VM& vm, DeprecatedFlyString const& string)
  202. {
  203. // 1. Let val be the result of evaluating UnaryExpression.
  204. auto reference = TRY(vm.resolve_binding(string));
  205. // 2. If val is a Reference Record, then
  206. // a. If IsUnresolvableReference(val) is true, return "undefined".
  207. if (reference.is_unresolvable())
  208. return PrimitiveString::create(vm, "undefined"_string);
  209. // 3. Set val to ? GetValue(val).
  210. auto value = TRY(reference.get_value(vm));
  211. // 4. NOTE: This step is replaced in section B.3.6.3.
  212. // 5. Return a String according to Table 41.
  213. return PrimitiveString::create(vm, value.typeof());
  214. }
  215. ThrowCompletionOr<void> set_variable(
  216. VM& vm,
  217. DeprecatedFlyString const& name,
  218. Value value,
  219. Op::EnvironmentMode mode,
  220. Op::SetVariable::InitializationMode initialization_mode)
  221. {
  222. auto environment = mode == Op::EnvironmentMode::Lexical ? vm.running_execution_context().lexical_environment : vm.running_execution_context().variable_environment;
  223. auto reference = TRY(vm.resolve_binding(name, environment));
  224. switch (initialization_mode) {
  225. case Op::SetVariable::InitializationMode::Initialize:
  226. TRY(reference.initialize_referenced_binding(vm, value));
  227. break;
  228. case Op::SetVariable::InitializationMode::Set:
  229. TRY(reference.put_value(vm, value));
  230. break;
  231. }
  232. return {};
  233. }
  234. Value new_function(VM& vm, FunctionExpression const& function_node, Optional<IdentifierTableIndex> const& lhs_name, Optional<Register> const& home_object)
  235. {
  236. Value value;
  237. if (!function_node.has_name()) {
  238. DeprecatedFlyString name = {};
  239. if (lhs_name.has_value())
  240. name = vm.bytecode_interpreter().current_executable().get_identifier(lhs_name.value());
  241. value = function_node.instantiate_ordinary_function_expression(vm, name);
  242. } else {
  243. value = ECMAScriptFunctionObject::create(*vm.current_realm(), function_node.name(), function_node.source_text(), function_node.body(), function_node.parameters(), function_node.function_length(), function_node.local_variables_names(), vm.lexical_environment(), vm.running_execution_context().private_environment, function_node.kind(), function_node.is_strict_mode(), function_node.might_need_arguments_object(), function_node.contains_direct_call_to_eval(), function_node.is_arrow_function());
  244. }
  245. if (home_object.has_value()) {
  246. auto home_object_value = vm.bytecode_interpreter().reg(home_object.value());
  247. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(&home_object_value.as_object());
  248. }
  249. return value;
  250. }
  251. ThrowCompletionOr<void> put_by_value(VM& vm, Value base, Value property_key_value, Value value, Op::PropertyKind kind)
  252. {
  253. // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects.
  254. if (base.is_object() && property_key_value.is_int32() && property_key_value.as_i32() >= 0) {
  255. auto& object = base.as_object();
  256. auto* storage = object.indexed_properties().storage();
  257. auto index = static_cast<u32>(property_key_value.as_i32());
  258. if (storage
  259. && storage->is_simple_storage()
  260. && !object.may_interfere_with_indexed_property_access()
  261. && storage->has_index(index)) {
  262. auto existing_value = storage->get(index)->value;
  263. if (!existing_value.is_accessor()) {
  264. storage->put(index, value);
  265. return {};
  266. }
  267. }
  268. }
  269. auto property_key = kind != Op::PropertyKind::Spread ? TRY(property_key_value.to_property_key(vm)) : PropertyKey {};
  270. TRY(put_by_property_key(vm, base, base, value, property_key, kind));
  271. return {};
  272. }
  273. ThrowCompletionOr<Value> get_variable(Bytecode::Interpreter& interpreter, DeprecatedFlyString const& name, u32 cache_index)
  274. {
  275. auto& vm = interpreter.vm();
  276. auto& cached_environment_coordinate = interpreter.current_executable().environment_variable_caches[cache_index];
  277. if (cached_environment_coordinate.has_value()) {
  278. auto environment = vm.running_execution_context().lexical_environment;
  279. for (size_t i = 0; i < cached_environment_coordinate->hops; ++i)
  280. environment = environment->outer_environment();
  281. VERIFY(environment);
  282. VERIFY(environment->is_declarative_environment());
  283. if (!environment->is_permanently_screwed_by_eval()) {
  284. return TRY(verify_cast<DeclarativeEnvironment>(*environment).get_binding_value_direct(vm, cached_environment_coordinate.value().index, vm.in_strict_mode()));
  285. }
  286. cached_environment_coordinate = {};
  287. }
  288. auto reference = TRY(vm.resolve_binding(name));
  289. if (reference.environment_coordinate().has_value())
  290. cached_environment_coordinate = reference.environment_coordinate();
  291. return TRY(reference.get_value(vm));
  292. }
  293. ThrowCompletionOr<CalleeAndThis> get_callee_and_this_from_environment(Bytecode::Interpreter& interpreter, DeprecatedFlyString const& name, u32 cache_index)
  294. {
  295. auto& vm = interpreter.vm();
  296. Value callee = js_undefined();
  297. Value this_value = js_undefined();
  298. auto& cached_environment_coordinate = interpreter.current_executable().environment_variable_caches[cache_index];
  299. if (cached_environment_coordinate.has_value()) {
  300. auto environment = vm.running_execution_context().lexical_environment;
  301. for (size_t i = 0; i < cached_environment_coordinate->hops; ++i)
  302. environment = environment->outer_environment();
  303. VERIFY(environment);
  304. VERIFY(environment->is_declarative_environment());
  305. if (!environment->is_permanently_screwed_by_eval()) {
  306. callee = TRY(verify_cast<DeclarativeEnvironment>(*environment).get_binding_value_direct(vm, cached_environment_coordinate.value().index, vm.in_strict_mode()));
  307. this_value = js_undefined();
  308. if (auto base_object = environment->with_base_object())
  309. this_value = base_object;
  310. return CalleeAndThis {
  311. .callee = callee,
  312. .this_value = this_value,
  313. };
  314. }
  315. cached_environment_coordinate = {};
  316. }
  317. auto reference = TRY(vm.resolve_binding(name));
  318. if (reference.environment_coordinate().has_value())
  319. cached_environment_coordinate = reference.environment_coordinate();
  320. callee = TRY(reference.get_value(vm));
  321. if (reference.is_property_reference()) {
  322. this_value = reference.get_this_value();
  323. } else {
  324. if (reference.is_environment_reference()) {
  325. if (auto base_object = reference.base_environment().with_base_object(); base_object != nullptr)
  326. this_value = base_object;
  327. }
  328. }
  329. return CalleeAndThis {
  330. .callee = callee,
  331. .this_value = this_value,
  332. };
  333. }
  334. // 13.2.7.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation
  335. Value new_regexp(VM& vm, ParsedRegex const& parsed_regex, DeprecatedString const& pattern, DeprecatedString const& flags)
  336. {
  337. // 1. Let pattern be CodePointsToString(BodyText of RegularExpressionLiteral).
  338. // 2. Let flags be CodePointsToString(FlagText of RegularExpressionLiteral).
  339. // 3. Return ! RegExpCreate(pattern, flags).
  340. auto& realm = *vm.current_realm();
  341. Regex<ECMA262> regex(parsed_regex.regex, parsed_regex.pattern, parsed_regex.flags);
  342. // NOTE: We bypass RegExpCreate and subsequently RegExpAlloc as an optimization to use the already parsed values.
  343. auto regexp_object = RegExpObject::create(realm, move(regex), pattern, flags);
  344. // RegExpAlloc has these two steps from the 'Legacy RegExp features' proposal.
  345. regexp_object->set_realm(realm);
  346. // We don't need to check 'If SameValue(newTarget, thisRealm.[[Intrinsics]].[[%RegExp%]]) is true'
  347. // here as we know RegExpCreate calls RegExpAlloc with %RegExp% for newTarget.
  348. regexp_object->set_legacy_features_enabled(true);
  349. return regexp_object;
  350. }
  351. // 13.3.8.1 https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  352. MarkedVector<Value> argument_list_evaluation(VM& vm, Value arguments)
  353. {
  354. // Note: Any spreading and actual evaluation is handled in preceding opcodes
  355. // Note: The spec uses the concept of a list, while we create a temporary array
  356. // in the preceding opcodes, so we have to convert in a manner that is not
  357. // visible to the user
  358. MarkedVector<Value> argument_values { vm.heap() };
  359. auto& argument_array = arguments.as_array();
  360. auto array_length = argument_array.indexed_properties().array_like_size();
  361. argument_values.ensure_capacity(array_length);
  362. for (size_t i = 0; i < array_length; ++i) {
  363. if (auto maybe_value = argument_array.indexed_properties().get(i); maybe_value.has_value())
  364. argument_values.append(maybe_value.release_value().value);
  365. else
  366. argument_values.append(js_undefined());
  367. }
  368. return argument_values;
  369. }
  370. ThrowCompletionOr<void> create_variable(VM& vm, DeprecatedFlyString const& name, Op::EnvironmentMode mode, bool is_global, bool is_immutable, bool is_strict)
  371. {
  372. if (mode == Op::EnvironmentMode::Lexical) {
  373. VERIFY(!is_global);
  374. // Note: This is papering over an issue where "FunctionDeclarationInstantiation" creates these bindings for us.
  375. // Instead of crashing in there, we'll just raise an exception here.
  376. if (TRY(vm.lexical_environment()->has_binding(name)))
  377. return vm.throw_completion<InternalError>(TRY_OR_THROW_OOM(vm, String::formatted("Lexical environment already has binding '{}'", name)));
  378. if (is_immutable)
  379. return vm.lexical_environment()->create_immutable_binding(vm, name, is_strict);
  380. return vm.lexical_environment()->create_mutable_binding(vm, name, is_strict);
  381. }
  382. if (!is_global) {
  383. if (is_immutable)
  384. return vm.variable_environment()->create_immutable_binding(vm, name, is_strict);
  385. return vm.variable_environment()->create_mutable_binding(vm, name, is_strict);
  386. }
  387. // NOTE: CreateVariable with m_is_global set to true is expected to only be used in GlobalDeclarationInstantiation currently, which only uses "false" for "can_be_deleted".
  388. // The only area that sets "can_be_deleted" to true is EvalDeclarationInstantiation, which is currently fully implemented in C++ and not in Bytecode.
  389. return verify_cast<GlobalEnvironment>(vm.variable_environment())->create_global_var_binding(name, false);
  390. }
  391. ThrowCompletionOr<ECMAScriptFunctionObject*> new_class(VM& vm, Value super_class, ClassExpression const& class_expression, Optional<IdentifierTableIndex> const& lhs_name)
  392. {
  393. auto& interpreter = vm.bytecode_interpreter();
  394. auto name = class_expression.name();
  395. // NOTE: NewClass expects classEnv to be active lexical environment
  396. auto* class_environment = vm.lexical_environment();
  397. vm.running_execution_context().lexical_environment = interpreter.saved_lexical_environment_stack().take_last();
  398. DeprecatedFlyString binding_name;
  399. DeprecatedFlyString class_name;
  400. if (!class_expression.has_name() && lhs_name.has_value()) {
  401. class_name = interpreter.current_executable().get_identifier(lhs_name.value());
  402. } else {
  403. binding_name = name;
  404. class_name = name.is_null() ? ""sv : name;
  405. }
  406. return TRY(class_expression.create_class_constructor(vm, class_environment, vm.lexical_environment(), super_class, binding_name, class_name));
  407. }
  408. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  409. ThrowCompletionOr<NonnullGCPtr<Object>> super_call_with_argument_array(VM& vm, Value argument_array, bool is_synthetic)
  410. {
  411. // 1. Let newTarget be GetNewTarget().
  412. auto new_target = vm.get_new_target();
  413. // 2. Assert: Type(newTarget) is Object.
  414. VERIFY(new_target.is_object());
  415. // 3. Let func be GetSuperConstructor().
  416. auto* func = get_super_constructor(vm);
  417. // 4. Let argList be ? ArgumentListEvaluation of Arguments.
  418. MarkedVector<Value> arg_list { vm.heap() };
  419. if (is_synthetic) {
  420. VERIFY(argument_array.is_object() && is<Array>(argument_array.as_object()));
  421. auto const& array_value = static_cast<Array const&>(argument_array.as_object());
  422. auto length = MUST(length_of_array_like(vm, array_value));
  423. for (size_t i = 0; i < length; ++i)
  424. arg_list.append(array_value.get_without_side_effects(PropertyKey { i }));
  425. } else {
  426. arg_list = argument_list_evaluation(vm, argument_array);
  427. }
  428. // 5. If IsConstructor(func) is false, throw a TypeError exception.
  429. if (!Value(func).is_constructor())
  430. return vm.throw_completion<TypeError>(ErrorType::NotAConstructor, "Super constructor");
  431. // 6. Let result be ? Construct(func, argList, newTarget).
  432. auto result = TRY(construct(vm, static_cast<FunctionObject&>(*func), move(arg_list), &new_target.as_function()));
  433. // 7. Let thisER be GetThisEnvironment().
  434. auto& this_environment = verify_cast<FunctionEnvironment>(*get_this_environment(vm));
  435. // 8. Perform ? thisER.BindThisValue(result).
  436. TRY(this_environment.bind_this_value(vm, result));
  437. // 9. Let F be thisER.[[FunctionObject]].
  438. auto& f = this_environment.function_object();
  439. // 10. Assert: F is an ECMAScript function object.
  440. // NOTE: This is implied by the strong C++ type.
  441. // 11. Perform ? InitializeInstanceElements(result, F).
  442. TRY(result->initialize_instance_elements(f));
  443. // 12. Return result.
  444. return result;
  445. }
  446. // FIXME: Since the accumulator is a Value, we store an object there and have to convert back and forth between that an Iterator records. Not great.
  447. // Make sure to put this into the accumulator before the iterator object disappears from the stack to prevent the members from being GC'd.
  448. Object* iterator_to_object(VM& vm, IteratorRecord iterator)
  449. {
  450. auto& realm = *vm.current_realm();
  451. auto object = Object::create(realm, nullptr);
  452. object->define_direct_property(vm.names.iterator, iterator.iterator, 0);
  453. object->define_direct_property(vm.names.next, iterator.next_method, 0);
  454. object->define_direct_property(vm.names.done, Value(iterator.done), 0);
  455. return object;
  456. }
  457. IteratorRecord object_to_iterator(VM& vm, Object& object)
  458. {
  459. return IteratorRecord {
  460. .iterator = &MUST(object.get(vm.names.iterator)).as_object(),
  461. .next_method = MUST(object.get(vm.names.next)),
  462. .done = MUST(object.get(vm.names.done)).as_bool()
  463. };
  464. }
  465. ThrowCompletionOr<NonnullGCPtr<Array>> iterator_to_array(VM& vm, Value iterator)
  466. {
  467. auto iterator_object = TRY(iterator.to_object(vm));
  468. auto iterator_record = object_to_iterator(vm, iterator_object);
  469. auto array = MUST(Array::create(*vm.current_realm(), 0));
  470. size_t index = 0;
  471. while (true) {
  472. auto iterator_result = TRY(iterator_next(vm, iterator_record));
  473. auto complete = TRY(iterator_complete(vm, iterator_result));
  474. if (complete)
  475. return array;
  476. auto value = TRY(iterator_value(vm, iterator_result));
  477. MUST(array->create_data_property_or_throw(index, value));
  478. index++;
  479. }
  480. }
  481. ThrowCompletionOr<void> append(VM& vm, Value lhs, Value rhs, bool is_spread)
  482. {
  483. // Note: This OpCode is used to construct array literals and argument arrays for calls,
  484. // containing at least one spread element,
  485. // Iterating over such a spread element to unpack it has to be visible by
  486. // the user courtesy of
  487. // (1) https://tc39.es/ecma262/#sec-runtime-semantics-arrayaccumulation
  488. // SpreadElement : ... AssignmentExpression
  489. // 1. Let spreadRef be ? Evaluation of AssignmentExpression.
  490. // 2. Let spreadObj be ? GetValue(spreadRef).
  491. // 3. Let iteratorRecord be ? GetIterator(spreadObj).
  492. // 4. Repeat,
  493. // a. Let next be ? IteratorStep(iteratorRecord).
  494. // b. If next is false, return nextIndex.
  495. // c. Let nextValue be ? IteratorValue(next).
  496. // d. Perform ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), nextValue).
  497. // e. Set nextIndex to nextIndex + 1.
  498. // (2) https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  499. // ArgumentList : ... AssignmentExpression
  500. // 1. Let list be a new empty List.
  501. // 2. Let spreadRef be ? Evaluation of AssignmentExpression.
  502. // 3. Let spreadObj be ? GetValue(spreadRef).
  503. // 4. Let iteratorRecord be ? GetIterator(spreadObj).
  504. // 5. Repeat,
  505. // a. Let next be ? IteratorStep(iteratorRecord).
  506. // b. If next is false, return list.
  507. // c. Let nextArg be ? IteratorValue(next).
  508. // d. Append nextArg to list.
  509. // ArgumentList : ArgumentList , ... AssignmentExpression
  510. // 1. Let precedingArgs be ? ArgumentListEvaluation of ArgumentList.
  511. // 2. Let spreadRef be ? Evaluation of AssignmentExpression.
  512. // 3. Let iteratorRecord be ? GetIterator(? GetValue(spreadRef)).
  513. // 4. Repeat,
  514. // a. Let next be ? IteratorStep(iteratorRecord).
  515. // b. If next is false, return precedingArgs.
  516. // c. Let nextArg be ? IteratorValue(next).
  517. // d. Append nextArg to precedingArgs.
  518. // Note: We know from codegen, that lhs is a plain array with only indexed properties
  519. auto& lhs_array = lhs.as_array();
  520. auto lhs_size = lhs_array.indexed_properties().array_like_size();
  521. if (is_spread) {
  522. // ...rhs
  523. size_t i = lhs_size;
  524. TRY(get_iterator_values(vm, rhs, [&i, &lhs_array](Value iterator_value) -> Optional<Completion> {
  525. lhs_array.indexed_properties().put(i, iterator_value, default_attributes);
  526. ++i;
  527. return {};
  528. }));
  529. } else {
  530. lhs_array.indexed_properties().put(lhs_size, rhs, default_attributes);
  531. }
  532. return {};
  533. }
  534. ThrowCompletionOr<Value> delete_by_id(Bytecode::Interpreter& interpreter, Value base, IdentifierTableIndex property)
  535. {
  536. auto& vm = interpreter.vm();
  537. auto const& identifier = interpreter.current_executable().get_identifier(property);
  538. bool strict = vm.in_strict_mode();
  539. auto reference = Reference { base, identifier, {}, strict };
  540. return TRY(reference.delete_(vm));
  541. }
  542. ThrowCompletionOr<Value> delete_by_value(Bytecode::Interpreter& interpreter, Value base, Value property_key_value)
  543. {
  544. auto& vm = interpreter.vm();
  545. auto property_key = TRY(property_key_value.to_property_key(vm));
  546. bool strict = vm.in_strict_mode();
  547. auto reference = Reference { base, property_key, {}, strict };
  548. return Value(TRY(reference.delete_(vm)));
  549. }
  550. ThrowCompletionOr<Value> delete_by_value_with_this(Bytecode::Interpreter& interpreter, Value base, Value property_key_value, Value this_value)
  551. {
  552. auto& vm = interpreter.vm();
  553. auto property_key = TRY(property_key_value.to_property_key(vm));
  554. bool strict = vm.in_strict_mode();
  555. auto reference = Reference { base, property_key, this_value, strict };
  556. return Value(TRY(reference.delete_(vm)));
  557. }
  558. // 14.7.5.9 EnumerateObjectProperties ( O ), https://tc39.es/ecma262/#sec-enumerate-object-properties
  559. ThrowCompletionOr<Object*> get_object_property_iterator(VM& vm, Value value)
  560. {
  561. // While the spec does provide an algorithm, it allows us to implement it ourselves so long as we meet the following invariants:
  562. // 1- Returned property keys do not include keys that are Symbols
  563. // 2- Properties of the target object may be deleted during enumeration. A property that is deleted before it is processed by the iterator's next method is ignored
  564. // 3- If new properties are added to the target object during enumeration, the newly added properties are not guaranteed to be processed in the active enumeration
  565. // 4- A property name will be returned by the iterator's next method at most once in any enumeration.
  566. // 5- Enumerating the properties of the target object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively;
  567. // but a property of a prototype is not processed if it has the same name as a property that has already been processed by the iterator's next method.
  568. // 6- The values of [[Enumerable]] attributes are not considered when determining if a property of a prototype object has already been processed.
  569. // 7- The enumerable property names of prototype objects must be obtained by invoking EnumerateObjectProperties passing the prototype object as the argument.
  570. // 8- EnumerateObjectProperties must obtain the own property keys of the target object by calling its [[OwnPropertyKeys]] internal method.
  571. // 9- Property attributes of the target object must be obtained by calling its [[GetOwnProperty]] internal method
  572. // Invariant 3 effectively allows the implementation to ignore newly added keys, and we do so (similar to other implementations).
  573. auto object = TRY(value.to_object(vm));
  574. // Note: While the spec doesn't explicitly require these to be ordered, it says that the values should be retrieved via OwnPropertyKeys,
  575. // so we just keep the order consistent anyway.
  576. OrderedHashTable<PropertyKey> properties;
  577. OrderedHashTable<PropertyKey> non_enumerable_properties;
  578. HashTable<NonnullGCPtr<Object>> seen_objects;
  579. // Collect all keys immediately (invariant no. 5)
  580. for (auto object_to_check = GCPtr { object.ptr() }; object_to_check && !seen_objects.contains(*object_to_check); object_to_check = TRY(object_to_check->internal_get_prototype_of())) {
  581. seen_objects.set(*object_to_check);
  582. for (auto& key : TRY(object_to_check->internal_own_property_keys())) {
  583. if (key.is_symbol())
  584. continue;
  585. auto property_key = TRY(PropertyKey::from_value(vm, key));
  586. // If there is a non-enumerable property higher up the prototype chain with the same key,
  587. // we mustn't include this property even if it's enumerable (invariant no. 5 and 6)
  588. if (non_enumerable_properties.contains(property_key))
  589. continue;
  590. if (properties.contains(property_key))
  591. continue;
  592. auto descriptor = TRY(object_to_check->internal_get_own_property(property_key));
  593. if (!*descriptor->enumerable)
  594. non_enumerable_properties.set(move(property_key));
  595. else
  596. properties.set(move(property_key));
  597. }
  598. }
  599. IteratorRecord iterator {
  600. .iterator = object,
  601. .next_method = NativeFunction::create(
  602. *vm.current_realm(),
  603. [items = move(properties)](VM& vm) mutable -> ThrowCompletionOr<Value> {
  604. auto& realm = *vm.current_realm();
  605. auto iterated_object_value = vm.this_value();
  606. if (!iterated_object_value.is_object())
  607. return vm.throw_completion<InternalError>("Invalid state for GetObjectPropertyIterator.next"sv);
  608. auto& iterated_object = iterated_object_value.as_object();
  609. auto result_object = Object::create(realm, nullptr);
  610. while (true) {
  611. if (items.is_empty()) {
  612. result_object->define_direct_property(vm.names.done, JS::Value(true), default_attributes);
  613. return result_object;
  614. }
  615. auto key = items.take_first();
  616. // If the property is deleted, don't include it (invariant no. 2)
  617. if (!TRY(iterated_object.has_property(key)))
  618. continue;
  619. result_object->define_direct_property(vm.names.done, JS::Value(false), default_attributes);
  620. if (key.is_number())
  621. result_object->define_direct_property(vm.names.value, PrimitiveString::create(vm, TRY_OR_THROW_OOM(vm, String::number(key.as_number()))), default_attributes);
  622. else if (key.is_string())
  623. result_object->define_direct_property(vm.names.value, PrimitiveString::create(vm, key.as_string()), default_attributes);
  624. else
  625. VERIFY_NOT_REACHED(); // We should not have non-string/number keys.
  626. return result_object;
  627. }
  628. },
  629. 1,
  630. vm.names.next),
  631. .done = false,
  632. };
  633. return iterator_to_object(vm, move(iterator));
  634. }
  635. }