CommonImplementations.h 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. /*
  2. * Copyright (c) 2021-2024, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibJS/Bytecode/CommonImplementations.h>
  8. #include <LibJS/Bytecode/Interpreter.h>
  9. #include <LibJS/Bytecode/Op.h>
  10. #include <LibJS/Runtime/Array.h>
  11. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  12. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  13. #include <LibJS/Runtime/FunctionEnvironment.h>
  14. #include <LibJS/Runtime/GlobalEnvironment.h>
  15. #include <LibJS/Runtime/NativeFunction.h>
  16. #include <LibJS/Runtime/ObjectEnvironment.h>
  17. #include <LibJS/Runtime/RegExpObject.h>
  18. #include <LibJS/Runtime/TypedArray.h>
  19. #include <LibJS/Runtime/ValueInlines.h>
  20. namespace JS::Bytecode {
  21. // NOTE: This function assumes that the index is valid within the TypedArray,
  22. // and that the TypedArray is not detached.
  23. template<typename T>
  24. inline Value fast_typed_array_get_element(TypedArrayBase& typed_array, u32 index)
  25. {
  26. Checked<u32> offset_into_array_buffer = index;
  27. offset_into_array_buffer *= sizeof(T);
  28. offset_into_array_buffer += typed_array.byte_offset();
  29. if (offset_into_array_buffer.has_overflow()) [[unlikely]] {
  30. return js_undefined();
  31. }
  32. auto const& array_buffer = *typed_array.viewed_array_buffer();
  33. auto const* slot = reinterpret_cast<T const*>(array_buffer.buffer().offset_pointer(offset_into_array_buffer.value()));
  34. return Value { *slot };
  35. }
  36. // NOTE: This function assumes that the index is valid within the TypedArray,
  37. // and that the TypedArray is not detached.
  38. template<typename T>
  39. inline void fast_typed_array_set_element(TypedArrayBase& typed_array, u32 index, T value)
  40. {
  41. Checked<u32> offset_into_array_buffer = index;
  42. offset_into_array_buffer *= sizeof(T);
  43. offset_into_array_buffer += typed_array.byte_offset();
  44. if (offset_into_array_buffer.has_overflow()) [[unlikely]] {
  45. return;
  46. }
  47. auto& array_buffer = *typed_array.viewed_array_buffer();
  48. auto* slot = reinterpret_cast<T*>(array_buffer.buffer().offset_pointer(offset_into_array_buffer.value()));
  49. *slot = value;
  50. }
  51. template<typename BaseType, typename PropertyType>
  52. ALWAYS_INLINE Completion throw_null_or_undefined_property_access(VM& vm, Value base_value, BaseType const& base_identifier, PropertyType const& property_identifier)
  53. {
  54. VERIFY(base_value.is_nullish());
  55. bool has_base_identifier = true;
  56. bool has_property_identifier = true;
  57. if constexpr (requires { base_identifier.has_value(); })
  58. has_base_identifier = base_identifier.has_value();
  59. if constexpr (requires { property_identifier.has_value(); })
  60. has_property_identifier = property_identifier.has_value();
  61. if (has_base_identifier && has_property_identifier)
  62. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefinedWithPropertyAndName, property_identifier, base_value, base_identifier);
  63. if (has_property_identifier)
  64. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefinedWithProperty, property_identifier, base_value);
  65. if (has_base_identifier)
  66. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefinedWithName, base_identifier, base_value);
  67. return vm.throw_completion<TypeError>(ErrorType::ToObjectNullOrUndefined);
  68. }
  69. template<typename BaseType, typename PropertyType>
  70. ALWAYS_INLINE ThrowCompletionOr<NonnullGCPtr<Object>> base_object_for_get(VM& vm, Value base_value, BaseType const& base_identifier, PropertyType property_identifier)
  71. {
  72. if (base_value.is_object()) [[likely]]
  73. return base_value.as_object();
  74. // OPTIMIZATION: For various primitives we can avoid actually creating a new object for them.
  75. auto& realm = *vm.current_realm();
  76. if (base_value.is_string())
  77. return realm.intrinsics().string_prototype();
  78. if (base_value.is_number())
  79. return realm.intrinsics().number_prototype();
  80. if (base_value.is_boolean())
  81. return realm.intrinsics().boolean_prototype();
  82. if (base_value.is_bigint())
  83. return realm.intrinsics().bigint_prototype();
  84. if (base_value.is_symbol())
  85. return realm.intrinsics().symbol_prototype();
  86. // NOTE: At this point this is guaranteed to throw (null or undefined).
  87. return throw_null_or_undefined_property_access(vm, base_value, base_identifier, property_identifier);
  88. }
  89. inline ThrowCompletionOr<Value> get_by_id(VM& vm, Optional<DeprecatedFlyString const&> const& base_identifier, DeprecatedFlyString const& property, Value base_value, Value this_value, PropertyLookupCache& cache)
  90. {
  91. if (base_value.is_string()) {
  92. auto string_value = TRY(base_value.as_string().get(vm, property));
  93. if (string_value.has_value())
  94. return *string_value;
  95. }
  96. auto base_obj = TRY(base_object_for_get(vm, base_value, base_identifier, property));
  97. // OPTIMIZATION: Fast path for the magical "length" property on Array objects.
  98. if (base_obj->has_magical_length_property() && property == vm.names.length.as_string()) {
  99. return Value { base_obj->indexed_properties().array_like_size() };
  100. }
  101. auto& shape = base_obj->shape();
  102. if (cache.prototype) {
  103. // OPTIMIZATION: If the prototype chain hasn't been mutated in a way that would invalidate the cache, we can use it.
  104. bool can_use_cache = [&]() -> bool {
  105. if (&shape != cache.shape)
  106. return false;
  107. if (!cache.prototype_chain_validity)
  108. return false;
  109. if (!cache.prototype_chain_validity->is_valid())
  110. return false;
  111. return true;
  112. }();
  113. if (can_use_cache)
  114. return cache.prototype->get_direct(cache.property_offset.value());
  115. } else if (&shape == cache.shape) {
  116. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  117. return base_obj->get_direct(cache.property_offset.value());
  118. }
  119. CacheablePropertyMetadata cacheable_metadata;
  120. auto value = TRY(base_obj->internal_get(property, this_value, &cacheable_metadata));
  121. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  122. cache = {};
  123. cache.shape = shape;
  124. cache.property_offset = cacheable_metadata.property_offset.value();
  125. } else if (cacheable_metadata.type == CacheablePropertyMetadata::Type::InPrototypeChain) {
  126. cache = {};
  127. cache.shape = &base_obj->shape();
  128. cache.property_offset = cacheable_metadata.property_offset.value();
  129. cache.prototype = *cacheable_metadata.prototype;
  130. cache.prototype_chain_validity = *cacheable_metadata.prototype->shape().prototype_chain_validity();
  131. }
  132. return value;
  133. }
  134. inline ThrowCompletionOr<Value> get_by_value(VM& vm, Optional<DeprecatedFlyString const&> const& base_identifier, Value base_value, Value property_key_value)
  135. {
  136. // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects.
  137. if (base_value.is_object() && property_key_value.is_int32() && property_key_value.as_i32() >= 0) {
  138. auto& object = base_value.as_object();
  139. auto index = static_cast<u32>(property_key_value.as_i32());
  140. auto const* object_storage = object.indexed_properties().storage();
  141. // For "non-typed arrays":
  142. if (!object.may_interfere_with_indexed_property_access()
  143. && object_storage) {
  144. auto maybe_value = [&] {
  145. if (object_storage->is_simple_storage())
  146. return static_cast<SimpleIndexedPropertyStorage const*>(object_storage)->inline_get(index);
  147. else
  148. return static_cast<GenericIndexedPropertyStorage const*>(object_storage)->get(index);
  149. }();
  150. if (maybe_value.has_value()) {
  151. auto value = maybe_value->value;
  152. if (!value.is_accessor())
  153. return value;
  154. }
  155. }
  156. // For typed arrays:
  157. if (object.is_typed_array()) {
  158. auto& typed_array = static_cast<TypedArrayBase&>(object);
  159. auto canonical_index = CanonicalIndex { CanonicalIndex::Type::Index, index };
  160. if (is_valid_integer_index(typed_array, canonical_index)) {
  161. switch (typed_array.kind()) {
  162. case TypedArrayBase::Kind::Uint8Array:
  163. return fast_typed_array_get_element<u8>(typed_array, index);
  164. case TypedArrayBase::Kind::Uint16Array:
  165. return fast_typed_array_get_element<u16>(typed_array, index);
  166. case TypedArrayBase::Kind::Uint32Array:
  167. return fast_typed_array_get_element<u32>(typed_array, index);
  168. case TypedArrayBase::Kind::Int8Array:
  169. return fast_typed_array_get_element<i8>(typed_array, index);
  170. case TypedArrayBase::Kind::Int16Array:
  171. return fast_typed_array_get_element<i16>(typed_array, index);
  172. case TypedArrayBase::Kind::Int32Array:
  173. return fast_typed_array_get_element<i32>(typed_array, index);
  174. case TypedArrayBase::Kind::Uint8ClampedArray:
  175. return fast_typed_array_get_element<u8>(typed_array, index);
  176. default:
  177. // FIXME: Support more TypedArray kinds.
  178. break;
  179. }
  180. }
  181. switch (typed_array.kind()) {
  182. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  183. case TypedArrayBase::Kind::ClassName: \
  184. return typed_array_get_element<Type>(typed_array, canonical_index);
  185. JS_ENUMERATE_TYPED_ARRAYS
  186. #undef __JS_ENUMERATE
  187. }
  188. }
  189. }
  190. auto object = TRY(base_object_for_get(vm, base_value, base_identifier, property_key_value));
  191. auto property_key = TRY(property_key_value.to_property_key(vm));
  192. if (base_value.is_string()) {
  193. auto string_value = TRY(base_value.as_string().get(vm, property_key));
  194. if (string_value.has_value())
  195. return *string_value;
  196. }
  197. return TRY(object->internal_get(property_key, base_value));
  198. }
  199. inline ThrowCompletionOr<Value> get_global(Interpreter& interpreter, IdentifierTableIndex identifier_index, GlobalVariableCache& cache)
  200. {
  201. auto& vm = interpreter.vm();
  202. auto& binding_object = interpreter.global_object();
  203. auto& declarative_record = interpreter.global_declarative_environment();
  204. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  205. auto& shape = binding_object.shape();
  206. if (cache.environment_serial_number == declarative_record.environment_serial_number()
  207. && &shape == cache.shape) {
  208. return binding_object.get_direct(cache.property_offset.value());
  209. }
  210. cache.environment_serial_number = declarative_record.environment_serial_number();
  211. auto& identifier = interpreter.current_executable().get_identifier(identifier_index);
  212. if (vm.running_execution_context().script_or_module.has<NonnullGCPtr<Module>>()) {
  213. // NOTE: GetGlobal is used to access variables stored in the module environment and global environment.
  214. // The module environment is checked first since it precedes the global environment in the environment chain.
  215. auto& module_environment = *vm.running_execution_context().script_or_module.get<NonnullGCPtr<Module>>()->environment();
  216. if (TRY(module_environment.has_binding(identifier))) {
  217. // TODO: Cache offset of binding value
  218. return TRY(module_environment.get_binding_value(vm, identifier, vm.in_strict_mode()));
  219. }
  220. }
  221. if (TRY(declarative_record.has_binding(identifier))) {
  222. // TODO: Cache offset of binding value
  223. return TRY(declarative_record.get_binding_value(vm, identifier, vm.in_strict_mode()));
  224. }
  225. if (TRY(binding_object.has_property(identifier))) {
  226. CacheablePropertyMetadata cacheable_metadata;
  227. auto value = TRY(binding_object.internal_get(identifier, js_undefined(), &cacheable_metadata));
  228. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  229. cache.shape = shape;
  230. cache.property_offset = cacheable_metadata.property_offset.value();
  231. }
  232. return value;
  233. }
  234. return vm.throw_completion<ReferenceError>(ErrorType::UnknownIdentifier, identifier);
  235. }
  236. inline ThrowCompletionOr<void> put_by_property_key(VM& vm, Value base, Value this_value, Value value, Optional<DeprecatedFlyString const&> const& base_identifier, PropertyKey name, Op::PropertyKind kind, PropertyLookupCache* cache = nullptr)
  237. {
  238. // Better error message than to_object would give
  239. if (vm.in_strict_mode() && base.is_nullish())
  240. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, base.to_string_without_side_effects());
  241. // a. Let baseObj be ? ToObject(V.[[Base]]).
  242. auto maybe_object = base.to_object(vm);
  243. if (maybe_object.is_error())
  244. return throw_null_or_undefined_property_access(vm, base, base_identifier, name);
  245. auto object = maybe_object.release_value();
  246. if (kind == Op::PropertyKind::Getter || kind == Op::PropertyKind::Setter) {
  247. // The generator should only pass us functions for getters and setters.
  248. VERIFY(value.is_function());
  249. }
  250. switch (kind) {
  251. case Op::PropertyKind::Getter: {
  252. auto& function = value.as_function();
  253. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  254. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(ByteString::formatted("get {}", name));
  255. object->define_direct_accessor(name, &function, nullptr, Attribute::Configurable | Attribute::Enumerable);
  256. break;
  257. }
  258. case Op::PropertyKind::Setter: {
  259. auto& function = value.as_function();
  260. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  261. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(ByteString::formatted("set {}", name));
  262. object->define_direct_accessor(name, nullptr, &function, Attribute::Configurable | Attribute::Enumerable);
  263. break;
  264. }
  265. case Op::PropertyKind::KeyValue: {
  266. if (cache && cache->shape == &object->shape()) {
  267. object->put_direct(*cache->property_offset, value);
  268. return {};
  269. }
  270. CacheablePropertyMetadata cacheable_metadata;
  271. bool succeeded = TRY(object->internal_set(name, value, this_value, &cacheable_metadata));
  272. if (succeeded && cache && cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  273. cache->shape = object->shape();
  274. cache->property_offset = cacheable_metadata.property_offset.value();
  275. }
  276. if (!succeeded && vm.in_strict_mode()) {
  277. if (base.is_object())
  278. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, base.to_string_without_side_effects());
  279. return vm.throw_completion<TypeError>(ErrorType::ReferencePrimitiveSetProperty, name, base.typeof(), base.to_string_without_side_effects());
  280. }
  281. break;
  282. }
  283. case Op::PropertyKind::DirectKeyValue:
  284. object->define_direct_property(name, value, Attribute::Enumerable | Attribute::Writable | Attribute::Configurable);
  285. break;
  286. case Op::PropertyKind::Spread:
  287. TRY(object->copy_data_properties(vm, value, {}));
  288. break;
  289. case Op::PropertyKind::ProtoSetter:
  290. if (value.is_object() || value.is_null())
  291. MUST(object->internal_set_prototype_of(value.is_object() ? &value.as_object() : nullptr));
  292. break;
  293. }
  294. return {};
  295. }
  296. inline ThrowCompletionOr<Value> perform_call(Interpreter& interpreter, Value this_value, Op::CallType call_type, Value callee, ReadonlySpan<Value> argument_values)
  297. {
  298. auto& vm = interpreter.vm();
  299. auto& function = callee.as_function();
  300. Value return_value;
  301. if (call_type == Op::CallType::DirectEval) {
  302. if (callee == interpreter.realm().intrinsics().eval_function())
  303. 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));
  304. else
  305. return_value = TRY(JS::call(vm, function, this_value, argument_values));
  306. } else if (call_type == Op::CallType::Call)
  307. return_value = TRY(JS::call(vm, function, this_value, argument_values));
  308. else
  309. return_value = TRY(construct(vm, function, argument_values));
  310. return return_value;
  311. }
  312. static inline Completion throw_type_error_for_callee(Bytecode::Interpreter& interpreter, Value callee, StringView callee_type, Optional<StringTableIndex> const& expression_string)
  313. {
  314. auto& vm = interpreter.vm();
  315. if (expression_string.has_value())
  316. return vm.throw_completion<TypeError>(ErrorType::IsNotAEvaluatedFrom, callee.to_string_without_side_effects(), callee_type, interpreter.current_executable().get_string(expression_string->value()));
  317. return vm.throw_completion<TypeError>(ErrorType::IsNotA, callee.to_string_without_side_effects(), callee_type);
  318. }
  319. inline ThrowCompletionOr<void> throw_if_needed_for_call(Interpreter& interpreter, Value callee, Op::CallType call_type, Optional<StringTableIndex> const& expression_string)
  320. {
  321. if ((call_type == Op::CallType::Call || call_type == Op::CallType::DirectEval)
  322. && !callee.is_function())
  323. return throw_type_error_for_callee(interpreter, callee, "function"sv, expression_string);
  324. if (call_type == Op::CallType::Construct && !callee.is_constructor())
  325. return throw_type_error_for_callee(interpreter, callee, "constructor"sv, expression_string);
  326. return {};
  327. }
  328. inline ThrowCompletionOr<Value> typeof_variable(VM& vm, DeprecatedFlyString const& string)
  329. {
  330. // 1. Let val be the result of evaluating UnaryExpression.
  331. auto reference = TRY(vm.resolve_binding(string));
  332. // 2. If val is a Reference Record, then
  333. // a. If IsUnresolvableReference(val) is true, return "undefined".
  334. if (reference.is_unresolvable())
  335. return PrimitiveString::create(vm, "undefined"_string);
  336. // 3. Set val to ? GetValue(val).
  337. auto value = TRY(reference.get_value(vm));
  338. // 4. NOTE: This step is replaced in section B.3.6.3.
  339. // 5. Return a String according to Table 41.
  340. return PrimitiveString::create(vm, value.typeof());
  341. }
  342. inline ThrowCompletionOr<void> set_variable(
  343. VM& vm,
  344. DeprecatedFlyString const& name,
  345. Value value,
  346. Op::EnvironmentMode mode,
  347. Op::SetVariable::InitializationMode initialization_mode,
  348. EnvironmentCoordinate& cache)
  349. {
  350. auto environment = mode == Op::EnvironmentMode::Lexical ? vm.running_execution_context().lexical_environment : vm.running_execution_context().variable_environment;
  351. auto reference = TRY(vm.resolve_binding(name, environment));
  352. if (reference.environment_coordinate().has_value())
  353. cache = reference.environment_coordinate().value();
  354. switch (initialization_mode) {
  355. case Op::SetVariable::InitializationMode::Initialize:
  356. TRY(reference.initialize_referenced_binding(vm, value));
  357. break;
  358. case Op::SetVariable::InitializationMode::Set:
  359. TRY(reference.put_value(vm, value));
  360. break;
  361. }
  362. return {};
  363. }
  364. inline Value new_function(VM& vm, FunctionNode const& function_node, Optional<IdentifierTableIndex> const& lhs_name, Optional<Operand> const& home_object)
  365. {
  366. Value value;
  367. if (!function_node.has_name()) {
  368. DeprecatedFlyString name = {};
  369. if (lhs_name.has_value())
  370. name = vm.bytecode_interpreter().current_executable().get_identifier(lhs_name.value());
  371. value = function_node.instantiate_ordinary_function_expression(vm, name);
  372. } else {
  373. 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.uses_this(), function_node.might_need_arguments_object(), function_node.contains_direct_call_to_eval(), function_node.is_arrow_function());
  374. }
  375. if (home_object.has_value()) {
  376. auto home_object_value = vm.bytecode_interpreter().get(home_object.value());
  377. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(&home_object_value.as_object());
  378. }
  379. return value;
  380. }
  381. inline ThrowCompletionOr<void> put_by_value(VM& vm, Value base, Optional<DeprecatedFlyString const&> const& base_identifier, Value property_key_value, Value value, Op::PropertyKind kind)
  382. {
  383. // OPTIMIZATION: Fast path for simple Int32 indexes in array-like objects.
  384. if ((kind == Op::PropertyKind::KeyValue || kind == Op::PropertyKind::DirectKeyValue)
  385. && base.is_object() && property_key_value.is_int32() && property_key_value.as_i32() >= 0) {
  386. auto& object = base.as_object();
  387. auto* storage = object.indexed_properties().storage();
  388. auto index = static_cast<u32>(property_key_value.as_i32());
  389. // For "non-typed arrays":
  390. if (storage
  391. && storage->is_simple_storage()
  392. && !object.may_interfere_with_indexed_property_access()) {
  393. auto maybe_value = storage->get(index);
  394. if (maybe_value.has_value()) {
  395. auto existing_value = maybe_value->value;
  396. if (!existing_value.is_accessor()) {
  397. storage->put(index, value);
  398. return {};
  399. }
  400. }
  401. }
  402. // For typed arrays:
  403. if (object.is_typed_array()) {
  404. auto& typed_array = static_cast<TypedArrayBase&>(object);
  405. auto canonical_index = CanonicalIndex { CanonicalIndex::Type::Index, index };
  406. if (value.is_int32() && is_valid_integer_index(typed_array, canonical_index)) {
  407. switch (typed_array.kind()) {
  408. case TypedArrayBase::Kind::Uint8Array:
  409. fast_typed_array_set_element<u8>(typed_array, index, static_cast<u8>(value.as_i32()));
  410. return {};
  411. case TypedArrayBase::Kind::Uint16Array:
  412. fast_typed_array_set_element<u16>(typed_array, index, static_cast<u16>(value.as_i32()));
  413. return {};
  414. case TypedArrayBase::Kind::Uint32Array:
  415. fast_typed_array_set_element<u32>(typed_array, index, static_cast<u32>(value.as_i32()));
  416. return {};
  417. case TypedArrayBase::Kind::Int8Array:
  418. fast_typed_array_set_element<i8>(typed_array, index, static_cast<i8>(value.as_i32()));
  419. return {};
  420. case TypedArrayBase::Kind::Int16Array:
  421. fast_typed_array_set_element<i16>(typed_array, index, static_cast<i16>(value.as_i32()));
  422. return {};
  423. case TypedArrayBase::Kind::Int32Array:
  424. fast_typed_array_set_element<i32>(typed_array, index, value.as_i32());
  425. return {};
  426. case TypedArrayBase::Kind::Uint8ClampedArray:
  427. fast_typed_array_set_element<u8>(typed_array, index, clamp(value.as_i32(), 0, 255));
  428. return {};
  429. default:
  430. // FIXME: Support more TypedArray kinds.
  431. break;
  432. }
  433. }
  434. if (typed_array.kind() == TypedArrayBase::Kind::Uint32Array && value.is_integral_number()) {
  435. auto integer = value.as_double();
  436. if (AK::is_within_range<u32>(integer) && is_valid_integer_index(typed_array, canonical_index)) {
  437. fast_typed_array_set_element<u32>(typed_array, index, static_cast<u32>(integer));
  438. return {};
  439. }
  440. }
  441. switch (typed_array.kind()) {
  442. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, Type) \
  443. case TypedArrayBase::Kind::ClassName: \
  444. return typed_array_set_element<Type>(typed_array, canonical_index, value);
  445. JS_ENUMERATE_TYPED_ARRAYS
  446. #undef __JS_ENUMERATE
  447. }
  448. return {};
  449. }
  450. }
  451. auto property_key = kind != Op::PropertyKind::Spread ? TRY(property_key_value.to_property_key(vm)) : PropertyKey {};
  452. TRY(put_by_property_key(vm, base, base, value, base_identifier, property_key, kind));
  453. return {};
  454. }
  455. struct CalleeAndThis {
  456. Value callee;
  457. Value this_value;
  458. };
  459. inline ThrowCompletionOr<CalleeAndThis> get_callee_and_this_from_environment(Bytecode::Interpreter& interpreter, DeprecatedFlyString const& name, EnvironmentCoordinate& cache)
  460. {
  461. auto& vm = interpreter.vm();
  462. Value callee = js_undefined();
  463. Value this_value = js_undefined();
  464. if (cache.is_valid()) {
  465. auto const* environment = interpreter.running_execution_context().lexical_environment.ptr();
  466. for (size_t i = 0; i < cache.hops; ++i)
  467. environment = environment->outer_environment();
  468. if (!environment->is_permanently_screwed_by_eval()) {
  469. callee = TRY(static_cast<DeclarativeEnvironment const&>(*environment).get_binding_value_direct(vm, cache.index));
  470. this_value = js_undefined();
  471. if (auto base_object = environment->with_base_object())
  472. this_value = base_object;
  473. return CalleeAndThis {
  474. .callee = callee,
  475. .this_value = this_value,
  476. };
  477. }
  478. cache = {};
  479. }
  480. auto reference = TRY(vm.resolve_binding(name));
  481. if (reference.environment_coordinate().has_value())
  482. cache = reference.environment_coordinate().value();
  483. callee = TRY(reference.get_value(vm));
  484. if (reference.is_property_reference()) {
  485. this_value = reference.get_this_value();
  486. } else {
  487. if (reference.is_environment_reference()) {
  488. if (auto base_object = reference.base_environment().with_base_object(); base_object != nullptr)
  489. this_value = base_object;
  490. }
  491. }
  492. return CalleeAndThis {
  493. .callee = callee,
  494. .this_value = this_value,
  495. };
  496. }
  497. // 13.2.7.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation
  498. inline Value new_regexp(VM& vm, ParsedRegex const& parsed_regex, ByteString const& pattern, ByteString const& flags)
  499. {
  500. // 1. Let pattern be CodePointsToString(BodyText of RegularExpressionLiteral).
  501. // 2. Let flags be CodePointsToString(FlagText of RegularExpressionLiteral).
  502. // 3. Return ! RegExpCreate(pattern, flags).
  503. auto& realm = *vm.current_realm();
  504. Regex<ECMA262> regex(parsed_regex.regex, parsed_regex.pattern, parsed_regex.flags);
  505. // NOTE: We bypass RegExpCreate and subsequently RegExpAlloc as an optimization to use the already parsed values.
  506. auto regexp_object = RegExpObject::create(realm, move(regex), pattern, flags);
  507. // RegExpAlloc has these two steps from the 'Legacy RegExp features' proposal.
  508. regexp_object->set_realm(realm);
  509. // We don't need to check 'If SameValue(newTarget, thisRealm.[[Intrinsics]].[[%RegExp%]]) is true'
  510. // here as we know RegExpCreate calls RegExpAlloc with %RegExp% for newTarget.
  511. regexp_object->set_legacy_features_enabled(true);
  512. return regexp_object;
  513. }
  514. // 13.3.8.1 https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  515. inline MarkedVector<Value> argument_list_evaluation(VM& vm, Value arguments)
  516. {
  517. // Note: Any spreading and actual evaluation is handled in preceding opcodes
  518. // Note: The spec uses the concept of a list, while we create a temporary array
  519. // in the preceding opcodes, so we have to convert in a manner that is not
  520. // visible to the user
  521. MarkedVector<Value> argument_values { vm.heap() };
  522. auto& argument_array = arguments.as_array();
  523. auto array_length = argument_array.indexed_properties().array_like_size();
  524. argument_values.ensure_capacity(array_length);
  525. for (size_t i = 0; i < array_length; ++i) {
  526. if (auto maybe_value = argument_array.indexed_properties().get(i); maybe_value.has_value())
  527. argument_values.append(maybe_value.release_value().value);
  528. else
  529. argument_values.append(js_undefined());
  530. }
  531. return argument_values;
  532. }
  533. inline ThrowCompletionOr<void> create_variable(VM& vm, DeprecatedFlyString const& name, Op::EnvironmentMode mode, bool is_global, bool is_immutable, bool is_strict)
  534. {
  535. if (mode == Op::EnvironmentMode::Lexical) {
  536. VERIFY(!is_global);
  537. // Note: This is papering over an issue where "FunctionDeclarationInstantiation" creates these bindings for us.
  538. // Instead of crashing in there, we'll just raise an exception here.
  539. if (TRY(vm.lexical_environment()->has_binding(name)))
  540. return vm.throw_completion<InternalError>(TRY_OR_THROW_OOM(vm, String::formatted("Lexical environment already has binding '{}'", name)));
  541. if (is_immutable)
  542. return vm.lexical_environment()->create_immutable_binding(vm, name, is_strict);
  543. return vm.lexical_environment()->create_mutable_binding(vm, name, is_strict);
  544. }
  545. if (!is_global) {
  546. if (is_immutable)
  547. return vm.variable_environment()->create_immutable_binding(vm, name, is_strict);
  548. return vm.variable_environment()->create_mutable_binding(vm, name, is_strict);
  549. }
  550. // 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".
  551. // The only area that sets "can_be_deleted" to true is EvalDeclarationInstantiation, which is currently fully implemented in C++ and not in Bytecode.
  552. return verify_cast<GlobalEnvironment>(vm.variable_environment())->create_global_var_binding(name, false);
  553. }
  554. inline ThrowCompletionOr<ECMAScriptFunctionObject*> new_class(VM& vm, Value super_class, ClassExpression const& class_expression, Optional<IdentifierTableIndex> const& lhs_name, ReadonlySpan<Value> element_keys)
  555. {
  556. auto& interpreter = vm.bytecode_interpreter();
  557. auto name = class_expression.name();
  558. // NOTE: NewClass expects classEnv to be active lexical environment
  559. auto* class_environment = vm.lexical_environment();
  560. vm.running_execution_context().lexical_environment = vm.running_execution_context().saved_lexical_environments.take_last();
  561. Optional<DeprecatedFlyString> binding_name;
  562. DeprecatedFlyString class_name;
  563. if (!class_expression.has_name() && lhs_name.has_value()) {
  564. class_name = interpreter.current_executable().get_identifier(lhs_name.value());
  565. } else {
  566. binding_name = name;
  567. class_name = name.is_null() ? ""sv : name;
  568. }
  569. return TRY(class_expression.create_class_constructor(vm, class_environment, vm.lexical_environment(), super_class, element_keys, binding_name, class_name));
  570. }
  571. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  572. inline ThrowCompletionOr<NonnullGCPtr<Object>> super_call_with_argument_array(VM& vm, Value argument_array, bool is_synthetic)
  573. {
  574. // 1. Let newTarget be GetNewTarget().
  575. auto new_target = vm.get_new_target();
  576. // 2. Assert: Type(newTarget) is Object.
  577. VERIFY(new_target.is_object());
  578. // 3. Let func be GetSuperConstructor().
  579. auto* func = get_super_constructor(vm);
  580. // 4. Let argList be ? ArgumentListEvaluation of Arguments.
  581. MarkedVector<Value> arg_list { vm.heap() };
  582. if (is_synthetic) {
  583. VERIFY(argument_array.is_object() && is<Array>(argument_array.as_object()));
  584. auto const& array_value = static_cast<Array const&>(argument_array.as_object());
  585. auto length = MUST(length_of_array_like(vm, array_value));
  586. for (size_t i = 0; i < length; ++i)
  587. arg_list.append(array_value.get_without_side_effects(PropertyKey { i }));
  588. } else {
  589. arg_list = argument_list_evaluation(vm, argument_array);
  590. }
  591. // 5. If IsConstructor(func) is false, throw a TypeError exception.
  592. if (!Value(func).is_constructor())
  593. return vm.throw_completion<TypeError>(ErrorType::NotAConstructor, "Super constructor");
  594. // 6. Let result be ? Construct(func, argList, newTarget).
  595. auto result = TRY(construct(vm, static_cast<FunctionObject&>(*func), arg_list.span(), &new_target.as_function()));
  596. // 7. Let thisER be GetThisEnvironment().
  597. auto& this_environment = verify_cast<FunctionEnvironment>(*get_this_environment(vm));
  598. // 8. Perform ? thisER.BindThisValue(result).
  599. TRY(this_environment.bind_this_value(vm, result));
  600. // 9. Let F be thisER.[[FunctionObject]].
  601. auto& f = this_environment.function_object();
  602. // 10. Assert: F is an ECMAScript function object.
  603. // NOTE: This is implied by the strong C++ type.
  604. // 11. Perform ? InitializeInstanceElements(result, F).
  605. TRY(result->initialize_instance_elements(f));
  606. // 12. Return result.
  607. return result;
  608. }
  609. inline ThrowCompletionOr<NonnullGCPtr<Array>> iterator_to_array(VM& vm, Value iterator)
  610. {
  611. auto& iterator_record = verify_cast<IteratorRecord>(iterator.as_object());
  612. auto array = MUST(Array::create(*vm.current_realm(), 0));
  613. size_t index = 0;
  614. while (true) {
  615. auto value = TRY(iterator_step_value(vm, iterator_record));
  616. if (!value.has_value())
  617. return array;
  618. MUST(array->create_data_property_or_throw(index, value.release_value()));
  619. index++;
  620. }
  621. }
  622. inline ThrowCompletionOr<void> append(VM& vm, Value lhs, Value rhs, bool is_spread)
  623. {
  624. // Note: This OpCode is used to construct array literals and argument arrays for calls,
  625. // containing at least one spread element,
  626. // Iterating over such a spread element to unpack it has to be visible by
  627. // the user courtesy of
  628. // (1) https://tc39.es/ecma262/#sec-runtime-semantics-arrayaccumulation
  629. // SpreadElement : ... AssignmentExpression
  630. // 1. Let spreadRef be ? Evaluation of AssignmentExpression.
  631. // 2. Let spreadObj be ? GetValue(spreadRef).
  632. // 3. Let iteratorRecord be ? GetIterator(spreadObj).
  633. // 4. Repeat,
  634. // a. Let next be ? IteratorStep(iteratorRecord).
  635. // b. If next is false, return nextIndex.
  636. // c. Let nextValue be ? IteratorValue(next).
  637. // d. Perform ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), nextValue).
  638. // e. Set nextIndex to nextIndex + 1.
  639. // (2) https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  640. // ArgumentList : ... AssignmentExpression
  641. // 1. Let list be a new empty List.
  642. // 2. Let spreadRef be ? Evaluation of AssignmentExpression.
  643. // 3. Let spreadObj be ? GetValue(spreadRef).
  644. // 4. Let iteratorRecord be ? GetIterator(spreadObj).
  645. // 5. Repeat,
  646. // a. Let next be ? IteratorStep(iteratorRecord).
  647. // b. If next is false, return list.
  648. // c. Let nextArg be ? IteratorValue(next).
  649. // d. Append nextArg to list.
  650. // ArgumentList : ArgumentList , ... AssignmentExpression
  651. // 1. Let precedingArgs be ? ArgumentListEvaluation of ArgumentList.
  652. // 2. Let spreadRef be ? Evaluation of AssignmentExpression.
  653. // 3. Let iteratorRecord be ? GetIterator(? GetValue(spreadRef)).
  654. // 4. Repeat,
  655. // a. Let next be ? IteratorStep(iteratorRecord).
  656. // b. If next is false, return precedingArgs.
  657. // c. Let nextArg be ? IteratorValue(next).
  658. // d. Append nextArg to precedingArgs.
  659. // Note: We know from codegen, that lhs is a plain array with only indexed properties
  660. auto& lhs_array = lhs.as_array();
  661. auto lhs_size = lhs_array.indexed_properties().array_like_size();
  662. if (is_spread) {
  663. // ...rhs
  664. size_t i = lhs_size;
  665. TRY(get_iterator_values(vm, rhs, [&i, &lhs_array](Value iterator_value) -> Optional<Completion> {
  666. lhs_array.indexed_properties().put(i, iterator_value, default_attributes);
  667. ++i;
  668. return {};
  669. }));
  670. } else {
  671. lhs_array.indexed_properties().put(lhs_size, rhs, default_attributes);
  672. }
  673. return {};
  674. }
  675. inline ThrowCompletionOr<Value> delete_by_id(Bytecode::Interpreter& interpreter, Value base, IdentifierTableIndex property)
  676. {
  677. auto& vm = interpreter.vm();
  678. auto const& identifier = interpreter.current_executable().get_identifier(property);
  679. bool strict = vm.in_strict_mode();
  680. auto reference = Reference { base, identifier, {}, strict };
  681. return TRY(reference.delete_(vm));
  682. }
  683. inline ThrowCompletionOr<Value> delete_by_value(Bytecode::Interpreter& interpreter, Value base, Value property_key_value)
  684. {
  685. auto& vm = interpreter.vm();
  686. auto property_key = TRY(property_key_value.to_property_key(vm));
  687. bool strict = vm.in_strict_mode();
  688. auto reference = Reference { base, property_key, {}, strict };
  689. return Value(TRY(reference.delete_(vm)));
  690. }
  691. inline ThrowCompletionOr<Value> delete_by_value_with_this(Bytecode::Interpreter& interpreter, Value base, Value property_key_value, Value this_value)
  692. {
  693. auto& vm = interpreter.vm();
  694. auto property_key = TRY(property_key_value.to_property_key(vm));
  695. bool strict = vm.in_strict_mode();
  696. auto reference = Reference { base, property_key, this_value, strict };
  697. return Value(TRY(reference.delete_(vm)));
  698. }
  699. // 14.7.5.9 EnumerateObjectProperties ( O ), https://tc39.es/ecma262/#sec-enumerate-object-properties
  700. inline ThrowCompletionOr<Object*> get_object_property_iterator(VM& vm, Value value)
  701. {
  702. // While the spec does provide an algorithm, it allows us to implement it ourselves so long as we meet the following invariants:
  703. // 1- Returned property keys do not include keys that are Symbols
  704. // 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
  705. // 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
  706. // 4- A property name will be returned by the iterator's next method at most once in any enumeration.
  707. // 5- Enumerating the properties of the target object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively;
  708. // 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.
  709. // 6- The values of [[Enumerable]] attributes are not considered when determining if a property of a prototype object has already been processed.
  710. // 7- The enumerable property names of prototype objects must be obtained by invoking EnumerateObjectProperties passing the prototype object as the argument.
  711. // 8- EnumerateObjectProperties must obtain the own property keys of the target object by calling its [[OwnPropertyKeys]] internal method.
  712. // 9- Property attributes of the target object must be obtained by calling its [[GetOwnProperty]] internal method
  713. // Invariant 3 effectively allows the implementation to ignore newly added keys, and we do so (similar to other implementations).
  714. auto object = TRY(value.to_object(vm));
  715. // Note: While the spec doesn't explicitly require these to be ordered, it says that the values should be retrieved via OwnPropertyKeys,
  716. // so we just keep the order consistent anyway.
  717. OrderedHashTable<PropertyKey> properties;
  718. OrderedHashTable<PropertyKey> non_enumerable_properties;
  719. HashTable<NonnullGCPtr<Object>> seen_objects;
  720. // Collect all keys immediately (invariant no. 5)
  721. 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())) {
  722. seen_objects.set(*object_to_check);
  723. for (auto& key : TRY(object_to_check->internal_own_property_keys())) {
  724. if (key.is_symbol())
  725. continue;
  726. auto property_key = TRY(PropertyKey::from_value(vm, key));
  727. // If there is a non-enumerable property higher up the prototype chain with the same key,
  728. // we mustn't include this property even if it's enumerable (invariant no. 5 and 6)
  729. if (non_enumerable_properties.contains(property_key))
  730. continue;
  731. if (properties.contains(property_key))
  732. continue;
  733. auto descriptor = TRY(object_to_check->internal_get_own_property(property_key));
  734. if (!*descriptor->enumerable)
  735. non_enumerable_properties.set(move(property_key));
  736. else
  737. properties.set(move(property_key));
  738. }
  739. }
  740. auto& realm = *vm.current_realm();
  741. auto callback = NativeFunction::create(
  742. *vm.current_realm(), [items = move(properties)](VM& vm) mutable -> ThrowCompletionOr<Value> {
  743. auto& realm = *vm.current_realm();
  744. auto iterated_object_value = vm.this_value();
  745. if (!iterated_object_value.is_object())
  746. return vm.throw_completion<InternalError>("Invalid state for GetObjectPropertyIterator.next"sv);
  747. auto& iterated_object = iterated_object_value.as_object();
  748. auto result_object = Object::create(realm, nullptr);
  749. while (true) {
  750. if (items.is_empty()) {
  751. result_object->define_direct_property(vm.names.done, JS::Value(true), default_attributes);
  752. return result_object;
  753. }
  754. auto key = items.take_first();
  755. // If the property is deleted, don't include it (invariant no. 2)
  756. if (!TRY(iterated_object.has_property(key)))
  757. continue;
  758. result_object->define_direct_property(vm.names.done, JS::Value(false), default_attributes);
  759. if (key.is_number())
  760. result_object->define_direct_property(vm.names.value, PrimitiveString::create(vm, TRY_OR_THROW_OOM(vm, String::number(key.as_number()))), default_attributes);
  761. else if (key.is_string())
  762. result_object->define_direct_property(vm.names.value, PrimitiveString::create(vm, key.as_string()), default_attributes);
  763. else
  764. VERIFY_NOT_REACHED(); // We should not have non-string/number keys.
  765. return result_object;
  766. }
  767. },
  768. 1, vm.names.next);
  769. return vm.heap().allocate<IteratorRecord>(realm, realm, object, callback, false).ptr();
  770. }
  771. }