ASTCodegen.cpp 163 KB

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