ASTCodegen.cpp 125 KB

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