ASTCodegen.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Gunnar Beutner <gbeutner@serenityos.org>
  5. * Copyright (c) 2021, Marcin Gasperowicz <xnooga@gmail.com>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Format.h>
  10. #include <LibJS/AST.h>
  11. #include <LibJS/Bytecode/Generator.h>
  12. #include <LibJS/Bytecode/Instruction.h>
  13. #include <LibJS/Bytecode/Op.h>
  14. #include <LibJS/Bytecode/Register.h>
  15. #include <LibJS/Bytecode/StringTable.h>
  16. #include <LibJS/Runtime/Environment.h>
  17. namespace JS {
  18. Bytecode::CodeGenerationErrorOr<void> ASTNode::generate_bytecode(Bytecode::Generator&) const
  19. {
  20. return Bytecode::CodeGenerationError {
  21. this,
  22. "Missing generate_bytecode()"sv,
  23. };
  24. }
  25. Bytecode::CodeGenerationErrorOr<void> ScopeNode::generate_bytecode(Bytecode::Generator& generator) const
  26. {
  27. Optional<Bytecode::CodeGenerationError> maybe_error;
  28. size_t pushed_scope_count = 0;
  29. auto const failing_completion = Completion(Completion::Type::Throw, {}, {});
  30. if (is<BlockStatement>(*this) || is<SwitchStatement>(*this)) {
  31. // Perform the steps of BlockDeclarationInstantiation.
  32. if (has_lexical_declarations()) {
  33. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  34. pushed_scope_count++;
  35. }
  36. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  37. auto is_constant_declaration = declaration.is_constant_declaration();
  38. declaration.for_each_bound_name([&](auto const& name) {
  39. auto index = generator.intern_identifier(name);
  40. if (is_constant_declaration || !generator.has_binding(index)) {
  41. generator.register_binding(index);
  42. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration);
  43. }
  44. });
  45. if (is<FunctionDeclaration>(declaration)) {
  46. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  47. auto const& name = function_declaration.name();
  48. auto index = generator.intern_identifier(name);
  49. generator.emit<Bytecode::Op::NewFunction>(function_declaration);
  50. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  51. }
  52. return {};
  53. });
  54. } else if (is<Program>(*this)) {
  55. // Perform the steps of GlobalDeclarationInstantiation.
  56. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Global, Bytecode::Generator::SurroundingScopeKind::Global);
  57. pushed_scope_count++;
  58. // 1. Let lexNames be the LexicallyDeclaredNames of script.
  59. // 2. Let varNames be the VarDeclaredNames of script.
  60. // 3. For each element name of lexNames, do
  61. (void)for_each_lexically_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
  62. auto identifier = generator.intern_identifier(name);
  63. // a. If env.HasVarDeclaration(name) is true, throw a SyntaxError exception.
  64. // b. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  65. if (generator.has_binding(identifier)) {
  66. // FIXME: Throw an actual SyntaxError instance.
  67. generator.emit<Bytecode::Op::NewString>(generator.intern_string(String::formatted("SyntaxError: toplevel variable already declared: {}", name)));
  68. generator.emit<Bytecode::Op::Throw>();
  69. return {};
  70. }
  71. // FIXME: c. If hasRestrictedGlobalProperty is true, throw a SyntaxError exception.
  72. // d. If hasRestrictedGlobal is true, throw a SyntaxError exception.
  73. return {};
  74. });
  75. // 4. For each element name of varNames, do
  76. (void)for_each_var_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
  77. auto identifier = generator.intern_identifier(name);
  78. // a. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  79. if (generator.has_binding(identifier)) {
  80. // FIXME: Throw an actual SyntaxError instance.
  81. generator.emit<Bytecode::Op::NewString>(generator.intern_string(String::formatted("SyntaxError: toplevel variable already declared: {}", name)));
  82. generator.emit<Bytecode::Op::Throw>();
  83. }
  84. return {};
  85. });
  86. // 5. Let varDeclarations be the VarScopedDeclarations of script.
  87. // 6. Let functionsToInitialize be a new empty List.
  88. Vector<FunctionDeclaration const&> functions_to_initialize;
  89. // 7. Let declaredFunctionNames be a new empty List.
  90. HashTable<FlyString> declared_function_names;
  91. // 8. For each element d of varDeclarations, in reverse List order, do
  92. (void)for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) -> ThrowCompletionOr<void> {
  93. // a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then
  94. // i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
  95. // Note: This is checked in for_each_var_function_declaration_in_reverse_order.
  96. // ii. NOTE: If there are multiple function declarations for the same name, the last declaration is used.
  97. // iii. Let fn be the sole element of the BoundNames of d.
  98. // iv. If fn is not an element of declaredFunctionNames, then
  99. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  100. return {};
  101. // FIXME: 1. Let fnDefinable be ? env.CanDeclareGlobalFunction(fn).
  102. // FIXME: 2. If fnDefinable is false, throw a TypeError exception.
  103. // 3. Append fn to declaredFunctionNames.
  104. // Note: Already done in step iv. above.
  105. // 4. Insert d as the first element of functionsToInitialize.
  106. functions_to_initialize.prepend(function);
  107. return {};
  108. });
  109. // 9. Let declaredVarNames be a new empty List.
  110. HashTable<FlyString> declared_var_names;
  111. // 10. For each element d of varDeclarations, do
  112. (void)for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
  113. // a. If d is a VariableDeclaration, a ForBinding, or a BindingIdentifier, then
  114. // Note: This is done in for_each_var_scoped_variable_declaration.
  115. // i. For each String vn of the BoundNames of d, do
  116. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  117. // 1. If vn is not an element of declaredFunctionNames, then
  118. if (declared_function_names.contains(name))
  119. return {};
  120. // FIXME: a. Let vnDefinable be ? env.CanDeclareGlobalVar(vn).
  121. // FIXME: b. If vnDefinable is false, throw a TypeError exception.
  122. // c. If vn is not an element of declaredVarNames, then
  123. // i. Append vn to declaredVarNames.
  124. declared_var_names.set(name);
  125. return {};
  126. });
  127. });
  128. // 11. NOTE: No abnormal terminations occur after this algorithm step if the global object is an ordinary object. However, if the global object is a Proxy exotic object it may exhibit behaviours that cause abnormal terminations in some of the following steps.
  129. // 12. NOTE: Annex B.3.2.2 adds additional steps at this point.
  130. // 12. Let strict be IsStrict of script.
  131. // 13. If strict is false, then
  132. if (!verify_cast<Program>(*this).is_strict_mode()) {
  133. // a. Let declaredFunctionOrVarNames be the list-concatenation of declaredFunctionNames and declaredVarNames.
  134. // b. For each FunctionDeclaration f that is directly contained in the StatementList of a Block, CaseClause, or DefaultClause Contained within script, do
  135. (void)for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  136. // i. Let F be StringValue of the BindingIdentifier of f.
  137. auto& function_name = function_declaration.name();
  138. // ii. If replacing the FunctionDeclaration f with a VariableStatement that has F as a BindingIdentifier would not produce any Early Errors for script, then
  139. // Note: This step is already performed during parsing and for_each_function_hoistable_with_annexB_extension so this always passes here.
  140. // 1. If env.HasLexicalDeclaration(F) is false, then
  141. auto index = generator.intern_identifier(function_name);
  142. if (generator.has_binding(index, Bytecode::Generator::BindingMode::Lexical))
  143. return;
  144. // FIXME: a. Let fnDefinable be ? env.CanDeclareGlobalVar(F).
  145. // b. If fnDefinable is true, then
  146. // i. NOTE: A var binding for F is only instantiated here if it is neither a VarDeclaredName nor the name of another FunctionDeclaration.
  147. // ii. If declaredFunctionOrVarNames does not contain F, then
  148. if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
  149. // i. Perform ? env.CreateGlobalVarBinding(F, false).
  150. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Var, false);
  151. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  152. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Var);
  153. // ii. Append F to declaredFunctionOrVarNames.
  154. declared_function_names.set(function_name);
  155. }
  156. // iii. When the FunctionDeclaration f is evaluated, perform the following steps in place of the FunctionDeclaration Evaluation algorithm provided in 15.2.6:
  157. // i. Let genv be the running execution context's VariableEnvironment.
  158. // ii. Let benv be the running execution context's LexicalEnvironment.
  159. // iii. Let fobj be ! benv.GetBindingValue(F, false).
  160. // iv. Perform ? genv.SetMutableBinding(F, fobj, false).
  161. // v. Return NormalCompletion(empty).
  162. function_declaration.set_should_do_additional_annexB_steps();
  163. });
  164. }
  165. // 15. For each element d of lexDeclarations, do
  166. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  167. // a. NOTE: Lexically declared names are only instantiated here but not initialized.
  168. // b. For each element dn of the BoundNames of d, do
  169. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  170. auto identifier = generator.intern_identifier(name);
  171. // i. If IsConstantDeclaration of d is true, then
  172. generator.register_binding(identifier);
  173. if (declaration.is_constant_declaration()) {
  174. // 1. Perform ? env.CreateImmutableBinding(dn, true).
  175. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  176. } else {
  177. // ii. Else,
  178. // 1. Perform ? env.CreateMutableBinding(dn, false).
  179. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  180. }
  181. return {};
  182. });
  183. });
  184. // 16. For each Parse Node f of functionsToInitialize, do
  185. for (auto& function_declaration : functions_to_initialize) {
  186. // FIXME: Do this more correctly.
  187. // a. Let fn be the sole element of the BoundNames of f.
  188. // b. Let fo be InstantiateFunctionObject of f with arguments env and privateEnv.
  189. generator.emit<Bytecode::Op::NewFunction>(function_declaration);
  190. // c. Perform ? env.CreateGlobalFunctionBinding(fn, fo, false).
  191. auto const& name = function_declaration.name();
  192. auto index = generator.intern_identifier(name);
  193. if (!generator.has_binding(index)) {
  194. generator.register_binding(index, Bytecode::Generator::BindingMode::Var);
  195. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, false);
  196. }
  197. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  198. }
  199. // 17. For each String vn of declaredVarNames, do
  200. // a. Perform ? env.CreateGlobalVarBinding(vn, false).
  201. for (auto& var_name : declared_var_names)
  202. generator.register_binding(generator.intern_identifier(var_name), Bytecode::Generator::BindingMode::Var);
  203. } else {
  204. // Perform the steps of FunctionDeclarationInstantiation.
  205. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Var, Bytecode::Generator::SurroundingScopeKind::Function);
  206. pushed_scope_count++;
  207. if (has_lexical_declarations()) {
  208. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Function);
  209. pushed_scope_count++;
  210. }
  211. // FIXME: Implement this boi correctly.
  212. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  213. auto is_constant_declaration = declaration.is_constant_declaration();
  214. declaration.for_each_bound_name([&](auto const& name) {
  215. auto index = generator.intern_identifier(name);
  216. if (is_constant_declaration || !generator.has_binding(index)) {
  217. generator.register_binding(index);
  218. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration);
  219. }
  220. });
  221. if (is<FunctionDeclaration>(declaration)) {
  222. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  223. if (auto result = function_declaration.generate_bytecode(generator); result.is_error()) {
  224. maybe_error = result.release_error();
  225. // To make `for_each_lexically_scoped_declaration` happy.
  226. return failing_completion;
  227. }
  228. auto const& name = function_declaration.name();
  229. auto index = generator.intern_identifier(name);
  230. if (!generator.has_binding(index)) {
  231. generator.register_binding(index);
  232. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, false);
  233. }
  234. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::InitializeOrSet);
  235. }
  236. return {};
  237. });
  238. }
  239. if (maybe_error.has_value())
  240. return maybe_error.release_value();
  241. for (auto& child : children()) {
  242. TRY(child.generate_bytecode(generator));
  243. if (generator.is_current_block_terminated())
  244. break;
  245. }
  246. for (size_t i = 0; i < pushed_scope_count; ++i)
  247. generator.end_variable_scope();
  248. return {};
  249. }
  250. Bytecode::CodeGenerationErrorOr<void> EmptyStatement::generate_bytecode(Bytecode::Generator&) const
  251. {
  252. return {};
  253. }
  254. Bytecode::CodeGenerationErrorOr<void> ExpressionStatement::generate_bytecode(Bytecode::Generator& generator) const
  255. {
  256. return m_expression->generate_bytecode(generator);
  257. }
  258. Bytecode::CodeGenerationErrorOr<void> BinaryExpression::generate_bytecode(Bytecode::Generator& generator) const
  259. {
  260. TRY(m_lhs->generate_bytecode(generator));
  261. auto lhs_reg = generator.allocate_register();
  262. generator.emit<Bytecode::Op::Store>(lhs_reg);
  263. TRY(m_rhs->generate_bytecode(generator));
  264. switch (m_op) {
  265. case BinaryOp::Addition:
  266. generator.emit<Bytecode::Op::Add>(lhs_reg);
  267. break;
  268. case BinaryOp::Subtraction:
  269. generator.emit<Bytecode::Op::Sub>(lhs_reg);
  270. break;
  271. case BinaryOp::Multiplication:
  272. generator.emit<Bytecode::Op::Mul>(lhs_reg);
  273. break;
  274. case BinaryOp::Division:
  275. generator.emit<Bytecode::Op::Div>(lhs_reg);
  276. break;
  277. case BinaryOp::Modulo:
  278. generator.emit<Bytecode::Op::Mod>(lhs_reg);
  279. break;
  280. case BinaryOp::Exponentiation:
  281. generator.emit<Bytecode::Op::Exp>(lhs_reg);
  282. break;
  283. case BinaryOp::GreaterThan:
  284. generator.emit<Bytecode::Op::GreaterThan>(lhs_reg);
  285. break;
  286. case BinaryOp::GreaterThanEquals:
  287. generator.emit<Bytecode::Op::GreaterThanEquals>(lhs_reg);
  288. break;
  289. case BinaryOp::LessThan:
  290. generator.emit<Bytecode::Op::LessThan>(lhs_reg);
  291. break;
  292. case BinaryOp::LessThanEquals:
  293. generator.emit<Bytecode::Op::LessThanEquals>(lhs_reg);
  294. break;
  295. case BinaryOp::LooselyInequals:
  296. generator.emit<Bytecode::Op::LooselyInequals>(lhs_reg);
  297. break;
  298. case BinaryOp::LooselyEquals:
  299. generator.emit<Bytecode::Op::LooselyEquals>(lhs_reg);
  300. break;
  301. case BinaryOp::StrictlyInequals:
  302. generator.emit<Bytecode::Op::StrictlyInequals>(lhs_reg);
  303. break;
  304. case BinaryOp::StrictlyEquals:
  305. generator.emit<Bytecode::Op::StrictlyEquals>(lhs_reg);
  306. break;
  307. case BinaryOp::BitwiseAnd:
  308. generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
  309. break;
  310. case BinaryOp::BitwiseOr:
  311. generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
  312. break;
  313. case BinaryOp::BitwiseXor:
  314. generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
  315. break;
  316. case BinaryOp::LeftShift:
  317. generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
  318. break;
  319. case BinaryOp::RightShift:
  320. generator.emit<Bytecode::Op::RightShift>(lhs_reg);
  321. break;
  322. case BinaryOp::UnsignedRightShift:
  323. generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
  324. break;
  325. case BinaryOp::In:
  326. generator.emit<Bytecode::Op::In>(lhs_reg);
  327. break;
  328. case BinaryOp::InstanceOf:
  329. generator.emit<Bytecode::Op::InstanceOf>(lhs_reg);
  330. break;
  331. default:
  332. VERIFY_NOT_REACHED();
  333. }
  334. return {};
  335. }
  336. Bytecode::CodeGenerationErrorOr<void> LogicalExpression::generate_bytecode(Bytecode::Generator& generator) const
  337. {
  338. TRY(m_lhs->generate_bytecode(generator));
  339. // lhs
  340. // jump op (true) end (false) rhs
  341. // rhs
  342. // jump always (true) end
  343. // end
  344. auto& rhs_block = generator.make_block();
  345. auto& end_block = generator.make_block();
  346. switch (m_op) {
  347. case LogicalOp::And:
  348. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  349. Bytecode::Label { rhs_block },
  350. Bytecode::Label { end_block });
  351. break;
  352. case LogicalOp::Or:
  353. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  354. Bytecode::Label { end_block },
  355. Bytecode::Label { rhs_block });
  356. break;
  357. case LogicalOp::NullishCoalescing:
  358. generator.emit<Bytecode::Op::JumpNullish>().set_targets(
  359. Bytecode::Label { rhs_block },
  360. Bytecode::Label { end_block });
  361. break;
  362. default:
  363. VERIFY_NOT_REACHED();
  364. }
  365. generator.switch_to_basic_block(rhs_block);
  366. TRY(m_rhs->generate_bytecode(generator));
  367. generator.emit<Bytecode::Op::Jump>().set_targets(
  368. Bytecode::Label { end_block },
  369. {});
  370. generator.switch_to_basic_block(end_block);
  371. return {};
  372. }
  373. Bytecode::CodeGenerationErrorOr<void> UnaryExpression::generate_bytecode(Bytecode::Generator& generator) const
  374. {
  375. TRY(m_lhs->generate_bytecode(generator));
  376. switch (m_op) {
  377. case UnaryOp::BitwiseNot:
  378. generator.emit<Bytecode::Op::BitwiseNot>();
  379. break;
  380. case UnaryOp::Not:
  381. generator.emit<Bytecode::Op::Not>();
  382. break;
  383. case UnaryOp::Plus:
  384. generator.emit<Bytecode::Op::UnaryPlus>();
  385. break;
  386. case UnaryOp::Minus:
  387. generator.emit<Bytecode::Op::UnaryMinus>();
  388. break;
  389. case UnaryOp::Typeof:
  390. generator.emit<Bytecode::Op::Typeof>();
  391. break;
  392. case UnaryOp::Void:
  393. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  394. break;
  395. default:
  396. return Bytecode::CodeGenerationError {
  397. this,
  398. "Unimplemented operation"sv,
  399. };
  400. }
  401. return {};
  402. }
  403. Bytecode::CodeGenerationErrorOr<void> NumericLiteral::generate_bytecode(Bytecode::Generator& generator) const
  404. {
  405. generator.emit<Bytecode::Op::LoadImmediate>(m_value);
  406. return {};
  407. }
  408. Bytecode::CodeGenerationErrorOr<void> BooleanLiteral::generate_bytecode(Bytecode::Generator& generator) const
  409. {
  410. generator.emit<Bytecode::Op::LoadImmediate>(Value(m_value));
  411. return {};
  412. }
  413. Bytecode::CodeGenerationErrorOr<void> NullLiteral::generate_bytecode(Bytecode::Generator& generator) const
  414. {
  415. generator.emit<Bytecode::Op::LoadImmediate>(js_null());
  416. return {};
  417. }
  418. Bytecode::CodeGenerationErrorOr<void> BigIntLiteral::generate_bytecode(Bytecode::Generator& generator) const
  419. {
  420. generator.emit<Bytecode::Op::NewBigInt>(Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1)));
  421. return {};
  422. }
  423. Bytecode::CodeGenerationErrorOr<void> StringLiteral::generate_bytecode(Bytecode::Generator& generator) const
  424. {
  425. generator.emit<Bytecode::Op::NewString>(generator.intern_string(m_value));
  426. return {};
  427. }
  428. Bytecode::CodeGenerationErrorOr<void> RegExpLiteral::generate_bytecode(Bytecode::Generator& generator) const
  429. {
  430. auto source_index = generator.intern_string(m_pattern);
  431. auto flags_index = generator.intern_string(m_flags);
  432. generator.emit<Bytecode::Op::NewRegExp>(source_index, flags_index);
  433. return {};
  434. }
  435. Bytecode::CodeGenerationErrorOr<void> Identifier::generate_bytecode(Bytecode::Generator& generator) const
  436. {
  437. generator.emit<Bytecode::Op::GetVariable>(generator.intern_identifier(m_string));
  438. return {};
  439. }
  440. Bytecode::CodeGenerationErrorOr<void> AssignmentExpression::generate_bytecode(Bytecode::Generator& generator) const
  441. {
  442. // FIXME: Implement this for BindingPatterns too.
  443. auto& lhs = m_lhs.get<NonnullRefPtr<Expression>>();
  444. if (m_op == AssignmentOp::Assignment) {
  445. TRY(m_rhs->generate_bytecode(generator));
  446. return generator.emit_store_to_reference(lhs);
  447. }
  448. TRY(generator.emit_load_from_reference(lhs));
  449. Bytecode::BasicBlock* rhs_block_ptr { nullptr };
  450. Bytecode::BasicBlock* end_block_ptr { nullptr };
  451. // Logical assignments short circuit.
  452. if (m_op == AssignmentOp::AndAssignment) { // &&=
  453. rhs_block_ptr = &generator.make_block();
  454. end_block_ptr = &generator.make_block();
  455. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  456. Bytecode::Label { *rhs_block_ptr },
  457. Bytecode::Label { *end_block_ptr });
  458. } else if (m_op == AssignmentOp::OrAssignment) { // ||=
  459. rhs_block_ptr = &generator.make_block();
  460. end_block_ptr = &generator.make_block();
  461. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  462. Bytecode::Label { *end_block_ptr },
  463. Bytecode::Label { *rhs_block_ptr });
  464. } else if (m_op == AssignmentOp::NullishAssignment) { // ??=
  465. rhs_block_ptr = &generator.make_block();
  466. end_block_ptr = &generator.make_block();
  467. generator.emit<Bytecode::Op::JumpNullish>().set_targets(
  468. Bytecode::Label { *rhs_block_ptr },
  469. Bytecode::Label { *end_block_ptr });
  470. }
  471. if (rhs_block_ptr)
  472. generator.switch_to_basic_block(*rhs_block_ptr);
  473. // lhs_reg is a part of the rhs_block because the store isn't necessary
  474. // if the logical assignment condition fails.
  475. auto lhs_reg = generator.allocate_register();
  476. generator.emit<Bytecode::Op::Store>(lhs_reg);
  477. TRY(m_rhs->generate_bytecode(generator));
  478. switch (m_op) {
  479. case AssignmentOp::AdditionAssignment:
  480. generator.emit<Bytecode::Op::Add>(lhs_reg);
  481. break;
  482. case AssignmentOp::SubtractionAssignment:
  483. generator.emit<Bytecode::Op::Sub>(lhs_reg);
  484. break;
  485. case AssignmentOp::MultiplicationAssignment:
  486. generator.emit<Bytecode::Op::Mul>(lhs_reg);
  487. break;
  488. case AssignmentOp::DivisionAssignment:
  489. generator.emit<Bytecode::Op::Div>(lhs_reg);
  490. break;
  491. case AssignmentOp::ModuloAssignment:
  492. generator.emit<Bytecode::Op::Mod>(lhs_reg);
  493. break;
  494. case AssignmentOp::ExponentiationAssignment:
  495. generator.emit<Bytecode::Op::Exp>(lhs_reg);
  496. break;
  497. case AssignmentOp::BitwiseAndAssignment:
  498. generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
  499. break;
  500. case AssignmentOp::BitwiseOrAssignment:
  501. generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
  502. break;
  503. case AssignmentOp::BitwiseXorAssignment:
  504. generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
  505. break;
  506. case AssignmentOp::LeftShiftAssignment:
  507. generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
  508. break;
  509. case AssignmentOp::RightShiftAssignment:
  510. generator.emit<Bytecode::Op::RightShift>(lhs_reg);
  511. break;
  512. case AssignmentOp::UnsignedRightShiftAssignment:
  513. generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
  514. break;
  515. case AssignmentOp::AndAssignment:
  516. case AssignmentOp::OrAssignment:
  517. case AssignmentOp::NullishAssignment:
  518. break; // These are handled above.
  519. default:
  520. return Bytecode::CodeGenerationError {
  521. this,
  522. "Unimplemented operation"sv,
  523. };
  524. }
  525. TRY(generator.emit_store_to_reference(lhs));
  526. if (end_block_ptr) {
  527. generator.emit<Bytecode::Op::Jump>().set_targets(
  528. Bytecode::Label { *end_block_ptr },
  529. {});
  530. generator.switch_to_basic_block(*end_block_ptr);
  531. }
  532. return {};
  533. }
  534. Bytecode::CodeGenerationErrorOr<void> WhileStatement::generate_bytecode(Bytecode::Generator& generator) const
  535. {
  536. // test
  537. // jump if_false (true) end (false) body
  538. // body
  539. // jump always (true) test
  540. // end
  541. auto& test_block = generator.make_block();
  542. auto& body_block = generator.make_block();
  543. auto& end_block = generator.make_block();
  544. // Init result register
  545. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  546. auto result_reg = generator.allocate_register();
  547. generator.emit<Bytecode::Op::Store>(result_reg);
  548. // jump to the test block
  549. generator.emit<Bytecode::Op::Jump>().set_targets(
  550. Bytecode::Label { test_block },
  551. {});
  552. generator.switch_to_basic_block(test_block);
  553. TRY(m_test->generate_bytecode(generator));
  554. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  555. Bytecode::Label { body_block },
  556. Bytecode::Label { end_block });
  557. generator.switch_to_basic_block(body_block);
  558. generator.begin_continuable_scope(Bytecode::Label { test_block });
  559. generator.begin_breakable_scope(Bytecode::Label { end_block });
  560. TRY(m_body->generate_bytecode(generator));
  561. generator.end_breakable_scope();
  562. generator.end_continuable_scope();
  563. if (!generator.is_current_block_terminated()) {
  564. generator.emit<Bytecode::Op::Jump>().set_targets(
  565. Bytecode::Label { test_block },
  566. {});
  567. generator.switch_to_basic_block(end_block);
  568. generator.emit<Bytecode::Op::Load>(result_reg);
  569. }
  570. return {};
  571. }
  572. Bytecode::CodeGenerationErrorOr<void> DoWhileStatement::generate_bytecode(Bytecode::Generator& generator) const
  573. {
  574. // jump always (true) body
  575. // test
  576. // jump if_false (true) end (false) body
  577. // body
  578. // jump always (true) test
  579. // end
  580. auto& test_block = generator.make_block();
  581. auto& body_block = generator.make_block();
  582. auto& end_block = generator.make_block();
  583. // Init result register
  584. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  585. auto result_reg = generator.allocate_register();
  586. generator.emit<Bytecode::Op::Store>(result_reg);
  587. // jump to the body block
  588. generator.emit<Bytecode::Op::Jump>().set_targets(
  589. Bytecode::Label { body_block },
  590. {});
  591. generator.switch_to_basic_block(test_block);
  592. TRY(m_test->generate_bytecode(generator));
  593. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  594. Bytecode::Label { body_block },
  595. Bytecode::Label { end_block });
  596. generator.switch_to_basic_block(body_block);
  597. generator.begin_continuable_scope(Bytecode::Label { test_block });
  598. generator.begin_breakable_scope(Bytecode::Label { end_block });
  599. TRY(m_body->generate_bytecode(generator));
  600. generator.end_breakable_scope();
  601. generator.end_continuable_scope();
  602. if (!generator.is_current_block_terminated()) {
  603. generator.emit<Bytecode::Op::Jump>().set_targets(
  604. Bytecode::Label { test_block },
  605. {});
  606. generator.switch_to_basic_block(end_block);
  607. generator.emit<Bytecode::Op::Load>(result_reg);
  608. }
  609. return {};
  610. }
  611. Bytecode::CodeGenerationErrorOr<void> ForStatement::generate_bytecode(Bytecode::Generator& generator) const
  612. {
  613. // init
  614. // jump always (true) test
  615. // test
  616. // jump if_true (true) body (false) end
  617. // body
  618. // jump always (true) update
  619. // update
  620. // jump always (true) test
  621. // end
  622. // If 'test' is missing, fuse the 'test' and 'body' basic blocks
  623. // If 'update' is missing, fuse the 'body' and 'update' basic blocks
  624. Bytecode::BasicBlock* test_block_ptr { nullptr };
  625. Bytecode::BasicBlock* body_block_ptr { nullptr };
  626. Bytecode::BasicBlock* update_block_ptr { nullptr };
  627. auto& end_block = generator.make_block();
  628. if (m_init)
  629. TRY(m_init->generate_bytecode(generator));
  630. body_block_ptr = &generator.make_block();
  631. if (m_test)
  632. test_block_ptr = &generator.make_block();
  633. else
  634. test_block_ptr = body_block_ptr;
  635. if (m_update)
  636. update_block_ptr = &generator.make_block();
  637. else
  638. update_block_ptr = body_block_ptr;
  639. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  640. auto result_reg = generator.allocate_register();
  641. generator.emit<Bytecode::Op::Store>(result_reg);
  642. generator.emit<Bytecode::Op::Jump>().set_targets(
  643. Bytecode::Label { *test_block_ptr },
  644. {});
  645. if (m_test) {
  646. generator.switch_to_basic_block(*test_block_ptr);
  647. TRY(m_test->generate_bytecode(generator));
  648. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  649. Bytecode::Label { *body_block_ptr },
  650. Bytecode::Label { end_block });
  651. }
  652. generator.switch_to_basic_block(*body_block_ptr);
  653. generator.begin_continuable_scope(Bytecode::Label { *update_block_ptr });
  654. generator.begin_breakable_scope(Bytecode::Label { end_block });
  655. TRY(m_body->generate_bytecode(generator));
  656. generator.end_breakable_scope();
  657. generator.end_continuable_scope();
  658. if (!generator.is_current_block_terminated()) {
  659. if (m_update) {
  660. generator.emit<Bytecode::Op::Jump>().set_targets(
  661. Bytecode::Label { *update_block_ptr },
  662. {});
  663. generator.switch_to_basic_block(*update_block_ptr);
  664. TRY(m_update->generate_bytecode(generator));
  665. }
  666. generator.emit<Bytecode::Op::Jump>().set_targets(
  667. Bytecode::Label { *test_block_ptr },
  668. {});
  669. generator.switch_to_basic_block(end_block);
  670. generator.emit<Bytecode::Op::Load>(result_reg);
  671. }
  672. return {};
  673. }
  674. Bytecode::CodeGenerationErrorOr<void> ObjectExpression::generate_bytecode(Bytecode::Generator& generator) const
  675. {
  676. generator.emit<Bytecode::Op::NewObject>();
  677. if (m_properties.is_empty())
  678. return {};
  679. auto object_reg = generator.allocate_register();
  680. generator.emit<Bytecode::Op::Store>(object_reg);
  681. for (auto& property : m_properties) {
  682. if (property.type() != ObjectProperty::Type::KeyValue)
  683. return Bytecode::CodeGenerationError {
  684. this,
  685. "Unimplemented property kind"sv,
  686. };
  687. if (is<StringLiteral>(property.key())) {
  688. auto& string_literal = static_cast<StringLiteral const&>(property.key());
  689. Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(string_literal.value());
  690. TRY(property.value().generate_bytecode(generator));
  691. generator.emit<Bytecode::Op::PutById>(object_reg, key_name);
  692. } else {
  693. TRY(property.key().generate_bytecode(generator));
  694. auto property_reg = generator.allocate_register();
  695. generator.emit<Bytecode::Op::Store>(property_reg);
  696. TRY(property.value().generate_bytecode(generator));
  697. generator.emit<Bytecode::Op::PutByValue>(object_reg, property_reg);
  698. }
  699. }
  700. generator.emit<Bytecode::Op::Load>(object_reg);
  701. return {};
  702. }
  703. Bytecode::CodeGenerationErrorOr<void> ArrayExpression::generate_bytecode(Bytecode::Generator& generator) const
  704. {
  705. Vector<Bytecode::Register> element_regs;
  706. for (auto& element : m_elements) {
  707. if (element) {
  708. TRY(element->generate_bytecode(generator));
  709. if (is<SpreadExpression>(*element)) {
  710. return Bytecode::CodeGenerationError {
  711. this,
  712. "Unimplemented element kind: SpreadExpression"sv,
  713. };
  714. }
  715. } else {
  716. generator.emit<Bytecode::Op::LoadImmediate>(Value {});
  717. }
  718. auto element_reg = generator.allocate_register();
  719. generator.emit<Bytecode::Op::Store>(element_reg);
  720. element_regs.append(element_reg);
  721. }
  722. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(element_regs.size(), element_regs);
  723. return {};
  724. }
  725. Bytecode::CodeGenerationErrorOr<void> MemberExpression::generate_bytecode(Bytecode::Generator& generator) const
  726. {
  727. return generator.emit_load_from_reference(*this);
  728. }
  729. Bytecode::CodeGenerationErrorOr<void> FunctionDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  730. {
  731. if (m_is_hoisted) {
  732. auto index = generator.intern_identifier(name());
  733. generator.emit<Bytecode::Op::GetVariable>(index);
  734. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode::Var);
  735. }
  736. return {};
  737. }
  738. Bytecode::CodeGenerationErrorOr<void> FunctionExpression::generate_bytecode(Bytecode::Generator& generator) const
  739. {
  740. generator.emit<Bytecode::Op::NewFunction>(*this);
  741. return {};
  742. }
  743. static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode, Bytecode::Register const& value_reg);
  744. 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)
  745. {
  746. Vector<Bytecode::Register> excluded_property_names;
  747. auto has_rest = false;
  748. if (pattern.entries.size() > 0)
  749. has_rest = pattern.entries[pattern.entries.size() - 1].is_rest;
  750. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  751. if (is_rest) {
  752. VERIFY(name.has<NonnullRefPtr<Identifier>>());
  753. VERIFY(alias.has<Empty>());
  754. VERIFY(!initializer);
  755. auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  756. auto interned_identifier = generator.intern_identifier(identifier);
  757. generator.emit_with_extra_register_slots<Bytecode::Op::CopyObjectExcludingProperties>(excluded_property_names.size(), value_reg, excluded_property_names);
  758. generator.emit<Bytecode::Op::SetVariable>(interned_identifier, initialization_mode);
  759. return {};
  760. }
  761. Bytecode::StringTableIndex name_index;
  762. if (name.has<NonnullRefPtr<Identifier>>()) {
  763. auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  764. name_index = generator.intern_string(identifier);
  765. if (has_rest) {
  766. auto excluded_name_reg = generator.allocate_register();
  767. excluded_property_names.append(excluded_name_reg);
  768. generator.emit<Bytecode::Op::NewString>(name_index);
  769. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  770. }
  771. generator.emit<Bytecode::Op::Load>(value_reg);
  772. generator.emit<Bytecode::Op::GetById>(generator.intern_identifier(identifier));
  773. } else {
  774. auto expression = name.get<NonnullRefPtr<Expression>>();
  775. TRY(expression->generate_bytecode(generator));
  776. if (has_rest) {
  777. auto excluded_name_reg = generator.allocate_register();
  778. excluded_property_names.append(excluded_name_reg);
  779. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  780. }
  781. generator.emit<Bytecode::Op::GetByValue>(value_reg);
  782. }
  783. if (initializer) {
  784. auto& if_undefined_block = generator.make_block();
  785. auto& if_not_undefined_block = generator.make_block();
  786. generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
  787. Bytecode::Label { if_undefined_block },
  788. Bytecode::Label { if_not_undefined_block });
  789. generator.switch_to_basic_block(if_undefined_block);
  790. TRY(initializer->generate_bytecode(generator));
  791. generator.emit<Bytecode::Op::Jump>().set_targets(
  792. Bytecode::Label { if_not_undefined_block },
  793. {});
  794. generator.switch_to_basic_block(if_not_undefined_block);
  795. }
  796. if (alias.has<NonnullRefPtr<BindingPattern>>()) {
  797. auto& binding_pattern = *alias.get<NonnullRefPtr<BindingPattern>>();
  798. auto nested_value_reg = generator.allocate_register();
  799. generator.emit<Bytecode::Op::Store>(nested_value_reg);
  800. TRY(generate_binding_pattern_bytecode(generator, binding_pattern, initialization_mode, nested_value_reg));
  801. } else if (alias.has<Empty>()) {
  802. if (name.has<NonnullRefPtr<Expression>>()) {
  803. // This needs some sort of SetVariableByValue opcode, as it's a runtime binding
  804. return Bytecode::CodeGenerationError {
  805. name.get<NonnullRefPtr<Expression>>().ptr(),
  806. "Unimplemented name/alias pair: Empty/Expression"sv,
  807. };
  808. }
  809. auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string();
  810. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  811. } else {
  812. auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string();
  813. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  814. }
  815. }
  816. return {};
  817. }
  818. 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)
  819. {
  820. /*
  821. * Consider the following destructuring assignment:
  822. *
  823. * let [a, b, c, d, e] = o;
  824. *
  825. * It would be fairly trivial to just loop through this iterator, getting the value
  826. * at each step and assigning them to the binding sequentially. However, this is not
  827. * correct: once an iterator is exhausted, it must not be called again. This complicates
  828. * the bytecode. In order to accomplish this, we do the following:
  829. *
  830. * - Reserve a special boolean register which holds 'true' if the iterator is exhausted,
  831. * and false otherwise
  832. * - When we are retrieving the value which should be bound, we first check this register.
  833. * If it is 'true', we load undefined into the accumulator. Otherwise, we grab the next
  834. * value from the iterator and store it into the accumulator.
  835. *
  836. * Note that the is_exhausted register does not need to be loaded with false because the
  837. * first IteratorNext bytecode is _not_ proceeded by an exhausted check, as it is
  838. * unnecessary.
  839. */
  840. auto is_iterator_exhausted_register = generator.allocate_register();
  841. auto iterator_reg = generator.allocate_register();
  842. generator.emit<Bytecode::Op::Load>(value_reg);
  843. generator.emit<Bytecode::Op::GetIterator>();
  844. generator.emit<Bytecode::Op::Store>(iterator_reg);
  845. bool first = true;
  846. auto temp_iterator_result_reg = generator.allocate_register();
  847. auto assign_accumulator_to_alias = [&](auto& alias) {
  848. return alias.visit(
  849. [&](Empty) -> Bytecode::CodeGenerationErrorOr<void> {
  850. // This element is an elision
  851. return {};
  852. },
  853. [&](NonnullRefPtr<Identifier> const& identifier) -> Bytecode::CodeGenerationErrorOr<void> {
  854. auto interned_index = generator.intern_identifier(identifier->string());
  855. generator.emit<Bytecode::Op::SetVariable>(interned_index, initialization_mode);
  856. return {};
  857. },
  858. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  859. // Store the accumulator value in a permanent register
  860. auto target_reg = generator.allocate_register();
  861. generator.emit<Bytecode::Op::Store>(target_reg);
  862. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, target_reg);
  863. },
  864. [&](NonnullRefPtr<MemberExpression> const& expr) -> Bytecode::CodeGenerationErrorOr<void> {
  865. return Bytecode::CodeGenerationError {
  866. expr.ptr(),
  867. "Unimplemented alias mode: MemberExpression"sv,
  868. };
  869. });
  870. };
  871. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  872. VERIFY(name.has<Empty>());
  873. if (is_rest) {
  874. if (first) {
  875. // The iterator has not been called, and is thus known to be not exhausted
  876. generator.emit<Bytecode::Op::Load>(iterator_reg);
  877. generator.emit<Bytecode::Op::IteratorToArray>();
  878. } else {
  879. auto& if_exhausted_block = generator.make_block();
  880. auto& if_not_exhausted_block = generator.make_block();
  881. auto& continuation_block = generator.make_block();
  882. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  883. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  884. Bytecode::Label { if_exhausted_block },
  885. Bytecode::Label { if_not_exhausted_block });
  886. generator.switch_to_basic_block(if_exhausted_block);
  887. generator.emit<Bytecode::Op::NewArray>();
  888. generator.emit<Bytecode::Op::Jump>().set_targets(
  889. Bytecode::Label { continuation_block },
  890. {});
  891. generator.switch_to_basic_block(if_not_exhausted_block);
  892. generator.emit<Bytecode::Op::Load>(iterator_reg);
  893. generator.emit<Bytecode::Op::IteratorToArray>();
  894. generator.emit<Bytecode::Op::Jump>().set_targets(
  895. Bytecode::Label { continuation_block },
  896. {});
  897. generator.switch_to_basic_block(continuation_block);
  898. }
  899. return assign_accumulator_to_alias(alias);
  900. }
  901. // In the first iteration of the loop, a few things are true which can save
  902. // us some bytecode:
  903. // - the iterator result is still in the accumulator, so we can avoid a load
  904. // - the iterator is not yet exhausted, which can save us a jump and some
  905. // creation
  906. auto& iterator_is_exhausted_block = generator.make_block();
  907. if (!first) {
  908. auto& iterator_is_not_exhausted_block = generator.make_block();
  909. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  910. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  911. Bytecode::Label { iterator_is_exhausted_block },
  912. Bytecode::Label { iterator_is_not_exhausted_block });
  913. generator.switch_to_basic_block(iterator_is_not_exhausted_block);
  914. generator.emit<Bytecode::Op::Load>(iterator_reg);
  915. }
  916. generator.emit<Bytecode::Op::IteratorNext>();
  917. generator.emit<Bytecode::Op::Store>(temp_iterator_result_reg);
  918. generator.emit<Bytecode::Op::IteratorResultDone>();
  919. generator.emit<Bytecode::Op::Store>(is_iterator_exhausted_register);
  920. // We still have to check for exhaustion here. If the iterator is exhausted,
  921. // we need to bail before trying to get the value
  922. auto& no_bail_block = generator.make_block();
  923. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  924. Bytecode::Label { iterator_is_exhausted_block },
  925. Bytecode::Label { no_bail_block });
  926. generator.switch_to_basic_block(no_bail_block);
  927. // Get the next value in the iterator
  928. generator.emit<Bytecode::Op::Load>(temp_iterator_result_reg);
  929. generator.emit<Bytecode::Op::IteratorResultValue>();
  930. auto& create_binding_block = generator.make_block();
  931. generator.emit<Bytecode::Op::Jump>().set_targets(
  932. Bytecode::Label { create_binding_block },
  933. {});
  934. // The iterator is exhausted, so we just load undefined and continue binding
  935. generator.switch_to_basic_block(iterator_is_exhausted_block);
  936. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  937. generator.emit<Bytecode::Op::Jump>().set_targets(
  938. Bytecode::Label { create_binding_block },
  939. {});
  940. // Create the actual binding. The value which this entry must bind is now in the
  941. // accumulator. We can proceed, processing the alias as a nested destructuring
  942. // pattern if necessary.
  943. generator.switch_to_basic_block(create_binding_block);
  944. TRY(assign_accumulator_to_alias(alias));
  945. first = false;
  946. }
  947. return {};
  948. }
  949. 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)
  950. {
  951. if (pattern.kind == BindingPattern::Kind::Object)
  952. return generate_object_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  953. return generate_array_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  954. }
  955. Bytecode::CodeGenerationErrorOr<void> VariableDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  956. {
  957. for (auto& declarator : m_declarations) {
  958. if (declarator.init())
  959. TRY(declarator.init()->generate_bytecode(generator));
  960. else
  961. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  962. auto initialization_mode = is_lexical_declaration() ? Bytecode::Op::SetVariable::InitializationMode::Initialize : Bytecode::Op::SetVariable::InitializationMode::Set;
  963. auto environment_mode = is_lexical_declaration() ? Bytecode::Op::EnvironmentMode::Lexical : Bytecode::Op::EnvironmentMode::Var;
  964. TRY(declarator.target().visit(
  965. [&](NonnullRefPtr<Identifier> const& id) -> Bytecode::CodeGenerationErrorOr<void> {
  966. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(id->string()), initialization_mode, environment_mode);
  967. return {};
  968. },
  969. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  970. auto value_register = generator.allocate_register();
  971. generator.emit<Bytecode::Op::Store>(value_register);
  972. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, value_register);
  973. }));
  974. }
  975. return {};
  976. }
  977. Bytecode::CodeGenerationErrorOr<void> CallExpression::generate_bytecode(Bytecode::Generator& generator) const
  978. {
  979. auto callee_reg = generator.allocate_register();
  980. auto this_reg = generator.allocate_register();
  981. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  982. generator.emit<Bytecode::Op::Store>(this_reg);
  983. if (is<NewExpression>(this)) {
  984. TRY(m_callee->generate_bytecode(generator));
  985. generator.emit<Bytecode::Op::Store>(callee_reg);
  986. } else if (is<SuperExpression>(*m_callee)) {
  987. return Bytecode::CodeGenerationError {
  988. this,
  989. "Unimplemented callee kind: SuperExpression"sv,
  990. };
  991. } else if (is<MemberExpression>(*m_callee)) {
  992. auto& member_expression = static_cast<const MemberExpression&>(*m_callee);
  993. if (is<SuperExpression>(member_expression.object())) {
  994. return Bytecode::CodeGenerationError {
  995. this,
  996. "Unimplemented callee kind: MemberExpression on SuperExpression"sv,
  997. };
  998. }
  999. TRY(member_expression.object().generate_bytecode(generator));
  1000. generator.emit<Bytecode::Op::Store>(this_reg);
  1001. if (member_expression.is_computed()) {
  1002. TRY(member_expression.property().generate_bytecode(generator));
  1003. generator.emit<Bytecode::Op::GetByValue>(this_reg);
  1004. } else {
  1005. auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string());
  1006. generator.emit<Bytecode::Op::GetById>(identifier_table_ref);
  1007. }
  1008. generator.emit<Bytecode::Op::Store>(callee_reg);
  1009. } else {
  1010. // FIXME: this = global object in sloppy mode.
  1011. TRY(m_callee->generate_bytecode(generator));
  1012. generator.emit<Bytecode::Op::Store>(callee_reg);
  1013. }
  1014. Vector<Bytecode::Register> argument_registers;
  1015. for (auto& arg : m_arguments) {
  1016. TRY(arg.value->generate_bytecode(generator));
  1017. auto arg_reg = generator.allocate_register();
  1018. generator.emit<Bytecode::Op::Store>(arg_reg);
  1019. argument_registers.append(arg_reg);
  1020. }
  1021. Bytecode::Op::Call::CallType call_type;
  1022. if (is<NewExpression>(*this)) {
  1023. call_type = Bytecode::Op::Call::CallType::Construct;
  1024. } else {
  1025. call_type = Bytecode::Op::Call::CallType::Call;
  1026. }
  1027. generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_registers.size(), call_type, callee_reg, this_reg, argument_registers);
  1028. return {};
  1029. }
  1030. Bytecode::CodeGenerationErrorOr<void> ReturnStatement::generate_bytecode(Bytecode::Generator& generator) const
  1031. {
  1032. if (m_argument)
  1033. TRY(m_argument->generate_bytecode(generator));
  1034. if (generator.is_in_generator_or_async_function()) {
  1035. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1036. generator.emit<Bytecode::Op::Yield>(nullptr);
  1037. } else {
  1038. generator.perform_needed_unwinds<Bytecode::Op::Return>();
  1039. generator.emit<Bytecode::Op::Return>();
  1040. }
  1041. return {};
  1042. }
  1043. Bytecode::CodeGenerationErrorOr<void> YieldExpression::generate_bytecode(Bytecode::Generator& generator) const
  1044. {
  1045. VERIFY(generator.is_in_generator_function());
  1046. if (m_is_yield_from) {
  1047. return Bytecode::CodeGenerationError {
  1048. this,
  1049. "Unimplemented form: `yield*`"sv,
  1050. };
  1051. }
  1052. if (m_argument)
  1053. TRY(m_argument->generate_bytecode(generator));
  1054. auto& continuation_block = generator.make_block();
  1055. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1056. generator.switch_to_basic_block(continuation_block);
  1057. return {};
  1058. }
  1059. Bytecode::CodeGenerationErrorOr<void> IfStatement::generate_bytecode(Bytecode::Generator& generator) const
  1060. {
  1061. // test
  1062. // jump if_true (true) true (false) false
  1063. // true
  1064. // jump always (true) end
  1065. // false
  1066. // jump always (true) end
  1067. // end
  1068. auto& true_block = generator.make_block();
  1069. auto& false_block = generator.make_block();
  1070. TRY(m_predicate->generate_bytecode(generator));
  1071. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1072. Bytecode::Label { true_block },
  1073. Bytecode::Label { false_block });
  1074. Bytecode::Op::Jump* true_block_jump { nullptr };
  1075. generator.switch_to_basic_block(true_block);
  1076. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1077. TRY(m_consequent->generate_bytecode(generator));
  1078. if (!generator.is_current_block_terminated())
  1079. true_block_jump = &generator.emit<Bytecode::Op::Jump>();
  1080. generator.switch_to_basic_block(false_block);
  1081. auto& end_block = generator.make_block();
  1082. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1083. if (m_alternate)
  1084. TRY(m_alternate->generate_bytecode(generator));
  1085. if (!generator.is_current_block_terminated())
  1086. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1087. if (true_block_jump)
  1088. true_block_jump->set_targets(Bytecode::Label { end_block }, {});
  1089. generator.switch_to_basic_block(end_block);
  1090. return {};
  1091. }
  1092. Bytecode::CodeGenerationErrorOr<void> ContinueStatement::generate_bytecode(Bytecode::Generator& generator) const
  1093. {
  1094. generator.perform_needed_unwinds<Bytecode::Op::Jump>();
  1095. generator.emit<Bytecode::Op::Jump>().set_targets(
  1096. generator.nearest_continuable_scope(),
  1097. {});
  1098. return {};
  1099. }
  1100. Bytecode::CodeGenerationErrorOr<void> DebuggerStatement::generate_bytecode(Bytecode::Generator&) const
  1101. {
  1102. return {};
  1103. }
  1104. Bytecode::CodeGenerationErrorOr<void> ConditionalExpression::generate_bytecode(Bytecode::Generator& generator) const
  1105. {
  1106. // test
  1107. // jump if_true (true) true (false) false
  1108. // true
  1109. // jump always (true) end
  1110. // false
  1111. // jump always (true) end
  1112. // end
  1113. auto& true_block = generator.make_block();
  1114. auto& false_block = generator.make_block();
  1115. auto& end_block = generator.make_block();
  1116. TRY(m_test->generate_bytecode(generator));
  1117. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1118. Bytecode::Label { true_block },
  1119. Bytecode::Label { false_block });
  1120. generator.switch_to_basic_block(true_block);
  1121. TRY(m_consequent->generate_bytecode(generator));
  1122. generator.emit<Bytecode::Op::Jump>().set_targets(
  1123. Bytecode::Label { end_block },
  1124. {});
  1125. generator.switch_to_basic_block(false_block);
  1126. TRY(m_alternate->generate_bytecode(generator));
  1127. generator.emit<Bytecode::Op::Jump>().set_targets(
  1128. Bytecode::Label { end_block },
  1129. {});
  1130. generator.switch_to_basic_block(end_block);
  1131. return {};
  1132. }
  1133. Bytecode::CodeGenerationErrorOr<void> SequenceExpression::generate_bytecode(Bytecode::Generator& generator) const
  1134. {
  1135. for (auto& expression : m_expressions)
  1136. TRY(expression.generate_bytecode(generator));
  1137. return {};
  1138. }
  1139. Bytecode::CodeGenerationErrorOr<void> TemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1140. {
  1141. auto string_reg = generator.allocate_register();
  1142. for (size_t i = 0; i < m_expressions.size(); i++) {
  1143. TRY(m_expressions[i].generate_bytecode(generator));
  1144. if (i == 0) {
  1145. generator.emit<Bytecode::Op::Store>(string_reg);
  1146. } else {
  1147. generator.emit<Bytecode::Op::ConcatString>(string_reg);
  1148. }
  1149. }
  1150. generator.emit<Bytecode::Op::Load>(string_reg);
  1151. return {};
  1152. }
  1153. Bytecode::CodeGenerationErrorOr<void> TaggedTemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1154. {
  1155. TRY(m_tag->generate_bytecode(generator));
  1156. auto tag_reg = generator.allocate_register();
  1157. generator.emit<Bytecode::Op::Store>(tag_reg);
  1158. Vector<Bytecode::Register> string_regs;
  1159. auto& expressions = m_template_literal->expressions();
  1160. for (size_t i = 0; i < expressions.size(); ++i) {
  1161. if (i % 2 != 0)
  1162. continue;
  1163. TRY(expressions[i].generate_bytecode(generator));
  1164. auto string_reg = generator.allocate_register();
  1165. generator.emit<Bytecode::Op::Store>(string_reg);
  1166. string_regs.append(string_reg);
  1167. }
  1168. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(string_regs.size(), string_regs);
  1169. auto strings_reg = generator.allocate_register();
  1170. generator.emit<Bytecode::Op::Store>(strings_reg);
  1171. Vector<Bytecode::Register> argument_regs;
  1172. argument_regs.append(strings_reg);
  1173. for (size_t i = 0; i < expressions.size(); ++i) {
  1174. if (i % 2 == 0)
  1175. continue;
  1176. TRY(expressions[i].generate_bytecode(generator));
  1177. auto string_reg = generator.allocate_register();
  1178. generator.emit<Bytecode::Op::Store>(string_reg);
  1179. argument_regs.append(string_reg);
  1180. }
  1181. Vector<Bytecode::Register> raw_string_regs;
  1182. for (auto& raw_string : m_template_literal->raw_strings()) {
  1183. TRY(raw_string.generate_bytecode(generator));
  1184. auto raw_string_reg = generator.allocate_register();
  1185. generator.emit<Bytecode::Op::Store>(raw_string_reg);
  1186. raw_string_regs.append(raw_string_reg);
  1187. }
  1188. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(raw_string_regs.size(), raw_string_regs);
  1189. auto raw_strings_reg = generator.allocate_register();
  1190. generator.emit<Bytecode::Op::Store>(raw_strings_reg);
  1191. generator.emit<Bytecode::Op::Load>(strings_reg);
  1192. generator.emit<Bytecode::Op::PutById>(raw_strings_reg, generator.intern_identifier("raw"));
  1193. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1194. auto this_reg = generator.allocate_register();
  1195. generator.emit<Bytecode::Op::Store>(this_reg);
  1196. generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_regs.size(), Bytecode::Op::Call::CallType::Call, tag_reg, this_reg, move(argument_regs));
  1197. return {};
  1198. }
  1199. Bytecode::CodeGenerationErrorOr<void> UpdateExpression::generate_bytecode(Bytecode::Generator& generator) const
  1200. {
  1201. TRY(generator.emit_load_from_reference(*m_argument));
  1202. Optional<Bytecode::Register> previous_value_for_postfix_reg;
  1203. if (!m_prefixed) {
  1204. previous_value_for_postfix_reg = generator.allocate_register();
  1205. generator.emit<Bytecode::Op::Store>(*previous_value_for_postfix_reg);
  1206. }
  1207. if (m_op == UpdateOp::Increment)
  1208. generator.emit<Bytecode::Op::Increment>();
  1209. else
  1210. generator.emit<Bytecode::Op::Decrement>();
  1211. TRY(generator.emit_store_to_reference(*m_argument));
  1212. if (!m_prefixed)
  1213. generator.emit<Bytecode::Op::Load>(*previous_value_for_postfix_reg);
  1214. return {};
  1215. }
  1216. Bytecode::CodeGenerationErrorOr<void> ThrowStatement::generate_bytecode(Bytecode::Generator& generator) const
  1217. {
  1218. TRY(m_argument->generate_bytecode(generator));
  1219. generator.emit<Bytecode::Op::Throw>();
  1220. return {};
  1221. }
  1222. Bytecode::CodeGenerationErrorOr<void> BreakStatement::generate_bytecode(Bytecode::Generator& generator) const
  1223. {
  1224. generator.perform_needed_unwinds<Bytecode::Op::Jump>(true);
  1225. generator.emit<Bytecode::Op::Jump>().set_targets(
  1226. generator.nearest_breakable_scope(),
  1227. {});
  1228. return {};
  1229. }
  1230. Bytecode::CodeGenerationErrorOr<void> TryStatement::generate_bytecode(Bytecode::Generator& generator) const
  1231. {
  1232. auto& saved_block = generator.current_block();
  1233. Optional<Bytecode::Label> handler_target;
  1234. Optional<Bytecode::Label> finalizer_target;
  1235. Bytecode::BasicBlock* next_block { nullptr };
  1236. if (m_finalizer) {
  1237. auto& finalizer_block = generator.make_block();
  1238. generator.switch_to_basic_block(finalizer_block);
  1239. TRY(m_finalizer->generate_bytecode(generator));
  1240. if (!generator.is_current_block_terminated()) {
  1241. next_block = &generator.make_block();
  1242. auto next_target = Bytecode::Label { *next_block };
  1243. generator.emit<Bytecode::Op::ContinuePendingUnwind>(next_target);
  1244. }
  1245. finalizer_target = Bytecode::Label { finalizer_block };
  1246. }
  1247. if (m_handler) {
  1248. auto& handler_block = generator.make_block();
  1249. generator.switch_to_basic_block(handler_block);
  1250. TRY(m_handler->parameter().visit(
  1251. [&](FlyString const& parameter) -> Bytecode::CodeGenerationErrorOr<void> {
  1252. if (!parameter.is_empty()) {
  1253. // FIXME: We need a separate DeclarativeEnvironment here
  1254. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(parameter));
  1255. }
  1256. return {};
  1257. },
  1258. [&](NonnullRefPtr<BindingPattern> const&) -> Bytecode::CodeGenerationErrorOr<void> {
  1259. // FIXME: Implement this path when the above DeclarativeEnvironment issue is dealt with.
  1260. return Bytecode::CodeGenerationError {
  1261. this,
  1262. "Unimplemented catch argument: BindingPattern"sv,
  1263. };
  1264. }));
  1265. TRY(m_handler->body().generate_bytecode(generator));
  1266. handler_target = Bytecode::Label { handler_block };
  1267. if (!generator.is_current_block_terminated()) {
  1268. if (m_finalizer) {
  1269. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1270. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1271. } else {
  1272. VERIFY(!next_block);
  1273. next_block = &generator.make_block();
  1274. auto next_target = Bytecode::Label { *next_block };
  1275. generator.emit<Bytecode::Op::Jump>(next_target);
  1276. }
  1277. }
  1278. }
  1279. auto& target_block = generator.make_block();
  1280. generator.switch_to_basic_block(saved_block);
  1281. generator.emit<Bytecode::Op::EnterUnwindContext>(Bytecode::Label { target_block }, handler_target, finalizer_target);
  1282. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1283. generator.switch_to_basic_block(target_block);
  1284. TRY(m_block->generate_bytecode(generator));
  1285. if (!generator.is_current_block_terminated()) {
  1286. if (m_finalizer) {
  1287. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1288. } else {
  1289. auto& block = generator.make_block();
  1290. generator.emit<Bytecode::Op::FinishUnwind>(Bytecode::Label { block });
  1291. next_block = &block;
  1292. }
  1293. }
  1294. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1295. generator.switch_to_basic_block(next_block ? *next_block : saved_block);
  1296. return {};
  1297. }
  1298. Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_bytecode(Bytecode::Generator& generator) const
  1299. {
  1300. auto discriminant_reg = generator.allocate_register();
  1301. TRY(m_discriminant->generate_bytecode(generator));
  1302. generator.emit<Bytecode::Op::Store>(discriminant_reg);
  1303. Vector<Bytecode::BasicBlock&> case_blocks;
  1304. Bytecode::BasicBlock* default_block { nullptr };
  1305. Bytecode::BasicBlock* next_test_block = &generator.make_block();
  1306. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_test_block }, {});
  1307. for (auto& switch_case : m_cases) {
  1308. auto& case_block = generator.make_block();
  1309. if (switch_case.test()) {
  1310. generator.switch_to_basic_block(*next_test_block);
  1311. TRY(switch_case.test()->generate_bytecode(generator));
  1312. generator.emit<Bytecode::Op::StrictlyEquals>(discriminant_reg);
  1313. next_test_block = &generator.make_block();
  1314. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { case_block }, Bytecode::Label { *next_test_block });
  1315. } else {
  1316. default_block = &case_block;
  1317. }
  1318. case_blocks.append(case_block);
  1319. }
  1320. generator.switch_to_basic_block(*next_test_block);
  1321. auto& end_block = generator.make_block();
  1322. if (default_block != nullptr) {
  1323. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *default_block }, {});
  1324. } else {
  1325. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1326. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1327. }
  1328. auto current_block = case_blocks.begin();
  1329. generator.begin_breakable_scope(Bytecode::Label { end_block });
  1330. for (auto& switch_case : m_cases) {
  1331. generator.switch_to_basic_block(*current_block);
  1332. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1333. for (auto& statement : switch_case.children()) {
  1334. TRY(statement.generate_bytecode(generator));
  1335. }
  1336. if (!generator.is_current_block_terminated()) {
  1337. auto next_block = current_block;
  1338. next_block++;
  1339. if (next_block.is_end()) {
  1340. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1341. } else {
  1342. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_block }, {});
  1343. }
  1344. }
  1345. current_block++;
  1346. }
  1347. generator.end_breakable_scope();
  1348. generator.switch_to_basic_block(end_block);
  1349. return {};
  1350. }
  1351. Bytecode::CodeGenerationErrorOr<void> ClassDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1352. {
  1353. TRY(m_class_expression->generate_bytecode(generator));
  1354. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(m_class_expression.ptr()->name()), Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1355. return {};
  1356. }
  1357. Bytecode::CodeGenerationErrorOr<void> ClassExpression::generate_bytecode(Bytecode::Generator& generator) const
  1358. {
  1359. generator.emit<Bytecode::Op::NewClass>(*this);
  1360. return {};
  1361. }
  1362. Bytecode::CodeGenerationErrorOr<void> ThisExpression::generate_bytecode(Bytecode::Generator& generator) const
  1363. {
  1364. generator.emit<Bytecode::Op::ResolveThisBinding>();
  1365. return {};
  1366. }
  1367. Bytecode::CodeGenerationErrorOr<void> AwaitExpression::generate_bytecode(Bytecode::Generator& generator) const
  1368. {
  1369. VERIFY(generator.is_in_async_function());
  1370. // Transform `await expr` to `yield expr`
  1371. TRY(m_argument->generate_bytecode(generator));
  1372. auto& continuation_block = generator.make_block();
  1373. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1374. generator.switch_to_basic_block(continuation_block);
  1375. return {};
  1376. }
  1377. Bytecode::CodeGenerationErrorOr<void> WithStatement::generate_bytecode(Bytecode::Generator& generator) const
  1378. {
  1379. TRY(m_object->generate_bytecode(generator));
  1380. generator.emit<Bytecode::Op::EnterObjectEnvironment>();
  1381. TRY(m_body->generate_bytecode(generator));
  1382. generator.emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  1383. return {};
  1384. }
  1385. }