CommonImplementations.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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/GlobalEnvironment.h>
  13. #include <LibJS/Runtime/ObjectEnvironment.h>
  14. #include <LibJS/Runtime/RegExpObject.h>
  15. namespace JS::Bytecode {
  16. ThrowCompletionOr<NonnullGCPtr<Object>> base_object_for_get(Bytecode::Interpreter& interpreter, Value base_value)
  17. {
  18. auto& vm = interpreter.vm();
  19. if (base_value.is_object())
  20. return base_value.as_object();
  21. // OPTIMIZATION: For various primitives we can avoid actually creating a new object for them.
  22. if (base_value.is_string())
  23. return vm.current_realm()->intrinsics().string_prototype();
  24. if (base_value.is_number())
  25. return vm.current_realm()->intrinsics().number_prototype();
  26. if (base_value.is_boolean())
  27. return vm.current_realm()->intrinsics().boolean_prototype();
  28. return base_value.to_object(vm);
  29. }
  30. ThrowCompletionOr<Value> get_by_id(Bytecode::Interpreter& interpreter, IdentifierTableIndex property, Value base_value, Value this_value, u32 cache_index)
  31. {
  32. auto& vm = interpreter.vm();
  33. auto const& name = interpreter.current_executable().get_identifier(property);
  34. auto& cache = interpreter.current_executable().property_lookup_caches[cache_index];
  35. if (base_value.is_string()) {
  36. auto string_value = TRY(base_value.as_string().get(vm, name));
  37. if (string_value.has_value())
  38. return *string_value;
  39. }
  40. auto base_obj = TRY(base_object_for_get(interpreter, base_value));
  41. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  42. // NOTE: Unique shapes don't change identity, so we compare their serial numbers instead.
  43. auto& shape = base_obj->shape();
  44. if (&shape == cache.shape
  45. && (!shape.is_unique() || shape.unique_shape_serial_number() == cache.unique_shape_serial_number)) {
  46. return base_obj->get_direct(cache.property_offset.value());
  47. }
  48. CacheablePropertyMetadata cacheable_metadata;
  49. auto value = TRY(base_obj->internal_get(name, this_value, &cacheable_metadata));
  50. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  51. cache.shape = shape;
  52. cache.property_offset = cacheable_metadata.property_offset.value();
  53. cache.unique_shape_serial_number = shape.unique_shape_serial_number();
  54. }
  55. return value;
  56. }
  57. ThrowCompletionOr<Value> get_by_value(Bytecode::Interpreter& interpreter, Value base_value, Value property_key_value)
  58. {
  59. auto& vm = interpreter.vm();
  60. auto object = TRY(base_object_for_get(interpreter, base_value));
  61. // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects.
  62. if (property_key_value.is_int32()
  63. && property_key_value.as_i32() >= 0
  64. && !object->may_interfere_with_indexed_property_access()
  65. && object->indexed_properties().has_index(property_key_value.as_i32())) {
  66. auto value = object->indexed_properties().get(property_key_value.as_i32())->value;
  67. if (!value.is_accessor())
  68. return value;
  69. }
  70. auto property_key = TRY(property_key_value.to_property_key(vm));
  71. if (base_value.is_string()) {
  72. auto string_value = TRY(base_value.as_string().get(vm, property_key));
  73. if (string_value.has_value())
  74. return *string_value;
  75. }
  76. return TRY(object->internal_get(property_key, base_value));
  77. }
  78. ThrowCompletionOr<Value> get_global(Bytecode::Interpreter& interpreter, IdentifierTableIndex identifier, u32 cache_index)
  79. {
  80. auto& vm = interpreter.vm();
  81. auto& realm = *vm.current_realm();
  82. auto& cache = interpreter.current_executable().global_variable_caches[cache_index];
  83. auto& binding_object = realm.global_environment().object_record().binding_object();
  84. auto& declarative_record = realm.global_environment().declarative_record();
  85. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  86. // NOTE: Unique shapes don't change identity, so we compare their serial numbers instead.
  87. auto& shape = binding_object.shape();
  88. if (cache.environment_serial_number == declarative_record.environment_serial_number()
  89. && &shape == cache.shape
  90. && (!shape.is_unique() || shape.unique_shape_serial_number() == cache.unique_shape_serial_number)) {
  91. return binding_object.get_direct(cache.property_offset.value());
  92. }
  93. cache.environment_serial_number = declarative_record.environment_serial_number();
  94. auto const& name = interpreter.current_executable().get_identifier(identifier);
  95. if (vm.running_execution_context().script_or_module.has<NonnullGCPtr<Module>>()) {
  96. // NOTE: GetGlobal is used to access variables stored in the module environment and global environment.
  97. // The module environment is checked first since it precedes the global environment in the environment chain.
  98. auto& module_environment = *vm.running_execution_context().script_or_module.get<NonnullGCPtr<Module>>()->environment();
  99. if (TRY(module_environment.has_binding(name))) {
  100. // TODO: Cache offset of binding value
  101. return TRY(module_environment.get_binding_value(vm, name, vm.in_strict_mode()));
  102. }
  103. }
  104. if (TRY(declarative_record.has_binding(name))) {
  105. // TODO: Cache offset of binding value
  106. return TRY(declarative_record.get_binding_value(vm, name, vm.in_strict_mode()));
  107. }
  108. if (TRY(binding_object.has_property(name))) {
  109. CacheablePropertyMetadata cacheable_metadata;
  110. auto value = TRY(binding_object.internal_get(name, js_undefined(), &cacheable_metadata));
  111. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  112. cache.shape = shape;
  113. cache.property_offset = cacheable_metadata.property_offset.value();
  114. cache.unique_shape_serial_number = shape.unique_shape_serial_number();
  115. }
  116. return value;
  117. }
  118. return vm.throw_completion<ReferenceError>(ErrorType::UnknownIdentifier, name);
  119. }
  120. ThrowCompletionOr<void> put_by_property_key(VM& vm, Value base, Value this_value, Value value, PropertyKey name, Op::PropertyKind kind)
  121. {
  122. auto object = TRY(base.to_object(vm));
  123. if (kind == Op::PropertyKind::Getter || kind == Op::PropertyKind::Setter) {
  124. // The generator should only pass us functions for getters and setters.
  125. VERIFY(value.is_function());
  126. }
  127. switch (kind) {
  128. case Op::PropertyKind::Getter: {
  129. auto& function = value.as_function();
  130. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  131. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(DeprecatedString::formatted("get {}", name));
  132. object->define_direct_accessor(name, &function, nullptr, Attribute::Configurable | Attribute::Enumerable);
  133. break;
  134. }
  135. case Op::PropertyKind::Setter: {
  136. auto& function = value.as_function();
  137. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  138. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(DeprecatedString::formatted("set {}", name));
  139. object->define_direct_accessor(name, nullptr, &function, Attribute::Configurable | Attribute::Enumerable);
  140. break;
  141. }
  142. case Op::PropertyKind::KeyValue: {
  143. bool succeeded = TRY(object->internal_set(name, value, this_value));
  144. if (!succeeded && vm.in_strict_mode())
  145. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, base.to_string_without_side_effects());
  146. break;
  147. }
  148. case Op::PropertyKind::DirectKeyValue:
  149. object->define_direct_property(name, value, Attribute::Enumerable | Attribute::Writable | Attribute::Configurable);
  150. break;
  151. case Op::PropertyKind::Spread:
  152. TRY(object->copy_data_properties(vm, value, {}));
  153. break;
  154. case Op::PropertyKind::ProtoSetter:
  155. if (value.is_object() || value.is_null())
  156. MUST(object->internal_set_prototype_of(value.is_object() ? &value.as_object() : nullptr));
  157. break;
  158. }
  159. return {};
  160. }
  161. ThrowCompletionOr<Value> perform_call(Interpreter& interpreter, Value this_value, Op::CallType call_type, Value callee, MarkedVector<Value> argument_values)
  162. {
  163. auto& vm = interpreter.vm();
  164. auto& function = callee.as_function();
  165. Value return_value;
  166. if (call_type == Op::CallType::DirectEval) {
  167. if (callee == interpreter.realm().intrinsics().eval_function())
  168. 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));
  169. else
  170. return_value = TRY(JS::call(vm, function, this_value, move(argument_values)));
  171. } else if (call_type == Op::CallType::Call)
  172. return_value = TRY(JS::call(vm, function, this_value, move(argument_values)));
  173. else
  174. return_value = TRY(construct(vm, function, move(argument_values)));
  175. return return_value;
  176. }
  177. static Completion throw_type_error_for_callee(Bytecode::Interpreter& interpreter, Value callee, StringView callee_type, Optional<StringTableIndex> const& expression_string)
  178. {
  179. auto& vm = interpreter.vm();
  180. if (expression_string.has_value())
  181. return vm.throw_completion<TypeError>(ErrorType::IsNotAEvaluatedFrom, callee.to_string_without_side_effects(), callee_type, interpreter.current_executable().get_string(expression_string->value()));
  182. return vm.throw_completion<TypeError>(ErrorType::IsNotA, callee.to_string_without_side_effects(), callee_type);
  183. }
  184. ThrowCompletionOr<void> throw_if_needed_for_call(Interpreter& interpreter, Value callee, Op::CallType call_type, Optional<StringTableIndex> const& expression_string)
  185. {
  186. if (call_type == Op::CallType::Call && !callee.is_function())
  187. return throw_type_error_for_callee(interpreter, callee, "function"sv, expression_string);
  188. if (call_type == Op::CallType::Construct && !callee.is_constructor())
  189. return throw_type_error_for_callee(interpreter, callee, "constructor"sv, expression_string);
  190. return {};
  191. }
  192. ThrowCompletionOr<Value> typeof_variable(VM& vm, DeprecatedFlyString const& string)
  193. {
  194. // 1. Let val be the result of evaluating UnaryExpression.
  195. auto reference = TRY(vm.resolve_binding(string));
  196. // 2. If val is a Reference Record, then
  197. // a. If IsUnresolvableReference(val) is true, return "undefined".
  198. if (reference.is_unresolvable())
  199. return PrimitiveString::create(vm, "undefined"_string);
  200. // 3. Set val to ? GetValue(val).
  201. auto value = TRY(reference.get_value(vm));
  202. // 4. NOTE: This step is replaced in section B.3.6.3.
  203. // 5. Return a String according to Table 41.
  204. return PrimitiveString::create(vm, value.typeof());
  205. }
  206. ThrowCompletionOr<void> set_variable(
  207. VM& vm,
  208. DeprecatedFlyString const& name,
  209. Value value,
  210. Op::EnvironmentMode mode,
  211. Op::SetVariable::InitializationMode initialization_mode)
  212. {
  213. auto environment = mode == Op::EnvironmentMode::Lexical ? vm.running_execution_context().lexical_environment : vm.running_execution_context().variable_environment;
  214. auto reference = TRY(vm.resolve_binding(name, environment));
  215. switch (initialization_mode) {
  216. case Op::SetVariable::InitializationMode::Initialize:
  217. TRY(reference.initialize_referenced_binding(vm, value));
  218. break;
  219. case Op::SetVariable::InitializationMode::Set:
  220. TRY(reference.put_value(vm, value));
  221. break;
  222. }
  223. return {};
  224. }
  225. Value new_function(VM& vm, FunctionExpression const& function_node, Optional<IdentifierTableIndex> const& lhs_name, Optional<Register> const& home_object)
  226. {
  227. Value value;
  228. if (!function_node.has_name()) {
  229. DeprecatedFlyString name = {};
  230. if (lhs_name.has_value())
  231. name = vm.bytecode_interpreter().current_executable().get_identifier(lhs_name.value());
  232. value = function_node.instantiate_ordinary_function_expression(vm, name);
  233. } else {
  234. 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());
  235. }
  236. if (home_object.has_value()) {
  237. auto home_object_value = vm.bytecode_interpreter().reg(home_object.value());
  238. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(&home_object_value.as_object());
  239. }
  240. return value;
  241. }
  242. ThrowCompletionOr<void> put_by_value(VM& vm, Value base, Value property_key_value, Value value, Op::PropertyKind kind)
  243. {
  244. // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects.
  245. if (base.is_object() && property_key_value.is_int32() && property_key_value.as_i32() >= 0) {
  246. auto& object = base.as_object();
  247. auto* storage = object.indexed_properties().storage();
  248. auto index = static_cast<u32>(property_key_value.as_i32());
  249. if (storage
  250. && storage->is_simple_storage()
  251. && !object.may_interfere_with_indexed_property_access()
  252. && storage->has_index(index)) {
  253. auto existing_value = storage->get(index)->value;
  254. if (!existing_value.is_accessor()) {
  255. storage->put(index, value);
  256. return {};
  257. }
  258. }
  259. }
  260. auto property_key = kind != Op::PropertyKind::Spread ? TRY(property_key_value.to_property_key(vm)) : PropertyKey {};
  261. TRY(put_by_property_key(vm, base, base, value, property_key, kind));
  262. return {};
  263. }
  264. ThrowCompletionOr<Value> get_variable(Bytecode::Interpreter& interpreter, DeprecatedFlyString const& name, u32 cache_index)
  265. {
  266. auto& vm = interpreter.vm();
  267. auto& cached_environment_coordinate = interpreter.current_executable().environment_variable_caches[cache_index];
  268. if (cached_environment_coordinate.has_value()) {
  269. auto environment = vm.running_execution_context().lexical_environment;
  270. for (size_t i = 0; i < cached_environment_coordinate->hops; ++i)
  271. environment = environment->outer_environment();
  272. VERIFY(environment);
  273. VERIFY(environment->is_declarative_environment());
  274. if (!environment->is_permanently_screwed_by_eval()) {
  275. return TRY(verify_cast<DeclarativeEnvironment>(*environment).get_binding_value_direct(vm, cached_environment_coordinate.value().index, vm.in_strict_mode()));
  276. }
  277. cached_environment_coordinate = {};
  278. }
  279. auto reference = TRY(vm.resolve_binding(name));
  280. if (reference.environment_coordinate().has_value())
  281. cached_environment_coordinate = reference.environment_coordinate();
  282. return TRY(reference.get_value(vm));
  283. }
  284. ThrowCompletionOr<CalleeAndThis> get_callee_and_this_from_environment(Bytecode::Interpreter& interpreter, DeprecatedFlyString const& name, u32 cache_index)
  285. {
  286. auto& vm = interpreter.vm();
  287. Value callee = js_undefined();
  288. Value this_value = js_undefined();
  289. auto& cached_environment_coordinate = interpreter.current_executable().environment_variable_caches[cache_index];
  290. if (cached_environment_coordinate.has_value()) {
  291. auto environment = vm.running_execution_context().lexical_environment;
  292. for (size_t i = 0; i < cached_environment_coordinate->hops; ++i)
  293. environment = environment->outer_environment();
  294. VERIFY(environment);
  295. VERIFY(environment->is_declarative_environment());
  296. if (!environment->is_permanently_screwed_by_eval()) {
  297. callee = TRY(verify_cast<DeclarativeEnvironment>(*environment).get_binding_value_direct(vm, cached_environment_coordinate.value().index, vm.in_strict_mode()));
  298. this_value = js_undefined();
  299. if (auto base_object = environment->with_base_object())
  300. this_value = base_object;
  301. return CalleeAndThis {
  302. .callee = callee,
  303. .this_value = this_value,
  304. };
  305. }
  306. cached_environment_coordinate = {};
  307. }
  308. auto reference = TRY(vm.resolve_binding(name));
  309. if (reference.environment_coordinate().has_value())
  310. cached_environment_coordinate = reference.environment_coordinate();
  311. callee = TRY(reference.get_value(vm));
  312. if (reference.is_property_reference()) {
  313. this_value = reference.get_this_value();
  314. } else {
  315. if (reference.is_environment_reference()) {
  316. if (auto base_object = reference.base_environment().with_base_object(); base_object != nullptr)
  317. this_value = base_object;
  318. }
  319. }
  320. return CalleeAndThis {
  321. .callee = callee,
  322. .this_value = this_value,
  323. };
  324. }
  325. // 13.2.7.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation
  326. Value new_regexp(VM& vm, ParsedRegex const& parsed_regex, DeprecatedString const& pattern, DeprecatedString const& flags)
  327. {
  328. // 1. Let pattern be CodePointsToString(BodyText of RegularExpressionLiteral).
  329. // 2. Let flags be CodePointsToString(FlagText of RegularExpressionLiteral).
  330. // 3. Return ! RegExpCreate(pattern, flags).
  331. auto& realm = *vm.current_realm();
  332. Regex<ECMA262> regex(parsed_regex.regex, parsed_regex.pattern, parsed_regex.flags);
  333. // NOTE: We bypass RegExpCreate and subsequently RegExpAlloc as an optimization to use the already parsed values.
  334. auto regexp_object = RegExpObject::create(realm, move(regex), pattern, flags);
  335. // RegExpAlloc has these two steps from the 'Legacy RegExp features' proposal.
  336. regexp_object->set_realm(realm);
  337. // We don't need to check 'If SameValue(newTarget, thisRealm.[[Intrinsics]].[[%RegExp%]]) is true'
  338. // here as we know RegExpCreate calls RegExpAlloc with %RegExp% for newTarget.
  339. regexp_object->set_legacy_features_enabled(true);
  340. return regexp_object;
  341. }
  342. // 13.3.8.1 https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  343. MarkedVector<Value> argument_list_evaluation(Bytecode::Interpreter& interpreter)
  344. {
  345. // Note: Any spreading and actual evaluation is handled in preceding opcodes
  346. // Note: The spec uses the concept of a list, while we create a temporary array
  347. // in the preceding opcodes, so we have to convert in a manner that is not
  348. // visible to the user
  349. auto& vm = interpreter.vm();
  350. MarkedVector<Value> argument_values { vm.heap() };
  351. auto arguments = interpreter.accumulator();
  352. auto& argument_array = arguments.as_array();
  353. auto array_length = argument_array.indexed_properties().array_like_size();
  354. argument_values.ensure_capacity(array_length);
  355. for (size_t i = 0; i < array_length; ++i) {
  356. if (auto maybe_value = argument_array.indexed_properties().get(i); maybe_value.has_value())
  357. argument_values.append(maybe_value.release_value().value);
  358. else
  359. argument_values.append(js_undefined());
  360. }
  361. return argument_values;
  362. }
  363. ThrowCompletionOr<void> create_variable(VM& vm, DeprecatedFlyString const& name, Op::EnvironmentMode mode, bool is_global, bool is_immutable, bool is_strict)
  364. {
  365. if (mode == Op::EnvironmentMode::Lexical) {
  366. VERIFY(!is_global);
  367. // Note: This is papering over an issue where "FunctionDeclarationInstantiation" creates these bindings for us.
  368. // Instead of crashing in there, we'll just raise an exception here.
  369. if (TRY(vm.lexical_environment()->has_binding(name)))
  370. return vm.throw_completion<InternalError>(TRY_OR_THROW_OOM(vm, String::formatted("Lexical environment already has binding '{}'", name)));
  371. if (is_immutable)
  372. return vm.lexical_environment()->create_immutable_binding(vm, name, is_strict);
  373. return vm.lexical_environment()->create_mutable_binding(vm, name, is_strict);
  374. }
  375. if (!is_global) {
  376. if (is_immutable)
  377. return vm.variable_environment()->create_immutable_binding(vm, name, is_strict);
  378. return vm.variable_environment()->create_mutable_binding(vm, name, is_strict);
  379. }
  380. // 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".
  381. // The only area that sets "can_be_deleted" to true is EvalDeclarationInstantiation, which is currently fully implemented in C++ and not in Bytecode.
  382. return verify_cast<GlobalEnvironment>(vm.variable_environment())->create_global_var_binding(name, false);
  383. }
  384. ThrowCompletionOr<ECMAScriptFunctionObject*> new_class(VM& vm, ClassExpression const& class_expression, Optional<IdentifierTableIndex> const& lhs_name)
  385. {
  386. auto& interpreter = vm.bytecode_interpreter();
  387. auto name = class_expression.name();
  388. auto super_class = interpreter.accumulator();
  389. // NOTE: NewClass expects classEnv to be active lexical environment
  390. auto* class_environment = vm.lexical_environment();
  391. vm.running_execution_context().lexical_environment = interpreter.saved_lexical_environment_stack().take_last();
  392. DeprecatedFlyString binding_name;
  393. DeprecatedFlyString class_name;
  394. if (!class_expression.has_name() && lhs_name.has_value()) {
  395. class_name = interpreter.current_executable().get_identifier(lhs_name.value());
  396. } else {
  397. binding_name = name;
  398. class_name = name.is_null() ? ""sv : name;
  399. }
  400. return TRY(class_expression.create_class_constructor(vm, class_environment, vm.lexical_environment(), super_class, binding_name, class_name));
  401. }
  402. }