ASTCodegen.cpp 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055
  1. /*
  2. * Copyright (c) 2021, 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/Format.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. namespace JS {
  18. Bytecode::CodeGenerationErrorOr<void> ASTNode::generate_bytecode(Bytecode::Generator&) const
  19. {
  20. return Bytecode::CodeGenerationError {
  21. this,
  22. "Missing generate_bytecode()"sv,
  23. };
  24. }
  25. Bytecode::CodeGenerationErrorOr<void> ScopeNode::generate_bytecode(Bytecode::Generator& generator) const
  26. {
  27. Optional<Bytecode::CodeGenerationError> maybe_error;
  28. size_t pushed_scope_count = 0;
  29. auto const failing_completion = Completion(Completion::Type::Throw, {}, {});
  30. if (is<BlockStatement>(*this) || is<SwitchStatement>(*this)) {
  31. // Perform the steps of BlockDeclarationInstantiation.
  32. if (has_lexical_declarations()) {
  33. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  34. pushed_scope_count++;
  35. }
  36. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  37. auto is_constant_declaration = declaration.is_constant_declaration();
  38. declaration.for_each_bound_name([&](auto const& name) {
  39. auto index = generator.intern_identifier(name);
  40. if (is_constant_declaration || !generator.has_binding(index)) {
  41. generator.register_binding(index);
  42. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration);
  43. }
  44. });
  45. if (is<FunctionDeclaration>(declaration)) {
  46. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  47. auto const& name = function_declaration.name();
  48. auto index = generator.intern_identifier(name);
  49. generator.emit<Bytecode::Op::NewFunction>(function_declaration);
  50. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  51. }
  52. return {};
  53. });
  54. } else if (is<Program>(*this)) {
  55. // Perform the steps of GlobalDeclarationInstantiation.
  56. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Global, Bytecode::Generator::SurroundingScopeKind::Global);
  57. pushed_scope_count++;
  58. // 1. Let lexNames be the LexicallyDeclaredNames of script.
  59. // 2. Let varNames be the VarDeclaredNames of script.
  60. // 3. For each element name of lexNames, do
  61. (void)for_each_lexically_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
  62. auto identifier = generator.intern_identifier(name);
  63. // a. If env.HasVarDeclaration(name) is true, throw a SyntaxError exception.
  64. // b. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  65. if (generator.has_binding(identifier)) {
  66. // FIXME: Throw an actual SyntaxError instance.
  67. generator.emit<Bytecode::Op::NewString>(generator.intern_string(String::formatted("SyntaxError: toplevel variable already declared: {}", name)));
  68. generator.emit<Bytecode::Op::Throw>();
  69. return {};
  70. }
  71. // FIXME: c. If hasRestrictedGlobalProperty is true, throw a SyntaxError exception.
  72. // d. If hasRestrictedGlobal is true, throw a SyntaxError exception.
  73. return {};
  74. });
  75. // 4. For each element name of varNames, do
  76. (void)for_each_var_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
  77. auto identifier = generator.intern_identifier(name);
  78. // a. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  79. if (generator.has_binding(identifier)) {
  80. // FIXME: Throw an actual SyntaxError instance.
  81. generator.emit<Bytecode::Op::NewString>(generator.intern_string(String::formatted("SyntaxError: toplevel variable already declared: {}", name)));
  82. generator.emit<Bytecode::Op::Throw>();
  83. }
  84. return {};
  85. });
  86. // 5. Let varDeclarations be the VarScopedDeclarations of script.
  87. // 6. Let functionsToInitialize be a new empty List.
  88. Vector<FunctionDeclaration const&> functions_to_initialize;
  89. // 7. Let declaredFunctionNames be a new empty List.
  90. HashTable<FlyString> declared_function_names;
  91. // 8. For each element d of varDeclarations, in reverse List order, do
  92. (void)for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) -> ThrowCompletionOr<void> {
  93. // a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then
  94. // i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
  95. // Note: This is checked in for_each_var_function_declaration_in_reverse_order.
  96. // ii. NOTE: If there are multiple function declarations for the same name, the last declaration is used.
  97. // iii. Let fn be the sole element of the BoundNames of d.
  98. // iv. If fn is not an element of declaredFunctionNames, then
  99. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  100. return {};
  101. // FIXME: 1. Let fnDefinable be ? env.CanDeclareGlobalFunction(fn).
  102. // FIXME: 2. If fnDefinable is false, throw a TypeError exception.
  103. // 3. Append fn to declaredFunctionNames.
  104. // Note: Already done in step iv. above.
  105. // 4. Insert d as the first element of functionsToInitialize.
  106. functions_to_initialize.prepend(function);
  107. return {};
  108. });
  109. // 9. Let declaredVarNames be a new empty List.
  110. HashTable<FlyString> declared_var_names;
  111. // 10. For each element d of varDeclarations, do
  112. (void)for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
  113. // a. If d is a VariableDeclaration, a ForBinding, or a BindingIdentifier, then
  114. // Note: This is done in for_each_var_scoped_variable_declaration.
  115. // i. For each String vn of the BoundNames of d, do
  116. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  117. // 1. If vn is not an element of declaredFunctionNames, then
  118. if (declared_function_names.contains(name))
  119. return {};
  120. // FIXME: a. Let vnDefinable be ? env.CanDeclareGlobalVar(vn).
  121. // FIXME: b. If vnDefinable is false, throw a TypeError exception.
  122. // c. If vn is not an element of declaredVarNames, then
  123. // i. Append vn to declaredVarNames.
  124. declared_var_names.set(name);
  125. return {};
  126. });
  127. });
  128. // 11. NOTE: No abnormal terminations occur after this algorithm step if the global object is an ordinary object. However, if the global object is a Proxy exotic object it may exhibit behaviours that cause abnormal terminations in some of the following steps.
  129. // 12. NOTE: Annex B.3.2.2 adds additional steps at this point.
  130. // 12. Let strict be IsStrict of script.
  131. // 13. If strict is false, then
  132. if (!verify_cast<Program>(*this).is_strict_mode()) {
  133. // a. Let declaredFunctionOrVarNames be the list-concatenation of declaredFunctionNames and declaredVarNames.
  134. // b. For each FunctionDeclaration f that is directly contained in the StatementList of a Block, CaseClause, or DefaultClause Contained within script, do
  135. (void)for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  136. // i. Let F be StringValue of the BindingIdentifier of f.
  137. auto& function_name = function_declaration.name();
  138. // ii. If replacing the FunctionDeclaration f with a VariableStatement that has F as a BindingIdentifier would not produce any Early Errors for script, then
  139. // Note: This step is already performed during parsing and for_each_function_hoistable_with_annexB_extension so this always passes here.
  140. // 1. If env.HasLexicalDeclaration(F) is false, then
  141. auto index = generator.intern_identifier(function_name);
  142. if (generator.has_binding(index, Bytecode::Generator::BindingMode::Lexical))
  143. return;
  144. // FIXME: a. Let fnDefinable be ? env.CanDeclareGlobalVar(F).
  145. // b. If fnDefinable is true, then
  146. // i. NOTE: A var binding for F is only instantiated here if it is neither a VarDeclaredName nor the name of another FunctionDeclaration.
  147. // ii. If declaredFunctionOrVarNames does not contain F, then
  148. if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
  149. // i. Perform ? env.CreateGlobalVarBinding(F, false).
  150. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Var, false);
  151. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  152. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Var);
  153. // ii. Append F to declaredFunctionOrVarNames.
  154. declared_function_names.set(function_name);
  155. }
  156. // iii. When the FunctionDeclaration f is evaluated, perform the following steps in place of the FunctionDeclaration Evaluation algorithm provided in 15.2.6:
  157. // i. Let genv be the running execution context's VariableEnvironment.
  158. // ii. Let benv be the running execution context's LexicalEnvironment.
  159. // iii. Let fobj be ! benv.GetBindingValue(F, false).
  160. // iv. Perform ? genv.SetMutableBinding(F, fobj, false).
  161. // v. Return NormalCompletion(empty).
  162. function_declaration.set_should_do_additional_annexB_steps();
  163. });
  164. }
  165. // 15. For each element d of lexDeclarations, do
  166. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  167. // a. NOTE: Lexically declared names are only instantiated here but not initialized.
  168. // b. For each element dn of the BoundNames of d, do
  169. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  170. auto identifier = generator.intern_identifier(name);
  171. // i. If IsConstantDeclaration of d is true, then
  172. generator.register_binding(identifier);
  173. if (declaration.is_constant_declaration()) {
  174. // 1. Perform ? env.CreateImmutableBinding(dn, true).
  175. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  176. } else {
  177. // ii. Else,
  178. // 1. Perform ? env.CreateMutableBinding(dn, false).
  179. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  180. }
  181. return {};
  182. });
  183. });
  184. // 16. For each Parse Node f of functionsToInitialize, do
  185. for (auto& function_declaration : functions_to_initialize) {
  186. // FIXME: Do this more correctly.
  187. // a. Let fn be the sole element of the BoundNames of f.
  188. // b. Let fo be InstantiateFunctionObject of f with arguments env and privateEnv.
  189. generator.emit<Bytecode::Op::NewFunction>(function_declaration);
  190. // c. Perform ? env.CreateGlobalFunctionBinding(fn, fo, false).
  191. auto const& name = function_declaration.name();
  192. auto index = generator.intern_identifier(name);
  193. if (!generator.has_binding(index)) {
  194. generator.register_binding(index, Bytecode::Generator::BindingMode::Var);
  195. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, false);
  196. }
  197. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  198. }
  199. // 17. For each String vn of declaredVarNames, do
  200. // a. Perform ? env.CreateGlobalVarBinding(vn, false).
  201. for (auto& var_name : declared_var_names)
  202. generator.register_binding(generator.intern_identifier(var_name), Bytecode::Generator::BindingMode::Var);
  203. } else {
  204. // Perform the steps of FunctionDeclarationInstantiation.
  205. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Var, Bytecode::Generator::SurroundingScopeKind::Function);
  206. pushed_scope_count++;
  207. if (has_lexical_declarations()) {
  208. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Function);
  209. pushed_scope_count++;
  210. }
  211. // FIXME: Implement this boi correctly.
  212. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  213. auto is_constant_declaration = declaration.is_constant_declaration();
  214. declaration.for_each_bound_name([&](auto const& name) {
  215. auto index = generator.intern_identifier(name);
  216. if (is_constant_declaration || !generator.has_binding(index)) {
  217. generator.register_binding(index);
  218. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration);
  219. }
  220. });
  221. if (is<FunctionDeclaration>(declaration)) {
  222. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  223. if (auto result = function_declaration.generate_bytecode(generator); result.is_error()) {
  224. maybe_error = result.release_error();
  225. // To make `for_each_lexically_scoped_declaration` happy.
  226. return failing_completion;
  227. }
  228. auto const& name = function_declaration.name();
  229. auto index = generator.intern_identifier(name);
  230. if (!generator.has_binding(index)) {
  231. generator.register_binding(index);
  232. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, false);
  233. }
  234. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::InitializeOrSet);
  235. }
  236. return {};
  237. });
  238. }
  239. if (maybe_error.has_value())
  240. return maybe_error.release_value();
  241. for (auto& child : children()) {
  242. TRY(child.generate_bytecode(generator));
  243. if (generator.is_current_block_terminated())
  244. break;
  245. }
  246. for (size_t i = 0; i < pushed_scope_count; ++i)
  247. generator.end_variable_scope();
  248. return {};
  249. }
  250. Bytecode::CodeGenerationErrorOr<void> EmptyStatement::generate_bytecode(Bytecode::Generator&) const
  251. {
  252. return {};
  253. }
  254. Bytecode::CodeGenerationErrorOr<void> ExpressionStatement::generate_bytecode(Bytecode::Generator& generator) const
  255. {
  256. return m_expression->generate_bytecode(generator);
  257. }
  258. Bytecode::CodeGenerationErrorOr<void> BinaryExpression::generate_bytecode(Bytecode::Generator& generator) const
  259. {
  260. TRY(m_lhs->generate_bytecode(generator));
  261. auto lhs_reg = generator.allocate_register();
  262. generator.emit<Bytecode::Op::Store>(lhs_reg);
  263. TRY(m_rhs->generate_bytecode(generator));
  264. switch (m_op) {
  265. case BinaryOp::Addition:
  266. generator.emit<Bytecode::Op::Add>(lhs_reg);
  267. break;
  268. case BinaryOp::Subtraction:
  269. generator.emit<Bytecode::Op::Sub>(lhs_reg);
  270. break;
  271. case BinaryOp::Multiplication:
  272. generator.emit<Bytecode::Op::Mul>(lhs_reg);
  273. break;
  274. case BinaryOp::Division:
  275. generator.emit<Bytecode::Op::Div>(lhs_reg);
  276. break;
  277. case BinaryOp::Modulo:
  278. generator.emit<Bytecode::Op::Mod>(lhs_reg);
  279. break;
  280. case BinaryOp::Exponentiation:
  281. generator.emit<Bytecode::Op::Exp>(lhs_reg);
  282. break;
  283. case BinaryOp::GreaterThan:
  284. generator.emit<Bytecode::Op::GreaterThan>(lhs_reg);
  285. break;
  286. case BinaryOp::GreaterThanEquals:
  287. generator.emit<Bytecode::Op::GreaterThanEquals>(lhs_reg);
  288. break;
  289. case BinaryOp::LessThan:
  290. generator.emit<Bytecode::Op::LessThan>(lhs_reg);
  291. break;
  292. case BinaryOp::LessThanEquals:
  293. generator.emit<Bytecode::Op::LessThanEquals>(lhs_reg);
  294. break;
  295. case BinaryOp::LooselyInequals:
  296. generator.emit<Bytecode::Op::LooselyInequals>(lhs_reg);
  297. break;
  298. case BinaryOp::LooselyEquals:
  299. generator.emit<Bytecode::Op::LooselyEquals>(lhs_reg);
  300. break;
  301. case BinaryOp::StrictlyInequals:
  302. generator.emit<Bytecode::Op::StrictlyInequals>(lhs_reg);
  303. break;
  304. case BinaryOp::StrictlyEquals:
  305. generator.emit<Bytecode::Op::StrictlyEquals>(lhs_reg);
  306. break;
  307. case BinaryOp::BitwiseAnd:
  308. generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
  309. break;
  310. case BinaryOp::BitwiseOr:
  311. generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
  312. break;
  313. case BinaryOp::BitwiseXor:
  314. generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
  315. break;
  316. case BinaryOp::LeftShift:
  317. generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
  318. break;
  319. case BinaryOp::RightShift:
  320. generator.emit<Bytecode::Op::RightShift>(lhs_reg);
  321. break;
  322. case BinaryOp::UnsignedRightShift:
  323. generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
  324. break;
  325. case BinaryOp::In:
  326. generator.emit<Bytecode::Op::In>(lhs_reg);
  327. break;
  328. case BinaryOp::InstanceOf:
  329. generator.emit<Bytecode::Op::InstanceOf>(lhs_reg);
  330. break;
  331. default:
  332. VERIFY_NOT_REACHED();
  333. }
  334. return {};
  335. }
  336. Bytecode::CodeGenerationErrorOr<void> LogicalExpression::generate_bytecode(Bytecode::Generator& generator) const
  337. {
  338. TRY(m_lhs->generate_bytecode(generator));
  339. // lhs
  340. // jump op (true) end (false) rhs
  341. // rhs
  342. // jump always (true) end
  343. // end
  344. auto& rhs_block = generator.make_block();
  345. auto& end_block = generator.make_block();
  346. switch (m_op) {
  347. case LogicalOp::And:
  348. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  349. Bytecode::Label { rhs_block },
  350. Bytecode::Label { end_block });
  351. break;
  352. case LogicalOp::Or:
  353. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  354. Bytecode::Label { end_block },
  355. Bytecode::Label { rhs_block });
  356. break;
  357. case LogicalOp::NullishCoalescing:
  358. generator.emit<Bytecode::Op::JumpNullish>().set_targets(
  359. Bytecode::Label { rhs_block },
  360. Bytecode::Label { end_block });
  361. break;
  362. default:
  363. VERIFY_NOT_REACHED();
  364. }
  365. generator.switch_to_basic_block(rhs_block);
  366. TRY(m_rhs->generate_bytecode(generator));
  367. generator.emit<Bytecode::Op::Jump>().set_targets(
  368. Bytecode::Label { end_block },
  369. {});
  370. generator.switch_to_basic_block(end_block);
  371. return {};
  372. }
  373. Bytecode::CodeGenerationErrorOr<void> UnaryExpression::generate_bytecode(Bytecode::Generator& generator) const
  374. {
  375. TRY(m_lhs->generate_bytecode(generator));
  376. switch (m_op) {
  377. case UnaryOp::BitwiseNot:
  378. generator.emit<Bytecode::Op::BitwiseNot>();
  379. break;
  380. case UnaryOp::Not:
  381. generator.emit<Bytecode::Op::Not>();
  382. break;
  383. case UnaryOp::Plus:
  384. generator.emit<Bytecode::Op::UnaryPlus>();
  385. break;
  386. case UnaryOp::Minus:
  387. generator.emit<Bytecode::Op::UnaryMinus>();
  388. break;
  389. case UnaryOp::Typeof:
  390. generator.emit<Bytecode::Op::Typeof>();
  391. break;
  392. case UnaryOp::Void:
  393. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  394. break;
  395. default:
  396. return Bytecode::CodeGenerationError {
  397. this,
  398. "Unimplemented operation"sv,
  399. };
  400. }
  401. return {};
  402. }
  403. Bytecode::CodeGenerationErrorOr<void> NumericLiteral::generate_bytecode(Bytecode::Generator& generator) const
  404. {
  405. generator.emit<Bytecode::Op::LoadImmediate>(m_value);
  406. return {};
  407. }
  408. Bytecode::CodeGenerationErrorOr<void> BooleanLiteral::generate_bytecode(Bytecode::Generator& generator) const
  409. {
  410. generator.emit<Bytecode::Op::LoadImmediate>(Value(m_value));
  411. return {};
  412. }
  413. Bytecode::CodeGenerationErrorOr<void> NullLiteral::generate_bytecode(Bytecode::Generator& generator) const
  414. {
  415. generator.emit<Bytecode::Op::LoadImmediate>(js_null());
  416. return {};
  417. }
  418. Bytecode::CodeGenerationErrorOr<void> BigIntLiteral::generate_bytecode(Bytecode::Generator& generator) const
  419. {
  420. generator.emit<Bytecode::Op::NewBigInt>(Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1)));
  421. return {};
  422. }
  423. Bytecode::CodeGenerationErrorOr<void> StringLiteral::generate_bytecode(Bytecode::Generator& generator) const
  424. {
  425. generator.emit<Bytecode::Op::NewString>(generator.intern_string(m_value));
  426. return {};
  427. }
  428. Bytecode::CodeGenerationErrorOr<void> RegExpLiteral::generate_bytecode(Bytecode::Generator& generator) const
  429. {
  430. auto source_index = generator.intern_string(m_pattern);
  431. auto flags_index = generator.intern_string(m_flags);
  432. generator.emit<Bytecode::Op::NewRegExp>(source_index, flags_index);
  433. return {};
  434. }
  435. Bytecode::CodeGenerationErrorOr<void> Identifier::generate_bytecode(Bytecode::Generator& generator) const
  436. {
  437. generator.emit<Bytecode::Op::GetVariable>(generator.intern_identifier(m_string));
  438. return {};
  439. }
  440. Bytecode::CodeGenerationErrorOr<void> AssignmentExpression::generate_bytecode(Bytecode::Generator& generator) const
  441. {
  442. // FIXME: Implement this for BindingPatterns too.
  443. auto& lhs = m_lhs.get<NonnullRefPtr<Expression>>();
  444. if (m_op == AssignmentOp::Assignment) {
  445. TRY(m_rhs->generate_bytecode(generator));
  446. return generator.emit_store_to_reference(lhs);
  447. }
  448. TRY(generator.emit_load_from_reference(lhs));
  449. Bytecode::BasicBlock* rhs_block_ptr { nullptr };
  450. Bytecode::BasicBlock* end_block_ptr { nullptr };
  451. // Logical assignments short circuit.
  452. if (m_op == AssignmentOp::AndAssignment) { // &&=
  453. rhs_block_ptr = &generator.make_block();
  454. end_block_ptr = &generator.make_block();
  455. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  456. Bytecode::Label { *rhs_block_ptr },
  457. Bytecode::Label { *end_block_ptr });
  458. } else if (m_op == AssignmentOp::OrAssignment) { // ||=
  459. rhs_block_ptr = &generator.make_block();
  460. end_block_ptr = &generator.make_block();
  461. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  462. Bytecode::Label { *end_block_ptr },
  463. Bytecode::Label { *rhs_block_ptr });
  464. } else if (m_op == AssignmentOp::NullishAssignment) { // ??=
  465. rhs_block_ptr = &generator.make_block();
  466. end_block_ptr = &generator.make_block();
  467. generator.emit<Bytecode::Op::JumpNullish>().set_targets(
  468. Bytecode::Label { *rhs_block_ptr },
  469. Bytecode::Label { *end_block_ptr });
  470. }
  471. if (rhs_block_ptr)
  472. generator.switch_to_basic_block(*rhs_block_ptr);
  473. // lhs_reg is a part of the rhs_block because the store isn't necessary
  474. // if the logical assignment condition fails.
  475. auto lhs_reg = generator.allocate_register();
  476. generator.emit<Bytecode::Op::Store>(lhs_reg);
  477. TRY(m_rhs->generate_bytecode(generator));
  478. switch (m_op) {
  479. case AssignmentOp::AdditionAssignment:
  480. generator.emit<Bytecode::Op::Add>(lhs_reg);
  481. break;
  482. case AssignmentOp::SubtractionAssignment:
  483. generator.emit<Bytecode::Op::Sub>(lhs_reg);
  484. break;
  485. case AssignmentOp::MultiplicationAssignment:
  486. generator.emit<Bytecode::Op::Mul>(lhs_reg);
  487. break;
  488. case AssignmentOp::DivisionAssignment:
  489. generator.emit<Bytecode::Op::Div>(lhs_reg);
  490. break;
  491. case AssignmentOp::ModuloAssignment:
  492. generator.emit<Bytecode::Op::Mod>(lhs_reg);
  493. break;
  494. case AssignmentOp::ExponentiationAssignment:
  495. generator.emit<Bytecode::Op::Exp>(lhs_reg);
  496. break;
  497. case AssignmentOp::BitwiseAndAssignment:
  498. generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
  499. break;
  500. case AssignmentOp::BitwiseOrAssignment:
  501. generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
  502. break;
  503. case AssignmentOp::BitwiseXorAssignment:
  504. generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
  505. break;
  506. case AssignmentOp::LeftShiftAssignment:
  507. generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
  508. break;
  509. case AssignmentOp::RightShiftAssignment:
  510. generator.emit<Bytecode::Op::RightShift>(lhs_reg);
  511. break;
  512. case AssignmentOp::UnsignedRightShiftAssignment:
  513. generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
  514. break;
  515. case AssignmentOp::AndAssignment:
  516. case AssignmentOp::OrAssignment:
  517. case AssignmentOp::NullishAssignment:
  518. break; // These are handled above.
  519. default:
  520. return Bytecode::CodeGenerationError {
  521. this,
  522. "Unimplemented operation"sv,
  523. };
  524. }
  525. TRY(generator.emit_store_to_reference(lhs));
  526. if (end_block_ptr) {
  527. generator.emit<Bytecode::Op::Jump>().set_targets(
  528. Bytecode::Label { *end_block_ptr },
  529. {});
  530. generator.switch_to_basic_block(*end_block_ptr);
  531. }
  532. return {};
  533. }
  534. Bytecode::CodeGenerationErrorOr<void> WhileStatement::generate_bytecode(Bytecode::Generator& generator) const
  535. {
  536. // test
  537. // jump if_false (true) end (false) body
  538. // body
  539. // jump always (true) test
  540. // end
  541. auto& test_block = generator.make_block();
  542. auto& body_block = generator.make_block();
  543. auto& end_block = generator.make_block();
  544. // Init result register
  545. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  546. auto result_reg = generator.allocate_register();
  547. generator.emit<Bytecode::Op::Store>(result_reg);
  548. // jump to the test block
  549. generator.emit<Bytecode::Op::Jump>().set_targets(
  550. Bytecode::Label { test_block },
  551. {});
  552. generator.switch_to_basic_block(test_block);
  553. TRY(m_test->generate_bytecode(generator));
  554. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  555. Bytecode::Label { body_block },
  556. Bytecode::Label { end_block });
  557. generator.switch_to_basic_block(body_block);
  558. generator.begin_continuable_scope(Bytecode::Label { test_block });
  559. generator.begin_breakable_scope(Bytecode::Label { end_block });
  560. TRY(m_body->generate_bytecode(generator));
  561. generator.end_breakable_scope();
  562. generator.end_continuable_scope();
  563. if (!generator.is_current_block_terminated()) {
  564. generator.emit<Bytecode::Op::Jump>().set_targets(
  565. Bytecode::Label { test_block },
  566. {});
  567. generator.switch_to_basic_block(end_block);
  568. generator.emit<Bytecode::Op::Load>(result_reg);
  569. }
  570. return {};
  571. }
  572. Bytecode::CodeGenerationErrorOr<void> DoWhileStatement::generate_bytecode(Bytecode::Generator& generator) const
  573. {
  574. // jump always (true) body
  575. // test
  576. // jump if_false (true) end (false) body
  577. // body
  578. // jump always (true) test
  579. // end
  580. auto& test_block = generator.make_block();
  581. auto& body_block = generator.make_block();
  582. auto& end_block = generator.make_block();
  583. // Init result register
  584. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  585. auto result_reg = generator.allocate_register();
  586. generator.emit<Bytecode::Op::Store>(result_reg);
  587. // jump to the body block
  588. generator.emit<Bytecode::Op::Jump>().set_targets(
  589. Bytecode::Label { body_block },
  590. {});
  591. generator.switch_to_basic_block(test_block);
  592. TRY(m_test->generate_bytecode(generator));
  593. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  594. Bytecode::Label { body_block },
  595. Bytecode::Label { end_block });
  596. generator.switch_to_basic_block(body_block);
  597. generator.begin_continuable_scope(Bytecode::Label { test_block });
  598. generator.begin_breakable_scope(Bytecode::Label { end_block });
  599. TRY(m_body->generate_bytecode(generator));
  600. generator.end_breakable_scope();
  601. generator.end_continuable_scope();
  602. if (!generator.is_current_block_terminated()) {
  603. generator.emit<Bytecode::Op::Jump>().set_targets(
  604. Bytecode::Label { test_block },
  605. {});
  606. generator.switch_to_basic_block(end_block);
  607. generator.emit<Bytecode::Op::Load>(result_reg);
  608. }
  609. return {};
  610. }
  611. Bytecode::CodeGenerationErrorOr<void> ForStatement::generate_bytecode(Bytecode::Generator& generator) const
  612. {
  613. // init
  614. // jump always (true) test
  615. // test
  616. // jump if_true (true) body (false) end
  617. // body
  618. // jump always (true) update
  619. // update
  620. // jump always (true) test
  621. // end
  622. // If 'test' is missing, fuse the 'test' and 'body' basic blocks
  623. // If 'update' is missing, fuse the 'body' and 'update' basic blocks
  624. Bytecode::BasicBlock* test_block_ptr { nullptr };
  625. Bytecode::BasicBlock* body_block_ptr { nullptr };
  626. Bytecode::BasicBlock* update_block_ptr { nullptr };
  627. auto& end_block = generator.make_block();
  628. bool has_lexical_environment = false;
  629. if (m_init) {
  630. if (m_init->is_variable_declaration()) {
  631. auto& variable_declaration = verify_cast<VariableDeclaration>(*m_init);
  632. if (variable_declaration.is_lexical_declaration()) {
  633. has_lexical_environment = true;
  634. // FIXME: Is Block correct?
  635. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  636. bool is_const = variable_declaration.is_constant_declaration();
  637. variable_declaration.for_each_bound_name([&](auto const& name) {
  638. auto index = generator.intern_identifier(name);
  639. generator.register_binding(index);
  640. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_const);
  641. });
  642. }
  643. }
  644. TRY(m_init->generate_bytecode(generator));
  645. }
  646. body_block_ptr = &generator.make_block();
  647. if (m_test)
  648. test_block_ptr = &generator.make_block();
  649. else
  650. test_block_ptr = body_block_ptr;
  651. if (m_update)
  652. update_block_ptr = &generator.make_block();
  653. else
  654. update_block_ptr = body_block_ptr;
  655. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  656. auto result_reg = generator.allocate_register();
  657. generator.emit<Bytecode::Op::Store>(result_reg);
  658. generator.emit<Bytecode::Op::Jump>().set_targets(
  659. Bytecode::Label { *test_block_ptr },
  660. {});
  661. if (m_test) {
  662. generator.switch_to_basic_block(*test_block_ptr);
  663. TRY(m_test->generate_bytecode(generator));
  664. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  665. Bytecode::Label { *body_block_ptr },
  666. Bytecode::Label { end_block });
  667. }
  668. generator.switch_to_basic_block(*body_block_ptr);
  669. generator.begin_continuable_scope(Bytecode::Label { *update_block_ptr });
  670. generator.begin_breakable_scope(Bytecode::Label { end_block });
  671. TRY(m_body->generate_bytecode(generator));
  672. generator.end_breakable_scope();
  673. generator.end_continuable_scope();
  674. if (!generator.is_current_block_terminated()) {
  675. if (m_update) {
  676. generator.emit<Bytecode::Op::Jump>().set_targets(
  677. Bytecode::Label { *update_block_ptr },
  678. {});
  679. generator.switch_to_basic_block(*update_block_ptr);
  680. TRY(m_update->generate_bytecode(generator));
  681. }
  682. generator.emit<Bytecode::Op::Jump>().set_targets(
  683. Bytecode::Label { *test_block_ptr },
  684. {});
  685. generator.switch_to_basic_block(end_block);
  686. generator.emit<Bytecode::Op::Load>(result_reg);
  687. }
  688. if (has_lexical_environment)
  689. generator.end_variable_scope();
  690. return {};
  691. }
  692. Bytecode::CodeGenerationErrorOr<void> ObjectExpression::generate_bytecode(Bytecode::Generator& generator) const
  693. {
  694. generator.emit<Bytecode::Op::NewObject>();
  695. if (m_properties.is_empty())
  696. return {};
  697. auto object_reg = generator.allocate_register();
  698. generator.emit<Bytecode::Op::Store>(object_reg);
  699. for (auto& property : m_properties) {
  700. if (property.type() != ObjectProperty::Type::KeyValue)
  701. return Bytecode::CodeGenerationError {
  702. this,
  703. "Unimplemented property kind"sv,
  704. };
  705. if (is<StringLiteral>(property.key())) {
  706. auto& string_literal = static_cast<StringLiteral const&>(property.key());
  707. Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(string_literal.value());
  708. TRY(property.value().generate_bytecode(generator));
  709. generator.emit<Bytecode::Op::PutById>(object_reg, key_name);
  710. } else {
  711. TRY(property.key().generate_bytecode(generator));
  712. auto property_reg = generator.allocate_register();
  713. generator.emit<Bytecode::Op::Store>(property_reg);
  714. TRY(property.value().generate_bytecode(generator));
  715. generator.emit<Bytecode::Op::PutByValue>(object_reg, property_reg);
  716. }
  717. }
  718. generator.emit<Bytecode::Op::Load>(object_reg);
  719. return {};
  720. }
  721. Bytecode::CodeGenerationErrorOr<void> ArrayExpression::generate_bytecode(Bytecode::Generator& generator) const
  722. {
  723. Vector<Bytecode::Register> element_regs;
  724. for (auto& element : m_elements) {
  725. if (element && is<SpreadExpression>(*element)) {
  726. return Bytecode::CodeGenerationError {
  727. this,
  728. "Unimplemented element kind: SpreadExpression"sv,
  729. };
  730. }
  731. element_regs.append(generator.allocate_register());
  732. }
  733. size_t i = 0;
  734. for (auto& element : m_elements) {
  735. if (element) {
  736. TRY(element->generate_bytecode(generator));
  737. if (is<SpreadExpression>(*element))
  738. VERIFY_NOT_REACHED();
  739. } else {
  740. generator.emit<Bytecode::Op::LoadImmediate>(Value {});
  741. }
  742. auto& element_reg = element_regs[i++];
  743. generator.emit<Bytecode::Op::Store>(element_reg);
  744. }
  745. if (element_regs.is_empty()) {
  746. generator.emit<Bytecode::Op::NewArray>();
  747. } else {
  748. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { element_regs.first(), element_regs.last() });
  749. }
  750. return {};
  751. }
  752. Bytecode::CodeGenerationErrorOr<void> MemberExpression::generate_bytecode(Bytecode::Generator& generator) const
  753. {
  754. return generator.emit_load_from_reference(*this);
  755. }
  756. Bytecode::CodeGenerationErrorOr<void> FunctionDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  757. {
  758. if (m_is_hoisted) {
  759. auto index = generator.intern_identifier(name());
  760. generator.emit<Bytecode::Op::GetVariable>(index);
  761. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode::Var);
  762. }
  763. return {};
  764. }
  765. Bytecode::CodeGenerationErrorOr<void> FunctionExpression::generate_bytecode(Bytecode::Generator& generator) const
  766. {
  767. generator.emit<Bytecode::Op::NewFunction>(*this);
  768. return {};
  769. }
  770. static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode, Bytecode::Register const& value_reg);
  771. 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)
  772. {
  773. Vector<Bytecode::Register> excluded_property_names;
  774. auto has_rest = false;
  775. if (pattern.entries.size() > 0)
  776. has_rest = pattern.entries[pattern.entries.size() - 1].is_rest;
  777. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  778. if (is_rest) {
  779. VERIFY(name.has<NonnullRefPtr<Identifier>>());
  780. VERIFY(alias.has<Empty>());
  781. VERIFY(!initializer);
  782. auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  783. auto interned_identifier = generator.intern_identifier(identifier);
  784. generator.emit_with_extra_register_slots<Bytecode::Op::CopyObjectExcludingProperties>(excluded_property_names.size(), value_reg, excluded_property_names);
  785. generator.emit<Bytecode::Op::SetVariable>(interned_identifier, initialization_mode);
  786. return {};
  787. }
  788. Bytecode::StringTableIndex name_index;
  789. if (name.has<NonnullRefPtr<Identifier>>()) {
  790. auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  791. name_index = generator.intern_string(identifier);
  792. if (has_rest) {
  793. auto excluded_name_reg = generator.allocate_register();
  794. excluded_property_names.append(excluded_name_reg);
  795. generator.emit<Bytecode::Op::NewString>(name_index);
  796. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  797. }
  798. generator.emit<Bytecode::Op::Load>(value_reg);
  799. generator.emit<Bytecode::Op::GetById>(generator.intern_identifier(identifier));
  800. } else {
  801. auto expression = name.get<NonnullRefPtr<Expression>>();
  802. TRY(expression->generate_bytecode(generator));
  803. if (has_rest) {
  804. auto excluded_name_reg = generator.allocate_register();
  805. excluded_property_names.append(excluded_name_reg);
  806. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  807. }
  808. generator.emit<Bytecode::Op::GetByValue>(value_reg);
  809. }
  810. if (initializer) {
  811. auto& if_undefined_block = generator.make_block();
  812. auto& if_not_undefined_block = generator.make_block();
  813. generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
  814. Bytecode::Label { if_undefined_block },
  815. Bytecode::Label { if_not_undefined_block });
  816. generator.switch_to_basic_block(if_undefined_block);
  817. TRY(initializer->generate_bytecode(generator));
  818. generator.emit<Bytecode::Op::Jump>().set_targets(
  819. Bytecode::Label { if_not_undefined_block },
  820. {});
  821. generator.switch_to_basic_block(if_not_undefined_block);
  822. }
  823. if (alias.has<NonnullRefPtr<BindingPattern>>()) {
  824. auto& binding_pattern = *alias.get<NonnullRefPtr<BindingPattern>>();
  825. auto nested_value_reg = generator.allocate_register();
  826. generator.emit<Bytecode::Op::Store>(nested_value_reg);
  827. TRY(generate_binding_pattern_bytecode(generator, binding_pattern, initialization_mode, nested_value_reg));
  828. } else if (alias.has<Empty>()) {
  829. if (name.has<NonnullRefPtr<Expression>>()) {
  830. // This needs some sort of SetVariableByValue opcode, as it's a runtime binding
  831. return Bytecode::CodeGenerationError {
  832. name.get<NonnullRefPtr<Expression>>().ptr(),
  833. "Unimplemented name/alias pair: Empty/Expression"sv,
  834. };
  835. }
  836. auto& identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  837. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  838. } else {
  839. auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string();
  840. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  841. }
  842. }
  843. return {};
  844. }
  845. 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)
  846. {
  847. /*
  848. * Consider the following destructuring assignment:
  849. *
  850. * let [a, b, c, d, e] = o;
  851. *
  852. * It would be fairly trivial to just loop through this iterator, getting the value
  853. * at each step and assigning them to the binding sequentially. However, this is not
  854. * correct: once an iterator is exhausted, it must not be called again. This complicates
  855. * the bytecode. In order to accomplish this, we do the following:
  856. *
  857. * - Reserve a special boolean register which holds 'true' if the iterator is exhausted,
  858. * and false otherwise
  859. * - When we are retrieving the value which should be bound, we first check this register.
  860. * If it is 'true', we load undefined into the accumulator. Otherwise, we grab the next
  861. * value from the iterator and store it into the accumulator.
  862. *
  863. * Note that the is_exhausted register does not need to be loaded with false because the
  864. * first IteratorNext bytecode is _not_ proceeded by an exhausted check, as it is
  865. * unnecessary.
  866. */
  867. auto is_iterator_exhausted_register = generator.allocate_register();
  868. auto iterator_reg = generator.allocate_register();
  869. generator.emit<Bytecode::Op::Load>(value_reg);
  870. generator.emit<Bytecode::Op::GetIterator>();
  871. generator.emit<Bytecode::Op::Store>(iterator_reg);
  872. bool first = true;
  873. auto temp_iterator_result_reg = generator.allocate_register();
  874. auto assign_accumulator_to_alias = [&](auto& alias) {
  875. return alias.visit(
  876. [&](Empty) -> Bytecode::CodeGenerationErrorOr<void> {
  877. // This element is an elision
  878. return {};
  879. },
  880. [&](NonnullRefPtr<Identifier> const& identifier) -> Bytecode::CodeGenerationErrorOr<void> {
  881. auto interned_index = generator.intern_identifier(identifier->string());
  882. generator.emit<Bytecode::Op::SetVariable>(interned_index, initialization_mode);
  883. return {};
  884. },
  885. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  886. // Store the accumulator value in a permanent register
  887. auto target_reg = generator.allocate_register();
  888. generator.emit<Bytecode::Op::Store>(target_reg);
  889. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, target_reg);
  890. },
  891. [&](NonnullRefPtr<MemberExpression> const& expr) -> Bytecode::CodeGenerationErrorOr<void> {
  892. return Bytecode::CodeGenerationError {
  893. expr.ptr(),
  894. "Unimplemented alias mode: MemberExpression"sv,
  895. };
  896. });
  897. };
  898. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  899. VERIFY(name.has<Empty>());
  900. if (is_rest) {
  901. if (first) {
  902. // The iterator has not been called, and is thus known to be not exhausted
  903. generator.emit<Bytecode::Op::Load>(iterator_reg);
  904. generator.emit<Bytecode::Op::IteratorToArray>();
  905. } else {
  906. auto& if_exhausted_block = generator.make_block();
  907. auto& if_not_exhausted_block = generator.make_block();
  908. auto& continuation_block = generator.make_block();
  909. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  910. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  911. Bytecode::Label { if_exhausted_block },
  912. Bytecode::Label { if_not_exhausted_block });
  913. generator.switch_to_basic_block(if_exhausted_block);
  914. generator.emit<Bytecode::Op::NewArray>();
  915. generator.emit<Bytecode::Op::Jump>().set_targets(
  916. Bytecode::Label { continuation_block },
  917. {});
  918. generator.switch_to_basic_block(if_not_exhausted_block);
  919. generator.emit<Bytecode::Op::Load>(iterator_reg);
  920. generator.emit<Bytecode::Op::IteratorToArray>();
  921. generator.emit<Bytecode::Op::Jump>().set_targets(
  922. Bytecode::Label { continuation_block },
  923. {});
  924. generator.switch_to_basic_block(continuation_block);
  925. }
  926. return assign_accumulator_to_alias(alias);
  927. }
  928. // In the first iteration of the loop, a few things are true which can save
  929. // us some bytecode:
  930. // - the iterator result is still in the accumulator, so we can avoid a load
  931. // - the iterator is not yet exhausted, which can save us a jump and some
  932. // creation
  933. auto& iterator_is_exhausted_block = generator.make_block();
  934. if (!first) {
  935. auto& iterator_is_not_exhausted_block = generator.make_block();
  936. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  937. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  938. Bytecode::Label { iterator_is_exhausted_block },
  939. Bytecode::Label { iterator_is_not_exhausted_block });
  940. generator.switch_to_basic_block(iterator_is_not_exhausted_block);
  941. generator.emit<Bytecode::Op::Load>(iterator_reg);
  942. }
  943. generator.emit<Bytecode::Op::IteratorNext>();
  944. generator.emit<Bytecode::Op::Store>(temp_iterator_result_reg);
  945. generator.emit<Bytecode::Op::IteratorResultDone>();
  946. generator.emit<Bytecode::Op::Store>(is_iterator_exhausted_register);
  947. // We still have to check for exhaustion here. If the iterator is exhausted,
  948. // we need to bail before trying to get the value
  949. auto& no_bail_block = generator.make_block();
  950. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  951. Bytecode::Label { iterator_is_exhausted_block },
  952. Bytecode::Label { no_bail_block });
  953. generator.switch_to_basic_block(no_bail_block);
  954. // Get the next value in the iterator
  955. generator.emit<Bytecode::Op::Load>(temp_iterator_result_reg);
  956. generator.emit<Bytecode::Op::IteratorResultValue>();
  957. auto& create_binding_block = generator.make_block();
  958. generator.emit<Bytecode::Op::Jump>().set_targets(
  959. Bytecode::Label { create_binding_block },
  960. {});
  961. // The iterator is exhausted, so we just load undefined and continue binding
  962. generator.switch_to_basic_block(iterator_is_exhausted_block);
  963. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  964. generator.emit<Bytecode::Op::Jump>().set_targets(
  965. Bytecode::Label { create_binding_block },
  966. {});
  967. // Create the actual binding. The value which this entry must bind is now in the
  968. // accumulator. We can proceed, processing the alias as a nested destructuring
  969. // pattern if necessary.
  970. generator.switch_to_basic_block(create_binding_block);
  971. TRY(assign_accumulator_to_alias(alias));
  972. first = false;
  973. }
  974. return {};
  975. }
  976. 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)
  977. {
  978. if (pattern.kind == BindingPattern::Kind::Object)
  979. return generate_object_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  980. return generate_array_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  981. }
  982. static Bytecode::CodeGenerationErrorOr<void> assign_accumulator_to_variable_declarator(Bytecode::Generator& generator, VariableDeclarator const& declarator, VariableDeclaration const& declaration)
  983. {
  984. auto initialization_mode = declaration.is_lexical_declaration() ? Bytecode::Op::SetVariable::InitializationMode::Initialize : Bytecode::Op::SetVariable::InitializationMode::Set;
  985. auto environment_mode = declaration.is_lexical_declaration() ? Bytecode::Op::EnvironmentMode::Lexical : Bytecode::Op::EnvironmentMode::Var;
  986. return declarator.target().visit(
  987. [&](NonnullRefPtr<Identifier> const& id) -> Bytecode::CodeGenerationErrorOr<void> {
  988. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(id->string()), initialization_mode, environment_mode);
  989. return {};
  990. },
  991. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  992. auto value_register = generator.allocate_register();
  993. generator.emit<Bytecode::Op::Store>(value_register);
  994. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, value_register);
  995. });
  996. }
  997. Bytecode::CodeGenerationErrorOr<void> VariableDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  998. {
  999. for (auto& declarator : m_declarations) {
  1000. if (declarator.init())
  1001. TRY(declarator.init()->generate_bytecode(generator));
  1002. else
  1003. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1004. TRY(assign_accumulator_to_variable_declarator(generator, declarator, *this));
  1005. }
  1006. return {};
  1007. }
  1008. Bytecode::CodeGenerationErrorOr<void> CallExpression::generate_bytecode(Bytecode::Generator& generator) const
  1009. {
  1010. auto callee_reg = generator.allocate_register();
  1011. auto this_reg = generator.allocate_register();
  1012. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1013. generator.emit<Bytecode::Op::Store>(this_reg);
  1014. if (is<NewExpression>(this)) {
  1015. TRY(m_callee->generate_bytecode(generator));
  1016. generator.emit<Bytecode::Op::Store>(callee_reg);
  1017. } else if (is<SuperExpression>(*m_callee)) {
  1018. return Bytecode::CodeGenerationError {
  1019. this,
  1020. "Unimplemented callee kind: SuperExpression"sv,
  1021. };
  1022. } else if (is<MemberExpression>(*m_callee)) {
  1023. auto& member_expression = static_cast<const MemberExpression&>(*m_callee);
  1024. if (is<SuperExpression>(member_expression.object())) {
  1025. return Bytecode::CodeGenerationError {
  1026. this,
  1027. "Unimplemented callee kind: MemberExpression on SuperExpression"sv,
  1028. };
  1029. }
  1030. TRY(member_expression.object().generate_bytecode(generator));
  1031. generator.emit<Bytecode::Op::Store>(this_reg);
  1032. if (member_expression.is_computed()) {
  1033. TRY(member_expression.property().generate_bytecode(generator));
  1034. generator.emit<Bytecode::Op::GetByValue>(this_reg);
  1035. } else {
  1036. auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string());
  1037. generator.emit<Bytecode::Op::GetById>(identifier_table_ref);
  1038. }
  1039. generator.emit<Bytecode::Op::Store>(callee_reg);
  1040. } else {
  1041. // FIXME: this = global object in sloppy mode.
  1042. TRY(m_callee->generate_bytecode(generator));
  1043. generator.emit<Bytecode::Op::Store>(callee_reg);
  1044. }
  1045. Vector<Bytecode::Register> argument_registers;
  1046. for (auto& arg : m_arguments) {
  1047. TRY(arg.value->generate_bytecode(generator));
  1048. auto arg_reg = generator.allocate_register();
  1049. generator.emit<Bytecode::Op::Store>(arg_reg);
  1050. argument_registers.append(arg_reg);
  1051. }
  1052. Bytecode::Op::Call::CallType call_type;
  1053. if (is<NewExpression>(*this)) {
  1054. call_type = Bytecode::Op::Call::CallType::Construct;
  1055. } else {
  1056. call_type = Bytecode::Op::Call::CallType::Call;
  1057. }
  1058. generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_registers.size(), call_type, callee_reg, this_reg, argument_registers);
  1059. return {};
  1060. }
  1061. Bytecode::CodeGenerationErrorOr<void> ReturnStatement::generate_bytecode(Bytecode::Generator& generator) const
  1062. {
  1063. if (m_argument)
  1064. TRY(m_argument->generate_bytecode(generator));
  1065. if (generator.is_in_generator_or_async_function()) {
  1066. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1067. generator.emit<Bytecode::Op::Yield>(nullptr);
  1068. } else {
  1069. generator.perform_needed_unwinds<Bytecode::Op::Return>();
  1070. generator.emit<Bytecode::Op::Return>();
  1071. }
  1072. return {};
  1073. }
  1074. Bytecode::CodeGenerationErrorOr<void> YieldExpression::generate_bytecode(Bytecode::Generator& generator) const
  1075. {
  1076. VERIFY(generator.is_in_generator_function());
  1077. if (m_is_yield_from) {
  1078. return Bytecode::CodeGenerationError {
  1079. this,
  1080. "Unimplemented form: `yield*`"sv,
  1081. };
  1082. }
  1083. if (m_argument)
  1084. TRY(m_argument->generate_bytecode(generator));
  1085. auto& continuation_block = generator.make_block();
  1086. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1087. generator.switch_to_basic_block(continuation_block);
  1088. return {};
  1089. }
  1090. Bytecode::CodeGenerationErrorOr<void> IfStatement::generate_bytecode(Bytecode::Generator& generator) const
  1091. {
  1092. // test
  1093. // jump if_true (true) true (false) false
  1094. // true
  1095. // jump always (true) end
  1096. // false
  1097. // jump always (true) end
  1098. // end
  1099. auto& true_block = generator.make_block();
  1100. auto& false_block = generator.make_block();
  1101. TRY(m_predicate->generate_bytecode(generator));
  1102. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1103. Bytecode::Label { true_block },
  1104. Bytecode::Label { false_block });
  1105. Bytecode::Op::Jump* true_block_jump { nullptr };
  1106. generator.switch_to_basic_block(true_block);
  1107. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1108. TRY(m_consequent->generate_bytecode(generator));
  1109. if (!generator.is_current_block_terminated())
  1110. true_block_jump = &generator.emit<Bytecode::Op::Jump>();
  1111. generator.switch_to_basic_block(false_block);
  1112. auto& end_block = generator.make_block();
  1113. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1114. if (m_alternate)
  1115. TRY(m_alternate->generate_bytecode(generator));
  1116. if (!generator.is_current_block_terminated())
  1117. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1118. if (true_block_jump)
  1119. true_block_jump->set_targets(Bytecode::Label { end_block }, {});
  1120. generator.switch_to_basic_block(end_block);
  1121. return {};
  1122. }
  1123. Bytecode::CodeGenerationErrorOr<void> ContinueStatement::generate_bytecode(Bytecode::Generator& generator) const
  1124. {
  1125. generator.perform_needed_unwinds<Bytecode::Op::Jump>();
  1126. generator.emit<Bytecode::Op::Jump>().set_targets(
  1127. generator.nearest_continuable_scope(),
  1128. {});
  1129. return {};
  1130. }
  1131. Bytecode::CodeGenerationErrorOr<void> DebuggerStatement::generate_bytecode(Bytecode::Generator&) const
  1132. {
  1133. return {};
  1134. }
  1135. Bytecode::CodeGenerationErrorOr<void> ConditionalExpression::generate_bytecode(Bytecode::Generator& generator) const
  1136. {
  1137. // test
  1138. // jump if_true (true) true (false) false
  1139. // true
  1140. // jump always (true) end
  1141. // false
  1142. // jump always (true) end
  1143. // end
  1144. auto& true_block = generator.make_block();
  1145. auto& false_block = generator.make_block();
  1146. auto& end_block = generator.make_block();
  1147. TRY(m_test->generate_bytecode(generator));
  1148. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1149. Bytecode::Label { true_block },
  1150. Bytecode::Label { false_block });
  1151. generator.switch_to_basic_block(true_block);
  1152. TRY(m_consequent->generate_bytecode(generator));
  1153. generator.emit<Bytecode::Op::Jump>().set_targets(
  1154. Bytecode::Label { end_block },
  1155. {});
  1156. generator.switch_to_basic_block(false_block);
  1157. TRY(m_alternate->generate_bytecode(generator));
  1158. generator.emit<Bytecode::Op::Jump>().set_targets(
  1159. Bytecode::Label { end_block },
  1160. {});
  1161. generator.switch_to_basic_block(end_block);
  1162. return {};
  1163. }
  1164. Bytecode::CodeGenerationErrorOr<void> SequenceExpression::generate_bytecode(Bytecode::Generator& generator) const
  1165. {
  1166. for (auto& expression : m_expressions)
  1167. TRY(expression.generate_bytecode(generator));
  1168. return {};
  1169. }
  1170. Bytecode::CodeGenerationErrorOr<void> TemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1171. {
  1172. auto string_reg = generator.allocate_register();
  1173. for (size_t i = 0; i < m_expressions.size(); i++) {
  1174. TRY(m_expressions[i].generate_bytecode(generator));
  1175. if (i == 0) {
  1176. generator.emit<Bytecode::Op::Store>(string_reg);
  1177. } else {
  1178. generator.emit<Bytecode::Op::ConcatString>(string_reg);
  1179. }
  1180. }
  1181. generator.emit<Bytecode::Op::Load>(string_reg);
  1182. return {};
  1183. }
  1184. Bytecode::CodeGenerationErrorOr<void> TaggedTemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1185. {
  1186. TRY(m_tag->generate_bytecode(generator));
  1187. auto tag_reg = generator.allocate_register();
  1188. generator.emit<Bytecode::Op::Store>(tag_reg);
  1189. Vector<Bytecode::Register> string_regs;
  1190. auto& expressions = m_template_literal->expressions();
  1191. for (size_t i = 0; i < expressions.size(); ++i) {
  1192. if (i % 2 != 0)
  1193. continue;
  1194. string_regs.append(generator.allocate_register());
  1195. }
  1196. size_t reg_index = 0;
  1197. for (size_t i = 0; i < expressions.size(); ++i) {
  1198. if (i % 2 != 0)
  1199. continue;
  1200. TRY(expressions[i].generate_bytecode(generator));
  1201. auto string_reg = string_regs[reg_index++];
  1202. generator.emit<Bytecode::Op::Store>(string_reg);
  1203. }
  1204. if (string_regs.is_empty()) {
  1205. generator.emit<Bytecode::Op::NewArray>();
  1206. } else {
  1207. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { string_regs.first(), string_regs.last() });
  1208. }
  1209. auto strings_reg = generator.allocate_register();
  1210. generator.emit<Bytecode::Op::Store>(strings_reg);
  1211. Vector<Bytecode::Register> argument_regs;
  1212. argument_regs.append(strings_reg);
  1213. for (size_t i = 0; i < expressions.size(); ++i) {
  1214. if (i % 2 == 0)
  1215. continue;
  1216. TRY(expressions[i].generate_bytecode(generator));
  1217. auto string_reg = generator.allocate_register();
  1218. generator.emit<Bytecode::Op::Store>(string_reg);
  1219. argument_regs.append(string_reg);
  1220. }
  1221. Vector<Bytecode::Register> raw_string_regs;
  1222. for ([[maybe_unused]] auto& raw_string : m_template_literal->raw_strings())
  1223. string_regs.append(generator.allocate_register());
  1224. reg_index = 0;
  1225. for (auto& raw_string : m_template_literal->raw_strings()) {
  1226. TRY(raw_string.generate_bytecode(generator));
  1227. auto raw_string_reg = string_regs[reg_index++];
  1228. generator.emit<Bytecode::Op::Store>(raw_string_reg);
  1229. raw_string_regs.append(raw_string_reg);
  1230. }
  1231. if (raw_string_regs.is_empty()) {
  1232. generator.emit<Bytecode::Op::NewArray>();
  1233. } else {
  1234. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { raw_string_regs.first(), raw_string_regs.last() });
  1235. }
  1236. auto raw_strings_reg = generator.allocate_register();
  1237. generator.emit<Bytecode::Op::Store>(raw_strings_reg);
  1238. generator.emit<Bytecode::Op::Load>(strings_reg);
  1239. generator.emit<Bytecode::Op::PutById>(raw_strings_reg, generator.intern_identifier("raw"));
  1240. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1241. auto this_reg = generator.allocate_register();
  1242. generator.emit<Bytecode::Op::Store>(this_reg);
  1243. generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_regs.size(), Bytecode::Op::Call::CallType::Call, tag_reg, this_reg, move(argument_regs));
  1244. return {};
  1245. }
  1246. Bytecode::CodeGenerationErrorOr<void> UpdateExpression::generate_bytecode(Bytecode::Generator& generator) const
  1247. {
  1248. TRY(generator.emit_load_from_reference(*m_argument));
  1249. Optional<Bytecode::Register> previous_value_for_postfix_reg;
  1250. if (!m_prefixed) {
  1251. previous_value_for_postfix_reg = generator.allocate_register();
  1252. generator.emit<Bytecode::Op::Store>(*previous_value_for_postfix_reg);
  1253. }
  1254. if (m_op == UpdateOp::Increment)
  1255. generator.emit<Bytecode::Op::Increment>();
  1256. else
  1257. generator.emit<Bytecode::Op::Decrement>();
  1258. TRY(generator.emit_store_to_reference(*m_argument));
  1259. if (!m_prefixed)
  1260. generator.emit<Bytecode::Op::Load>(*previous_value_for_postfix_reg);
  1261. return {};
  1262. }
  1263. Bytecode::CodeGenerationErrorOr<void> ThrowStatement::generate_bytecode(Bytecode::Generator& generator) const
  1264. {
  1265. TRY(m_argument->generate_bytecode(generator));
  1266. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1267. generator.emit<Bytecode::Op::Throw>();
  1268. return {};
  1269. }
  1270. Bytecode::CodeGenerationErrorOr<void> BreakStatement::generate_bytecode(Bytecode::Generator& generator) const
  1271. {
  1272. generator.perform_needed_unwinds<Bytecode::Op::Jump>(true);
  1273. generator.emit<Bytecode::Op::Jump>().set_targets(
  1274. generator.nearest_breakable_scope(),
  1275. {});
  1276. return {};
  1277. }
  1278. Bytecode::CodeGenerationErrorOr<void> TryStatement::generate_bytecode(Bytecode::Generator& generator) const
  1279. {
  1280. auto& saved_block = generator.current_block();
  1281. Optional<Bytecode::Label> handler_target;
  1282. Optional<Bytecode::Label> finalizer_target;
  1283. Bytecode::BasicBlock* next_block { nullptr };
  1284. if (m_finalizer) {
  1285. auto& finalizer_block = generator.make_block();
  1286. generator.switch_to_basic_block(finalizer_block);
  1287. TRY(m_finalizer->generate_bytecode(generator));
  1288. if (!generator.is_current_block_terminated()) {
  1289. next_block = &generator.make_block();
  1290. auto next_target = Bytecode::Label { *next_block };
  1291. generator.emit<Bytecode::Op::ContinuePendingUnwind>(next_target);
  1292. }
  1293. finalizer_target = Bytecode::Label { finalizer_block };
  1294. }
  1295. if (m_handler) {
  1296. auto& handler_block = generator.make_block();
  1297. generator.switch_to_basic_block(handler_block);
  1298. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  1299. TRY(m_handler->parameter().visit(
  1300. [&](FlyString const& parameter) -> Bytecode::CodeGenerationErrorOr<void> {
  1301. if (!parameter.is_empty()) {
  1302. auto parameter_identifier = generator.intern_identifier(parameter);
  1303. generator.register_binding(parameter_identifier);
  1304. generator.emit<Bytecode::Op::CreateVariable>(parameter_identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1305. generator.emit<Bytecode::Op::SetVariable>(parameter_identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1306. }
  1307. return {};
  1308. },
  1309. [&](NonnullRefPtr<BindingPattern> const&) -> Bytecode::CodeGenerationErrorOr<void> {
  1310. // FIXME: Implement this path when the above DeclarativeEnvironment issue is dealt with.
  1311. return Bytecode::CodeGenerationError {
  1312. this,
  1313. "Unimplemented catch argument: BindingPattern"sv,
  1314. };
  1315. }));
  1316. TRY(m_handler->body().generate_bytecode(generator));
  1317. handler_target = Bytecode::Label { handler_block };
  1318. generator.end_variable_scope();
  1319. if (!generator.is_current_block_terminated()) {
  1320. if (m_finalizer) {
  1321. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1322. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1323. } else {
  1324. VERIFY(!next_block);
  1325. next_block = &generator.make_block();
  1326. auto next_target = Bytecode::Label { *next_block };
  1327. generator.emit<Bytecode::Op::Jump>(next_target);
  1328. }
  1329. }
  1330. }
  1331. auto& target_block = generator.make_block();
  1332. generator.switch_to_basic_block(saved_block);
  1333. generator.emit<Bytecode::Op::EnterUnwindContext>(Bytecode::Label { target_block }, handler_target, finalizer_target);
  1334. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1335. generator.switch_to_basic_block(target_block);
  1336. TRY(m_block->generate_bytecode(generator));
  1337. if (!generator.is_current_block_terminated()) {
  1338. if (m_finalizer) {
  1339. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1340. } else {
  1341. auto& block = generator.make_block();
  1342. generator.emit<Bytecode::Op::FinishUnwind>(Bytecode::Label { block });
  1343. next_block = &block;
  1344. }
  1345. }
  1346. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1347. generator.switch_to_basic_block(next_block ? *next_block : saved_block);
  1348. return {};
  1349. }
  1350. Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_bytecode(Bytecode::Generator& generator) const
  1351. {
  1352. auto discriminant_reg = generator.allocate_register();
  1353. TRY(m_discriminant->generate_bytecode(generator));
  1354. generator.emit<Bytecode::Op::Store>(discriminant_reg);
  1355. Vector<Bytecode::BasicBlock&> case_blocks;
  1356. Bytecode::BasicBlock* default_block { nullptr };
  1357. Bytecode::BasicBlock* next_test_block = &generator.make_block();
  1358. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_test_block }, {});
  1359. for (auto& switch_case : m_cases) {
  1360. auto& case_block = generator.make_block();
  1361. if (switch_case.test()) {
  1362. generator.switch_to_basic_block(*next_test_block);
  1363. TRY(switch_case.test()->generate_bytecode(generator));
  1364. generator.emit<Bytecode::Op::StrictlyEquals>(discriminant_reg);
  1365. next_test_block = &generator.make_block();
  1366. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { case_block }, Bytecode::Label { *next_test_block });
  1367. } else {
  1368. default_block = &case_block;
  1369. }
  1370. case_blocks.append(case_block);
  1371. }
  1372. generator.switch_to_basic_block(*next_test_block);
  1373. auto& end_block = generator.make_block();
  1374. if (default_block != nullptr) {
  1375. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *default_block }, {});
  1376. } else {
  1377. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1378. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1379. }
  1380. auto current_block = case_blocks.begin();
  1381. generator.begin_breakable_scope(Bytecode::Label { end_block });
  1382. for (auto& switch_case : m_cases) {
  1383. generator.switch_to_basic_block(*current_block);
  1384. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1385. for (auto& statement : switch_case.children()) {
  1386. TRY(statement.generate_bytecode(generator));
  1387. if (generator.is_current_block_terminated())
  1388. break;
  1389. }
  1390. if (!generator.is_current_block_terminated()) {
  1391. auto next_block = current_block;
  1392. next_block++;
  1393. if (next_block.is_end()) {
  1394. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1395. } else {
  1396. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_block }, {});
  1397. }
  1398. }
  1399. current_block++;
  1400. }
  1401. generator.end_breakable_scope();
  1402. generator.switch_to_basic_block(end_block);
  1403. return {};
  1404. }
  1405. Bytecode::CodeGenerationErrorOr<void> ClassDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1406. {
  1407. TRY(m_class_expression->generate_bytecode(generator));
  1408. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(m_class_expression.ptr()->name()), Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1409. return {};
  1410. }
  1411. Bytecode::CodeGenerationErrorOr<void> ClassExpression::generate_bytecode(Bytecode::Generator& generator) const
  1412. {
  1413. generator.emit<Bytecode::Op::NewClass>(*this);
  1414. return {};
  1415. }
  1416. Bytecode::CodeGenerationErrorOr<void> ThisExpression::generate_bytecode(Bytecode::Generator& generator) const
  1417. {
  1418. generator.emit<Bytecode::Op::ResolveThisBinding>();
  1419. return {};
  1420. }
  1421. Bytecode::CodeGenerationErrorOr<void> AwaitExpression::generate_bytecode(Bytecode::Generator& generator) const
  1422. {
  1423. VERIFY(generator.is_in_async_function());
  1424. // Transform `await expr` to `yield expr`
  1425. TRY(m_argument->generate_bytecode(generator));
  1426. auto& continuation_block = generator.make_block();
  1427. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1428. generator.switch_to_basic_block(continuation_block);
  1429. return {};
  1430. }
  1431. Bytecode::CodeGenerationErrorOr<void> WithStatement::generate_bytecode(Bytecode::Generator& generator) const
  1432. {
  1433. TRY(m_object->generate_bytecode(generator));
  1434. generator.emit<Bytecode::Op::EnterObjectEnvironment>();
  1435. // EnterObjectEnvironment sets the running execution context's lexical_environment to a new Object Environment.
  1436. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1437. TRY(m_body->generate_bytecode(generator));
  1438. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1439. if (!generator.is_current_block_terminated())
  1440. generator.emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  1441. return {};
  1442. }
  1443. enum class LHSKind {
  1444. Assignment,
  1445. VarBinding,
  1446. LexicalBinding,
  1447. };
  1448. enum class IterationKind {
  1449. Enumerate,
  1450. Iterate,
  1451. AsyncIterate,
  1452. };
  1453. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  1454. struct ForInOfHeadEvaluationResult {
  1455. bool is_destructuring { false };
  1456. LHSKind lhs_kind { LHSKind::Assignment };
  1457. };
  1458. static Bytecode::CodeGenerationErrorOr<ForInOfHeadEvaluationResult> for_in_of_head_evaluation(Bytecode::Generator& generator, IterationKind iteration_kind, Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> const& lhs, NonnullRefPtr<ASTNode> const& rhs)
  1459. {
  1460. ForInOfHeadEvaluationResult result {};
  1461. if (auto* ast_ptr = lhs.get_pointer<NonnullRefPtr<ASTNode>>(); ast_ptr && is<VariableDeclaration>(**ast_ptr)) {
  1462. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  1463. // ForInOfStatement : for ( var ForBinding in Expression ) Statement
  1464. // ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  1465. // ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  1466. // ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  1467. auto& variable_declaration = static_cast<VariableDeclaration const&>(**ast_ptr);
  1468. result.is_destructuring = variable_declaration.declarations().first().target().has<NonnullRefPtr<BindingPattern>>();
  1469. result.lhs_kind = variable_declaration.is_lexical_declaration() ? LHSKind::LexicalBinding : LHSKind::VarBinding;
  1470. // 1. Let oldEnv be the running execution context's LexicalEnvironment.
  1471. // NOTE: 'uninitializedBoundNames' refers to the lexical bindings (i.e. Const/Let) present in the second and last form.
  1472. // 2. If uninitializedBoundNames is not an empty List, then
  1473. bool entered_lexical_scope = false;
  1474. if (variable_declaration.declaration_kind() != DeclarationKind::Var) {
  1475. entered_lexical_scope = true;
  1476. // a. Assert: uninitializedBoundNames has no duplicate entries.
  1477. // b. Let newEnv be NewDeclarativeEnvironment(oldEnv).
  1478. generator.begin_variable_scope();
  1479. // c. For each String name of uninitializedBoundNames, do
  1480. variable_declaration.for_each_bound_name([&](auto const& name) {
  1481. // i. Perform ! newEnv.CreateMutableBinding(name, false).
  1482. auto identifier = generator.intern_identifier(name);
  1483. generator.register_binding(identifier);
  1484. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1485. });
  1486. // d. Set the running execution context's LexicalEnvironment to newEnv.
  1487. // NOTE: Done by CreateEnvironment.
  1488. }
  1489. // 3. Let exprRef be the result of evaluating expr.
  1490. TRY(rhs->generate_bytecode(generator));
  1491. // 4. Set the running execution context's LexicalEnvironment to oldEnv.
  1492. if (entered_lexical_scope)
  1493. generator.end_variable_scope();
  1494. // 5. Let exprValue be ? GetValue(exprRef).
  1495. // NOTE: No need to store this anywhere.
  1496. // 6. If iterationKind is enumerate, then
  1497. if (iteration_kind == IterationKind::Enumerate) {
  1498. // a. If exprValue is undefined or null, then
  1499. auto& nullish_block = generator.make_block();
  1500. auto& continuation_block = generator.make_block();
  1501. auto& jump = generator.emit<Bytecode::Op::JumpNullish>();
  1502. jump.set_targets(Bytecode::Label { nullish_block }, Bytecode::Label { continuation_block });
  1503. // i. Return Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  1504. generator.switch_to_basic_block(nullish_block);
  1505. generator.perform_needed_unwinds<Bytecode::Op::Jump>(true);
  1506. generator.emit<Bytecode::Op::Jump>().set_targets(generator.nearest_breakable_scope(), {});
  1507. generator.switch_to_basic_block(continuation_block);
  1508. // b. Let obj be ! ToObject(exprValue).
  1509. // NOTE: GetObjectPropertyIterator does this.
  1510. // c. Let iterator be EnumerateObjectProperties(obj).
  1511. // d. Let nextMethod be ! GetV(iterator, "next").
  1512. // e. Return the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
  1513. generator.emit<Bytecode::Op::GetObjectPropertyIterator>();
  1514. }
  1515. // 7. Else,
  1516. else {
  1517. // a. Assert: iterationKind is iterate or async-iterate.
  1518. // b. If iterationKind is async-iterate, let iteratorHint be async.
  1519. if (iteration_kind == IterationKind::AsyncIterate) {
  1520. return Bytecode::CodeGenerationError {
  1521. rhs.ptr(),
  1522. "Unimplemented iteration mode: AsyncIterate"sv,
  1523. };
  1524. }
  1525. // c. Else, let iteratorHint be sync.
  1526. // d. Return ? GetIterator(exprValue, iteratorHint).
  1527. generator.emit<Bytecode::Op::GetIterator>();
  1528. }
  1529. } else {
  1530. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  1531. // ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  1532. // ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  1533. // Skip everything except steps 3, 5 and 7 (see above true branch for listing).
  1534. result.lhs_kind = LHSKind::Assignment;
  1535. // 3. Let exprRef be the result of evaluating expr.
  1536. TRY(rhs->generate_bytecode(generator));
  1537. // 5. Let exprValue be ? GetValue(exprRef).
  1538. // NOTE: No need to store this anywhere.
  1539. // a. Assert: iterationKind is iterate or async-iterate.
  1540. // b. If iterationKind is async-iterate, let iteratorHint be async.
  1541. if (iteration_kind == IterationKind::AsyncIterate) {
  1542. return Bytecode::CodeGenerationError {
  1543. rhs.ptr(),
  1544. "Unimplemented iteration mode: AsyncIterate"sv,
  1545. };
  1546. }
  1547. // c. Else, let iteratorHint be sync.
  1548. // d. Return ? GetIterator(exprValue, iteratorHint).
  1549. generator.emit<Bytecode::Op::GetIterator>();
  1550. }
  1551. return result;
  1552. }
  1553. // 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
  1554. static Bytecode::CodeGenerationErrorOr<void> for_in_of_body_evaluation(Bytecode::Generator& generator, ASTNode const& node, Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> const& lhs, ASTNode const& body, ForInOfHeadEvaluationResult const& head_result, Bytecode::BasicBlock& loop_end, Bytecode::BasicBlock& loop_update)
  1555. {
  1556. auto iterator_register = generator.allocate_register();
  1557. generator.emit<Bytecode::Op::Store>(iterator_register);
  1558. // FIXME: Implement this
  1559. // 1. If iteratorKind is not present, set iteratorKind to sync.
  1560. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  1561. bool has_lexical_binding = false;
  1562. // 3. Let V be undefined.
  1563. // NOTE: We don't need 'V' as the resulting value will naturally flow through via the accumulator register.
  1564. // 4. Let destructuring be IsDestructuring of lhs.
  1565. auto destructuring = head_result.is_destructuring;
  1566. // 5. If destructuring is true and if lhsKind is assignment, then
  1567. if (destructuring) {
  1568. // a. Assert: lhs is a LeftHandSideExpression.
  1569. // b. Let assignmentPattern be the AssignmentPattern that is covered by lhs.
  1570. // FIXME: Implement this.
  1571. return Bytecode::CodeGenerationError {
  1572. &node,
  1573. "Unimplemented: destructuring in for-in/of"sv,
  1574. };
  1575. }
  1576. // 6. Repeat,
  1577. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_update });
  1578. generator.switch_to_basic_block(loop_update);
  1579. // a. Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
  1580. generator.emit<Bytecode::Op::Load>(iterator_register);
  1581. generator.emit<Bytecode::Op::IteratorNext>();
  1582. // FIXME: Implement this:
  1583. // b. If iteratorKind is async, set nextResult to ? Await(nextResult).
  1584. // c. If Type(nextResult) is not Object, throw a TypeError exception.
  1585. // NOTE: IteratorComplete already does this.
  1586. // d. Let done be ? IteratorComplete(nextResult).
  1587. auto iterator_result_register = generator.allocate_register();
  1588. generator.emit<Bytecode::Op::Store>(iterator_result_register);
  1589. generator.emit<Bytecode::Op::IteratorResultDone>();
  1590. // e. If done is true, return V.
  1591. auto& loop_continue = generator.make_block();
  1592. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { loop_end }, Bytecode::Label { loop_continue });
  1593. generator.switch_to_basic_block(loop_continue);
  1594. // f. Let nextValue be ? IteratorValue(nextResult).
  1595. generator.emit<Bytecode::Op::Load>(iterator_result_register);
  1596. generator.emit<Bytecode::Op::IteratorResultValue>();
  1597. // g. If lhsKind is either assignment or varBinding, then
  1598. if (head_result.lhs_kind != LHSKind::LexicalBinding) {
  1599. // i. If destructuring is false, then
  1600. if (!destructuring) {
  1601. // 1. Let lhsRef be the result of evaluating lhs. (It may be evaluated repeatedly.)
  1602. // NOTE: We're skipping all the completion stuff that the spec does, as the unwinding mechanism will take case of doing that.
  1603. if (head_result.lhs_kind == LHSKind::VarBinding) {
  1604. auto& declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode>>());
  1605. VERIFY(declaration.declarations().size() == 1);
  1606. TRY(assign_accumulator_to_variable_declarator(generator, declaration.declarations().first(), declaration));
  1607. } else {
  1608. TRY(generator.emit_store_to_reference(*lhs.get<NonnullRefPtr<ASTNode>>()));
  1609. }
  1610. }
  1611. }
  1612. // h. Else,
  1613. else {
  1614. // i. Assert: lhsKind is lexicalBinding.
  1615. // ii. Assert: lhs is a ForDeclaration.
  1616. // iii. Let iterationEnv be NewDeclarativeEnvironment(oldEnv).
  1617. // iv. Perform ForDeclarationBindingInstantiation of lhs with argument iterationEnv.
  1618. // v. Set the running execution context's LexicalEnvironment to iterationEnv.
  1619. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical);
  1620. has_lexical_binding = true;
  1621. // 14.7.5.4 Runtime Semantics: ForDeclarationBindingInstantiation, https://tc39.es/ecma262/#sec-runtime-semantics-fordeclarationbindinginstantiation
  1622. // 1. Assert: environment is a declarative Environment Record.
  1623. // NOTE: We just made it.
  1624. auto& variable_declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode>>());
  1625. // 2. For each element name of the BoundNames of ForBinding, do
  1626. variable_declaration.for_each_bound_name([&](auto const& name) {
  1627. auto identifier = generator.intern_identifier(name);
  1628. generator.register_binding(identifier, Bytecode::Generator::BindingMode::Lexical);
  1629. // a. If IsConstantDeclaration of LetOrConst is true, then
  1630. if (variable_declaration.is_constant_declaration()) {
  1631. // i. Perform ! environment.CreateImmutableBinding(name, true).
  1632. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  1633. }
  1634. // b. Else,
  1635. else {
  1636. // i. Perform ! environment.CreateMutableBinding(name, false).
  1637. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1638. }
  1639. });
  1640. // 3. Return unused.
  1641. // NOTE: No need to do that as we've inlined this.
  1642. // vi. If destructuring is false, then
  1643. if (!destructuring) {
  1644. // 1. Assert: lhs binds a single name.
  1645. // 2. Let lhsName be the sole element of BoundNames of lhs.
  1646. auto lhs_name = variable_declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->string();
  1647. // 3. Let lhsRef be ! ResolveBinding(lhsName).
  1648. // NOTE: We're skipping all the completion stuff that the spec does, as the unwinding mechanism will take case of doing that.
  1649. auto identifier = generator.intern_identifier(lhs_name);
  1650. generator.emit<Bytecode::Op::SetVariable>(identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Lexical);
  1651. }
  1652. }
  1653. // i. If destructuring is false, then
  1654. if (!destructuring) {
  1655. // i. If lhsRef is an abrupt completion, then
  1656. // 1. Let status be lhsRef.
  1657. // ii. Else if lhsKind is lexicalBinding, then
  1658. // 1. Let status be Completion(InitializeReferencedBinding(lhsRef, nextValue)).
  1659. // iii. Else,
  1660. // 1. Let status be Completion(PutValue(lhsRef, nextValue)).
  1661. // NOTE: This is performed above.
  1662. }
  1663. // j. Else,
  1664. else {
  1665. // FIXME: Implement destructuring
  1666. // i. If lhsKind is assignment, then
  1667. // 1. Let status be Completion(DestructuringAssignmentEvaluation of assignmentPattern with argument nextValue).
  1668. // ii. Else if lhsKind is varBinding, then
  1669. // 1. Assert: lhs is a ForBinding.
  1670. // 2. Let status be Completion(BindingInitialization of lhs with arguments nextValue and undefined).
  1671. // iii. Else,
  1672. // 1. Assert: lhsKind is lexicalBinding.
  1673. // 2. Assert: lhs is a ForDeclaration.
  1674. // 3. Let status be Completion(ForDeclarationBindingInitialization of lhs with arguments nextValue and iterationEnv).
  1675. return Bytecode::CodeGenerationError {
  1676. &node,
  1677. "Unimplemented: destructuring in for-in/of"sv,
  1678. };
  1679. }
  1680. // FIXME: Implement iteration closure.
  1681. // k. If status is an abrupt completion, then
  1682. // i. Set the running execution context's LexicalEnvironment to oldEnv.
  1683. // ii. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  1684. // iii. If iterationKind is enumerate, then
  1685. // 1. Return ? status.
  1686. // iv. Else,
  1687. // 1. Assert: iterationKind is iterate.
  1688. // 2. Return ? IteratorClose(iteratorRecord, status).
  1689. // l. Let result be the result of evaluating stmt.
  1690. TRY(body.generate_bytecode(generator));
  1691. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  1692. if (has_lexical_binding)
  1693. generator.end_variable_scope();
  1694. generator.end_continuable_scope();
  1695. generator.end_breakable_scope();
  1696. // NOTE: If we're here, then the loop definitely continues.
  1697. // n. If LoopContinues(result, labelSet) is false, then
  1698. // i. If iterationKind is enumerate, then
  1699. // 1. Return ? UpdateEmpty(result, V).
  1700. // ii. Else,
  1701. // 1. Assert: iterationKind is iterate.
  1702. // 2. Set status to Completion(UpdateEmpty(result, V)).
  1703. // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  1704. // 4. Return ? IteratorClose(iteratorRecord, status).
  1705. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  1706. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { loop_update }, {});
  1707. generator.switch_to_basic_block(loop_end);
  1708. return {};
  1709. }
  1710. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  1711. Bytecode::CodeGenerationErrorOr<void> ForInStatement::generate_bytecode(Bytecode::Generator& generator) const
  1712. {
  1713. auto& loop_end = generator.make_block();
  1714. auto& loop_update = generator.make_block();
  1715. generator.begin_breakable_scope(Bytecode::Label { loop_end });
  1716. generator.begin_continuable_scope(Bytecode::Label { loop_update });
  1717. auto head_result = TRY(for_in_of_head_evaluation(generator, IterationKind::Enumerate, m_lhs, m_rhs));
  1718. // Now perform the rest of ForInOfLoopEvaluation, given that the accumulator holds the iterator we're supposed to iterate over.
  1719. return for_in_of_body_evaluation(generator, *this, m_lhs, body(), head_result, loop_end, loop_update);
  1720. }
  1721. Bytecode::CodeGenerationErrorOr<void> ForOfStatement::generate_bytecode(Bytecode::Generator& generator) const
  1722. {
  1723. auto& loop_end = generator.make_block();
  1724. auto& loop_update = generator.make_block();
  1725. generator.begin_breakable_scope(Bytecode::Label { loop_end });
  1726. generator.begin_continuable_scope(Bytecode::Label { loop_update });
  1727. auto head_result = TRY(for_in_of_head_evaluation(generator, IterationKind::Iterate, m_lhs, m_rhs));
  1728. // Now perform the rest of ForInOfLoopEvaluation, given that the accumulator holds the iterator we're supposed to iterate over.
  1729. return for_in_of_body_evaluation(generator, *this, m_lhs, body(), head_result, loop_end, loop_update);
  1730. }
  1731. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  1732. Bytecode::CodeGenerationErrorOr<void> MetaProperty::generate_bytecode(Bytecode::Generator& generator) const
  1733. {
  1734. // NewTarget : new . target
  1735. if (m_type == MetaProperty::Type::NewTarget) {
  1736. // 1. Return GetNewTarget().
  1737. generator.emit<Bytecode::Op::GetNewTarget>();
  1738. return {};
  1739. }
  1740. // ImportMeta : import . meta
  1741. if (m_type == MetaProperty::Type::ImportMeta) {
  1742. return Bytecode::CodeGenerationError {
  1743. this,
  1744. "Unimplemented meta property: import.meta"sv,
  1745. };
  1746. }
  1747. VERIFY_NOT_REACHED();
  1748. }
  1749. }