ASTCodegen.cpp 95 KB

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