ASTCodegen.cpp 104 KB

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