Op.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Gunnar Beutner <gbeutner@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/HashTable.h>
  9. #include <LibJS/Bytecode/Interpreter.h>
  10. #include <LibJS/Bytecode/Op.h>
  11. #include <LibJS/Runtime/AbstractOperations.h>
  12. #include <LibJS/Runtime/Array.h>
  13. #include <LibJS/Runtime/BigInt.h>
  14. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  15. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  16. #include <LibJS/Runtime/Environment.h>
  17. #include <LibJS/Runtime/GlobalObject.h>
  18. #include <LibJS/Runtime/Iterator.h>
  19. #include <LibJS/Runtime/IteratorOperations.h>
  20. #include <LibJS/Runtime/NativeFunction.h>
  21. #include <LibJS/Runtime/ObjectEnvironment.h>
  22. #include <LibJS/Runtime/RegExpObject.h>
  23. #include <LibJS/Runtime/Value.h>
  24. namespace JS::Bytecode {
  25. String Instruction::to_string(Bytecode::Executable const& executable) const
  26. {
  27. #define __BYTECODE_OP(op) \
  28. case Instruction::Type::op: \
  29. return static_cast<Bytecode::Op::op const&>(*this).to_string_impl(executable);
  30. switch (type()) {
  31. ENUMERATE_BYTECODE_OPS(__BYTECODE_OP)
  32. default:
  33. VERIFY_NOT_REACHED();
  34. }
  35. #undef __BYTECODE_OP
  36. }
  37. }
  38. namespace JS::Bytecode::Op {
  39. ThrowCompletionOr<void> Load::execute_impl(Bytecode::Interpreter& interpreter) const
  40. {
  41. interpreter.accumulator() = interpreter.reg(m_src);
  42. return {};
  43. }
  44. ThrowCompletionOr<void> LoadImmediate::execute_impl(Bytecode::Interpreter& interpreter) const
  45. {
  46. interpreter.accumulator() = m_value;
  47. return {};
  48. }
  49. ThrowCompletionOr<void> Store::execute_impl(Bytecode::Interpreter& interpreter) const
  50. {
  51. interpreter.reg(m_dst) = interpreter.accumulator();
  52. return {};
  53. }
  54. static ThrowCompletionOr<Value> abstract_inequals(GlobalObject& global_object, Value src1, Value src2)
  55. {
  56. return Value(!TRY(is_loosely_equal(global_object, src1, src2)));
  57. }
  58. static ThrowCompletionOr<Value> abstract_equals(GlobalObject& global_object, Value src1, Value src2)
  59. {
  60. return Value(TRY(is_loosely_equal(global_object, src1, src2)));
  61. }
  62. static ThrowCompletionOr<Value> typed_inequals(GlobalObject&, Value src1, Value src2)
  63. {
  64. return Value(!is_strictly_equal(src1, src2));
  65. }
  66. static ThrowCompletionOr<Value> typed_equals(GlobalObject&, Value src1, Value src2)
  67. {
  68. return Value(is_strictly_equal(src1, src2));
  69. }
  70. #define JS_DEFINE_COMMON_BINARY_OP(OpTitleCase, op_snake_case) \
  71. ThrowCompletionOr<void> OpTitleCase::execute_impl(Bytecode::Interpreter& interpreter) const \
  72. { \
  73. auto lhs = interpreter.reg(m_lhs_reg); \
  74. auto rhs = interpreter.accumulator(); \
  75. interpreter.accumulator() = TRY(op_snake_case(interpreter.global_object(), lhs, rhs)); \
  76. return {}; \
  77. } \
  78. String OpTitleCase::to_string_impl(Bytecode::Executable const&) const \
  79. { \
  80. return String::formatted(#OpTitleCase " {}", m_lhs_reg); \
  81. }
  82. JS_ENUMERATE_COMMON_BINARY_OPS(JS_DEFINE_COMMON_BINARY_OP)
  83. static ThrowCompletionOr<Value> not_(GlobalObject&, Value value)
  84. {
  85. return Value(!value.to_boolean());
  86. }
  87. static ThrowCompletionOr<Value> typeof_(GlobalObject& global_object, Value value)
  88. {
  89. return Value(js_string(global_object.vm(), value.typeof()));
  90. }
  91. #define JS_DEFINE_COMMON_UNARY_OP(OpTitleCase, op_snake_case) \
  92. ThrowCompletionOr<void> OpTitleCase::execute_impl(Bytecode::Interpreter& interpreter) const \
  93. { \
  94. interpreter.accumulator() = TRY(op_snake_case(interpreter.global_object(), interpreter.accumulator())); \
  95. return {}; \
  96. } \
  97. String OpTitleCase::to_string_impl(Bytecode::Executable const&) const \
  98. { \
  99. return #OpTitleCase; \
  100. }
  101. JS_ENUMERATE_COMMON_UNARY_OPS(JS_DEFINE_COMMON_UNARY_OP)
  102. ThrowCompletionOr<void> NewBigInt::execute_impl(Bytecode::Interpreter& interpreter) const
  103. {
  104. interpreter.accumulator() = js_bigint(interpreter.vm().heap(), m_bigint);
  105. return {};
  106. }
  107. ThrowCompletionOr<void> NewArray::execute_impl(Bytecode::Interpreter& interpreter) const
  108. {
  109. auto* array = MUST(Array::create(interpreter.global_object(), 0));
  110. for (size_t i = 0; i < m_element_count; i++) {
  111. auto& value = interpreter.reg(Register(m_elements[0].index() + i));
  112. array->indexed_properties().put(i, value, default_attributes);
  113. }
  114. interpreter.accumulator() = array;
  115. return {};
  116. }
  117. // FIXME: Since the accumulator is a Value, we store an object there and have to convert back and forth between that an Iterator records. Not great.
  118. // Make sure to put this into the accumulator before the iterator object disappears from the stack to prevent the members from being GC'd.
  119. static Object* iterator_to_object(GlobalObject& global_object, Iterator iterator)
  120. {
  121. auto& vm = global_object.vm();
  122. auto* object = Object::create(global_object, nullptr);
  123. object->define_direct_property(vm.names.iterator, iterator.iterator, 0);
  124. object->define_direct_property(vm.names.next, iterator.next_method, 0);
  125. object->define_direct_property(vm.names.done, Value(iterator.done), 0);
  126. return object;
  127. }
  128. static Iterator object_to_iterator(GlobalObject& global_object, Object& object)
  129. {
  130. auto& vm = global_object.vm();
  131. return Iterator {
  132. .iterator = &MUST(object.get(vm.names.iterator)).as_object(),
  133. .next_method = MUST(object.get(vm.names.next)),
  134. .done = MUST(object.get(vm.names.done)).as_bool()
  135. };
  136. }
  137. ThrowCompletionOr<void> IteratorToArray::execute_impl(Bytecode::Interpreter& interpreter) const
  138. {
  139. auto& global_object = interpreter.global_object();
  140. auto iterator_object = TRY(interpreter.accumulator().to_object(global_object));
  141. auto iterator = object_to_iterator(global_object, *iterator_object);
  142. auto* array = MUST(Array::create(global_object, 0));
  143. size_t index = 0;
  144. while (true) {
  145. auto* iterator_result = TRY(iterator_next(global_object, iterator));
  146. auto complete = TRY(iterator_complete(global_object, *iterator_result));
  147. if (complete) {
  148. interpreter.accumulator() = array;
  149. return {};
  150. }
  151. auto value = TRY(iterator_value(global_object, *iterator_result));
  152. MUST(array->create_data_property_or_throw(index, value));
  153. index++;
  154. }
  155. return {};
  156. }
  157. ThrowCompletionOr<void> NewString::execute_impl(Bytecode::Interpreter& interpreter) const
  158. {
  159. interpreter.accumulator() = js_string(interpreter.vm(), interpreter.current_executable().get_string(m_string));
  160. return {};
  161. }
  162. ThrowCompletionOr<void> NewObject::execute_impl(Bytecode::Interpreter& interpreter) const
  163. {
  164. interpreter.accumulator() = Object::create(interpreter.global_object(), interpreter.global_object().object_prototype());
  165. return {};
  166. }
  167. ThrowCompletionOr<void> NewRegExp::execute_impl(Bytecode::Interpreter& interpreter) const
  168. {
  169. auto source = interpreter.current_executable().get_string(m_source_index);
  170. auto flags = interpreter.current_executable().get_string(m_flags_index);
  171. interpreter.accumulator() = TRY(regexp_create(interpreter.global_object(), js_string(interpreter.vm(), source), js_string(interpreter.vm(), flags)));
  172. return {};
  173. }
  174. ThrowCompletionOr<void> CopyObjectExcludingProperties::execute_impl(Bytecode::Interpreter& interpreter) const
  175. {
  176. auto* from_object = TRY(interpreter.reg(m_from_object).to_object(interpreter.global_object()));
  177. auto* to_object = Object::create(interpreter.global_object(), interpreter.global_object().object_prototype());
  178. HashTable<Value, ValueTraits> excluded_names;
  179. for (size_t i = 0; i < m_excluded_names_count; ++i)
  180. excluded_names.set(interpreter.reg(m_excluded_names[i]));
  181. auto own_keys = TRY(from_object->internal_own_property_keys());
  182. for (auto& key : own_keys) {
  183. if (!excluded_names.contains(key)) {
  184. auto property_key = TRY(key.to_property_key(interpreter.global_object()));
  185. auto property_value = TRY(from_object->get(property_key));
  186. to_object->define_direct_property(property_key, property_value, JS::default_attributes);
  187. }
  188. }
  189. interpreter.accumulator() = to_object;
  190. return {};
  191. }
  192. ThrowCompletionOr<void> ConcatString::execute_impl(Bytecode::Interpreter& interpreter) const
  193. {
  194. interpreter.reg(m_lhs) = TRY(add(interpreter.global_object(), interpreter.reg(m_lhs), interpreter.accumulator()));
  195. return {};
  196. }
  197. ThrowCompletionOr<void> GetVariable::execute_impl(Bytecode::Interpreter& interpreter) const
  198. {
  199. auto get_reference = [&]() -> ThrowCompletionOr<Reference> {
  200. auto const& string = interpreter.current_executable().get_identifier(m_identifier);
  201. if (m_cached_environment_coordinate.has_value()) {
  202. auto* environment = interpreter.vm().running_execution_context().lexical_environment;
  203. for (size_t i = 0; i < m_cached_environment_coordinate->hops; ++i)
  204. environment = environment->outer_environment();
  205. VERIFY(environment);
  206. VERIFY(environment->is_declarative_environment());
  207. if (!environment->is_permanently_screwed_by_eval()) {
  208. return Reference { *environment, string, interpreter.vm().in_strict_mode(), m_cached_environment_coordinate };
  209. }
  210. m_cached_environment_coordinate = {};
  211. }
  212. auto reference = TRY(interpreter.vm().resolve_binding(string));
  213. if (reference.environment_coordinate().has_value())
  214. m_cached_environment_coordinate = reference.environment_coordinate();
  215. return reference;
  216. };
  217. auto reference = TRY(get_reference());
  218. interpreter.accumulator() = TRY(reference.get_value(interpreter.global_object()));
  219. return {};
  220. }
  221. ThrowCompletionOr<void> CreateEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  222. {
  223. auto make_and_swap_envs = [&](auto*& old_environment) {
  224. Environment* environment = new_declarative_environment(*old_environment);
  225. swap(old_environment, environment);
  226. return environment;
  227. };
  228. if (m_mode == EnvironmentMode::Lexical)
  229. interpreter.saved_lexical_environment_stack().append(make_and_swap_envs(interpreter.vm().running_execution_context().lexical_environment));
  230. else if (m_mode == EnvironmentMode::Var)
  231. interpreter.saved_variable_environment_stack().append(make_and_swap_envs(interpreter.vm().running_execution_context().variable_environment));
  232. return {};
  233. }
  234. ThrowCompletionOr<void> EnterObjectEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  235. {
  236. auto& old_environment = interpreter.vm().running_execution_context().lexical_environment;
  237. interpreter.saved_lexical_environment_stack().append(old_environment);
  238. auto object = TRY(interpreter.accumulator().to_object(interpreter.global_object()));
  239. interpreter.vm().running_execution_context().lexical_environment = new_object_environment(*object, true, old_environment);
  240. return {};
  241. }
  242. ThrowCompletionOr<void> CreateVariable::execute_impl(Bytecode::Interpreter& interpreter) const
  243. {
  244. auto& vm = interpreter.vm();
  245. auto const& name = interpreter.current_executable().get_identifier(m_identifier);
  246. if (m_mode == EnvironmentMode::Lexical) {
  247. // Note: This is papering over an issue where "FunctionDeclarationInstantiation" creates these bindings for us.
  248. // Instead of crashing in there, we'll just raise an exception here.
  249. if (TRY(vm.lexical_environment()->has_binding(name)))
  250. return vm.throw_completion<InternalError>(interpreter.global_object(), String::formatted("Lexical environment already has binding '{}'", name));
  251. if (m_is_immutable)
  252. vm.lexical_environment()->create_immutable_binding(interpreter.global_object(), name, vm.in_strict_mode());
  253. else
  254. vm.lexical_environment()->create_mutable_binding(interpreter.global_object(), name, vm.in_strict_mode());
  255. } else {
  256. if (m_is_immutable)
  257. vm.variable_environment()->create_immutable_binding(interpreter.global_object(), name, vm.in_strict_mode());
  258. else
  259. vm.variable_environment()->create_mutable_binding(interpreter.global_object(), name, vm.in_strict_mode());
  260. }
  261. return {};
  262. }
  263. ThrowCompletionOr<void> SetVariable::execute_impl(Bytecode::Interpreter& interpreter) const
  264. {
  265. auto& vm = interpreter.vm();
  266. auto const& name = interpreter.current_executable().get_identifier(m_identifier);
  267. auto environment = m_mode == EnvironmentMode::Lexical ? vm.running_execution_context().lexical_environment : vm.running_execution_context().variable_environment;
  268. auto reference = TRY(vm.resolve_binding(name, environment));
  269. switch (m_initialization_mode) {
  270. case InitializationMode::Initialize:
  271. TRY(reference.initialize_referenced_binding(interpreter.global_object(), interpreter.accumulator()));
  272. break;
  273. case InitializationMode::Set:
  274. TRY(reference.put_value(interpreter.global_object(), interpreter.accumulator()));
  275. break;
  276. case InitializationMode::InitializeOrSet:
  277. VERIFY(reference.is_environment_reference());
  278. VERIFY(reference.base_environment().is_declarative_environment());
  279. TRY(static_cast<DeclarativeEnvironment&>(reference.base_environment()).initialize_or_set_mutable_binding(interpreter.global_object(), name, interpreter.accumulator()));
  280. break;
  281. }
  282. return {};
  283. }
  284. ThrowCompletionOr<void> GetById::execute_impl(Bytecode::Interpreter& interpreter) const
  285. {
  286. auto* object = TRY(interpreter.accumulator().to_object(interpreter.global_object()));
  287. interpreter.accumulator() = TRY(object->get(interpreter.current_executable().get_identifier(m_property)));
  288. return {};
  289. }
  290. ThrowCompletionOr<void> PutById::execute_impl(Bytecode::Interpreter& interpreter) const
  291. {
  292. auto* object = TRY(interpreter.reg(m_base).to_object(interpreter.global_object()));
  293. TRY(object->set(interpreter.current_executable().get_identifier(m_property), interpreter.accumulator(), Object::ShouldThrowExceptions::Yes));
  294. return {};
  295. }
  296. ThrowCompletionOr<void> Jump::execute_impl(Bytecode::Interpreter& interpreter) const
  297. {
  298. interpreter.jump(*m_true_target);
  299. return {};
  300. }
  301. ThrowCompletionOr<void> ResolveThisBinding::execute_impl(Bytecode::Interpreter& interpreter) const
  302. {
  303. interpreter.accumulator() = TRY(interpreter.vm().resolve_this_binding(interpreter.global_object()));
  304. return {};
  305. }
  306. void Jump::replace_references_impl(BasicBlock const& from, BasicBlock const& to)
  307. {
  308. if (m_true_target.has_value() && &m_true_target->block() == &from)
  309. m_true_target = Label { to };
  310. if (m_false_target.has_value() && &m_false_target->block() == &from)
  311. m_false_target = Label { to };
  312. }
  313. ThrowCompletionOr<void> JumpConditional::execute_impl(Bytecode::Interpreter& interpreter) const
  314. {
  315. VERIFY(m_true_target.has_value());
  316. VERIFY(m_false_target.has_value());
  317. auto result = interpreter.accumulator();
  318. if (result.to_boolean())
  319. interpreter.jump(m_true_target.value());
  320. else
  321. interpreter.jump(m_false_target.value());
  322. return {};
  323. }
  324. ThrowCompletionOr<void> JumpNullish::execute_impl(Bytecode::Interpreter& interpreter) const
  325. {
  326. VERIFY(m_true_target.has_value());
  327. VERIFY(m_false_target.has_value());
  328. auto result = interpreter.accumulator();
  329. if (result.is_nullish())
  330. interpreter.jump(m_true_target.value());
  331. else
  332. interpreter.jump(m_false_target.value());
  333. return {};
  334. }
  335. ThrowCompletionOr<void> JumpUndefined::execute_impl(Bytecode::Interpreter& interpreter) const
  336. {
  337. VERIFY(m_true_target.has_value());
  338. VERIFY(m_false_target.has_value());
  339. auto result = interpreter.accumulator();
  340. if (result.is_undefined())
  341. interpreter.jump(m_true_target.value());
  342. else
  343. interpreter.jump(m_false_target.value());
  344. return {};
  345. }
  346. ThrowCompletionOr<void> Call::execute_impl(Bytecode::Interpreter& interpreter) const
  347. {
  348. auto callee = interpreter.reg(m_callee);
  349. if (!callee.is_function())
  350. return interpreter.vm().throw_completion<TypeError>(interpreter.global_object(), ErrorType::IsNotA, callee.to_string_without_side_effects(), "function"sv);
  351. auto& function = callee.as_function();
  352. auto this_value = interpreter.reg(m_this_value);
  353. MarkedVector<Value> argument_values { interpreter.vm().heap() };
  354. for (size_t i = 0; i < m_argument_count; ++i)
  355. argument_values.append(interpreter.reg(m_arguments[i]));
  356. Value return_value;
  357. if (m_type == CallType::Call)
  358. return_value = TRY(call(interpreter.global_object(), function, this_value, move(argument_values)));
  359. else
  360. return_value = TRY(construct(interpreter.global_object(), function, move(argument_values)));
  361. interpreter.accumulator() = return_value;
  362. return {};
  363. }
  364. ThrowCompletionOr<void> NewFunction::execute_impl(Bytecode::Interpreter& interpreter) const
  365. {
  366. auto& vm = interpreter.vm();
  367. interpreter.accumulator() = ECMAScriptFunctionObject::create(interpreter.global_object(), m_function_node.name(), m_function_node.source_text(), m_function_node.body(), m_function_node.parameters(), m_function_node.function_length(), vm.lexical_environment(), vm.running_execution_context().private_environment, m_function_node.kind(), m_function_node.is_strict_mode(), m_function_node.might_need_arguments_object(), m_function_node.is_arrow_function());
  368. return {};
  369. }
  370. ThrowCompletionOr<void> Return::execute_impl(Bytecode::Interpreter& interpreter) const
  371. {
  372. interpreter.do_return(interpreter.accumulator().value_or(js_undefined()));
  373. return {};
  374. }
  375. ThrowCompletionOr<void> Increment::execute_impl(Bytecode::Interpreter& interpreter) const
  376. {
  377. auto old_value = TRY(interpreter.accumulator().to_numeric(interpreter.global_object()));
  378. if (old_value.is_number())
  379. interpreter.accumulator() = Value(old_value.as_double() + 1);
  380. else
  381. interpreter.accumulator() = js_bigint(interpreter.vm().heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  382. return {};
  383. }
  384. ThrowCompletionOr<void> Decrement::execute_impl(Bytecode::Interpreter& interpreter) const
  385. {
  386. auto old_value = TRY(interpreter.accumulator().to_numeric(interpreter.global_object()));
  387. if (old_value.is_number())
  388. interpreter.accumulator() = Value(old_value.as_double() - 1);
  389. else
  390. interpreter.accumulator() = js_bigint(interpreter.vm().heap(), old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
  391. return {};
  392. }
  393. ThrowCompletionOr<void> Throw::execute_impl(Bytecode::Interpreter& interpreter) const
  394. {
  395. return throw_completion(interpreter.accumulator());
  396. }
  397. ThrowCompletionOr<void> EnterUnwindContext::execute_impl(Bytecode::Interpreter& interpreter) const
  398. {
  399. interpreter.enter_unwind_context(m_handler_target, m_finalizer_target);
  400. interpreter.jump(m_entry_point);
  401. return {};
  402. }
  403. void EnterUnwindContext::replace_references_impl(BasicBlock const& from, BasicBlock const& to)
  404. {
  405. if (&m_entry_point.block() == &from)
  406. m_entry_point = Label { to };
  407. if (m_handler_target.has_value() && &m_handler_target->block() == &from)
  408. m_handler_target = Label { to };
  409. if (m_finalizer_target.has_value() && &m_finalizer_target->block() == &from)
  410. m_finalizer_target = Label { to };
  411. }
  412. ThrowCompletionOr<void> FinishUnwind::execute_impl(Bytecode::Interpreter& interpreter) const
  413. {
  414. interpreter.leave_unwind_context();
  415. interpreter.jump(m_next_target);
  416. return {};
  417. }
  418. void FinishUnwind::replace_references_impl(BasicBlock const& from, BasicBlock const& to)
  419. {
  420. if (&m_next_target.block() == &from)
  421. m_next_target = Label { to };
  422. }
  423. ThrowCompletionOr<void> LeaveEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  424. {
  425. if (m_mode == EnvironmentMode::Lexical)
  426. interpreter.vm().running_execution_context().lexical_environment = interpreter.saved_lexical_environment_stack().take_last();
  427. if (m_mode == EnvironmentMode::Var)
  428. interpreter.vm().running_execution_context().variable_environment = interpreter.saved_variable_environment_stack().take_last();
  429. return {};
  430. }
  431. ThrowCompletionOr<void> LeaveUnwindContext::execute_impl(Bytecode::Interpreter& interpreter) const
  432. {
  433. interpreter.leave_unwind_context();
  434. return {};
  435. }
  436. ThrowCompletionOr<void> ContinuePendingUnwind::execute_impl(Bytecode::Interpreter& interpreter) const
  437. {
  438. return interpreter.continue_pending_unwind(m_resume_target);
  439. }
  440. void ContinuePendingUnwind::replace_references_impl(BasicBlock const& from, BasicBlock const& to)
  441. {
  442. if (&m_resume_target.block() == &from)
  443. m_resume_target = Label { to };
  444. }
  445. ThrowCompletionOr<void> PushDeclarativeEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  446. {
  447. auto* environment = interpreter.vm().heap().allocate_without_global_object<DeclarativeEnvironment>(interpreter.vm().lexical_environment());
  448. interpreter.vm().running_execution_context().lexical_environment = environment;
  449. interpreter.vm().running_execution_context().variable_environment = environment;
  450. return {};
  451. }
  452. ThrowCompletionOr<void> Yield::execute_impl(Bytecode::Interpreter& interpreter) const
  453. {
  454. auto yielded_value = interpreter.accumulator().value_or(js_undefined());
  455. auto object = JS::Object::create(interpreter.global_object(), nullptr);
  456. object->define_direct_property("result", yielded_value, JS::default_attributes);
  457. if (m_continuation_label.has_value())
  458. object->define_direct_property("continuation", Value(static_cast<double>(reinterpret_cast<u64>(&m_continuation_label->block()))), JS::default_attributes);
  459. else
  460. object->define_direct_property("continuation", Value(0), JS::default_attributes);
  461. interpreter.do_return(object);
  462. return {};
  463. }
  464. void Yield::replace_references_impl(BasicBlock const& from, BasicBlock const& to)
  465. {
  466. if (m_continuation_label.has_value() && &m_continuation_label->block() == &from)
  467. m_continuation_label = Label { to };
  468. }
  469. ThrowCompletionOr<void> GetByValue::execute_impl(Bytecode::Interpreter& interpreter) const
  470. {
  471. auto* object = TRY(interpreter.reg(m_base).to_object(interpreter.global_object()));
  472. auto property_key = TRY(interpreter.accumulator().to_property_key(interpreter.global_object()));
  473. interpreter.accumulator() = TRY(object->get(property_key));
  474. return {};
  475. }
  476. ThrowCompletionOr<void> PutByValue::execute_impl(Bytecode::Interpreter& interpreter) const
  477. {
  478. auto* object = TRY(interpreter.reg(m_base).to_object(interpreter.global_object()));
  479. auto property_key = TRY(interpreter.reg(m_property).to_property_key(interpreter.global_object()));
  480. TRY(object->set(property_key, interpreter.accumulator(), Object::ShouldThrowExceptions::Yes));
  481. return {};
  482. }
  483. ThrowCompletionOr<void> GetIterator::execute_impl(Bytecode::Interpreter& interpreter) const
  484. {
  485. auto iterator = TRY(get_iterator(interpreter.global_object(), interpreter.accumulator()));
  486. interpreter.accumulator() = iterator_to_object(interpreter.global_object(), iterator);
  487. return {};
  488. }
  489. // 14.7.5.9 EnumerateObjectProperties ( O ), https://tc39.es/ecma262/#sec-enumerate-object-properties
  490. ThrowCompletionOr<void> GetObjectPropertyIterator::execute_impl(Bytecode::Interpreter& interpreter) const
  491. {
  492. // While the spec does provide an algorithm, it allows us to implement it ourselves so long as we meet the following invariants:
  493. // 1- Returned property keys do not include keys that are Symbols
  494. // 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
  495. // 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
  496. // 4- A property name will be returned by the iterator's next method at most once in any enumeration.
  497. // 5- Enumerating the properties of the target object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively;
  498. // 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.
  499. // 6- The values of [[Enumerable]] attributes are not considered when determining if a property of a prototype object has already been processed.
  500. // 7- The enumerable property names of prototype objects must be obtained by invoking EnumerateObjectProperties passing the prototype object as the argument.
  501. // 8- EnumerateObjectProperties must obtain the own property keys of the target object by calling its [[OwnPropertyKeys]] internal method.
  502. // 9- Property attributes of the target object must be obtained by calling its [[GetOwnProperty]] internal method
  503. // Invariant 3 effectively allows the implementation to ignore newly added keys, and we do so (similar to other implementations).
  504. // Invariants 1 and 6 through 9 are implemented in `enumerable_own_property_names`, which implements the EnumerableOwnPropertyNames AO.
  505. auto* object = TRY(interpreter.accumulator().to_object(interpreter.global_object()));
  506. // Note: While the spec doesn't explicitly require these to be ordered, it says that the values should be retrieved via OwnPropertyKeys,
  507. // so we just keep the order consistent anyway.
  508. OrderedHashTable<PropertyKey> properties;
  509. HashTable<Object*> seen_objects;
  510. // Collect all keys immediately (invariant no. 5)
  511. for (auto* object_to_check = object; object_to_check && !seen_objects.contains(object_to_check); object_to_check = TRY(object_to_check->internal_get_prototype_of())) {
  512. seen_objects.set(object_to_check);
  513. for (auto& key : TRY(object_to_check->enumerable_own_property_names(Object::PropertyKind::Key))) {
  514. properties.set(TRY(PropertyKey::from_value(interpreter.global_object(), key)));
  515. }
  516. }
  517. Iterator iterator {
  518. .iterator = object,
  519. .next_method = NativeFunction::create(
  520. interpreter.global_object(),
  521. [seen_items = HashTable<PropertyKey>(), items = move(properties)](VM& vm, GlobalObject& global_object) mutable -> ThrowCompletionOr<Value> {
  522. auto iterated_object_value = vm.this_value(global_object);
  523. if (!iterated_object_value.is_object())
  524. return vm.throw_completion<InternalError>(global_object, "Invalid state for GetObjectPropertyIterator.next");
  525. auto& iterated_object = iterated_object_value.as_object();
  526. auto* result_object = Object::create(global_object, nullptr);
  527. while (true) {
  528. if (items.is_empty()) {
  529. result_object->define_direct_property(vm.names.done, JS::Value(true), default_attributes);
  530. return result_object;
  531. }
  532. auto it = items.begin();
  533. auto key = *it;
  534. items.remove(it);
  535. // If the key was already seen, skip over it (invariant no. 4)
  536. auto result = seen_items.set(key);
  537. if (result != AK::HashSetResult::InsertedNewEntry)
  538. continue;
  539. // If the property is deleted, don't include it (invariant no. 2)
  540. if (!TRY(iterated_object.has_property(key)))
  541. continue;
  542. result_object->define_direct_property(vm.names.done, JS::Value(false), default_attributes);
  543. if (key.is_number())
  544. result_object->define_direct_property(vm.names.value, JS::Value(key.as_number()), default_attributes);
  545. else if (key.is_string())
  546. result_object->define_direct_property(vm.names.value, js_string(vm.heap(), key.as_string()), default_attributes);
  547. else
  548. VERIFY_NOT_REACHED(); // We should not have non-string/number keys.
  549. return result_object;
  550. }
  551. },
  552. 1,
  553. interpreter.vm().names.next),
  554. .done = false,
  555. };
  556. interpreter.accumulator() = iterator_to_object(interpreter.global_object(), move(iterator));
  557. return {};
  558. }
  559. ThrowCompletionOr<void> IteratorNext::execute_impl(Bytecode::Interpreter& interpreter) const
  560. {
  561. auto* iterator_object = TRY(interpreter.accumulator().to_object(interpreter.global_object()));
  562. auto iterator = object_to_iterator(interpreter.global_object(), *iterator_object);
  563. interpreter.accumulator() = TRY(iterator_next(interpreter.global_object(), iterator));
  564. return {};
  565. }
  566. ThrowCompletionOr<void> IteratorResultDone::execute_impl(Bytecode::Interpreter& interpreter) const
  567. {
  568. auto* iterator_result = TRY(interpreter.accumulator().to_object(interpreter.global_object()));
  569. auto complete = TRY(iterator_complete(interpreter.global_object(), *iterator_result));
  570. interpreter.accumulator() = Value(complete);
  571. return {};
  572. }
  573. ThrowCompletionOr<void> IteratorResultValue::execute_impl(Bytecode::Interpreter& interpreter) const
  574. {
  575. auto* iterator_result = TRY(interpreter.accumulator().to_object(interpreter.global_object()));
  576. interpreter.accumulator() = TRY(iterator_value(interpreter.global_object(), *iterator_result));
  577. return {};
  578. }
  579. ThrowCompletionOr<void> NewClass::execute_impl(Bytecode::Interpreter& interpreter) const
  580. {
  581. auto name = m_class_expression.name();
  582. auto scope = interpreter.ast_interpreter_scope();
  583. auto& ast_interpreter = scope.interpreter();
  584. auto class_object = TRY(m_class_expression.class_definition_evaluation(ast_interpreter, interpreter.global_object(), name, name.is_null() ? "" : name));
  585. interpreter.accumulator() = class_object;
  586. return {};
  587. }
  588. String Load::to_string_impl(Bytecode::Executable const&) const
  589. {
  590. return String::formatted("Load {}", m_src);
  591. }
  592. String LoadImmediate::to_string_impl(Bytecode::Executable const&) const
  593. {
  594. return String::formatted("LoadImmediate {}", m_value);
  595. }
  596. String Store::to_string_impl(Bytecode::Executable const&) const
  597. {
  598. return String::formatted("Store {}", m_dst);
  599. }
  600. String NewBigInt::to_string_impl(Bytecode::Executable const&) const
  601. {
  602. return String::formatted("NewBigInt \"{}\"", m_bigint.to_base(10));
  603. }
  604. String NewArray::to_string_impl(Bytecode::Executable const&) const
  605. {
  606. StringBuilder builder;
  607. builder.append("NewArray");
  608. if (m_element_count != 0) {
  609. builder.append(" [");
  610. for (size_t i = 0; i < m_element_count; ++i) {
  611. builder.appendff("{}", m_elements[i]);
  612. if (i != m_element_count - 1)
  613. builder.append(',');
  614. }
  615. builder.append(']');
  616. }
  617. return builder.to_string();
  618. }
  619. String IteratorToArray::to_string_impl(const Bytecode::Executable&) const
  620. {
  621. return "IteratorToArray";
  622. }
  623. String NewString::to_string_impl(Bytecode::Executable const& executable) const
  624. {
  625. return String::formatted("NewString {} (\"{}\")", m_string, executable.string_table->get(m_string));
  626. }
  627. String NewObject::to_string_impl(Bytecode::Executable const&) const
  628. {
  629. return "NewObject";
  630. }
  631. String NewRegExp::to_string_impl(Bytecode::Executable const& executable) const
  632. {
  633. return String::formatted("NewRegExp source:{} (\"{}\") flags:{} (\"{}\")", m_source_index, executable.get_string(m_source_index), m_flags_index, executable.get_string(m_flags_index));
  634. }
  635. String CopyObjectExcludingProperties::to_string_impl(const Bytecode::Executable&) const
  636. {
  637. StringBuilder builder;
  638. builder.appendff("CopyObjectExcludingProperties from:{}", m_from_object);
  639. if (m_excluded_names_count != 0) {
  640. builder.append(" excluding:[");
  641. for (size_t i = 0; i < m_excluded_names_count; ++i) {
  642. builder.appendff("{}", m_excluded_names[i]);
  643. if (i != m_excluded_names_count - 1)
  644. builder.append(',');
  645. }
  646. builder.append(']');
  647. }
  648. return builder.to_string();
  649. }
  650. String ConcatString::to_string_impl(Bytecode::Executable const&) const
  651. {
  652. return String::formatted("ConcatString {}", m_lhs);
  653. }
  654. String GetVariable::to_string_impl(Bytecode::Executable const& executable) const
  655. {
  656. return String::formatted("GetVariable {} ({})", m_identifier, executable.identifier_table->get(m_identifier));
  657. }
  658. String CreateEnvironment::to_string_impl(Bytecode::Executable const&) const
  659. {
  660. auto mode_string = m_mode == EnvironmentMode::Lexical
  661. ? "Lexical"
  662. : "Variable";
  663. return String::formatted("CreateEnvironment mode:{}", mode_string);
  664. }
  665. String CreateVariable::to_string_impl(Bytecode::Executable const& executable) const
  666. {
  667. auto mode_string = m_mode == EnvironmentMode::Lexical ? "Lexical" : "Variable";
  668. return String::formatted("CreateVariable env:{} immutable:{} {} ({})", mode_string, m_is_immutable, m_identifier, executable.identifier_table->get(m_identifier));
  669. }
  670. String EnterObjectEnvironment::to_string_impl(const Executable&) const
  671. {
  672. return String::formatted("EnterObjectEnvironment");
  673. }
  674. String SetVariable::to_string_impl(Bytecode::Executable const& executable) const
  675. {
  676. auto initialization_mode_name = m_initialization_mode == InitializationMode ::Initialize ? "Initialize"
  677. : m_initialization_mode == InitializationMode::Set ? "Set"
  678. : "InitializeOrSet";
  679. auto mode_string = m_mode == EnvironmentMode::Lexical ? "Lexical" : "Variable";
  680. return String::formatted("SetVariable env:{} init:{} {} ({})", mode_string, initialization_mode_name, m_identifier, executable.identifier_table->get(m_identifier));
  681. }
  682. String PutById::to_string_impl(Bytecode::Executable const& executable) const
  683. {
  684. return String::formatted("PutById base:{}, property:{} ({})", m_base, m_property, executable.identifier_table->get(m_property));
  685. }
  686. String GetById::to_string_impl(Bytecode::Executable const& executable) const
  687. {
  688. return String::formatted("GetById {} ({})", m_property, executable.identifier_table->get(m_property));
  689. }
  690. String Jump::to_string_impl(Bytecode::Executable const&) const
  691. {
  692. if (m_true_target.has_value())
  693. return String::formatted("Jump {}", *m_true_target);
  694. return String::formatted("Jump <empty>");
  695. }
  696. String JumpConditional::to_string_impl(Bytecode::Executable const&) const
  697. {
  698. auto true_string = m_true_target.has_value() ? String::formatted("{}", *m_true_target) : "<empty>";
  699. auto false_string = m_false_target.has_value() ? String::formatted("{}", *m_false_target) : "<empty>";
  700. return String::formatted("JumpConditional true:{} false:{}", true_string, false_string);
  701. }
  702. String JumpNullish::to_string_impl(Bytecode::Executable const&) const
  703. {
  704. auto true_string = m_true_target.has_value() ? String::formatted("{}", *m_true_target) : "<empty>";
  705. auto false_string = m_false_target.has_value() ? String::formatted("{}", *m_false_target) : "<empty>";
  706. return String::formatted("JumpNullish null:{} nonnull:{}", true_string, false_string);
  707. }
  708. String JumpUndefined::to_string_impl(Bytecode::Executable const&) const
  709. {
  710. auto true_string = m_true_target.has_value() ? String::formatted("{}", *m_true_target) : "<empty>";
  711. auto false_string = m_false_target.has_value() ? String::formatted("{}", *m_false_target) : "<empty>";
  712. return String::formatted("JumpUndefined undefined:{} not undefined:{}", true_string, false_string);
  713. }
  714. String Call::to_string_impl(Bytecode::Executable const&) const
  715. {
  716. StringBuilder builder;
  717. builder.appendff("Call callee:{}, this:{}", m_callee, m_this_value);
  718. if (m_argument_count != 0) {
  719. builder.append(", arguments:[");
  720. for (size_t i = 0; i < m_argument_count; ++i) {
  721. builder.appendff("{}", m_arguments[i]);
  722. if (i != m_argument_count - 1)
  723. builder.append(',');
  724. }
  725. builder.append(']');
  726. }
  727. return builder.to_string();
  728. }
  729. String NewFunction::to_string_impl(Bytecode::Executable const&) const
  730. {
  731. return "NewFunction";
  732. }
  733. String NewClass::to_string_impl(Bytecode::Executable const&) const
  734. {
  735. return "NewClass";
  736. }
  737. String Return::to_string_impl(Bytecode::Executable const&) const
  738. {
  739. return "Return";
  740. }
  741. String Increment::to_string_impl(Bytecode::Executable const&) const
  742. {
  743. return "Increment";
  744. }
  745. String Decrement::to_string_impl(Bytecode::Executable const&) const
  746. {
  747. return "Decrement";
  748. }
  749. String Throw::to_string_impl(Bytecode::Executable const&) const
  750. {
  751. return "Throw";
  752. }
  753. String EnterUnwindContext::to_string_impl(Bytecode::Executable const&) const
  754. {
  755. auto handler_string = m_handler_target.has_value() ? String::formatted("{}", *m_handler_target) : "<empty>";
  756. auto finalizer_string = m_finalizer_target.has_value() ? String::formatted("{}", *m_finalizer_target) : "<empty>";
  757. return String::formatted("EnterUnwindContext handler:{} finalizer:{} entry:{}", handler_string, finalizer_string, m_entry_point);
  758. }
  759. String FinishUnwind::to_string_impl(const Bytecode::Executable&) const
  760. {
  761. return String::formatted("FinishUnwind next:{}", m_next_target);
  762. }
  763. String LeaveEnvironment::to_string_impl(Bytecode::Executable const&) const
  764. {
  765. auto mode_string = m_mode == EnvironmentMode::Lexical
  766. ? "Lexical"
  767. : "Variable";
  768. return String::formatted("LeaveEnvironment env:{}", mode_string);
  769. }
  770. String LeaveUnwindContext::to_string_impl(Bytecode::Executable const&) const
  771. {
  772. return "LeaveUnwindContext";
  773. }
  774. String ContinuePendingUnwind::to_string_impl(Bytecode::Executable const&) const
  775. {
  776. return String::formatted("ContinuePendingUnwind resume:{}", m_resume_target);
  777. }
  778. String PushDeclarativeEnvironment::to_string_impl(const Bytecode::Executable& executable) const
  779. {
  780. StringBuilder builder;
  781. builder.append("PushDeclarativeEnvironment");
  782. if (!m_variables.is_empty()) {
  783. builder.append(" {");
  784. Vector<String> names;
  785. for (auto& it : m_variables)
  786. names.append(executable.get_string(it.key));
  787. builder.join(", ", names);
  788. builder.append("}");
  789. }
  790. return builder.to_string();
  791. }
  792. String Yield::to_string_impl(Bytecode::Executable const&) const
  793. {
  794. if (m_continuation_label.has_value())
  795. return String::formatted("Yield continuation:@{}", m_continuation_label->block().name());
  796. return String::formatted("Yield return");
  797. }
  798. String GetByValue::to_string_impl(const Bytecode::Executable&) const
  799. {
  800. return String::formatted("GetByValue base:{}", m_base);
  801. }
  802. String PutByValue::to_string_impl(const Bytecode::Executable&) const
  803. {
  804. return String::formatted("PutByValue base:{}, property:{}", m_base, m_property);
  805. }
  806. String GetIterator::to_string_impl(Executable const&) const
  807. {
  808. return "GetIterator";
  809. }
  810. String GetObjectPropertyIterator::to_string_impl(const Bytecode::Executable&) const
  811. {
  812. return "GetObjectPropertyIterator";
  813. }
  814. String IteratorNext::to_string_impl(Executable const&) const
  815. {
  816. return "IteratorNext";
  817. }
  818. String IteratorResultDone::to_string_impl(Executable const&) const
  819. {
  820. return "IteratorResultDone";
  821. }
  822. String IteratorResultValue::to_string_impl(Executable const&) const
  823. {
  824. return "IteratorResultValue";
  825. }
  826. String ResolveThisBinding::to_string_impl(Bytecode::Executable const&) const
  827. {
  828. return "ResolveThisBinding"sv;
  829. }
  830. }