ASTCodegen.cpp 149 KB

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