ASTCodegen.cpp 104 KB

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