ASTCodegen.cpp 101 KB

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