CommonImplementations.h 40 KB

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