ASTCodegen.cpp 135 KB

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