ASTCodegen.cpp 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077
  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. if (m_op == UnaryOp::Delete)
  376. return generator.emit_delete_reference(m_lhs);
  377. TRY(m_lhs->generate_bytecode(generator));
  378. switch (m_op) {
  379. case UnaryOp::BitwiseNot:
  380. generator.emit<Bytecode::Op::BitwiseNot>();
  381. break;
  382. case UnaryOp::Not:
  383. generator.emit<Bytecode::Op::Not>();
  384. break;
  385. case UnaryOp::Plus:
  386. generator.emit<Bytecode::Op::UnaryPlus>();
  387. break;
  388. case UnaryOp::Minus:
  389. generator.emit<Bytecode::Op::UnaryMinus>();
  390. break;
  391. case UnaryOp::Typeof:
  392. generator.emit<Bytecode::Op::Typeof>();
  393. break;
  394. case UnaryOp::Void:
  395. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  396. break;
  397. case UnaryOp::Delete: // Delete is implemented above.
  398. default:
  399. VERIFY_NOT_REACHED();
  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 (!generator.is_current_block_terminated()) {
  675. if (m_update) {
  676. generator.emit<Bytecode::Op::Jump>().set_targets(
  677. Bytecode::Label { *update_block_ptr },
  678. {});
  679. generator.switch_to_basic_block(*update_block_ptr);
  680. TRY(m_update->generate_bytecode(generator));
  681. }
  682. generator.emit<Bytecode::Op::Jump>().set_targets(
  683. Bytecode::Label { *test_block_ptr },
  684. {});
  685. generator.switch_to_basic_block(end_block);
  686. generator.emit<Bytecode::Op::Load>(result_reg);
  687. }
  688. if (has_lexical_environment)
  689. generator.end_variable_scope();
  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. Bytecode::Op::PropertyKind property_kind;
  701. switch (property.type()) {
  702. case ObjectProperty::Type::KeyValue:
  703. property_kind = Bytecode::Op::PropertyKind::KeyValue;
  704. break;
  705. case ObjectProperty::Type::Getter:
  706. property_kind = Bytecode::Op::PropertyKind::Getter;
  707. break;
  708. case ObjectProperty::Type::Setter:
  709. property_kind = Bytecode::Op::PropertyKind::Setter;
  710. break;
  711. case ObjectProperty::Type::Spread:
  712. property_kind = Bytecode::Op::PropertyKind::Spread;
  713. break;
  714. case ObjectProperty::Type::ProtoSetter:
  715. property_kind = Bytecode::Op::PropertyKind::ProtoSetter;
  716. break;
  717. }
  718. if (is<StringLiteral>(property.key())) {
  719. auto& string_literal = static_cast<StringLiteral const&>(property.key());
  720. Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(string_literal.value());
  721. if (property_kind != Bytecode::Op::PropertyKind::Spread)
  722. TRY(property.value().generate_bytecode(generator));
  723. generator.emit<Bytecode::Op::PutById>(object_reg, key_name, property_kind);
  724. } else {
  725. TRY(property.key().generate_bytecode(generator));
  726. auto property_reg = generator.allocate_register();
  727. generator.emit<Bytecode::Op::Store>(property_reg);
  728. if (property_kind != Bytecode::Op::PropertyKind::Spread)
  729. TRY(property.value().generate_bytecode(generator));
  730. generator.emit<Bytecode::Op::PutByValue>(object_reg, property_reg, property_kind);
  731. }
  732. }
  733. generator.emit<Bytecode::Op::Load>(object_reg);
  734. return {};
  735. }
  736. Bytecode::CodeGenerationErrorOr<void> ArrayExpression::generate_bytecode(Bytecode::Generator& generator) const
  737. {
  738. Vector<Bytecode::Register> element_regs;
  739. for (auto& element : m_elements) {
  740. if (element && is<SpreadExpression>(*element)) {
  741. return Bytecode::CodeGenerationError {
  742. this,
  743. "Unimplemented element kind: SpreadExpression"sv,
  744. };
  745. }
  746. element_regs.append(generator.allocate_register());
  747. }
  748. size_t i = 0;
  749. for (auto& element : m_elements) {
  750. if (element) {
  751. TRY(element->generate_bytecode(generator));
  752. if (is<SpreadExpression>(*element))
  753. VERIFY_NOT_REACHED();
  754. } else {
  755. generator.emit<Bytecode::Op::LoadImmediate>(Value {});
  756. }
  757. auto& element_reg = element_regs[i++];
  758. generator.emit<Bytecode::Op::Store>(element_reg);
  759. }
  760. if (element_regs.is_empty()) {
  761. generator.emit<Bytecode::Op::NewArray>();
  762. } else {
  763. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { element_regs.first(), element_regs.last() });
  764. }
  765. return {};
  766. }
  767. Bytecode::CodeGenerationErrorOr<void> MemberExpression::generate_bytecode(Bytecode::Generator& generator) const
  768. {
  769. return generator.emit_load_from_reference(*this);
  770. }
  771. Bytecode::CodeGenerationErrorOr<void> FunctionDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  772. {
  773. if (m_is_hoisted) {
  774. auto index = generator.intern_identifier(name());
  775. generator.emit<Bytecode::Op::GetVariable>(index);
  776. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode::Var);
  777. }
  778. return {};
  779. }
  780. Bytecode::CodeGenerationErrorOr<void> FunctionExpression::generate_bytecode(Bytecode::Generator& generator) const
  781. {
  782. generator.emit<Bytecode::Op::NewFunction>(*this);
  783. return {};
  784. }
  785. static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode, Bytecode::Register const& value_reg);
  786. 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)
  787. {
  788. Vector<Bytecode::Register> excluded_property_names;
  789. auto has_rest = false;
  790. if (pattern.entries.size() > 0)
  791. has_rest = pattern.entries[pattern.entries.size() - 1].is_rest;
  792. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  793. if (is_rest) {
  794. VERIFY(name.has<NonnullRefPtr<Identifier>>());
  795. VERIFY(alias.has<Empty>());
  796. VERIFY(!initializer);
  797. auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  798. auto interned_identifier = generator.intern_identifier(identifier);
  799. generator.emit_with_extra_register_slots<Bytecode::Op::CopyObjectExcludingProperties>(excluded_property_names.size(), value_reg, excluded_property_names);
  800. generator.emit<Bytecode::Op::SetVariable>(interned_identifier, initialization_mode);
  801. return {};
  802. }
  803. Bytecode::StringTableIndex name_index;
  804. if (name.has<NonnullRefPtr<Identifier>>()) {
  805. auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  806. name_index = generator.intern_string(identifier);
  807. if (has_rest) {
  808. auto excluded_name_reg = generator.allocate_register();
  809. excluded_property_names.append(excluded_name_reg);
  810. generator.emit<Bytecode::Op::NewString>(name_index);
  811. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  812. }
  813. generator.emit<Bytecode::Op::Load>(value_reg);
  814. generator.emit<Bytecode::Op::GetById>(generator.intern_identifier(identifier));
  815. } else {
  816. auto expression = name.get<NonnullRefPtr<Expression>>();
  817. TRY(expression->generate_bytecode(generator));
  818. if (has_rest) {
  819. auto excluded_name_reg = generator.allocate_register();
  820. excluded_property_names.append(excluded_name_reg);
  821. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  822. }
  823. generator.emit<Bytecode::Op::GetByValue>(value_reg);
  824. }
  825. if (initializer) {
  826. auto& if_undefined_block = generator.make_block();
  827. auto& if_not_undefined_block = generator.make_block();
  828. generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
  829. Bytecode::Label { if_undefined_block },
  830. Bytecode::Label { if_not_undefined_block });
  831. generator.switch_to_basic_block(if_undefined_block);
  832. TRY(initializer->generate_bytecode(generator));
  833. generator.emit<Bytecode::Op::Jump>().set_targets(
  834. Bytecode::Label { if_not_undefined_block },
  835. {});
  836. generator.switch_to_basic_block(if_not_undefined_block);
  837. }
  838. if (alias.has<NonnullRefPtr<BindingPattern>>()) {
  839. auto& binding_pattern = *alias.get<NonnullRefPtr<BindingPattern>>();
  840. auto nested_value_reg = generator.allocate_register();
  841. generator.emit<Bytecode::Op::Store>(nested_value_reg);
  842. TRY(generate_binding_pattern_bytecode(generator, binding_pattern, initialization_mode, nested_value_reg));
  843. } else if (alias.has<Empty>()) {
  844. if (name.has<NonnullRefPtr<Expression>>()) {
  845. // This needs some sort of SetVariableByValue opcode, as it's a runtime binding
  846. return Bytecode::CodeGenerationError {
  847. name.get<NonnullRefPtr<Expression>>().ptr(),
  848. "Unimplemented name/alias pair: Empty/Expression"sv,
  849. };
  850. }
  851. auto& identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  852. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  853. } else {
  854. auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string();
  855. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  856. }
  857. }
  858. return {};
  859. }
  860. 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)
  861. {
  862. /*
  863. * Consider the following destructuring assignment:
  864. *
  865. * let [a, b, c, d, e] = o;
  866. *
  867. * It would be fairly trivial to just loop through this iterator, getting the value
  868. * at each step and assigning them to the binding sequentially. However, this is not
  869. * correct: once an iterator is exhausted, it must not be called again. This complicates
  870. * the bytecode. In order to accomplish this, we do the following:
  871. *
  872. * - Reserve a special boolean register which holds 'true' if the iterator is exhausted,
  873. * and false otherwise
  874. * - When we are retrieving the value which should be bound, we first check this register.
  875. * If it is 'true', we load undefined into the accumulator. Otherwise, we grab the next
  876. * value from the iterator and store it into the accumulator.
  877. *
  878. * Note that the is_exhausted register does not need to be loaded with false because the
  879. * first IteratorNext bytecode is _not_ proceeded by an exhausted check, as it is
  880. * unnecessary.
  881. */
  882. auto is_iterator_exhausted_register = generator.allocate_register();
  883. auto iterator_reg = generator.allocate_register();
  884. generator.emit<Bytecode::Op::Load>(value_reg);
  885. generator.emit<Bytecode::Op::GetIterator>();
  886. generator.emit<Bytecode::Op::Store>(iterator_reg);
  887. bool first = true;
  888. auto temp_iterator_result_reg = generator.allocate_register();
  889. auto assign_accumulator_to_alias = [&](auto& alias) {
  890. return alias.visit(
  891. [&](Empty) -> Bytecode::CodeGenerationErrorOr<void> {
  892. // This element is an elision
  893. return {};
  894. },
  895. [&](NonnullRefPtr<Identifier> const& identifier) -> Bytecode::CodeGenerationErrorOr<void> {
  896. auto interned_index = generator.intern_identifier(identifier->string());
  897. generator.emit<Bytecode::Op::SetVariable>(interned_index, initialization_mode);
  898. return {};
  899. },
  900. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  901. // Store the accumulator value in a permanent register
  902. auto target_reg = generator.allocate_register();
  903. generator.emit<Bytecode::Op::Store>(target_reg);
  904. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, target_reg);
  905. },
  906. [&](NonnullRefPtr<MemberExpression> const& expr) -> Bytecode::CodeGenerationErrorOr<void> {
  907. return Bytecode::CodeGenerationError {
  908. expr.ptr(),
  909. "Unimplemented alias mode: MemberExpression"sv,
  910. };
  911. });
  912. };
  913. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  914. VERIFY(name.has<Empty>());
  915. if (is_rest) {
  916. if (first) {
  917. // The iterator has not been called, and is thus known to be not exhausted
  918. generator.emit<Bytecode::Op::Load>(iterator_reg);
  919. generator.emit<Bytecode::Op::IteratorToArray>();
  920. } else {
  921. auto& if_exhausted_block = generator.make_block();
  922. auto& if_not_exhausted_block = generator.make_block();
  923. auto& continuation_block = generator.make_block();
  924. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  925. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  926. Bytecode::Label { if_exhausted_block },
  927. Bytecode::Label { if_not_exhausted_block });
  928. generator.switch_to_basic_block(if_exhausted_block);
  929. generator.emit<Bytecode::Op::NewArray>();
  930. generator.emit<Bytecode::Op::Jump>().set_targets(
  931. Bytecode::Label { continuation_block },
  932. {});
  933. generator.switch_to_basic_block(if_not_exhausted_block);
  934. generator.emit<Bytecode::Op::Load>(iterator_reg);
  935. generator.emit<Bytecode::Op::IteratorToArray>();
  936. generator.emit<Bytecode::Op::Jump>().set_targets(
  937. Bytecode::Label { continuation_block },
  938. {});
  939. generator.switch_to_basic_block(continuation_block);
  940. }
  941. return assign_accumulator_to_alias(alias);
  942. }
  943. // In the first iteration of the loop, a few things are true which can save
  944. // us some bytecode:
  945. // - the iterator result is still in the accumulator, so we can avoid a load
  946. // - the iterator is not yet exhausted, which can save us a jump and some
  947. // creation
  948. auto& iterator_is_exhausted_block = generator.make_block();
  949. if (!first) {
  950. auto& iterator_is_not_exhausted_block = generator.make_block();
  951. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  952. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  953. Bytecode::Label { iterator_is_exhausted_block },
  954. Bytecode::Label { iterator_is_not_exhausted_block });
  955. generator.switch_to_basic_block(iterator_is_not_exhausted_block);
  956. generator.emit<Bytecode::Op::Load>(iterator_reg);
  957. }
  958. generator.emit<Bytecode::Op::IteratorNext>();
  959. generator.emit<Bytecode::Op::Store>(temp_iterator_result_reg);
  960. generator.emit<Bytecode::Op::IteratorResultDone>();
  961. generator.emit<Bytecode::Op::Store>(is_iterator_exhausted_register);
  962. // We still have to check for exhaustion here. If the iterator is exhausted,
  963. // we need to bail before trying to get the value
  964. auto& no_bail_block = generator.make_block();
  965. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  966. Bytecode::Label { iterator_is_exhausted_block },
  967. Bytecode::Label { no_bail_block });
  968. generator.switch_to_basic_block(no_bail_block);
  969. // Get the next value in the iterator
  970. generator.emit<Bytecode::Op::Load>(temp_iterator_result_reg);
  971. generator.emit<Bytecode::Op::IteratorResultValue>();
  972. auto& create_binding_block = generator.make_block();
  973. generator.emit<Bytecode::Op::Jump>().set_targets(
  974. Bytecode::Label { create_binding_block },
  975. {});
  976. // The iterator is exhausted, so we just load undefined and continue binding
  977. generator.switch_to_basic_block(iterator_is_exhausted_block);
  978. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  979. generator.emit<Bytecode::Op::Jump>().set_targets(
  980. Bytecode::Label { create_binding_block },
  981. {});
  982. // Create the actual binding. The value which this entry must bind is now in the
  983. // accumulator. We can proceed, processing the alias as a nested destructuring
  984. // pattern if necessary.
  985. generator.switch_to_basic_block(create_binding_block);
  986. TRY(assign_accumulator_to_alias(alias));
  987. first = false;
  988. }
  989. return {};
  990. }
  991. 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)
  992. {
  993. if (pattern.kind == BindingPattern::Kind::Object)
  994. return generate_object_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  995. return generate_array_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  996. }
  997. static Bytecode::CodeGenerationErrorOr<void> assign_accumulator_to_variable_declarator(Bytecode::Generator& generator, VariableDeclarator const& declarator, VariableDeclaration const& declaration)
  998. {
  999. auto initialization_mode = declaration.is_lexical_declaration() ? Bytecode::Op::SetVariable::InitializationMode::Initialize : Bytecode::Op::SetVariable::InitializationMode::Set;
  1000. auto environment_mode = declaration.is_lexical_declaration() ? Bytecode::Op::EnvironmentMode::Lexical : Bytecode::Op::EnvironmentMode::Var;
  1001. return declarator.target().visit(
  1002. [&](NonnullRefPtr<Identifier> const& id) -> Bytecode::CodeGenerationErrorOr<void> {
  1003. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(id->string()), initialization_mode, environment_mode);
  1004. return {};
  1005. },
  1006. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  1007. auto value_register = generator.allocate_register();
  1008. generator.emit<Bytecode::Op::Store>(value_register);
  1009. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, value_register);
  1010. });
  1011. }
  1012. Bytecode::CodeGenerationErrorOr<void> VariableDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1013. {
  1014. for (auto& declarator : m_declarations) {
  1015. if (declarator.init())
  1016. TRY(declarator.init()->generate_bytecode(generator));
  1017. else
  1018. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1019. TRY(assign_accumulator_to_variable_declarator(generator, declarator, *this));
  1020. }
  1021. return {};
  1022. }
  1023. Bytecode::CodeGenerationErrorOr<void> CallExpression::generate_bytecode(Bytecode::Generator& generator) const
  1024. {
  1025. auto callee_reg = generator.allocate_register();
  1026. auto this_reg = generator.allocate_register();
  1027. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1028. generator.emit<Bytecode::Op::Store>(this_reg);
  1029. if (is<NewExpression>(this)) {
  1030. TRY(m_callee->generate_bytecode(generator));
  1031. generator.emit<Bytecode::Op::Store>(callee_reg);
  1032. } else if (is<SuperExpression>(*m_callee)) {
  1033. return Bytecode::CodeGenerationError {
  1034. this,
  1035. "Unimplemented callee kind: SuperExpression"sv,
  1036. };
  1037. } else if (is<MemberExpression>(*m_callee)) {
  1038. auto& member_expression = static_cast<const MemberExpression&>(*m_callee);
  1039. if (is<SuperExpression>(member_expression.object())) {
  1040. return Bytecode::CodeGenerationError {
  1041. this,
  1042. "Unimplemented callee kind: MemberExpression on SuperExpression"sv,
  1043. };
  1044. }
  1045. TRY(member_expression.object().generate_bytecode(generator));
  1046. generator.emit<Bytecode::Op::Store>(this_reg);
  1047. if (member_expression.is_computed()) {
  1048. TRY(member_expression.property().generate_bytecode(generator));
  1049. generator.emit<Bytecode::Op::GetByValue>(this_reg);
  1050. } else {
  1051. auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string());
  1052. generator.emit<Bytecode::Op::GetById>(identifier_table_ref);
  1053. }
  1054. generator.emit<Bytecode::Op::Store>(callee_reg);
  1055. } else {
  1056. // FIXME: this = global object in sloppy mode.
  1057. TRY(m_callee->generate_bytecode(generator));
  1058. generator.emit<Bytecode::Op::Store>(callee_reg);
  1059. }
  1060. Vector<Bytecode::Register> argument_registers;
  1061. for (auto& arg : m_arguments) {
  1062. TRY(arg.value->generate_bytecode(generator));
  1063. auto arg_reg = generator.allocate_register();
  1064. generator.emit<Bytecode::Op::Store>(arg_reg);
  1065. argument_registers.append(arg_reg);
  1066. }
  1067. Bytecode::Op::Call::CallType call_type;
  1068. if (is<NewExpression>(*this)) {
  1069. call_type = Bytecode::Op::Call::CallType::Construct;
  1070. } else {
  1071. call_type = Bytecode::Op::Call::CallType::Call;
  1072. }
  1073. generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_registers.size(), call_type, callee_reg, this_reg, argument_registers);
  1074. return {};
  1075. }
  1076. Bytecode::CodeGenerationErrorOr<void> ReturnStatement::generate_bytecode(Bytecode::Generator& generator) const
  1077. {
  1078. if (m_argument)
  1079. TRY(m_argument->generate_bytecode(generator));
  1080. if (generator.is_in_generator_or_async_function()) {
  1081. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1082. generator.emit<Bytecode::Op::Yield>(nullptr);
  1083. } else {
  1084. generator.perform_needed_unwinds<Bytecode::Op::Return>();
  1085. generator.emit<Bytecode::Op::Return>();
  1086. }
  1087. return {};
  1088. }
  1089. Bytecode::CodeGenerationErrorOr<void> YieldExpression::generate_bytecode(Bytecode::Generator& generator) const
  1090. {
  1091. VERIFY(generator.is_in_generator_function());
  1092. if (m_is_yield_from) {
  1093. return Bytecode::CodeGenerationError {
  1094. this,
  1095. "Unimplemented form: `yield*`"sv,
  1096. };
  1097. }
  1098. if (m_argument)
  1099. TRY(m_argument->generate_bytecode(generator));
  1100. auto& continuation_block = generator.make_block();
  1101. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1102. generator.switch_to_basic_block(continuation_block);
  1103. return {};
  1104. }
  1105. Bytecode::CodeGenerationErrorOr<void> IfStatement::generate_bytecode(Bytecode::Generator& generator) const
  1106. {
  1107. // test
  1108. // jump if_true (true) true (false) false
  1109. // true
  1110. // jump always (true) end
  1111. // false
  1112. // jump always (true) end
  1113. // end
  1114. auto& true_block = generator.make_block();
  1115. auto& false_block = generator.make_block();
  1116. TRY(m_predicate->generate_bytecode(generator));
  1117. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1118. Bytecode::Label { true_block },
  1119. Bytecode::Label { false_block });
  1120. Bytecode::Op::Jump* true_block_jump { nullptr };
  1121. generator.switch_to_basic_block(true_block);
  1122. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1123. TRY(m_consequent->generate_bytecode(generator));
  1124. if (!generator.is_current_block_terminated())
  1125. true_block_jump = &generator.emit<Bytecode::Op::Jump>();
  1126. generator.switch_to_basic_block(false_block);
  1127. auto& end_block = generator.make_block();
  1128. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1129. if (m_alternate)
  1130. TRY(m_alternate->generate_bytecode(generator));
  1131. if (!generator.is_current_block_terminated())
  1132. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1133. if (true_block_jump)
  1134. true_block_jump->set_targets(Bytecode::Label { end_block }, {});
  1135. generator.switch_to_basic_block(end_block);
  1136. return {};
  1137. }
  1138. Bytecode::CodeGenerationErrorOr<void> ContinueStatement::generate_bytecode(Bytecode::Generator& generator) const
  1139. {
  1140. generator.perform_needed_unwinds<Bytecode::Op::Jump>();
  1141. generator.emit<Bytecode::Op::Jump>().set_targets(
  1142. generator.nearest_continuable_scope(),
  1143. {});
  1144. return {};
  1145. }
  1146. Bytecode::CodeGenerationErrorOr<void> DebuggerStatement::generate_bytecode(Bytecode::Generator&) const
  1147. {
  1148. return {};
  1149. }
  1150. Bytecode::CodeGenerationErrorOr<void> ConditionalExpression::generate_bytecode(Bytecode::Generator& generator) const
  1151. {
  1152. // test
  1153. // jump if_true (true) true (false) false
  1154. // true
  1155. // jump always (true) end
  1156. // false
  1157. // jump always (true) end
  1158. // end
  1159. auto& true_block = generator.make_block();
  1160. auto& false_block = generator.make_block();
  1161. auto& end_block = generator.make_block();
  1162. TRY(m_test->generate_bytecode(generator));
  1163. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1164. Bytecode::Label { true_block },
  1165. Bytecode::Label { false_block });
  1166. generator.switch_to_basic_block(true_block);
  1167. TRY(m_consequent->generate_bytecode(generator));
  1168. generator.emit<Bytecode::Op::Jump>().set_targets(
  1169. Bytecode::Label { end_block },
  1170. {});
  1171. generator.switch_to_basic_block(false_block);
  1172. TRY(m_alternate->generate_bytecode(generator));
  1173. generator.emit<Bytecode::Op::Jump>().set_targets(
  1174. Bytecode::Label { end_block },
  1175. {});
  1176. generator.switch_to_basic_block(end_block);
  1177. return {};
  1178. }
  1179. Bytecode::CodeGenerationErrorOr<void> SequenceExpression::generate_bytecode(Bytecode::Generator& generator) const
  1180. {
  1181. for (auto& expression : m_expressions)
  1182. TRY(expression.generate_bytecode(generator));
  1183. return {};
  1184. }
  1185. Bytecode::CodeGenerationErrorOr<void> TemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1186. {
  1187. auto string_reg = generator.allocate_register();
  1188. for (size_t i = 0; i < m_expressions.size(); i++) {
  1189. TRY(m_expressions[i].generate_bytecode(generator));
  1190. if (i == 0) {
  1191. generator.emit<Bytecode::Op::Store>(string_reg);
  1192. } else {
  1193. generator.emit<Bytecode::Op::ConcatString>(string_reg);
  1194. }
  1195. }
  1196. generator.emit<Bytecode::Op::Load>(string_reg);
  1197. return {};
  1198. }
  1199. Bytecode::CodeGenerationErrorOr<void> TaggedTemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1200. {
  1201. TRY(m_tag->generate_bytecode(generator));
  1202. auto tag_reg = generator.allocate_register();
  1203. generator.emit<Bytecode::Op::Store>(tag_reg);
  1204. Vector<Bytecode::Register> string_regs;
  1205. auto& expressions = m_template_literal->expressions();
  1206. for (size_t i = 0; i < expressions.size(); ++i) {
  1207. if (i % 2 != 0)
  1208. continue;
  1209. string_regs.append(generator.allocate_register());
  1210. }
  1211. size_t reg_index = 0;
  1212. for (size_t i = 0; i < expressions.size(); ++i) {
  1213. if (i % 2 != 0)
  1214. continue;
  1215. TRY(expressions[i].generate_bytecode(generator));
  1216. auto string_reg = string_regs[reg_index++];
  1217. generator.emit<Bytecode::Op::Store>(string_reg);
  1218. }
  1219. if (string_regs.is_empty()) {
  1220. generator.emit<Bytecode::Op::NewArray>();
  1221. } else {
  1222. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { string_regs.first(), string_regs.last() });
  1223. }
  1224. auto strings_reg = generator.allocate_register();
  1225. generator.emit<Bytecode::Op::Store>(strings_reg);
  1226. Vector<Bytecode::Register> argument_regs;
  1227. argument_regs.append(strings_reg);
  1228. for (size_t i = 0; i < expressions.size(); ++i) {
  1229. if (i % 2 == 0)
  1230. continue;
  1231. TRY(expressions[i].generate_bytecode(generator));
  1232. auto string_reg = generator.allocate_register();
  1233. generator.emit<Bytecode::Op::Store>(string_reg);
  1234. argument_regs.append(string_reg);
  1235. }
  1236. Vector<Bytecode::Register> raw_string_regs;
  1237. for ([[maybe_unused]] auto& raw_string : m_template_literal->raw_strings())
  1238. string_regs.append(generator.allocate_register());
  1239. reg_index = 0;
  1240. for (auto& raw_string : m_template_literal->raw_strings()) {
  1241. TRY(raw_string.generate_bytecode(generator));
  1242. auto raw_string_reg = string_regs[reg_index++];
  1243. generator.emit<Bytecode::Op::Store>(raw_string_reg);
  1244. raw_string_regs.append(raw_string_reg);
  1245. }
  1246. if (raw_string_regs.is_empty()) {
  1247. generator.emit<Bytecode::Op::NewArray>();
  1248. } else {
  1249. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { raw_string_regs.first(), raw_string_regs.last() });
  1250. }
  1251. auto raw_strings_reg = generator.allocate_register();
  1252. generator.emit<Bytecode::Op::Store>(raw_strings_reg);
  1253. generator.emit<Bytecode::Op::Load>(strings_reg);
  1254. generator.emit<Bytecode::Op::PutById>(raw_strings_reg, generator.intern_identifier("raw"));
  1255. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1256. auto this_reg = generator.allocate_register();
  1257. generator.emit<Bytecode::Op::Store>(this_reg);
  1258. generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_regs.size(), Bytecode::Op::Call::CallType::Call, tag_reg, this_reg, move(argument_regs));
  1259. return {};
  1260. }
  1261. Bytecode::CodeGenerationErrorOr<void> UpdateExpression::generate_bytecode(Bytecode::Generator& generator) const
  1262. {
  1263. TRY(generator.emit_load_from_reference(*m_argument));
  1264. Optional<Bytecode::Register> previous_value_for_postfix_reg;
  1265. if (!m_prefixed) {
  1266. previous_value_for_postfix_reg = generator.allocate_register();
  1267. generator.emit<Bytecode::Op::Store>(*previous_value_for_postfix_reg);
  1268. }
  1269. if (m_op == UpdateOp::Increment)
  1270. generator.emit<Bytecode::Op::Increment>();
  1271. else
  1272. generator.emit<Bytecode::Op::Decrement>();
  1273. TRY(generator.emit_store_to_reference(*m_argument));
  1274. if (!m_prefixed)
  1275. generator.emit<Bytecode::Op::Load>(*previous_value_for_postfix_reg);
  1276. return {};
  1277. }
  1278. Bytecode::CodeGenerationErrorOr<void> ThrowStatement::generate_bytecode(Bytecode::Generator& generator) const
  1279. {
  1280. TRY(m_argument->generate_bytecode(generator));
  1281. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1282. generator.emit<Bytecode::Op::Throw>();
  1283. return {};
  1284. }
  1285. Bytecode::CodeGenerationErrorOr<void> BreakStatement::generate_bytecode(Bytecode::Generator& generator) const
  1286. {
  1287. generator.perform_needed_unwinds<Bytecode::Op::Jump>(true);
  1288. generator.emit<Bytecode::Op::Jump>().set_targets(
  1289. generator.nearest_breakable_scope(),
  1290. {});
  1291. return {};
  1292. }
  1293. Bytecode::CodeGenerationErrorOr<void> TryStatement::generate_bytecode(Bytecode::Generator& generator) const
  1294. {
  1295. auto& saved_block = generator.current_block();
  1296. Optional<Bytecode::Label> handler_target;
  1297. Optional<Bytecode::Label> finalizer_target;
  1298. Bytecode::BasicBlock* next_block { nullptr };
  1299. if (m_finalizer) {
  1300. auto& finalizer_block = generator.make_block();
  1301. generator.switch_to_basic_block(finalizer_block);
  1302. TRY(m_finalizer->generate_bytecode(generator));
  1303. if (!generator.is_current_block_terminated()) {
  1304. next_block = &generator.make_block();
  1305. auto next_target = Bytecode::Label { *next_block };
  1306. generator.emit<Bytecode::Op::ContinuePendingUnwind>(next_target);
  1307. }
  1308. finalizer_target = Bytecode::Label { finalizer_block };
  1309. }
  1310. if (m_handler) {
  1311. auto& handler_block = generator.make_block();
  1312. generator.switch_to_basic_block(handler_block);
  1313. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  1314. TRY(m_handler->parameter().visit(
  1315. [&](FlyString const& parameter) -> Bytecode::CodeGenerationErrorOr<void> {
  1316. if (!parameter.is_empty()) {
  1317. auto parameter_identifier = generator.intern_identifier(parameter);
  1318. generator.register_binding(parameter_identifier);
  1319. generator.emit<Bytecode::Op::CreateVariable>(parameter_identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1320. generator.emit<Bytecode::Op::SetVariable>(parameter_identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1321. }
  1322. return {};
  1323. },
  1324. [&](NonnullRefPtr<BindingPattern> const&) -> Bytecode::CodeGenerationErrorOr<void> {
  1325. // FIXME: Implement this path when the above DeclarativeEnvironment issue is dealt with.
  1326. return Bytecode::CodeGenerationError {
  1327. this,
  1328. "Unimplemented catch argument: BindingPattern"sv,
  1329. };
  1330. }));
  1331. TRY(m_handler->body().generate_bytecode(generator));
  1332. handler_target = Bytecode::Label { handler_block };
  1333. generator.end_variable_scope();
  1334. if (!generator.is_current_block_terminated()) {
  1335. if (m_finalizer) {
  1336. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1337. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1338. } else {
  1339. VERIFY(!next_block);
  1340. next_block = &generator.make_block();
  1341. auto next_target = Bytecode::Label { *next_block };
  1342. generator.emit<Bytecode::Op::Jump>(next_target);
  1343. }
  1344. }
  1345. }
  1346. auto& target_block = generator.make_block();
  1347. generator.switch_to_basic_block(saved_block);
  1348. generator.emit<Bytecode::Op::EnterUnwindContext>(Bytecode::Label { target_block }, handler_target, finalizer_target);
  1349. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1350. generator.switch_to_basic_block(target_block);
  1351. TRY(m_block->generate_bytecode(generator));
  1352. if (!generator.is_current_block_terminated()) {
  1353. if (m_finalizer) {
  1354. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1355. } else {
  1356. auto& block = generator.make_block();
  1357. generator.emit<Bytecode::Op::FinishUnwind>(Bytecode::Label { block });
  1358. next_block = &block;
  1359. }
  1360. }
  1361. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1362. generator.switch_to_basic_block(next_block ? *next_block : saved_block);
  1363. return {};
  1364. }
  1365. Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_bytecode(Bytecode::Generator& generator) const
  1366. {
  1367. auto discriminant_reg = generator.allocate_register();
  1368. TRY(m_discriminant->generate_bytecode(generator));
  1369. generator.emit<Bytecode::Op::Store>(discriminant_reg);
  1370. Vector<Bytecode::BasicBlock&> case_blocks;
  1371. Bytecode::BasicBlock* default_block { nullptr };
  1372. Bytecode::BasicBlock* next_test_block = &generator.make_block();
  1373. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_test_block }, {});
  1374. for (auto& switch_case : m_cases) {
  1375. auto& case_block = generator.make_block();
  1376. if (switch_case.test()) {
  1377. generator.switch_to_basic_block(*next_test_block);
  1378. TRY(switch_case.test()->generate_bytecode(generator));
  1379. generator.emit<Bytecode::Op::StrictlyEquals>(discriminant_reg);
  1380. next_test_block = &generator.make_block();
  1381. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { case_block }, Bytecode::Label { *next_test_block });
  1382. } else {
  1383. default_block = &case_block;
  1384. }
  1385. case_blocks.append(case_block);
  1386. }
  1387. generator.switch_to_basic_block(*next_test_block);
  1388. auto& end_block = generator.make_block();
  1389. if (default_block != nullptr) {
  1390. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *default_block }, {});
  1391. } else {
  1392. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1393. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1394. }
  1395. auto current_block = case_blocks.begin();
  1396. generator.begin_breakable_scope(Bytecode::Label { end_block });
  1397. for (auto& switch_case : m_cases) {
  1398. generator.switch_to_basic_block(*current_block);
  1399. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1400. for (auto& statement : switch_case.children()) {
  1401. TRY(statement.generate_bytecode(generator));
  1402. if (generator.is_current_block_terminated())
  1403. break;
  1404. }
  1405. if (!generator.is_current_block_terminated()) {
  1406. auto next_block = current_block;
  1407. next_block++;
  1408. if (next_block.is_end()) {
  1409. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1410. } else {
  1411. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_block }, {});
  1412. }
  1413. }
  1414. current_block++;
  1415. }
  1416. generator.end_breakable_scope();
  1417. generator.switch_to_basic_block(end_block);
  1418. return {};
  1419. }
  1420. Bytecode::CodeGenerationErrorOr<void> ClassDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1421. {
  1422. TRY(m_class_expression->generate_bytecode(generator));
  1423. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(m_class_expression.ptr()->name()), Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1424. return {};
  1425. }
  1426. Bytecode::CodeGenerationErrorOr<void> ClassExpression::generate_bytecode(Bytecode::Generator& generator) const
  1427. {
  1428. generator.emit<Bytecode::Op::NewClass>(*this);
  1429. return {};
  1430. }
  1431. Bytecode::CodeGenerationErrorOr<void> ThisExpression::generate_bytecode(Bytecode::Generator& generator) const
  1432. {
  1433. generator.emit<Bytecode::Op::ResolveThisBinding>();
  1434. return {};
  1435. }
  1436. Bytecode::CodeGenerationErrorOr<void> AwaitExpression::generate_bytecode(Bytecode::Generator& generator) const
  1437. {
  1438. VERIFY(generator.is_in_async_function());
  1439. // Transform `await expr` to `yield expr`
  1440. TRY(m_argument->generate_bytecode(generator));
  1441. auto& continuation_block = generator.make_block();
  1442. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1443. generator.switch_to_basic_block(continuation_block);
  1444. return {};
  1445. }
  1446. Bytecode::CodeGenerationErrorOr<void> WithStatement::generate_bytecode(Bytecode::Generator& generator) const
  1447. {
  1448. TRY(m_object->generate_bytecode(generator));
  1449. generator.emit<Bytecode::Op::EnterObjectEnvironment>();
  1450. // EnterObjectEnvironment sets the running execution context's lexical_environment to a new Object Environment.
  1451. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1452. TRY(m_body->generate_bytecode(generator));
  1453. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1454. if (!generator.is_current_block_terminated())
  1455. generator.emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  1456. return {};
  1457. }
  1458. enum class LHSKind {
  1459. Assignment,
  1460. VarBinding,
  1461. LexicalBinding,
  1462. };
  1463. enum class IterationKind {
  1464. Enumerate,
  1465. Iterate,
  1466. AsyncIterate,
  1467. };
  1468. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  1469. struct ForInOfHeadEvaluationResult {
  1470. bool is_destructuring { false };
  1471. LHSKind lhs_kind { LHSKind::Assignment };
  1472. };
  1473. static Bytecode::CodeGenerationErrorOr<ForInOfHeadEvaluationResult> for_in_of_head_evaluation(Bytecode::Generator& generator, IterationKind iteration_kind, Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> const& lhs, NonnullRefPtr<ASTNode> const& rhs)
  1474. {
  1475. ForInOfHeadEvaluationResult result {};
  1476. if (auto* ast_ptr = lhs.get_pointer<NonnullRefPtr<ASTNode>>(); ast_ptr && is<VariableDeclaration>(**ast_ptr)) {
  1477. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  1478. // ForInOfStatement : for ( var ForBinding in Expression ) Statement
  1479. // ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  1480. // ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  1481. // ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  1482. auto& variable_declaration = static_cast<VariableDeclaration const&>(**ast_ptr);
  1483. result.is_destructuring = variable_declaration.declarations().first().target().has<NonnullRefPtr<BindingPattern>>();
  1484. result.lhs_kind = variable_declaration.is_lexical_declaration() ? LHSKind::LexicalBinding : LHSKind::VarBinding;
  1485. // 1. Let oldEnv be the running execution context's LexicalEnvironment.
  1486. // NOTE: 'uninitializedBoundNames' refers to the lexical bindings (i.e. Const/Let) present in the second and last form.
  1487. // 2. If uninitializedBoundNames is not an empty List, then
  1488. bool entered_lexical_scope = false;
  1489. if (variable_declaration.declaration_kind() != DeclarationKind::Var) {
  1490. entered_lexical_scope = true;
  1491. // a. Assert: uninitializedBoundNames has no duplicate entries.
  1492. // b. Let newEnv be NewDeclarativeEnvironment(oldEnv).
  1493. generator.begin_variable_scope();
  1494. // c. For each String name of uninitializedBoundNames, do
  1495. variable_declaration.for_each_bound_name([&](auto const& name) {
  1496. // i. Perform ! newEnv.CreateMutableBinding(name, false).
  1497. auto identifier = generator.intern_identifier(name);
  1498. generator.register_binding(identifier);
  1499. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1500. });
  1501. // d. Set the running execution context's LexicalEnvironment to newEnv.
  1502. // NOTE: Done by CreateEnvironment.
  1503. }
  1504. // 3. Let exprRef be the result of evaluating expr.
  1505. TRY(rhs->generate_bytecode(generator));
  1506. // 4. Set the running execution context's LexicalEnvironment to oldEnv.
  1507. if (entered_lexical_scope)
  1508. generator.end_variable_scope();
  1509. // 5. Let exprValue be ? GetValue(exprRef).
  1510. // NOTE: No need to store this anywhere.
  1511. // 6. If iterationKind is enumerate, then
  1512. if (iteration_kind == IterationKind::Enumerate) {
  1513. // a. If exprValue is undefined or null, then
  1514. auto& nullish_block = generator.make_block();
  1515. auto& continuation_block = generator.make_block();
  1516. auto& jump = generator.emit<Bytecode::Op::JumpNullish>();
  1517. jump.set_targets(Bytecode::Label { nullish_block }, Bytecode::Label { continuation_block });
  1518. // i. Return Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  1519. generator.switch_to_basic_block(nullish_block);
  1520. generator.perform_needed_unwinds<Bytecode::Op::Jump>(true);
  1521. generator.emit<Bytecode::Op::Jump>().set_targets(generator.nearest_breakable_scope(), {});
  1522. generator.switch_to_basic_block(continuation_block);
  1523. // b. Let obj be ! ToObject(exprValue).
  1524. // NOTE: GetObjectPropertyIterator does this.
  1525. // c. Let iterator be EnumerateObjectProperties(obj).
  1526. // d. Let nextMethod be ! GetV(iterator, "next").
  1527. // e. Return the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
  1528. generator.emit<Bytecode::Op::GetObjectPropertyIterator>();
  1529. }
  1530. // 7. Else,
  1531. else {
  1532. // a. Assert: iterationKind is iterate or async-iterate.
  1533. // b. If iterationKind is async-iterate, let iteratorHint be async.
  1534. if (iteration_kind == IterationKind::AsyncIterate) {
  1535. return Bytecode::CodeGenerationError {
  1536. rhs.ptr(),
  1537. "Unimplemented iteration mode: AsyncIterate"sv,
  1538. };
  1539. }
  1540. // c. Else, let iteratorHint be sync.
  1541. // d. Return ? GetIterator(exprValue, iteratorHint).
  1542. generator.emit<Bytecode::Op::GetIterator>();
  1543. }
  1544. } else {
  1545. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  1546. // ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  1547. // ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  1548. // Skip everything except steps 3, 5 and 7 (see above true branch for listing).
  1549. result.lhs_kind = LHSKind::Assignment;
  1550. // 3. Let exprRef be the result of evaluating expr.
  1551. TRY(rhs->generate_bytecode(generator));
  1552. // 5. Let exprValue be ? GetValue(exprRef).
  1553. // NOTE: No need to store this anywhere.
  1554. // a. Assert: iterationKind is iterate or async-iterate.
  1555. // b. If iterationKind is async-iterate, let iteratorHint be async.
  1556. if (iteration_kind == IterationKind::AsyncIterate) {
  1557. return Bytecode::CodeGenerationError {
  1558. rhs.ptr(),
  1559. "Unimplemented iteration mode: AsyncIterate"sv,
  1560. };
  1561. }
  1562. // c. Else, let iteratorHint be sync.
  1563. // d. Return ? GetIterator(exprValue, iteratorHint).
  1564. generator.emit<Bytecode::Op::GetIterator>();
  1565. }
  1566. return result;
  1567. }
  1568. // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  1569. static Bytecode::CodeGenerationErrorOr<void> for_in_of_body_evaluation(Bytecode::Generator& generator, ASTNode const& node, Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> const& lhs, ASTNode const& body, ForInOfHeadEvaluationResult const& head_result, Bytecode::BasicBlock& loop_end, Bytecode::BasicBlock& loop_update)
  1570. {
  1571. auto iterator_register = generator.allocate_register();
  1572. generator.emit<Bytecode::Op::Store>(iterator_register);
  1573. // FIXME: Implement this
  1574. // 1. If iteratorKind is not present, set iteratorKind to sync.
  1575. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  1576. bool has_lexical_binding = false;
  1577. // 3. Let V be undefined.
  1578. // NOTE: We don't need 'V' as the resulting value will naturally flow through via the accumulator register.
  1579. // 4. Let destructuring be IsDestructuring of lhs.
  1580. auto destructuring = head_result.is_destructuring;
  1581. // 5. If destructuring is true and if lhsKind is assignment, then
  1582. if (destructuring) {
  1583. // a. Assert: lhs is a LeftHandSideExpression.
  1584. // b. Let assignmentPattern be the AssignmentPattern that is covered by lhs.
  1585. // FIXME: Implement this.
  1586. return Bytecode::CodeGenerationError {
  1587. &node,
  1588. "Unimplemented: destructuring in for-in/of"sv,
  1589. };
  1590. }
  1591. // 6. Repeat,
  1592. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_update });
  1593. generator.switch_to_basic_block(loop_update);
  1594. // a. Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
  1595. generator.emit<Bytecode::Op::Load>(iterator_register);
  1596. generator.emit<Bytecode::Op::IteratorNext>();
  1597. // FIXME: Implement this:
  1598. // b. If iteratorKind is async, set nextResult to ? Await(nextResult).
  1599. // c. If Type(nextResult) is not Object, throw a TypeError exception.
  1600. // NOTE: IteratorComplete already does this.
  1601. // d. Let done be ? IteratorComplete(nextResult).
  1602. auto iterator_result_register = generator.allocate_register();
  1603. generator.emit<Bytecode::Op::Store>(iterator_result_register);
  1604. generator.emit<Bytecode::Op::IteratorResultDone>();
  1605. // e. If done is true, return V.
  1606. auto& loop_continue = generator.make_block();
  1607. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { loop_end }, Bytecode::Label { loop_continue });
  1608. generator.switch_to_basic_block(loop_continue);
  1609. // f. Let nextValue be ? IteratorValue(nextResult).
  1610. generator.emit<Bytecode::Op::Load>(iterator_result_register);
  1611. generator.emit<Bytecode::Op::IteratorResultValue>();
  1612. // g. If lhsKind is either assignment or varBinding, then
  1613. if (head_result.lhs_kind != LHSKind::LexicalBinding) {
  1614. // i. If destructuring is false, then
  1615. if (!destructuring) {
  1616. // 1. Let lhsRef be the result of evaluating lhs. (It may be evaluated repeatedly.)
  1617. // NOTE: We're skipping all the completion stuff that the spec does, as the unwinding mechanism will take case of doing that.
  1618. if (head_result.lhs_kind == LHSKind::VarBinding) {
  1619. auto& declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode>>());
  1620. VERIFY(declaration.declarations().size() == 1);
  1621. TRY(assign_accumulator_to_variable_declarator(generator, declaration.declarations().first(), declaration));
  1622. } else {
  1623. TRY(generator.emit_store_to_reference(*lhs.get<NonnullRefPtr<ASTNode>>()));
  1624. }
  1625. }
  1626. }
  1627. // h. Else,
  1628. else {
  1629. // i. Assert: lhsKind is lexicalBinding.
  1630. // ii. Assert: lhs is a ForDeclaration.
  1631. // iii. Let iterationEnv be NewDeclarativeEnvironment(oldEnv).
  1632. // iv. Perform ForDeclarationBindingInstantiation of lhs with argument iterationEnv.
  1633. // v. Set the running execution context's LexicalEnvironment to iterationEnv.
  1634. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical);
  1635. has_lexical_binding = true;
  1636. // 14.7.5.4 Runtime Semantics: ForDeclarationBindingInstantiation, https://tc39.es/ecma262/#sec-runtime-semantics-fordeclarationbindinginstantiation
  1637. // 1. Assert: environment is a declarative Environment Record.
  1638. // NOTE: We just made it.
  1639. auto& variable_declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode>>());
  1640. // 2. For each element name of the BoundNames of ForBinding, do
  1641. variable_declaration.for_each_bound_name([&](auto const& name) {
  1642. auto identifier = generator.intern_identifier(name);
  1643. generator.register_binding(identifier, Bytecode::Generator::BindingMode::Lexical);
  1644. // a. If IsConstantDeclaration of LetOrConst is true, then
  1645. if (variable_declaration.is_constant_declaration()) {
  1646. // i. Perform ! environment.CreateImmutableBinding(name, true).
  1647. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  1648. }
  1649. // b. Else,
  1650. else {
  1651. // i. Perform ! environment.CreateMutableBinding(name, false).
  1652. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1653. }
  1654. });
  1655. // 3. Return unused.
  1656. // NOTE: No need to do that as we've inlined this.
  1657. // vi. If destructuring is false, then
  1658. if (!destructuring) {
  1659. // 1. Assert: lhs binds a single name.
  1660. // 2. Let lhsName be the sole element of BoundNames of lhs.
  1661. auto lhs_name = variable_declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->string();
  1662. // 3. Let lhsRef be ! ResolveBinding(lhsName).
  1663. // NOTE: We're skipping all the completion stuff that the spec does, as the unwinding mechanism will take case of doing that.
  1664. auto identifier = generator.intern_identifier(lhs_name);
  1665. generator.emit<Bytecode::Op::SetVariable>(identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Lexical);
  1666. }
  1667. }
  1668. // i. If destructuring is false, then
  1669. if (!destructuring) {
  1670. // i. If lhsRef is an abrupt completion, then
  1671. // 1. Let status be lhsRef.
  1672. // ii. Else if lhsKind is lexicalBinding, then
  1673. // 1. Let status be Completion(InitializeReferencedBinding(lhsRef, nextValue)).
  1674. // iii. Else,
  1675. // 1. Let status be Completion(PutValue(lhsRef, nextValue)).
  1676. // NOTE: This is performed above.
  1677. }
  1678. // j. Else,
  1679. else {
  1680. // FIXME: Implement destructuring
  1681. // i. If lhsKind is assignment, then
  1682. // 1. Let status be Completion(DestructuringAssignmentEvaluation of assignmentPattern with argument nextValue).
  1683. // ii. Else if lhsKind is varBinding, then
  1684. // 1. Assert: lhs is a ForBinding.
  1685. // 2. Let status be Completion(BindingInitialization of lhs with arguments nextValue and undefined).
  1686. // iii. Else,
  1687. // 1. Assert: lhsKind is lexicalBinding.
  1688. // 2. Assert: lhs is a ForDeclaration.
  1689. // 3. Let status be Completion(ForDeclarationBindingInitialization of lhs with arguments nextValue and iterationEnv).
  1690. return Bytecode::CodeGenerationError {
  1691. &node,
  1692. "Unimplemented: destructuring in for-in/of"sv,
  1693. };
  1694. }
  1695. // FIXME: Implement iteration closure.
  1696. // k. If status is an abrupt completion, then
  1697. // i. Set the running execution context's LexicalEnvironment to oldEnv.
  1698. // ii. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  1699. // iii. If iterationKind is enumerate, then
  1700. // 1. Return ? status.
  1701. // iv. Else,
  1702. // 1. Assert: iterationKind is iterate.
  1703. // 2. Return ? IteratorClose(iteratorRecord, status).
  1704. // l. Let result be the result of evaluating stmt.
  1705. TRY(body.generate_bytecode(generator));
  1706. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  1707. if (has_lexical_binding)
  1708. generator.end_variable_scope();
  1709. generator.end_continuable_scope();
  1710. generator.end_breakable_scope();
  1711. // NOTE: If we're here, then the loop definitely continues.
  1712. // n. If LoopContinues(result, labelSet) is false, then
  1713. // i. If iterationKind is enumerate, then
  1714. // 1. Return ? UpdateEmpty(result, V).
  1715. // ii. Else,
  1716. // 1. Assert: iterationKind is iterate.
  1717. // 2. Set status to Completion(UpdateEmpty(result, V)).
  1718. // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  1719. // 4. Return ? IteratorClose(iteratorRecord, status).
  1720. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  1721. // The body can contain an unconditional block terminator (e.g. return, throw), so we have to check for that before generating the Jump.
  1722. if (!generator.is_current_block_terminated())
  1723. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { loop_update }, {});
  1724. generator.switch_to_basic_block(loop_end);
  1725. return {};
  1726. }
  1727. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  1728. Bytecode::CodeGenerationErrorOr<void> ForInStatement::generate_bytecode(Bytecode::Generator& generator) const
  1729. {
  1730. auto& loop_end = generator.make_block();
  1731. auto& loop_update = generator.make_block();
  1732. generator.begin_breakable_scope(Bytecode::Label { loop_end });
  1733. generator.begin_continuable_scope(Bytecode::Label { loop_update });
  1734. auto head_result = TRY(for_in_of_head_evaluation(generator, IterationKind::Enumerate, m_lhs, m_rhs));
  1735. // Now perform the rest of ForInOfLoopEvaluation, given that the accumulator holds the iterator we're supposed to iterate over.
  1736. return for_in_of_body_evaluation(generator, *this, m_lhs, body(), head_result, loop_end, loop_update);
  1737. }
  1738. Bytecode::CodeGenerationErrorOr<void> ForOfStatement::generate_bytecode(Bytecode::Generator& generator) const
  1739. {
  1740. auto& loop_end = generator.make_block();
  1741. auto& loop_update = generator.make_block();
  1742. generator.begin_breakable_scope(Bytecode::Label { loop_end });
  1743. generator.begin_continuable_scope(Bytecode::Label { loop_update });
  1744. auto head_result = TRY(for_in_of_head_evaluation(generator, IterationKind::Iterate, m_lhs, m_rhs));
  1745. // Now perform the rest of ForInOfLoopEvaluation, given that the accumulator holds the iterator we're supposed to iterate over.
  1746. return for_in_of_body_evaluation(generator, *this, m_lhs, body(), head_result, loop_end, loop_update);
  1747. }
  1748. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  1749. Bytecode::CodeGenerationErrorOr<void> MetaProperty::generate_bytecode(Bytecode::Generator& generator) const
  1750. {
  1751. // NewTarget : new . target
  1752. if (m_type == MetaProperty::Type::NewTarget) {
  1753. // 1. Return GetNewTarget().
  1754. generator.emit<Bytecode::Op::GetNewTarget>();
  1755. return {};
  1756. }
  1757. // ImportMeta : import . meta
  1758. if (m_type == MetaProperty::Type::ImportMeta) {
  1759. return Bytecode::CodeGenerationError {
  1760. this,
  1761. "Unimplemented meta property: import.meta"sv,
  1762. };
  1763. }
  1764. VERIFY_NOT_REACHED();
  1765. }
  1766. }