ASTCodegen.cpp 132 KB

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