ASTCodegen.cpp 65 KB

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