ASTCodegen.cpp 114 KB

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