ASTCodegen.cpp 125 KB

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