Interpreter.cpp 100 KB

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