ASTCodegen.cpp 94 KB

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