ASTCodegen.cpp 162 KB

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