CommonImplementations.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. namespace JS::Bytecode {
  14. ThrowCompletionOr<NonnullGCPtr<Object>> base_object_for_get(Bytecode::Interpreter& interpreter, Value base_value)
  15. {
  16. auto& vm = interpreter.vm();
  17. if (base_value.is_object())
  18. return base_value.as_object();
  19. // OPTIMIZATION: For various primitives we can avoid actually creating a new object for them.
  20. if (base_value.is_string())
  21. return vm.current_realm()->intrinsics().string_prototype();
  22. if (base_value.is_number())
  23. return vm.current_realm()->intrinsics().number_prototype();
  24. if (base_value.is_boolean())
  25. return vm.current_realm()->intrinsics().boolean_prototype();
  26. return base_value.to_object(vm);
  27. }
  28. ThrowCompletionOr<Value> get_by_id(Bytecode::Interpreter& interpreter, IdentifierTableIndex property, Value base_value, Value this_value, u32 cache_index)
  29. {
  30. auto& vm = interpreter.vm();
  31. auto const& name = interpreter.current_executable().get_identifier(property);
  32. auto& cache = interpreter.current_executable().property_lookup_caches[cache_index];
  33. if (base_value.is_string()) {
  34. auto string_value = TRY(base_value.as_string().get(vm, name));
  35. if (string_value.has_value())
  36. return *string_value;
  37. }
  38. auto base_obj = TRY(base_object_for_get(interpreter, base_value));
  39. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  40. // NOTE: Unique shapes don't change identity, so we compare their serial numbers instead.
  41. auto& shape = base_obj->shape();
  42. if (&shape == cache.shape
  43. && (!shape.is_unique() || shape.unique_shape_serial_number() == cache.unique_shape_serial_number)) {
  44. return base_obj->get_direct(cache.property_offset.value());
  45. }
  46. CacheablePropertyMetadata cacheable_metadata;
  47. auto value = TRY(base_obj->internal_get(name, this_value, &cacheable_metadata));
  48. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  49. cache.shape = shape;
  50. cache.property_offset = cacheable_metadata.property_offset.value();
  51. cache.unique_shape_serial_number = shape.unique_shape_serial_number();
  52. }
  53. return value;
  54. }
  55. ThrowCompletionOr<Value> get_by_value(Bytecode::Interpreter& interpreter, Value base_value, Value property_key_value)
  56. {
  57. auto& vm = interpreter.vm();
  58. auto object = TRY(base_object_for_get(interpreter, base_value));
  59. // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects.
  60. if (property_key_value.is_int32()
  61. && property_key_value.as_i32() >= 0
  62. && !object->may_interfere_with_indexed_property_access()
  63. && object->indexed_properties().has_index(property_key_value.as_i32())) {
  64. auto value = object->indexed_properties().get(property_key_value.as_i32())->value;
  65. if (!value.is_accessor())
  66. return value;
  67. }
  68. auto property_key = TRY(property_key_value.to_property_key(vm));
  69. if (base_value.is_string()) {
  70. auto string_value = TRY(base_value.as_string().get(vm, property_key));
  71. if (string_value.has_value())
  72. return *string_value;
  73. }
  74. return TRY(object->internal_get(property_key, base_value));
  75. }
  76. ThrowCompletionOr<Value> get_global(Bytecode::Interpreter& interpreter, IdentifierTableIndex identifier, u32 cache_index)
  77. {
  78. auto& vm = interpreter.vm();
  79. auto& realm = *vm.current_realm();
  80. auto& cache = interpreter.current_executable().global_variable_caches[cache_index];
  81. auto& binding_object = realm.global_environment().object_record().binding_object();
  82. auto& declarative_record = realm.global_environment().declarative_record();
  83. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  84. // NOTE: Unique shapes don't change identity, so we compare their serial numbers instead.
  85. auto& shape = binding_object.shape();
  86. if (cache.environment_serial_number == declarative_record.environment_serial_number()
  87. && &shape == cache.shape
  88. && (!shape.is_unique() || shape.unique_shape_serial_number() == cache.unique_shape_serial_number)) {
  89. return binding_object.get_direct(cache.property_offset.value());
  90. }
  91. cache.environment_serial_number = declarative_record.environment_serial_number();
  92. auto const& name = interpreter.current_executable().get_identifier(identifier);
  93. if (vm.running_execution_context().script_or_module.has<NonnullGCPtr<Module>>()) {
  94. // NOTE: GetGlobal is used to access variables stored in the module environment and global environment.
  95. // The module environment is checked first since it precedes the global environment in the environment chain.
  96. auto& module_environment = *vm.running_execution_context().script_or_module.get<NonnullGCPtr<Module>>()->environment();
  97. if (TRY(module_environment.has_binding(name))) {
  98. // TODO: Cache offset of binding value
  99. return TRY(module_environment.get_binding_value(vm, name, vm.in_strict_mode()));
  100. }
  101. }
  102. if (TRY(declarative_record.has_binding(name))) {
  103. // TODO: Cache offset of binding value
  104. return TRY(declarative_record.get_binding_value(vm, name, vm.in_strict_mode()));
  105. }
  106. if (TRY(binding_object.has_property(name))) {
  107. CacheablePropertyMetadata cacheable_metadata;
  108. auto value = TRY(binding_object.internal_get(name, js_undefined(), &cacheable_metadata));
  109. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  110. cache.shape = shape;
  111. cache.property_offset = cacheable_metadata.property_offset.value();
  112. cache.unique_shape_serial_number = shape.unique_shape_serial_number();
  113. }
  114. return value;
  115. }
  116. return vm.throw_completion<ReferenceError>(ErrorType::UnknownIdentifier, name);
  117. }
  118. ThrowCompletionOr<void> put_by_property_key(VM& vm, Value base, Value this_value, Value value, PropertyKey name, Op::PropertyKind kind)
  119. {
  120. auto object = TRY(base.to_object(vm));
  121. if (kind == Op::PropertyKind::Getter || kind == Op::PropertyKind::Setter) {
  122. // The generator should only pass us functions for getters and setters.
  123. VERIFY(value.is_function());
  124. }
  125. switch (kind) {
  126. case Op::PropertyKind::Getter: {
  127. auto& function = value.as_function();
  128. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  129. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(DeprecatedString::formatted("get {}", name));
  130. object->define_direct_accessor(name, &function, nullptr, Attribute::Configurable | Attribute::Enumerable);
  131. break;
  132. }
  133. case Op::PropertyKind::Setter: {
  134. auto& function = value.as_function();
  135. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  136. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(DeprecatedString::formatted("set {}", name));
  137. object->define_direct_accessor(name, nullptr, &function, Attribute::Configurable | Attribute::Enumerable);
  138. break;
  139. }
  140. case Op::PropertyKind::KeyValue: {
  141. bool succeeded = TRY(object->internal_set(name, value, this_value));
  142. if (!succeeded && vm.in_strict_mode())
  143. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, base.to_string_without_side_effects());
  144. break;
  145. }
  146. case Op::PropertyKind::DirectKeyValue:
  147. object->define_direct_property(name, value, Attribute::Enumerable | Attribute::Writable | Attribute::Configurable);
  148. break;
  149. case Op::PropertyKind::Spread:
  150. TRY(object->copy_data_properties(vm, value, {}));
  151. break;
  152. case Op::PropertyKind::ProtoSetter:
  153. if (value.is_object() || value.is_null())
  154. MUST(object->internal_set_prototype_of(value.is_object() ? &value.as_object() : nullptr));
  155. break;
  156. }
  157. return {};
  158. }
  159. ThrowCompletionOr<Value> perform_call(Interpreter& interpreter, Value this_value, Op::CallType call_type, Value callee, MarkedVector<Value> argument_values)
  160. {
  161. auto& vm = interpreter.vm();
  162. auto& function = callee.as_function();
  163. Value return_value;
  164. if (call_type == Op::CallType::DirectEval) {
  165. if (callee == interpreter.realm().intrinsics().eval_function())
  166. 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));
  167. else
  168. return_value = TRY(JS::call(vm, function, this_value, move(argument_values)));
  169. } else if (call_type == Op::CallType::Call)
  170. return_value = TRY(JS::call(vm, function, this_value, move(argument_values)));
  171. else
  172. return_value = TRY(construct(vm, function, move(argument_values)));
  173. return return_value;
  174. }
  175. static Completion throw_type_error_for_callee(Bytecode::Interpreter& interpreter, auto& call, StringView callee_type)
  176. {
  177. auto& vm = interpreter.vm();
  178. auto callee = interpreter.reg(call.callee());
  179. if (call.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(call.expression_string()->value()));
  181. return vm.throw_completion<TypeError>(ErrorType::IsNotA, callee.to_string_without_side_effects(), callee_type);
  182. }
  183. template<typename InstructionType>
  184. ThrowCompletionOr<void> throw_if_needed_for_call(Interpreter& interpreter, InstructionType const& call, Value callee)
  185. {
  186. if (call.call_type() == Op::CallType::Call && !callee.is_function())
  187. return throw_type_error_for_callee(interpreter, call, "function"sv);
  188. if (call.call_type() == Op::CallType::Construct && !callee.is_constructor())
  189. return throw_type_error_for_callee(interpreter, call, "constructor"sv);
  190. return {};
  191. }
  192. template ThrowCompletionOr<void> throw_if_needed_for_call(Interpreter&, Op::Call const&, Value);
  193. template ThrowCompletionOr<void> throw_if_needed_for_call(Interpreter&, Op::CallWithArgumentArray const&, Value);
  194. ThrowCompletionOr<Value> typeof_variable(VM& vm, DeprecatedFlyString const& string)
  195. {
  196. // 1. Let val be the result of evaluating UnaryExpression.
  197. auto reference = TRY(vm.resolve_binding(string));
  198. // 2. If val is a Reference Record, then
  199. // a. If IsUnresolvableReference(val) is true, return "undefined".
  200. if (reference.is_unresolvable())
  201. return PrimitiveString::create(vm, "undefined"_string);
  202. // 3. Set val to ? GetValue(val).
  203. auto value = TRY(reference.get_value(vm));
  204. // 4. NOTE: This step is replaced in section B.3.6.3.
  205. // 5. Return a String according to Table 41.
  206. return PrimitiveString::create(vm, value.typeof());
  207. }
  208. ThrowCompletionOr<void> set_variable(
  209. VM& vm,
  210. DeprecatedFlyString const& name,
  211. Value value,
  212. Op::EnvironmentMode mode,
  213. Op::SetVariable::InitializationMode initialization_mode)
  214. {
  215. auto environment = mode == Op::EnvironmentMode::Lexical ? vm.running_execution_context().lexical_environment : vm.running_execution_context().variable_environment;
  216. auto reference = TRY(vm.resolve_binding(name, environment));
  217. switch (initialization_mode) {
  218. case Op::SetVariable::InitializationMode::Initialize:
  219. TRY(reference.initialize_referenced_binding(vm, value));
  220. break;
  221. case Op::SetVariable::InitializationMode::Set:
  222. TRY(reference.put_value(vm, value));
  223. break;
  224. }
  225. return {};
  226. }
  227. Value new_function(VM& vm, FunctionExpression const& function_node, Optional<IdentifierTableIndex> const& lhs_name, Optional<Register> const& home_object)
  228. {
  229. Value value;
  230. if (!function_node.has_name()) {
  231. DeprecatedFlyString name = {};
  232. if (lhs_name.has_value())
  233. name = vm.bytecode_interpreter().current_executable().get_identifier(lhs_name.value());
  234. value = function_node.instantiate_ordinary_function_expression(vm, name);
  235. } else {
  236. 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());
  237. }
  238. if (home_object.has_value()) {
  239. auto home_object_value = vm.bytecode_interpreter().reg(home_object.value());
  240. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(&home_object_value.as_object());
  241. }
  242. return value;
  243. }
  244. ThrowCompletionOr<void> put_by_value(VM& vm, Value base, Value property_key_value, Value value, Op::PropertyKind kind)
  245. {
  246. // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects.
  247. if (base.is_object() && property_key_value.is_int32() && property_key_value.as_i32() >= 0) {
  248. auto& object = base.as_object();
  249. auto* storage = object.indexed_properties().storage();
  250. auto index = static_cast<u32>(property_key_value.as_i32());
  251. if (storage
  252. && storage->is_simple_storage()
  253. && !object.may_interfere_with_indexed_property_access()
  254. && storage->has_index(index)) {
  255. auto existing_value = storage->get(index)->value;
  256. if (!existing_value.is_accessor()) {
  257. storage->put(index, value);
  258. return {};
  259. }
  260. }
  261. }
  262. auto property_key = kind != Op::PropertyKind::Spread ? TRY(property_key_value.to_property_key(vm)) : PropertyKey {};
  263. TRY(put_by_property_key(vm, base, base, value, property_key, kind));
  264. return {};
  265. }
  266. }