ASTCodegen.cpp 164 KB

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