ASTCodegen.cpp 150 KB

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