ASTCodegen.cpp 162 KB

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