ASTCodegen.cpp 95 KB

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