ASTCodegen.cpp 69 KB

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