ASTCodegen.cpp 117 KB

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