Op.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  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. ThrowCompletionOr<void> GetNewTarget::execute_impl(Bytecode::Interpreter& interpreter) const
  307. {
  308. interpreter.accumulator() = interpreter.vm().get_new_target();
  309. return {};
  310. }
  311. void Jump::replace_references_impl(BasicBlock const& from, BasicBlock const& to)
  312. {
  313. if (m_true_target.has_value() && &m_true_target->block() == &from)
  314. m_true_target = Label { to };
  315. if (m_false_target.has_value() && &m_false_target->block() == &from)
  316. m_false_target = Label { to };
  317. }
  318. ThrowCompletionOr<void> JumpConditional::execute_impl(Bytecode::Interpreter& interpreter) const
  319. {
  320. VERIFY(m_true_target.has_value());
  321. VERIFY(m_false_target.has_value());
  322. auto result = interpreter.accumulator();
  323. if (result.to_boolean())
  324. interpreter.jump(m_true_target.value());
  325. else
  326. interpreter.jump(m_false_target.value());
  327. return {};
  328. }
  329. ThrowCompletionOr<void> JumpNullish::execute_impl(Bytecode::Interpreter& interpreter) const
  330. {
  331. VERIFY(m_true_target.has_value());
  332. VERIFY(m_false_target.has_value());
  333. auto result = interpreter.accumulator();
  334. if (result.is_nullish())
  335. interpreter.jump(m_true_target.value());
  336. else
  337. interpreter.jump(m_false_target.value());
  338. return {};
  339. }
  340. ThrowCompletionOr<void> JumpUndefined::execute_impl(Bytecode::Interpreter& interpreter) const
  341. {
  342. VERIFY(m_true_target.has_value());
  343. VERIFY(m_false_target.has_value());
  344. auto result = interpreter.accumulator();
  345. if (result.is_undefined())
  346. interpreter.jump(m_true_target.value());
  347. else
  348. interpreter.jump(m_false_target.value());
  349. return {};
  350. }
  351. ThrowCompletionOr<void> Call::execute_impl(Bytecode::Interpreter& interpreter) const
  352. {
  353. auto callee = interpreter.reg(m_callee);
  354. if (!callee.is_function())
  355. return interpreter.vm().throw_completion<TypeError>(interpreter.global_object(), ErrorType::IsNotA, callee.to_string_without_side_effects(), "function"sv);
  356. auto& function = callee.as_function();
  357. auto this_value = interpreter.reg(m_this_value);
  358. MarkedVector<Value> argument_values { interpreter.vm().heap() };
  359. for (size_t i = 0; i < m_argument_count; ++i)
  360. argument_values.append(interpreter.reg(m_arguments[i]));
  361. Value return_value;
  362. if (m_type == CallType::Call)
  363. return_value = TRY(call(interpreter.global_object(), function, this_value, move(argument_values)));
  364. else
  365. return_value = TRY(construct(interpreter.global_object(), function, move(argument_values)));
  366. interpreter.accumulator() = return_value;
  367. return {};
  368. }
  369. ThrowCompletionOr<void> NewFunction::execute_impl(Bytecode::Interpreter& interpreter) const
  370. {
  371. auto& vm = interpreter.vm();
  372. 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());
  373. return {};
  374. }
  375. ThrowCompletionOr<void> Return::execute_impl(Bytecode::Interpreter& interpreter) const
  376. {
  377. interpreter.do_return(interpreter.accumulator().value_or(js_undefined()));
  378. return {};
  379. }
  380. ThrowCompletionOr<void> Increment::execute_impl(Bytecode::Interpreter& interpreter) const
  381. {
  382. auto old_value = TRY(interpreter.accumulator().to_numeric(interpreter.global_object()));
  383. if (old_value.is_number())
  384. interpreter.accumulator() = Value(old_value.as_double() + 1);
  385. else
  386. interpreter.accumulator() = js_bigint(interpreter.vm().heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  387. return {};
  388. }
  389. ThrowCompletionOr<void> Decrement::execute_impl(Bytecode::Interpreter& interpreter) const
  390. {
  391. auto old_value = TRY(interpreter.accumulator().to_numeric(interpreter.global_object()));
  392. if (old_value.is_number())
  393. interpreter.accumulator() = Value(old_value.as_double() - 1);
  394. else
  395. interpreter.accumulator() = js_bigint(interpreter.vm().heap(), old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
  396. return {};
  397. }
  398. ThrowCompletionOr<void> Throw::execute_impl(Bytecode::Interpreter& interpreter) const
  399. {
  400. return throw_completion(interpreter.accumulator());
  401. }
  402. ThrowCompletionOr<void> EnterUnwindContext::execute_impl(Bytecode::Interpreter& interpreter) const
  403. {
  404. interpreter.enter_unwind_context(m_handler_target, m_finalizer_target);
  405. interpreter.jump(m_entry_point);
  406. return {};
  407. }
  408. void EnterUnwindContext::replace_references_impl(BasicBlock const& from, BasicBlock const& to)
  409. {
  410. if (&m_entry_point.block() == &from)
  411. m_entry_point = Label { to };
  412. if (m_handler_target.has_value() && &m_handler_target->block() == &from)
  413. m_handler_target = Label { to };
  414. if (m_finalizer_target.has_value() && &m_finalizer_target->block() == &from)
  415. m_finalizer_target = Label { to };
  416. }
  417. ThrowCompletionOr<void> FinishUnwind::execute_impl(Bytecode::Interpreter& interpreter) const
  418. {
  419. interpreter.leave_unwind_context();
  420. interpreter.jump(m_next_target);
  421. return {};
  422. }
  423. void FinishUnwind::replace_references_impl(BasicBlock const& from, BasicBlock const& to)
  424. {
  425. if (&m_next_target.block() == &from)
  426. m_next_target = Label { to };
  427. }
  428. ThrowCompletionOr<void> LeaveEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  429. {
  430. if (m_mode == EnvironmentMode::Lexical)
  431. interpreter.vm().running_execution_context().lexical_environment = interpreter.saved_lexical_environment_stack().take_last();
  432. if (m_mode == EnvironmentMode::Var)
  433. interpreter.vm().running_execution_context().variable_environment = interpreter.saved_variable_environment_stack().take_last();
  434. return {};
  435. }
  436. ThrowCompletionOr<void> LeaveUnwindContext::execute_impl(Bytecode::Interpreter& interpreter) const
  437. {
  438. interpreter.leave_unwind_context();
  439. return {};
  440. }
  441. ThrowCompletionOr<void> ContinuePendingUnwind::execute_impl(Bytecode::Interpreter& interpreter) const
  442. {
  443. return interpreter.continue_pending_unwind(m_resume_target);
  444. }
  445. void ContinuePendingUnwind::replace_references_impl(BasicBlock const& from, BasicBlock const& to)
  446. {
  447. if (&m_resume_target.block() == &from)
  448. m_resume_target = Label { to };
  449. }
  450. ThrowCompletionOr<void> PushDeclarativeEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  451. {
  452. auto* environment = interpreter.vm().heap().allocate_without_global_object<DeclarativeEnvironment>(interpreter.vm().lexical_environment());
  453. interpreter.vm().running_execution_context().lexical_environment = environment;
  454. interpreter.vm().running_execution_context().variable_environment = environment;
  455. return {};
  456. }
  457. ThrowCompletionOr<void> Yield::execute_impl(Bytecode::Interpreter& interpreter) const
  458. {
  459. auto yielded_value = interpreter.accumulator().value_or(js_undefined());
  460. auto object = JS::Object::create(interpreter.global_object(), nullptr);
  461. object->define_direct_property("result", yielded_value, JS::default_attributes);
  462. if (m_continuation_label.has_value())
  463. object->define_direct_property("continuation", Value(static_cast<double>(reinterpret_cast<u64>(&m_continuation_label->block()))), JS::default_attributes);
  464. else
  465. object->define_direct_property("continuation", Value(0), JS::default_attributes);
  466. interpreter.do_return(object);
  467. return {};
  468. }
  469. void Yield::replace_references_impl(BasicBlock const& from, BasicBlock const& to)
  470. {
  471. if (m_continuation_label.has_value() && &m_continuation_label->block() == &from)
  472. m_continuation_label = Label { to };
  473. }
  474. ThrowCompletionOr<void> GetByValue::execute_impl(Bytecode::Interpreter& interpreter) const
  475. {
  476. auto* object = TRY(interpreter.reg(m_base).to_object(interpreter.global_object()));
  477. auto property_key = TRY(interpreter.accumulator().to_property_key(interpreter.global_object()));
  478. interpreter.accumulator() = TRY(object->get(property_key));
  479. return {};
  480. }
  481. ThrowCompletionOr<void> PutByValue::execute_impl(Bytecode::Interpreter& interpreter) const
  482. {
  483. auto* object = TRY(interpreter.reg(m_base).to_object(interpreter.global_object()));
  484. auto property_key = TRY(interpreter.reg(m_property).to_property_key(interpreter.global_object()));
  485. TRY(object->set(property_key, interpreter.accumulator(), Object::ShouldThrowExceptions::Yes));
  486. return {};
  487. }
  488. ThrowCompletionOr<void> GetIterator::execute_impl(Bytecode::Interpreter& interpreter) const
  489. {
  490. auto iterator = TRY(get_iterator(interpreter.global_object(), interpreter.accumulator()));
  491. interpreter.accumulator() = iterator_to_object(interpreter.global_object(), iterator);
  492. return {};
  493. }
  494. // 14.7.5.9 EnumerateObjectProperties ( O ), https://tc39.es/ecma262/#sec-enumerate-object-properties
  495. ThrowCompletionOr<void> GetObjectPropertyIterator::execute_impl(Bytecode::Interpreter& interpreter) const
  496. {
  497. // While the spec does provide an algorithm, it allows us to implement it ourselves so long as we meet the following invariants:
  498. // 1- Returned property keys do not include keys that are Symbols
  499. // 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
  500. // 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
  501. // 4- A property name will be returned by the iterator's next method at most once in any enumeration.
  502. // 5- Enumerating the properties of the target object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively;
  503. // 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.
  504. // 6- The values of [[Enumerable]] attributes are not considered when determining if a property of a prototype object has already been processed.
  505. // 7- The enumerable property names of prototype objects must be obtained by invoking EnumerateObjectProperties passing the prototype object as the argument.
  506. // 8- EnumerateObjectProperties must obtain the own property keys of the target object by calling its [[OwnPropertyKeys]] internal method.
  507. // 9- Property attributes of the target object must be obtained by calling its [[GetOwnProperty]] internal method
  508. // Invariant 3 effectively allows the implementation to ignore newly added keys, and we do so (similar to other implementations).
  509. // Invariants 1 and 6 through 9 are implemented in `enumerable_own_property_names`, which implements the EnumerableOwnPropertyNames AO.
  510. auto* object = TRY(interpreter.accumulator().to_object(interpreter.global_object()));
  511. // Note: While the spec doesn't explicitly require these to be ordered, it says that the values should be retrieved via OwnPropertyKeys,
  512. // so we just keep the order consistent anyway.
  513. OrderedHashTable<PropertyKey> properties;
  514. HashTable<Object*> seen_objects;
  515. // Collect all keys immediately (invariant no. 5)
  516. 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())) {
  517. seen_objects.set(object_to_check);
  518. for (auto& key : TRY(object_to_check->enumerable_own_property_names(Object::PropertyKind::Key))) {
  519. properties.set(TRY(PropertyKey::from_value(interpreter.global_object(), key)));
  520. }
  521. }
  522. Iterator iterator {
  523. .iterator = object,
  524. .next_method = NativeFunction::create(
  525. interpreter.global_object(),
  526. [seen_items = HashTable<PropertyKey>(), items = move(properties)](VM& vm, GlobalObject& global_object) mutable -> ThrowCompletionOr<Value> {
  527. auto iterated_object_value = vm.this_value(global_object);
  528. if (!iterated_object_value.is_object())
  529. return vm.throw_completion<InternalError>(global_object, "Invalid state for GetObjectPropertyIterator.next");
  530. auto& iterated_object = iterated_object_value.as_object();
  531. auto* result_object = Object::create(global_object, nullptr);
  532. while (true) {
  533. if (items.is_empty()) {
  534. result_object->define_direct_property(vm.names.done, JS::Value(true), default_attributes);
  535. return result_object;
  536. }
  537. auto it = items.begin();
  538. auto key = *it;
  539. items.remove(it);
  540. // If the key was already seen, skip over it (invariant no. 4)
  541. auto result = seen_items.set(key);
  542. if (result != AK::HashSetResult::InsertedNewEntry)
  543. continue;
  544. // If the property is deleted, don't include it (invariant no. 2)
  545. if (!TRY(iterated_object.has_property(key)))
  546. continue;
  547. result_object->define_direct_property(vm.names.done, JS::Value(false), default_attributes);
  548. if (key.is_number())
  549. result_object->define_direct_property(vm.names.value, JS::Value(key.as_number()), default_attributes);
  550. else if (key.is_string())
  551. result_object->define_direct_property(vm.names.value, js_string(vm.heap(), key.as_string()), default_attributes);
  552. else
  553. VERIFY_NOT_REACHED(); // We should not have non-string/number keys.
  554. return result_object;
  555. }
  556. },
  557. 1,
  558. interpreter.vm().names.next),
  559. .done = false,
  560. };
  561. interpreter.accumulator() = iterator_to_object(interpreter.global_object(), move(iterator));
  562. return {};
  563. }
  564. ThrowCompletionOr<void> IteratorNext::execute_impl(Bytecode::Interpreter& interpreter) const
  565. {
  566. auto* iterator_object = TRY(interpreter.accumulator().to_object(interpreter.global_object()));
  567. auto iterator = object_to_iterator(interpreter.global_object(), *iterator_object);
  568. interpreter.accumulator() = TRY(iterator_next(interpreter.global_object(), iterator));
  569. return {};
  570. }
  571. ThrowCompletionOr<void> IteratorResultDone::execute_impl(Bytecode::Interpreter& interpreter) const
  572. {
  573. auto* iterator_result = TRY(interpreter.accumulator().to_object(interpreter.global_object()));
  574. auto complete = TRY(iterator_complete(interpreter.global_object(), *iterator_result));
  575. interpreter.accumulator() = Value(complete);
  576. return {};
  577. }
  578. ThrowCompletionOr<void> IteratorResultValue::execute_impl(Bytecode::Interpreter& interpreter) const
  579. {
  580. auto* iterator_result = TRY(interpreter.accumulator().to_object(interpreter.global_object()));
  581. interpreter.accumulator() = TRY(iterator_value(interpreter.global_object(), *iterator_result));
  582. return {};
  583. }
  584. ThrowCompletionOr<void> NewClass::execute_impl(Bytecode::Interpreter& interpreter) const
  585. {
  586. auto name = m_class_expression.name();
  587. auto scope = interpreter.ast_interpreter_scope();
  588. auto& ast_interpreter = scope.interpreter();
  589. auto class_object = TRY(m_class_expression.class_definition_evaluation(ast_interpreter, interpreter.global_object(), name, name.is_null() ? "" : name));
  590. interpreter.accumulator() = class_object;
  591. return {};
  592. }
  593. String Load::to_string_impl(Bytecode::Executable const&) const
  594. {
  595. return String::formatted("Load {}", m_src);
  596. }
  597. String LoadImmediate::to_string_impl(Bytecode::Executable const&) const
  598. {
  599. return String::formatted("LoadImmediate {}", m_value);
  600. }
  601. String Store::to_string_impl(Bytecode::Executable const&) const
  602. {
  603. return String::formatted("Store {}", m_dst);
  604. }
  605. String NewBigInt::to_string_impl(Bytecode::Executable const&) const
  606. {
  607. return String::formatted("NewBigInt \"{}\"", m_bigint.to_base(10));
  608. }
  609. String NewArray::to_string_impl(Bytecode::Executable const&) const
  610. {
  611. StringBuilder builder;
  612. builder.append("NewArray");
  613. if (m_element_count != 0) {
  614. builder.append(" [");
  615. for (size_t i = 0; i < m_element_count; ++i) {
  616. builder.appendff("{}", m_elements[i]);
  617. if (i != m_element_count - 1)
  618. builder.append(',');
  619. }
  620. builder.append(']');
  621. }
  622. return builder.to_string();
  623. }
  624. String IteratorToArray::to_string_impl(const Bytecode::Executable&) const
  625. {
  626. return "IteratorToArray";
  627. }
  628. String NewString::to_string_impl(Bytecode::Executable const& executable) const
  629. {
  630. return String::formatted("NewString {} (\"{}\")", m_string, executable.string_table->get(m_string));
  631. }
  632. String NewObject::to_string_impl(Bytecode::Executable const&) const
  633. {
  634. return "NewObject";
  635. }
  636. String NewRegExp::to_string_impl(Bytecode::Executable const& executable) const
  637. {
  638. return String::formatted("NewRegExp source:{} (\"{}\") flags:{} (\"{}\")", m_source_index, executable.get_string(m_source_index), m_flags_index, executable.get_string(m_flags_index));
  639. }
  640. String CopyObjectExcludingProperties::to_string_impl(const Bytecode::Executable&) const
  641. {
  642. StringBuilder builder;
  643. builder.appendff("CopyObjectExcludingProperties from:{}", m_from_object);
  644. if (m_excluded_names_count != 0) {
  645. builder.append(" excluding:[");
  646. for (size_t i = 0; i < m_excluded_names_count; ++i) {
  647. builder.appendff("{}", m_excluded_names[i]);
  648. if (i != m_excluded_names_count - 1)
  649. builder.append(',');
  650. }
  651. builder.append(']');
  652. }
  653. return builder.to_string();
  654. }
  655. String ConcatString::to_string_impl(Bytecode::Executable const&) const
  656. {
  657. return String::formatted("ConcatString {}", m_lhs);
  658. }
  659. String GetVariable::to_string_impl(Bytecode::Executable const& executable) const
  660. {
  661. return String::formatted("GetVariable {} ({})", m_identifier, executable.identifier_table->get(m_identifier));
  662. }
  663. String CreateEnvironment::to_string_impl(Bytecode::Executable const&) const
  664. {
  665. auto mode_string = m_mode == EnvironmentMode::Lexical
  666. ? "Lexical"
  667. : "Variable";
  668. return String::formatted("CreateEnvironment mode:{}", mode_string);
  669. }
  670. String CreateVariable::to_string_impl(Bytecode::Executable const& executable) const
  671. {
  672. auto mode_string = m_mode == EnvironmentMode::Lexical ? "Lexical" : "Variable";
  673. return String::formatted("CreateVariable env:{} immutable:{} {} ({})", mode_string, m_is_immutable, m_identifier, executable.identifier_table->get(m_identifier));
  674. }
  675. String EnterObjectEnvironment::to_string_impl(const Executable&) const
  676. {
  677. return String::formatted("EnterObjectEnvironment");
  678. }
  679. String SetVariable::to_string_impl(Bytecode::Executable const& executable) const
  680. {
  681. auto initialization_mode_name = m_initialization_mode == InitializationMode ::Initialize ? "Initialize"
  682. : m_initialization_mode == InitializationMode::Set ? "Set"
  683. : "InitializeOrSet";
  684. auto mode_string = m_mode == EnvironmentMode::Lexical ? "Lexical" : "Variable";
  685. return String::formatted("SetVariable env:{} init:{} {} ({})", mode_string, initialization_mode_name, m_identifier, executable.identifier_table->get(m_identifier));
  686. }
  687. String PutById::to_string_impl(Bytecode::Executable const& executable) const
  688. {
  689. return String::formatted("PutById base:{}, property:{} ({})", m_base, m_property, executable.identifier_table->get(m_property));
  690. }
  691. String GetById::to_string_impl(Bytecode::Executable const& executable) const
  692. {
  693. return String::formatted("GetById {} ({})", m_property, executable.identifier_table->get(m_property));
  694. }
  695. String Jump::to_string_impl(Bytecode::Executable const&) const
  696. {
  697. if (m_true_target.has_value())
  698. return String::formatted("Jump {}", *m_true_target);
  699. return String::formatted("Jump <empty>");
  700. }
  701. String JumpConditional::to_string_impl(Bytecode::Executable const&) const
  702. {
  703. auto true_string = m_true_target.has_value() ? String::formatted("{}", *m_true_target) : "<empty>";
  704. auto false_string = m_false_target.has_value() ? String::formatted("{}", *m_false_target) : "<empty>";
  705. return String::formatted("JumpConditional true:{} false:{}", true_string, false_string);
  706. }
  707. String JumpNullish::to_string_impl(Bytecode::Executable const&) const
  708. {
  709. auto true_string = m_true_target.has_value() ? String::formatted("{}", *m_true_target) : "<empty>";
  710. auto false_string = m_false_target.has_value() ? String::formatted("{}", *m_false_target) : "<empty>";
  711. return String::formatted("JumpNullish null:{} nonnull:{}", true_string, false_string);
  712. }
  713. String JumpUndefined::to_string_impl(Bytecode::Executable const&) const
  714. {
  715. auto true_string = m_true_target.has_value() ? String::formatted("{}", *m_true_target) : "<empty>";
  716. auto false_string = m_false_target.has_value() ? String::formatted("{}", *m_false_target) : "<empty>";
  717. return String::formatted("JumpUndefined undefined:{} not undefined:{}", true_string, false_string);
  718. }
  719. String Call::to_string_impl(Bytecode::Executable const&) const
  720. {
  721. StringBuilder builder;
  722. builder.appendff("Call callee:{}, this:{}", m_callee, m_this_value);
  723. if (m_argument_count != 0) {
  724. builder.append(", arguments:[");
  725. for (size_t i = 0; i < m_argument_count; ++i) {
  726. builder.appendff("{}", m_arguments[i]);
  727. if (i != m_argument_count - 1)
  728. builder.append(',');
  729. }
  730. builder.append(']');
  731. }
  732. return builder.to_string();
  733. }
  734. String NewFunction::to_string_impl(Bytecode::Executable const&) const
  735. {
  736. return "NewFunction";
  737. }
  738. String NewClass::to_string_impl(Bytecode::Executable const&) const
  739. {
  740. return "NewClass";
  741. }
  742. String Return::to_string_impl(Bytecode::Executable const&) const
  743. {
  744. return "Return";
  745. }
  746. String Increment::to_string_impl(Bytecode::Executable const&) const
  747. {
  748. return "Increment";
  749. }
  750. String Decrement::to_string_impl(Bytecode::Executable const&) const
  751. {
  752. return "Decrement";
  753. }
  754. String Throw::to_string_impl(Bytecode::Executable const&) const
  755. {
  756. return "Throw";
  757. }
  758. String EnterUnwindContext::to_string_impl(Bytecode::Executable const&) const
  759. {
  760. auto handler_string = m_handler_target.has_value() ? String::formatted("{}", *m_handler_target) : "<empty>";
  761. auto finalizer_string = m_finalizer_target.has_value() ? String::formatted("{}", *m_finalizer_target) : "<empty>";
  762. return String::formatted("EnterUnwindContext handler:{} finalizer:{} entry:{}", handler_string, finalizer_string, m_entry_point);
  763. }
  764. String FinishUnwind::to_string_impl(const Bytecode::Executable&) const
  765. {
  766. return String::formatted("FinishUnwind next:{}", m_next_target);
  767. }
  768. String LeaveEnvironment::to_string_impl(Bytecode::Executable const&) const
  769. {
  770. auto mode_string = m_mode == EnvironmentMode::Lexical
  771. ? "Lexical"
  772. : "Variable";
  773. return String::formatted("LeaveEnvironment env:{}", mode_string);
  774. }
  775. String LeaveUnwindContext::to_string_impl(Bytecode::Executable const&) const
  776. {
  777. return "LeaveUnwindContext";
  778. }
  779. String ContinuePendingUnwind::to_string_impl(Bytecode::Executable const&) const
  780. {
  781. return String::formatted("ContinuePendingUnwind resume:{}", m_resume_target);
  782. }
  783. String PushDeclarativeEnvironment::to_string_impl(const Bytecode::Executable& executable) const
  784. {
  785. StringBuilder builder;
  786. builder.append("PushDeclarativeEnvironment");
  787. if (!m_variables.is_empty()) {
  788. builder.append(" {");
  789. Vector<String> names;
  790. for (auto& it : m_variables)
  791. names.append(executable.get_string(it.key));
  792. builder.join(", ", names);
  793. builder.append("}");
  794. }
  795. return builder.to_string();
  796. }
  797. String Yield::to_string_impl(Bytecode::Executable const&) const
  798. {
  799. if (m_continuation_label.has_value())
  800. return String::formatted("Yield continuation:@{}", m_continuation_label->block().name());
  801. return String::formatted("Yield return");
  802. }
  803. String GetByValue::to_string_impl(const Bytecode::Executable&) const
  804. {
  805. return String::formatted("GetByValue base:{}", m_base);
  806. }
  807. String PutByValue::to_string_impl(const Bytecode::Executable&) const
  808. {
  809. return String::formatted("PutByValue base:{}, property:{}", m_base, m_property);
  810. }
  811. String GetIterator::to_string_impl(Executable const&) const
  812. {
  813. return "GetIterator";
  814. }
  815. String GetObjectPropertyIterator::to_string_impl(const Bytecode::Executable&) const
  816. {
  817. return "GetObjectPropertyIterator";
  818. }
  819. String IteratorNext::to_string_impl(Executable const&) const
  820. {
  821. return "IteratorNext";
  822. }
  823. String IteratorResultDone::to_string_impl(Executable const&) const
  824. {
  825. return "IteratorResultDone";
  826. }
  827. String IteratorResultValue::to_string_impl(Executable const&) const
  828. {
  829. return "IteratorResultValue";
  830. }
  831. String ResolveThisBinding::to_string_impl(Bytecode::Executable const&) const
  832. {
  833. return "ResolveThisBinding"sv;
  834. }
  835. String GetNewTarget::to_string_impl(Bytecode::Executable const&) const
  836. {
  837. return "GetNewTarget"sv;
  838. }
  839. }