Op.cpp 40 KB

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