ASTCodegen.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  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. bool has_lexical_environment = false;
  629. if (m_init) {
  630. if (m_init->is_variable_declaration()) {
  631. auto& variable_declaration = verify_cast<VariableDeclaration>(*m_init);
  632. if (variable_declaration.is_lexical_declaration()) {
  633. has_lexical_environment = true;
  634. // FIXME: Is Block correct?
  635. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  636. bool is_const = variable_declaration.is_constant_declaration();
  637. variable_declaration.for_each_bound_name([&](auto const& name) {
  638. auto index = generator.intern_identifier(name);
  639. generator.register_binding(index);
  640. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_const);
  641. });
  642. }
  643. }
  644. TRY(m_init->generate_bytecode(generator));
  645. }
  646. body_block_ptr = &generator.make_block();
  647. if (m_test)
  648. test_block_ptr = &generator.make_block();
  649. else
  650. test_block_ptr = body_block_ptr;
  651. if (m_update)
  652. update_block_ptr = &generator.make_block();
  653. else
  654. update_block_ptr = body_block_ptr;
  655. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  656. auto result_reg = generator.allocate_register();
  657. generator.emit<Bytecode::Op::Store>(result_reg);
  658. generator.emit<Bytecode::Op::Jump>().set_targets(
  659. Bytecode::Label { *test_block_ptr },
  660. {});
  661. if (m_test) {
  662. generator.switch_to_basic_block(*test_block_ptr);
  663. TRY(m_test->generate_bytecode(generator));
  664. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  665. Bytecode::Label { *body_block_ptr },
  666. Bytecode::Label { end_block });
  667. }
  668. generator.switch_to_basic_block(*body_block_ptr);
  669. generator.begin_continuable_scope(Bytecode::Label { *update_block_ptr });
  670. generator.begin_breakable_scope(Bytecode::Label { end_block });
  671. TRY(m_body->generate_bytecode(generator));
  672. generator.end_breakable_scope();
  673. generator.end_continuable_scope();
  674. if (has_lexical_environment)
  675. generator.end_variable_scope();
  676. if (!generator.is_current_block_terminated()) {
  677. if (m_update) {
  678. generator.emit<Bytecode::Op::Jump>().set_targets(
  679. Bytecode::Label { *update_block_ptr },
  680. {});
  681. generator.switch_to_basic_block(*update_block_ptr);
  682. TRY(m_update->generate_bytecode(generator));
  683. }
  684. generator.emit<Bytecode::Op::Jump>().set_targets(
  685. Bytecode::Label { *test_block_ptr },
  686. {});
  687. generator.switch_to_basic_block(end_block);
  688. generator.emit<Bytecode::Op::Load>(result_reg);
  689. }
  690. return {};
  691. }
  692. Bytecode::CodeGenerationErrorOr<void> ObjectExpression::generate_bytecode(Bytecode::Generator& generator) const
  693. {
  694. generator.emit<Bytecode::Op::NewObject>();
  695. if (m_properties.is_empty())
  696. return {};
  697. auto object_reg = generator.allocate_register();
  698. generator.emit<Bytecode::Op::Store>(object_reg);
  699. for (auto& property : m_properties) {
  700. if (property.type() != ObjectProperty::Type::KeyValue)
  701. return Bytecode::CodeGenerationError {
  702. this,
  703. "Unimplemented property kind"sv,
  704. };
  705. if (is<StringLiteral>(property.key())) {
  706. auto& string_literal = static_cast<StringLiteral const&>(property.key());
  707. Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(string_literal.value());
  708. TRY(property.value().generate_bytecode(generator));
  709. generator.emit<Bytecode::Op::PutById>(object_reg, key_name);
  710. } else {
  711. TRY(property.key().generate_bytecode(generator));
  712. auto property_reg = generator.allocate_register();
  713. generator.emit<Bytecode::Op::Store>(property_reg);
  714. TRY(property.value().generate_bytecode(generator));
  715. generator.emit<Bytecode::Op::PutByValue>(object_reg, property_reg);
  716. }
  717. }
  718. generator.emit<Bytecode::Op::Load>(object_reg);
  719. return {};
  720. }
  721. Bytecode::CodeGenerationErrorOr<void> ArrayExpression::generate_bytecode(Bytecode::Generator& generator) const
  722. {
  723. Vector<Bytecode::Register> element_regs;
  724. for (auto& element : m_elements) {
  725. if (element) {
  726. TRY(element->generate_bytecode(generator));
  727. if (is<SpreadExpression>(*element)) {
  728. return Bytecode::CodeGenerationError {
  729. this,
  730. "Unimplemented element kind: SpreadExpression"sv,
  731. };
  732. }
  733. } else {
  734. generator.emit<Bytecode::Op::LoadImmediate>(Value {});
  735. }
  736. auto element_reg = generator.allocate_register();
  737. generator.emit<Bytecode::Op::Store>(element_reg);
  738. element_regs.append(element_reg);
  739. }
  740. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(element_regs.size(), element_regs);
  741. return {};
  742. }
  743. Bytecode::CodeGenerationErrorOr<void> MemberExpression::generate_bytecode(Bytecode::Generator& generator) const
  744. {
  745. return generator.emit_load_from_reference(*this);
  746. }
  747. Bytecode::CodeGenerationErrorOr<void> FunctionDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  748. {
  749. if (m_is_hoisted) {
  750. auto index = generator.intern_identifier(name());
  751. generator.emit<Bytecode::Op::GetVariable>(index);
  752. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode::Var);
  753. }
  754. return {};
  755. }
  756. Bytecode::CodeGenerationErrorOr<void> FunctionExpression::generate_bytecode(Bytecode::Generator& generator) const
  757. {
  758. generator.emit<Bytecode::Op::NewFunction>(*this);
  759. return {};
  760. }
  761. static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode, Bytecode::Register const& value_reg);
  762. 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)
  763. {
  764. Vector<Bytecode::Register> excluded_property_names;
  765. auto has_rest = false;
  766. if (pattern.entries.size() > 0)
  767. has_rest = pattern.entries[pattern.entries.size() - 1].is_rest;
  768. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  769. if (is_rest) {
  770. VERIFY(name.has<NonnullRefPtr<Identifier>>());
  771. VERIFY(alias.has<Empty>());
  772. VERIFY(!initializer);
  773. auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  774. auto interned_identifier = generator.intern_identifier(identifier);
  775. generator.emit_with_extra_register_slots<Bytecode::Op::CopyObjectExcludingProperties>(excluded_property_names.size(), value_reg, excluded_property_names);
  776. generator.emit<Bytecode::Op::SetVariable>(interned_identifier, initialization_mode);
  777. return {};
  778. }
  779. Bytecode::StringTableIndex name_index;
  780. if (name.has<NonnullRefPtr<Identifier>>()) {
  781. auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  782. name_index = generator.intern_string(identifier);
  783. if (has_rest) {
  784. auto excluded_name_reg = generator.allocate_register();
  785. excluded_property_names.append(excluded_name_reg);
  786. generator.emit<Bytecode::Op::NewString>(name_index);
  787. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  788. }
  789. generator.emit<Bytecode::Op::Load>(value_reg);
  790. generator.emit<Bytecode::Op::GetById>(generator.intern_identifier(identifier));
  791. } else {
  792. auto expression = name.get<NonnullRefPtr<Expression>>();
  793. TRY(expression->generate_bytecode(generator));
  794. if (has_rest) {
  795. auto excluded_name_reg = generator.allocate_register();
  796. excluded_property_names.append(excluded_name_reg);
  797. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  798. }
  799. generator.emit<Bytecode::Op::GetByValue>(value_reg);
  800. }
  801. if (initializer) {
  802. auto& if_undefined_block = generator.make_block();
  803. auto& if_not_undefined_block = generator.make_block();
  804. generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
  805. Bytecode::Label { if_undefined_block },
  806. Bytecode::Label { if_not_undefined_block });
  807. generator.switch_to_basic_block(if_undefined_block);
  808. TRY(initializer->generate_bytecode(generator));
  809. generator.emit<Bytecode::Op::Jump>().set_targets(
  810. Bytecode::Label { if_not_undefined_block },
  811. {});
  812. generator.switch_to_basic_block(if_not_undefined_block);
  813. }
  814. if (alias.has<NonnullRefPtr<BindingPattern>>()) {
  815. auto& binding_pattern = *alias.get<NonnullRefPtr<BindingPattern>>();
  816. auto nested_value_reg = generator.allocate_register();
  817. generator.emit<Bytecode::Op::Store>(nested_value_reg);
  818. TRY(generate_binding_pattern_bytecode(generator, binding_pattern, initialization_mode, nested_value_reg));
  819. } else if (alias.has<Empty>()) {
  820. if (name.has<NonnullRefPtr<Expression>>()) {
  821. // This needs some sort of SetVariableByValue opcode, as it's a runtime binding
  822. return Bytecode::CodeGenerationError {
  823. name.get<NonnullRefPtr<Expression>>().ptr(),
  824. "Unimplemented name/alias pair: Empty/Expression"sv,
  825. };
  826. }
  827. auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string();
  828. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  829. } else {
  830. auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string();
  831. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  832. }
  833. }
  834. return {};
  835. }
  836. 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)
  837. {
  838. /*
  839. * Consider the following destructuring assignment:
  840. *
  841. * let [a, b, c, d, e] = o;
  842. *
  843. * It would be fairly trivial to just loop through this iterator, getting the value
  844. * at each step and assigning them to the binding sequentially. However, this is not
  845. * correct: once an iterator is exhausted, it must not be called again. This complicates
  846. * the bytecode. In order to accomplish this, we do the following:
  847. *
  848. * - Reserve a special boolean register which holds 'true' if the iterator is exhausted,
  849. * and false otherwise
  850. * - When we are retrieving the value which should be bound, we first check this register.
  851. * If it is 'true', we load undefined into the accumulator. Otherwise, we grab the next
  852. * value from the iterator and store it into the accumulator.
  853. *
  854. * Note that the is_exhausted register does not need to be loaded with false because the
  855. * first IteratorNext bytecode is _not_ proceeded by an exhausted check, as it is
  856. * unnecessary.
  857. */
  858. auto is_iterator_exhausted_register = generator.allocate_register();
  859. auto iterator_reg = generator.allocate_register();
  860. generator.emit<Bytecode::Op::Load>(value_reg);
  861. generator.emit<Bytecode::Op::GetIterator>();
  862. generator.emit<Bytecode::Op::Store>(iterator_reg);
  863. bool first = true;
  864. auto temp_iterator_result_reg = generator.allocate_register();
  865. auto assign_accumulator_to_alias = [&](auto& alias) {
  866. return alias.visit(
  867. [&](Empty) -> Bytecode::CodeGenerationErrorOr<void> {
  868. // This element is an elision
  869. return {};
  870. },
  871. [&](NonnullRefPtr<Identifier> const& identifier) -> Bytecode::CodeGenerationErrorOr<void> {
  872. auto interned_index = generator.intern_identifier(identifier->string());
  873. generator.emit<Bytecode::Op::SetVariable>(interned_index, initialization_mode);
  874. return {};
  875. },
  876. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  877. // Store the accumulator value in a permanent register
  878. auto target_reg = generator.allocate_register();
  879. generator.emit<Bytecode::Op::Store>(target_reg);
  880. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, target_reg);
  881. },
  882. [&](NonnullRefPtr<MemberExpression> const& expr) -> Bytecode::CodeGenerationErrorOr<void> {
  883. return Bytecode::CodeGenerationError {
  884. expr.ptr(),
  885. "Unimplemented alias mode: MemberExpression"sv,
  886. };
  887. });
  888. };
  889. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  890. VERIFY(name.has<Empty>());
  891. if (is_rest) {
  892. if (first) {
  893. // The iterator has not been called, and is thus known to be not exhausted
  894. generator.emit<Bytecode::Op::Load>(iterator_reg);
  895. generator.emit<Bytecode::Op::IteratorToArray>();
  896. } else {
  897. auto& if_exhausted_block = generator.make_block();
  898. auto& if_not_exhausted_block = generator.make_block();
  899. auto& continuation_block = generator.make_block();
  900. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  901. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  902. Bytecode::Label { if_exhausted_block },
  903. Bytecode::Label { if_not_exhausted_block });
  904. generator.switch_to_basic_block(if_exhausted_block);
  905. generator.emit<Bytecode::Op::NewArray>();
  906. generator.emit<Bytecode::Op::Jump>().set_targets(
  907. Bytecode::Label { continuation_block },
  908. {});
  909. generator.switch_to_basic_block(if_not_exhausted_block);
  910. generator.emit<Bytecode::Op::Load>(iterator_reg);
  911. generator.emit<Bytecode::Op::IteratorToArray>();
  912. generator.emit<Bytecode::Op::Jump>().set_targets(
  913. Bytecode::Label { continuation_block },
  914. {});
  915. generator.switch_to_basic_block(continuation_block);
  916. }
  917. return assign_accumulator_to_alias(alias);
  918. }
  919. // In the first iteration of the loop, a few things are true which can save
  920. // us some bytecode:
  921. // - the iterator result is still in the accumulator, so we can avoid a load
  922. // - the iterator is not yet exhausted, which can save us a jump and some
  923. // creation
  924. auto& iterator_is_exhausted_block = generator.make_block();
  925. if (!first) {
  926. auto& iterator_is_not_exhausted_block = generator.make_block();
  927. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  928. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  929. Bytecode::Label { iterator_is_exhausted_block },
  930. Bytecode::Label { iterator_is_not_exhausted_block });
  931. generator.switch_to_basic_block(iterator_is_not_exhausted_block);
  932. generator.emit<Bytecode::Op::Load>(iterator_reg);
  933. }
  934. generator.emit<Bytecode::Op::IteratorNext>();
  935. generator.emit<Bytecode::Op::Store>(temp_iterator_result_reg);
  936. generator.emit<Bytecode::Op::IteratorResultDone>();
  937. generator.emit<Bytecode::Op::Store>(is_iterator_exhausted_register);
  938. // We still have to check for exhaustion here. If the iterator is exhausted,
  939. // we need to bail before trying to get the value
  940. auto& no_bail_block = generator.make_block();
  941. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  942. Bytecode::Label { iterator_is_exhausted_block },
  943. Bytecode::Label { no_bail_block });
  944. generator.switch_to_basic_block(no_bail_block);
  945. // Get the next value in the iterator
  946. generator.emit<Bytecode::Op::Load>(temp_iterator_result_reg);
  947. generator.emit<Bytecode::Op::IteratorResultValue>();
  948. auto& create_binding_block = generator.make_block();
  949. generator.emit<Bytecode::Op::Jump>().set_targets(
  950. Bytecode::Label { create_binding_block },
  951. {});
  952. // The iterator is exhausted, so we just load undefined and continue binding
  953. generator.switch_to_basic_block(iterator_is_exhausted_block);
  954. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  955. generator.emit<Bytecode::Op::Jump>().set_targets(
  956. Bytecode::Label { create_binding_block },
  957. {});
  958. // Create the actual binding. The value which this entry must bind is now in the
  959. // accumulator. We can proceed, processing the alias as a nested destructuring
  960. // pattern if necessary.
  961. generator.switch_to_basic_block(create_binding_block);
  962. TRY(assign_accumulator_to_alias(alias));
  963. first = false;
  964. }
  965. return {};
  966. }
  967. 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)
  968. {
  969. if (pattern.kind == BindingPattern::Kind::Object)
  970. return generate_object_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  971. return generate_array_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  972. }
  973. Bytecode::CodeGenerationErrorOr<void> VariableDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  974. {
  975. for (auto& declarator : m_declarations) {
  976. if (declarator.init())
  977. TRY(declarator.init()->generate_bytecode(generator));
  978. else
  979. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  980. auto initialization_mode = is_lexical_declaration() ? Bytecode::Op::SetVariable::InitializationMode::Initialize : Bytecode::Op::SetVariable::InitializationMode::Set;
  981. auto environment_mode = is_lexical_declaration() ? Bytecode::Op::EnvironmentMode::Lexical : Bytecode::Op::EnvironmentMode::Var;
  982. TRY(declarator.target().visit(
  983. [&](NonnullRefPtr<Identifier> const& id) -> Bytecode::CodeGenerationErrorOr<void> {
  984. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(id->string()), initialization_mode, environment_mode);
  985. return {};
  986. },
  987. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  988. auto value_register = generator.allocate_register();
  989. generator.emit<Bytecode::Op::Store>(value_register);
  990. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, value_register);
  991. }));
  992. }
  993. return {};
  994. }
  995. Bytecode::CodeGenerationErrorOr<void> CallExpression::generate_bytecode(Bytecode::Generator& generator) const
  996. {
  997. auto callee_reg = generator.allocate_register();
  998. auto this_reg = generator.allocate_register();
  999. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1000. generator.emit<Bytecode::Op::Store>(this_reg);
  1001. if (is<NewExpression>(this)) {
  1002. TRY(m_callee->generate_bytecode(generator));
  1003. generator.emit<Bytecode::Op::Store>(callee_reg);
  1004. } else if (is<SuperExpression>(*m_callee)) {
  1005. return Bytecode::CodeGenerationError {
  1006. this,
  1007. "Unimplemented callee kind: SuperExpression"sv,
  1008. };
  1009. } else if (is<MemberExpression>(*m_callee)) {
  1010. auto& member_expression = static_cast<const MemberExpression&>(*m_callee);
  1011. if (is<SuperExpression>(member_expression.object())) {
  1012. return Bytecode::CodeGenerationError {
  1013. this,
  1014. "Unimplemented callee kind: MemberExpression on SuperExpression"sv,
  1015. };
  1016. }
  1017. TRY(member_expression.object().generate_bytecode(generator));
  1018. generator.emit<Bytecode::Op::Store>(this_reg);
  1019. if (member_expression.is_computed()) {
  1020. TRY(member_expression.property().generate_bytecode(generator));
  1021. generator.emit<Bytecode::Op::GetByValue>(this_reg);
  1022. } else {
  1023. auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string());
  1024. generator.emit<Bytecode::Op::GetById>(identifier_table_ref);
  1025. }
  1026. generator.emit<Bytecode::Op::Store>(callee_reg);
  1027. } else {
  1028. // FIXME: this = global object in sloppy mode.
  1029. TRY(m_callee->generate_bytecode(generator));
  1030. generator.emit<Bytecode::Op::Store>(callee_reg);
  1031. }
  1032. Vector<Bytecode::Register> argument_registers;
  1033. for (auto& arg : m_arguments) {
  1034. TRY(arg.value->generate_bytecode(generator));
  1035. auto arg_reg = generator.allocate_register();
  1036. generator.emit<Bytecode::Op::Store>(arg_reg);
  1037. argument_registers.append(arg_reg);
  1038. }
  1039. Bytecode::Op::Call::CallType call_type;
  1040. if (is<NewExpression>(*this)) {
  1041. call_type = Bytecode::Op::Call::CallType::Construct;
  1042. } else {
  1043. call_type = Bytecode::Op::Call::CallType::Call;
  1044. }
  1045. generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_registers.size(), call_type, callee_reg, this_reg, argument_registers);
  1046. return {};
  1047. }
  1048. Bytecode::CodeGenerationErrorOr<void> ReturnStatement::generate_bytecode(Bytecode::Generator& generator) const
  1049. {
  1050. if (m_argument)
  1051. TRY(m_argument->generate_bytecode(generator));
  1052. if (generator.is_in_generator_or_async_function()) {
  1053. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1054. generator.emit<Bytecode::Op::Yield>(nullptr);
  1055. } else {
  1056. generator.perform_needed_unwinds<Bytecode::Op::Return>();
  1057. generator.emit<Bytecode::Op::Return>();
  1058. }
  1059. return {};
  1060. }
  1061. Bytecode::CodeGenerationErrorOr<void> YieldExpression::generate_bytecode(Bytecode::Generator& generator) const
  1062. {
  1063. VERIFY(generator.is_in_generator_function());
  1064. if (m_is_yield_from) {
  1065. return Bytecode::CodeGenerationError {
  1066. this,
  1067. "Unimplemented form: `yield*`"sv,
  1068. };
  1069. }
  1070. if (m_argument)
  1071. TRY(m_argument->generate_bytecode(generator));
  1072. auto& continuation_block = generator.make_block();
  1073. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1074. generator.switch_to_basic_block(continuation_block);
  1075. return {};
  1076. }
  1077. Bytecode::CodeGenerationErrorOr<void> IfStatement::generate_bytecode(Bytecode::Generator& generator) const
  1078. {
  1079. // test
  1080. // jump if_true (true) true (false) false
  1081. // true
  1082. // jump always (true) end
  1083. // false
  1084. // jump always (true) end
  1085. // end
  1086. auto& true_block = generator.make_block();
  1087. auto& false_block = generator.make_block();
  1088. TRY(m_predicate->generate_bytecode(generator));
  1089. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1090. Bytecode::Label { true_block },
  1091. Bytecode::Label { false_block });
  1092. Bytecode::Op::Jump* true_block_jump { nullptr };
  1093. generator.switch_to_basic_block(true_block);
  1094. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1095. TRY(m_consequent->generate_bytecode(generator));
  1096. if (!generator.is_current_block_terminated())
  1097. true_block_jump = &generator.emit<Bytecode::Op::Jump>();
  1098. generator.switch_to_basic_block(false_block);
  1099. auto& end_block = generator.make_block();
  1100. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1101. if (m_alternate)
  1102. TRY(m_alternate->generate_bytecode(generator));
  1103. if (!generator.is_current_block_terminated())
  1104. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1105. if (true_block_jump)
  1106. true_block_jump->set_targets(Bytecode::Label { end_block }, {});
  1107. generator.switch_to_basic_block(end_block);
  1108. return {};
  1109. }
  1110. Bytecode::CodeGenerationErrorOr<void> ContinueStatement::generate_bytecode(Bytecode::Generator& generator) const
  1111. {
  1112. generator.perform_needed_unwinds<Bytecode::Op::Jump>();
  1113. generator.emit<Bytecode::Op::Jump>().set_targets(
  1114. generator.nearest_continuable_scope(),
  1115. {});
  1116. return {};
  1117. }
  1118. Bytecode::CodeGenerationErrorOr<void> DebuggerStatement::generate_bytecode(Bytecode::Generator&) const
  1119. {
  1120. return {};
  1121. }
  1122. Bytecode::CodeGenerationErrorOr<void> ConditionalExpression::generate_bytecode(Bytecode::Generator& generator) const
  1123. {
  1124. // test
  1125. // jump if_true (true) true (false) false
  1126. // true
  1127. // jump always (true) end
  1128. // false
  1129. // jump always (true) end
  1130. // end
  1131. auto& true_block = generator.make_block();
  1132. auto& false_block = generator.make_block();
  1133. auto& end_block = generator.make_block();
  1134. TRY(m_test->generate_bytecode(generator));
  1135. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1136. Bytecode::Label { true_block },
  1137. Bytecode::Label { false_block });
  1138. generator.switch_to_basic_block(true_block);
  1139. TRY(m_consequent->generate_bytecode(generator));
  1140. generator.emit<Bytecode::Op::Jump>().set_targets(
  1141. Bytecode::Label { end_block },
  1142. {});
  1143. generator.switch_to_basic_block(false_block);
  1144. TRY(m_alternate->generate_bytecode(generator));
  1145. generator.emit<Bytecode::Op::Jump>().set_targets(
  1146. Bytecode::Label { end_block },
  1147. {});
  1148. generator.switch_to_basic_block(end_block);
  1149. return {};
  1150. }
  1151. Bytecode::CodeGenerationErrorOr<void> SequenceExpression::generate_bytecode(Bytecode::Generator& generator) const
  1152. {
  1153. for (auto& expression : m_expressions)
  1154. TRY(expression.generate_bytecode(generator));
  1155. return {};
  1156. }
  1157. Bytecode::CodeGenerationErrorOr<void> TemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1158. {
  1159. auto string_reg = generator.allocate_register();
  1160. for (size_t i = 0; i < m_expressions.size(); i++) {
  1161. TRY(m_expressions[i].generate_bytecode(generator));
  1162. if (i == 0) {
  1163. generator.emit<Bytecode::Op::Store>(string_reg);
  1164. } else {
  1165. generator.emit<Bytecode::Op::ConcatString>(string_reg);
  1166. }
  1167. }
  1168. generator.emit<Bytecode::Op::Load>(string_reg);
  1169. return {};
  1170. }
  1171. Bytecode::CodeGenerationErrorOr<void> TaggedTemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1172. {
  1173. TRY(m_tag->generate_bytecode(generator));
  1174. auto tag_reg = generator.allocate_register();
  1175. generator.emit<Bytecode::Op::Store>(tag_reg);
  1176. Vector<Bytecode::Register> string_regs;
  1177. auto& expressions = m_template_literal->expressions();
  1178. for (size_t i = 0; i < expressions.size(); ++i) {
  1179. if (i % 2 != 0)
  1180. continue;
  1181. TRY(expressions[i].generate_bytecode(generator));
  1182. auto string_reg = generator.allocate_register();
  1183. generator.emit<Bytecode::Op::Store>(string_reg);
  1184. string_regs.append(string_reg);
  1185. }
  1186. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(string_regs.size(), string_regs);
  1187. auto strings_reg = generator.allocate_register();
  1188. generator.emit<Bytecode::Op::Store>(strings_reg);
  1189. Vector<Bytecode::Register> argument_regs;
  1190. argument_regs.append(strings_reg);
  1191. for (size_t i = 0; i < expressions.size(); ++i) {
  1192. if (i % 2 == 0)
  1193. continue;
  1194. TRY(expressions[i].generate_bytecode(generator));
  1195. auto string_reg = generator.allocate_register();
  1196. generator.emit<Bytecode::Op::Store>(string_reg);
  1197. argument_regs.append(string_reg);
  1198. }
  1199. Vector<Bytecode::Register> raw_string_regs;
  1200. for (auto& raw_string : m_template_literal->raw_strings()) {
  1201. TRY(raw_string.generate_bytecode(generator));
  1202. auto raw_string_reg = generator.allocate_register();
  1203. generator.emit<Bytecode::Op::Store>(raw_string_reg);
  1204. raw_string_regs.append(raw_string_reg);
  1205. }
  1206. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(raw_string_regs.size(), raw_string_regs);
  1207. auto raw_strings_reg = generator.allocate_register();
  1208. generator.emit<Bytecode::Op::Store>(raw_strings_reg);
  1209. generator.emit<Bytecode::Op::Load>(strings_reg);
  1210. generator.emit<Bytecode::Op::PutById>(raw_strings_reg, generator.intern_identifier("raw"));
  1211. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1212. auto this_reg = generator.allocate_register();
  1213. generator.emit<Bytecode::Op::Store>(this_reg);
  1214. generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_regs.size(), Bytecode::Op::Call::CallType::Call, tag_reg, this_reg, move(argument_regs));
  1215. return {};
  1216. }
  1217. Bytecode::CodeGenerationErrorOr<void> UpdateExpression::generate_bytecode(Bytecode::Generator& generator) const
  1218. {
  1219. TRY(generator.emit_load_from_reference(*m_argument));
  1220. Optional<Bytecode::Register> previous_value_for_postfix_reg;
  1221. if (!m_prefixed) {
  1222. previous_value_for_postfix_reg = generator.allocate_register();
  1223. generator.emit<Bytecode::Op::Store>(*previous_value_for_postfix_reg);
  1224. }
  1225. if (m_op == UpdateOp::Increment)
  1226. generator.emit<Bytecode::Op::Increment>();
  1227. else
  1228. generator.emit<Bytecode::Op::Decrement>();
  1229. TRY(generator.emit_store_to_reference(*m_argument));
  1230. if (!m_prefixed)
  1231. generator.emit<Bytecode::Op::Load>(*previous_value_for_postfix_reg);
  1232. return {};
  1233. }
  1234. Bytecode::CodeGenerationErrorOr<void> ThrowStatement::generate_bytecode(Bytecode::Generator& generator) const
  1235. {
  1236. TRY(m_argument->generate_bytecode(generator));
  1237. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1238. generator.emit<Bytecode::Op::Throw>();
  1239. return {};
  1240. }
  1241. Bytecode::CodeGenerationErrorOr<void> BreakStatement::generate_bytecode(Bytecode::Generator& generator) const
  1242. {
  1243. generator.perform_needed_unwinds<Bytecode::Op::Jump>(true);
  1244. generator.emit<Bytecode::Op::Jump>().set_targets(
  1245. generator.nearest_breakable_scope(),
  1246. {});
  1247. return {};
  1248. }
  1249. Bytecode::CodeGenerationErrorOr<void> TryStatement::generate_bytecode(Bytecode::Generator& generator) const
  1250. {
  1251. auto& saved_block = generator.current_block();
  1252. Optional<Bytecode::Label> handler_target;
  1253. Optional<Bytecode::Label> finalizer_target;
  1254. Bytecode::BasicBlock* next_block { nullptr };
  1255. if (m_finalizer) {
  1256. auto& finalizer_block = generator.make_block();
  1257. generator.switch_to_basic_block(finalizer_block);
  1258. TRY(m_finalizer->generate_bytecode(generator));
  1259. if (!generator.is_current_block_terminated()) {
  1260. next_block = &generator.make_block();
  1261. auto next_target = Bytecode::Label { *next_block };
  1262. generator.emit<Bytecode::Op::ContinuePendingUnwind>(next_target);
  1263. }
  1264. finalizer_target = Bytecode::Label { finalizer_block };
  1265. }
  1266. if (m_handler) {
  1267. auto& handler_block = generator.make_block();
  1268. generator.switch_to_basic_block(handler_block);
  1269. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  1270. TRY(m_handler->parameter().visit(
  1271. [&](FlyString const& parameter) -> Bytecode::CodeGenerationErrorOr<void> {
  1272. if (!parameter.is_empty()) {
  1273. auto parameter_identifier = generator.intern_identifier(parameter);
  1274. generator.register_binding(parameter_identifier);
  1275. generator.emit<Bytecode::Op::CreateVariable>(parameter_identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1276. generator.emit<Bytecode::Op::SetVariable>(parameter_identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1277. }
  1278. return {};
  1279. },
  1280. [&](NonnullRefPtr<BindingPattern> const&) -> Bytecode::CodeGenerationErrorOr<void> {
  1281. // FIXME: Implement this path when the above DeclarativeEnvironment issue is dealt with.
  1282. return Bytecode::CodeGenerationError {
  1283. this,
  1284. "Unimplemented catch argument: BindingPattern"sv,
  1285. };
  1286. }));
  1287. TRY(m_handler->body().generate_bytecode(generator));
  1288. handler_target = Bytecode::Label { handler_block };
  1289. generator.end_variable_scope();
  1290. if (!generator.is_current_block_terminated()) {
  1291. if (m_finalizer) {
  1292. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1293. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1294. } else {
  1295. VERIFY(!next_block);
  1296. next_block = &generator.make_block();
  1297. auto next_target = Bytecode::Label { *next_block };
  1298. generator.emit<Bytecode::Op::Jump>(next_target);
  1299. }
  1300. }
  1301. }
  1302. auto& target_block = generator.make_block();
  1303. generator.switch_to_basic_block(saved_block);
  1304. generator.emit<Bytecode::Op::EnterUnwindContext>(Bytecode::Label { target_block }, handler_target, finalizer_target);
  1305. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1306. generator.switch_to_basic_block(target_block);
  1307. TRY(m_block->generate_bytecode(generator));
  1308. if (!generator.is_current_block_terminated()) {
  1309. if (m_finalizer) {
  1310. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1311. } else {
  1312. auto& block = generator.make_block();
  1313. generator.emit<Bytecode::Op::FinishUnwind>(Bytecode::Label { block });
  1314. next_block = &block;
  1315. }
  1316. }
  1317. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1318. generator.switch_to_basic_block(next_block ? *next_block : saved_block);
  1319. return {};
  1320. }
  1321. Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_bytecode(Bytecode::Generator& generator) const
  1322. {
  1323. auto discriminant_reg = generator.allocate_register();
  1324. TRY(m_discriminant->generate_bytecode(generator));
  1325. generator.emit<Bytecode::Op::Store>(discriminant_reg);
  1326. Vector<Bytecode::BasicBlock&> case_blocks;
  1327. Bytecode::BasicBlock* default_block { nullptr };
  1328. Bytecode::BasicBlock* next_test_block = &generator.make_block();
  1329. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_test_block }, {});
  1330. for (auto& switch_case : m_cases) {
  1331. auto& case_block = generator.make_block();
  1332. if (switch_case.test()) {
  1333. generator.switch_to_basic_block(*next_test_block);
  1334. TRY(switch_case.test()->generate_bytecode(generator));
  1335. generator.emit<Bytecode::Op::StrictlyEquals>(discriminant_reg);
  1336. next_test_block = &generator.make_block();
  1337. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { case_block }, Bytecode::Label { *next_test_block });
  1338. } else {
  1339. default_block = &case_block;
  1340. }
  1341. case_blocks.append(case_block);
  1342. }
  1343. generator.switch_to_basic_block(*next_test_block);
  1344. auto& end_block = generator.make_block();
  1345. if (default_block != nullptr) {
  1346. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *default_block }, {});
  1347. } else {
  1348. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1349. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1350. }
  1351. auto current_block = case_blocks.begin();
  1352. generator.begin_breakable_scope(Bytecode::Label { end_block });
  1353. for (auto& switch_case : m_cases) {
  1354. generator.switch_to_basic_block(*current_block);
  1355. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1356. for (auto& statement : switch_case.children()) {
  1357. TRY(statement.generate_bytecode(generator));
  1358. }
  1359. if (!generator.is_current_block_terminated()) {
  1360. auto next_block = current_block;
  1361. next_block++;
  1362. if (next_block.is_end()) {
  1363. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1364. } else {
  1365. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_block }, {});
  1366. }
  1367. }
  1368. current_block++;
  1369. }
  1370. generator.end_breakable_scope();
  1371. generator.switch_to_basic_block(end_block);
  1372. return {};
  1373. }
  1374. Bytecode::CodeGenerationErrorOr<void> ClassDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1375. {
  1376. TRY(m_class_expression->generate_bytecode(generator));
  1377. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(m_class_expression.ptr()->name()), Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1378. return {};
  1379. }
  1380. Bytecode::CodeGenerationErrorOr<void> ClassExpression::generate_bytecode(Bytecode::Generator& generator) const
  1381. {
  1382. generator.emit<Bytecode::Op::NewClass>(*this);
  1383. return {};
  1384. }
  1385. Bytecode::CodeGenerationErrorOr<void> ThisExpression::generate_bytecode(Bytecode::Generator& generator) const
  1386. {
  1387. generator.emit<Bytecode::Op::ResolveThisBinding>();
  1388. return {};
  1389. }
  1390. Bytecode::CodeGenerationErrorOr<void> AwaitExpression::generate_bytecode(Bytecode::Generator& generator) const
  1391. {
  1392. VERIFY(generator.is_in_async_function());
  1393. // Transform `await expr` to `yield expr`
  1394. TRY(m_argument->generate_bytecode(generator));
  1395. auto& continuation_block = generator.make_block();
  1396. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1397. generator.switch_to_basic_block(continuation_block);
  1398. return {};
  1399. }
  1400. Bytecode::CodeGenerationErrorOr<void> WithStatement::generate_bytecode(Bytecode::Generator& generator) const
  1401. {
  1402. TRY(m_object->generate_bytecode(generator));
  1403. generator.emit<Bytecode::Op::EnterObjectEnvironment>();
  1404. // EnterObjectEnvironment sets the running execution context's lexical_environment to a new Object Environment.
  1405. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1406. TRY(m_body->generate_bytecode(generator));
  1407. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1408. if (!generator.is_current_block_terminated())
  1409. generator.emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  1410. return {};
  1411. }
  1412. }