CommonImplementations.h 42 KB

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