CommonImplementations.cpp 18 KB

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