ASTCodegen.cpp 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368
  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. // Note: SwitchStatement has its own codegen, but still calls into this function to handle the scoping of the switch body.
  31. auto is_switch_statement = is<SwitchStatement>(*this);
  32. if (is<BlockStatement>(*this) || is_switch_statement) {
  33. // Perform the steps of BlockDeclarationInstantiation.
  34. if (has_lexical_declarations()) {
  35. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  36. pushed_scope_count++;
  37. }
  38. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  39. auto is_constant_declaration = declaration.is_constant_declaration();
  40. declaration.for_each_bound_name([&](auto const& name) {
  41. auto index = generator.intern_identifier(name);
  42. // NOTE: BlockDeclarationInstantiation takes as input the new lexical environment that was created and checks if there is a binding for the current name only in this new scope.
  43. // For example: `{ let a = 1; { let a = 2; } }`. The second `a` will shadow the first `a` instead of re-initializing or setting it.
  44. if (is_constant_declaration || !generator.has_binding_in_current_scope(index)) {
  45. generator.register_binding(index);
  46. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration);
  47. }
  48. });
  49. if (is<FunctionDeclaration>(declaration)) {
  50. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  51. auto const& name = function_declaration.name();
  52. auto index = generator.intern_identifier(name);
  53. generator.emit<Bytecode::Op::NewFunction>(function_declaration);
  54. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::InitializeOrSet);
  55. }
  56. return {};
  57. });
  58. if (is_switch_statement)
  59. return {};
  60. } else if (is<Program>(*this)) {
  61. // Perform the steps of GlobalDeclarationInstantiation.
  62. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Global, Bytecode::Generator::SurroundingScopeKind::Global);
  63. pushed_scope_count++;
  64. // 1. Let lexNames be the LexicallyDeclaredNames of script.
  65. // 2. Let varNames be the VarDeclaredNames of script.
  66. // 3. For each element name of lexNames, do
  67. (void)for_each_lexically_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
  68. auto identifier = generator.intern_identifier(name);
  69. // a. If env.HasVarDeclaration(name) is true, throw a SyntaxError exception.
  70. // b. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  71. if (generator.has_binding(identifier)) {
  72. // FIXME: Throw an actual SyntaxError instance.
  73. generator.emit<Bytecode::Op::NewString>(generator.intern_string(String::formatted("SyntaxError: toplevel variable already declared: {}", name)));
  74. generator.emit<Bytecode::Op::Throw>();
  75. return {};
  76. }
  77. // FIXME: c. If hasRestrictedGlobalProperty is true, throw a SyntaxError exception.
  78. // d. If hasRestrictedGlobal is true, throw a SyntaxError exception.
  79. return {};
  80. });
  81. // 4. For each element name of varNames, do
  82. (void)for_each_var_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
  83. auto identifier = generator.intern_identifier(name);
  84. // a. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  85. if (generator.has_binding(identifier)) {
  86. // FIXME: Throw an actual SyntaxError instance.
  87. generator.emit<Bytecode::Op::NewString>(generator.intern_string(String::formatted("SyntaxError: toplevel variable already declared: {}", name)));
  88. generator.emit<Bytecode::Op::Throw>();
  89. }
  90. return {};
  91. });
  92. // 5. Let varDeclarations be the VarScopedDeclarations of script.
  93. // 6. Let functionsToInitialize be a new empty List.
  94. Vector<FunctionDeclaration const&> functions_to_initialize;
  95. // 7. Let declaredFunctionNames be a new empty List.
  96. HashTable<FlyString> declared_function_names;
  97. // 8. For each element d of varDeclarations, in reverse List order, do
  98. (void)for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) -> ThrowCompletionOr<void> {
  99. // a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then
  100. // i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
  101. // Note: This is checked in for_each_var_function_declaration_in_reverse_order.
  102. // ii. NOTE: If there are multiple function declarations for the same name, the last declaration is used.
  103. // iii. Let fn be the sole element of the BoundNames of d.
  104. // iv. If fn is not an element of declaredFunctionNames, then
  105. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  106. return {};
  107. // FIXME: 1. Let fnDefinable be ? env.CanDeclareGlobalFunction(fn).
  108. // FIXME: 2. If fnDefinable is false, throw a TypeError exception.
  109. // 3. Append fn to declaredFunctionNames.
  110. // Note: Already done in step iv. above.
  111. // 4. Insert d as the first element of functionsToInitialize.
  112. functions_to_initialize.prepend(function);
  113. return {};
  114. });
  115. // 9. Let declaredVarNames be a new empty List.
  116. HashTable<FlyString> declared_var_names;
  117. // 10. For each element d of varDeclarations, do
  118. (void)for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
  119. // a. If d is a VariableDeclaration, a ForBinding, or a BindingIdentifier, then
  120. // Note: This is done in for_each_var_scoped_variable_declaration.
  121. // i. For each String vn of the BoundNames of d, do
  122. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  123. // 1. If vn is not an element of declaredFunctionNames, then
  124. if (declared_function_names.contains(name))
  125. return {};
  126. // FIXME: a. Let vnDefinable be ? env.CanDeclareGlobalVar(vn).
  127. // FIXME: b. If vnDefinable is false, throw a TypeError exception.
  128. // c. If vn is not an element of declaredVarNames, then
  129. // i. Append vn to declaredVarNames.
  130. declared_var_names.set(name);
  131. return {};
  132. });
  133. });
  134. // 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.
  135. // 12. NOTE: Annex B.3.2.2 adds additional steps at this point.
  136. // 12. Let strict be IsStrict of script.
  137. // 13. If strict is false, then
  138. if (!verify_cast<Program>(*this).is_strict_mode()) {
  139. // a. Let declaredFunctionOrVarNames be the list-concatenation of declaredFunctionNames and declaredVarNames.
  140. // b. For each FunctionDeclaration f that is directly contained in the StatementList of a Block, CaseClause, or DefaultClause Contained within script, do
  141. (void)for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  142. // i. Let F be StringValue of the BindingIdentifier of f.
  143. auto& function_name = function_declaration.name();
  144. // ii. If replacing the FunctionDeclaration f with a VariableStatement that has F as a BindingIdentifier would not produce any Early Errors for script, then
  145. // Note: This step is already performed during parsing and for_each_function_hoistable_with_annexB_extension so this always passes here.
  146. // 1. If env.HasLexicalDeclaration(F) is false, then
  147. auto index = generator.intern_identifier(function_name);
  148. if (generator.has_binding(index, Bytecode::Generator::BindingMode::Lexical))
  149. return;
  150. // FIXME: a. Let fnDefinable be ? env.CanDeclareGlobalVar(F).
  151. // b. If fnDefinable is true, then
  152. // i. NOTE: A var binding for F is only instantiated here if it is neither a VarDeclaredName nor the name of another FunctionDeclaration.
  153. // ii. If declaredFunctionOrVarNames does not contain F, then
  154. if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
  155. // i. Perform ? env.CreateGlobalVarBinding(F, false).
  156. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Var, false, true);
  157. // ii. Append F to declaredFunctionOrVarNames.
  158. declared_function_names.set(function_name);
  159. }
  160. // iii. When the FunctionDeclaration f is evaluated, perform the following steps in place of the FunctionDeclaration Evaluation algorithm provided in 15.2.6:
  161. // i. Let genv be the running execution context's VariableEnvironment.
  162. // ii. Let benv be the running execution context's LexicalEnvironment.
  163. // iii. Let fobj be ! benv.GetBindingValue(F, false).
  164. // iv. Perform ? genv.SetMutableBinding(F, fobj, false).
  165. // v. Return unused.
  166. function_declaration.set_should_do_additional_annexB_steps();
  167. });
  168. }
  169. // 15. For each element d of lexDeclarations, do
  170. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  171. // a. NOTE: Lexically declared names are only instantiated here but not initialized.
  172. // b. For each element dn of the BoundNames of d, do
  173. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  174. auto identifier = generator.intern_identifier(name);
  175. // i. If IsConstantDeclaration of d is true, then
  176. generator.register_binding(identifier);
  177. if (declaration.is_constant_declaration()) {
  178. // 1. Perform ? env.CreateImmutableBinding(dn, true).
  179. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  180. } else {
  181. // ii. Else,
  182. // 1. Perform ? env.CreateMutableBinding(dn, false).
  183. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  184. }
  185. return {};
  186. });
  187. });
  188. // 16. For each Parse Node f of functionsToInitialize, do
  189. for (auto& function_declaration : functions_to_initialize) {
  190. // FIXME: Do this more correctly.
  191. // a. Let fn be the sole element of the BoundNames of f.
  192. // b. Let fo be InstantiateFunctionObject of f with arguments env and privateEnv.
  193. generator.emit<Bytecode::Op::NewFunction>(function_declaration);
  194. // c. Perform ? env.CreateGlobalFunctionBinding(fn, fo, false).
  195. auto const& name = function_declaration.name();
  196. auto index = generator.intern_identifier(name);
  197. if (!generator.has_binding(index)) {
  198. generator.register_binding(index, Bytecode::Generator::BindingMode::Var);
  199. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, false);
  200. }
  201. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  202. }
  203. // 17. For each String vn of declaredVarNames, do
  204. for (auto& var_name : declared_var_names) {
  205. // a. Perform ? env.CreateGlobalVarBinding(vn, false).
  206. auto index = generator.intern_identifier(var_name);
  207. generator.register_binding(index, Bytecode::Generator::BindingMode::Var);
  208. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Var, false, true);
  209. }
  210. } else {
  211. // Perform the steps of FunctionDeclarationInstantiation.
  212. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Var, Bytecode::Generator::SurroundingScopeKind::Function);
  213. pushed_scope_count++;
  214. if (has_lexical_declarations()) {
  215. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Function);
  216. pushed_scope_count++;
  217. }
  218. // FIXME: Implement this boi correctly.
  219. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  220. auto is_constant_declaration = declaration.is_constant_declaration();
  221. declaration.for_each_bound_name([&](auto const& name) {
  222. auto index = generator.intern_identifier(name);
  223. if (is_constant_declaration || !generator.has_binding(index)) {
  224. generator.register_binding(index);
  225. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration);
  226. }
  227. });
  228. if (is<FunctionDeclaration>(declaration)) {
  229. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  230. if (auto result = function_declaration.generate_bytecode(generator); result.is_error()) {
  231. maybe_error = result.release_error();
  232. // To make `for_each_lexically_scoped_declaration` happy.
  233. return failing_completion;
  234. }
  235. auto const& name = function_declaration.name();
  236. auto index = generator.intern_identifier(name);
  237. if (!generator.has_binding(index)) {
  238. generator.register_binding(index);
  239. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, false);
  240. }
  241. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::InitializeOrSet);
  242. }
  243. return {};
  244. });
  245. }
  246. if (maybe_error.has_value())
  247. return maybe_error.release_value();
  248. for (auto& child : children()) {
  249. TRY(child.generate_bytecode(generator));
  250. if (generator.is_current_block_terminated())
  251. break;
  252. }
  253. for (size_t i = 0; i < pushed_scope_count; ++i)
  254. generator.end_variable_scope();
  255. return {};
  256. }
  257. Bytecode::CodeGenerationErrorOr<void> EmptyStatement::generate_bytecode(Bytecode::Generator&) const
  258. {
  259. return {};
  260. }
  261. Bytecode::CodeGenerationErrorOr<void> ExpressionStatement::generate_bytecode(Bytecode::Generator& generator) const
  262. {
  263. return m_expression->generate_bytecode(generator);
  264. }
  265. Bytecode::CodeGenerationErrorOr<void> BinaryExpression::generate_bytecode(Bytecode::Generator& generator) const
  266. {
  267. TRY(m_lhs->generate_bytecode(generator));
  268. auto lhs_reg = generator.allocate_register();
  269. generator.emit<Bytecode::Op::Store>(lhs_reg);
  270. TRY(m_rhs->generate_bytecode(generator));
  271. switch (m_op) {
  272. case BinaryOp::Addition:
  273. generator.emit<Bytecode::Op::Add>(lhs_reg);
  274. break;
  275. case BinaryOp::Subtraction:
  276. generator.emit<Bytecode::Op::Sub>(lhs_reg);
  277. break;
  278. case BinaryOp::Multiplication:
  279. generator.emit<Bytecode::Op::Mul>(lhs_reg);
  280. break;
  281. case BinaryOp::Division:
  282. generator.emit<Bytecode::Op::Div>(lhs_reg);
  283. break;
  284. case BinaryOp::Modulo:
  285. generator.emit<Bytecode::Op::Mod>(lhs_reg);
  286. break;
  287. case BinaryOp::Exponentiation:
  288. generator.emit<Bytecode::Op::Exp>(lhs_reg);
  289. break;
  290. case BinaryOp::GreaterThan:
  291. generator.emit<Bytecode::Op::GreaterThan>(lhs_reg);
  292. break;
  293. case BinaryOp::GreaterThanEquals:
  294. generator.emit<Bytecode::Op::GreaterThanEquals>(lhs_reg);
  295. break;
  296. case BinaryOp::LessThan:
  297. generator.emit<Bytecode::Op::LessThan>(lhs_reg);
  298. break;
  299. case BinaryOp::LessThanEquals:
  300. generator.emit<Bytecode::Op::LessThanEquals>(lhs_reg);
  301. break;
  302. case BinaryOp::LooselyInequals:
  303. generator.emit<Bytecode::Op::LooselyInequals>(lhs_reg);
  304. break;
  305. case BinaryOp::LooselyEquals:
  306. generator.emit<Bytecode::Op::LooselyEquals>(lhs_reg);
  307. break;
  308. case BinaryOp::StrictlyInequals:
  309. generator.emit<Bytecode::Op::StrictlyInequals>(lhs_reg);
  310. break;
  311. case BinaryOp::StrictlyEquals:
  312. generator.emit<Bytecode::Op::StrictlyEquals>(lhs_reg);
  313. break;
  314. case BinaryOp::BitwiseAnd:
  315. generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
  316. break;
  317. case BinaryOp::BitwiseOr:
  318. generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
  319. break;
  320. case BinaryOp::BitwiseXor:
  321. generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
  322. break;
  323. case BinaryOp::LeftShift:
  324. generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
  325. break;
  326. case BinaryOp::RightShift:
  327. generator.emit<Bytecode::Op::RightShift>(lhs_reg);
  328. break;
  329. case BinaryOp::UnsignedRightShift:
  330. generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
  331. break;
  332. case BinaryOp::In:
  333. generator.emit<Bytecode::Op::In>(lhs_reg);
  334. break;
  335. case BinaryOp::InstanceOf:
  336. generator.emit<Bytecode::Op::InstanceOf>(lhs_reg);
  337. break;
  338. default:
  339. VERIFY_NOT_REACHED();
  340. }
  341. return {};
  342. }
  343. Bytecode::CodeGenerationErrorOr<void> LogicalExpression::generate_bytecode(Bytecode::Generator& generator) const
  344. {
  345. TRY(m_lhs->generate_bytecode(generator));
  346. // lhs
  347. // jump op (true) end (false) rhs
  348. // rhs
  349. // jump always (true) end
  350. // end
  351. auto& rhs_block = generator.make_block();
  352. auto& end_block = generator.make_block();
  353. switch (m_op) {
  354. case LogicalOp::And:
  355. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  356. Bytecode::Label { rhs_block },
  357. Bytecode::Label { end_block });
  358. break;
  359. case LogicalOp::Or:
  360. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  361. Bytecode::Label { end_block },
  362. Bytecode::Label { rhs_block });
  363. break;
  364. case LogicalOp::NullishCoalescing:
  365. generator.emit<Bytecode::Op::JumpNullish>().set_targets(
  366. Bytecode::Label { rhs_block },
  367. Bytecode::Label { end_block });
  368. break;
  369. default:
  370. VERIFY_NOT_REACHED();
  371. }
  372. generator.switch_to_basic_block(rhs_block);
  373. TRY(m_rhs->generate_bytecode(generator));
  374. generator.emit<Bytecode::Op::Jump>().set_targets(
  375. Bytecode::Label { end_block },
  376. {});
  377. generator.switch_to_basic_block(end_block);
  378. return {};
  379. }
  380. Bytecode::CodeGenerationErrorOr<void> UnaryExpression::generate_bytecode(Bytecode::Generator& generator) const
  381. {
  382. if (m_op == UnaryOp::Delete)
  383. return generator.emit_delete_reference(m_lhs);
  384. // Typeof needs some special handling for when the LHS is an Identifier. Namely, it shouldn't throw on unresolvable references, but instead return "undefined".
  385. if (m_op != UnaryOp::Typeof)
  386. TRY(m_lhs->generate_bytecode(generator));
  387. switch (m_op) {
  388. case UnaryOp::BitwiseNot:
  389. generator.emit<Bytecode::Op::BitwiseNot>();
  390. break;
  391. case UnaryOp::Not:
  392. generator.emit<Bytecode::Op::Not>();
  393. break;
  394. case UnaryOp::Plus:
  395. generator.emit<Bytecode::Op::UnaryPlus>();
  396. break;
  397. case UnaryOp::Minus:
  398. generator.emit<Bytecode::Op::UnaryMinus>();
  399. break;
  400. case UnaryOp::Typeof:
  401. if (is<Identifier>(*m_lhs)) {
  402. auto& identifier = static_cast<Identifier const&>(*m_lhs);
  403. generator.emit<Bytecode::Op::TypeofVariable>(generator.intern_identifier(identifier.string()));
  404. break;
  405. }
  406. TRY(m_lhs->generate_bytecode(generator));
  407. generator.emit<Bytecode::Op::Typeof>();
  408. break;
  409. case UnaryOp::Void:
  410. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  411. break;
  412. case UnaryOp::Delete: // Delete is implemented above.
  413. default:
  414. VERIFY_NOT_REACHED();
  415. }
  416. return {};
  417. }
  418. Bytecode::CodeGenerationErrorOr<void> NumericLiteral::generate_bytecode(Bytecode::Generator& generator) const
  419. {
  420. generator.emit<Bytecode::Op::LoadImmediate>(m_value);
  421. return {};
  422. }
  423. Bytecode::CodeGenerationErrorOr<void> BooleanLiteral::generate_bytecode(Bytecode::Generator& generator) const
  424. {
  425. generator.emit<Bytecode::Op::LoadImmediate>(Value(m_value));
  426. return {};
  427. }
  428. Bytecode::CodeGenerationErrorOr<void> NullLiteral::generate_bytecode(Bytecode::Generator& generator) const
  429. {
  430. generator.emit<Bytecode::Op::LoadImmediate>(js_null());
  431. return {};
  432. }
  433. Bytecode::CodeGenerationErrorOr<void> BigIntLiteral::generate_bytecode(Bytecode::Generator& generator) const
  434. {
  435. generator.emit<Bytecode::Op::NewBigInt>(Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1)));
  436. return {};
  437. }
  438. Bytecode::CodeGenerationErrorOr<void> StringLiteral::generate_bytecode(Bytecode::Generator& generator) const
  439. {
  440. generator.emit<Bytecode::Op::NewString>(generator.intern_string(m_value));
  441. return {};
  442. }
  443. Bytecode::CodeGenerationErrorOr<void> RegExpLiteral::generate_bytecode(Bytecode::Generator& generator) const
  444. {
  445. auto source_index = generator.intern_string(m_pattern);
  446. auto flags_index = generator.intern_string(m_flags);
  447. generator.emit<Bytecode::Op::NewRegExp>(source_index, flags_index);
  448. return {};
  449. }
  450. Bytecode::CodeGenerationErrorOr<void> Identifier::generate_bytecode(Bytecode::Generator& generator) const
  451. {
  452. generator.emit<Bytecode::Op::GetVariable>(generator.intern_identifier(m_string));
  453. return {};
  454. }
  455. Bytecode::CodeGenerationErrorOr<void> SuperCall::generate_bytecode(Bytecode::Generator& generator) const
  456. {
  457. Vector<Bytecode::Register> argument_registers;
  458. if (m_is_synthetic == IsPartOfSyntheticConstructor::Yes) {
  459. // NOTE: This is the case where we have a fake constructor(...args) { super(...args); } which
  460. // shouldn't call @@iterator of %Array.prototype%.
  461. VERIFY(m_arguments.size() == 1);
  462. VERIFY(m_arguments[0].is_spread);
  463. auto const& argument = m_arguments[0];
  464. // This generates a single argument, which will be implicitly passed in accumulator
  465. MUST(argument.value->generate_bytecode(generator));
  466. } else {
  467. argument_registers.ensure_capacity(m_arguments.size());
  468. for (auto const& arg : m_arguments) {
  469. TRY(arg.value->generate_bytecode(generator));
  470. auto arg_reg = generator.allocate_register();
  471. generator.emit<Bytecode::Op::Store>(arg_reg);
  472. argument_registers.unchecked_append(arg_reg);
  473. }
  474. }
  475. generator.emit_with_extra_register_slots<Bytecode::Op::SuperCall>(argument_registers.size(), m_is_synthetic == IsPartOfSyntheticConstructor::Yes, argument_registers);
  476. return {};
  477. }
  478. static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode, Bytecode::Register const& value_reg);
  479. Bytecode::CodeGenerationErrorOr<void> AssignmentExpression::generate_bytecode(Bytecode::Generator& generator) const
  480. {
  481. if (m_op == AssignmentOp::Assignment) {
  482. // AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  483. return m_lhs.visit(
  484. // 1. If LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral, then
  485. [&](NonnullRefPtr<Expression> const& lhs) -> Bytecode::CodeGenerationErrorOr<void> {
  486. // a. Let lref be the result of evaluating LeftHandSideExpression.
  487. // b. ReturnIfAbrupt(lref).
  488. Optional<Bytecode::Register> base_object_register;
  489. Optional<Bytecode::Register> computed_property_register;
  490. if (is<MemberExpression>(*lhs)) {
  491. auto& expression = static_cast<MemberExpression const&>(*lhs);
  492. TRY(expression.object().generate_bytecode(generator));
  493. base_object_register = generator.allocate_register();
  494. generator.emit<Bytecode::Op::Store>(*base_object_register);
  495. if (expression.is_computed()) {
  496. TRY(expression.property().generate_bytecode(generator));
  497. computed_property_register = generator.allocate_register();
  498. generator.emit<Bytecode::Op::Store>(*computed_property_register);
  499. // To be continued later with PutByValue.
  500. } else if (expression.property().is_identifier()) {
  501. // Do nothing, this will be handled by PutById later.
  502. } else {
  503. return Bytecode::CodeGenerationError {
  504. &expression,
  505. "Unimplemented non-computed member expression"sv
  506. };
  507. }
  508. } else if (is<Identifier>(*lhs)) {
  509. // NOTE: For Identifiers, we cannot perform GetVariable and then write into the reference it retrieves, only SetVariable can do this.
  510. // FIXME: However, this breaks spec as we are doing variable lookup after evaluating the RHS. This is observable in an object environment, where we visibly perform HasOwnProperty and Get(@@unscopables) on the binded object.
  511. } else {
  512. TRY(lhs->generate_bytecode(generator));
  513. }
  514. // FIXME: c. If IsAnonymousFunctionDefinition(AssignmentExpression) and IsIdentifierRef of LeftHandSideExpression are both true, then
  515. // i. Let rval be ? NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  516. // d. Else,
  517. // i. Let rref be the result of evaluating AssignmentExpression.
  518. // ii. Let rval be ? GetValue(rref).
  519. TRY(m_rhs->generate_bytecode(generator));
  520. // e. Perform ? PutValue(lref, rval).
  521. if (is<Identifier>(*lhs)) {
  522. auto& identifier = static_cast<Identifier const&>(*lhs);
  523. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier.string()));
  524. } else if (is<MemberExpression>(*lhs)) {
  525. auto& expression = static_cast<MemberExpression const&>(*lhs);
  526. if (expression.is_computed()) {
  527. generator.emit<Bytecode::Op::PutByValue>(*base_object_register, *computed_property_register);
  528. } else if (expression.property().is_identifier()) {
  529. auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(expression.property()).string());
  530. generator.emit<Bytecode::Op::PutById>(*base_object_register, identifier_table_ref);
  531. } else {
  532. return Bytecode::CodeGenerationError {
  533. &expression,
  534. "Unimplemented non-computed member expression"sv
  535. };
  536. }
  537. } else {
  538. return Bytecode::CodeGenerationError {
  539. lhs,
  540. "Unimplemented/invalid node used a reference"sv
  541. };
  542. }
  543. // f. Return rval.
  544. // NOTE: This is already in the accumulator.
  545. return {};
  546. },
  547. // 2. Let assignmentPattern be the AssignmentPattern that is covered by LeftHandSideExpression.
  548. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  549. // 3. Let rref be the result of evaluating AssignmentExpression.
  550. // 4. Let rval be ? GetValue(rref).
  551. TRY(m_rhs->generate_bytecode(generator));
  552. auto value_register = generator.allocate_register();
  553. generator.emit<Bytecode::Op::Store>(value_register);
  554. // 5. Perform ? DestructuringAssignmentEvaluation of assignmentPattern with argument rval.
  555. TRY(generate_binding_pattern_bytecode(generator, pattern, Bytecode::Op::SetVariable::InitializationMode::Set, value_register));
  556. // 6. Return rval.
  557. generator.emit<Bytecode::Op::Load>(value_register);
  558. return {};
  559. });
  560. }
  561. VERIFY(m_lhs.has<NonnullRefPtr<Expression>>());
  562. auto& lhs = m_lhs.get<NonnullRefPtr<Expression>>();
  563. TRY(generator.emit_load_from_reference(lhs));
  564. Bytecode::BasicBlock* rhs_block_ptr { nullptr };
  565. Bytecode::BasicBlock* end_block_ptr { nullptr };
  566. // Logical assignments short circuit.
  567. if (m_op == AssignmentOp::AndAssignment) { // &&=
  568. rhs_block_ptr = &generator.make_block();
  569. end_block_ptr = &generator.make_block();
  570. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  571. Bytecode::Label { *rhs_block_ptr },
  572. Bytecode::Label { *end_block_ptr });
  573. } else if (m_op == AssignmentOp::OrAssignment) { // ||=
  574. rhs_block_ptr = &generator.make_block();
  575. end_block_ptr = &generator.make_block();
  576. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  577. Bytecode::Label { *end_block_ptr },
  578. Bytecode::Label { *rhs_block_ptr });
  579. } else if (m_op == AssignmentOp::NullishAssignment) { // ??=
  580. rhs_block_ptr = &generator.make_block();
  581. end_block_ptr = &generator.make_block();
  582. generator.emit<Bytecode::Op::JumpNullish>().set_targets(
  583. Bytecode::Label { *rhs_block_ptr },
  584. Bytecode::Label { *end_block_ptr });
  585. }
  586. if (rhs_block_ptr)
  587. generator.switch_to_basic_block(*rhs_block_ptr);
  588. // lhs_reg is a part of the rhs_block because the store isn't necessary
  589. // if the logical assignment condition fails.
  590. auto lhs_reg = generator.allocate_register();
  591. generator.emit<Bytecode::Op::Store>(lhs_reg);
  592. TRY(m_rhs->generate_bytecode(generator));
  593. switch (m_op) {
  594. case AssignmentOp::AdditionAssignment:
  595. generator.emit<Bytecode::Op::Add>(lhs_reg);
  596. break;
  597. case AssignmentOp::SubtractionAssignment:
  598. generator.emit<Bytecode::Op::Sub>(lhs_reg);
  599. break;
  600. case AssignmentOp::MultiplicationAssignment:
  601. generator.emit<Bytecode::Op::Mul>(lhs_reg);
  602. break;
  603. case AssignmentOp::DivisionAssignment:
  604. generator.emit<Bytecode::Op::Div>(lhs_reg);
  605. break;
  606. case AssignmentOp::ModuloAssignment:
  607. generator.emit<Bytecode::Op::Mod>(lhs_reg);
  608. break;
  609. case AssignmentOp::ExponentiationAssignment:
  610. generator.emit<Bytecode::Op::Exp>(lhs_reg);
  611. break;
  612. case AssignmentOp::BitwiseAndAssignment:
  613. generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
  614. break;
  615. case AssignmentOp::BitwiseOrAssignment:
  616. generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
  617. break;
  618. case AssignmentOp::BitwiseXorAssignment:
  619. generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
  620. break;
  621. case AssignmentOp::LeftShiftAssignment:
  622. generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
  623. break;
  624. case AssignmentOp::RightShiftAssignment:
  625. generator.emit<Bytecode::Op::RightShift>(lhs_reg);
  626. break;
  627. case AssignmentOp::UnsignedRightShiftAssignment:
  628. generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
  629. break;
  630. case AssignmentOp::AndAssignment:
  631. case AssignmentOp::OrAssignment:
  632. case AssignmentOp::NullishAssignment:
  633. break; // These are handled above.
  634. default:
  635. return Bytecode::CodeGenerationError {
  636. this,
  637. "Unimplemented operation"sv,
  638. };
  639. }
  640. TRY(generator.emit_store_to_reference(lhs));
  641. if (end_block_ptr) {
  642. generator.emit<Bytecode::Op::Jump>().set_targets(
  643. Bytecode::Label { *end_block_ptr },
  644. {});
  645. generator.switch_to_basic_block(*end_block_ptr);
  646. }
  647. return {};
  648. }
  649. // 14.13.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-labelled-statements-runtime-semantics-evaluation
  650. // LabelledStatement : LabelIdentifier : LabelledItem
  651. Bytecode::CodeGenerationErrorOr<void> LabelledStatement::generate_bytecode(Bytecode::Generator& generator) const
  652. {
  653. // Return ? LabelledEvaluation of this LabelledStatement with argument « ».
  654. return generate_labelled_evaluation(generator, {});
  655. }
  656. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  657. // LabelledStatement : LabelIdentifier : LabelledItem
  658. Bytecode::CodeGenerationErrorOr<void> LabelledStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<FlyString> const& label_set) const
  659. {
  660. // Convert the m_labelled_item NNRP to a reference early so we don't have to do it every single time we want to use it.
  661. auto const& labelled_item = *m_labelled_item;
  662. // 1. Let label be the StringValue of LabelIdentifier.
  663. // NOTE: Not necessary, this is m_label.
  664. // 2. Let newLabelSet be the list-concatenation of labelSet and « label ».
  665. // FIXME: Avoid copy here.
  666. auto new_label_set = label_set;
  667. new_label_set.append(m_label);
  668. // 3. Let stmtResult be LabelledEvaluation of LabelledItem with argument newLabelSet.
  669. // NOTE: stmtResult will be in the accumulator after running the generated bytecode.
  670. if (is<IterationStatement>(labelled_item)) {
  671. auto const& iteration_statement = static_cast<IterationStatement const&>(labelled_item);
  672. TRY(iteration_statement.generate_labelled_evaluation(generator, new_label_set));
  673. } else if (is<SwitchStatement>(labelled_item)) {
  674. auto const& switch_statement = static_cast<SwitchStatement const&>(labelled_item);
  675. TRY(switch_statement.generate_labelled_evaluation(generator, new_label_set));
  676. } else if (is<LabelledStatement>(labelled_item)) {
  677. auto const& labelled_statement = static_cast<LabelledStatement const&>(labelled_item);
  678. TRY(labelled_statement.generate_labelled_evaluation(generator, new_label_set));
  679. } else {
  680. auto& labelled_break_block = generator.make_block();
  681. // NOTE: We do not need a continuable scope as `continue;` is not allowed outside of iteration statements, throwing a SyntaxError in the parser.
  682. generator.begin_breakable_scope(Bytecode::Label { labelled_break_block }, new_label_set);
  683. TRY(labelled_item.generate_bytecode(generator));
  684. generator.end_breakable_scope();
  685. if (!generator.is_current_block_terminated()) {
  686. generator.emit<Bytecode::Op::Jump>().set_targets(
  687. Bytecode::Label { labelled_break_block },
  688. {});
  689. }
  690. generator.switch_to_basic_block(labelled_break_block);
  691. }
  692. // 4. If stmtResult.[[Type]] is break and SameValue(stmtResult.[[Target]], label) is true, then
  693. // a. Set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  694. // NOTE: These steps are performed by making labelled break jump straight to the appropriate break block, which preserves the statement result's value in the accumulator.
  695. // 5. Return Completion(stmtResult).
  696. // NOTE: This is in the accumulator.
  697. return {};
  698. }
  699. Bytecode::CodeGenerationErrorOr<void> IterationStatement::generate_labelled_evaluation(Bytecode::Generator&, Vector<FlyString> const&) const
  700. {
  701. return Bytecode::CodeGenerationError {
  702. this,
  703. "Missing generate_labelled_evaluation()"sv,
  704. };
  705. }
  706. Bytecode::CodeGenerationErrorOr<void> WhileStatement::generate_bytecode(Bytecode::Generator& generator) const
  707. {
  708. return generate_labelled_evaluation(generator, {});
  709. }
  710. Bytecode::CodeGenerationErrorOr<void> WhileStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<FlyString> const& label_set) const
  711. {
  712. // test
  713. // jump if_false (true) end (false) body
  714. // body
  715. // jump always (true) test
  716. // end
  717. auto& test_block = generator.make_block();
  718. auto& body_block = generator.make_block();
  719. auto& end_block = generator.make_block();
  720. // Init result register
  721. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  722. auto result_reg = generator.allocate_register();
  723. generator.emit<Bytecode::Op::Store>(result_reg);
  724. // jump to the test block
  725. generator.emit<Bytecode::Op::Jump>().set_targets(
  726. Bytecode::Label { test_block },
  727. {});
  728. generator.switch_to_basic_block(test_block);
  729. TRY(m_test->generate_bytecode(generator));
  730. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  731. Bytecode::Label { body_block },
  732. Bytecode::Label { end_block });
  733. generator.switch_to_basic_block(body_block);
  734. generator.begin_continuable_scope(Bytecode::Label { test_block }, label_set);
  735. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  736. TRY(m_body->generate_bytecode(generator));
  737. generator.end_breakable_scope();
  738. generator.end_continuable_scope();
  739. if (!generator.is_current_block_terminated()) {
  740. generator.emit<Bytecode::Op::Jump>().set_targets(
  741. Bytecode::Label { test_block },
  742. {});
  743. }
  744. generator.switch_to_basic_block(end_block);
  745. generator.emit<Bytecode::Op::Load>(result_reg);
  746. return {};
  747. }
  748. Bytecode::CodeGenerationErrorOr<void> DoWhileStatement::generate_bytecode(Bytecode::Generator& generator) const
  749. {
  750. return generate_labelled_evaluation(generator, {});
  751. }
  752. Bytecode::CodeGenerationErrorOr<void> DoWhileStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<FlyString> const& label_set) const
  753. {
  754. // jump always (true) body
  755. // test
  756. // jump if_false (true) end (false) body
  757. // body
  758. // jump always (true) test
  759. // end
  760. auto& test_block = generator.make_block();
  761. auto& body_block = generator.make_block();
  762. auto& end_block = generator.make_block();
  763. // Init result register
  764. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  765. auto result_reg = generator.allocate_register();
  766. generator.emit<Bytecode::Op::Store>(result_reg);
  767. // jump to the body block
  768. generator.emit<Bytecode::Op::Jump>().set_targets(
  769. Bytecode::Label { body_block },
  770. {});
  771. generator.switch_to_basic_block(test_block);
  772. TRY(m_test->generate_bytecode(generator));
  773. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  774. Bytecode::Label { body_block },
  775. Bytecode::Label { end_block });
  776. generator.switch_to_basic_block(body_block);
  777. generator.begin_continuable_scope(Bytecode::Label { test_block }, label_set);
  778. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  779. TRY(m_body->generate_bytecode(generator));
  780. generator.end_breakable_scope();
  781. generator.end_continuable_scope();
  782. if (!generator.is_current_block_terminated()) {
  783. generator.emit<Bytecode::Op::Jump>().set_targets(
  784. Bytecode::Label { test_block },
  785. {});
  786. }
  787. generator.switch_to_basic_block(end_block);
  788. generator.emit<Bytecode::Op::Load>(result_reg);
  789. return {};
  790. }
  791. Bytecode::CodeGenerationErrorOr<void> ForStatement::generate_bytecode(Bytecode::Generator& generator) const
  792. {
  793. return generate_labelled_evaluation(generator, {});
  794. }
  795. Bytecode::CodeGenerationErrorOr<void> ForStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<FlyString> const& label_set) const
  796. {
  797. // init
  798. // jump always (true) test
  799. // test
  800. // jump if_true (true) body (false) end
  801. // body
  802. // jump always (true) update
  803. // update
  804. // jump always (true) test
  805. // end
  806. // If 'test' is missing, fuse the 'test' and 'body' basic blocks
  807. // If 'update' is missing, fuse the 'body' and 'update' basic blocks
  808. Bytecode::BasicBlock* test_block_ptr { nullptr };
  809. Bytecode::BasicBlock* body_block_ptr { nullptr };
  810. Bytecode::BasicBlock* update_block_ptr { nullptr };
  811. auto& end_block = generator.make_block();
  812. bool has_lexical_environment = false;
  813. if (m_init) {
  814. if (m_init->is_variable_declaration()) {
  815. auto& variable_declaration = verify_cast<VariableDeclaration>(*m_init);
  816. if (variable_declaration.is_lexical_declaration()) {
  817. has_lexical_environment = true;
  818. // FIXME: Is Block correct?
  819. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  820. bool is_const = variable_declaration.is_constant_declaration();
  821. variable_declaration.for_each_bound_name([&](auto const& name) {
  822. auto index = generator.intern_identifier(name);
  823. generator.register_binding(index);
  824. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_const);
  825. });
  826. }
  827. }
  828. TRY(m_init->generate_bytecode(generator));
  829. }
  830. body_block_ptr = &generator.make_block();
  831. if (m_test)
  832. test_block_ptr = &generator.make_block();
  833. else
  834. test_block_ptr = body_block_ptr;
  835. if (m_update)
  836. update_block_ptr = &generator.make_block();
  837. else
  838. update_block_ptr = body_block_ptr;
  839. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  840. auto result_reg = generator.allocate_register();
  841. generator.emit<Bytecode::Op::Store>(result_reg);
  842. generator.emit<Bytecode::Op::Jump>().set_targets(
  843. Bytecode::Label { *test_block_ptr },
  844. {});
  845. if (m_test) {
  846. generator.switch_to_basic_block(*test_block_ptr);
  847. TRY(m_test->generate_bytecode(generator));
  848. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  849. Bytecode::Label { *body_block_ptr },
  850. Bytecode::Label { end_block });
  851. }
  852. generator.switch_to_basic_block(*body_block_ptr);
  853. generator.begin_continuable_scope(Bytecode::Label { *update_block_ptr }, label_set);
  854. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  855. TRY(m_body->generate_bytecode(generator));
  856. generator.end_breakable_scope();
  857. generator.end_continuable_scope();
  858. if (!generator.is_current_block_terminated()) {
  859. if (m_update) {
  860. generator.emit<Bytecode::Op::Jump>().set_targets(
  861. Bytecode::Label { *update_block_ptr },
  862. {});
  863. generator.switch_to_basic_block(*update_block_ptr);
  864. TRY(m_update->generate_bytecode(generator));
  865. }
  866. generator.emit<Bytecode::Op::Jump>().set_targets(
  867. Bytecode::Label { *test_block_ptr },
  868. {});
  869. }
  870. generator.switch_to_basic_block(end_block);
  871. generator.emit<Bytecode::Op::Load>(result_reg);
  872. if (has_lexical_environment)
  873. generator.end_variable_scope();
  874. return {};
  875. }
  876. Bytecode::CodeGenerationErrorOr<void> ObjectExpression::generate_bytecode(Bytecode::Generator& generator) const
  877. {
  878. generator.emit<Bytecode::Op::NewObject>();
  879. if (m_properties.is_empty())
  880. return {};
  881. auto object_reg = generator.allocate_register();
  882. generator.emit<Bytecode::Op::Store>(object_reg);
  883. for (auto& property : m_properties) {
  884. Bytecode::Op::PropertyKind property_kind;
  885. switch (property.type()) {
  886. case ObjectProperty::Type::KeyValue:
  887. property_kind = Bytecode::Op::PropertyKind::KeyValue;
  888. break;
  889. case ObjectProperty::Type::Getter:
  890. property_kind = Bytecode::Op::PropertyKind::Getter;
  891. break;
  892. case ObjectProperty::Type::Setter:
  893. property_kind = Bytecode::Op::PropertyKind::Setter;
  894. break;
  895. case ObjectProperty::Type::Spread:
  896. property_kind = Bytecode::Op::PropertyKind::Spread;
  897. break;
  898. case ObjectProperty::Type::ProtoSetter:
  899. property_kind = Bytecode::Op::PropertyKind::ProtoSetter;
  900. break;
  901. }
  902. if (is<StringLiteral>(property.key())) {
  903. auto& string_literal = static_cast<StringLiteral const&>(property.key());
  904. Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(string_literal.value());
  905. if (property_kind != Bytecode::Op::PropertyKind::Spread)
  906. TRY(property.value().generate_bytecode(generator));
  907. generator.emit<Bytecode::Op::PutById>(object_reg, key_name, property_kind);
  908. } else {
  909. TRY(property.key().generate_bytecode(generator));
  910. auto property_reg = generator.allocate_register();
  911. generator.emit<Bytecode::Op::Store>(property_reg);
  912. if (property_kind != Bytecode::Op::PropertyKind::Spread)
  913. TRY(property.value().generate_bytecode(generator));
  914. generator.emit<Bytecode::Op::PutByValue>(object_reg, property_reg, property_kind);
  915. }
  916. }
  917. generator.emit<Bytecode::Op::Load>(object_reg);
  918. return {};
  919. }
  920. Bytecode::CodeGenerationErrorOr<void> ArrayExpression::generate_bytecode(Bytecode::Generator& generator) const
  921. {
  922. Vector<Bytecode::Register> element_regs;
  923. for (auto& element : m_elements) {
  924. if (element && is<SpreadExpression>(*element)) {
  925. return Bytecode::CodeGenerationError {
  926. this,
  927. "Unimplemented element kind: SpreadExpression"sv,
  928. };
  929. }
  930. element_regs.append(generator.allocate_register());
  931. }
  932. size_t i = 0;
  933. for (auto& element : m_elements) {
  934. if (element) {
  935. TRY(element->generate_bytecode(generator));
  936. if (is<SpreadExpression>(*element))
  937. VERIFY_NOT_REACHED();
  938. } else {
  939. generator.emit<Bytecode::Op::LoadImmediate>(Value {});
  940. }
  941. auto& element_reg = element_regs[i++];
  942. generator.emit<Bytecode::Op::Store>(element_reg);
  943. }
  944. if (element_regs.is_empty()) {
  945. generator.emit<Bytecode::Op::NewArray>();
  946. } else {
  947. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { element_regs.first(), element_regs.last() });
  948. }
  949. return {};
  950. }
  951. Bytecode::CodeGenerationErrorOr<void> MemberExpression::generate_bytecode(Bytecode::Generator& generator) const
  952. {
  953. return generator.emit_load_from_reference(*this);
  954. }
  955. Bytecode::CodeGenerationErrorOr<void> FunctionDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  956. {
  957. if (m_is_hoisted) {
  958. auto index = generator.intern_identifier(name());
  959. generator.emit<Bytecode::Op::GetVariable>(index);
  960. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode::Var);
  961. }
  962. return {};
  963. }
  964. Bytecode::CodeGenerationErrorOr<void> FunctionExpression::generate_bytecode(Bytecode::Generator& generator) const
  965. {
  966. bool has_name = !name().is_empty();
  967. Optional<Bytecode::IdentifierTableIndex> name_identifier;
  968. if (has_name) {
  969. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical);
  970. name_identifier = generator.intern_identifier(name());
  971. generator.emit<Bytecode::Op::CreateVariable>(*name_identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  972. }
  973. generator.emit<Bytecode::Op::NewFunction>(*this);
  974. if (has_name) {
  975. generator.emit<Bytecode::Op::SetVariable>(*name_identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Lexical);
  976. generator.end_variable_scope();
  977. }
  978. return {};
  979. }
  980. 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)
  981. {
  982. Vector<Bytecode::Register> excluded_property_names;
  983. auto has_rest = false;
  984. if (pattern.entries.size() > 0)
  985. has_rest = pattern.entries[pattern.entries.size() - 1].is_rest;
  986. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  987. if (is_rest) {
  988. VERIFY(name.has<NonnullRefPtr<Identifier>>());
  989. VERIFY(alias.has<Empty>());
  990. VERIFY(!initializer);
  991. auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  992. auto interned_identifier = generator.intern_identifier(identifier);
  993. generator.emit_with_extra_register_slots<Bytecode::Op::CopyObjectExcludingProperties>(excluded_property_names.size(), value_reg, excluded_property_names);
  994. generator.emit<Bytecode::Op::SetVariable>(interned_identifier, initialization_mode);
  995. return {};
  996. }
  997. Bytecode::StringTableIndex name_index;
  998. if (name.has<NonnullRefPtr<Identifier>>()) {
  999. auto identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  1000. name_index = generator.intern_string(identifier);
  1001. if (has_rest) {
  1002. auto excluded_name_reg = generator.allocate_register();
  1003. excluded_property_names.append(excluded_name_reg);
  1004. generator.emit<Bytecode::Op::NewString>(name_index);
  1005. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  1006. }
  1007. generator.emit<Bytecode::Op::Load>(value_reg);
  1008. generator.emit<Bytecode::Op::GetById>(generator.intern_identifier(identifier));
  1009. } else {
  1010. auto expression = name.get<NonnullRefPtr<Expression>>();
  1011. TRY(expression->generate_bytecode(generator));
  1012. if (has_rest) {
  1013. auto excluded_name_reg = generator.allocate_register();
  1014. excluded_property_names.append(excluded_name_reg);
  1015. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  1016. }
  1017. generator.emit<Bytecode::Op::GetByValue>(value_reg);
  1018. }
  1019. if (initializer) {
  1020. auto& if_undefined_block = generator.make_block();
  1021. auto& if_not_undefined_block = generator.make_block();
  1022. generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
  1023. Bytecode::Label { if_undefined_block },
  1024. Bytecode::Label { if_not_undefined_block });
  1025. generator.switch_to_basic_block(if_undefined_block);
  1026. TRY(initializer->generate_bytecode(generator));
  1027. generator.emit<Bytecode::Op::Jump>().set_targets(
  1028. Bytecode::Label { if_not_undefined_block },
  1029. {});
  1030. generator.switch_to_basic_block(if_not_undefined_block);
  1031. }
  1032. if (alias.has<NonnullRefPtr<BindingPattern>>()) {
  1033. auto& binding_pattern = *alias.get<NonnullRefPtr<BindingPattern>>();
  1034. auto nested_value_reg = generator.allocate_register();
  1035. generator.emit<Bytecode::Op::Store>(nested_value_reg);
  1036. TRY(generate_binding_pattern_bytecode(generator, binding_pattern, initialization_mode, nested_value_reg));
  1037. } else if (alias.has<Empty>()) {
  1038. if (name.has<NonnullRefPtr<Expression>>()) {
  1039. // This needs some sort of SetVariableByValue opcode, as it's a runtime binding
  1040. return Bytecode::CodeGenerationError {
  1041. name.get<NonnullRefPtr<Expression>>().ptr(),
  1042. "Unimplemented name/alias pair: Empty/Expression"sv,
  1043. };
  1044. }
  1045. auto& identifier = name.get<NonnullRefPtr<Identifier>>()->string();
  1046. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  1047. } else {
  1048. auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string();
  1049. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  1050. }
  1051. }
  1052. return {};
  1053. }
  1054. 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)
  1055. {
  1056. /*
  1057. * Consider the following destructuring assignment:
  1058. *
  1059. * let [a, b, c, d, e] = o;
  1060. *
  1061. * It would be fairly trivial to just loop through this iterator, getting the value
  1062. * at each step and assigning them to the binding sequentially. However, this is not
  1063. * correct: once an iterator is exhausted, it must not be called again. This complicates
  1064. * the bytecode. In order to accomplish this, we do the following:
  1065. *
  1066. * - Reserve a special boolean register which holds 'true' if the iterator is exhausted,
  1067. * and false otherwise
  1068. * - When we are retrieving the value which should be bound, we first check this register.
  1069. * If it is 'true', we load undefined into the accumulator. Otherwise, we grab the next
  1070. * value from the iterator and store it into the accumulator.
  1071. *
  1072. * Note that the is_exhausted register does not need to be loaded with false because the
  1073. * first IteratorNext bytecode is _not_ proceeded by an exhausted check, as it is
  1074. * unnecessary.
  1075. */
  1076. auto is_iterator_exhausted_register = generator.allocate_register();
  1077. auto iterator_reg = generator.allocate_register();
  1078. generator.emit<Bytecode::Op::Load>(value_reg);
  1079. generator.emit<Bytecode::Op::GetIterator>();
  1080. generator.emit<Bytecode::Op::Store>(iterator_reg);
  1081. bool first = true;
  1082. auto temp_iterator_result_reg = generator.allocate_register();
  1083. auto assign_accumulator_to_alias = [&](auto& alias) {
  1084. return alias.visit(
  1085. [&](Empty) -> Bytecode::CodeGenerationErrorOr<void> {
  1086. // This element is an elision
  1087. return {};
  1088. },
  1089. [&](NonnullRefPtr<Identifier> const& identifier) -> Bytecode::CodeGenerationErrorOr<void> {
  1090. auto interned_index = generator.intern_identifier(identifier->string());
  1091. generator.emit<Bytecode::Op::SetVariable>(interned_index, initialization_mode);
  1092. return {};
  1093. },
  1094. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  1095. // Store the accumulator value in a permanent register
  1096. auto target_reg = generator.allocate_register();
  1097. generator.emit<Bytecode::Op::Store>(target_reg);
  1098. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, target_reg);
  1099. },
  1100. [&](NonnullRefPtr<MemberExpression> const& expr) -> Bytecode::CodeGenerationErrorOr<void> {
  1101. return generator.emit_store_to_reference(*expr);
  1102. });
  1103. };
  1104. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  1105. VERIFY(name.has<Empty>());
  1106. if (is_rest) {
  1107. VERIFY(!initializer);
  1108. if (first) {
  1109. // The iterator has not been called, and is thus known to be not exhausted
  1110. generator.emit<Bytecode::Op::Load>(iterator_reg);
  1111. generator.emit<Bytecode::Op::IteratorToArray>();
  1112. } else {
  1113. auto& if_exhausted_block = generator.make_block();
  1114. auto& if_not_exhausted_block = generator.make_block();
  1115. auto& continuation_block = generator.make_block();
  1116. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  1117. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1118. Bytecode::Label { if_exhausted_block },
  1119. Bytecode::Label { if_not_exhausted_block });
  1120. generator.switch_to_basic_block(if_exhausted_block);
  1121. generator.emit<Bytecode::Op::NewArray>();
  1122. generator.emit<Bytecode::Op::Jump>().set_targets(
  1123. Bytecode::Label { continuation_block },
  1124. {});
  1125. generator.switch_to_basic_block(if_not_exhausted_block);
  1126. generator.emit<Bytecode::Op::Load>(iterator_reg);
  1127. generator.emit<Bytecode::Op::IteratorToArray>();
  1128. generator.emit<Bytecode::Op::Jump>().set_targets(
  1129. Bytecode::Label { continuation_block },
  1130. {});
  1131. generator.switch_to_basic_block(continuation_block);
  1132. }
  1133. return assign_accumulator_to_alias(alias);
  1134. }
  1135. // In the first iteration of the loop, a few things are true which can save
  1136. // us some bytecode:
  1137. // - the iterator result is still in the accumulator, so we can avoid a load
  1138. // - the iterator is not yet exhausted, which can save us a jump and some
  1139. // creation
  1140. auto& iterator_is_exhausted_block = generator.make_block();
  1141. if (!first) {
  1142. auto& iterator_is_not_exhausted_block = generator.make_block();
  1143. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  1144. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1145. Bytecode::Label { iterator_is_exhausted_block },
  1146. Bytecode::Label { iterator_is_not_exhausted_block });
  1147. generator.switch_to_basic_block(iterator_is_not_exhausted_block);
  1148. generator.emit<Bytecode::Op::Load>(iterator_reg);
  1149. }
  1150. generator.emit<Bytecode::Op::IteratorNext>();
  1151. generator.emit<Bytecode::Op::Store>(temp_iterator_result_reg);
  1152. generator.emit<Bytecode::Op::IteratorResultDone>();
  1153. generator.emit<Bytecode::Op::Store>(is_iterator_exhausted_register);
  1154. // We still have to check for exhaustion here. If the iterator is exhausted,
  1155. // we need to bail before trying to get the value
  1156. auto& no_bail_block = generator.make_block();
  1157. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1158. Bytecode::Label { iterator_is_exhausted_block },
  1159. Bytecode::Label { no_bail_block });
  1160. generator.switch_to_basic_block(no_bail_block);
  1161. // Get the next value in the iterator
  1162. generator.emit<Bytecode::Op::Load>(temp_iterator_result_reg);
  1163. generator.emit<Bytecode::Op::IteratorResultValue>();
  1164. auto& create_binding_block = generator.make_block();
  1165. generator.emit<Bytecode::Op::Jump>().set_targets(
  1166. Bytecode::Label { create_binding_block },
  1167. {});
  1168. // The iterator is exhausted, so we just load undefined and continue binding
  1169. generator.switch_to_basic_block(iterator_is_exhausted_block);
  1170. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1171. generator.emit<Bytecode::Op::Jump>().set_targets(
  1172. Bytecode::Label { create_binding_block },
  1173. {});
  1174. // Create the actual binding. The value which this entry must bind is now in the
  1175. // accumulator. We can proceed, processing the alias as a nested destructuring
  1176. // pattern if necessary.
  1177. generator.switch_to_basic_block(create_binding_block);
  1178. if (initializer) {
  1179. auto& value_is_undefined_block = generator.make_block();
  1180. auto& value_is_not_undefined_block = generator.make_block();
  1181. generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
  1182. Bytecode::Label { value_is_undefined_block },
  1183. Bytecode::Label { value_is_not_undefined_block });
  1184. generator.switch_to_basic_block(value_is_undefined_block);
  1185. TRY(initializer->generate_bytecode(generator));
  1186. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { value_is_not_undefined_block });
  1187. generator.switch_to_basic_block(value_is_not_undefined_block);
  1188. }
  1189. TRY(assign_accumulator_to_alias(alias));
  1190. first = false;
  1191. }
  1192. return {};
  1193. }
  1194. 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)
  1195. {
  1196. if (pattern.kind == BindingPattern::Kind::Object)
  1197. return generate_object_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  1198. return generate_array_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  1199. }
  1200. static Bytecode::CodeGenerationErrorOr<void> assign_accumulator_to_variable_declarator(Bytecode::Generator& generator, VariableDeclarator const& declarator, VariableDeclaration const& declaration)
  1201. {
  1202. auto initialization_mode = declaration.is_lexical_declaration() ? Bytecode::Op::SetVariable::InitializationMode::Initialize : Bytecode::Op::SetVariable::InitializationMode::Set;
  1203. auto environment_mode = declaration.is_lexical_declaration() ? Bytecode::Op::EnvironmentMode::Lexical : Bytecode::Op::EnvironmentMode::Var;
  1204. return declarator.target().visit(
  1205. [&](NonnullRefPtr<Identifier> const& id) -> Bytecode::CodeGenerationErrorOr<void> {
  1206. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(id->string()), initialization_mode, environment_mode);
  1207. return {};
  1208. },
  1209. [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  1210. auto value_register = generator.allocate_register();
  1211. generator.emit<Bytecode::Op::Store>(value_register);
  1212. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, value_register);
  1213. });
  1214. }
  1215. Bytecode::CodeGenerationErrorOr<void> VariableDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1216. {
  1217. for (auto& declarator : m_declarations) {
  1218. if (declarator.init())
  1219. TRY(declarator.init()->generate_bytecode(generator));
  1220. else
  1221. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1222. TRY(assign_accumulator_to_variable_declarator(generator, declarator, *this));
  1223. }
  1224. return {};
  1225. }
  1226. Bytecode::CodeGenerationErrorOr<void> CallExpression::generate_bytecode(Bytecode::Generator& generator) const
  1227. {
  1228. auto callee_reg = generator.allocate_register();
  1229. auto this_reg = generator.allocate_register();
  1230. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1231. generator.emit<Bytecode::Op::Store>(this_reg);
  1232. if (is<NewExpression>(this)) {
  1233. TRY(m_callee->generate_bytecode(generator));
  1234. generator.emit<Bytecode::Op::Store>(callee_reg);
  1235. } else if (is<SuperExpression>(*m_callee)) {
  1236. return Bytecode::CodeGenerationError {
  1237. this,
  1238. "Unimplemented callee kind: SuperExpression"sv,
  1239. };
  1240. } else if (is<MemberExpression>(*m_callee)) {
  1241. auto& member_expression = static_cast<MemberExpression const&>(*m_callee);
  1242. if (is<SuperExpression>(member_expression.object())) {
  1243. return Bytecode::CodeGenerationError {
  1244. this,
  1245. "Unimplemented callee kind: MemberExpression on SuperExpression"sv,
  1246. };
  1247. }
  1248. TRY(member_expression.object().generate_bytecode(generator));
  1249. generator.emit<Bytecode::Op::Store>(this_reg);
  1250. if (member_expression.is_computed()) {
  1251. TRY(member_expression.property().generate_bytecode(generator));
  1252. generator.emit<Bytecode::Op::GetByValue>(this_reg);
  1253. } else {
  1254. auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string());
  1255. generator.emit<Bytecode::Op::GetById>(identifier_table_ref);
  1256. }
  1257. generator.emit<Bytecode::Op::Store>(callee_reg);
  1258. } else {
  1259. // FIXME: this = global object in sloppy mode.
  1260. TRY(m_callee->generate_bytecode(generator));
  1261. generator.emit<Bytecode::Op::Store>(callee_reg);
  1262. }
  1263. Vector<Bytecode::Register> argument_registers;
  1264. for (auto& arg : m_arguments) {
  1265. TRY(arg.value->generate_bytecode(generator));
  1266. auto arg_reg = generator.allocate_register();
  1267. generator.emit<Bytecode::Op::Store>(arg_reg);
  1268. argument_registers.append(arg_reg);
  1269. }
  1270. Bytecode::Op::Call::CallType call_type;
  1271. if (is<NewExpression>(*this)) {
  1272. call_type = Bytecode::Op::Call::CallType::Construct;
  1273. } else {
  1274. call_type = Bytecode::Op::Call::CallType::Call;
  1275. }
  1276. generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_registers.size(), call_type, callee_reg, this_reg, argument_registers);
  1277. return {};
  1278. }
  1279. Bytecode::CodeGenerationErrorOr<void> ReturnStatement::generate_bytecode(Bytecode::Generator& generator) const
  1280. {
  1281. if (m_argument)
  1282. TRY(m_argument->generate_bytecode(generator));
  1283. else
  1284. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1285. if (generator.is_in_generator_or_async_function()) {
  1286. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1287. generator.emit<Bytecode::Op::Yield>(nullptr);
  1288. } else {
  1289. generator.perform_needed_unwinds<Bytecode::Op::Return>();
  1290. generator.emit<Bytecode::Op::Return>();
  1291. }
  1292. return {};
  1293. }
  1294. Bytecode::CodeGenerationErrorOr<void> YieldExpression::generate_bytecode(Bytecode::Generator& generator) const
  1295. {
  1296. VERIFY(generator.is_in_generator_function());
  1297. if (m_is_yield_from) {
  1298. return Bytecode::CodeGenerationError {
  1299. this,
  1300. "Unimplemented form: `yield*`"sv,
  1301. };
  1302. }
  1303. if (m_argument)
  1304. TRY(m_argument->generate_bytecode(generator));
  1305. auto& continuation_block = generator.make_block();
  1306. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1307. generator.switch_to_basic_block(continuation_block);
  1308. return {};
  1309. }
  1310. Bytecode::CodeGenerationErrorOr<void> IfStatement::generate_bytecode(Bytecode::Generator& generator) const
  1311. {
  1312. // test
  1313. // jump if_true (true) true (false) false
  1314. // true
  1315. // jump always (true) end
  1316. // false
  1317. // jump always (true) end
  1318. // end
  1319. auto& true_block = generator.make_block();
  1320. auto& false_block = generator.make_block();
  1321. TRY(m_predicate->generate_bytecode(generator));
  1322. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1323. Bytecode::Label { true_block },
  1324. Bytecode::Label { false_block });
  1325. Bytecode::Op::Jump* true_block_jump { nullptr };
  1326. generator.switch_to_basic_block(true_block);
  1327. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1328. TRY(m_consequent->generate_bytecode(generator));
  1329. if (!generator.is_current_block_terminated())
  1330. true_block_jump = &generator.emit<Bytecode::Op::Jump>();
  1331. generator.switch_to_basic_block(false_block);
  1332. auto& end_block = generator.make_block();
  1333. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1334. if (m_alternate)
  1335. TRY(m_alternate->generate_bytecode(generator));
  1336. if (!generator.is_current_block_terminated())
  1337. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1338. if (true_block_jump)
  1339. true_block_jump->set_targets(Bytecode::Label { end_block }, {});
  1340. generator.switch_to_basic_block(end_block);
  1341. return {};
  1342. }
  1343. Bytecode::CodeGenerationErrorOr<void> ContinueStatement::generate_bytecode(Bytecode::Generator& generator) const
  1344. {
  1345. if (m_target_label.is_null()) {
  1346. generator.perform_needed_unwinds<Bytecode::Op::Jump>();
  1347. generator.emit<Bytecode::Op::Jump>().set_targets(
  1348. generator.nearest_continuable_scope(),
  1349. {});
  1350. return {};
  1351. }
  1352. auto target_to_jump_to = generator.perform_needed_unwinds_for_labelled_continue_and_return_target_block(m_target_label);
  1353. generator.emit<Bytecode::Op::Jump>().set_targets(
  1354. target_to_jump_to,
  1355. {});
  1356. return {};
  1357. }
  1358. Bytecode::CodeGenerationErrorOr<void> DebuggerStatement::generate_bytecode(Bytecode::Generator&) const
  1359. {
  1360. return {};
  1361. }
  1362. Bytecode::CodeGenerationErrorOr<void> ConditionalExpression::generate_bytecode(Bytecode::Generator& generator) const
  1363. {
  1364. // test
  1365. // jump if_true (true) true (false) false
  1366. // true
  1367. // jump always (true) end
  1368. // false
  1369. // jump always (true) end
  1370. // end
  1371. auto& true_block = generator.make_block();
  1372. auto& false_block = generator.make_block();
  1373. auto& end_block = generator.make_block();
  1374. TRY(m_test->generate_bytecode(generator));
  1375. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1376. Bytecode::Label { true_block },
  1377. Bytecode::Label { false_block });
  1378. generator.switch_to_basic_block(true_block);
  1379. TRY(m_consequent->generate_bytecode(generator));
  1380. generator.emit<Bytecode::Op::Jump>().set_targets(
  1381. Bytecode::Label { end_block },
  1382. {});
  1383. generator.switch_to_basic_block(false_block);
  1384. TRY(m_alternate->generate_bytecode(generator));
  1385. generator.emit<Bytecode::Op::Jump>().set_targets(
  1386. Bytecode::Label { end_block },
  1387. {});
  1388. generator.switch_to_basic_block(end_block);
  1389. return {};
  1390. }
  1391. Bytecode::CodeGenerationErrorOr<void> SequenceExpression::generate_bytecode(Bytecode::Generator& generator) const
  1392. {
  1393. for (auto& expression : m_expressions)
  1394. TRY(expression.generate_bytecode(generator));
  1395. return {};
  1396. }
  1397. Bytecode::CodeGenerationErrorOr<void> TemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1398. {
  1399. auto string_reg = generator.allocate_register();
  1400. for (size_t i = 0; i < m_expressions.size(); i++) {
  1401. TRY(m_expressions[i].generate_bytecode(generator));
  1402. if (i == 0) {
  1403. generator.emit<Bytecode::Op::Store>(string_reg);
  1404. } else {
  1405. generator.emit<Bytecode::Op::ConcatString>(string_reg);
  1406. }
  1407. }
  1408. generator.emit<Bytecode::Op::Load>(string_reg);
  1409. return {};
  1410. }
  1411. Bytecode::CodeGenerationErrorOr<void> TaggedTemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1412. {
  1413. TRY(m_tag->generate_bytecode(generator));
  1414. auto tag_reg = generator.allocate_register();
  1415. generator.emit<Bytecode::Op::Store>(tag_reg);
  1416. Vector<Bytecode::Register> string_regs;
  1417. auto& expressions = m_template_literal->expressions();
  1418. for (size_t i = 0; i < expressions.size(); ++i) {
  1419. if (i % 2 != 0)
  1420. continue;
  1421. string_regs.append(generator.allocate_register());
  1422. }
  1423. size_t reg_index = 0;
  1424. for (size_t i = 0; i < expressions.size(); ++i) {
  1425. if (i % 2 != 0)
  1426. continue;
  1427. TRY(expressions[i].generate_bytecode(generator));
  1428. auto string_reg = string_regs[reg_index++];
  1429. generator.emit<Bytecode::Op::Store>(string_reg);
  1430. }
  1431. if (string_regs.is_empty()) {
  1432. generator.emit<Bytecode::Op::NewArray>();
  1433. } else {
  1434. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { string_regs.first(), string_regs.last() });
  1435. }
  1436. auto strings_reg = generator.allocate_register();
  1437. generator.emit<Bytecode::Op::Store>(strings_reg);
  1438. Vector<Bytecode::Register> argument_regs;
  1439. argument_regs.append(strings_reg);
  1440. for (size_t i = 0; i < expressions.size(); ++i) {
  1441. if (i % 2 == 0)
  1442. continue;
  1443. TRY(expressions[i].generate_bytecode(generator));
  1444. auto string_reg = generator.allocate_register();
  1445. generator.emit<Bytecode::Op::Store>(string_reg);
  1446. argument_regs.append(string_reg);
  1447. }
  1448. Vector<Bytecode::Register> raw_string_regs;
  1449. for ([[maybe_unused]] auto& raw_string : m_template_literal->raw_strings())
  1450. string_regs.append(generator.allocate_register());
  1451. reg_index = 0;
  1452. for (auto& raw_string : m_template_literal->raw_strings()) {
  1453. TRY(raw_string.generate_bytecode(generator));
  1454. auto raw_string_reg = string_regs[reg_index++];
  1455. generator.emit<Bytecode::Op::Store>(raw_string_reg);
  1456. raw_string_regs.append(raw_string_reg);
  1457. }
  1458. if (raw_string_regs.is_empty()) {
  1459. generator.emit<Bytecode::Op::NewArray>();
  1460. } else {
  1461. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { raw_string_regs.first(), raw_string_regs.last() });
  1462. }
  1463. auto raw_strings_reg = generator.allocate_register();
  1464. generator.emit<Bytecode::Op::Store>(raw_strings_reg);
  1465. generator.emit<Bytecode::Op::Load>(strings_reg);
  1466. generator.emit<Bytecode::Op::PutById>(raw_strings_reg, generator.intern_identifier("raw"));
  1467. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1468. auto this_reg = generator.allocate_register();
  1469. generator.emit<Bytecode::Op::Store>(this_reg);
  1470. generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_regs.size(), Bytecode::Op::Call::CallType::Call, tag_reg, this_reg, move(argument_regs));
  1471. return {};
  1472. }
  1473. Bytecode::CodeGenerationErrorOr<void> UpdateExpression::generate_bytecode(Bytecode::Generator& generator) const
  1474. {
  1475. TRY(generator.emit_load_from_reference(*m_argument));
  1476. Optional<Bytecode::Register> previous_value_for_postfix_reg;
  1477. if (!m_prefixed) {
  1478. previous_value_for_postfix_reg = generator.allocate_register();
  1479. generator.emit<Bytecode::Op::Store>(*previous_value_for_postfix_reg);
  1480. }
  1481. if (m_op == UpdateOp::Increment)
  1482. generator.emit<Bytecode::Op::Increment>();
  1483. else
  1484. generator.emit<Bytecode::Op::Decrement>();
  1485. TRY(generator.emit_store_to_reference(*m_argument));
  1486. if (!m_prefixed)
  1487. generator.emit<Bytecode::Op::Load>(*previous_value_for_postfix_reg);
  1488. return {};
  1489. }
  1490. Bytecode::CodeGenerationErrorOr<void> ThrowStatement::generate_bytecode(Bytecode::Generator& generator) const
  1491. {
  1492. TRY(m_argument->generate_bytecode(generator));
  1493. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1494. generator.emit<Bytecode::Op::Throw>();
  1495. return {};
  1496. }
  1497. Bytecode::CodeGenerationErrorOr<void> BreakStatement::generate_bytecode(Bytecode::Generator& generator) const
  1498. {
  1499. if (m_target_label.is_null()) {
  1500. generator.perform_needed_unwinds<Bytecode::Op::Jump>(true);
  1501. generator.emit<Bytecode::Op::Jump>().set_targets(
  1502. generator.nearest_breakable_scope(),
  1503. {});
  1504. return {};
  1505. }
  1506. auto target_to_jump_to = generator.perform_needed_unwinds_for_labelled_break_and_return_target_block(m_target_label);
  1507. generator.emit<Bytecode::Op::Jump>().set_targets(
  1508. target_to_jump_to,
  1509. {});
  1510. return {};
  1511. }
  1512. Bytecode::CodeGenerationErrorOr<void> TryStatement::generate_bytecode(Bytecode::Generator& generator) const
  1513. {
  1514. auto& saved_block = generator.current_block();
  1515. Optional<Bytecode::Label> handler_target;
  1516. Optional<Bytecode::Label> finalizer_target;
  1517. Bytecode::BasicBlock* next_block { nullptr };
  1518. if (m_finalizer) {
  1519. auto& finalizer_block = generator.make_block();
  1520. generator.switch_to_basic_block(finalizer_block);
  1521. TRY(m_finalizer->generate_bytecode(generator));
  1522. if (!generator.is_current_block_terminated()) {
  1523. next_block = &generator.make_block();
  1524. auto next_target = Bytecode::Label { *next_block };
  1525. generator.emit<Bytecode::Op::ContinuePendingUnwind>(next_target);
  1526. }
  1527. finalizer_target = Bytecode::Label { finalizer_block };
  1528. }
  1529. if (m_handler) {
  1530. auto& handler_block = generator.make_block();
  1531. generator.switch_to_basic_block(handler_block);
  1532. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  1533. TRY(m_handler->parameter().visit(
  1534. [&](FlyString const& parameter) -> Bytecode::CodeGenerationErrorOr<void> {
  1535. if (!parameter.is_empty()) {
  1536. auto parameter_identifier = generator.intern_identifier(parameter);
  1537. generator.register_binding(parameter_identifier);
  1538. generator.emit<Bytecode::Op::CreateVariable>(parameter_identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1539. generator.emit<Bytecode::Op::SetVariable>(parameter_identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1540. }
  1541. return {};
  1542. },
  1543. [&](NonnullRefPtr<BindingPattern> const&) -> Bytecode::CodeGenerationErrorOr<void> {
  1544. // FIXME: Implement this path when the above DeclarativeEnvironment issue is dealt with.
  1545. return Bytecode::CodeGenerationError {
  1546. this,
  1547. "Unimplemented catch argument: BindingPattern"sv,
  1548. };
  1549. }));
  1550. TRY(m_handler->body().generate_bytecode(generator));
  1551. handler_target = Bytecode::Label { handler_block };
  1552. generator.end_variable_scope();
  1553. if (!generator.is_current_block_terminated()) {
  1554. if (m_finalizer) {
  1555. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1556. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1557. } else {
  1558. VERIFY(!next_block);
  1559. next_block = &generator.make_block();
  1560. auto next_target = Bytecode::Label { *next_block };
  1561. generator.emit<Bytecode::Op::Jump>(next_target);
  1562. }
  1563. }
  1564. }
  1565. auto& target_block = generator.make_block();
  1566. generator.switch_to_basic_block(saved_block);
  1567. generator.emit<Bytecode::Op::EnterUnwindContext>(Bytecode::Label { target_block }, handler_target, finalizer_target);
  1568. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1569. generator.switch_to_basic_block(target_block);
  1570. TRY(m_block->generate_bytecode(generator));
  1571. if (!generator.is_current_block_terminated()) {
  1572. if (m_finalizer) {
  1573. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1574. } else {
  1575. auto& block = generator.make_block();
  1576. generator.emit<Bytecode::Op::FinishUnwind>(Bytecode::Label { block });
  1577. next_block = &block;
  1578. }
  1579. }
  1580. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1581. generator.switch_to_basic_block(next_block ? *next_block : saved_block);
  1582. return {};
  1583. }
  1584. Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_bytecode(Bytecode::Generator& generator) const
  1585. {
  1586. return generate_labelled_evaluation(generator, {});
  1587. }
  1588. Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<FlyString> const& label_set) const
  1589. {
  1590. auto discriminant_reg = generator.allocate_register();
  1591. TRY(m_discriminant->generate_bytecode(generator));
  1592. generator.emit<Bytecode::Op::Store>(discriminant_reg);
  1593. Vector<Bytecode::BasicBlock&> case_blocks;
  1594. Bytecode::BasicBlock* default_block { nullptr };
  1595. Bytecode::BasicBlock* next_test_block = &generator.make_block();
  1596. auto has_lexical_block = has_lexical_declarations();
  1597. // Note: This call ends up calling begin_variable_scope() if has_lexical_block is true, so we need to clean up after it at the end.
  1598. TRY(ScopeNode::generate_bytecode(generator));
  1599. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_test_block }, {});
  1600. for (auto& switch_case : m_cases) {
  1601. auto& case_block = generator.make_block();
  1602. if (switch_case.test()) {
  1603. generator.switch_to_basic_block(*next_test_block);
  1604. TRY(switch_case.test()->generate_bytecode(generator));
  1605. generator.emit<Bytecode::Op::StrictlyEquals>(discriminant_reg);
  1606. next_test_block = &generator.make_block();
  1607. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { case_block }, Bytecode::Label { *next_test_block });
  1608. } else {
  1609. default_block = &case_block;
  1610. }
  1611. case_blocks.append(case_block);
  1612. }
  1613. generator.switch_to_basic_block(*next_test_block);
  1614. auto& end_block = generator.make_block();
  1615. if (default_block != nullptr) {
  1616. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *default_block }, {});
  1617. } else {
  1618. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1619. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1620. }
  1621. auto current_block = case_blocks.begin();
  1622. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  1623. for (auto& switch_case : m_cases) {
  1624. generator.switch_to_basic_block(*current_block);
  1625. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1626. for (auto& statement : switch_case.children()) {
  1627. TRY(statement.generate_bytecode(generator));
  1628. if (generator.is_current_block_terminated())
  1629. break;
  1630. }
  1631. if (!generator.is_current_block_terminated()) {
  1632. auto next_block = current_block;
  1633. next_block++;
  1634. if (next_block.is_end()) {
  1635. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1636. } else {
  1637. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_block }, {});
  1638. }
  1639. }
  1640. current_block++;
  1641. }
  1642. generator.end_breakable_scope();
  1643. if (has_lexical_block)
  1644. generator.end_variable_scope();
  1645. generator.switch_to_basic_block(end_block);
  1646. return {};
  1647. }
  1648. Bytecode::CodeGenerationErrorOr<void> ClassDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1649. {
  1650. TRY(m_class_expression->generate_bytecode(generator));
  1651. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(m_class_expression.ptr()->name()), Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1652. return {};
  1653. }
  1654. Bytecode::CodeGenerationErrorOr<void> ClassExpression::generate_bytecode(Bytecode::Generator& generator) const
  1655. {
  1656. generator.emit<Bytecode::Op::NewClass>(*this);
  1657. return {};
  1658. }
  1659. Bytecode::CodeGenerationErrorOr<void> ThisExpression::generate_bytecode(Bytecode::Generator& generator) const
  1660. {
  1661. generator.emit<Bytecode::Op::ResolveThisBinding>();
  1662. return {};
  1663. }
  1664. Bytecode::CodeGenerationErrorOr<void> AwaitExpression::generate_bytecode(Bytecode::Generator& generator) const
  1665. {
  1666. VERIFY(generator.is_in_async_function());
  1667. // Transform `await expr` to `yield expr`
  1668. TRY(m_argument->generate_bytecode(generator));
  1669. auto& continuation_block = generator.make_block();
  1670. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1671. generator.switch_to_basic_block(continuation_block);
  1672. return {};
  1673. }
  1674. Bytecode::CodeGenerationErrorOr<void> WithStatement::generate_bytecode(Bytecode::Generator& generator) const
  1675. {
  1676. TRY(m_object->generate_bytecode(generator));
  1677. generator.emit<Bytecode::Op::EnterObjectEnvironment>();
  1678. // EnterObjectEnvironment sets the running execution context's lexical_environment to a new Object Environment.
  1679. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1680. TRY(m_body->generate_bytecode(generator));
  1681. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1682. if (!generator.is_current_block_terminated())
  1683. generator.emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  1684. return {};
  1685. }
  1686. enum class LHSKind {
  1687. Assignment,
  1688. VarBinding,
  1689. LexicalBinding,
  1690. };
  1691. enum class IterationKind {
  1692. Enumerate,
  1693. Iterate,
  1694. AsyncIterate,
  1695. };
  1696. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  1697. struct ForInOfHeadEvaluationResult {
  1698. bool is_destructuring { false };
  1699. LHSKind lhs_kind { LHSKind::Assignment };
  1700. };
  1701. 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)
  1702. {
  1703. ForInOfHeadEvaluationResult result {};
  1704. if (auto* ast_ptr = lhs.get_pointer<NonnullRefPtr<ASTNode>>(); ast_ptr && is<VariableDeclaration>(**ast_ptr)) {
  1705. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  1706. // ForInOfStatement : for ( var ForBinding in Expression ) Statement
  1707. // ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  1708. // ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  1709. // ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  1710. auto& variable_declaration = static_cast<VariableDeclaration const&>(**ast_ptr);
  1711. result.is_destructuring = variable_declaration.declarations().first().target().has<NonnullRefPtr<BindingPattern>>();
  1712. result.lhs_kind = variable_declaration.is_lexical_declaration() ? LHSKind::LexicalBinding : LHSKind::VarBinding;
  1713. // 1. Let oldEnv be the running execution context's LexicalEnvironment.
  1714. // NOTE: 'uninitializedBoundNames' refers to the lexical bindings (i.e. Const/Let) present in the second and last form.
  1715. // 2. If uninitializedBoundNames is not an empty List, then
  1716. bool entered_lexical_scope = false;
  1717. if (variable_declaration.declaration_kind() != DeclarationKind::Var) {
  1718. entered_lexical_scope = true;
  1719. // a. Assert: uninitializedBoundNames has no duplicate entries.
  1720. // b. Let newEnv be NewDeclarativeEnvironment(oldEnv).
  1721. generator.begin_variable_scope();
  1722. // c. For each String name of uninitializedBoundNames, do
  1723. variable_declaration.for_each_bound_name([&](auto const& name) {
  1724. // i. Perform ! newEnv.CreateMutableBinding(name, false).
  1725. auto identifier = generator.intern_identifier(name);
  1726. generator.register_binding(identifier);
  1727. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1728. });
  1729. // d. Set the running execution context's LexicalEnvironment to newEnv.
  1730. // NOTE: Done by CreateEnvironment.
  1731. }
  1732. // 3. Let exprRef be the result of evaluating expr.
  1733. TRY(rhs->generate_bytecode(generator));
  1734. // 4. Set the running execution context's LexicalEnvironment to oldEnv.
  1735. if (entered_lexical_scope)
  1736. generator.end_variable_scope();
  1737. // 5. Let exprValue be ? GetValue(exprRef).
  1738. // NOTE: No need to store this anywhere.
  1739. // 6. If iterationKind is enumerate, then
  1740. if (iteration_kind == IterationKind::Enumerate) {
  1741. // a. If exprValue is undefined or null, then
  1742. auto& nullish_block = generator.make_block();
  1743. auto& continuation_block = generator.make_block();
  1744. auto& jump = generator.emit<Bytecode::Op::JumpNullish>();
  1745. jump.set_targets(Bytecode::Label { nullish_block }, Bytecode::Label { continuation_block });
  1746. // i. Return Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  1747. generator.switch_to_basic_block(nullish_block);
  1748. generator.perform_needed_unwinds<Bytecode::Op::Jump>(true);
  1749. generator.emit<Bytecode::Op::Jump>().set_targets(generator.nearest_breakable_scope(), {});
  1750. generator.switch_to_basic_block(continuation_block);
  1751. // b. Let obj be ! ToObject(exprValue).
  1752. // NOTE: GetObjectPropertyIterator does this.
  1753. // c. Let iterator be EnumerateObjectProperties(obj).
  1754. // d. Let nextMethod be ! GetV(iterator, "next").
  1755. // e. Return the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
  1756. generator.emit<Bytecode::Op::GetObjectPropertyIterator>();
  1757. }
  1758. // 7. Else,
  1759. else {
  1760. // a. Assert: iterationKind is iterate or async-iterate.
  1761. // b. If iterationKind is async-iterate, let iteratorHint be async.
  1762. if (iteration_kind == IterationKind::AsyncIterate) {
  1763. return Bytecode::CodeGenerationError {
  1764. rhs.ptr(),
  1765. "Unimplemented iteration mode: AsyncIterate"sv,
  1766. };
  1767. }
  1768. // c. Else, let iteratorHint be sync.
  1769. // d. Return ? GetIterator(exprValue, iteratorHint).
  1770. generator.emit<Bytecode::Op::GetIterator>();
  1771. }
  1772. } else {
  1773. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  1774. // ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  1775. // ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  1776. // Skip everything except steps 3, 5 and 7 (see above true branch for listing).
  1777. result.lhs_kind = LHSKind::Assignment;
  1778. // 3. Let exprRef be the result of evaluating expr.
  1779. TRY(rhs->generate_bytecode(generator));
  1780. // 5. Let exprValue be ? GetValue(exprRef).
  1781. // NOTE: No need to store this anywhere.
  1782. // a. Assert: iterationKind is iterate or async-iterate.
  1783. // b. If iterationKind is async-iterate, let iteratorHint be async.
  1784. if (iteration_kind == IterationKind::AsyncIterate) {
  1785. return Bytecode::CodeGenerationError {
  1786. rhs.ptr(),
  1787. "Unimplemented iteration mode: AsyncIterate"sv,
  1788. };
  1789. }
  1790. // c. Else, let iteratorHint be sync.
  1791. // d. Return ? GetIterator(exprValue, iteratorHint).
  1792. generator.emit<Bytecode::Op::GetIterator>();
  1793. }
  1794. return result;
  1795. }
  1796. // 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
  1797. 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, Vector<FlyString> const& label_set, Bytecode::BasicBlock& loop_end, Bytecode::BasicBlock& loop_update)
  1798. {
  1799. auto iterator_register = generator.allocate_register();
  1800. generator.emit<Bytecode::Op::Store>(iterator_register);
  1801. // FIXME: Implement this
  1802. // 1. If iteratorKind is not present, set iteratorKind to sync.
  1803. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  1804. bool has_lexical_binding = false;
  1805. // 3. Let V be undefined.
  1806. // NOTE: We don't need 'V' as the resulting value will naturally flow through via the accumulator register.
  1807. // 4. Let destructuring be IsDestructuring of lhs.
  1808. auto destructuring = head_result.is_destructuring;
  1809. // 5. If destructuring is true and if lhsKind is assignment, then
  1810. if (destructuring) {
  1811. // a. Assert: lhs is a LeftHandSideExpression.
  1812. // b. Let assignmentPattern be the AssignmentPattern that is covered by lhs.
  1813. // FIXME: Implement this.
  1814. return Bytecode::CodeGenerationError {
  1815. &node,
  1816. "Unimplemented: destructuring in for-in/of"sv,
  1817. };
  1818. }
  1819. // 6. Repeat,
  1820. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_update });
  1821. generator.switch_to_basic_block(loop_update);
  1822. generator.begin_continuable_scope(Bytecode::Label { loop_update }, label_set);
  1823. // a. Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
  1824. generator.emit<Bytecode::Op::Load>(iterator_register);
  1825. generator.emit<Bytecode::Op::IteratorNext>();
  1826. // FIXME: Implement this:
  1827. // b. If iteratorKind is async, set nextResult to ? Await(nextResult).
  1828. // c. If Type(nextResult) is not Object, throw a TypeError exception.
  1829. // NOTE: IteratorComplete already does this.
  1830. // d. Let done be ? IteratorComplete(nextResult).
  1831. auto iterator_result_register = generator.allocate_register();
  1832. generator.emit<Bytecode::Op::Store>(iterator_result_register);
  1833. generator.emit<Bytecode::Op::IteratorResultDone>();
  1834. // e. If done is true, return V.
  1835. auto& loop_continue = generator.make_block();
  1836. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { loop_end }, Bytecode::Label { loop_continue });
  1837. generator.switch_to_basic_block(loop_continue);
  1838. // f. Let nextValue be ? IteratorValue(nextResult).
  1839. generator.emit<Bytecode::Op::Load>(iterator_result_register);
  1840. generator.emit<Bytecode::Op::IteratorResultValue>();
  1841. // g. If lhsKind is either assignment or varBinding, then
  1842. if (head_result.lhs_kind != LHSKind::LexicalBinding) {
  1843. // i. If destructuring is false, then
  1844. if (!destructuring) {
  1845. // 1. Let lhsRef be the result of evaluating lhs. (It may be evaluated repeatedly.)
  1846. // NOTE: We're skipping all the completion stuff that the spec does, as the unwinding mechanism will take case of doing that.
  1847. if (head_result.lhs_kind == LHSKind::VarBinding) {
  1848. auto& declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode>>());
  1849. VERIFY(declaration.declarations().size() == 1);
  1850. TRY(assign_accumulator_to_variable_declarator(generator, declaration.declarations().first(), declaration));
  1851. } else {
  1852. if (auto ptr = lhs.get_pointer<NonnullRefPtr<ASTNode>>()) {
  1853. TRY(generator.emit_store_to_reference(**ptr));
  1854. } else {
  1855. auto& binding_pattern = lhs.get<NonnullRefPtr<BindingPattern>>();
  1856. TRY(generate_binding_pattern_bytecode(generator, *binding_pattern, Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Register::accumulator()));
  1857. }
  1858. }
  1859. }
  1860. }
  1861. // h. Else,
  1862. else {
  1863. // i. Assert: lhsKind is lexicalBinding.
  1864. // ii. Assert: lhs is a ForDeclaration.
  1865. // iii. Let iterationEnv be NewDeclarativeEnvironment(oldEnv).
  1866. // iv. Perform ForDeclarationBindingInstantiation of lhs with argument iterationEnv.
  1867. // v. Set the running execution context's LexicalEnvironment to iterationEnv.
  1868. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical);
  1869. has_lexical_binding = true;
  1870. // 14.7.5.4 Runtime Semantics: ForDeclarationBindingInstantiation, https://tc39.es/ecma262/#sec-runtime-semantics-fordeclarationbindinginstantiation
  1871. // 1. Assert: environment is a declarative Environment Record.
  1872. // NOTE: We just made it.
  1873. auto& variable_declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode>>());
  1874. // 2. For each element name of the BoundNames of ForBinding, do
  1875. variable_declaration.for_each_bound_name([&](auto const& name) {
  1876. auto identifier = generator.intern_identifier(name);
  1877. generator.register_binding(identifier, Bytecode::Generator::BindingMode::Lexical);
  1878. // a. If IsConstantDeclaration of LetOrConst is true, then
  1879. if (variable_declaration.is_constant_declaration()) {
  1880. // i. Perform ! environment.CreateImmutableBinding(name, true).
  1881. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  1882. }
  1883. // b. Else,
  1884. else {
  1885. // i. Perform ! environment.CreateMutableBinding(name, false).
  1886. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1887. }
  1888. });
  1889. // 3. Return unused.
  1890. // NOTE: No need to do that as we've inlined this.
  1891. // vi. If destructuring is false, then
  1892. if (!destructuring) {
  1893. // 1. Assert: lhs binds a single name.
  1894. // 2. Let lhsName be the sole element of BoundNames of lhs.
  1895. auto lhs_name = variable_declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->string();
  1896. // 3. Let lhsRef be ! ResolveBinding(lhsName).
  1897. // NOTE: We're skipping all the completion stuff that the spec does, as the unwinding mechanism will take case of doing that.
  1898. auto identifier = generator.intern_identifier(lhs_name);
  1899. generator.emit<Bytecode::Op::SetVariable>(identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Lexical);
  1900. }
  1901. }
  1902. // i. If destructuring is false, then
  1903. if (!destructuring) {
  1904. // i. If lhsRef is an abrupt completion, then
  1905. // 1. Let status be lhsRef.
  1906. // ii. Else if lhsKind is lexicalBinding, then
  1907. // 1. Let status be Completion(InitializeReferencedBinding(lhsRef, nextValue)).
  1908. // iii. Else,
  1909. // 1. Let status be Completion(PutValue(lhsRef, nextValue)).
  1910. // NOTE: This is performed above.
  1911. }
  1912. // j. Else,
  1913. else {
  1914. // FIXME: Implement destructuring
  1915. // i. If lhsKind is assignment, then
  1916. // 1. Let status be Completion(DestructuringAssignmentEvaluation of assignmentPattern with argument nextValue).
  1917. // ii. Else if lhsKind is varBinding, then
  1918. // 1. Assert: lhs is a ForBinding.
  1919. // 2. Let status be Completion(BindingInitialization of lhs with arguments nextValue and undefined).
  1920. // iii. Else,
  1921. // 1. Assert: lhsKind is lexicalBinding.
  1922. // 2. Assert: lhs is a ForDeclaration.
  1923. // 3. Let status be Completion(ForDeclarationBindingInitialization of lhs with arguments nextValue and iterationEnv).
  1924. return Bytecode::CodeGenerationError {
  1925. &node,
  1926. "Unimplemented: destructuring in for-in/of"sv,
  1927. };
  1928. }
  1929. // FIXME: Implement iteration closure.
  1930. // k. If status is an abrupt completion, then
  1931. // i. Set the running execution context's LexicalEnvironment to oldEnv.
  1932. // ii. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  1933. // iii. If iterationKind is enumerate, then
  1934. // 1. Return ? status.
  1935. // iv. Else,
  1936. // 1. Assert: iterationKind is iterate.
  1937. // 2. Return ? IteratorClose(iteratorRecord, status).
  1938. // l. Let result be the result of evaluating stmt.
  1939. TRY(body.generate_bytecode(generator));
  1940. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  1941. if (has_lexical_binding)
  1942. generator.end_variable_scope();
  1943. generator.end_continuable_scope();
  1944. generator.end_breakable_scope();
  1945. // NOTE: If we're here, then the loop definitely continues.
  1946. // n. If LoopContinues(result, labelSet) is false, then
  1947. // i. If iterationKind is enumerate, then
  1948. // 1. Return ? UpdateEmpty(result, V).
  1949. // ii. Else,
  1950. // 1. Assert: iterationKind is iterate.
  1951. // 2. Set status to Completion(UpdateEmpty(result, V)).
  1952. // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  1953. // 4. Return ? IteratorClose(iteratorRecord, status).
  1954. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  1955. // The body can contain an unconditional block terminator (e.g. return, throw), so we have to check for that before generating the Jump.
  1956. if (!generator.is_current_block_terminated())
  1957. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { loop_update }, {});
  1958. generator.switch_to_basic_block(loop_end);
  1959. return {};
  1960. }
  1961. Bytecode::CodeGenerationErrorOr<void> ForInStatement::generate_bytecode(Bytecode::Generator& generator) const
  1962. {
  1963. return generate_labelled_evaluation(generator, {});
  1964. }
  1965. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  1966. Bytecode::CodeGenerationErrorOr<void> ForInStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<FlyString> const& label_set) const
  1967. {
  1968. auto& loop_end = generator.make_block();
  1969. auto& loop_update = generator.make_block();
  1970. generator.begin_breakable_scope(Bytecode::Label { loop_end }, label_set);
  1971. auto head_result = TRY(for_in_of_head_evaluation(generator, IterationKind::Enumerate, m_lhs, m_rhs));
  1972. // Now perform the rest of ForInOfLoopEvaluation, given that the accumulator holds the iterator we're supposed to iterate over.
  1973. return for_in_of_body_evaluation(generator, *this, m_lhs, body(), head_result, label_set, loop_end, loop_update);
  1974. }
  1975. Bytecode::CodeGenerationErrorOr<void> ForOfStatement::generate_bytecode(Bytecode::Generator& generator) const
  1976. {
  1977. return generate_labelled_evaluation(generator, {});
  1978. }
  1979. Bytecode::CodeGenerationErrorOr<void> ForOfStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<FlyString> const& label_set) const
  1980. {
  1981. auto& loop_end = generator.make_block();
  1982. auto& loop_update = generator.make_block();
  1983. generator.begin_breakable_scope(Bytecode::Label { loop_end }, label_set);
  1984. auto head_result = TRY(for_in_of_head_evaluation(generator, IterationKind::Iterate, m_lhs, m_rhs));
  1985. // Now perform the rest of ForInOfLoopEvaluation, given that the accumulator holds the iterator we're supposed to iterate over.
  1986. return for_in_of_body_evaluation(generator, *this, m_lhs, body(), head_result, label_set, loop_end, loop_update);
  1987. }
  1988. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  1989. Bytecode::CodeGenerationErrorOr<void> MetaProperty::generate_bytecode(Bytecode::Generator& generator) const
  1990. {
  1991. // NewTarget : new . target
  1992. if (m_type == MetaProperty::Type::NewTarget) {
  1993. // 1. Return GetNewTarget().
  1994. generator.emit<Bytecode::Op::GetNewTarget>();
  1995. return {};
  1996. }
  1997. // ImportMeta : import . meta
  1998. if (m_type == MetaProperty::Type::ImportMeta) {
  1999. return Bytecode::CodeGenerationError {
  2000. this,
  2001. "Unimplemented meta property: import.meta"sv,
  2002. };
  2003. }
  2004. VERIFY_NOT_REACHED();
  2005. }
  2006. }