ASTCodegen.cpp 122 KB

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