Interpreter.cpp 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/HashTable.h>
  8. #include <AK/TemporaryChange.h>
  9. #include <LibJS/AST.h>
  10. #include <LibJS/Bytecode/BasicBlock.h>
  11. #include <LibJS/Bytecode/Generator.h>
  12. #include <LibJS/Bytecode/Instruction.h>
  13. #include <LibJS/Bytecode/Interpreter.h>
  14. #include <LibJS/Bytecode/Op.h>
  15. #include <LibJS/Runtime/AbstractOperations.h>
  16. #include <LibJS/Runtime/Array.h>
  17. #include <LibJS/Runtime/BigInt.h>
  18. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  19. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  20. #include <LibJS/Runtime/Environment.h>
  21. #include <LibJS/Runtime/FunctionEnvironment.h>
  22. #include <LibJS/Runtime/GlobalEnvironment.h>
  23. #include <LibJS/Runtime/GlobalObject.h>
  24. #include <LibJS/Runtime/Iterator.h>
  25. #include <LibJS/Runtime/NativeFunction.h>
  26. #include <LibJS/Runtime/ObjectEnvironment.h>
  27. #include <LibJS/Runtime/Realm.h>
  28. #include <LibJS/Runtime/Reference.h>
  29. #include <LibJS/Runtime/RegExpObject.h>
  30. #include <LibJS/Runtime/Value.h>
  31. #include <LibJS/SourceTextModule.h>
  32. namespace JS::Bytecode {
  33. bool g_dump_bytecode = false;
  34. Interpreter::Interpreter(VM& vm)
  35. : m_vm(vm)
  36. {
  37. }
  38. Interpreter::~Interpreter()
  39. {
  40. }
  41. void Interpreter::visit_edges(Cell::Visitor& visitor)
  42. {
  43. for (auto& frame : m_call_frames) {
  44. frame.visit([&](auto& value) { value->visit_edges(visitor); });
  45. }
  46. }
  47. // 16.1.6 ScriptEvaluation ( scriptRecord ), https://tc39.es/ecma262/#sec-runtime-semantics-scriptevaluation
  48. ThrowCompletionOr<Value> Interpreter::run(Script& script_record, JS::GCPtr<Environment> lexical_environment_override)
  49. {
  50. auto& vm = this->vm();
  51. // 1. Let globalEnv be scriptRecord.[[Realm]].[[GlobalEnv]].
  52. auto& global_environment = script_record.realm().global_environment();
  53. // 2. Let scriptContext be a new ECMAScript code execution context.
  54. ExecutionContext script_context(vm.heap());
  55. // 3. Set the Function of scriptContext to null.
  56. // NOTE: This was done during execution context construction.
  57. // 4. Set the Realm of scriptContext to scriptRecord.[[Realm]].
  58. script_context.realm = &script_record.realm();
  59. // 5. Set the ScriptOrModule of scriptContext to scriptRecord.
  60. script_context.script_or_module = NonnullGCPtr<Script>(script_record);
  61. // 6. Set the VariableEnvironment of scriptContext to globalEnv.
  62. script_context.variable_environment = &global_environment;
  63. // 7. Set the LexicalEnvironment of scriptContext to globalEnv.
  64. script_context.lexical_environment = &global_environment;
  65. // Non-standard: Override the lexical environment if requested.
  66. if (lexical_environment_override)
  67. script_context.lexical_environment = lexical_environment_override;
  68. // 8. Set the PrivateEnvironment of scriptContext to null.
  69. // NOTE: This isn't in the spec, but we require it.
  70. script_context.is_strict_mode = script_record.parse_node().is_strict_mode();
  71. // FIXME: 9. Suspend the currently running execution context.
  72. // 10. Push scriptContext onto the execution context stack; scriptContext is now the running execution context.
  73. TRY(vm.push_execution_context(script_context, {}));
  74. // 11. Let script be scriptRecord.[[ECMAScriptCode]].
  75. auto& script = script_record.parse_node();
  76. // 12. Let result be Completion(GlobalDeclarationInstantiation(script, globalEnv)).
  77. auto instantiation_result = script.global_declaration_instantiation(vm, global_environment);
  78. Completion result = instantiation_result.is_throw_completion() ? instantiation_result.throw_completion() : normal_completion({});
  79. // 13. If result.[[Type]] is normal, then
  80. if (result.type() == Completion::Type::Normal) {
  81. auto executable_result = JS::Bytecode::Generator::generate(script);
  82. if (executable_result.is_error()) {
  83. if (auto error_string = executable_result.error().to_string(); error_string.is_error())
  84. result = vm.template throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  85. else if (error_string = String::formatted("TODO({})", error_string.value()); error_string.is_error())
  86. result = vm.template throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  87. else
  88. result = JS::throw_completion(JS::InternalError::create(realm(), error_string.release_value()));
  89. } else {
  90. auto executable = executable_result.release_value();
  91. if (g_dump_bytecode)
  92. executable->dump();
  93. // a. Set result to the result of evaluating script.
  94. auto result_or_error = run_and_return_frame(*executable, nullptr);
  95. if (result_or_error.value.is_error())
  96. result = result_or_error.value.release_error();
  97. else
  98. result = result_or_error.frame->registers[0];
  99. }
  100. }
  101. // 14. If result.[[Type]] is normal and result.[[Value]] is empty, then
  102. if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
  103. // a. Set result to NormalCompletion(undefined).
  104. result = normal_completion(js_undefined());
  105. }
  106. // FIXME: 15. Suspend scriptContext and remove it from the execution context stack.
  107. vm.pop_execution_context();
  108. // 16. Assert: The execution context stack is not empty.
  109. VERIFY(!vm.execution_context_stack().is_empty());
  110. // FIXME: 17. Resume the context that is now on the top of the execution context stack as the running execution context.
  111. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  112. // in which case this is a no-op.
  113. // FIXME: These three should be moved out of Interpreter::run and give the host an option to run these, as it's up to the host when these get run.
  114. // https://tc39.es/ecma262/#sec-jobs for jobs and https://tc39.es/ecma262/#_ref_3508 for ClearKeptObjects
  115. // finish_execution_generation is particularly an issue for LibWeb, as the HTML spec wants to run it specifically after performing a microtask checkpoint.
  116. // The promise and registry cleanup queues don't cause LibWeb an issue, as LibWeb overrides the hooks that push onto these queues.
  117. vm.run_queued_promise_jobs();
  118. vm.run_queued_finalization_registry_cleanup_jobs();
  119. vm.finish_execution_generation();
  120. // 18. Return ? result.
  121. if (result.is_abrupt()) {
  122. VERIFY(result.type() == Completion::Type::Throw);
  123. return result.release_error();
  124. }
  125. VERIFY(result.value().has_value());
  126. return *result.value();
  127. }
  128. ThrowCompletionOr<Value> Interpreter::run(SourceTextModule& module)
  129. {
  130. // FIXME: This is not a entry point as defined in the spec, but is convenient.
  131. // To avoid work we use link_and_eval_module however that can already be
  132. // dangerous if the vm loaded other modules.
  133. auto& vm = this->vm();
  134. TRY(vm.link_and_eval_module(Badge<Bytecode::Interpreter> {}, module));
  135. vm.run_queued_promise_jobs();
  136. vm.run_queued_finalization_registry_cleanup_jobs();
  137. return js_undefined();
  138. }
  139. void Interpreter::run_bytecode()
  140. {
  141. auto* locals = vm().running_execution_context().local_variables.data();
  142. auto* registers = this->registers().data();
  143. auto& accumulator = this->accumulator();
  144. for (;;) {
  145. start:
  146. auto pc = InstructionStreamIterator { m_current_block->instruction_stream(), m_current_executable };
  147. TemporaryChange temp_change { m_pc, Optional<InstructionStreamIterator&>(pc) };
  148. bool will_return = false;
  149. bool will_yield = false;
  150. ThrowCompletionOr<void> result;
  151. while (!pc.at_end()) {
  152. auto& instruction = *pc;
  153. switch (instruction.type()) {
  154. case Instruction::Type::GetLocal: {
  155. auto& local = locals[static_cast<Op::GetLocal const&>(instruction).index()];
  156. if (local.is_empty()) {
  157. auto const& variable_name = vm().running_execution_context().function->local_variables_names()[static_cast<Op::GetLocal const&>(instruction).index()];
  158. result = vm().throw_completion<ReferenceError>(ErrorType::BindingNotInitialized, variable_name);
  159. break;
  160. }
  161. accumulator = local;
  162. break;
  163. }
  164. case Instruction::Type::SetLocal:
  165. locals[static_cast<Op::SetLocal const&>(instruction).index()] = accumulator;
  166. break;
  167. case Instruction::Type::Load:
  168. accumulator = registers[static_cast<Op::Load const&>(instruction).src().index()];
  169. break;
  170. case Instruction::Type::Store:
  171. registers[static_cast<Op::Store const&>(instruction).dst().index()] = accumulator;
  172. break;
  173. case Instruction::Type::LoadImmediate:
  174. accumulator = static_cast<Op::LoadImmediate const&>(instruction).value();
  175. break;
  176. case Instruction::Type::Jump:
  177. m_current_block = &static_cast<Op::Jump const&>(instruction).true_target()->block();
  178. goto start;
  179. case Instruction::Type::JumpConditional:
  180. if (accumulator.to_boolean())
  181. m_current_block = &static_cast<Op::Jump const&>(instruction).true_target()->block();
  182. else
  183. m_current_block = &static_cast<Op::Jump const&>(instruction).false_target()->block();
  184. goto start;
  185. case Instruction::Type::JumpNullish:
  186. if (accumulator.is_nullish())
  187. m_current_block = &static_cast<Op::Jump const&>(instruction).true_target()->block();
  188. else
  189. m_current_block = &static_cast<Op::Jump const&>(instruction).false_target()->block();
  190. goto start;
  191. case Instruction::Type::JumpUndefined:
  192. if (accumulator.is_undefined())
  193. m_current_block = &static_cast<Op::Jump const&>(instruction).true_target()->block();
  194. else
  195. m_current_block = &static_cast<Op::Jump const&>(instruction).false_target()->block();
  196. goto start;
  197. case Instruction::Type::EnterUnwindContext:
  198. enter_unwind_context(
  199. static_cast<Op::EnterUnwindContext const&>(instruction).handler_target(),
  200. static_cast<Op::EnterUnwindContext const&>(instruction).finalizer_target());
  201. m_current_block = &static_cast<Op::EnterUnwindContext const&>(instruction).entry_point().block();
  202. goto start;
  203. case Instruction::Type::ContinuePendingUnwind:
  204. if (auto exception = reg(Register::exception()); !exception.is_empty()) {
  205. result = throw_completion(exception);
  206. break;
  207. }
  208. if (!saved_return_value().is_empty()) {
  209. do_return(saved_return_value());
  210. break;
  211. }
  212. if (m_scheduled_jump) {
  213. // FIXME: If we `break` or `continue` in the finally, we need to clear
  214. // this field
  215. m_current_block = exchange(m_scheduled_jump, nullptr);
  216. } else {
  217. m_current_block = &static_cast<Op::ContinuePendingUnwind const&>(instruction).resume_target().block();
  218. }
  219. goto start;
  220. case Instruction::Type::ScheduleJump:
  221. m_scheduled_jump = &static_cast<Op::ScheduleJump const&>(instruction).target().block();
  222. m_current_block = unwind_contexts().last().finalizer;
  223. goto start;
  224. default:
  225. result = instruction.execute(*this);
  226. break;
  227. }
  228. if (result.is_error()) [[unlikely]] {
  229. reg(Register::exception()) = *result.throw_completion().value();
  230. if (unwind_contexts().is_empty())
  231. return;
  232. auto& unwind_context = unwind_contexts().last();
  233. if (unwind_context.executable != m_current_executable)
  234. return;
  235. if (unwind_context.handler && !unwind_context.handler_called) {
  236. vm().running_execution_context().lexical_environment = unwind_context.lexical_environment;
  237. m_current_block = unwind_context.handler;
  238. unwind_context.handler_called = true;
  239. accumulator = reg(Register::exception());
  240. reg(Register::exception()) = {};
  241. goto start;
  242. }
  243. if (unwind_context.finalizer) {
  244. m_current_block = unwind_context.finalizer;
  245. // If an exception was thrown inside the corresponding `catch` block, we need to rethrow it
  246. // from the `finally` block. But if the exception is from the `try` block, and has already been
  247. // handled by `catch`, we swallow it.
  248. if (!unwind_context.handler_called)
  249. reg(Register::exception()) = {};
  250. goto start;
  251. }
  252. // An unwind context with no handler or finalizer? We have nowhere to jump, and continuing on will make us crash on the next `Call` to a non-native function if there's an exception! So let's crash here instead.
  253. // If you run into this, you probably forgot to remove the current unwind_context somewhere.
  254. VERIFY_NOT_REACHED();
  255. }
  256. if (!reg(Register::return_value()).is_empty()) {
  257. will_return = true;
  258. // Note: A `yield` statement will not go through a finally statement,
  259. // hence we need to set a flag to not do so,
  260. // but we generate a Yield Operation in the case of returns in
  261. // generators as well, so we need to check if it will actually
  262. // continue or is a `return` in disguise
  263. will_yield = (instruction.type() == Instruction::Type::Yield && static_cast<Op::Yield const&>(instruction).continuation().has_value()) || instruction.type() == Instruction::Type::Await;
  264. break;
  265. }
  266. ++pc;
  267. }
  268. if (!unwind_contexts().is_empty() && !will_yield) {
  269. auto& unwind_context = unwind_contexts().last();
  270. if (unwind_context.executable == m_current_executable && unwind_context.finalizer) {
  271. reg(Register::saved_return_value()) = reg(Register::return_value());
  272. reg(Register::return_value()) = {};
  273. m_current_block = unwind_context.finalizer;
  274. // the unwind_context will be pop'ed when entering the finally block
  275. continue;
  276. }
  277. }
  278. if (pc.at_end())
  279. break;
  280. if (will_return)
  281. break;
  282. }
  283. }
  284. Interpreter::ValueAndFrame Interpreter::run_and_return_frame(Executable& executable, BasicBlock const* entry_point, CallFrame* in_frame)
  285. {
  286. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter will run unit {:p}", &executable);
  287. TemporaryChange restore_executable { m_current_executable, &executable };
  288. TemporaryChange restore_saved_jump { m_scheduled_jump, static_cast<BasicBlock const*>(nullptr) };
  289. VERIFY(!vm().execution_context_stack().is_empty());
  290. TemporaryChange restore_current_block { m_current_block, entry_point ?: executable.basic_blocks.first() };
  291. if (in_frame)
  292. push_call_frame(in_frame, executable.number_of_registers);
  293. else
  294. push_call_frame(make<CallFrame>(), executable.number_of_registers);
  295. run_bytecode();
  296. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter did run unit {:p}", &executable);
  297. if constexpr (JS_BYTECODE_DEBUG) {
  298. for (size_t i = 0; i < registers().size(); ++i) {
  299. String value_string;
  300. if (registers()[i].is_empty())
  301. value_string = "(empty)"_string;
  302. else
  303. value_string = registers()[i].to_string_without_side_effects();
  304. dbgln("[{:3}] {}", i, value_string);
  305. }
  306. }
  307. auto return_value = js_undefined();
  308. if (!reg(Register::return_value()).is_empty())
  309. return_value = reg(Register::return_value());
  310. else if (!reg(Register::saved_return_value()).is_empty())
  311. return_value = reg(Register::saved_return_value());
  312. auto exception = reg(Register::exception());
  313. auto frame = pop_call_frame();
  314. // NOTE: The return value from a called function is put into $0 in the caller context.
  315. if (!m_call_frames.is_empty())
  316. call_frame().registers[0] = return_value;
  317. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  318. // in which case this is a no-op.
  319. vm().run_queued_promise_jobs();
  320. vm().finish_execution_generation();
  321. if (!exception.is_empty()) {
  322. if (auto* call_frame = frame.get_pointer<NonnullOwnPtr<CallFrame>>())
  323. return { throw_completion(exception), move(*call_frame) };
  324. return { throw_completion(exception), nullptr };
  325. }
  326. if (auto* call_frame = frame.get_pointer<NonnullOwnPtr<CallFrame>>())
  327. return { return_value, move(*call_frame) };
  328. return { return_value, nullptr };
  329. }
  330. void Interpreter::enter_unwind_context(Optional<Label> handler_target, Optional<Label> finalizer_target)
  331. {
  332. unwind_contexts().empend(
  333. m_current_executable,
  334. handler_target.has_value() ? &handler_target->block() : nullptr,
  335. finalizer_target.has_value() ? &finalizer_target->block() : nullptr,
  336. vm().running_execution_context().lexical_environment);
  337. }
  338. void Interpreter::leave_unwind_context()
  339. {
  340. unwind_contexts().take_last();
  341. }
  342. ThrowCompletionOr<NonnullRefPtr<Bytecode::Executable>> compile(VM& vm, ASTNode const& node, FunctionKind kind, DeprecatedFlyString const& name)
  343. {
  344. auto executable_result = Bytecode::Generator::generate(node, kind);
  345. if (executable_result.is_error())
  346. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string()));
  347. auto bytecode_executable = executable_result.release_value();
  348. bytecode_executable->name = name;
  349. if (Bytecode::g_dump_bytecode)
  350. bytecode_executable->dump();
  351. return bytecode_executable;
  352. }
  353. Realm& Interpreter::realm()
  354. {
  355. return *m_vm.current_realm();
  356. }
  357. void Interpreter::push_call_frame(Variant<NonnullOwnPtr<CallFrame>, CallFrame*> frame, size_t register_count)
  358. {
  359. m_call_frames.append(move(frame));
  360. this->call_frame().registers.resize(register_count);
  361. m_current_call_frame = this->call_frame().registers;
  362. reg(Register::return_value()) = {};
  363. }
  364. Variant<NonnullOwnPtr<CallFrame>, CallFrame*> Interpreter::pop_call_frame()
  365. {
  366. auto frame = m_call_frames.take_last();
  367. m_current_call_frame = m_call_frames.is_empty() ? Span<Value> {} : this->call_frame().registers;
  368. return frame;
  369. }
  370. }
  371. namespace JS::Bytecode {
  372. DeprecatedString Instruction::to_deprecated_string(Bytecode::Executable const& executable) const
  373. {
  374. #define __BYTECODE_OP(op) \
  375. case Instruction::Type::op: \
  376. return static_cast<Bytecode::Op::op const&>(*this).to_deprecated_string_impl(executable);
  377. switch (type()) {
  378. ENUMERATE_BYTECODE_OPS(__BYTECODE_OP)
  379. default:
  380. VERIFY_NOT_REACHED();
  381. }
  382. #undef __BYTECODE_OP
  383. }
  384. }
  385. namespace JS::Bytecode::Op {
  386. static ThrowCompletionOr<void> put_by_property_key(VM& vm, Value base, Value this_value, Value value, PropertyKey name, PropertyKind kind)
  387. {
  388. auto object = TRY(base.to_object(vm));
  389. if (kind == PropertyKind::Getter || kind == PropertyKind::Setter) {
  390. // The generator should only pass us functions for getters and setters.
  391. VERIFY(value.is_function());
  392. }
  393. switch (kind) {
  394. case PropertyKind::Getter: {
  395. auto& function = value.as_function();
  396. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  397. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(DeprecatedString::formatted("get {}", name));
  398. object->define_direct_accessor(name, &function, nullptr, Attribute::Configurable | Attribute::Enumerable);
  399. break;
  400. }
  401. case PropertyKind::Setter: {
  402. auto& function = value.as_function();
  403. if (function.name().is_empty() && is<ECMAScriptFunctionObject>(function))
  404. static_cast<ECMAScriptFunctionObject*>(&function)->set_name(DeprecatedString::formatted("set {}", name));
  405. object->define_direct_accessor(name, nullptr, &function, Attribute::Configurable | Attribute::Enumerable);
  406. break;
  407. }
  408. case PropertyKind::KeyValue: {
  409. bool succeeded = TRY(object->internal_set(name, value, this_value));
  410. if (!succeeded && vm.in_strict_mode())
  411. return vm.throw_completion<TypeError>(ErrorType::ReferenceNullishSetProperty, name, base.to_string_without_side_effects());
  412. break;
  413. }
  414. case PropertyKind::DirectKeyValue:
  415. object->define_direct_property(name, value, Attribute::Enumerable | Attribute::Writable | Attribute::Configurable);
  416. break;
  417. case PropertyKind::Spread:
  418. TRY(object->copy_data_properties(vm, value, {}));
  419. break;
  420. case PropertyKind::ProtoSetter:
  421. if (value.is_object() || value.is_null())
  422. MUST(object->internal_set_prototype_of(value.is_object() ? &value.as_object() : nullptr));
  423. break;
  424. }
  425. return {};
  426. }
  427. ThrowCompletionOr<void> Load::execute_impl(Bytecode::Interpreter&) const
  428. {
  429. // Handled in the interpreter loop.
  430. __builtin_unreachable();
  431. }
  432. ThrowCompletionOr<void> LoadImmediate::execute_impl(Bytecode::Interpreter&) const
  433. {
  434. // Handled in the interpreter loop.
  435. __builtin_unreachable();
  436. }
  437. ThrowCompletionOr<void> Store::execute_impl(Bytecode::Interpreter&) const
  438. {
  439. // Handled in the interpreter loop.
  440. __builtin_unreachable();
  441. }
  442. static ThrowCompletionOr<Value> abstract_inequals(VM& vm, Value src1, Value src2)
  443. {
  444. return Value(!TRY(is_loosely_equal(vm, src1, src2)));
  445. }
  446. static ThrowCompletionOr<Value> abstract_equals(VM& vm, Value src1, Value src2)
  447. {
  448. return Value(TRY(is_loosely_equal(vm, src1, src2)));
  449. }
  450. static ThrowCompletionOr<Value> typed_inequals(VM&, Value src1, Value src2)
  451. {
  452. return Value(!is_strictly_equal(src1, src2));
  453. }
  454. static ThrowCompletionOr<Value> typed_equals(VM&, Value src1, Value src2)
  455. {
  456. return Value(is_strictly_equal(src1, src2));
  457. }
  458. #define JS_DEFINE_COMMON_BINARY_OP(OpTitleCase, op_snake_case) \
  459. ThrowCompletionOr<void> OpTitleCase::execute_impl(Bytecode::Interpreter& interpreter) const \
  460. { \
  461. auto& vm = interpreter.vm(); \
  462. auto lhs = interpreter.reg(m_lhs_reg); \
  463. auto rhs = interpreter.accumulator(); \
  464. interpreter.accumulator() = TRY(op_snake_case(vm, lhs, rhs)); \
  465. return {}; \
  466. } \
  467. DeprecatedString OpTitleCase::to_deprecated_string_impl(Bytecode::Executable const&) const \
  468. { \
  469. return DeprecatedString::formatted(#OpTitleCase " {}", m_lhs_reg); \
  470. }
  471. JS_ENUMERATE_COMMON_BINARY_OPS(JS_DEFINE_COMMON_BINARY_OP)
  472. static ThrowCompletionOr<Value> not_(VM&, Value value)
  473. {
  474. return Value(!value.to_boolean());
  475. }
  476. static ThrowCompletionOr<Value> typeof_(VM& vm, Value value)
  477. {
  478. return PrimitiveString::create(vm, value.typeof());
  479. }
  480. #define JS_DEFINE_COMMON_UNARY_OP(OpTitleCase, op_snake_case) \
  481. ThrowCompletionOr<void> OpTitleCase::execute_impl(Bytecode::Interpreter& interpreter) const \
  482. { \
  483. auto& vm = interpreter.vm(); \
  484. interpreter.accumulator() = TRY(op_snake_case(vm, interpreter.accumulator())); \
  485. return {}; \
  486. } \
  487. DeprecatedString OpTitleCase::to_deprecated_string_impl(Bytecode::Executable const&) const \
  488. { \
  489. return #OpTitleCase; \
  490. }
  491. JS_ENUMERATE_COMMON_UNARY_OPS(JS_DEFINE_COMMON_UNARY_OP)
  492. ThrowCompletionOr<void> NewBigInt::execute_impl(Bytecode::Interpreter& interpreter) const
  493. {
  494. auto& vm = interpreter.vm();
  495. interpreter.accumulator() = BigInt::create(vm, m_bigint);
  496. return {};
  497. }
  498. ThrowCompletionOr<void> NewArray::execute_impl(Bytecode::Interpreter& interpreter) const
  499. {
  500. auto array = MUST(Array::create(interpreter.realm(), 0));
  501. for (size_t i = 0; i < m_element_count; i++) {
  502. auto& value = interpreter.reg(Register(m_elements[0].index() + i));
  503. array->indexed_properties().put(i, value, default_attributes);
  504. }
  505. interpreter.accumulator() = array;
  506. return {};
  507. }
  508. ThrowCompletionOr<void> Append::execute_impl(Bytecode::Interpreter& interpreter) const
  509. {
  510. // Note: This OpCode is used to construct array literals and argument arrays for calls,
  511. // containing at least one spread element,
  512. // Iterating over such a spread element to unpack it has to be visible by
  513. // the user courtesy of
  514. // (1) https://tc39.es/ecma262/#sec-runtime-semantics-arrayaccumulation
  515. // SpreadElement : ... AssignmentExpression
  516. // 1. Let spreadRef be ? Evaluation of AssignmentExpression.
  517. // 2. Let spreadObj be ? GetValue(spreadRef).
  518. // 3. Let iteratorRecord be ? GetIterator(spreadObj).
  519. // 4. Repeat,
  520. // a. Let next be ? IteratorStep(iteratorRecord).
  521. // b. If next is false, return nextIndex.
  522. // c. Let nextValue be ? IteratorValue(next).
  523. // d. Perform ! CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), nextValue).
  524. // e. Set nextIndex to nextIndex + 1.
  525. // (2) https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  526. // ArgumentList : ... AssignmentExpression
  527. // 1. Let list be a new empty List.
  528. // 2. Let spreadRef be ? Evaluation of AssignmentExpression.
  529. // 3. Let spreadObj be ? GetValue(spreadRef).
  530. // 4. Let iteratorRecord be ? GetIterator(spreadObj).
  531. // 5. Repeat,
  532. // a. Let next be ? IteratorStep(iteratorRecord).
  533. // b. If next is false, return list.
  534. // c. Let nextArg be ? IteratorValue(next).
  535. // d. Append nextArg to list.
  536. // ArgumentList : ArgumentList , ... AssignmentExpression
  537. // 1. Let precedingArgs be ? ArgumentListEvaluation of ArgumentList.
  538. // 2. Let spreadRef be ? Evaluation of AssignmentExpression.
  539. // 3. Let iteratorRecord be ? GetIterator(? GetValue(spreadRef)).
  540. // 4. Repeat,
  541. // a. Let next be ? IteratorStep(iteratorRecord).
  542. // b. If next is false, return precedingArgs.
  543. // c. Let nextArg be ? IteratorValue(next).
  544. // d. Append nextArg to precedingArgs.
  545. auto& vm = interpreter.vm();
  546. // Note: We know from codegen, that lhs is a plain array with only indexed properties
  547. auto& lhs = interpreter.reg(m_lhs).as_array();
  548. auto lhs_size = lhs.indexed_properties().array_like_size();
  549. auto rhs = interpreter.accumulator();
  550. if (m_is_spread) {
  551. // ...rhs
  552. size_t i = lhs_size;
  553. TRY(get_iterator_values(vm, rhs, [&i, &lhs](Value iterator_value) -> Optional<Completion> {
  554. lhs.indexed_properties().put(i, iterator_value, default_attributes);
  555. ++i;
  556. return {};
  557. }));
  558. } else {
  559. lhs.indexed_properties().put(lhs_size, rhs, default_attributes);
  560. }
  561. return {};
  562. }
  563. ThrowCompletionOr<void> ImportCall::execute_impl(Bytecode::Interpreter& interpreter) const
  564. {
  565. auto& vm = interpreter.vm();
  566. auto specifier = interpreter.reg(m_specifier);
  567. auto options_value = interpreter.reg(m_options);
  568. interpreter.accumulator() = TRY(perform_import_call(vm, specifier, options_value));
  569. return {};
  570. }
  571. // 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.
  572. // Make sure to put this into the accumulator before the iterator object disappears from the stack to prevent the members from being GC'd.
  573. static Object* iterator_to_object(VM& vm, IteratorRecord iterator)
  574. {
  575. auto& realm = *vm.current_realm();
  576. auto object = Object::create(realm, nullptr);
  577. object->define_direct_property(vm.names.iterator, iterator.iterator, 0);
  578. object->define_direct_property(vm.names.next, iterator.next_method, 0);
  579. object->define_direct_property(vm.names.done, Value(iterator.done), 0);
  580. return object;
  581. }
  582. static IteratorRecord object_to_iterator(VM& vm, Object& object)
  583. {
  584. return IteratorRecord {
  585. .iterator = &MUST(object.get(vm.names.iterator)).as_object(),
  586. .next_method = MUST(object.get(vm.names.next)),
  587. .done = MUST(object.get(vm.names.done)).as_bool()
  588. };
  589. }
  590. ThrowCompletionOr<void> IteratorToArray::execute_impl(Bytecode::Interpreter& interpreter) const
  591. {
  592. auto& vm = interpreter.vm();
  593. auto iterator_object = TRY(interpreter.accumulator().to_object(vm));
  594. auto iterator = object_to_iterator(vm, iterator_object);
  595. auto array = MUST(Array::create(interpreter.realm(), 0));
  596. size_t index = 0;
  597. while (true) {
  598. auto iterator_result = TRY(iterator_next(vm, iterator));
  599. auto complete = TRY(iterator_complete(vm, iterator_result));
  600. if (complete) {
  601. interpreter.accumulator() = array;
  602. return {};
  603. }
  604. auto value = TRY(iterator_value(vm, iterator_result));
  605. MUST(array->create_data_property_or_throw(index, value));
  606. index++;
  607. }
  608. return {};
  609. }
  610. ThrowCompletionOr<void> NewString::execute_impl(Bytecode::Interpreter& interpreter) const
  611. {
  612. interpreter.accumulator() = PrimitiveString::create(interpreter.vm(), interpreter.current_executable().get_string(m_string));
  613. return {};
  614. }
  615. ThrowCompletionOr<void> NewObject::execute_impl(Bytecode::Interpreter& interpreter) const
  616. {
  617. auto& vm = interpreter.vm();
  618. auto& realm = *vm.current_realm();
  619. interpreter.accumulator() = Object::create(realm, realm.intrinsics().object_prototype());
  620. return {};
  621. }
  622. // 13.2.7.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation
  623. ThrowCompletionOr<void> NewRegExp::execute_impl(Bytecode::Interpreter& interpreter) const
  624. {
  625. auto& vm = interpreter.vm();
  626. auto& realm = *vm.current_realm();
  627. // 1. Let pattern be CodePointsToString(BodyText of RegularExpressionLiteral).
  628. auto pattern = interpreter.current_executable().get_string(m_source_index);
  629. // 2. Let flags be CodePointsToString(FlagText of RegularExpressionLiteral).
  630. auto flags = interpreter.current_executable().get_string(m_flags_index);
  631. // 3. Return ! RegExpCreate(pattern, flags).
  632. auto& parsed_regex = interpreter.current_executable().regex_table->get(m_regex_index);
  633. Regex<ECMA262> regex(parsed_regex.regex, parsed_regex.pattern, parsed_regex.flags);
  634. // NOTE: We bypass RegExpCreate and subsequently RegExpAlloc as an optimization to use the already parsed values.
  635. auto regexp_object = RegExpObject::create(realm, move(regex), move(pattern), move(flags));
  636. // RegExpAlloc has these two steps from the 'Legacy RegExp features' proposal.
  637. regexp_object->set_realm(*vm.current_realm());
  638. // We don't need to check 'If SameValue(newTarget, thisRealm.[[Intrinsics]].[[%RegExp%]]) is true'
  639. // here as we know RegExpCreate calls RegExpAlloc with %RegExp% for newTarget.
  640. regexp_object->set_legacy_features_enabled(true);
  641. interpreter.accumulator() = regexp_object;
  642. return {};
  643. }
  644. #define JS_DEFINE_NEW_BUILTIN_ERROR_OP(ErrorName) \
  645. ThrowCompletionOr<void> New##ErrorName::execute_impl(Bytecode::Interpreter& interpreter) const \
  646. { \
  647. auto& vm = interpreter.vm(); \
  648. auto& realm = *vm.current_realm(); \
  649. interpreter.accumulator() = ErrorName::create(realm, interpreter.current_executable().get_string(m_error_string)); \
  650. return {}; \
  651. } \
  652. DeprecatedString New##ErrorName::to_deprecated_string_impl(Bytecode::Executable const& executable) const \
  653. { \
  654. return DeprecatedString::formatted("New" #ErrorName " {} (\"{}\")", m_error_string, executable.string_table->get(m_error_string)); \
  655. }
  656. JS_ENUMERATE_NEW_BUILTIN_ERROR_OPS(JS_DEFINE_NEW_BUILTIN_ERROR_OP)
  657. ThrowCompletionOr<void> CopyObjectExcludingProperties::execute_impl(Bytecode::Interpreter& interpreter) const
  658. {
  659. auto& vm = interpreter.vm();
  660. auto& realm = *vm.current_realm();
  661. auto from_object = interpreter.reg(m_from_object);
  662. auto to_object = Object::create(realm, realm.intrinsics().object_prototype());
  663. HashTable<PropertyKey> excluded_names;
  664. for (size_t i = 0; i < m_excluded_names_count; ++i) {
  665. excluded_names.set(TRY(interpreter.reg(m_excluded_names[i]).to_property_key(vm)));
  666. }
  667. TRY(to_object->copy_data_properties(vm, from_object, excluded_names));
  668. interpreter.accumulator() = to_object;
  669. return {};
  670. }
  671. ThrowCompletionOr<void> ConcatString::execute_impl(Bytecode::Interpreter& interpreter) const
  672. {
  673. auto& vm = interpreter.vm();
  674. auto string = TRY(interpreter.accumulator().to_primitive_string(vm));
  675. interpreter.reg(m_lhs) = PrimitiveString::create(vm, interpreter.reg(m_lhs).as_string(), string);
  676. return {};
  677. }
  678. ThrowCompletionOr<void> GetVariable::execute_impl(Bytecode::Interpreter& interpreter) const
  679. {
  680. auto& vm = interpreter.vm();
  681. auto get_reference = [&]() -> ThrowCompletionOr<Reference> {
  682. auto const& string = interpreter.current_executable().get_identifier(m_identifier);
  683. if (m_cached_environment_coordinate.has_value()) {
  684. auto environment = vm.running_execution_context().lexical_environment;
  685. for (size_t i = 0; i < m_cached_environment_coordinate->hops; ++i)
  686. environment = environment->outer_environment();
  687. VERIFY(environment);
  688. VERIFY(environment->is_declarative_environment());
  689. if (!environment->is_permanently_screwed_by_eval()) {
  690. return Reference { *environment, string, vm.in_strict_mode(), m_cached_environment_coordinate };
  691. }
  692. m_cached_environment_coordinate = {};
  693. }
  694. auto reference = TRY(vm.resolve_binding(string));
  695. if (reference.environment_coordinate().has_value())
  696. m_cached_environment_coordinate = reference.environment_coordinate();
  697. return reference;
  698. };
  699. auto reference = TRY(get_reference());
  700. interpreter.accumulator() = TRY(reference.get_value(vm));
  701. return {};
  702. }
  703. ThrowCompletionOr<void> GetCalleeAndThisFromEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  704. {
  705. auto& vm = interpreter.vm();
  706. auto get_reference = [&]() -> ThrowCompletionOr<Reference> {
  707. auto const& string = interpreter.current_executable().get_identifier(m_identifier);
  708. if (m_cached_environment_coordinate.has_value()) {
  709. auto environment = vm.running_execution_context().lexical_environment;
  710. for (size_t i = 0; i < m_cached_environment_coordinate->hops; ++i)
  711. environment = environment->outer_environment();
  712. VERIFY(environment);
  713. VERIFY(environment->is_declarative_environment());
  714. if (!environment->is_permanently_screwed_by_eval()) {
  715. return Reference { *environment, string, vm.in_strict_mode(), m_cached_environment_coordinate };
  716. }
  717. m_cached_environment_coordinate = {};
  718. }
  719. auto reference = TRY(vm.resolve_binding(string));
  720. if (reference.environment_coordinate().has_value())
  721. m_cached_environment_coordinate = reference.environment_coordinate();
  722. return reference;
  723. };
  724. auto reference = TRY(get_reference());
  725. interpreter.reg(m_callee_reg) = TRY(reference.get_value(vm));
  726. Value this_value = js_undefined();
  727. if (reference.is_property_reference()) {
  728. this_value = reference.get_this_value();
  729. } else {
  730. if (reference.is_environment_reference()) {
  731. if (auto base_object = reference.base_environment().with_base_object(); base_object != nullptr)
  732. this_value = base_object;
  733. }
  734. }
  735. interpreter.reg(m_this_reg) = this_value;
  736. return {};
  737. }
  738. ThrowCompletionOr<void> GetGlobal::execute_impl(Bytecode::Interpreter& interpreter) const
  739. {
  740. auto& vm = interpreter.vm();
  741. auto& realm = *vm.current_realm();
  742. auto const& name = interpreter.current_executable().get_identifier(m_identifier);
  743. auto& cache = interpreter.current_executable().global_variable_caches[m_cache_index];
  744. auto& binding_object = realm.global_environment().object_record().binding_object();
  745. auto& declarative_record = realm.global_environment().declarative_record();
  746. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  747. // NOTE: Unique shapes don't change identity, so we compare their serial numbers instead.
  748. auto& shape = binding_object.shape();
  749. if (cache.environment_serial_number == declarative_record.environment_serial_number()
  750. && &shape == cache.shape
  751. && (!shape.is_unique() || shape.unique_shape_serial_number() == cache.unique_shape_serial_number)) {
  752. interpreter.accumulator() = binding_object.get_direct(cache.property_offset.value());
  753. return {};
  754. }
  755. cache.environment_serial_number = declarative_record.environment_serial_number();
  756. if (vm.running_execution_context().script_or_module.has<NonnullGCPtr<Module>>()) {
  757. // NOTE: GetGlobal is used to access variables stored in the module environment and global environment.
  758. // The module environment is checked first since it precedes the global environment in the environment chain.
  759. auto& module_environment = *vm.running_execution_context().script_or_module.get<NonnullGCPtr<Module>>()->environment();
  760. if (TRY(module_environment.has_binding(name))) {
  761. // TODO: Cache offset of binding value
  762. interpreter.accumulator() = TRY(module_environment.get_binding_value(vm, name, vm.in_strict_mode()));
  763. return {};
  764. }
  765. }
  766. if (TRY(declarative_record.has_binding(name))) {
  767. // TODO: Cache offset of binding value
  768. interpreter.accumulator() = TRY(declarative_record.get_binding_value(vm, name, vm.in_strict_mode()));
  769. return {};
  770. }
  771. if (TRY(binding_object.has_property(name))) {
  772. CacheablePropertyMetadata cacheable_metadata;
  773. interpreter.accumulator() = js_undefined();
  774. interpreter.accumulator() = TRY(binding_object.internal_get(name, interpreter.accumulator(), &cacheable_metadata));
  775. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  776. cache.shape = shape;
  777. cache.property_offset = cacheable_metadata.property_offset.value();
  778. cache.unique_shape_serial_number = shape.unique_shape_serial_number();
  779. }
  780. return {};
  781. }
  782. return vm.throw_completion<ReferenceError>(ErrorType::UnknownIdentifier, name);
  783. }
  784. ThrowCompletionOr<void> GetLocal::execute_impl(Bytecode::Interpreter&) const
  785. {
  786. // Handled in the interpreter loop.
  787. __builtin_unreachable();
  788. }
  789. ThrowCompletionOr<void> DeleteVariable::execute_impl(Bytecode::Interpreter& interpreter) const
  790. {
  791. auto& vm = interpreter.vm();
  792. auto const& string = interpreter.current_executable().get_identifier(m_identifier);
  793. auto reference = TRY(vm.resolve_binding(string));
  794. interpreter.accumulator() = Value(TRY(reference.delete_(vm)));
  795. return {};
  796. }
  797. ThrowCompletionOr<void> CreateLexicalEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  798. {
  799. auto make_and_swap_envs = [&](auto& old_environment) {
  800. GCPtr<Environment> environment = new_declarative_environment(*old_environment).ptr();
  801. swap(old_environment, environment);
  802. return environment;
  803. };
  804. interpreter.saved_lexical_environment_stack().append(make_and_swap_envs(interpreter.vm().running_execution_context().lexical_environment));
  805. return {};
  806. }
  807. ThrowCompletionOr<void> EnterObjectEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  808. {
  809. auto& vm = interpreter.vm();
  810. auto& old_environment = vm.running_execution_context().lexical_environment;
  811. interpreter.saved_lexical_environment_stack().append(old_environment);
  812. auto object = TRY(interpreter.accumulator().to_object(vm));
  813. vm.running_execution_context().lexical_environment = new_object_environment(object, true, old_environment);
  814. return {};
  815. }
  816. ThrowCompletionOr<void> CreateVariable::execute_impl(Bytecode::Interpreter& interpreter) const
  817. {
  818. auto& vm = interpreter.vm();
  819. auto const& name = interpreter.current_executable().get_identifier(m_identifier);
  820. if (m_mode == EnvironmentMode::Lexical) {
  821. VERIFY(!m_is_global);
  822. // Note: This is papering over an issue where "FunctionDeclarationInstantiation" creates these bindings for us.
  823. // Instead of crashing in there, we'll just raise an exception here.
  824. if (TRY(vm.lexical_environment()->has_binding(name)))
  825. return vm.throw_completion<InternalError>(TRY_OR_THROW_OOM(vm, String::formatted("Lexical environment already has binding '{}'", name)));
  826. if (m_is_immutable)
  827. return vm.lexical_environment()->create_immutable_binding(vm, name, m_is_strict);
  828. else
  829. return vm.lexical_environment()->create_mutable_binding(vm, name, m_is_strict);
  830. } else {
  831. if (!m_is_global) {
  832. if (m_is_immutable)
  833. return vm.variable_environment()->create_immutable_binding(vm, name, m_is_strict);
  834. else
  835. return vm.variable_environment()->create_mutable_binding(vm, name, m_is_strict);
  836. } else {
  837. // NOTE: CreateVariable with m_is_global set to true is expected to only be used in GlobalDeclarationInstantiation currently, which only uses "false" for "can_be_deleted".
  838. // The only area that sets "can_be_deleted" to true is EvalDeclarationInstantiation, which is currently fully implemented in C++ and not in Bytecode.
  839. return verify_cast<GlobalEnvironment>(vm.variable_environment())->create_global_var_binding(name, false);
  840. }
  841. }
  842. return {};
  843. }
  844. ThrowCompletionOr<void> SetVariable::execute_impl(Bytecode::Interpreter& interpreter) const
  845. {
  846. auto& vm = interpreter.vm();
  847. auto const& name = interpreter.current_executable().get_identifier(m_identifier);
  848. auto environment = m_mode == EnvironmentMode::Lexical ? vm.running_execution_context().lexical_environment : vm.running_execution_context().variable_environment;
  849. auto reference = TRY(vm.resolve_binding(name, environment));
  850. switch (m_initialization_mode) {
  851. case InitializationMode::Initialize:
  852. TRY(reference.initialize_referenced_binding(vm, interpreter.accumulator()));
  853. break;
  854. case InitializationMode::Set:
  855. TRY(reference.put_value(vm, interpreter.accumulator()));
  856. break;
  857. }
  858. return {};
  859. }
  860. ThrowCompletionOr<void> SetLocal::execute_impl(Bytecode::Interpreter&) const
  861. {
  862. // Handled in the interpreter loop.
  863. __builtin_unreachable();
  864. }
  865. static ThrowCompletionOr<NonnullGCPtr<Object>> base_object_for_get(Bytecode::Interpreter& interpreter, Value base_value)
  866. {
  867. auto& vm = interpreter.vm();
  868. if (base_value.is_object())
  869. return base_value.as_object();
  870. // OPTIMIZATION: For various primitives we can avoid actually creating a new object for them.
  871. if (base_value.is_string())
  872. return vm.current_realm()->intrinsics().string_prototype();
  873. if (base_value.is_number())
  874. return vm.current_realm()->intrinsics().number_prototype();
  875. if (base_value.is_boolean())
  876. return vm.current_realm()->intrinsics().boolean_prototype();
  877. return base_value.to_object(vm);
  878. }
  879. static ThrowCompletionOr<void> get_by_id(Bytecode::Interpreter& interpreter, IdentifierTableIndex property, Value base_value, Value this_value, u32 cache_index)
  880. {
  881. auto& vm = interpreter.vm();
  882. auto const& name = interpreter.current_executable().get_identifier(property);
  883. auto& cache = interpreter.current_executable().property_lookup_caches[cache_index];
  884. if (base_value.is_string()) {
  885. auto string_value = TRY(base_value.as_string().get(vm, name));
  886. if (string_value.has_value()) {
  887. interpreter.accumulator() = *string_value;
  888. return {};
  889. }
  890. }
  891. auto base_obj = TRY(base_object_for_get(interpreter, base_value));
  892. // OPTIMIZATION: If the shape of the object hasn't changed, we can use the cached property offset.
  893. // NOTE: Unique shapes don't change identity, so we compare their serial numbers instead.
  894. auto& shape = base_obj->shape();
  895. if (&shape == cache.shape
  896. && (!shape.is_unique() || shape.unique_shape_serial_number() == cache.unique_shape_serial_number)) {
  897. interpreter.accumulator() = base_obj->get_direct(cache.property_offset.value());
  898. return {};
  899. }
  900. CacheablePropertyMetadata cacheable_metadata;
  901. interpreter.accumulator() = TRY(base_obj->internal_get(name, this_value, &cacheable_metadata));
  902. if (cacheable_metadata.type == CacheablePropertyMetadata::Type::OwnProperty) {
  903. cache.shape = shape;
  904. cache.property_offset = cacheable_metadata.property_offset.value();
  905. cache.unique_shape_serial_number = shape.unique_shape_serial_number();
  906. }
  907. return {};
  908. }
  909. ThrowCompletionOr<void> GetById::execute_impl(Bytecode::Interpreter& interpreter) const
  910. {
  911. auto base_value = interpreter.accumulator();
  912. return get_by_id(interpreter, m_property, base_value, base_value, m_cache_index);
  913. }
  914. ThrowCompletionOr<void> GetByIdWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  915. {
  916. auto base_value = interpreter.accumulator();
  917. auto this_value = interpreter.reg(m_this_value);
  918. return get_by_id(interpreter, m_property, base_value, this_value, m_cache_index);
  919. }
  920. ThrowCompletionOr<void> GetPrivateById::execute_impl(Bytecode::Interpreter& interpreter) const
  921. {
  922. auto& vm = interpreter.vm();
  923. auto const& name = interpreter.current_executable().get_identifier(m_property);
  924. auto base_value = interpreter.accumulator();
  925. auto private_reference = make_private_reference(vm, base_value, name);
  926. interpreter.accumulator() = TRY(private_reference.get_value(vm));
  927. return {};
  928. }
  929. ThrowCompletionOr<void> HasPrivateId::execute_impl(Bytecode::Interpreter& interpreter) const
  930. {
  931. auto& vm = interpreter.vm();
  932. if (!interpreter.accumulator().is_object())
  933. return vm.throw_completion<TypeError>(ErrorType::InOperatorWithObject);
  934. auto private_environment = vm.running_execution_context().private_environment;
  935. VERIFY(private_environment);
  936. auto private_name = private_environment->resolve_private_identifier(interpreter.current_executable().get_identifier(m_property));
  937. interpreter.accumulator() = Value(interpreter.accumulator().as_object().private_element_find(private_name) != nullptr);
  938. return {};
  939. }
  940. ThrowCompletionOr<void> PutById::execute_impl(Bytecode::Interpreter& interpreter) const
  941. {
  942. auto& vm = interpreter.vm();
  943. // NOTE: Get the value from the accumulator before side effects have a chance to overwrite it.
  944. auto value = interpreter.accumulator();
  945. auto base = interpreter.reg(m_base);
  946. PropertyKey name = interpreter.current_executable().get_identifier(m_property);
  947. TRY(put_by_property_key(vm, base, base, value, name, m_kind));
  948. interpreter.accumulator() = value;
  949. return {};
  950. }
  951. ThrowCompletionOr<void> PutByIdWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  952. {
  953. auto& vm = interpreter.vm();
  954. // NOTE: Get the value from the accumulator before side effects have a chance to overwrite it.
  955. auto value = interpreter.accumulator();
  956. auto base = interpreter.reg(m_base);
  957. PropertyKey name = interpreter.current_executable().get_identifier(m_property);
  958. TRY(put_by_property_key(vm, base, interpreter.reg(m_this_value), value, name, m_kind));
  959. interpreter.accumulator() = value;
  960. return {};
  961. }
  962. ThrowCompletionOr<void> PutPrivateById::execute_impl(Bytecode::Interpreter& interpreter) const
  963. {
  964. auto& vm = interpreter.vm();
  965. // NOTE: Get the value from the accumulator before side effects have a chance to overwrite it.
  966. auto value = interpreter.accumulator();
  967. auto object = TRY(interpreter.reg(m_base).to_object(vm));
  968. auto name = interpreter.current_executable().get_identifier(m_property);
  969. auto private_reference = make_private_reference(vm, object, name);
  970. TRY(private_reference.put_value(vm, value));
  971. interpreter.accumulator() = value;
  972. return {};
  973. }
  974. ThrowCompletionOr<void> DeleteById::execute_impl(Bytecode::Interpreter& interpreter) const
  975. {
  976. auto& vm = interpreter.vm();
  977. auto base_value = interpreter.accumulator();
  978. auto const& identifier = interpreter.current_executable().get_identifier(m_property);
  979. bool strict = vm.in_strict_mode();
  980. auto reference = Reference { base_value, identifier, {}, strict };
  981. interpreter.accumulator() = Value(TRY(reference.delete_(vm)));
  982. return {};
  983. }
  984. ThrowCompletionOr<void> DeleteByIdWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  985. {
  986. auto& vm = interpreter.vm();
  987. auto base_value = interpreter.accumulator();
  988. auto const& identifier = interpreter.current_executable().get_identifier(m_property);
  989. bool strict = vm.in_strict_mode();
  990. auto reference = Reference { base_value, identifier, interpreter.reg(m_this_value), strict };
  991. interpreter.accumulator() = Value(TRY(reference.delete_(vm)));
  992. return {};
  993. }
  994. ThrowCompletionOr<void> Jump::execute_impl(Bytecode::Interpreter&) const
  995. {
  996. // Handled in the interpreter loop.
  997. __builtin_unreachable();
  998. }
  999. ThrowCompletionOr<void> ResolveThisBinding::execute_impl(Bytecode::Interpreter& interpreter) const
  1000. {
  1001. auto& cached_this_value = interpreter.reg(Register::this_value());
  1002. if (cached_this_value.is_empty()) {
  1003. // OPTIMIZATION: Because the value of 'this' cannot be reassigned during a function execution, it's
  1004. // resolved once and then saved for subsequent use.
  1005. auto& vm = interpreter.vm();
  1006. cached_this_value = TRY(vm.resolve_this_binding());
  1007. }
  1008. interpreter.accumulator() = cached_this_value;
  1009. return {};
  1010. }
  1011. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  1012. ThrowCompletionOr<void> ResolveSuperBase::execute_impl(Bytecode::Interpreter& interpreter) const
  1013. {
  1014. auto& vm = interpreter.vm();
  1015. // 1. Let env be GetThisEnvironment().
  1016. auto& env = verify_cast<FunctionEnvironment>(*get_this_environment(vm));
  1017. // 2. Assert: env.HasSuperBinding() is true.
  1018. VERIFY(env.has_super_binding());
  1019. // 3. Let baseValue be ? env.GetSuperBase().
  1020. interpreter.accumulator() = TRY(env.get_super_base());
  1021. return {};
  1022. }
  1023. ThrowCompletionOr<void> GetNewTarget::execute_impl(Bytecode::Interpreter& interpreter) const
  1024. {
  1025. interpreter.accumulator() = interpreter.vm().get_new_target();
  1026. return {};
  1027. }
  1028. ThrowCompletionOr<void> GetImportMeta::execute_impl(Bytecode::Interpreter& interpreter) const
  1029. {
  1030. interpreter.accumulator() = interpreter.vm().get_import_meta();
  1031. return {};
  1032. }
  1033. ThrowCompletionOr<void> JumpConditional::execute_impl(Bytecode::Interpreter&) const
  1034. {
  1035. // Handled in the interpreter loop.
  1036. __builtin_unreachable();
  1037. }
  1038. ThrowCompletionOr<void> JumpNullish::execute_impl(Bytecode::Interpreter&) const
  1039. {
  1040. // Handled in the interpreter loop.
  1041. __builtin_unreachable();
  1042. }
  1043. ThrowCompletionOr<void> JumpUndefined::execute_impl(Bytecode::Interpreter&) const
  1044. {
  1045. // Handled in the interpreter loop.
  1046. __builtin_unreachable();
  1047. }
  1048. // 13.3.8.1 https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  1049. static MarkedVector<Value> argument_list_evaluation(Bytecode::Interpreter& interpreter)
  1050. {
  1051. // Note: Any spreading and actual evaluation is handled in preceding opcodes
  1052. // Note: The spec uses the concept of a list, while we create a temporary array
  1053. // in the preceding opcodes, so we have to convert in a manner that is not
  1054. // visible to the user
  1055. auto& vm = interpreter.vm();
  1056. MarkedVector<Value> argument_values { vm.heap() };
  1057. auto arguments = interpreter.accumulator();
  1058. auto& argument_array = arguments.as_array();
  1059. auto array_length = argument_array.indexed_properties().array_like_size();
  1060. argument_values.ensure_capacity(array_length);
  1061. for (size_t i = 0; i < array_length; ++i) {
  1062. if (auto maybe_value = argument_array.indexed_properties().get(i); maybe_value.has_value())
  1063. argument_values.append(maybe_value.release_value().value);
  1064. else
  1065. argument_values.append(js_undefined());
  1066. }
  1067. return argument_values;
  1068. }
  1069. static Completion throw_type_error_for_callee(Bytecode::Interpreter& interpreter, auto& call, StringView callee_type)
  1070. {
  1071. auto& vm = interpreter.vm();
  1072. auto callee = interpreter.reg(call.callee());
  1073. if (call.expression_string().has_value())
  1074. return vm.throw_completion<TypeError>(ErrorType::IsNotAEvaluatedFrom, callee.to_string_without_side_effects(), callee_type, interpreter.current_executable().get_string(call.expression_string()->value()));
  1075. return vm.throw_completion<TypeError>(ErrorType::IsNotA, callee.to_string_without_side_effects(), callee_type);
  1076. }
  1077. static ThrowCompletionOr<void> throw_if_needed_for_call(Interpreter& interpreter, auto& call, Value callee)
  1078. {
  1079. if (call.call_type() == CallType::Call && !callee.is_function())
  1080. return throw_type_error_for_callee(interpreter, call, "function"sv);
  1081. if (call.call_type() == CallType::Construct && !callee.is_constructor())
  1082. return throw_type_error_for_callee(interpreter, call, "constructor"sv);
  1083. return {};
  1084. }
  1085. static ThrowCompletionOr<void> perform_call(Interpreter& interpreter, auto& call, Value callee, MarkedVector<Value> argument_values)
  1086. {
  1087. auto& vm = interpreter.vm();
  1088. auto this_value = interpreter.reg(call.this_value());
  1089. auto& function = callee.as_function();
  1090. Value return_value;
  1091. if (call.call_type() == CallType::DirectEval) {
  1092. if (callee == interpreter.realm().intrinsics().eval_function())
  1093. return_value = TRY(perform_eval(vm, !argument_values.is_empty() ? argument_values[0].value_or(JS::js_undefined()) : js_undefined(), vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct));
  1094. else
  1095. return_value = TRY(JS::call(vm, function, this_value, move(argument_values)));
  1096. } else if (call.call_type() == CallType::Call)
  1097. return_value = TRY(JS::call(vm, function, this_value, move(argument_values)));
  1098. else
  1099. return_value = TRY(construct(vm, function, move(argument_values)));
  1100. interpreter.accumulator() = return_value;
  1101. return {};
  1102. }
  1103. ThrowCompletionOr<void> Call::execute_impl(Bytecode::Interpreter& interpreter) const
  1104. {
  1105. auto& vm = interpreter.vm();
  1106. auto callee = interpreter.reg(m_callee);
  1107. TRY(throw_if_needed_for_call(interpreter, *this, callee));
  1108. MarkedVector<Value> argument_values(vm.heap());
  1109. argument_values.ensure_capacity(m_argument_count);
  1110. for (u32 i = 0; i < m_argument_count; ++i) {
  1111. argument_values.unchecked_append(interpreter.reg(Register { m_first_argument.index() + i }));
  1112. }
  1113. return perform_call(interpreter, *this, callee, move(argument_values));
  1114. }
  1115. ThrowCompletionOr<void> CallWithArgumentArray::execute_impl(Bytecode::Interpreter& interpreter) const
  1116. {
  1117. auto callee = interpreter.reg(m_callee);
  1118. TRY(throw_if_needed_for_call(interpreter, *this, callee));
  1119. auto argument_values = argument_list_evaluation(interpreter);
  1120. return perform_call(interpreter, *this, callee, move(argument_values));
  1121. }
  1122. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  1123. ThrowCompletionOr<void> SuperCallWithArgumentArray::execute_impl(Bytecode::Interpreter& interpreter) const
  1124. {
  1125. auto& vm = interpreter.vm();
  1126. // 1. Let newTarget be GetNewTarget().
  1127. auto new_target = vm.get_new_target();
  1128. // 2. Assert: Type(newTarget) is Object.
  1129. VERIFY(new_target.is_object());
  1130. // 3. Let func be GetSuperConstructor().
  1131. auto* func = get_super_constructor(vm);
  1132. // 4. Let argList be ? ArgumentListEvaluation of Arguments.
  1133. MarkedVector<Value> arg_list { vm.heap() };
  1134. if (m_is_synthetic) {
  1135. auto const& value = interpreter.accumulator();
  1136. VERIFY(value.is_object() && is<Array>(value.as_object()));
  1137. auto const& array_value = static_cast<Array const&>(value.as_object());
  1138. auto length = MUST(length_of_array_like(vm, array_value));
  1139. for (size_t i = 0; i < length; ++i)
  1140. arg_list.append(array_value.get_without_side_effects(PropertyKey { i }));
  1141. } else {
  1142. arg_list = argument_list_evaluation(interpreter);
  1143. }
  1144. // 5. If IsConstructor(func) is false, throw a TypeError exception.
  1145. if (!Value(func).is_constructor())
  1146. return vm.throw_completion<TypeError>(ErrorType::NotAConstructor, "Super constructor");
  1147. // 6. Let result be ? Construct(func, argList, newTarget).
  1148. auto result = TRY(construct(vm, static_cast<FunctionObject&>(*func), move(arg_list), &new_target.as_function()));
  1149. // 7. Let thisER be GetThisEnvironment().
  1150. auto& this_environment = verify_cast<FunctionEnvironment>(*get_this_environment(vm));
  1151. // 8. Perform ? thisER.BindThisValue(result).
  1152. TRY(this_environment.bind_this_value(vm, result));
  1153. // 9. Let F be thisER.[[FunctionObject]].
  1154. auto& f = this_environment.function_object();
  1155. // 10. Assert: F is an ECMAScript function object.
  1156. // NOTE: This is implied by the strong C++ type.
  1157. // 11. Perform ? InitializeInstanceElements(result, F).
  1158. TRY(result->initialize_instance_elements(f));
  1159. // 12. Return result.
  1160. interpreter.accumulator() = result;
  1161. return {};
  1162. }
  1163. ThrowCompletionOr<void> NewFunction::execute_impl(Bytecode::Interpreter& interpreter) const
  1164. {
  1165. auto& vm = interpreter.vm();
  1166. if (!m_function_node.has_name()) {
  1167. DeprecatedFlyString name = {};
  1168. if (m_lhs_name.has_value())
  1169. name = interpreter.current_executable().get_identifier(m_lhs_name.value());
  1170. interpreter.accumulator() = m_function_node.instantiate_ordinary_function_expression(vm, name);
  1171. } else {
  1172. interpreter.accumulator() = ECMAScriptFunctionObject::create(interpreter.realm(), m_function_node.name(), m_function_node.source_text(), m_function_node.body(), m_function_node.parameters(), m_function_node.function_length(), m_function_node.local_variables_names(), 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.contains_direct_call_to_eval(), m_function_node.is_arrow_function());
  1173. }
  1174. if (m_home_object.has_value()) {
  1175. auto home_object_value = interpreter.reg(m_home_object.value());
  1176. static_cast<ECMAScriptFunctionObject&>(interpreter.accumulator().as_function()).set_home_object(&home_object_value.as_object());
  1177. }
  1178. return {};
  1179. }
  1180. ThrowCompletionOr<void> Return::execute_impl(Bytecode::Interpreter& interpreter) const
  1181. {
  1182. interpreter.do_return(interpreter.accumulator().value_or(js_undefined()));
  1183. return {};
  1184. }
  1185. ThrowCompletionOr<void> Increment::execute_impl(Bytecode::Interpreter& interpreter) const
  1186. {
  1187. auto& vm = interpreter.vm();
  1188. auto old_value = TRY(interpreter.accumulator().to_numeric(vm));
  1189. if (old_value.is_number())
  1190. interpreter.accumulator() = Value(old_value.as_double() + 1);
  1191. else
  1192. interpreter.accumulator() = BigInt::create(vm, old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  1193. return {};
  1194. }
  1195. ThrowCompletionOr<void> Decrement::execute_impl(Bytecode::Interpreter& interpreter) const
  1196. {
  1197. auto& vm = interpreter.vm();
  1198. auto old_value = TRY(interpreter.accumulator().to_numeric(vm));
  1199. if (old_value.is_number())
  1200. interpreter.accumulator() = Value(old_value.as_double() - 1);
  1201. else
  1202. interpreter.accumulator() = BigInt::create(vm, old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
  1203. return {};
  1204. }
  1205. ThrowCompletionOr<void> Throw::execute_impl(Bytecode::Interpreter& interpreter) const
  1206. {
  1207. return throw_completion(interpreter.accumulator());
  1208. }
  1209. ThrowCompletionOr<void> ThrowIfNotObject::execute_impl(Bytecode::Interpreter& interpreter) const
  1210. {
  1211. auto& vm = interpreter.vm();
  1212. if (!interpreter.accumulator().is_object())
  1213. return vm.throw_completion<TypeError>(ErrorType::NotAnObject, interpreter.accumulator().to_string_without_side_effects());
  1214. return {};
  1215. }
  1216. ThrowCompletionOr<void> ThrowIfNullish::execute_impl(Bytecode::Interpreter& interpreter) const
  1217. {
  1218. auto& vm = interpreter.vm();
  1219. auto value = interpreter.accumulator();
  1220. if (value.is_nullish())
  1221. return vm.throw_completion<TypeError>(ErrorType::NotObjectCoercible, value.to_string_without_side_effects());
  1222. return {};
  1223. }
  1224. ThrowCompletionOr<void> EnterUnwindContext::execute_impl(Bytecode::Interpreter&) const
  1225. {
  1226. // Handled in the interpreter loop.
  1227. __builtin_unreachable();
  1228. }
  1229. ThrowCompletionOr<void> ScheduleJump::execute_impl(Bytecode::Interpreter&) const
  1230. {
  1231. // Handled in the interpreter loop.
  1232. __builtin_unreachable();
  1233. }
  1234. ThrowCompletionOr<void> LeaveLexicalEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  1235. {
  1236. interpreter.vm().running_execution_context().lexical_environment = interpreter.saved_lexical_environment_stack().take_last();
  1237. return {};
  1238. }
  1239. ThrowCompletionOr<void> LeaveUnwindContext::execute_impl(Bytecode::Interpreter& interpreter) const
  1240. {
  1241. interpreter.leave_unwind_context();
  1242. return {};
  1243. }
  1244. ThrowCompletionOr<void> ContinuePendingUnwind::execute_impl(Bytecode::Interpreter&) const
  1245. {
  1246. // Handled in the interpreter loop.
  1247. __builtin_unreachable();
  1248. }
  1249. ThrowCompletionOr<void> PushDeclarativeEnvironment::execute_impl(Bytecode::Interpreter& interpreter) const
  1250. {
  1251. auto environment = interpreter.vm().heap().allocate_without_realm<DeclarativeEnvironment>(interpreter.vm().lexical_environment());
  1252. interpreter.vm().running_execution_context().lexical_environment = environment;
  1253. interpreter.vm().running_execution_context().variable_environment = environment;
  1254. return {};
  1255. }
  1256. ThrowCompletionOr<void> Yield::execute_impl(Bytecode::Interpreter& interpreter) const
  1257. {
  1258. auto yielded_value = interpreter.accumulator().value_or(js_undefined());
  1259. auto object = Object::create(interpreter.realm(), nullptr);
  1260. object->define_direct_property("result", yielded_value, JS::default_attributes);
  1261. if (m_continuation_label.has_value())
  1262. // FIXME: If we get a pointer, which is not accurately representable as a double
  1263. // will cause this to explode
  1264. object->define_direct_property("continuation", Value(static_cast<double>(reinterpret_cast<u64>(&m_continuation_label->block()))), JS::default_attributes);
  1265. else
  1266. object->define_direct_property("continuation", Value(0), JS::default_attributes);
  1267. object->define_direct_property("isAwait", Value(false), JS::default_attributes);
  1268. interpreter.do_return(object);
  1269. return {};
  1270. }
  1271. ThrowCompletionOr<void> Await::execute_impl(Bytecode::Interpreter& interpreter) const
  1272. {
  1273. auto yielded_value = interpreter.accumulator().value_or(js_undefined());
  1274. auto object = Object::create(interpreter.realm(), nullptr);
  1275. object->define_direct_property("result", yielded_value, JS::default_attributes);
  1276. // FIXME: If we get a pointer, which is not accurately representable as a double
  1277. // will cause this to explode
  1278. object->define_direct_property("continuation", Value(static_cast<double>(reinterpret_cast<u64>(&m_continuation_label.block()))), JS::default_attributes);
  1279. object->define_direct_property("isAwait", Value(true), JS::default_attributes);
  1280. interpreter.do_return(object);
  1281. return {};
  1282. }
  1283. ThrowCompletionOr<void> GetByValue::execute_impl(Bytecode::Interpreter& interpreter) const
  1284. {
  1285. auto& vm = interpreter.vm();
  1286. // NOTE: Get the property key from the accumulator before side effects have a chance to overwrite it.
  1287. auto property_key_value = interpreter.accumulator();
  1288. auto base_value = interpreter.reg(m_base);
  1289. auto object = TRY(base_object_for_get(interpreter, base_value));
  1290. auto property_key = TRY(property_key_value.to_property_key(vm));
  1291. if (base_value.is_string()) {
  1292. auto string_value = TRY(base_value.as_string().get(vm, property_key));
  1293. if (string_value.has_value()) {
  1294. interpreter.accumulator() = *string_value;
  1295. return {};
  1296. }
  1297. }
  1298. interpreter.accumulator() = TRY(object->internal_get(property_key, base_value));
  1299. return {};
  1300. }
  1301. ThrowCompletionOr<void> GetByValueWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  1302. {
  1303. auto& vm = interpreter.vm();
  1304. // NOTE: Get the property key from the accumulator before side effects have a chance to overwrite it.
  1305. auto property_key_value = interpreter.accumulator();
  1306. auto object = TRY(interpreter.reg(m_base).to_object(vm));
  1307. auto property_key = TRY(property_key_value.to_property_key(vm));
  1308. interpreter.accumulator() = TRY(object->internal_get(property_key, interpreter.reg(m_this_value)));
  1309. return {};
  1310. }
  1311. ThrowCompletionOr<void> PutByValue::execute_impl(Bytecode::Interpreter& interpreter) const
  1312. {
  1313. auto& vm = interpreter.vm();
  1314. // NOTE: Get the value from the accumulator before side effects have a chance to overwrite it.
  1315. auto value = interpreter.accumulator();
  1316. auto base = interpreter.reg(m_base);
  1317. auto property_key = m_kind != PropertyKind::Spread ? TRY(interpreter.reg(m_property).to_property_key(vm)) : PropertyKey {};
  1318. TRY(put_by_property_key(vm, base, base, value, property_key, m_kind));
  1319. interpreter.accumulator() = value;
  1320. return {};
  1321. }
  1322. ThrowCompletionOr<void> PutByValueWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  1323. {
  1324. auto& vm = interpreter.vm();
  1325. // NOTE: Get the value from the accumulator before side effects have a chance to overwrite it.
  1326. auto value = interpreter.accumulator();
  1327. auto base = interpreter.reg(m_base);
  1328. auto property_key = m_kind != PropertyKind::Spread ? TRY(interpreter.reg(m_property).to_property_key(vm)) : PropertyKey {};
  1329. TRY(put_by_property_key(vm, base, interpreter.reg(m_this_value), value, property_key, m_kind));
  1330. interpreter.accumulator() = value;
  1331. return {};
  1332. }
  1333. ThrowCompletionOr<void> DeleteByValue::execute_impl(Bytecode::Interpreter& interpreter) const
  1334. {
  1335. auto& vm = interpreter.vm();
  1336. // NOTE: Get the property key from the accumulator before side effects have a chance to overwrite it.
  1337. auto property_key_value = interpreter.accumulator();
  1338. auto base_value = interpreter.reg(m_base);
  1339. auto property_key = TRY(property_key_value.to_property_key(vm));
  1340. bool strict = vm.in_strict_mode();
  1341. auto reference = Reference { base_value, property_key, {}, strict };
  1342. interpreter.accumulator() = Value(TRY(reference.delete_(vm)));
  1343. return {};
  1344. }
  1345. ThrowCompletionOr<void> DeleteByValueWithThis::execute_impl(Bytecode::Interpreter& interpreter) const
  1346. {
  1347. auto& vm = interpreter.vm();
  1348. // NOTE: Get the property key from the accumulator before side effects have a chance to overwrite it.
  1349. auto property_key_value = interpreter.accumulator();
  1350. auto base_value = interpreter.reg(m_base);
  1351. auto property_key = TRY(property_key_value.to_property_key(vm));
  1352. bool strict = vm.in_strict_mode();
  1353. auto reference = Reference { base_value, property_key, interpreter.reg(m_this_value), strict };
  1354. interpreter.accumulator() = Value(TRY(reference.delete_(vm)));
  1355. return {};
  1356. }
  1357. ThrowCompletionOr<void> GetIterator::execute_impl(Bytecode::Interpreter& interpreter) const
  1358. {
  1359. auto& vm = interpreter.vm();
  1360. auto iterator = TRY(get_iterator(vm, interpreter.accumulator(), m_hint));
  1361. interpreter.accumulator() = iterator_to_object(vm, iterator);
  1362. return {};
  1363. }
  1364. ThrowCompletionOr<void> GetMethod::execute_impl(Bytecode::Interpreter& interpreter) const
  1365. {
  1366. auto& vm = interpreter.vm();
  1367. auto identifier = interpreter.current_executable().get_identifier(m_property);
  1368. auto method = TRY(interpreter.accumulator().get_method(vm, identifier));
  1369. interpreter.accumulator() = method ?: js_undefined();
  1370. return {};
  1371. }
  1372. // 14.7.5.9 EnumerateObjectProperties ( O ), https://tc39.es/ecma262/#sec-enumerate-object-properties
  1373. ThrowCompletionOr<void> GetObjectPropertyIterator::execute_impl(Bytecode::Interpreter& interpreter) const
  1374. {
  1375. // While the spec does provide an algorithm, it allows us to implement it ourselves so long as we meet the following invariants:
  1376. // 1- Returned property keys do not include keys that are Symbols
  1377. // 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
  1378. // 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
  1379. // 4- A property name will be returned by the iterator's next method at most once in any enumeration.
  1380. // 5- Enumerating the properties of the target object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively;
  1381. // 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.
  1382. // 6- The values of [[Enumerable]] attributes are not considered when determining if a property of a prototype object has already been processed.
  1383. // 7- The enumerable property names of prototype objects must be obtained by invoking EnumerateObjectProperties passing the prototype object as the argument.
  1384. // 8- EnumerateObjectProperties must obtain the own property keys of the target object by calling its [[OwnPropertyKeys]] internal method.
  1385. // 9- Property attributes of the target object must be obtained by calling its [[GetOwnProperty]] internal method
  1386. // Invariant 3 effectively allows the implementation to ignore newly added keys, and we do so (similar to other implementations).
  1387. auto& vm = interpreter.vm();
  1388. auto object = TRY(interpreter.accumulator().to_object(vm));
  1389. // Note: While the spec doesn't explicitly require these to be ordered, it says that the values should be retrieved via OwnPropertyKeys,
  1390. // so we just keep the order consistent anyway.
  1391. OrderedHashTable<PropertyKey> properties;
  1392. OrderedHashTable<PropertyKey> non_enumerable_properties;
  1393. HashTable<NonnullGCPtr<Object>> seen_objects;
  1394. // Collect all keys immediately (invariant no. 5)
  1395. for (auto object_to_check = GCPtr { object.ptr() }; object_to_check && !seen_objects.contains(*object_to_check); object_to_check = TRY(object_to_check->internal_get_prototype_of())) {
  1396. seen_objects.set(*object_to_check);
  1397. for (auto& key : TRY(object_to_check->internal_own_property_keys())) {
  1398. if (key.is_symbol())
  1399. continue;
  1400. auto property_key = TRY(PropertyKey::from_value(vm, key));
  1401. // If there is a non-enumerable property higher up the prototype chain with the same key,
  1402. // we mustn't include this property even if it's enumerable (invariant no. 5 and 6)
  1403. if (non_enumerable_properties.contains(property_key))
  1404. continue;
  1405. if (properties.contains(property_key))
  1406. continue;
  1407. auto descriptor = TRY(object_to_check->internal_get_own_property(property_key));
  1408. if (!*descriptor->enumerable)
  1409. non_enumerable_properties.set(move(property_key));
  1410. else
  1411. properties.set(move(property_key));
  1412. }
  1413. }
  1414. IteratorRecord iterator {
  1415. .iterator = object,
  1416. .next_method = NativeFunction::create(
  1417. interpreter.realm(),
  1418. [items = move(properties)](VM& vm) mutable -> ThrowCompletionOr<Value> {
  1419. auto& realm = *vm.current_realm();
  1420. auto iterated_object_value = vm.this_value();
  1421. if (!iterated_object_value.is_object())
  1422. return vm.throw_completion<InternalError>("Invalid state for GetObjectPropertyIterator.next"sv);
  1423. auto& iterated_object = iterated_object_value.as_object();
  1424. auto result_object = Object::create(realm, nullptr);
  1425. while (true) {
  1426. if (items.is_empty()) {
  1427. result_object->define_direct_property(vm.names.done, JS::Value(true), default_attributes);
  1428. return result_object;
  1429. }
  1430. auto key = items.take_first();
  1431. // If the property is deleted, don't include it (invariant no. 2)
  1432. if (!TRY(iterated_object.has_property(key)))
  1433. continue;
  1434. result_object->define_direct_property(vm.names.done, JS::Value(false), default_attributes);
  1435. if (key.is_number())
  1436. result_object->define_direct_property(vm.names.value, PrimitiveString::create(vm, TRY_OR_THROW_OOM(vm, String::number(key.as_number()))), default_attributes);
  1437. else if (key.is_string())
  1438. result_object->define_direct_property(vm.names.value, PrimitiveString::create(vm, key.as_string()), default_attributes);
  1439. else
  1440. VERIFY_NOT_REACHED(); // We should not have non-string/number keys.
  1441. return result_object;
  1442. }
  1443. },
  1444. 1,
  1445. vm.names.next),
  1446. .done = false,
  1447. };
  1448. interpreter.accumulator() = iterator_to_object(vm, move(iterator));
  1449. return {};
  1450. }
  1451. ThrowCompletionOr<void> IteratorClose::execute_impl(Bytecode::Interpreter& interpreter) const
  1452. {
  1453. auto& vm = interpreter.vm();
  1454. auto iterator_object = TRY(interpreter.accumulator().to_object(vm));
  1455. auto iterator = object_to_iterator(vm, iterator_object);
  1456. // FIXME: Return the value of the resulting completion. (Note that m_completion_value can be empty!)
  1457. TRY(iterator_close(vm, iterator, Completion { m_completion_type, m_completion_value, {} }));
  1458. return {};
  1459. }
  1460. ThrowCompletionOr<void> AsyncIteratorClose::execute_impl(Bytecode::Interpreter& interpreter) const
  1461. {
  1462. auto& vm = interpreter.vm();
  1463. auto iterator_object = TRY(interpreter.accumulator().to_object(vm));
  1464. auto iterator = object_to_iterator(vm, iterator_object);
  1465. // FIXME: Return the value of the resulting completion. (Note that m_completion_value can be empty!)
  1466. TRY(async_iterator_close(vm, iterator, Completion { m_completion_type, m_completion_value, {} }));
  1467. return {};
  1468. }
  1469. ThrowCompletionOr<void> IteratorNext::execute_impl(Bytecode::Interpreter& interpreter) const
  1470. {
  1471. auto& vm = interpreter.vm();
  1472. auto iterator_object = TRY(interpreter.accumulator().to_object(vm));
  1473. auto iterator = object_to_iterator(vm, iterator_object);
  1474. interpreter.accumulator() = TRY(iterator_next(vm, iterator));
  1475. return {};
  1476. }
  1477. ThrowCompletionOr<void> IteratorResultDone::execute_impl(Bytecode::Interpreter& interpreter) const
  1478. {
  1479. auto& vm = interpreter.vm();
  1480. auto iterator_result = TRY(interpreter.accumulator().to_object(vm));
  1481. auto complete = TRY(iterator_complete(vm, iterator_result));
  1482. interpreter.accumulator() = Value(complete);
  1483. return {};
  1484. }
  1485. ThrowCompletionOr<void> IteratorResultValue::execute_impl(Bytecode::Interpreter& interpreter) const
  1486. {
  1487. auto& vm = interpreter.vm();
  1488. auto iterator_result = TRY(interpreter.accumulator().to_object(vm));
  1489. interpreter.accumulator() = TRY(iterator_value(vm, iterator_result));
  1490. return {};
  1491. }
  1492. ThrowCompletionOr<void> NewClass::execute_impl(Bytecode::Interpreter& interpreter) const
  1493. {
  1494. auto& vm = interpreter.vm();
  1495. auto name = m_class_expression.name();
  1496. auto super_class = interpreter.accumulator();
  1497. // NOTE: NewClass expects classEnv to be active lexical environment
  1498. auto class_environment = vm.lexical_environment();
  1499. vm.running_execution_context().lexical_environment = interpreter.saved_lexical_environment_stack().take_last();
  1500. DeprecatedFlyString binding_name;
  1501. DeprecatedFlyString class_name;
  1502. if (!m_class_expression.has_name() && m_lhs_name.has_value()) {
  1503. class_name = interpreter.current_executable().get_identifier(m_lhs_name.value());
  1504. } else {
  1505. binding_name = name;
  1506. class_name = name.is_null() ? ""sv : name;
  1507. }
  1508. interpreter.accumulator() = TRY(m_class_expression.create_class_constructor(vm, class_environment, vm.lexical_environment(), super_class, binding_name, class_name));
  1509. return {};
  1510. }
  1511. // 13.5.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-typeof-operator-runtime-semantics-evaluation
  1512. ThrowCompletionOr<void> TypeofVariable::execute_impl(Bytecode::Interpreter& interpreter) const
  1513. {
  1514. auto& vm = interpreter.vm();
  1515. // 1. Let val be the result of evaluating UnaryExpression.
  1516. auto const& string = interpreter.current_executable().get_identifier(m_identifier);
  1517. auto reference = TRY(vm.resolve_binding(string));
  1518. // 2. If val is a Reference Record, then
  1519. // a. If IsUnresolvableReference(val) is true, return "undefined".
  1520. if (reference.is_unresolvable()) {
  1521. interpreter.accumulator() = PrimitiveString::create(vm, "undefined"_string);
  1522. return {};
  1523. }
  1524. // 3. Set val to ? GetValue(val).
  1525. auto value = TRY(reference.get_value(vm));
  1526. // 4. NOTE: This step is replaced in section B.3.6.3.
  1527. // 5. Return a String according to Table 41.
  1528. interpreter.accumulator() = PrimitiveString::create(vm, value.typeof());
  1529. return {};
  1530. }
  1531. ThrowCompletionOr<void> TypeofLocal::execute_impl(Bytecode::Interpreter& interpreter) const
  1532. {
  1533. auto& vm = interpreter.vm();
  1534. auto const& value = vm.running_execution_context().local_variables[m_index];
  1535. interpreter.accumulator() = PrimitiveString::create(vm, value.typeof());
  1536. return {};
  1537. }
  1538. ThrowCompletionOr<void> ToNumeric::execute_impl(Bytecode::Interpreter& interpreter) const
  1539. {
  1540. interpreter.accumulator() = TRY(interpreter.accumulator().to_numeric(interpreter.vm()));
  1541. return {};
  1542. }
  1543. ThrowCompletionOr<void> BlockDeclarationInstantiation::execute_impl(Bytecode::Interpreter& interpreter) const
  1544. {
  1545. auto& vm = interpreter.vm();
  1546. auto old_environment = vm.running_execution_context().lexical_environment;
  1547. interpreter.saved_lexical_environment_stack().append(old_environment);
  1548. vm.running_execution_context().lexical_environment = new_declarative_environment(*old_environment);
  1549. m_scope_node.block_declaration_instantiation(vm, vm.running_execution_context().lexical_environment);
  1550. return {};
  1551. }
  1552. DeprecatedString Load::to_deprecated_string_impl(Bytecode::Executable const&) const
  1553. {
  1554. return DeprecatedString::formatted("Load {}", m_src);
  1555. }
  1556. DeprecatedString LoadImmediate::to_deprecated_string_impl(Bytecode::Executable const&) const
  1557. {
  1558. return DeprecatedString::formatted("LoadImmediate {}", m_value);
  1559. }
  1560. DeprecatedString Store::to_deprecated_string_impl(Bytecode::Executable const&) const
  1561. {
  1562. return DeprecatedString::formatted("Store {}", m_dst);
  1563. }
  1564. DeprecatedString NewBigInt::to_deprecated_string_impl(Bytecode::Executable const&) const
  1565. {
  1566. return DeprecatedString::formatted("NewBigInt \"{}\"", m_bigint.to_base_deprecated(10));
  1567. }
  1568. DeprecatedString NewArray::to_deprecated_string_impl(Bytecode::Executable const&) const
  1569. {
  1570. StringBuilder builder;
  1571. builder.append("NewArray"sv);
  1572. if (m_element_count != 0) {
  1573. builder.appendff(" [{}-{}]", m_elements[0], m_elements[1]);
  1574. }
  1575. return builder.to_deprecated_string();
  1576. }
  1577. DeprecatedString Append::to_deprecated_string_impl(Bytecode::Executable const&) const
  1578. {
  1579. if (m_is_spread)
  1580. return DeprecatedString::formatted("Append lhs: **{}", m_lhs);
  1581. return DeprecatedString::formatted("Append lhs: {}", m_lhs);
  1582. }
  1583. DeprecatedString IteratorToArray::to_deprecated_string_impl(Bytecode::Executable const&) const
  1584. {
  1585. return "IteratorToArray";
  1586. }
  1587. DeprecatedString NewString::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1588. {
  1589. return DeprecatedString::formatted("NewString {} (\"{}\")", m_string, executable.string_table->get(m_string));
  1590. }
  1591. DeprecatedString NewObject::to_deprecated_string_impl(Bytecode::Executable const&) const
  1592. {
  1593. return "NewObject";
  1594. }
  1595. DeprecatedString NewRegExp::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1596. {
  1597. return DeprecatedString::formatted("NewRegExp source:{} (\"{}\") flags:{} (\"{}\")", m_source_index, executable.get_string(m_source_index), m_flags_index, executable.get_string(m_flags_index));
  1598. }
  1599. DeprecatedString CopyObjectExcludingProperties::to_deprecated_string_impl(Bytecode::Executable const&) const
  1600. {
  1601. StringBuilder builder;
  1602. builder.appendff("CopyObjectExcludingProperties from:{}", m_from_object);
  1603. if (m_excluded_names_count != 0) {
  1604. builder.append(" excluding:["sv);
  1605. builder.join(", "sv, ReadonlySpan<Register>(m_excluded_names, m_excluded_names_count));
  1606. builder.append(']');
  1607. }
  1608. return builder.to_deprecated_string();
  1609. }
  1610. DeprecatedString ConcatString::to_deprecated_string_impl(Bytecode::Executable const&) const
  1611. {
  1612. return DeprecatedString::formatted("ConcatString {}", m_lhs);
  1613. }
  1614. DeprecatedString GetCalleeAndThisFromEnvironment::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1615. {
  1616. return DeprecatedString::formatted("GetCalleeAndThisFromEnvironment {} -> callee: {}, this:{} ", executable.identifier_table->get(m_identifier), m_callee_reg, m_this_reg);
  1617. }
  1618. DeprecatedString GetVariable::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1619. {
  1620. return DeprecatedString::formatted("GetVariable {} ({})", m_identifier, executable.identifier_table->get(m_identifier));
  1621. }
  1622. DeprecatedString GetGlobal::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1623. {
  1624. return DeprecatedString::formatted("GetGlobal {} ({})", m_identifier, executable.identifier_table->get(m_identifier));
  1625. }
  1626. DeprecatedString GetLocal::to_deprecated_string_impl(Bytecode::Executable const&) const
  1627. {
  1628. return DeprecatedString::formatted("GetLocal {}", m_index);
  1629. }
  1630. DeprecatedString DeleteVariable::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1631. {
  1632. return DeprecatedString::formatted("DeleteVariable {} ({})", m_identifier, executable.identifier_table->get(m_identifier));
  1633. }
  1634. DeprecatedString CreateLexicalEnvironment::to_deprecated_string_impl(Bytecode::Executable const&) const
  1635. {
  1636. return "CreateLexicalEnvironment"sv;
  1637. }
  1638. DeprecatedString CreateVariable::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1639. {
  1640. auto mode_string = m_mode == EnvironmentMode::Lexical ? "Lexical" : "Variable";
  1641. return DeprecatedString::formatted("CreateVariable env:{} immutable:{} global:{} {} ({})", mode_string, m_is_immutable, m_is_global, m_identifier, executable.identifier_table->get(m_identifier));
  1642. }
  1643. DeprecatedString EnterObjectEnvironment::to_deprecated_string_impl(Executable const&) const
  1644. {
  1645. return DeprecatedString::formatted("EnterObjectEnvironment");
  1646. }
  1647. DeprecatedString SetVariable::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1648. {
  1649. auto initialization_mode_name = m_initialization_mode == InitializationMode::Initialize ? "Initialize" : "Set";
  1650. auto mode_string = m_mode == EnvironmentMode::Lexical ? "Lexical" : "Variable";
  1651. return DeprecatedString::formatted("SetVariable env:{} init:{} {} ({})", mode_string, initialization_mode_name, m_identifier, executable.identifier_table->get(m_identifier));
  1652. }
  1653. DeprecatedString SetLocal::to_deprecated_string_impl(Bytecode::Executable const&) const
  1654. {
  1655. return DeprecatedString::formatted("SetLocal {}", m_index);
  1656. }
  1657. static StringView property_kind_to_string(PropertyKind kind)
  1658. {
  1659. switch (kind) {
  1660. case PropertyKind::Getter:
  1661. return "getter"sv;
  1662. case PropertyKind::Setter:
  1663. return "setter"sv;
  1664. case PropertyKind::KeyValue:
  1665. return "key-value"sv;
  1666. case PropertyKind::DirectKeyValue:
  1667. return "direct-key-value"sv;
  1668. case PropertyKind::Spread:
  1669. return "spread"sv;
  1670. case PropertyKind::ProtoSetter:
  1671. return "proto-setter"sv;
  1672. }
  1673. VERIFY_NOT_REACHED();
  1674. }
  1675. DeprecatedString PutById::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1676. {
  1677. auto kind = property_kind_to_string(m_kind);
  1678. return DeprecatedString::formatted("PutById kind:{} base:{}, property:{} ({})", kind, m_base, m_property, executable.identifier_table->get(m_property));
  1679. }
  1680. DeprecatedString PutByIdWithThis::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1681. {
  1682. auto kind = property_kind_to_string(m_kind);
  1683. return DeprecatedString::formatted("PutByIdWithThis kind:{} base:{}, property:{} ({}) this_value:{}", kind, m_base, m_property, executable.identifier_table->get(m_property), m_this_value);
  1684. }
  1685. DeprecatedString PutPrivateById::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1686. {
  1687. auto kind = property_kind_to_string(m_kind);
  1688. return DeprecatedString::formatted("PutPrivateById kind:{} base:{}, property:{} ({})", kind, m_base, m_property, executable.identifier_table->get(m_property));
  1689. }
  1690. DeprecatedString GetById::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1691. {
  1692. return DeprecatedString::formatted("GetById {} ({})", m_property, executable.identifier_table->get(m_property));
  1693. }
  1694. DeprecatedString GetByIdWithThis::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1695. {
  1696. return DeprecatedString::formatted("GetByIdWithThis {} ({}) this_value:{}", m_property, executable.identifier_table->get(m_property), m_this_value);
  1697. }
  1698. DeprecatedString GetPrivateById::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1699. {
  1700. return DeprecatedString::formatted("GetPrivateById {} ({})", m_property, executable.identifier_table->get(m_property));
  1701. }
  1702. DeprecatedString HasPrivateId::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1703. {
  1704. return DeprecatedString::formatted("HasPrivateId {} ({})", m_property, executable.identifier_table->get(m_property));
  1705. }
  1706. DeprecatedString DeleteById::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1707. {
  1708. return DeprecatedString::formatted("DeleteById {} ({})", m_property, executable.identifier_table->get(m_property));
  1709. }
  1710. DeprecatedString DeleteByIdWithThis::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1711. {
  1712. return DeprecatedString::formatted("DeleteByIdWithThis {} ({}) this_value:{}", m_property, executable.identifier_table->get(m_property), m_this_value);
  1713. }
  1714. DeprecatedString Jump::to_deprecated_string_impl(Bytecode::Executable const&) const
  1715. {
  1716. if (m_true_target.has_value())
  1717. return DeprecatedString::formatted("Jump {}", *m_true_target);
  1718. return DeprecatedString::formatted("Jump <empty>");
  1719. }
  1720. DeprecatedString JumpConditional::to_deprecated_string_impl(Bytecode::Executable const&) const
  1721. {
  1722. auto true_string = m_true_target.has_value() ? DeprecatedString::formatted("{}", *m_true_target) : "<empty>";
  1723. auto false_string = m_false_target.has_value() ? DeprecatedString::formatted("{}", *m_false_target) : "<empty>";
  1724. return DeprecatedString::formatted("JumpConditional true:{} false:{}", true_string, false_string);
  1725. }
  1726. DeprecatedString JumpNullish::to_deprecated_string_impl(Bytecode::Executable const&) const
  1727. {
  1728. auto true_string = m_true_target.has_value() ? DeprecatedString::formatted("{}", *m_true_target) : "<empty>";
  1729. auto false_string = m_false_target.has_value() ? DeprecatedString::formatted("{}", *m_false_target) : "<empty>";
  1730. return DeprecatedString::formatted("JumpNullish null:{} nonnull:{}", true_string, false_string);
  1731. }
  1732. DeprecatedString JumpUndefined::to_deprecated_string_impl(Bytecode::Executable const&) const
  1733. {
  1734. auto true_string = m_true_target.has_value() ? DeprecatedString::formatted("{}", *m_true_target) : "<empty>";
  1735. auto false_string = m_false_target.has_value() ? DeprecatedString::formatted("{}", *m_false_target) : "<empty>";
  1736. return DeprecatedString::formatted("JumpUndefined undefined:{} not undefined:{}", true_string, false_string);
  1737. }
  1738. static StringView call_type_to_string(CallType type)
  1739. {
  1740. switch (type) {
  1741. case CallType::Call:
  1742. return ""sv;
  1743. case CallType::Construct:
  1744. return " (Construct)"sv;
  1745. case CallType::DirectEval:
  1746. return " (DirectEval)"sv;
  1747. }
  1748. VERIFY_NOT_REACHED();
  1749. }
  1750. DeprecatedString Call::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1751. {
  1752. auto type = call_type_to_string(m_type);
  1753. if (m_expression_string.has_value())
  1754. return DeprecatedString::formatted("Call{} callee:{}, this:{}, first_arg:{} ({})", type, m_callee, m_this_value, m_first_argument, executable.get_string(m_expression_string.value()));
  1755. return DeprecatedString::formatted("Call{} callee:{}, this:{}, first_arg:{}", type, m_callee, m_first_argument, m_this_value);
  1756. }
  1757. DeprecatedString CallWithArgumentArray::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1758. {
  1759. auto type = call_type_to_string(m_type);
  1760. if (m_expression_string.has_value())
  1761. return DeprecatedString::formatted("CallWithArgumentArray{} callee:{}, this:{}, arguments:[...acc] ({})", type, m_callee, m_this_value, executable.get_string(m_expression_string.value()));
  1762. return DeprecatedString::formatted("CallWithArgumentArray{} callee:{}, this:{}, arguments:[...acc]", type, m_callee, m_this_value);
  1763. }
  1764. DeprecatedString SuperCallWithArgumentArray::to_deprecated_string_impl(Bytecode::Executable const&) const
  1765. {
  1766. return "SuperCallWithArgumentArray arguments:[...acc]"sv;
  1767. }
  1768. DeprecatedString NewFunction::to_deprecated_string_impl(Bytecode::Executable const&) const
  1769. {
  1770. StringBuilder builder;
  1771. builder.append("NewFunction"sv);
  1772. if (m_function_node.has_name())
  1773. builder.appendff(" name:{}"sv, m_function_node.name());
  1774. if (m_lhs_name.has_value())
  1775. builder.appendff(" lhs_name:{}"sv, m_lhs_name.value());
  1776. if (m_home_object.has_value())
  1777. builder.appendff(" home_object:{}"sv, m_home_object.value());
  1778. return builder.to_deprecated_string();
  1779. }
  1780. DeprecatedString NewClass::to_deprecated_string_impl(Bytecode::Executable const&) const
  1781. {
  1782. StringBuilder builder;
  1783. auto name = m_class_expression.name();
  1784. builder.appendff("NewClass '{}'"sv, name.is_null() ? ""sv : name);
  1785. if (m_lhs_name.has_value())
  1786. builder.appendff(" lhs_name:{}"sv, m_lhs_name.value());
  1787. return builder.to_deprecated_string();
  1788. }
  1789. DeprecatedString Return::to_deprecated_string_impl(Bytecode::Executable const&) const
  1790. {
  1791. return "Return";
  1792. }
  1793. DeprecatedString Increment::to_deprecated_string_impl(Bytecode::Executable const&) const
  1794. {
  1795. return "Increment";
  1796. }
  1797. DeprecatedString Decrement::to_deprecated_string_impl(Bytecode::Executable const&) const
  1798. {
  1799. return "Decrement";
  1800. }
  1801. DeprecatedString Throw::to_deprecated_string_impl(Bytecode::Executable const&) const
  1802. {
  1803. return "Throw";
  1804. }
  1805. DeprecatedString ThrowIfNotObject::to_deprecated_string_impl(Bytecode::Executable const&) const
  1806. {
  1807. return "ThrowIfNotObject";
  1808. }
  1809. DeprecatedString ThrowIfNullish::to_deprecated_string_impl(Bytecode::Executable const&) const
  1810. {
  1811. return "ThrowIfNullish";
  1812. }
  1813. DeprecatedString EnterUnwindContext::to_deprecated_string_impl(Bytecode::Executable const&) const
  1814. {
  1815. auto handler_string = m_handler_target.has_value() ? DeprecatedString::formatted("{}", *m_handler_target) : "<empty>";
  1816. auto finalizer_string = m_finalizer_target.has_value() ? DeprecatedString::formatted("{}", *m_finalizer_target) : "<empty>";
  1817. return DeprecatedString::formatted("EnterUnwindContext handler:{} finalizer:{} entry:{}", handler_string, finalizer_string, m_entry_point);
  1818. }
  1819. DeprecatedString ScheduleJump::to_deprecated_string_impl(Bytecode::Executable const&) const
  1820. {
  1821. return DeprecatedString::formatted("ScheduleJump {}", m_target);
  1822. }
  1823. DeprecatedString LeaveLexicalEnvironment::to_deprecated_string_impl(Bytecode::Executable const&) const
  1824. {
  1825. return "LeaveLexicalEnvironment"sv;
  1826. }
  1827. DeprecatedString LeaveUnwindContext::to_deprecated_string_impl(Bytecode::Executable const&) const
  1828. {
  1829. return "LeaveUnwindContext";
  1830. }
  1831. DeprecatedString ContinuePendingUnwind::to_deprecated_string_impl(Bytecode::Executable const&) const
  1832. {
  1833. return DeprecatedString::formatted("ContinuePendingUnwind resume:{}", m_resume_target);
  1834. }
  1835. DeprecatedString PushDeclarativeEnvironment::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1836. {
  1837. StringBuilder builder;
  1838. builder.append("PushDeclarativeEnvironment"sv);
  1839. if (!m_variables.is_empty()) {
  1840. builder.append(" {"sv);
  1841. Vector<DeprecatedString> names;
  1842. for (auto& it : m_variables)
  1843. names.append(executable.get_string(it.key));
  1844. builder.append('}');
  1845. builder.join(", "sv, names);
  1846. }
  1847. return builder.to_deprecated_string();
  1848. }
  1849. DeprecatedString Yield::to_deprecated_string_impl(Bytecode::Executable const&) const
  1850. {
  1851. if (m_continuation_label.has_value())
  1852. return DeprecatedString::formatted("Yield continuation:@{}", m_continuation_label->block().name());
  1853. return DeprecatedString::formatted("Yield return");
  1854. }
  1855. DeprecatedString Await::to_deprecated_string_impl(Bytecode::Executable const&) const
  1856. {
  1857. return DeprecatedString::formatted("Await continuation:@{}", m_continuation_label.block().name());
  1858. }
  1859. DeprecatedString GetByValue::to_deprecated_string_impl(Bytecode::Executable const&) const
  1860. {
  1861. return DeprecatedString::formatted("GetByValue base:{}", m_base);
  1862. }
  1863. DeprecatedString GetByValueWithThis::to_deprecated_string_impl(Bytecode::Executable const&) const
  1864. {
  1865. return DeprecatedString::formatted("GetByValueWithThis base:{} this_value:{}", m_base, m_this_value);
  1866. }
  1867. DeprecatedString PutByValue::to_deprecated_string_impl(Bytecode::Executable const&) const
  1868. {
  1869. auto kind = property_kind_to_string(m_kind);
  1870. return DeprecatedString::formatted("PutByValue kind:{} base:{}, property:{}", kind, m_base, m_property);
  1871. }
  1872. DeprecatedString PutByValueWithThis::to_deprecated_string_impl(Bytecode::Executable const&) const
  1873. {
  1874. auto kind = property_kind_to_string(m_kind);
  1875. return DeprecatedString::formatted("PutByValueWithThis kind:{} base:{}, property:{} this_value:{}", kind, m_base, m_property, m_this_value);
  1876. }
  1877. DeprecatedString DeleteByValue::to_deprecated_string_impl(Bytecode::Executable const&) const
  1878. {
  1879. return DeprecatedString::formatted("DeleteByValue base:{}", m_base);
  1880. }
  1881. DeprecatedString DeleteByValueWithThis::to_deprecated_string_impl(Bytecode::Executable const&) const
  1882. {
  1883. return DeprecatedString::formatted("DeleteByValueWithThis base:{} this_value:{}", m_base, m_this_value);
  1884. }
  1885. DeprecatedString GetIterator::to_deprecated_string_impl(Executable const&) const
  1886. {
  1887. auto hint = m_hint == IteratorHint::Sync ? "sync" : "async";
  1888. return DeprecatedString::formatted("GetIterator hint:{}", hint);
  1889. }
  1890. DeprecatedString GetMethod::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1891. {
  1892. return DeprecatedString::formatted("GetMethod {} ({})", m_property, executable.identifier_table->get(m_property));
  1893. }
  1894. DeprecatedString GetObjectPropertyIterator::to_deprecated_string_impl(Bytecode::Executable const&) const
  1895. {
  1896. return "GetObjectPropertyIterator";
  1897. }
  1898. DeprecatedString IteratorClose::to_deprecated_string_impl(Bytecode::Executable const&) const
  1899. {
  1900. if (!m_completion_value.has_value())
  1901. return DeprecatedString::formatted("IteratorClose completion_type={} completion_value=<empty>", to_underlying(m_completion_type));
  1902. auto completion_value_string = m_completion_value->to_string_without_side_effects();
  1903. return DeprecatedString::formatted("IteratorClose completion_type={} completion_value={}", to_underlying(m_completion_type), completion_value_string);
  1904. }
  1905. DeprecatedString AsyncIteratorClose::to_deprecated_string_impl(Bytecode::Executable const&) const
  1906. {
  1907. if (!m_completion_value.has_value())
  1908. return DeprecatedString::formatted("AsyncIteratorClose completion_type={} completion_value=<empty>", to_underlying(m_completion_type));
  1909. auto completion_value_string = m_completion_value->to_string_without_side_effects();
  1910. return DeprecatedString::formatted("AsyncIteratorClose completion_type={} completion_value={}", to_underlying(m_completion_type), completion_value_string);
  1911. }
  1912. DeprecatedString IteratorNext::to_deprecated_string_impl(Executable const&) const
  1913. {
  1914. return "IteratorNext";
  1915. }
  1916. DeprecatedString IteratorResultDone::to_deprecated_string_impl(Executable const&) const
  1917. {
  1918. return "IteratorResultDone";
  1919. }
  1920. DeprecatedString IteratorResultValue::to_deprecated_string_impl(Executable const&) const
  1921. {
  1922. return "IteratorResultValue";
  1923. }
  1924. DeprecatedString ResolveThisBinding::to_deprecated_string_impl(Bytecode::Executable const&) const
  1925. {
  1926. return "ResolveThisBinding"sv;
  1927. }
  1928. DeprecatedString ResolveSuperBase::to_deprecated_string_impl(Bytecode::Executable const&) const
  1929. {
  1930. return "ResolveSuperBase"sv;
  1931. }
  1932. DeprecatedString GetNewTarget::to_deprecated_string_impl(Bytecode::Executable const&) const
  1933. {
  1934. return "GetNewTarget"sv;
  1935. }
  1936. DeprecatedString GetImportMeta::to_deprecated_string_impl(Bytecode::Executable const&) const
  1937. {
  1938. return "GetImportMeta"sv;
  1939. }
  1940. DeprecatedString TypeofVariable::to_deprecated_string_impl(Bytecode::Executable const& executable) const
  1941. {
  1942. return DeprecatedString::formatted("TypeofVariable {} ({})", m_identifier, executable.identifier_table->get(m_identifier));
  1943. }
  1944. DeprecatedString TypeofLocal::to_deprecated_string_impl(Bytecode::Executable const&) const
  1945. {
  1946. return DeprecatedString::formatted("TypeofLocal {}", m_index);
  1947. }
  1948. DeprecatedString ToNumeric::to_deprecated_string_impl(Bytecode::Executable const&) const
  1949. {
  1950. return "ToNumeric"sv;
  1951. }
  1952. DeprecatedString BlockDeclarationInstantiation::to_deprecated_string_impl(Bytecode::Executable const&) const
  1953. {
  1954. return "BlockDeclarationInstantiation"sv;
  1955. }
  1956. DeprecatedString ImportCall::to_deprecated_string_impl(Bytecode::Executable const&) const
  1957. {
  1958. return DeprecatedString::formatted("ImportCall specifier:{} options:{}"sv, m_specifier, m_options);
  1959. }
  1960. }