ASTCodegen.cpp 124 KB

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