ASTCodegen.cpp 108 KB

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