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