ASTCodegen.cpp 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632
  1. /*
  2. * Copyright (c) 2021-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Gunnar Beutner <gbeutner@serenityos.org>
  5. * Copyright (c) 2021, Marcin Gasperowicz <xnooga@gmail.com>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Find.h>
  10. #include <LibJS/AST.h>
  11. #include <LibJS/Bytecode/Generator.h>
  12. #include <LibJS/Bytecode/Instruction.h>
  13. #include <LibJS/Bytecode/Op.h>
  14. #include <LibJS/Bytecode/Register.h>
  15. #include <LibJS/Bytecode/StringTable.h>
  16. #include <LibJS/Runtime/Environment.h>
  17. #include <LibJS/Runtime/ErrorTypes.h>
  18. namespace JS {
  19. Bytecode::CodeGenerationErrorOr<void> ASTNode::generate_bytecode(Bytecode::Generator&) const
  20. {
  21. return Bytecode::CodeGenerationError {
  22. this,
  23. "Missing generate_bytecode()"sv,
  24. };
  25. }
  26. Bytecode::CodeGenerationErrorOr<void> ScopeNode::generate_bytecode(Bytecode::Generator& generator) const
  27. {
  28. Optional<Bytecode::CodeGenerationError> maybe_error;
  29. size_t pushed_scope_count = 0;
  30. auto const failing_completion = Completion(Completion::Type::Throw, {}, {});
  31. // Note: SwitchStatement has its own codegen, but still calls into this function to handle the scoping of the switch body.
  32. auto is_switch_statement = is<SwitchStatement>(*this);
  33. if (is<BlockStatement>(*this) || is_switch_statement) {
  34. // Perform the steps of BlockDeclarationInstantiation.
  35. if (has_lexical_declarations()) {
  36. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  37. pushed_scope_count++;
  38. }
  39. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  40. auto is_constant_declaration = declaration.is_constant_declaration();
  41. // NOTE: Nothing in the callback throws an exception.
  42. MUST(declaration.for_each_bound_name([&](auto const& name) {
  43. auto index = generator.intern_identifier(name);
  44. // NOTE: BlockDeclarationInstantiation takes as input the new lexical environment that was created and checks if there is a binding for the current name only in this new scope.
  45. // For example: `{ let a = 1; { let a = 2; } }`. The second `a` will shadow the first `a` instead of re-initializing or setting it.
  46. if (is_constant_declaration || !generator.has_binding_in_current_scope(index)) {
  47. generator.register_binding(index);
  48. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration);
  49. }
  50. }));
  51. if (is<FunctionDeclaration>(declaration)) {
  52. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  53. auto const& name = function_declaration.name();
  54. auto index = generator.intern_identifier(name);
  55. generator.emit<Bytecode::Op::NewFunction>(function_declaration);
  56. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::InitializeOrSet);
  57. }
  58. return {};
  59. });
  60. if (is_switch_statement)
  61. return {};
  62. } else if (is<Program>(*this)) {
  63. // GlobalDeclarationInstantiation is handled by the C++ AO.
  64. } else {
  65. // FunctionDeclarationInstantiation is handled by the C++ AO.
  66. }
  67. if (maybe_error.has_value())
  68. return maybe_error.release_value();
  69. for (auto& child : children()) {
  70. TRY(child->generate_bytecode(generator));
  71. if (generator.is_current_block_terminated())
  72. break;
  73. }
  74. for (size_t i = 0; i < pushed_scope_count; ++i)
  75. generator.end_variable_scope();
  76. return {};
  77. }
  78. Bytecode::CodeGenerationErrorOr<void> EmptyStatement::generate_bytecode(Bytecode::Generator&) const
  79. {
  80. return {};
  81. }
  82. Bytecode::CodeGenerationErrorOr<void> ExpressionStatement::generate_bytecode(Bytecode::Generator& generator) const
  83. {
  84. return m_expression->generate_bytecode(generator);
  85. }
  86. Bytecode::CodeGenerationErrorOr<void> BinaryExpression::generate_bytecode(Bytecode::Generator& generator) const
  87. {
  88. TRY(m_lhs->generate_bytecode(generator));
  89. auto lhs_reg = generator.allocate_register();
  90. generator.emit<Bytecode::Op::Store>(lhs_reg);
  91. TRY(m_rhs->generate_bytecode(generator));
  92. switch (m_op) {
  93. case BinaryOp::Addition:
  94. generator.emit<Bytecode::Op::Add>(lhs_reg);
  95. break;
  96. case BinaryOp::Subtraction:
  97. generator.emit<Bytecode::Op::Sub>(lhs_reg);
  98. break;
  99. case BinaryOp::Multiplication:
  100. generator.emit<Bytecode::Op::Mul>(lhs_reg);
  101. break;
  102. case BinaryOp::Division:
  103. generator.emit<Bytecode::Op::Div>(lhs_reg);
  104. break;
  105. case BinaryOp::Modulo:
  106. generator.emit<Bytecode::Op::Mod>(lhs_reg);
  107. break;
  108. case BinaryOp::Exponentiation:
  109. generator.emit<Bytecode::Op::Exp>(lhs_reg);
  110. break;
  111. case BinaryOp::GreaterThan:
  112. generator.emit<Bytecode::Op::GreaterThan>(lhs_reg);
  113. break;
  114. case BinaryOp::GreaterThanEquals:
  115. generator.emit<Bytecode::Op::GreaterThanEquals>(lhs_reg);
  116. break;
  117. case BinaryOp::LessThan:
  118. generator.emit<Bytecode::Op::LessThan>(lhs_reg);
  119. break;
  120. case BinaryOp::LessThanEquals:
  121. generator.emit<Bytecode::Op::LessThanEquals>(lhs_reg);
  122. break;
  123. case BinaryOp::LooselyInequals:
  124. generator.emit<Bytecode::Op::LooselyInequals>(lhs_reg);
  125. break;
  126. case BinaryOp::LooselyEquals:
  127. generator.emit<Bytecode::Op::LooselyEquals>(lhs_reg);
  128. break;
  129. case BinaryOp::StrictlyInequals:
  130. generator.emit<Bytecode::Op::StrictlyInequals>(lhs_reg);
  131. break;
  132. case BinaryOp::StrictlyEquals:
  133. generator.emit<Bytecode::Op::StrictlyEquals>(lhs_reg);
  134. break;
  135. case BinaryOp::BitwiseAnd:
  136. generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
  137. break;
  138. case BinaryOp::BitwiseOr:
  139. generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
  140. break;
  141. case BinaryOp::BitwiseXor:
  142. generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
  143. break;
  144. case BinaryOp::LeftShift:
  145. generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
  146. break;
  147. case BinaryOp::RightShift:
  148. generator.emit<Bytecode::Op::RightShift>(lhs_reg);
  149. break;
  150. case BinaryOp::UnsignedRightShift:
  151. generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
  152. break;
  153. case BinaryOp::In:
  154. generator.emit<Bytecode::Op::In>(lhs_reg);
  155. break;
  156. case BinaryOp::InstanceOf:
  157. generator.emit<Bytecode::Op::InstanceOf>(lhs_reg);
  158. break;
  159. default:
  160. VERIFY_NOT_REACHED();
  161. }
  162. return {};
  163. }
  164. Bytecode::CodeGenerationErrorOr<void> LogicalExpression::generate_bytecode(Bytecode::Generator& generator) const
  165. {
  166. TRY(m_lhs->generate_bytecode(generator));
  167. // lhs
  168. // jump op (true) end (false) rhs
  169. // rhs
  170. // jump always (true) end
  171. // end
  172. auto& rhs_block = generator.make_block();
  173. auto& end_block = generator.make_block();
  174. switch (m_op) {
  175. case LogicalOp::And:
  176. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  177. Bytecode::Label { rhs_block },
  178. Bytecode::Label { end_block });
  179. break;
  180. case LogicalOp::Or:
  181. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  182. Bytecode::Label { end_block },
  183. Bytecode::Label { rhs_block });
  184. break;
  185. case LogicalOp::NullishCoalescing:
  186. generator.emit<Bytecode::Op::JumpNullish>().set_targets(
  187. Bytecode::Label { rhs_block },
  188. Bytecode::Label { end_block });
  189. break;
  190. default:
  191. VERIFY_NOT_REACHED();
  192. }
  193. generator.switch_to_basic_block(rhs_block);
  194. TRY(m_rhs->generate_bytecode(generator));
  195. generator.emit<Bytecode::Op::Jump>().set_targets(
  196. Bytecode::Label { end_block },
  197. {});
  198. generator.switch_to_basic_block(end_block);
  199. return {};
  200. }
  201. Bytecode::CodeGenerationErrorOr<void> UnaryExpression::generate_bytecode(Bytecode::Generator& generator) const
  202. {
  203. if (m_op == UnaryOp::Delete)
  204. return generator.emit_delete_reference(m_lhs);
  205. // Typeof needs some special handling for when the LHS is an Identifier. Namely, it shouldn't throw on unresolvable references, but instead return "undefined".
  206. if (m_op != UnaryOp::Typeof)
  207. TRY(m_lhs->generate_bytecode(generator));
  208. switch (m_op) {
  209. case UnaryOp::BitwiseNot:
  210. generator.emit<Bytecode::Op::BitwiseNot>();
  211. break;
  212. case UnaryOp::Not:
  213. generator.emit<Bytecode::Op::Not>();
  214. break;
  215. case UnaryOp::Plus:
  216. generator.emit<Bytecode::Op::UnaryPlus>();
  217. break;
  218. case UnaryOp::Minus:
  219. generator.emit<Bytecode::Op::UnaryMinus>();
  220. break;
  221. case UnaryOp::Typeof:
  222. if (is<Identifier>(*m_lhs)) {
  223. auto& identifier = static_cast<Identifier const&>(*m_lhs);
  224. generator.emit<Bytecode::Op::TypeofVariable>(generator.intern_identifier(identifier.string()));
  225. break;
  226. }
  227. TRY(m_lhs->generate_bytecode(generator));
  228. generator.emit<Bytecode::Op::Typeof>();
  229. break;
  230. case UnaryOp::Void:
  231. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  232. break;
  233. case UnaryOp::Delete: // Delete is implemented above.
  234. default:
  235. VERIFY_NOT_REACHED();
  236. }
  237. return {};
  238. }
  239. Bytecode::CodeGenerationErrorOr<void> NumericLiteral::generate_bytecode(Bytecode::Generator& generator) const
  240. {
  241. generator.emit<Bytecode::Op::LoadImmediate>(m_value);
  242. return {};
  243. }
  244. Bytecode::CodeGenerationErrorOr<void> BooleanLiteral::generate_bytecode(Bytecode::Generator& generator) const
  245. {
  246. generator.emit<Bytecode::Op::LoadImmediate>(Value(m_value));
  247. return {};
  248. }
  249. Bytecode::CodeGenerationErrorOr<void> NullLiteral::generate_bytecode(Bytecode::Generator& generator) const
  250. {
  251. generator.emit<Bytecode::Op::LoadImmediate>(js_null());
  252. return {};
  253. }
  254. Bytecode::CodeGenerationErrorOr<void> BigIntLiteral::generate_bytecode(Bytecode::Generator& generator) const
  255. {
  256. // 1. Return the NumericValue of NumericLiteral as defined in 12.8.3.
  257. auto integer = [&] {
  258. if (m_value[0] == '0' && m_value.length() >= 3)
  259. if (m_value[1] == 'x' || m_value[1] == 'X')
  260. return Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3));
  261. if (m_value[1] == 'o' || m_value[1] == 'O')
  262. return Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3));
  263. if (m_value[1] == 'b' || m_value[1] == 'B')
  264. return Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3));
  265. return Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1));
  266. }();
  267. generator.emit<Bytecode::Op::NewBigInt>(integer);
  268. return {};
  269. }
  270. Bytecode::CodeGenerationErrorOr<void> StringLiteral::generate_bytecode(Bytecode::Generator& generator) const
  271. {
  272. generator.emit<Bytecode::Op::NewString>(generator.intern_string(m_value));
  273. return {};
  274. }
  275. Bytecode::CodeGenerationErrorOr<void> RegExpLiteral::generate_bytecode(Bytecode::Generator& generator) const
  276. {
  277. auto source_index = generator.intern_string(m_pattern);
  278. auto flags_index = generator.intern_string(m_flags);
  279. generator.emit<Bytecode::Op::NewRegExp>(source_index, flags_index);
  280. return {};
  281. }
  282. Bytecode::CodeGenerationErrorOr<void> Identifier::generate_bytecode(Bytecode::Generator& generator) const
  283. {
  284. generator.emit<Bytecode::Op::GetVariable>(generator.intern_identifier(m_string));
  285. return {};
  286. }
  287. static Bytecode::CodeGenerationErrorOr<void> arguments_to_array_for_call(Bytecode::Generator& generator, ReadonlySpan<CallExpression::Argument> arguments)
  288. {
  289. if (arguments.is_empty()) {
  290. generator.emit<Bytecode::Op::NewArray>();
  291. return {};
  292. }
  293. auto first_spread = find_if(arguments.begin(), arguments.end(), [](auto el) { return el.is_spread; });
  294. Bytecode::Register args_start_reg { 0 };
  295. for (auto it = arguments.begin(); it != first_spread; ++it) {
  296. auto reg = generator.allocate_register();
  297. if (args_start_reg.index() == 0)
  298. args_start_reg = reg;
  299. }
  300. u32 i = 0;
  301. for (auto it = arguments.begin(); it != first_spread; ++it, ++i) {
  302. VERIFY(it->is_spread == false);
  303. Bytecode::Register reg { args_start_reg.index() + i };
  304. TRY(it->value->generate_bytecode(generator));
  305. generator.emit<Bytecode::Op::Store>(reg);
  306. }
  307. if (first_spread.index() != 0)
  308. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { args_start_reg, Bytecode::Register { args_start_reg.index() + static_cast<u32>(first_spread.index() - 1) } });
  309. else
  310. generator.emit<Bytecode::Op::NewArray>();
  311. if (first_spread != arguments.end()) {
  312. auto array_reg = generator.allocate_register();
  313. generator.emit<Bytecode::Op::Store>(array_reg);
  314. for (auto it = first_spread; it != arguments.end(); ++it) {
  315. TRY(it->value->generate_bytecode(generator));
  316. generator.emit<Bytecode::Op::Append>(array_reg, it->is_spread);
  317. }
  318. generator.emit<Bytecode::Op::Load>(array_reg);
  319. }
  320. return {};
  321. }
  322. Bytecode::CodeGenerationErrorOr<void> SuperCall::generate_bytecode(Bytecode::Generator& generator) const
  323. {
  324. if (m_is_synthetic == IsPartOfSyntheticConstructor::Yes) {
  325. // NOTE: This is the case where we have a fake constructor(...args) { super(...args); } which
  326. // shouldn't call @@iterator of %Array.prototype%.
  327. VERIFY(m_arguments.size() == 1);
  328. VERIFY(m_arguments[0].is_spread);
  329. auto const& argument = m_arguments[0];
  330. // This generates a single argument, which will be implicitly passed in accumulator
  331. MUST(argument.value->generate_bytecode(generator));
  332. } else {
  333. TRY(arguments_to_array_for_call(generator, m_arguments));
  334. }
  335. generator.emit<Bytecode::Op::SuperCall>(m_is_synthetic == IsPartOfSyntheticConstructor::Yes);
  336. return {};
  337. }
  338. static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode, Bytecode::Register const& value_reg);
  339. Bytecode::CodeGenerationErrorOr<void> AssignmentExpression::generate_bytecode(Bytecode::Generator& generator) const
  340. {
  341. if (m_op == AssignmentOp::Assignment) {
  342. // AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  343. return m_lhs.visit(
  344. // 1. If LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral, then
  345. [&](NonnullRefPtr<Expression const> const& lhs) -> Bytecode::CodeGenerationErrorOr<void> {
  346. // a. Let lref be the result of evaluating LeftHandSideExpression.
  347. // b. ReturnIfAbrupt(lref).
  348. Optional<Bytecode::Register> base_object_register;
  349. Optional<Bytecode::Register> computed_property_register;
  350. if (is<MemberExpression>(*lhs)) {
  351. auto& expression = static_cast<MemberExpression const&>(*lhs);
  352. TRY(expression.object().generate_bytecode(generator));
  353. base_object_register = generator.allocate_register();
  354. generator.emit<Bytecode::Op::Store>(*base_object_register);
  355. if (expression.is_computed()) {
  356. TRY(expression.property().generate_bytecode(generator));
  357. computed_property_register = generator.allocate_register();
  358. generator.emit<Bytecode::Op::Store>(*computed_property_register);
  359. // To be continued later with PutByValue.
  360. } else if (expression.property().is_identifier()) {
  361. // Do nothing, this will be handled by PutById later.
  362. } else {
  363. return Bytecode::CodeGenerationError {
  364. &expression,
  365. "Unimplemented non-computed member expression"sv
  366. };
  367. }
  368. } else if (is<Identifier>(*lhs)) {
  369. // NOTE: For Identifiers, we cannot perform GetVariable and then write into the reference it retrieves, only SetVariable can do this.
  370. // FIXME: However, this breaks spec as we are doing variable lookup after evaluating the RHS. This is observable in an object environment, where we visibly perform HasOwnProperty and Get(@@unscopables) on the binded object.
  371. } else {
  372. TRY(lhs->generate_bytecode(generator));
  373. }
  374. // FIXME: c. If IsAnonymousFunctionDefinition(AssignmentExpression) and IsIdentifierRef of LeftHandSideExpression are both true, then
  375. // i. Let rval be ? NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  376. // d. Else,
  377. // i. Let rref be the result of evaluating AssignmentExpression.
  378. // ii. Let rval be ? GetValue(rref).
  379. TRY(m_rhs->generate_bytecode(generator));
  380. // e. Perform ? PutValue(lref, rval).
  381. if (is<Identifier>(*lhs)) {
  382. auto& identifier = static_cast<Identifier const&>(*lhs);
  383. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier.string()));
  384. } else if (is<MemberExpression>(*lhs)) {
  385. auto& expression = static_cast<MemberExpression const&>(*lhs);
  386. if (expression.is_computed()) {
  387. generator.emit<Bytecode::Op::PutByValue>(*base_object_register, *computed_property_register);
  388. } else if (expression.property().is_identifier()) {
  389. auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(expression.property()).string());
  390. generator.emit<Bytecode::Op::PutById>(*base_object_register, identifier_table_ref);
  391. } else {
  392. return Bytecode::CodeGenerationError {
  393. &expression,
  394. "Unimplemented non-computed member expression"sv
  395. };
  396. }
  397. } else {
  398. return Bytecode::CodeGenerationError {
  399. lhs,
  400. "Unimplemented/invalid node used a reference"sv
  401. };
  402. }
  403. // f. Return rval.
  404. // NOTE: This is already in the accumulator.
  405. return {};
  406. },
  407. // 2. Let assignmentPattern be the AssignmentPattern that is covered by LeftHandSideExpression.
  408. [&](NonnullRefPtr<BindingPattern const> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  409. // 3. Let rref be the result of evaluating AssignmentExpression.
  410. // 4. Let rval be ? GetValue(rref).
  411. TRY(m_rhs->generate_bytecode(generator));
  412. auto value_register = generator.allocate_register();
  413. generator.emit<Bytecode::Op::Store>(value_register);
  414. // 5. Perform ? DestructuringAssignmentEvaluation of assignmentPattern with argument rval.
  415. TRY(generate_binding_pattern_bytecode(generator, pattern, Bytecode::Op::SetVariable::InitializationMode::Set, value_register));
  416. // 6. Return rval.
  417. generator.emit<Bytecode::Op::Load>(value_register);
  418. return {};
  419. });
  420. }
  421. VERIFY(m_lhs.has<NonnullRefPtr<Expression const>>());
  422. auto& lhs = m_lhs.get<NonnullRefPtr<Expression const>>();
  423. TRY(generator.emit_load_from_reference(lhs));
  424. Bytecode::BasicBlock* rhs_block_ptr { nullptr };
  425. Bytecode::BasicBlock* end_block_ptr { nullptr };
  426. // Logical assignments short circuit.
  427. if (m_op == AssignmentOp::AndAssignment) { // &&=
  428. rhs_block_ptr = &generator.make_block();
  429. end_block_ptr = &generator.make_block();
  430. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  431. Bytecode::Label { *rhs_block_ptr },
  432. Bytecode::Label { *end_block_ptr });
  433. } else if (m_op == AssignmentOp::OrAssignment) { // ||=
  434. rhs_block_ptr = &generator.make_block();
  435. end_block_ptr = &generator.make_block();
  436. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  437. Bytecode::Label { *end_block_ptr },
  438. Bytecode::Label { *rhs_block_ptr });
  439. } else if (m_op == AssignmentOp::NullishAssignment) { // ??=
  440. rhs_block_ptr = &generator.make_block();
  441. end_block_ptr = &generator.make_block();
  442. generator.emit<Bytecode::Op::JumpNullish>().set_targets(
  443. Bytecode::Label { *rhs_block_ptr },
  444. Bytecode::Label { *end_block_ptr });
  445. }
  446. if (rhs_block_ptr)
  447. generator.switch_to_basic_block(*rhs_block_ptr);
  448. // lhs_reg is a part of the rhs_block because the store isn't necessary
  449. // if the logical assignment condition fails.
  450. auto lhs_reg = generator.allocate_register();
  451. generator.emit<Bytecode::Op::Store>(lhs_reg);
  452. TRY(m_rhs->generate_bytecode(generator));
  453. switch (m_op) {
  454. case AssignmentOp::AdditionAssignment:
  455. generator.emit<Bytecode::Op::Add>(lhs_reg);
  456. break;
  457. case AssignmentOp::SubtractionAssignment:
  458. generator.emit<Bytecode::Op::Sub>(lhs_reg);
  459. break;
  460. case AssignmentOp::MultiplicationAssignment:
  461. generator.emit<Bytecode::Op::Mul>(lhs_reg);
  462. break;
  463. case AssignmentOp::DivisionAssignment:
  464. generator.emit<Bytecode::Op::Div>(lhs_reg);
  465. break;
  466. case AssignmentOp::ModuloAssignment:
  467. generator.emit<Bytecode::Op::Mod>(lhs_reg);
  468. break;
  469. case AssignmentOp::ExponentiationAssignment:
  470. generator.emit<Bytecode::Op::Exp>(lhs_reg);
  471. break;
  472. case AssignmentOp::BitwiseAndAssignment:
  473. generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
  474. break;
  475. case AssignmentOp::BitwiseOrAssignment:
  476. generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
  477. break;
  478. case AssignmentOp::BitwiseXorAssignment:
  479. generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
  480. break;
  481. case AssignmentOp::LeftShiftAssignment:
  482. generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
  483. break;
  484. case AssignmentOp::RightShiftAssignment:
  485. generator.emit<Bytecode::Op::RightShift>(lhs_reg);
  486. break;
  487. case AssignmentOp::UnsignedRightShiftAssignment:
  488. generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
  489. break;
  490. case AssignmentOp::AndAssignment:
  491. case AssignmentOp::OrAssignment:
  492. case AssignmentOp::NullishAssignment:
  493. break; // These are handled above.
  494. default:
  495. return Bytecode::CodeGenerationError {
  496. this,
  497. "Unimplemented operation"sv,
  498. };
  499. }
  500. TRY(generator.emit_store_to_reference(lhs));
  501. if (end_block_ptr) {
  502. generator.emit<Bytecode::Op::Jump>().set_targets(
  503. Bytecode::Label { *end_block_ptr },
  504. {});
  505. generator.switch_to_basic_block(*end_block_ptr);
  506. }
  507. return {};
  508. }
  509. // 14.13.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-labelled-statements-runtime-semantics-evaluation
  510. // LabelledStatement : LabelIdentifier : LabelledItem
  511. Bytecode::CodeGenerationErrorOr<void> LabelledStatement::generate_bytecode(Bytecode::Generator& generator) const
  512. {
  513. // Return ? LabelledEvaluation of this LabelledStatement with argument « ».
  514. return generate_labelled_evaluation(generator, {});
  515. }
  516. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  517. // LabelledStatement : LabelIdentifier : LabelledItem
  518. Bytecode::CodeGenerationErrorOr<void> LabelledStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  519. {
  520. // Convert the m_labelled_item NNRP to a reference early so we don't have to do it every single time we want to use it.
  521. auto const& labelled_item = *m_labelled_item;
  522. // 1. Let label be the StringValue of LabelIdentifier.
  523. // NOTE: Not necessary, this is m_label.
  524. // 2. Let newLabelSet be the list-concatenation of labelSet and « label ».
  525. // FIXME: Avoid copy here.
  526. auto new_label_set = label_set;
  527. new_label_set.append(m_label);
  528. // 3. Let stmtResult be LabelledEvaluation of LabelledItem with argument newLabelSet.
  529. // NOTE: stmtResult will be in the accumulator after running the generated bytecode.
  530. if (is<IterationStatement>(labelled_item)) {
  531. auto const& iteration_statement = static_cast<IterationStatement const&>(labelled_item);
  532. TRY(iteration_statement.generate_labelled_evaluation(generator, new_label_set));
  533. } else if (is<SwitchStatement>(labelled_item)) {
  534. auto const& switch_statement = static_cast<SwitchStatement const&>(labelled_item);
  535. TRY(switch_statement.generate_labelled_evaluation(generator, new_label_set));
  536. } else if (is<LabelledStatement>(labelled_item)) {
  537. auto const& labelled_statement = static_cast<LabelledStatement const&>(labelled_item);
  538. TRY(labelled_statement.generate_labelled_evaluation(generator, new_label_set));
  539. } else {
  540. auto& labelled_break_block = generator.make_block();
  541. // NOTE: We do not need a continuable scope as `continue;` is not allowed outside of iteration statements, throwing a SyntaxError in the parser.
  542. generator.begin_breakable_scope(Bytecode::Label { labelled_break_block }, new_label_set);
  543. TRY(labelled_item.generate_bytecode(generator));
  544. generator.end_breakable_scope();
  545. if (!generator.is_current_block_terminated()) {
  546. generator.emit<Bytecode::Op::Jump>().set_targets(
  547. Bytecode::Label { labelled_break_block },
  548. {});
  549. }
  550. generator.switch_to_basic_block(labelled_break_block);
  551. }
  552. // 4. If stmtResult.[[Type]] is break and SameValue(stmtResult.[[Target]], label) is true, then
  553. // a. Set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  554. // NOTE: These steps are performed by making labelled break jump straight to the appropriate break block, which preserves the statement result's value in the accumulator.
  555. // 5. Return Completion(stmtResult).
  556. // NOTE: This is in the accumulator.
  557. return {};
  558. }
  559. Bytecode::CodeGenerationErrorOr<void> IterationStatement::generate_labelled_evaluation(Bytecode::Generator&, Vector<DeprecatedFlyString> const&) const
  560. {
  561. return Bytecode::CodeGenerationError {
  562. this,
  563. "Missing generate_labelled_evaluation()"sv,
  564. };
  565. }
  566. Bytecode::CodeGenerationErrorOr<void> WhileStatement::generate_bytecode(Bytecode::Generator& generator) const
  567. {
  568. return generate_labelled_evaluation(generator, {});
  569. }
  570. Bytecode::CodeGenerationErrorOr<void> WhileStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  571. {
  572. // test
  573. // jump if_false (true) end (false) body
  574. // body
  575. // jump always (true) test
  576. // end
  577. auto& test_block = generator.make_block();
  578. auto& body_block = generator.make_block();
  579. auto& end_block = generator.make_block();
  580. // Init result register
  581. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  582. auto result_reg = generator.allocate_register();
  583. generator.emit<Bytecode::Op::Store>(result_reg);
  584. // jump to the test block
  585. generator.emit<Bytecode::Op::Jump>().set_targets(
  586. Bytecode::Label { test_block },
  587. {});
  588. generator.switch_to_basic_block(test_block);
  589. TRY(m_test->generate_bytecode(generator));
  590. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  591. Bytecode::Label { body_block },
  592. Bytecode::Label { end_block });
  593. generator.switch_to_basic_block(body_block);
  594. generator.begin_continuable_scope(Bytecode::Label { test_block }, label_set);
  595. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  596. TRY(m_body->generate_bytecode(generator));
  597. generator.end_breakable_scope();
  598. generator.end_continuable_scope();
  599. if (!generator.is_current_block_terminated()) {
  600. generator.emit<Bytecode::Op::Jump>().set_targets(
  601. Bytecode::Label { test_block },
  602. {});
  603. }
  604. generator.switch_to_basic_block(end_block);
  605. generator.emit<Bytecode::Op::Load>(result_reg);
  606. return {};
  607. }
  608. Bytecode::CodeGenerationErrorOr<void> DoWhileStatement::generate_bytecode(Bytecode::Generator& generator) const
  609. {
  610. return generate_labelled_evaluation(generator, {});
  611. }
  612. Bytecode::CodeGenerationErrorOr<void> DoWhileStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  613. {
  614. // jump always (true) body
  615. // test
  616. // jump if_false (true) end (false) body
  617. // body
  618. // jump always (true) test
  619. // end
  620. auto& test_block = generator.make_block();
  621. auto& body_block = generator.make_block();
  622. auto& end_block = generator.make_block();
  623. // Init result register
  624. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  625. auto result_reg = generator.allocate_register();
  626. generator.emit<Bytecode::Op::Store>(result_reg);
  627. // jump to the body block
  628. generator.emit<Bytecode::Op::Jump>().set_targets(
  629. Bytecode::Label { body_block },
  630. {});
  631. generator.switch_to_basic_block(test_block);
  632. TRY(m_test->generate_bytecode(generator));
  633. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  634. Bytecode::Label { body_block },
  635. Bytecode::Label { end_block });
  636. generator.switch_to_basic_block(body_block);
  637. generator.begin_continuable_scope(Bytecode::Label { test_block }, label_set);
  638. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  639. TRY(m_body->generate_bytecode(generator));
  640. generator.end_breakable_scope();
  641. generator.end_continuable_scope();
  642. if (!generator.is_current_block_terminated()) {
  643. generator.emit<Bytecode::Op::Jump>().set_targets(
  644. Bytecode::Label { test_block },
  645. {});
  646. }
  647. generator.switch_to_basic_block(end_block);
  648. generator.emit<Bytecode::Op::Load>(result_reg);
  649. return {};
  650. }
  651. Bytecode::CodeGenerationErrorOr<void> ForStatement::generate_bytecode(Bytecode::Generator& generator) const
  652. {
  653. return generate_labelled_evaluation(generator, {});
  654. }
  655. Bytecode::CodeGenerationErrorOr<void> ForStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  656. {
  657. // init
  658. // jump always (true) test
  659. // test
  660. // jump if_true (true) body (false) end
  661. // body
  662. // jump always (true) update
  663. // update
  664. // jump always (true) test
  665. // end
  666. // If 'test' is missing, fuse the 'test' and 'body' basic blocks
  667. // If 'update' is missing, fuse the 'body' and 'update' basic blocks
  668. Bytecode::BasicBlock* test_block_ptr { nullptr };
  669. Bytecode::BasicBlock* body_block_ptr { nullptr };
  670. Bytecode::BasicBlock* update_block_ptr { nullptr };
  671. auto& end_block = generator.make_block();
  672. bool has_lexical_environment = false;
  673. if (m_init) {
  674. if (m_init->is_variable_declaration()) {
  675. auto& variable_declaration = verify_cast<VariableDeclaration>(*m_init);
  676. if (variable_declaration.is_lexical_declaration()) {
  677. has_lexical_environment = true;
  678. // FIXME: Is Block correct?
  679. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  680. bool is_const = variable_declaration.is_constant_declaration();
  681. // NOTE: Nothing in the callback throws an exception.
  682. MUST(variable_declaration.for_each_bound_name([&](auto const& name) {
  683. auto index = generator.intern_identifier(name);
  684. generator.register_binding(index);
  685. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_const);
  686. }));
  687. }
  688. }
  689. TRY(m_init->generate_bytecode(generator));
  690. }
  691. body_block_ptr = &generator.make_block();
  692. if (m_test)
  693. test_block_ptr = &generator.make_block();
  694. else
  695. test_block_ptr = body_block_ptr;
  696. if (m_update)
  697. update_block_ptr = &generator.make_block();
  698. else
  699. update_block_ptr = body_block_ptr;
  700. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  701. auto result_reg = generator.allocate_register();
  702. generator.emit<Bytecode::Op::Store>(result_reg);
  703. generator.emit<Bytecode::Op::Jump>().set_targets(
  704. Bytecode::Label { *test_block_ptr },
  705. {});
  706. if (m_test) {
  707. generator.switch_to_basic_block(*test_block_ptr);
  708. TRY(m_test->generate_bytecode(generator));
  709. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  710. Bytecode::Label { *body_block_ptr },
  711. Bytecode::Label { end_block });
  712. }
  713. if (m_update) {
  714. generator.switch_to_basic_block(*update_block_ptr);
  715. TRY(m_update->generate_bytecode(generator));
  716. generator.emit<Bytecode::Op::Jump>().set_targets(
  717. Bytecode::Label { *test_block_ptr },
  718. {});
  719. }
  720. generator.switch_to_basic_block(*body_block_ptr);
  721. generator.begin_continuable_scope(Bytecode::Label { m_update ? *update_block_ptr : *test_block_ptr }, label_set);
  722. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  723. TRY(m_body->generate_bytecode(generator));
  724. generator.end_breakable_scope();
  725. generator.end_continuable_scope();
  726. if (!generator.is_current_block_terminated()) {
  727. if (m_update) {
  728. generator.emit<Bytecode::Op::Jump>().set_targets(
  729. Bytecode::Label { *update_block_ptr },
  730. {});
  731. } else {
  732. generator.emit<Bytecode::Op::Jump>().set_targets(
  733. Bytecode::Label { *test_block_ptr },
  734. {});
  735. }
  736. }
  737. generator.switch_to_basic_block(end_block);
  738. generator.emit<Bytecode::Op::Load>(result_reg);
  739. if (has_lexical_environment)
  740. generator.end_variable_scope();
  741. return {};
  742. }
  743. Bytecode::CodeGenerationErrorOr<void> ObjectExpression::generate_bytecode(Bytecode::Generator& generator) const
  744. {
  745. generator.emit<Bytecode::Op::NewObject>();
  746. if (m_properties.is_empty())
  747. return {};
  748. auto object_reg = generator.allocate_register();
  749. generator.emit<Bytecode::Op::Store>(object_reg);
  750. generator.push_home_object(object_reg);
  751. for (auto& property : m_properties) {
  752. Bytecode::Op::PropertyKind property_kind;
  753. switch (property->type()) {
  754. case ObjectProperty::Type::KeyValue:
  755. property_kind = Bytecode::Op::PropertyKind::KeyValue;
  756. break;
  757. case ObjectProperty::Type::Getter:
  758. property_kind = Bytecode::Op::PropertyKind::Getter;
  759. break;
  760. case ObjectProperty::Type::Setter:
  761. property_kind = Bytecode::Op::PropertyKind::Setter;
  762. break;
  763. case ObjectProperty::Type::Spread:
  764. property_kind = Bytecode::Op::PropertyKind::Spread;
  765. break;
  766. case ObjectProperty::Type::ProtoSetter:
  767. property_kind = Bytecode::Op::PropertyKind::ProtoSetter;
  768. break;
  769. }
  770. if (is<StringLiteral>(property->key())) {
  771. auto& string_literal = static_cast<StringLiteral const&>(property->key());
  772. Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(string_literal.value());
  773. if (property_kind != Bytecode::Op::PropertyKind::Spread)
  774. TRY(property->value().generate_bytecode(generator));
  775. generator.emit<Bytecode::Op::PutById>(object_reg, key_name, property_kind);
  776. } else {
  777. TRY(property->key().generate_bytecode(generator));
  778. auto property_reg = generator.allocate_register();
  779. generator.emit<Bytecode::Op::Store>(property_reg);
  780. if (property_kind != Bytecode::Op::PropertyKind::Spread)
  781. TRY(property->value().generate_bytecode(generator));
  782. generator.emit<Bytecode::Op::PutByValue>(object_reg, property_reg, property_kind);
  783. }
  784. }
  785. generator.emit<Bytecode::Op::Load>(object_reg);
  786. generator.pop_home_object();
  787. return {};
  788. }
  789. Bytecode::CodeGenerationErrorOr<void> ArrayExpression::generate_bytecode(Bytecode::Generator& generator) const
  790. {
  791. if (m_elements.is_empty()) {
  792. generator.emit<Bytecode::Op::NewArray>();
  793. return {};
  794. }
  795. auto first_spread = find_if(m_elements.begin(), m_elements.end(), [](auto el) { return el && is<SpreadExpression>(*el); });
  796. Bytecode::Register args_start_reg { 0 };
  797. for (auto it = m_elements.begin(); it != first_spread; ++it) {
  798. auto reg = generator.allocate_register();
  799. if (args_start_reg.index() == 0)
  800. args_start_reg = reg;
  801. }
  802. u32 i = 0;
  803. for (auto it = m_elements.begin(); it != first_spread; ++it, ++i) {
  804. Bytecode::Register reg { args_start_reg.index() + i };
  805. if (!*it)
  806. generator.emit<Bytecode::Op::LoadImmediate>(Value {});
  807. else {
  808. TRY((*it)->generate_bytecode(generator));
  809. }
  810. generator.emit<Bytecode::Op::Store>(reg);
  811. }
  812. if (first_spread.index() != 0)
  813. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { args_start_reg, Bytecode::Register { args_start_reg.index() + static_cast<u32>(first_spread.index() - 1) } });
  814. else
  815. generator.emit<Bytecode::Op::NewArray>();
  816. if (first_spread != m_elements.end()) {
  817. auto array_reg = generator.allocate_register();
  818. generator.emit<Bytecode::Op::Store>(array_reg);
  819. for (auto it = first_spread; it != m_elements.end(); ++it) {
  820. if (!*it) {
  821. generator.emit<Bytecode::Op::LoadImmediate>(Value {});
  822. generator.emit<Bytecode::Op::Append>(array_reg, false);
  823. } else {
  824. TRY((*it)->generate_bytecode(generator));
  825. generator.emit<Bytecode::Op::Append>(array_reg, *it && is<SpreadExpression>(**it));
  826. }
  827. }
  828. generator.emit<Bytecode::Op::Load>(array_reg);
  829. }
  830. return {};
  831. }
  832. Bytecode::CodeGenerationErrorOr<void> MemberExpression::generate_bytecode(Bytecode::Generator& generator) const
  833. {
  834. return generator.emit_load_from_reference(*this);
  835. }
  836. Bytecode::CodeGenerationErrorOr<void> FunctionDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  837. {
  838. if (m_is_hoisted) {
  839. auto index = generator.intern_identifier(name());
  840. generator.emit<Bytecode::Op::GetVariable>(index);
  841. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode::Var);
  842. }
  843. return {};
  844. }
  845. Bytecode::CodeGenerationErrorOr<void> FunctionExpression::generate_bytecode(Bytecode::Generator& generator) const
  846. {
  847. bool has_name = !name().is_empty();
  848. Optional<Bytecode::IdentifierTableIndex> name_identifier;
  849. if (has_name) {
  850. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical);
  851. name_identifier = generator.intern_identifier(name());
  852. generator.emit<Bytecode::Op::CreateVariable>(*name_identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  853. }
  854. generator.emit_new_function(*this);
  855. if (has_name) {
  856. generator.emit<Bytecode::Op::SetVariable>(*name_identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Lexical);
  857. generator.end_variable_scope();
  858. }
  859. return {};
  860. }
  861. static Bytecode::CodeGenerationErrorOr<void> generate_object_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg)
  862. {
  863. Vector<Bytecode::Register> excluded_property_names;
  864. auto has_rest = false;
  865. if (pattern.entries.size() > 0)
  866. has_rest = pattern.entries[pattern.entries.size() - 1].is_rest;
  867. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  868. if (is_rest) {
  869. VERIFY(name.has<NonnullRefPtr<Identifier const>>());
  870. VERIFY(alias.has<Empty>());
  871. VERIFY(!initializer);
  872. auto identifier = name.get<NonnullRefPtr<Identifier const>>()->string();
  873. auto interned_identifier = generator.intern_identifier(identifier);
  874. generator.emit_with_extra_register_slots<Bytecode::Op::CopyObjectExcludingProperties>(excluded_property_names.size(), value_reg, excluded_property_names);
  875. generator.emit<Bytecode::Op::SetVariable>(interned_identifier, initialization_mode);
  876. return {};
  877. }
  878. Bytecode::StringTableIndex name_index;
  879. if (name.has<NonnullRefPtr<Identifier const>>()) {
  880. auto identifier = name.get<NonnullRefPtr<Identifier const>>()->string();
  881. name_index = generator.intern_string(identifier);
  882. if (has_rest) {
  883. auto excluded_name_reg = generator.allocate_register();
  884. excluded_property_names.append(excluded_name_reg);
  885. generator.emit<Bytecode::Op::NewString>(name_index);
  886. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  887. }
  888. generator.emit<Bytecode::Op::Load>(value_reg);
  889. generator.emit<Bytecode::Op::GetById>(generator.intern_identifier(identifier));
  890. } else {
  891. auto expression = name.get<NonnullRefPtr<Expression const>>();
  892. TRY(expression->generate_bytecode(generator));
  893. if (has_rest) {
  894. auto excluded_name_reg = generator.allocate_register();
  895. excluded_property_names.append(excluded_name_reg);
  896. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  897. }
  898. generator.emit<Bytecode::Op::GetByValue>(value_reg);
  899. }
  900. if (initializer) {
  901. auto& if_undefined_block = generator.make_block();
  902. auto& if_not_undefined_block = generator.make_block();
  903. generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
  904. Bytecode::Label { if_undefined_block },
  905. Bytecode::Label { if_not_undefined_block });
  906. generator.switch_to_basic_block(if_undefined_block);
  907. TRY(initializer->generate_bytecode(generator));
  908. generator.emit<Bytecode::Op::Jump>().set_targets(
  909. Bytecode::Label { if_not_undefined_block },
  910. {});
  911. generator.switch_to_basic_block(if_not_undefined_block);
  912. }
  913. if (alias.has<NonnullRefPtr<BindingPattern const>>()) {
  914. auto& binding_pattern = *alias.get<NonnullRefPtr<BindingPattern const>>();
  915. auto nested_value_reg = generator.allocate_register();
  916. generator.emit<Bytecode::Op::Store>(nested_value_reg);
  917. TRY(generate_binding_pattern_bytecode(generator, binding_pattern, initialization_mode, nested_value_reg));
  918. } else if (alias.has<Empty>()) {
  919. if (name.has<NonnullRefPtr<Expression const>>()) {
  920. // This needs some sort of SetVariableByValue opcode, as it's a runtime binding
  921. return Bytecode::CodeGenerationError {
  922. name.get<NonnullRefPtr<Expression const>>().ptr(),
  923. "Unimplemented name/alias pair: Empty/Expression"sv,
  924. };
  925. }
  926. auto& identifier = name.get<NonnullRefPtr<Identifier const>>()->string();
  927. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  928. } else {
  929. auto& identifier = alias.get<NonnullRefPtr<Identifier const>>()->string();
  930. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  931. }
  932. }
  933. return {};
  934. }
  935. static Bytecode::CodeGenerationErrorOr<void> generate_array_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg)
  936. {
  937. /*
  938. * Consider the following destructuring assignment:
  939. *
  940. * let [a, b, c, d, e] = o;
  941. *
  942. * It would be fairly trivial to just loop through this iterator, getting the value
  943. * at each step and assigning them to the binding sequentially. However, this is not
  944. * correct: once an iterator is exhausted, it must not be called again. This complicates
  945. * the bytecode. In order to accomplish this, we do the following:
  946. *
  947. * - Reserve a special boolean register which holds 'true' if the iterator is exhausted,
  948. * and false otherwise
  949. * - When we are retrieving the value which should be bound, we first check this register.
  950. * If it is 'true', we load undefined into the accumulator. Otherwise, we grab the next
  951. * value from the iterator and store it into the accumulator.
  952. *
  953. * Note that the is_exhausted register does not need to be loaded with false because the
  954. * first IteratorNext bytecode is _not_ proceeded by an exhausted check, as it is
  955. * unnecessary.
  956. */
  957. auto is_iterator_exhausted_register = generator.allocate_register();
  958. auto iterator_reg = generator.allocate_register();
  959. generator.emit<Bytecode::Op::Load>(value_reg);
  960. generator.emit<Bytecode::Op::GetIterator>();
  961. generator.emit<Bytecode::Op::Store>(iterator_reg);
  962. bool first = true;
  963. auto temp_iterator_result_reg = generator.allocate_register();
  964. auto assign_accumulator_to_alias = [&](auto& alias) {
  965. return alias.visit(
  966. [&](Empty) -> Bytecode::CodeGenerationErrorOr<void> {
  967. // This element is an elision
  968. return {};
  969. },
  970. [&](NonnullRefPtr<Identifier const> const& identifier) -> Bytecode::CodeGenerationErrorOr<void> {
  971. auto interned_index = generator.intern_identifier(identifier->string());
  972. generator.emit<Bytecode::Op::SetVariable>(interned_index, initialization_mode);
  973. return {};
  974. },
  975. [&](NonnullRefPtr<BindingPattern const> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  976. // Store the accumulator value in a permanent register
  977. auto target_reg = generator.allocate_register();
  978. generator.emit<Bytecode::Op::Store>(target_reg);
  979. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, target_reg);
  980. },
  981. [&](NonnullRefPtr<MemberExpression const> const& expr) -> Bytecode::CodeGenerationErrorOr<void> {
  982. return generator.emit_store_to_reference(*expr);
  983. });
  984. };
  985. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  986. VERIFY(name.has<Empty>());
  987. if (is_rest) {
  988. VERIFY(!initializer);
  989. if (first) {
  990. // The iterator has not been called, and is thus known to be not exhausted
  991. generator.emit<Bytecode::Op::Load>(iterator_reg);
  992. generator.emit<Bytecode::Op::IteratorToArray>();
  993. } else {
  994. auto& if_exhausted_block = generator.make_block();
  995. auto& if_not_exhausted_block = generator.make_block();
  996. auto& continuation_block = generator.make_block();
  997. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  998. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  999. Bytecode::Label { if_exhausted_block },
  1000. Bytecode::Label { if_not_exhausted_block });
  1001. generator.switch_to_basic_block(if_exhausted_block);
  1002. generator.emit<Bytecode::Op::NewArray>();
  1003. generator.emit<Bytecode::Op::Jump>().set_targets(
  1004. Bytecode::Label { continuation_block },
  1005. {});
  1006. generator.switch_to_basic_block(if_not_exhausted_block);
  1007. generator.emit<Bytecode::Op::Load>(iterator_reg);
  1008. generator.emit<Bytecode::Op::IteratorToArray>();
  1009. generator.emit<Bytecode::Op::Jump>().set_targets(
  1010. Bytecode::Label { continuation_block },
  1011. {});
  1012. generator.switch_to_basic_block(continuation_block);
  1013. }
  1014. return assign_accumulator_to_alias(alias);
  1015. }
  1016. // In the first iteration of the loop, a few things are true which can save
  1017. // us some bytecode:
  1018. // - the iterator result is still in the accumulator, so we can avoid a load
  1019. // - the iterator is not yet exhausted, which can save us a jump and some
  1020. // creation
  1021. auto& iterator_is_exhausted_block = generator.make_block();
  1022. if (!first) {
  1023. auto& iterator_is_not_exhausted_block = generator.make_block();
  1024. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  1025. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1026. Bytecode::Label { iterator_is_exhausted_block },
  1027. Bytecode::Label { iterator_is_not_exhausted_block });
  1028. generator.switch_to_basic_block(iterator_is_not_exhausted_block);
  1029. generator.emit<Bytecode::Op::Load>(iterator_reg);
  1030. }
  1031. generator.emit<Bytecode::Op::IteratorNext>();
  1032. generator.emit<Bytecode::Op::Store>(temp_iterator_result_reg);
  1033. generator.emit<Bytecode::Op::IteratorResultDone>();
  1034. generator.emit<Bytecode::Op::Store>(is_iterator_exhausted_register);
  1035. // We still have to check for exhaustion here. If the iterator is exhausted,
  1036. // we need to bail before trying to get the value
  1037. auto& no_bail_block = generator.make_block();
  1038. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1039. Bytecode::Label { iterator_is_exhausted_block },
  1040. Bytecode::Label { no_bail_block });
  1041. generator.switch_to_basic_block(no_bail_block);
  1042. // Get the next value in the iterator
  1043. generator.emit<Bytecode::Op::Load>(temp_iterator_result_reg);
  1044. generator.emit<Bytecode::Op::IteratorResultValue>();
  1045. auto& create_binding_block = generator.make_block();
  1046. generator.emit<Bytecode::Op::Jump>().set_targets(
  1047. Bytecode::Label { create_binding_block },
  1048. {});
  1049. // The iterator is exhausted, so we just load undefined and continue binding
  1050. generator.switch_to_basic_block(iterator_is_exhausted_block);
  1051. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1052. generator.emit<Bytecode::Op::Jump>().set_targets(
  1053. Bytecode::Label { create_binding_block },
  1054. {});
  1055. // Create the actual binding. The value which this entry must bind is now in the
  1056. // accumulator. We can proceed, processing the alias as a nested destructuring
  1057. // pattern if necessary.
  1058. generator.switch_to_basic_block(create_binding_block);
  1059. if (initializer) {
  1060. auto& value_is_undefined_block = generator.make_block();
  1061. auto& value_is_not_undefined_block = generator.make_block();
  1062. generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
  1063. Bytecode::Label { value_is_undefined_block },
  1064. Bytecode::Label { value_is_not_undefined_block });
  1065. generator.switch_to_basic_block(value_is_undefined_block);
  1066. TRY(initializer->generate_bytecode(generator));
  1067. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { value_is_not_undefined_block });
  1068. generator.switch_to_basic_block(value_is_not_undefined_block);
  1069. }
  1070. TRY(assign_accumulator_to_alias(alias));
  1071. first = false;
  1072. }
  1073. return {};
  1074. }
  1075. static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg)
  1076. {
  1077. if (pattern.kind == BindingPattern::Kind::Object)
  1078. return generate_object_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  1079. return generate_array_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  1080. }
  1081. static Bytecode::CodeGenerationErrorOr<void> assign_accumulator_to_variable_declarator(Bytecode::Generator& generator, VariableDeclarator const& declarator, VariableDeclaration const& declaration)
  1082. {
  1083. auto initialization_mode = declaration.is_lexical_declaration() ? Bytecode::Op::SetVariable::InitializationMode::Initialize : Bytecode::Op::SetVariable::InitializationMode::Set;
  1084. return declarator.target().visit(
  1085. [&](NonnullRefPtr<Identifier const> const& id) -> Bytecode::CodeGenerationErrorOr<void> {
  1086. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(id->string()), initialization_mode);
  1087. return {};
  1088. },
  1089. [&](NonnullRefPtr<BindingPattern const> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  1090. auto value_register = generator.allocate_register();
  1091. generator.emit<Bytecode::Op::Store>(value_register);
  1092. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, value_register);
  1093. });
  1094. }
  1095. Bytecode::CodeGenerationErrorOr<void> VariableDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1096. {
  1097. for (auto& declarator : m_declarations) {
  1098. if (declarator->init())
  1099. TRY(declarator->init()->generate_bytecode(generator));
  1100. else
  1101. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1102. TRY(assign_accumulator_to_variable_declarator(generator, declarator, *this));
  1103. }
  1104. return {};
  1105. }
  1106. Bytecode::CodeGenerationErrorOr<void> CallExpression::generate_bytecode(Bytecode::Generator& generator) const
  1107. {
  1108. auto callee_reg = generator.allocate_register();
  1109. auto this_reg = generator.allocate_register();
  1110. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1111. generator.emit<Bytecode::Op::Store>(this_reg);
  1112. if (is<NewExpression>(this)) {
  1113. TRY(m_callee->generate_bytecode(generator));
  1114. generator.emit<Bytecode::Op::Store>(callee_reg);
  1115. } else if (is<MemberExpression>(*m_callee)) {
  1116. auto& member_expression = static_cast<MemberExpression const&>(*m_callee);
  1117. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  1118. if (is<SuperExpression>(member_expression.object())) {
  1119. // 1. Let env be GetThisEnvironment().
  1120. // 2. Let actualThis be ? env.GetThisBinding().
  1121. generator.emit<Bytecode::Op::ResolveThisBinding>();
  1122. generator.emit<Bytecode::Op::Store>(this_reg);
  1123. Optional<Bytecode::Register> computed_property_value_register;
  1124. if (member_expression.is_computed()) {
  1125. // SuperProperty : super [ Expression ]
  1126. // 3. Let propertyNameReference be ? Evaluation of Expression.
  1127. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  1128. TRY(member_expression.property().generate_bytecode(generator));
  1129. computed_property_value_register = generator.allocate_register();
  1130. generator.emit<Bytecode::Op::Store>(*computed_property_value_register);
  1131. }
  1132. // 5/7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  1133. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  1134. // 1. Let env be GetThisEnvironment().
  1135. // 2. Assert: env.HasSuperBinding() is true.
  1136. // 3. Let baseValue be ? env.GetSuperBase().
  1137. generator.emit<Bytecode::Op::ResolveSuperBase>();
  1138. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  1139. if (computed_property_value_register.has_value()) {
  1140. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  1141. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  1142. generator.emit<Bytecode::Op::GetByValue>(*computed_property_value_register);
  1143. } else {
  1144. // 3. Let propertyKey be StringValue of IdentifierName.
  1145. auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string());
  1146. generator.emit<Bytecode::Op::GetById>(identifier_table_ref);
  1147. }
  1148. } else {
  1149. TRY(member_expression.object().generate_bytecode(generator));
  1150. generator.emit<Bytecode::Op::Store>(this_reg);
  1151. if (member_expression.is_computed()) {
  1152. TRY(member_expression.property().generate_bytecode(generator));
  1153. generator.emit<Bytecode::Op::GetByValue>(this_reg);
  1154. } else {
  1155. auto identifier_table_ref = [&] {
  1156. if (is<PrivateIdentifier>(member_expression.property()))
  1157. return generator.intern_identifier(verify_cast<PrivateIdentifier>(member_expression.property()).string());
  1158. return generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string());
  1159. }();
  1160. generator.emit<Bytecode::Op::GetById>(identifier_table_ref);
  1161. }
  1162. }
  1163. generator.emit<Bytecode::Op::Store>(callee_reg);
  1164. } else {
  1165. // FIXME: this = global object in sloppy mode.
  1166. TRY(m_callee->generate_bytecode(generator));
  1167. generator.emit<Bytecode::Op::Store>(callee_reg);
  1168. }
  1169. TRY(arguments_to_array_for_call(generator, arguments()));
  1170. Bytecode::Op::Call::CallType call_type;
  1171. if (is<NewExpression>(*this)) {
  1172. call_type = Bytecode::Op::Call::CallType::Construct;
  1173. } else if (m_callee->is_identifier() && static_cast<Identifier const&>(*m_callee).string() == "eval"sv) {
  1174. call_type = Bytecode::Op::Call::CallType::DirectEval;
  1175. } else {
  1176. call_type = Bytecode::Op::Call::CallType::Call;
  1177. }
  1178. Optional<Bytecode::StringTableIndex> expression_string_index;
  1179. if (auto expression_string = this->expression_string(); expression_string.has_value())
  1180. expression_string_index = generator.intern_string(expression_string.release_value());
  1181. generator.emit<Bytecode::Op::Call>(call_type, callee_reg, this_reg, expression_string_index);
  1182. return {};
  1183. }
  1184. Bytecode::CodeGenerationErrorOr<void> ReturnStatement::generate_bytecode(Bytecode::Generator& generator) const
  1185. {
  1186. if (m_argument)
  1187. TRY(m_argument->generate_bytecode(generator));
  1188. else
  1189. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1190. if (generator.is_in_generator_or_async_function()) {
  1191. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1192. generator.emit<Bytecode::Op::Yield>(nullptr);
  1193. } else {
  1194. generator.perform_needed_unwinds<Bytecode::Op::Return>();
  1195. generator.emit<Bytecode::Op::Return>();
  1196. }
  1197. return {};
  1198. }
  1199. Bytecode::CodeGenerationErrorOr<void> YieldExpression::generate_bytecode(Bytecode::Generator& generator) const
  1200. {
  1201. VERIFY(generator.is_in_generator_function());
  1202. auto received_completion_register = generator.allocate_register();
  1203. auto received_completion_type_register = generator.allocate_register();
  1204. auto received_completion_value_register = generator.allocate_register();
  1205. auto type_identifier = generator.intern_identifier("type");
  1206. auto value_identifier = generator.intern_identifier("value");
  1207. auto get_received_completion_type_and_value = [&]() {
  1208. // The accumulator is set to an object, for example: { "type": 1 (normal), value: 1337 }
  1209. generator.emit<Bytecode::Op::Store>(received_completion_register);
  1210. generator.emit<Bytecode::Op::GetById>(type_identifier);
  1211. generator.emit<Bytecode::Op::Store>(received_completion_type_register);
  1212. generator.emit<Bytecode::Op::Load>(received_completion_register);
  1213. generator.emit<Bytecode::Op::GetById>(value_identifier);
  1214. generator.emit<Bytecode::Op::Store>(received_completion_value_register);
  1215. };
  1216. if (m_is_yield_from) {
  1217. // 15.5.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-generator-function-definitions-runtime-semantics-evaluation
  1218. // FIXME: 1. Let generatorKind be GetGeneratorKind().
  1219. // 2. Let exprRef be ? Evaluation of AssignmentExpression.
  1220. // 3. Let value be ? GetValue(exprRef).
  1221. VERIFY(m_argument);
  1222. TRY(m_argument->generate_bytecode(generator));
  1223. // 4. Let iteratorRecord be ? GetIterator(value, generatorKind).
  1224. // FIXME: Consider generatorKind.
  1225. auto iterator_record_register = generator.allocate_register();
  1226. generator.emit<Bytecode::Op::GetIterator>();
  1227. generator.emit<Bytecode::Op::Store>(iterator_record_register);
  1228. // 5. Let iterator be iteratorRecord.[[Iterator]].
  1229. auto iterator_register = generator.allocate_register();
  1230. auto iterator_identifier = generator.intern_identifier("iterator");
  1231. generator.emit<Bytecode::Op::GetById>(iterator_identifier);
  1232. generator.emit<Bytecode::Op::Store>(iterator_register);
  1233. // Cache iteratorRecord.[[NextMethod]] for use in step 7.a.i.
  1234. auto next_method_register = generator.allocate_register();
  1235. auto next_method_identifier = generator.intern_identifier("next");
  1236. generator.emit<Bytecode::Op::Load>(iterator_record_register);
  1237. generator.emit<Bytecode::Op::GetById>(next_method_identifier);
  1238. generator.emit<Bytecode::Op::Store>(next_method_register);
  1239. // 6. Let received be NormalCompletion(undefined).
  1240. // See get_received_completion_type_and_value above.
  1241. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Normal)));
  1242. generator.emit<Bytecode::Op::Store>(received_completion_type_register);
  1243. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1244. generator.emit<Bytecode::Op::Store>(received_completion_value_register);
  1245. // 7. Repeat,
  1246. auto& loop_block = generator.make_block();
  1247. auto& continuation_block = generator.make_block();
  1248. auto& loop_end_block = generator.make_block();
  1249. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_block });
  1250. generator.switch_to_basic_block(loop_block);
  1251. // a. If received.[[Type]] is normal, then
  1252. auto& type_is_normal_block = generator.make_block();
  1253. auto& is_type_throw_block = generator.make_block();
  1254. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Normal)));
  1255. generator.emit<Bytecode::Op::StrictlyEquals>(received_completion_type_register);
  1256. generator.emit<Bytecode::Op::JumpConditional>(
  1257. Bytecode::Label { type_is_normal_block },
  1258. Bytecode::Label { is_type_throw_block });
  1259. generator.switch_to_basic_block(type_is_normal_block);
  1260. // i. Let innerResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « received.[[Value]] »).
  1261. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2, AK::Array { received_completion_value_register, received_completion_value_register });
  1262. generator.emit<Bytecode::Op::Call>(Bytecode::Op::Call::CallType::Call, next_method_register, iterator_register);
  1263. // FIXME: ii. If generatorKind is async, set innerResult to ? Await(innerResult).
  1264. // iii. If innerResult is not an Object, throw a TypeError exception.
  1265. generator.emit<Bytecode::Op::ThrowIfNotObject>();
  1266. auto inner_result_register = generator.allocate_register();
  1267. generator.emit<Bytecode::Op::Store>(inner_result_register);
  1268. // iv. Let done be ? IteratorComplete(innerResult).
  1269. generator.emit<Bytecode::Op::IteratorResultDone>();
  1270. // v. If done is true, then
  1271. auto& type_is_normal_done_block = generator.make_block();
  1272. auto& type_is_normal_not_done_block = generator.make_block();
  1273. generator.emit<Bytecode::Op::JumpConditional>(
  1274. Bytecode::Label { type_is_normal_done_block },
  1275. Bytecode::Label { type_is_normal_not_done_block });
  1276. generator.switch_to_basic_block(type_is_normal_done_block);
  1277. // 1. Return ? IteratorValue(innerResult).
  1278. generator.emit<Bytecode::Op::Load>(inner_result_register);
  1279. generator.emit<Bytecode::Op::IteratorResultValue>();
  1280. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_end_block });
  1281. generator.switch_to_basic_block(type_is_normal_not_done_block);
  1282. // FIXME: vi. If generatorKind is async, set received to Completion(AsyncGeneratorYield(? IteratorValue(innerResult))).
  1283. // vii. Else, set received to Completion(GeneratorYield(innerResult)).
  1284. // FIXME: Else,
  1285. generator.emit<Bytecode::Op::Load>(inner_result_register);
  1286. // FIXME: Yield currently only accepts a Value, not an object conforming to the IteratorResult interface, so we have to do an observable lookup of `value` here.
  1287. generator.emit<Bytecode::Op::IteratorResultValue>();
  1288. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1289. // b. Else if received.[[Type]] is throw, then
  1290. generator.switch_to_basic_block(is_type_throw_block);
  1291. auto& type_is_throw_block = generator.make_block();
  1292. auto& type_is_return_block = generator.make_block();
  1293. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Throw)));
  1294. generator.emit<Bytecode::Op::StrictlyEquals>(received_completion_type_register);
  1295. generator.emit<Bytecode::Op::JumpConditional>(
  1296. Bytecode::Label { type_is_throw_block },
  1297. Bytecode::Label { type_is_return_block });
  1298. generator.switch_to_basic_block(type_is_throw_block);
  1299. // i. Let throw be ? GetMethod(iterator, "throw").
  1300. auto throw_method_register = generator.allocate_register();
  1301. auto throw_identifier = generator.intern_identifier("throw");
  1302. generator.emit<Bytecode::Op::Load>(iterator_register);
  1303. generator.emit<Bytecode::Op::GetMethod>(throw_identifier);
  1304. generator.emit<Bytecode::Op::Store>(throw_method_register);
  1305. // ii. If throw is not undefined, then
  1306. auto& throw_method_is_defined_block = generator.make_block();
  1307. auto& throw_method_is_undefined_block = generator.make_block();
  1308. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1309. generator.emit<Bytecode::Op::StrictlyInequals>(throw_method_register);
  1310. generator.emit<Bytecode::Op::JumpConditional>(
  1311. Bytecode::Label { throw_method_is_defined_block },
  1312. Bytecode::Label { throw_method_is_undefined_block });
  1313. generator.switch_to_basic_block(throw_method_is_defined_block);
  1314. // 1. Let innerResult be ? Call(throw, iterator, « received.[[Value]] »).
  1315. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2, AK::Array { received_completion_value_register, received_completion_value_register });
  1316. generator.emit<Bytecode::Op::Call>(Bytecode::Op::Call::CallType::Call, throw_method_register, iterator_register);
  1317. // FIXME: 2. If generatorKind is async, set innerResult to ? Await(innerResult).
  1318. // 3. NOTE: Exceptions from the inner iterator throw method are propagated. Normal completions from an inner throw method are processed similarly to an inner next.
  1319. // 4. If innerResult is not an Object, throw a TypeError exception.
  1320. generator.emit<Bytecode::Op::ThrowIfNotObject>();
  1321. generator.emit<Bytecode::Op::Store>(inner_result_register);
  1322. // 5. Let done be ? IteratorComplete(innerResult).
  1323. generator.emit<Bytecode::Op::IteratorResultDone>();
  1324. // 6. If done is true, then
  1325. auto& type_is_throw_done_block = generator.make_block();
  1326. auto& type_is_throw_not_done_block = generator.make_block();
  1327. generator.emit<Bytecode::Op::JumpConditional>(
  1328. Bytecode::Label { type_is_throw_done_block },
  1329. Bytecode::Label { type_is_throw_not_done_block });
  1330. generator.switch_to_basic_block(type_is_throw_done_block);
  1331. // a. Return ? IteratorValue(innerResult).
  1332. generator.emit<Bytecode::Op::Load>(inner_result_register);
  1333. generator.emit<Bytecode::Op::IteratorResultValue>();
  1334. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_end_block });
  1335. generator.switch_to_basic_block(type_is_throw_not_done_block);
  1336. // FIXME: 7. If generatorKind is async, set received to Completion(AsyncGeneratorYield(? IteratorValue(innerResult))).
  1337. // 8. Else, set received to Completion(GeneratorYield(innerResult)).
  1338. // FIXME: Else,
  1339. generator.emit<Bytecode::Op::Load>(inner_result_register);
  1340. // FIXME: Yield currently only accepts a Value, not an object conforming to the IteratorResult interface, so we have to do an observable lookup of `value` here.
  1341. generator.emit<Bytecode::Op::IteratorResultValue>();
  1342. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1343. generator.switch_to_basic_block(throw_method_is_undefined_block);
  1344. // 1. NOTE: If iterator does not have a throw method, this throw is going to terminate the yield* loop. But first we need to give iterator a chance to clean up.
  1345. // 2. Let closeCompletion be Completion Record { [[Type]]: normal, [[Value]]: empty, [[Target]]: empty }.
  1346. // FIXME: 3. If generatorKind is async, perform ? AsyncIteratorClose(iteratorRecord, closeCompletion).
  1347. // 4. Else, perform ? IteratorClose(iteratorRecord, closeCompletion).
  1348. // FIXME: Else,
  1349. generator.emit<Bytecode::Op::Load>(iterator_record_register);
  1350. generator.emit<Bytecode::Op::IteratorClose>(Completion::Type::Normal, Optional<Value> {});
  1351. // 5. NOTE: The next step throws a TypeError to indicate that there was a yield* protocol violation: iterator does not have a throw method.
  1352. // 6. Throw a TypeError exception.
  1353. generator.emit<Bytecode::Op::NewTypeError>(generator.intern_string(ErrorType::YieldFromIteratorMissingThrowMethod.message()));
  1354. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1355. generator.emit<Bytecode::Op::Throw>();
  1356. // c. Else,
  1357. // i. Assert: received.[[Type]] is return.
  1358. generator.switch_to_basic_block(type_is_return_block);
  1359. // ii. Let return be ? GetMethod(iterator, "return").
  1360. auto return_method_register = generator.allocate_register();
  1361. auto return_identifier = generator.intern_identifier("return");
  1362. generator.emit<Bytecode::Op::Load>(iterator_register);
  1363. generator.emit<Bytecode::Op::GetMethod>(return_identifier);
  1364. generator.emit<Bytecode::Op::Store>(return_method_register);
  1365. // iii. If return is undefined, then
  1366. auto& return_is_undefined_block = generator.make_block();
  1367. auto& return_is_defined_block = generator.make_block();
  1368. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1369. generator.emit<Bytecode::Op::StrictlyEquals>(return_method_register);
  1370. generator.emit<Bytecode::Op::JumpConditional>(
  1371. Bytecode::Label { return_is_undefined_block },
  1372. Bytecode::Label { return_is_defined_block });
  1373. generator.switch_to_basic_block(return_is_undefined_block);
  1374. // FIXME: 1. If generatorKind is async, set received.[[Value]] to ? Await(received.[[Value]]).
  1375. // 2. Return ? received.
  1376. // NOTE: This will always be a return completion.
  1377. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1378. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1379. generator.emit<Bytecode::Op::Yield>(nullptr);
  1380. generator.switch_to_basic_block(return_is_defined_block);
  1381. // iv. Let innerReturnResult be ? Call(return, iterator, « received.[[Value]] »).
  1382. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2, AK::Array { received_completion_value_register, received_completion_value_register });
  1383. generator.emit<Bytecode::Op::Call>(Bytecode::Op::Call::CallType::Call, return_method_register, iterator_register);
  1384. // FIXME: v. If generatorKind is async, set innerReturnResult to ? Await(innerReturnResult).
  1385. // vi. If innerReturnResult is not an Object, throw a TypeError exception.
  1386. generator.emit<Bytecode::Op::ThrowIfNotObject>();
  1387. auto inner_return_result_register = generator.allocate_register();
  1388. generator.emit<Bytecode::Op::Store>(inner_return_result_register);
  1389. // vii. Let done be ? IteratorComplete(innerReturnResult).
  1390. generator.emit<Bytecode::Op::IteratorResultDone>();
  1391. // viii. If done is true, then
  1392. auto& type_is_return_done_block = generator.make_block();
  1393. auto& type_is_return_not_done_block = generator.make_block();
  1394. generator.emit<Bytecode::Op::JumpConditional>(
  1395. Bytecode::Label { type_is_return_done_block },
  1396. Bytecode::Label { type_is_return_not_done_block });
  1397. generator.switch_to_basic_block(type_is_return_done_block);
  1398. // 1. Let value be ? IteratorValue(innerReturnResult).
  1399. generator.emit<Bytecode::Op::Load>(inner_result_register);
  1400. generator.emit<Bytecode::Op::IteratorResultValue>();
  1401. // 2. Return Completion Record { [[Type]]: return, [[Value]]: value, [[Target]]: empty }.
  1402. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1403. generator.emit<Bytecode::Op::Yield>(nullptr);
  1404. generator.switch_to_basic_block(type_is_return_not_done_block);
  1405. // FIXME: ix. If generatorKind is async, set received to Completion(AsyncGeneratorYield(? IteratorValue(innerReturnResult))).
  1406. // x. Else, set received to Completion(GeneratorYield(innerReturnResult)).
  1407. // FIXME: Else,
  1408. generator.emit<Bytecode::Op::Load>(inner_return_result_register);
  1409. // FIXME: Yield currently only accepts a Value, not an object conforming to the IteratorResult interface, so we have to do an observable lookup of `value` here.
  1410. generator.emit<Bytecode::Op::IteratorResultValue>();
  1411. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1412. generator.switch_to_basic_block(continuation_block);
  1413. get_received_completion_type_and_value();
  1414. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_block });
  1415. generator.switch_to_basic_block(loop_end_block);
  1416. return {};
  1417. }
  1418. if (m_argument)
  1419. TRY(m_argument->generate_bytecode(generator));
  1420. else
  1421. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1422. auto& continuation_block = generator.make_block();
  1423. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1424. generator.switch_to_basic_block(continuation_block);
  1425. get_received_completion_type_and_value();
  1426. auto& normal_completion_continuation_block = generator.make_block();
  1427. auto& throw_completion_continuation_block = generator.make_block();
  1428. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Normal)));
  1429. generator.emit<Bytecode::Op::StrictlyEquals>(received_completion_type_register);
  1430. generator.emit<Bytecode::Op::JumpConditional>(
  1431. Bytecode::Label { normal_completion_continuation_block },
  1432. Bytecode::Label { throw_completion_continuation_block });
  1433. auto& throw_value_block = generator.make_block();
  1434. auto& return_value_block = generator.make_block();
  1435. generator.switch_to_basic_block(throw_completion_continuation_block);
  1436. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Throw)));
  1437. generator.emit<Bytecode::Op::StrictlyEquals>(received_completion_type_register);
  1438. // If type is not equal to "throw" or "normal", assume it's "return".
  1439. generator.emit<Bytecode::Op::JumpConditional>(
  1440. Bytecode::Label { throw_value_block },
  1441. Bytecode::Label { return_value_block });
  1442. generator.switch_to_basic_block(throw_value_block);
  1443. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1444. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1445. generator.emit<Bytecode::Op::Throw>();
  1446. generator.switch_to_basic_block(return_value_block);
  1447. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1448. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1449. generator.emit<Bytecode::Op::Yield>(nullptr);
  1450. generator.switch_to_basic_block(normal_completion_continuation_block);
  1451. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1452. return {};
  1453. }
  1454. Bytecode::CodeGenerationErrorOr<void> IfStatement::generate_bytecode(Bytecode::Generator& generator) const
  1455. {
  1456. // test
  1457. // jump if_true (true) true (false) false
  1458. // true
  1459. // jump always (true) end
  1460. // false
  1461. // jump always (true) end
  1462. // end
  1463. auto& true_block = generator.make_block();
  1464. auto& false_block = generator.make_block();
  1465. TRY(m_predicate->generate_bytecode(generator));
  1466. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1467. Bytecode::Label { true_block },
  1468. Bytecode::Label { false_block });
  1469. Bytecode::Op::Jump* true_block_jump { nullptr };
  1470. generator.switch_to_basic_block(true_block);
  1471. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1472. TRY(m_consequent->generate_bytecode(generator));
  1473. if (!generator.is_current_block_terminated())
  1474. true_block_jump = &generator.emit<Bytecode::Op::Jump>();
  1475. generator.switch_to_basic_block(false_block);
  1476. auto& end_block = generator.make_block();
  1477. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1478. if (m_alternate)
  1479. TRY(m_alternate->generate_bytecode(generator));
  1480. if (!generator.is_current_block_terminated())
  1481. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1482. if (true_block_jump)
  1483. true_block_jump->set_targets(Bytecode::Label { end_block }, {});
  1484. generator.switch_to_basic_block(end_block);
  1485. return {};
  1486. }
  1487. Bytecode::CodeGenerationErrorOr<void> ContinueStatement::generate_bytecode(Bytecode::Generator& generator) const
  1488. {
  1489. // FIXME: Handle finally blocks in a graceful manner
  1490. // We need to execute the finally block, but tell it to resume
  1491. // execution at the designated block
  1492. if (m_target_label.is_null()) {
  1493. generator.generate_continue();
  1494. return {};
  1495. }
  1496. generator.generate_continue(m_target_label);
  1497. return {};
  1498. }
  1499. Bytecode::CodeGenerationErrorOr<void> DebuggerStatement::generate_bytecode(Bytecode::Generator&) const
  1500. {
  1501. return {};
  1502. }
  1503. Bytecode::CodeGenerationErrorOr<void> ConditionalExpression::generate_bytecode(Bytecode::Generator& generator) const
  1504. {
  1505. // test
  1506. // jump if_true (true) true (false) false
  1507. // true
  1508. // jump always (true) end
  1509. // false
  1510. // jump always (true) end
  1511. // end
  1512. auto& true_block = generator.make_block();
  1513. auto& false_block = generator.make_block();
  1514. auto& end_block = generator.make_block();
  1515. TRY(m_test->generate_bytecode(generator));
  1516. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1517. Bytecode::Label { true_block },
  1518. Bytecode::Label { false_block });
  1519. generator.switch_to_basic_block(true_block);
  1520. TRY(m_consequent->generate_bytecode(generator));
  1521. generator.emit<Bytecode::Op::Jump>().set_targets(
  1522. Bytecode::Label { end_block },
  1523. {});
  1524. generator.switch_to_basic_block(false_block);
  1525. TRY(m_alternate->generate_bytecode(generator));
  1526. generator.emit<Bytecode::Op::Jump>().set_targets(
  1527. Bytecode::Label { end_block },
  1528. {});
  1529. generator.switch_to_basic_block(end_block);
  1530. return {};
  1531. }
  1532. Bytecode::CodeGenerationErrorOr<void> SequenceExpression::generate_bytecode(Bytecode::Generator& generator) const
  1533. {
  1534. for (auto& expression : m_expressions)
  1535. TRY(expression->generate_bytecode(generator));
  1536. return {};
  1537. }
  1538. Bytecode::CodeGenerationErrorOr<void> TemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1539. {
  1540. auto string_reg = generator.allocate_register();
  1541. for (size_t i = 0; i < m_expressions.size(); i++) {
  1542. TRY(m_expressions[i]->generate_bytecode(generator));
  1543. if (i == 0) {
  1544. generator.emit<Bytecode::Op::Store>(string_reg);
  1545. } else {
  1546. generator.emit<Bytecode::Op::ConcatString>(string_reg);
  1547. }
  1548. }
  1549. generator.emit<Bytecode::Op::Load>(string_reg);
  1550. return {};
  1551. }
  1552. Bytecode::CodeGenerationErrorOr<void> TaggedTemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1553. {
  1554. TRY(m_tag->generate_bytecode(generator));
  1555. auto tag_reg = generator.allocate_register();
  1556. generator.emit<Bytecode::Op::Store>(tag_reg);
  1557. // FIXME: We only need to record the first and last register,
  1558. // due to packing everything in an array, same goes for argument_regs
  1559. Vector<Bytecode::Register> string_regs;
  1560. auto& expressions = m_template_literal->expressions();
  1561. for (size_t i = 0; i < expressions.size(); ++i) {
  1562. if (i % 2 != 0)
  1563. continue;
  1564. string_regs.append(generator.allocate_register());
  1565. }
  1566. size_t reg_index = 0;
  1567. for (size_t i = 0; i < expressions.size(); ++i) {
  1568. if (i % 2 != 0)
  1569. continue;
  1570. TRY(expressions[i]->generate_bytecode(generator));
  1571. auto string_reg = string_regs[reg_index++];
  1572. generator.emit<Bytecode::Op::Store>(string_reg);
  1573. }
  1574. if (string_regs.is_empty()) {
  1575. generator.emit<Bytecode::Op::NewArray>();
  1576. } else {
  1577. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { string_regs.first(), string_regs.last() });
  1578. }
  1579. auto strings_reg = generator.allocate_register();
  1580. generator.emit<Bytecode::Op::Store>(strings_reg);
  1581. Vector<Bytecode::Register> argument_regs;
  1582. argument_regs.append(strings_reg);
  1583. for (size_t i = 1; i < expressions.size(); i += 2)
  1584. argument_regs.append(generator.allocate_register());
  1585. for (size_t i = 1; i < expressions.size(); i += 2) {
  1586. auto string_reg = argument_regs[1 + i / 2];
  1587. TRY(expressions[i]->generate_bytecode(generator));
  1588. generator.emit<Bytecode::Op::Store>(string_reg);
  1589. }
  1590. Vector<Bytecode::Register> raw_string_regs;
  1591. for ([[maybe_unused]] auto& raw_string : m_template_literal->raw_strings())
  1592. string_regs.append(generator.allocate_register());
  1593. reg_index = 0;
  1594. for (auto& raw_string : m_template_literal->raw_strings()) {
  1595. TRY(raw_string->generate_bytecode(generator));
  1596. auto raw_string_reg = string_regs[reg_index++];
  1597. generator.emit<Bytecode::Op::Store>(raw_string_reg);
  1598. raw_string_regs.append(raw_string_reg);
  1599. }
  1600. if (raw_string_regs.is_empty()) {
  1601. generator.emit<Bytecode::Op::NewArray>();
  1602. } else {
  1603. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { raw_string_regs.first(), raw_string_regs.last() });
  1604. }
  1605. auto raw_strings_reg = generator.allocate_register();
  1606. generator.emit<Bytecode::Op::Store>(raw_strings_reg);
  1607. generator.emit<Bytecode::Op::PutById>(strings_reg, generator.intern_identifier("raw"));
  1608. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1609. auto this_reg = generator.allocate_register();
  1610. generator.emit<Bytecode::Op::Store>(this_reg);
  1611. if (!argument_regs.is_empty())
  1612. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2, AK::Array { argument_regs.first(), argument_regs.last() });
  1613. else
  1614. generator.emit<Bytecode::Op::NewArray>();
  1615. generator.emit<Bytecode::Op::Call>(Bytecode::Op::Call::CallType::Call, tag_reg, this_reg);
  1616. return {};
  1617. }
  1618. Bytecode::CodeGenerationErrorOr<void> UpdateExpression::generate_bytecode(Bytecode::Generator& generator) const
  1619. {
  1620. TRY(generator.emit_load_from_reference(*m_argument));
  1621. Optional<Bytecode::Register> previous_value_for_postfix_reg;
  1622. if (!m_prefixed) {
  1623. previous_value_for_postfix_reg = generator.allocate_register();
  1624. generator.emit<Bytecode::Op::ToNumeric>();
  1625. generator.emit<Bytecode::Op::Store>(*previous_value_for_postfix_reg);
  1626. }
  1627. if (m_op == UpdateOp::Increment)
  1628. generator.emit<Bytecode::Op::Increment>();
  1629. else
  1630. generator.emit<Bytecode::Op::Decrement>();
  1631. TRY(generator.emit_store_to_reference(*m_argument));
  1632. if (!m_prefixed)
  1633. generator.emit<Bytecode::Op::Load>(*previous_value_for_postfix_reg);
  1634. return {};
  1635. }
  1636. Bytecode::CodeGenerationErrorOr<void> ThrowStatement::generate_bytecode(Bytecode::Generator& generator) const
  1637. {
  1638. TRY(m_argument->generate_bytecode(generator));
  1639. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1640. generator.emit<Bytecode::Op::Throw>();
  1641. return {};
  1642. }
  1643. Bytecode::CodeGenerationErrorOr<void> BreakStatement::generate_bytecode(Bytecode::Generator& generator) const
  1644. {
  1645. // FIXME: Handle finally blocks in a graceful manner
  1646. // We need to execute the finally block, but tell it to resume
  1647. // execution at the designated block
  1648. if (m_target_label.is_null()) {
  1649. generator.generate_break();
  1650. return {};
  1651. }
  1652. generator.generate_break(m_target_label);
  1653. return {};
  1654. }
  1655. Bytecode::CodeGenerationErrorOr<void> TryStatement::generate_bytecode(Bytecode::Generator& generator) const
  1656. {
  1657. auto& saved_block = generator.current_block();
  1658. Optional<Bytecode::Label> handler_target;
  1659. Optional<Bytecode::Label> finalizer_target;
  1660. Bytecode::BasicBlock* next_block { nullptr };
  1661. if (m_finalizer) {
  1662. // FIXME: See notes in Op.h->ScheduleJump
  1663. auto& finalizer_block = generator.make_block();
  1664. generator.switch_to_basic_block(finalizer_block);
  1665. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1666. TRY(m_finalizer->generate_bytecode(generator));
  1667. if (!generator.is_current_block_terminated()) {
  1668. next_block = &generator.make_block();
  1669. auto next_target = Bytecode::Label { *next_block };
  1670. generator.emit<Bytecode::Op::ContinuePendingUnwind>(next_target);
  1671. }
  1672. finalizer_target = Bytecode::Label { finalizer_block };
  1673. }
  1674. if (m_finalizer)
  1675. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::ReturnToFinally);
  1676. if (m_handler) {
  1677. auto& handler_block = generator.make_block();
  1678. generator.switch_to_basic_block(handler_block);
  1679. if (!m_finalizer)
  1680. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1681. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  1682. TRY(m_handler->parameter().visit(
  1683. [&](DeprecatedFlyString const& parameter) -> Bytecode::CodeGenerationErrorOr<void> {
  1684. if (!parameter.is_empty()) {
  1685. auto parameter_identifier = generator.intern_identifier(parameter);
  1686. generator.register_binding(parameter_identifier);
  1687. generator.emit<Bytecode::Op::CreateVariable>(parameter_identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1688. generator.emit<Bytecode::Op::SetVariable>(parameter_identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1689. }
  1690. return {};
  1691. },
  1692. [&](NonnullRefPtr<BindingPattern const> const&) -> Bytecode::CodeGenerationErrorOr<void> {
  1693. // FIXME: Implement this path when the above DeclarativeEnvironment issue is dealt with.
  1694. return Bytecode::CodeGenerationError {
  1695. this,
  1696. "Unimplemented catch argument: BindingPattern"sv,
  1697. };
  1698. }));
  1699. TRY(m_handler->body().generate_bytecode(generator));
  1700. handler_target = Bytecode::Label { handler_block };
  1701. generator.end_variable_scope();
  1702. if (!generator.is_current_block_terminated()) {
  1703. if (m_finalizer) {
  1704. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1705. } else {
  1706. VERIFY(!next_block);
  1707. next_block = &generator.make_block();
  1708. auto next_target = Bytecode::Label { *next_block };
  1709. generator.emit<Bytecode::Op::Jump>(next_target);
  1710. }
  1711. }
  1712. }
  1713. if (m_finalizer)
  1714. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::ReturnToFinally);
  1715. auto& target_block = generator.make_block();
  1716. generator.switch_to_basic_block(saved_block);
  1717. generator.emit<Bytecode::Op::EnterUnwindContext>(Bytecode::Label { target_block }, handler_target, finalizer_target);
  1718. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1719. if (m_finalizer)
  1720. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::ReturnToFinally);
  1721. generator.switch_to_basic_block(target_block);
  1722. TRY(m_block->generate_bytecode(generator));
  1723. if (!generator.is_current_block_terminated()) {
  1724. if (m_finalizer) {
  1725. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1726. } else {
  1727. if (!next_block)
  1728. next_block = &generator.make_block();
  1729. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1730. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { *next_block });
  1731. }
  1732. }
  1733. if (m_finalizer)
  1734. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::ReturnToFinally);
  1735. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1736. generator.switch_to_basic_block(next_block ? *next_block : saved_block);
  1737. return {};
  1738. }
  1739. Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_bytecode(Bytecode::Generator& generator) const
  1740. {
  1741. return generate_labelled_evaluation(generator, {});
  1742. }
  1743. Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  1744. {
  1745. auto discriminant_reg = generator.allocate_register();
  1746. TRY(m_discriminant->generate_bytecode(generator));
  1747. generator.emit<Bytecode::Op::Store>(discriminant_reg);
  1748. Vector<Bytecode::BasicBlock&> case_blocks;
  1749. Bytecode::BasicBlock* default_block { nullptr };
  1750. Bytecode::BasicBlock* next_test_block = &generator.make_block();
  1751. auto has_lexical_block = has_lexical_declarations();
  1752. // Note: This call ends up calling begin_variable_scope() if has_lexical_block is true, so we need to clean up after it at the end.
  1753. TRY(ScopeNode::generate_bytecode(generator));
  1754. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_test_block }, {});
  1755. for (auto& switch_case : m_cases) {
  1756. auto& case_block = generator.make_block();
  1757. if (switch_case->test()) {
  1758. generator.switch_to_basic_block(*next_test_block);
  1759. TRY(switch_case->test()->generate_bytecode(generator));
  1760. generator.emit<Bytecode::Op::StrictlyEquals>(discriminant_reg);
  1761. next_test_block = &generator.make_block();
  1762. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { case_block }, Bytecode::Label { *next_test_block });
  1763. } else {
  1764. default_block = &case_block;
  1765. }
  1766. case_blocks.append(case_block);
  1767. }
  1768. generator.switch_to_basic_block(*next_test_block);
  1769. auto& end_block = generator.make_block();
  1770. if (default_block != nullptr) {
  1771. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *default_block }, {});
  1772. } else {
  1773. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1774. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1775. }
  1776. auto current_block = case_blocks.begin();
  1777. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  1778. for (auto& switch_case : m_cases) {
  1779. generator.switch_to_basic_block(*current_block);
  1780. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1781. for (auto& statement : switch_case->children()) {
  1782. TRY(statement->generate_bytecode(generator));
  1783. if (generator.is_current_block_terminated())
  1784. break;
  1785. }
  1786. if (!generator.is_current_block_terminated()) {
  1787. auto next_block = current_block;
  1788. next_block++;
  1789. if (next_block.is_end()) {
  1790. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1791. } else {
  1792. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_block }, {});
  1793. }
  1794. }
  1795. current_block++;
  1796. }
  1797. generator.end_breakable_scope();
  1798. if (has_lexical_block)
  1799. generator.end_variable_scope();
  1800. generator.switch_to_basic_block(end_block);
  1801. return {};
  1802. }
  1803. Bytecode::CodeGenerationErrorOr<void> ClassDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1804. {
  1805. TRY(m_class_expression->generate_bytecode(generator));
  1806. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(m_class_expression.ptr()->name()), Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1807. return {};
  1808. }
  1809. Bytecode::CodeGenerationErrorOr<void> ClassExpression::generate_bytecode(Bytecode::Generator& generator) const
  1810. {
  1811. generator.emit<Bytecode::Op::NewClass>(*this);
  1812. return {};
  1813. }
  1814. Bytecode::CodeGenerationErrorOr<void> SpreadExpression::generate_bytecode(Bytecode::Generator& generator) const
  1815. {
  1816. // NOTE: All users of this should handle the behaviour of this on their own,
  1817. // assuming it returns an Array-like object
  1818. return m_target->generate_bytecode(generator);
  1819. }
  1820. Bytecode::CodeGenerationErrorOr<void> ThisExpression::generate_bytecode(Bytecode::Generator& generator) const
  1821. {
  1822. generator.emit<Bytecode::Op::ResolveThisBinding>();
  1823. return {};
  1824. }
  1825. Bytecode::CodeGenerationErrorOr<void> AwaitExpression::generate_bytecode(Bytecode::Generator& generator) const
  1826. {
  1827. VERIFY(generator.is_in_async_function());
  1828. // Transform `await expr` to `yield expr`, see AsyncFunctionDriverWrapper
  1829. // For that we just need to copy most of the code from YieldExpression
  1830. auto received_completion_register = generator.allocate_register();
  1831. auto received_completion_type_register = generator.allocate_register();
  1832. auto received_completion_value_register = generator.allocate_register();
  1833. auto type_identifier = generator.intern_identifier("type");
  1834. auto value_identifier = generator.intern_identifier("value");
  1835. TRY(m_argument->generate_bytecode(generator));
  1836. auto& continuation_block = generator.make_block();
  1837. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1838. generator.switch_to_basic_block(continuation_block);
  1839. // The accumulator is set to an object, for example: { "type": 1 (normal), value: 1337 }
  1840. generator.emit<Bytecode::Op::Store>(received_completion_register);
  1841. generator.emit<Bytecode::Op::GetById>(type_identifier);
  1842. generator.emit<Bytecode::Op::Store>(received_completion_type_register);
  1843. generator.emit<Bytecode::Op::Load>(received_completion_register);
  1844. generator.emit<Bytecode::Op::GetById>(value_identifier);
  1845. generator.emit<Bytecode::Op::Store>(received_completion_value_register);
  1846. auto& normal_completion_continuation_block = generator.make_block();
  1847. auto& throw_value_block = generator.make_block();
  1848. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Normal)));
  1849. generator.emit<Bytecode::Op::StrictlyEquals>(received_completion_type_register);
  1850. generator.emit<Bytecode::Op::JumpConditional>(
  1851. Bytecode::Label { normal_completion_continuation_block },
  1852. Bytecode::Label { throw_value_block });
  1853. // Simplification: The only abrupt completion we receive from AsyncFunctionDriverWrapper is Type::Throw
  1854. // So we do not need to account for the Type::Return path
  1855. generator.switch_to_basic_block(throw_value_block);
  1856. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1857. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1858. generator.emit<Bytecode::Op::Throw>();
  1859. generator.switch_to_basic_block(normal_completion_continuation_block);
  1860. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1861. return {};
  1862. }
  1863. Bytecode::CodeGenerationErrorOr<void> WithStatement::generate_bytecode(Bytecode::Generator& generator) const
  1864. {
  1865. TRY(m_object->generate_bytecode(generator));
  1866. generator.emit<Bytecode::Op::EnterObjectEnvironment>();
  1867. // EnterObjectEnvironment sets the running execution context's lexical_environment to a new Object Environment.
  1868. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1869. TRY(m_body->generate_bytecode(generator));
  1870. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1871. if (!generator.is_current_block_terminated())
  1872. generator.emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  1873. return {};
  1874. }
  1875. enum class LHSKind {
  1876. Assignment,
  1877. VarBinding,
  1878. LexicalBinding,
  1879. };
  1880. enum class IterationKind {
  1881. Enumerate,
  1882. Iterate,
  1883. AsyncIterate,
  1884. };
  1885. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  1886. struct ForInOfHeadEvaluationResult {
  1887. bool is_destructuring { false };
  1888. LHSKind lhs_kind { LHSKind::Assignment };
  1889. };
  1890. static Bytecode::CodeGenerationErrorOr<ForInOfHeadEvaluationResult> for_in_of_head_evaluation(Bytecode::Generator& generator, IterationKind iteration_kind, Variant<NonnullRefPtr<ASTNode const>, NonnullRefPtr<BindingPattern const>> const& lhs, NonnullRefPtr<ASTNode const> const& rhs)
  1891. {
  1892. ForInOfHeadEvaluationResult result {};
  1893. bool entered_lexical_scope = false;
  1894. if (auto* ast_ptr = lhs.get_pointer<NonnullRefPtr<ASTNode const>>(); ast_ptr && is<VariableDeclaration>(**ast_ptr)) {
  1895. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  1896. // ForInOfStatement : for ( var ForBinding in Expression ) Statement
  1897. // ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  1898. // ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  1899. // ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  1900. auto& variable_declaration = static_cast<VariableDeclaration const&>(**ast_ptr);
  1901. result.is_destructuring = variable_declaration.declarations().first()->target().has<NonnullRefPtr<BindingPattern const>>();
  1902. result.lhs_kind = variable_declaration.is_lexical_declaration() ? LHSKind::LexicalBinding : LHSKind::VarBinding;
  1903. // 1. Let oldEnv be the running execution context's LexicalEnvironment.
  1904. // NOTE: 'uninitializedBoundNames' refers to the lexical bindings (i.e. Const/Let) present in the second and last form.
  1905. // 2. If uninitializedBoundNames is not an empty List, then
  1906. if (variable_declaration.declaration_kind() != DeclarationKind::Var) {
  1907. entered_lexical_scope = true;
  1908. // a. Assert: uninitializedBoundNames has no duplicate entries.
  1909. // b. Let newEnv be NewDeclarativeEnvironment(oldEnv).
  1910. generator.begin_variable_scope();
  1911. // c. For each String name of uninitializedBoundNames, do
  1912. // NOTE: Nothing in the callback throws an exception.
  1913. MUST(variable_declaration.for_each_bound_name([&](auto const& name) {
  1914. // i. Perform ! newEnv.CreateMutableBinding(name, false).
  1915. auto identifier = generator.intern_identifier(name);
  1916. generator.register_binding(identifier);
  1917. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1918. }));
  1919. // d. Set the running execution context's LexicalEnvironment to newEnv.
  1920. // NOTE: Done by CreateEnvironment.
  1921. }
  1922. } else {
  1923. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  1924. // ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  1925. // ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  1926. result.lhs_kind = LHSKind::Assignment;
  1927. }
  1928. // 3. Let exprRef be the result of evaluating expr.
  1929. TRY(rhs->generate_bytecode(generator));
  1930. // 4. Set the running execution context's LexicalEnvironment to oldEnv.
  1931. if (entered_lexical_scope)
  1932. generator.end_variable_scope();
  1933. // 5. Let exprValue be ? GetValue(exprRef).
  1934. // NOTE: No need to store this anywhere.
  1935. // 6. If iterationKind is enumerate, then
  1936. if (iteration_kind == IterationKind::Enumerate) {
  1937. // a. If exprValue is undefined or null, then
  1938. auto& nullish_block = generator.make_block();
  1939. auto& continuation_block = generator.make_block();
  1940. auto& jump = generator.emit<Bytecode::Op::JumpNullish>();
  1941. jump.set_targets(Bytecode::Label { nullish_block }, Bytecode::Label { continuation_block });
  1942. // i. Return Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  1943. generator.switch_to_basic_block(nullish_block);
  1944. generator.generate_break();
  1945. generator.switch_to_basic_block(continuation_block);
  1946. // b. Let obj be ! ToObject(exprValue).
  1947. // NOTE: GetObjectPropertyIterator does this.
  1948. // c. Let iterator be EnumerateObjectProperties(obj).
  1949. // d. Let nextMethod be ! GetV(iterator, "next").
  1950. // e. Return the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
  1951. generator.emit<Bytecode::Op::GetObjectPropertyIterator>();
  1952. }
  1953. // 7. Else,
  1954. else {
  1955. // a. Assert: iterationKind is iterate or async-iterate.
  1956. // b. If iterationKind is async-iterate, let iteratorHint be async.
  1957. if (iteration_kind == IterationKind::AsyncIterate) {
  1958. return Bytecode::CodeGenerationError {
  1959. rhs.ptr(),
  1960. "Unimplemented iteration mode: AsyncIterate"sv,
  1961. };
  1962. }
  1963. // c. Else, let iteratorHint be sync.
  1964. // d. Return ? GetIterator(exprValue, iteratorHint).
  1965. generator.emit<Bytecode::Op::GetIterator>();
  1966. }
  1967. return result;
  1968. }
  1969. // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  1970. static Bytecode::CodeGenerationErrorOr<void> for_in_of_body_evaluation(Bytecode::Generator& generator, ASTNode const& node, Variant<NonnullRefPtr<ASTNode const>, NonnullRefPtr<BindingPattern const>> const& lhs, ASTNode const& body, ForInOfHeadEvaluationResult const& head_result, Vector<DeprecatedFlyString> const& label_set, Bytecode::BasicBlock& loop_end, Bytecode::BasicBlock& loop_update)
  1971. {
  1972. auto iterator_register = generator.allocate_register();
  1973. generator.emit<Bytecode::Op::Store>(iterator_register);
  1974. // FIXME: Implement this
  1975. // 1. If iteratorKind is not present, set iteratorKind to sync.
  1976. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  1977. bool has_lexical_binding = false;
  1978. // 3. Let V be undefined.
  1979. // NOTE: We don't need 'V' as the resulting value will naturally flow through via the accumulator register.
  1980. // 4. Let destructuring be IsDestructuring of lhs.
  1981. auto destructuring = head_result.is_destructuring;
  1982. // 5. If destructuring is true and if lhsKind is assignment, then
  1983. if (destructuring && head_result.lhs_kind == LHSKind::Assignment) {
  1984. // a. Assert: lhs is a LeftHandSideExpression.
  1985. // b. Let assignmentPattern be the AssignmentPattern that is covered by lhs.
  1986. // FIXME: Implement this.
  1987. return Bytecode::CodeGenerationError {
  1988. &node,
  1989. "Unimplemented: assignment destructuring in for/of"sv,
  1990. };
  1991. }
  1992. // 6. Repeat,
  1993. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_update });
  1994. generator.switch_to_basic_block(loop_update);
  1995. generator.begin_continuable_scope(Bytecode::Label { loop_update }, label_set);
  1996. // a. Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
  1997. generator.emit<Bytecode::Op::Load>(iterator_register);
  1998. generator.emit<Bytecode::Op::IteratorNext>();
  1999. // FIXME: Implement this:
  2000. // b. If iteratorKind is async, set nextResult to ? Await(nextResult).
  2001. // c. If Type(nextResult) is not Object, throw a TypeError exception.
  2002. // NOTE: IteratorComplete already does this.
  2003. // d. Let done be ? IteratorComplete(nextResult).
  2004. auto iterator_result_register = generator.allocate_register();
  2005. generator.emit<Bytecode::Op::Store>(iterator_result_register);
  2006. generator.emit<Bytecode::Op::IteratorResultDone>();
  2007. // e. If done is true, return V.
  2008. auto& loop_continue = generator.make_block();
  2009. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { loop_end }, Bytecode::Label { loop_continue });
  2010. generator.switch_to_basic_block(loop_continue);
  2011. // f. Let nextValue be ? IteratorValue(nextResult).
  2012. generator.emit<Bytecode::Op::Load>(iterator_result_register);
  2013. generator.emit<Bytecode::Op::IteratorResultValue>();
  2014. // g. If lhsKind is either assignment or varBinding, then
  2015. if (head_result.lhs_kind != LHSKind::LexicalBinding) {
  2016. // i. If destructuring is false, then
  2017. if (!destructuring) {
  2018. // 1. Let lhsRef be the result of evaluating lhs. (It may be evaluated repeatedly.)
  2019. // NOTE: We're skipping all the completion stuff that the spec does, as the unwinding mechanism will take case of doing that.
  2020. if (head_result.lhs_kind == LHSKind::VarBinding) {
  2021. auto& declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode const>>());
  2022. VERIFY(declaration.declarations().size() == 1);
  2023. TRY(assign_accumulator_to_variable_declarator(generator, declaration.declarations().first(), declaration));
  2024. } else {
  2025. if (auto ptr = lhs.get_pointer<NonnullRefPtr<ASTNode const>>()) {
  2026. TRY(generator.emit_store_to_reference(**ptr));
  2027. } else {
  2028. auto& binding_pattern = lhs.get<NonnullRefPtr<BindingPattern const>>();
  2029. auto value_register = generator.allocate_register();
  2030. generator.emit<Bytecode::Op::Store>(value_register);
  2031. TRY(generate_binding_pattern_bytecode(generator, *binding_pattern, Bytecode::Op::SetVariable::InitializationMode::Set, value_register));
  2032. }
  2033. }
  2034. }
  2035. }
  2036. // h. Else,
  2037. else {
  2038. // i. Assert: lhsKind is lexicalBinding.
  2039. // ii. Assert: lhs is a ForDeclaration.
  2040. // iii. Let iterationEnv be NewDeclarativeEnvironment(oldEnv).
  2041. // iv. Perform ForDeclarationBindingInstantiation of lhs with argument iterationEnv.
  2042. // v. Set the running execution context's LexicalEnvironment to iterationEnv.
  2043. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical);
  2044. has_lexical_binding = true;
  2045. // 14.7.5.4 Runtime Semantics: ForDeclarationBindingInstantiation, https://tc39.es/ecma262/#sec-runtime-semantics-fordeclarationbindinginstantiation
  2046. // 1. Assert: environment is a declarative Environment Record.
  2047. // NOTE: We just made it.
  2048. auto& variable_declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode const>>());
  2049. // 2. For each element name of the BoundNames of ForBinding, do
  2050. // NOTE: Nothing in the callback throws an exception.
  2051. MUST(variable_declaration.for_each_bound_name([&](auto const& name) {
  2052. auto identifier = generator.intern_identifier(name);
  2053. generator.register_binding(identifier, Bytecode::Generator::BindingMode::Lexical);
  2054. // a. If IsConstantDeclaration of LetOrConst is true, then
  2055. if (variable_declaration.is_constant_declaration()) {
  2056. // i. Perform ! environment.CreateImmutableBinding(name, true).
  2057. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  2058. }
  2059. // b. Else,
  2060. else {
  2061. // i. Perform ! environment.CreateMutableBinding(name, false).
  2062. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  2063. }
  2064. }));
  2065. // 3. Return unused.
  2066. // NOTE: No need to do that as we've inlined this.
  2067. // vi. If destructuring is false, then
  2068. if (!destructuring) {
  2069. // 1. Assert: lhs binds a single name.
  2070. // 2. Let lhsName be the sole element of BoundNames of lhs.
  2071. auto lhs_name = variable_declaration.declarations().first()->target().get<NonnullRefPtr<Identifier const>>()->string();
  2072. // 3. Let lhsRef be ! ResolveBinding(lhsName).
  2073. // NOTE: We're skipping all the completion stuff that the spec does, as the unwinding mechanism will take case of doing that.
  2074. auto identifier = generator.intern_identifier(lhs_name);
  2075. generator.emit<Bytecode::Op::SetVariable>(identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Lexical);
  2076. }
  2077. }
  2078. // i. If destructuring is false, then
  2079. if (!destructuring) {
  2080. // i. If lhsRef is an abrupt completion, then
  2081. // 1. Let status be lhsRef.
  2082. // ii. Else if lhsKind is lexicalBinding, then
  2083. // 1. Let status be Completion(InitializeReferencedBinding(lhsRef, nextValue)).
  2084. // iii. Else,
  2085. // 1. Let status be Completion(PutValue(lhsRef, nextValue)).
  2086. // NOTE: This is performed above.
  2087. }
  2088. // j. Else,
  2089. else {
  2090. // FIXME: i. If lhsKind is assignment, then
  2091. // 1. Let status be Completion(DestructuringAssignmentEvaluation of assignmentPattern with argument nextValue).
  2092. // ii. Else if lhsKind is varBinding, then
  2093. // 1. Assert: lhs is a ForBinding.
  2094. // 2. Let status be Completion(BindingInitialization of lhs with arguments nextValue and undefined).
  2095. // iii. Else,
  2096. // 1. Assert: lhsKind is lexicalBinding.
  2097. // 2. Assert: lhs is a ForDeclaration.
  2098. // 3. Let status be Completion(ForDeclarationBindingInitialization of lhs with arguments nextValue and iterationEnv).
  2099. if (head_result.lhs_kind == LHSKind::VarBinding || head_result.lhs_kind == LHSKind::LexicalBinding) {
  2100. auto& declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode const>>());
  2101. VERIFY(declaration.declarations().size() == 1);
  2102. auto& binding_pattern = declaration.declarations().first()->target().get<NonnullRefPtr<BindingPattern const>>();
  2103. auto value_register = generator.allocate_register();
  2104. generator.emit<Bytecode::Op::Store>(value_register);
  2105. TRY(generate_binding_pattern_bytecode(generator, *binding_pattern, head_result.lhs_kind == LHSKind::VarBinding ? Bytecode::Op::SetVariable::InitializationMode::Set : Bytecode::Op::SetVariable::InitializationMode::Initialize, value_register));
  2106. } else {
  2107. return Bytecode::CodeGenerationError {
  2108. &node,
  2109. "Unimplemented: assignment destructuring in for/of"sv,
  2110. };
  2111. }
  2112. }
  2113. // FIXME: Implement iteration closure.
  2114. // k. If status is an abrupt completion, then
  2115. // i. Set the running execution context's LexicalEnvironment to oldEnv.
  2116. // ii. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  2117. // iii. If iterationKind is enumerate, then
  2118. // 1. Return ? status.
  2119. // iv. Else,
  2120. // 1. Assert: iterationKind is iterate.
  2121. // 2. Return ? IteratorClose(iteratorRecord, status).
  2122. // l. Let result be the result of evaluating stmt.
  2123. TRY(body.generate_bytecode(generator));
  2124. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  2125. if (has_lexical_binding)
  2126. generator.end_variable_scope();
  2127. generator.end_continuable_scope();
  2128. generator.end_breakable_scope();
  2129. // NOTE: If we're here, then the loop definitely continues.
  2130. // n. If LoopContinues(result, labelSet) is false, then
  2131. // i. If iterationKind is enumerate, then
  2132. // 1. Return ? UpdateEmpty(result, V).
  2133. // ii. Else,
  2134. // 1. Assert: iterationKind is iterate.
  2135. // 2. Set status to Completion(UpdateEmpty(result, V)).
  2136. // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  2137. // 4. Return ? IteratorClose(iteratorRecord, status).
  2138. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  2139. // The body can contain an unconditional block terminator (e.g. return, throw), so we have to check for that before generating the Jump.
  2140. if (!generator.is_current_block_terminated())
  2141. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { loop_update }, {});
  2142. generator.switch_to_basic_block(loop_end);
  2143. return {};
  2144. }
  2145. Bytecode::CodeGenerationErrorOr<void> ForInStatement::generate_bytecode(Bytecode::Generator& generator) const
  2146. {
  2147. return generate_labelled_evaluation(generator, {});
  2148. }
  2149. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  2150. Bytecode::CodeGenerationErrorOr<void> ForInStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  2151. {
  2152. auto& loop_end = generator.make_block();
  2153. auto& loop_update = generator.make_block();
  2154. generator.begin_breakable_scope(Bytecode::Label { loop_end }, label_set);
  2155. auto head_result = TRY(for_in_of_head_evaluation(generator, IterationKind::Enumerate, m_lhs, m_rhs));
  2156. // Now perform the rest of ForInOfLoopEvaluation, given that the accumulator holds the iterator we're supposed to iterate over.
  2157. return for_in_of_body_evaluation(generator, *this, m_lhs, body(), head_result, label_set, loop_end, loop_update);
  2158. }
  2159. Bytecode::CodeGenerationErrorOr<void> ForOfStatement::generate_bytecode(Bytecode::Generator& generator) const
  2160. {
  2161. return generate_labelled_evaluation(generator, {});
  2162. }
  2163. Bytecode::CodeGenerationErrorOr<void> ForOfStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  2164. {
  2165. auto& loop_end = generator.make_block();
  2166. auto& loop_update = generator.make_block();
  2167. generator.begin_breakable_scope(Bytecode::Label { loop_end }, label_set);
  2168. auto head_result = TRY(for_in_of_head_evaluation(generator, IterationKind::Iterate, m_lhs, m_rhs));
  2169. // Now perform the rest of ForInOfLoopEvaluation, given that the accumulator holds the iterator we're supposed to iterate over.
  2170. return for_in_of_body_evaluation(generator, *this, m_lhs, body(), head_result, label_set, loop_end, loop_update);
  2171. }
  2172. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  2173. Bytecode::CodeGenerationErrorOr<void> MetaProperty::generate_bytecode(Bytecode::Generator& generator) const
  2174. {
  2175. // NewTarget : new . target
  2176. if (m_type == MetaProperty::Type::NewTarget) {
  2177. // 1. Return GetNewTarget().
  2178. generator.emit<Bytecode::Op::GetNewTarget>();
  2179. return {};
  2180. }
  2181. // ImportMeta : import . meta
  2182. if (m_type == MetaProperty::Type::ImportMeta) {
  2183. return Bytecode::CodeGenerationError {
  2184. this,
  2185. "Unimplemented meta property: import.meta"sv,
  2186. };
  2187. }
  2188. VERIFY_NOT_REACHED();
  2189. }
  2190. }