ASTCodegen.cpp 163 KB

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