AST.cpp 190 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Demangle.h>
  9. #include <AK/HashMap.h>
  10. #include <AK/HashTable.h>
  11. #include <AK/QuickSort.h>
  12. #include <AK/ScopeGuard.h>
  13. #include <AK/StringBuilder.h>
  14. #include <AK/TemporaryChange.h>
  15. #include <LibCrypto/BigInt/SignedBigInteger.h>
  16. #include <LibJS/AST.h>
  17. #include <LibJS/Heap/MarkedVector.h>
  18. #include <LibJS/Interpreter.h>
  19. #include <LibJS/Runtime/AbstractOperations.h>
  20. #include <LibJS/Runtime/Accessor.h>
  21. #include <LibJS/Runtime/Array.h>
  22. #include <LibJS/Runtime/BigInt.h>
  23. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  24. #include <LibJS/Runtime/Error.h>
  25. #include <LibJS/Runtime/FunctionEnvironment.h>
  26. #include <LibJS/Runtime/GlobalObject.h>
  27. #include <LibJS/Runtime/IteratorOperations.h>
  28. #include <LibJS/Runtime/NativeFunction.h>
  29. #include <LibJS/Runtime/ObjectEnvironment.h>
  30. #include <LibJS/Runtime/PrimitiveString.h>
  31. #include <LibJS/Runtime/PromiseConstructor.h>
  32. #include <LibJS/Runtime/PromiseReaction.h>
  33. #include <LibJS/Runtime/Reference.h>
  34. #include <LibJS/Runtime/RegExpObject.h>
  35. #include <LibJS/Runtime/Shape.h>
  36. #include <typeinfo>
  37. namespace JS {
  38. class InterpreterNodeScope {
  39. AK_MAKE_NONCOPYABLE(InterpreterNodeScope);
  40. AK_MAKE_NONMOVABLE(InterpreterNodeScope);
  41. public:
  42. InterpreterNodeScope(Interpreter& interpreter, ASTNode const& node)
  43. : m_interpreter(interpreter)
  44. , m_chain_node { nullptr, node }
  45. {
  46. m_interpreter.vm().running_execution_context().current_node = &node;
  47. m_interpreter.push_ast_node(m_chain_node);
  48. }
  49. ~InterpreterNodeScope()
  50. {
  51. m_interpreter.pop_ast_node();
  52. }
  53. private:
  54. Interpreter& m_interpreter;
  55. ExecutingASTNodeChain m_chain_node;
  56. };
  57. String ASTNode::class_name() const
  58. {
  59. // NOTE: We strip the "JS::" prefix.
  60. return demangle(typeid(*this).name()).substring(4);
  61. }
  62. static void print_indent(int indent)
  63. {
  64. out("{}", String::repeated(' ', indent * 2));
  65. }
  66. static void update_function_name(Value value, FlyString const& name)
  67. {
  68. if (!value.is_function())
  69. return;
  70. auto& function = value.as_function();
  71. if (is<ECMAScriptFunctionObject>(function) && function.name().is_empty())
  72. static_cast<ECMAScriptFunctionObject&>(function).set_name(name);
  73. }
  74. static ThrowCompletionOr<String> get_function_property_name(PropertyKey key)
  75. {
  76. if (key.is_symbol())
  77. return String::formatted("[{}]", key.as_symbol()->description());
  78. return key.to_string();
  79. }
  80. // 14.2.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation
  81. // StatementList : StatementList StatementListItem
  82. Completion ScopeNode::evaluate_statements(Interpreter& interpreter, GlobalObject& global_object) const
  83. {
  84. auto completion = normal_completion({});
  85. for (auto const& node : children()) {
  86. completion = node.execute(interpreter, global_object).update_empty(completion.value());
  87. if (completion.is_abrupt())
  88. break;
  89. }
  90. return completion;
  91. }
  92. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  93. // BreakableStatement : IterationStatement
  94. static Completion labelled_evaluation(Interpreter& interpreter, GlobalObject& global_object, IterationStatement const& statement, Vector<FlyString> const& label_set)
  95. {
  96. // 1. Let stmtResult be LoopEvaluation of IterationStatement with argument labelSet.
  97. auto result = statement.loop_evaluation(interpreter, global_object, label_set);
  98. // 2. If stmtResult.[[Type]] is break, then
  99. if (result.type() == Completion::Type::Break) {
  100. // a. If stmtResult.[[Target]] is empty, then
  101. if (!result.target().has_value()) {
  102. // i. If stmtResult.[[Value]] is empty, set stmtResult to NormalCompletion(undefined).
  103. // ii. Else, set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  104. result = normal_completion(result.value().value_or(js_undefined()));
  105. }
  106. }
  107. // 3. Return Completion(stmtResult).
  108. return result;
  109. }
  110. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  111. // BreakableStatement : SwitchStatement
  112. static Completion labelled_evaluation(Interpreter& interpreter, GlobalObject& global_object, SwitchStatement const& statement, Vector<FlyString> const&)
  113. {
  114. // 1. Let stmtResult be the result of evaluating SwitchStatement.
  115. auto result = statement.execute_impl(interpreter, global_object);
  116. // 2. If stmtResult.[[Type]] is break, then
  117. if (result.type() == Completion::Type::Break) {
  118. // a. If stmtResult.[[Target]] is empty, then
  119. if (!result.target().has_value()) {
  120. // i. If stmtResult.[[Value]] is empty, set stmtResult to NormalCompletion(undefined).
  121. // ii. Else, set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  122. result = normal_completion(result.value().value_or(js_undefined()));
  123. }
  124. }
  125. // 3. Return Completion(stmtResult).
  126. return result;
  127. }
  128. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  129. // LabelledStatement : LabelIdentifier : LabelledItem
  130. static Completion labelled_evaluation(Interpreter& interpreter, GlobalObject& global_object, LabelledStatement const& statement, Vector<FlyString> const& label_set)
  131. {
  132. auto const& labelled_item = *statement.labelled_item();
  133. // 1. Let label be the StringValue of LabelIdentifier.
  134. auto const& label = statement.label();
  135. // 2. Let newLabelSet be the list-concatenation of labelSet and « label ».
  136. // Optimization: Avoid vector copy if possible.
  137. Optional<Vector<FlyString>> new_label_set;
  138. if (is<IterationStatement>(labelled_item) || is<SwitchStatement>(labelled_item) || is<LabelledStatement>(labelled_item)) {
  139. new_label_set = label_set;
  140. new_label_set->append(label);
  141. }
  142. // 3. Let stmtResult be LabelledEvaluation of LabelledItem with argument newLabelSet.
  143. Completion result;
  144. if (is<IterationStatement>(labelled_item))
  145. result = labelled_evaluation(interpreter, global_object, static_cast<IterationStatement const&>(labelled_item), *new_label_set);
  146. else if (is<SwitchStatement>(labelled_item))
  147. result = labelled_evaluation(interpreter, global_object, static_cast<SwitchStatement const&>(labelled_item), *new_label_set);
  148. else if (is<LabelledStatement>(labelled_item))
  149. result = labelled_evaluation(interpreter, global_object, static_cast<LabelledStatement const&>(labelled_item), *new_label_set);
  150. else
  151. result = labelled_item.execute(interpreter, global_object);
  152. // 4. If stmtResult.[[Type]] is break and SameValue(stmtResult.[[Target]], label) is true, then
  153. if (result.type() == Completion::Type::Break && result.target() == label) {
  154. // a. Set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  155. result = normal_completion(result.value());
  156. }
  157. // 5. Return Completion(stmtResult).
  158. return result;
  159. }
  160. // 14.13.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-labelled-statements-runtime-semantics-evaluation
  161. Completion LabelledStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  162. {
  163. InterpreterNodeScope node_scope { interpreter, *this };
  164. // 1. Let newLabelSet be a new empty List.
  165. // 2. Return LabelledEvaluation of this LabelledStatement with argument newLabelSet.
  166. return labelled_evaluation(interpreter, global_object, *this, {});
  167. }
  168. void LabelledStatement::dump(int indent) const
  169. {
  170. ASTNode::dump(indent);
  171. print_indent(indent + 1);
  172. outln("(Label)");
  173. print_indent(indent + 2);
  174. outln("\"{}\"", m_label);
  175. print_indent(indent + 1);
  176. outln("(Labelled item)");
  177. m_labelled_item->dump(indent + 2);
  178. }
  179. // 10.2.1.3 Runtime Semantics: EvaluateBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody
  180. Completion FunctionBody::execute(Interpreter& interpreter, GlobalObject& global_object) const
  181. {
  182. InterpreterNodeScope node_scope { interpreter, *this };
  183. // Note: Scoping should have already been set up by whoever is calling this FunctionBody.
  184. // 1. Return ? EvaluateFunctionBody of FunctionBody with arguments functionObject and argumentsList.
  185. return evaluate_statements(interpreter, global_object);
  186. }
  187. // 14.2.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation
  188. Completion BlockStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  189. {
  190. InterpreterNodeScope node_scope { interpreter, *this };
  191. auto& vm = interpreter.vm();
  192. Environment* old_environment { nullptr };
  193. ArmedScopeGuard restore_environment = [&] {
  194. vm.running_execution_context().lexical_environment = old_environment;
  195. };
  196. // Optimization: We only need a new lexical environment if there are any lexical declarations. :^)
  197. if (has_lexical_declarations()) {
  198. old_environment = vm.running_execution_context().lexical_environment;
  199. auto* block_environment = new_declarative_environment(*old_environment);
  200. block_declaration_instantiation(global_object, block_environment);
  201. vm.running_execution_context().lexical_environment = block_environment;
  202. } else {
  203. restore_environment.disarm();
  204. }
  205. return evaluate_statements(interpreter, global_object);
  206. }
  207. Completion Program::execute(Interpreter& interpreter, GlobalObject& global_object) const
  208. {
  209. InterpreterNodeScope node_scope { interpreter, *this };
  210. return evaluate_statements(interpreter, global_object);
  211. }
  212. // 15.2.6 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-definitions-runtime-semantics-evaluation
  213. Completion FunctionDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  214. {
  215. InterpreterNodeScope node_scope { interpreter, *this };
  216. if (m_is_hoisted) {
  217. // Perform special annexB steps see step 3 of: https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  218. // i. Let genv be the running execution context's VariableEnvironment.
  219. auto* variable_environment = interpreter.vm().running_execution_context().variable_environment;
  220. // ii. Let benv be the running execution context's LexicalEnvironment.
  221. auto* lexical_environment = interpreter.vm().running_execution_context().lexical_environment;
  222. // iii. Let fobj be ! benv.GetBindingValue(F, false).
  223. auto function_object = MUST(lexical_environment->get_binding_value(global_object, name(), false));
  224. // iv. Perform ? genv.SetMutableBinding(F, fobj, false).
  225. TRY(variable_environment->set_mutable_binding(global_object, name(), function_object, false));
  226. // v. Return NormalCompletion(empty).
  227. return normal_completion({});
  228. }
  229. // 1. Return NormalCompletion(empty).
  230. return normal_completion({});
  231. }
  232. // 15.2.6 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-definitions-runtime-semantics-evaluation
  233. Completion FunctionExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  234. {
  235. InterpreterNodeScope node_scope { interpreter, *this };
  236. // 1. Return InstantiateOrdinaryFunctionExpression of FunctionExpression.
  237. return instantiate_ordinary_function_expression(interpreter, global_object, name());
  238. }
  239. // 15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression, https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionexpression
  240. Value FunctionExpression::instantiate_ordinary_function_expression(Interpreter& interpreter, GlobalObject& global_object, FlyString given_name) const
  241. {
  242. if (given_name.is_empty())
  243. given_name = "";
  244. auto has_own_name = !name().is_empty();
  245. auto const& used_name = has_own_name ? name() : given_name;
  246. auto* scope = interpreter.lexical_environment();
  247. if (has_own_name) {
  248. VERIFY(scope);
  249. scope = new_declarative_environment(*scope);
  250. MUST(scope->create_immutable_binding(global_object, name(), false));
  251. }
  252. auto* private_scope = interpreter.vm().running_execution_context().private_environment;
  253. auto closure = ECMAScriptFunctionObject::create(global_object, used_name, source_text(), body(), parameters(), function_length(), scope, private_scope, kind(), is_strict_mode(), might_need_arguments_object(), contains_direct_call_to_eval(), is_arrow_function());
  254. // FIXME: 6. Perform SetFunctionName(closure, name).
  255. // FIXME: 7. Perform MakeConstructor(closure).
  256. if (has_own_name)
  257. MUST(scope->initialize_binding(global_object, name(), closure));
  258. return closure;
  259. }
  260. // 14.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-empty-statement-runtime-semantics-evaluation
  261. Completion EmptyStatement::execute(Interpreter&, GlobalObject&) const
  262. {
  263. // 1. Return NormalCompletion(empty).
  264. return normal_completion({});
  265. }
  266. // 14.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-expression-statement-runtime-semantics-evaluation
  267. Completion ExpressionStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  268. {
  269. InterpreterNodeScope node_scope { interpreter, *this };
  270. // 1. Let exprRef be the result of evaluating Expression.
  271. // 2. Return ? GetValue(exprRef).
  272. return m_expression->execute(interpreter, global_object);
  273. }
  274. // TODO: This shouldn't exist. Refactor into EvaluateCall.
  275. ThrowCompletionOr<CallExpression::ThisAndCallee> CallExpression::compute_this_and_callee(Interpreter& interpreter, GlobalObject& global_object, Reference const& callee_reference) const
  276. {
  277. if (callee_reference.is_property_reference()) {
  278. auto this_value = callee_reference.get_this_value();
  279. auto callee = TRY(callee_reference.get_value(global_object));
  280. return ThisAndCallee { this_value, callee };
  281. }
  282. // [[Call]] will handle that in non-strict mode the this value becomes the global object
  283. return ThisAndCallee {
  284. js_undefined(),
  285. callee_reference.is_unresolvable()
  286. ? TRY(m_callee->execute(interpreter, global_object)).release_value()
  287. : TRY(callee_reference.get_value(global_object))
  288. };
  289. }
  290. // 13.3.8.1 Runtime Semantics: ArgumentListEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  291. static ThrowCompletionOr<void> argument_list_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<CallExpression::Argument> const& arguments, MarkedVector<Value>& list)
  292. {
  293. list.ensure_capacity(arguments.size());
  294. for (auto& argument : arguments) {
  295. auto value = TRY(argument.value->execute(interpreter, global_object)).release_value();
  296. if (argument.is_spread) {
  297. auto result = TRY(get_iterator_values(global_object, value, [&](Value iterator_value) -> Optional<Completion> {
  298. list.append(iterator_value);
  299. return {};
  300. }));
  301. } else {
  302. list.append(value);
  303. }
  304. }
  305. return {};
  306. }
  307. // 13.3.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-new-operator-runtime-semantics-evaluation
  308. // 13.3.5.1.1 EvaluateNew ( constructExpr, arguments ), https://tc39.es/ecma262/#sec-evaluatenew
  309. Completion NewExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  310. {
  311. InterpreterNodeScope node_scope { interpreter, *this };
  312. auto& vm = interpreter.vm();
  313. // 1. Let ref be the result of evaluating constructExpr.
  314. // 2. Let constructor be ? GetValue(ref).
  315. auto constructor = TRY(m_callee->execute(interpreter, global_object)).release_value();
  316. // 3. If arguments is empty, let argList be a new empty List.
  317. // 4. Else,
  318. // a. Let argList be ? ArgumentListEvaluation of arguments.
  319. MarkedVector<Value> arg_list(vm.heap());
  320. TRY(argument_list_evaluation(interpreter, global_object, m_arguments, arg_list));
  321. // 5. If IsConstructor(constructor) is false, throw a TypeError exception.
  322. if (!constructor.is_constructor())
  323. return throw_type_error_for_callee(interpreter, global_object, constructor, "constructor"sv);
  324. // 6. Return ? Construct(constructor, argList).
  325. return Value { TRY(construct(global_object, constructor.as_function(), move(arg_list))) };
  326. }
  327. Completion CallExpression::throw_type_error_for_callee(Interpreter& interpreter, GlobalObject& global_object, Value callee_value, StringView call_type) const
  328. {
  329. auto& vm = interpreter.vm();
  330. if (is<Identifier>(*m_callee) || is<MemberExpression>(*m_callee)) {
  331. String expression_string;
  332. if (is<Identifier>(*m_callee)) {
  333. expression_string = static_cast<Identifier const&>(*m_callee).string();
  334. } else {
  335. expression_string = static_cast<MemberExpression const&>(*m_callee).to_string_approximation();
  336. }
  337. return vm.throw_completion<TypeError>(global_object, ErrorType::IsNotAEvaluatedFrom, callee_value.to_string_without_side_effects(), call_type, expression_string);
  338. } else {
  339. return vm.throw_completion<TypeError>(global_object, ErrorType::IsNotA, callee_value.to_string_without_side_effects(), call_type);
  340. }
  341. }
  342. // 13.3.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation
  343. Completion CallExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  344. {
  345. InterpreterNodeScope node_scope { interpreter, *this };
  346. auto& vm = interpreter.vm();
  347. auto callee_reference = TRY(m_callee->to_reference(interpreter, global_object));
  348. auto [this_value, callee] = TRY(compute_this_and_callee(interpreter, global_object, callee_reference));
  349. VERIFY(!callee.is_empty());
  350. MarkedVector<Value> arg_list(vm.heap());
  351. TRY(argument_list_evaluation(interpreter, global_object, m_arguments, arg_list));
  352. if (!callee.is_function())
  353. return throw_type_error_for_callee(interpreter, global_object, callee, "function"sv);
  354. auto& function = callee.as_function();
  355. if (&function == global_object.eval_function()
  356. && callee_reference.is_environment_reference()
  357. && callee_reference.name().is_string()
  358. && callee_reference.name().as_string() == vm.names.eval.as_string()) {
  359. auto script_value = arg_list.size() == 0 ? js_undefined() : arg_list[0];
  360. return perform_eval(script_value, global_object, vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct);
  361. }
  362. return call(global_object, function, this_value, move(arg_list));
  363. }
  364. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  365. // SuperCall : super Arguments
  366. Completion SuperCall::execute(Interpreter& interpreter, GlobalObject& global_object) const
  367. {
  368. InterpreterNodeScope node_scope { interpreter, *this };
  369. auto& vm = interpreter.vm();
  370. // 1. Let newTarget be GetNewTarget().
  371. auto new_target = vm.get_new_target();
  372. // 2. Assert: Type(newTarget) is Object.
  373. VERIFY(new_target.is_function());
  374. // 3. Let func be ! GetSuperConstructor().
  375. auto* func = get_super_constructor(interpreter.vm());
  376. // 4. Let argList be ? ArgumentListEvaluation of Arguments.
  377. MarkedVector<Value> arg_list(vm.heap());
  378. TRY(argument_list_evaluation(interpreter, global_object, m_arguments, arg_list));
  379. // 5. If IsConstructor(func) is false, throw a TypeError exception.
  380. if (!func || !Value(func).is_constructor())
  381. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, "Super constructor");
  382. // 6. Let result be ? Construct(func, argList, newTarget).
  383. auto* result = TRY(construct(global_object, static_cast<FunctionObject&>(*func), move(arg_list), &new_target.as_function()));
  384. // 7. Let thisER be GetThisEnvironment().
  385. auto& this_er = verify_cast<FunctionEnvironment>(get_this_environment(interpreter.vm()));
  386. // 8. Perform ? thisER.BindThisValue(result).
  387. TRY(this_er.bind_this_value(global_object, result));
  388. // 9. Let F be thisER.[[FunctionObject]].
  389. // 10. Assert: F is an ECMAScript function object. (NOTE: This is implied by the strong C++ type.)
  390. [[maybe_unused]] auto& f = this_er.function_object();
  391. // 11. Perform ? InitializeInstanceElements(result, F).
  392. TRY(vm.initialize_instance_elements(*result, f));
  393. // 12. Return result.
  394. return Value { result };
  395. }
  396. // 15.5.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-generator-function-definitions-runtime-semantics-evaluation
  397. Completion YieldExpression::execute(Interpreter&, GlobalObject&) const
  398. {
  399. // This should be transformed to a return.
  400. VERIFY_NOT_REACHED();
  401. }
  402. // 15.8.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-async-function-definitions-runtime-semantics-evaluation
  403. Completion AwaitExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  404. {
  405. InterpreterNodeScope node_scope { interpreter, *this };
  406. // 1. Let exprRef be the result of evaluating UnaryExpression.
  407. // 2. Let value be ? GetValue(exprRef).
  408. auto value = TRY(m_argument->execute(interpreter, global_object)).release_value();
  409. // 3. Return ? Await(value).
  410. return await(global_object, value);
  411. }
  412. // 14.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-return-statement-runtime-semantics-evaluation
  413. Completion ReturnStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  414. {
  415. InterpreterNodeScope node_scope { interpreter, *this };
  416. // ReturnStatement : return ;
  417. if (!m_argument) {
  418. // 1. Return Completion { [[Type]]: return, [[Value]]: undefined, [[Target]]: empty }.
  419. return { Completion::Type::Return, js_undefined(), {} };
  420. }
  421. // ReturnStatement : return Expression ;
  422. // 1. Let exprRef be the result of evaluating Expression.
  423. // 2. Let exprValue be ? GetValue(exprRef).
  424. auto value = TRY(m_argument->execute(interpreter, global_object));
  425. // NOTE: Generators are not supported in the AST interpreter
  426. // 3. If ! GetGeneratorKind() is async, set exprValue to ? Await(exprValue).
  427. // 4. Return Completion { [[Type]]: return, [[Value]]: exprValue, [[Target]]: empty }.
  428. return { Completion::Type::Return, value, {} };
  429. }
  430. // 14.6.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-if-statement-runtime-semantics-evaluation
  431. Completion IfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  432. {
  433. InterpreterNodeScope node_scope { interpreter, *this };
  434. // IfStatement : if ( Expression ) Statement else Statement
  435. // 1. Let exprRef be the result of evaluating Expression.
  436. // 2. Let exprValue be ! ToBoolean(? GetValue(exprRef)).
  437. auto predicate_result = TRY(m_predicate->execute(interpreter, global_object)).release_value();
  438. // 3. If exprValue is true, then
  439. if (predicate_result.to_boolean()) {
  440. // a. Let stmtCompletion be the result of evaluating the first Statement.
  441. // 5. Return Completion(UpdateEmpty(stmtCompletion, undefined)).
  442. return m_consequent->execute(interpreter, global_object).update_empty(js_undefined());
  443. }
  444. // 4. Else,
  445. if (m_alternate) {
  446. // a. Let stmtCompletion be the result of evaluating the second Statement.
  447. // 5. Return Completion(UpdateEmpty(stmtCompletion, undefined)).
  448. return m_alternate->execute(interpreter, global_object).update_empty(js_undefined());
  449. }
  450. // IfStatement : if ( Expression ) Statement
  451. // 3. If exprValue is false, then
  452. // a. Return NormalCompletion(undefined).
  453. return normal_completion(js_undefined());
  454. }
  455. // 14.11.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-with-statement-runtime-semantics-evaluation
  456. // WithStatement : with ( Expression ) Statement
  457. Completion WithStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  458. {
  459. InterpreterNodeScope node_scope { interpreter, *this };
  460. // 1. Let value be the result of evaluating Expression.
  461. auto value = TRY(m_object->execute(interpreter, global_object)).release_value();
  462. // 2. Let obj be ? ToObject(? GetValue(value)).
  463. auto* object = TRY(value.to_object(global_object));
  464. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
  465. auto* old_environment = interpreter.vm().running_execution_context().lexical_environment;
  466. // 4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv).
  467. auto* new_environment = new_object_environment(*object, true, old_environment);
  468. // 5. Set the running execution context's LexicalEnvironment to newEnv.
  469. interpreter.vm().running_execution_context().lexical_environment = new_environment;
  470. // 6. Let C be the result of evaluating Statement.
  471. auto result = m_body->execute(interpreter, global_object);
  472. // 7. Set the running execution context's LexicalEnvironment to oldEnv.
  473. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  474. // 8. Return Completion(UpdateEmpty(C, undefined)).
  475. return result.update_empty(js_undefined());
  476. }
  477. // 14.7.1.1 LoopContinues ( completion, labelSet ), https://tc39.es/ecma262/#sec-loopcontinues
  478. static bool loop_continues(Completion const& completion, Vector<FlyString> const& label_set)
  479. {
  480. // 1. If completion.[[Type]] is normal, return true.
  481. if (completion.type() == Completion::Type::Normal)
  482. return true;
  483. // 2. If completion.[[Type]] is not continue, return false.
  484. if (completion.type() != Completion::Type::Continue)
  485. return false;
  486. // 3. If completion.[[Target]] is empty, return true.
  487. if (!completion.target().has_value())
  488. return true;
  489. // 4. If completion.[[Target]] is an element of labelSet, return true.
  490. if (label_set.contains_slow(*completion.target()))
  491. return true;
  492. // 5. Return false.
  493. return false;
  494. }
  495. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  496. // BreakableStatement : IterationStatement
  497. Completion WhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  498. {
  499. // 1. Let newLabelSet be a new empty List.
  500. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  501. return labelled_evaluation(interpreter, global_object, *this, {});
  502. }
  503. // 14.7.3.2 Runtime Semantics: WhileLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-whileloopevaluation
  504. Completion WhileStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  505. {
  506. InterpreterNodeScope node_scope { interpreter, *this };
  507. // 1. Let V be undefined.
  508. auto last_value = js_undefined();
  509. // 2. Repeat,
  510. for (;;) {
  511. // a. Let exprRef be the result of evaluating Expression.
  512. // b. Let exprValue be ? GetValue(exprRef).
  513. auto test_result = TRY(m_test->execute(interpreter, global_object)).release_value();
  514. // c. If ! ToBoolean(exprValue) is false, return NormalCompletion(V).
  515. if (!test_result.to_boolean())
  516. return normal_completion(last_value);
  517. // d. Let stmtResult be the result of evaluating Statement.
  518. auto body_result = m_body->execute(interpreter, global_object);
  519. // e. If LoopContinues(stmtResult, labelSet) is false, return Completion(UpdateEmpty(stmtResult, V)).
  520. if (!loop_continues(body_result, label_set))
  521. return body_result.update_empty(last_value);
  522. // f. If stmtResult.[[Value]] is not empty, set V to stmtResult.[[Value]].
  523. if (body_result.value().has_value())
  524. last_value = *body_result.value();
  525. }
  526. VERIFY_NOT_REACHED();
  527. }
  528. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  529. // BreakableStatement : IterationStatement
  530. Completion DoWhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  531. {
  532. // 1. Let newLabelSet be a new empty List.
  533. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  534. return labelled_evaluation(interpreter, global_object, *this, {});
  535. }
  536. // 14.7.2.2 Runtime Semantics: DoWhileLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-dowhileloopevaluation
  537. Completion DoWhileStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  538. {
  539. InterpreterNodeScope node_scope { interpreter, *this };
  540. // 1. Let V be undefined.
  541. auto last_value = js_undefined();
  542. // 2. Repeat,
  543. for (;;) {
  544. // a. Let stmtResult be the result of evaluating Statement.
  545. auto body_result = m_body->execute(interpreter, global_object);
  546. // b. If LoopContinues(stmtResult, labelSet) is false, return Completion(UpdateEmpty(stmtResult, V)).
  547. if (!loop_continues(body_result, label_set))
  548. return body_result.update_empty(last_value);
  549. // c. If stmtResult.[[Value]] is not empty, set V to stmtResult.[[Value]].
  550. if (body_result.value().has_value())
  551. last_value = *body_result.value();
  552. // d. Let exprRef be the result of evaluating Expression.
  553. // e. Let exprValue be ? GetValue(exprRef).
  554. auto test_result = TRY(m_test->execute(interpreter, global_object)).release_value();
  555. // f. If ! ToBoolean(exprValue) is false, return NormalCompletion(V).
  556. if (!test_result.to_boolean())
  557. return normal_completion(last_value);
  558. }
  559. VERIFY_NOT_REACHED();
  560. }
  561. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  562. // BreakableStatement : IterationStatement
  563. Completion ForStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  564. {
  565. // 1. Let newLabelSet be a new empty List.
  566. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  567. return labelled_evaluation(interpreter, global_object, *this, {});
  568. }
  569. // 14.7.4.2 Runtime Semantics: ForLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forloopevaluation
  570. Completion ForStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  571. {
  572. InterpreterNodeScope node_scope { interpreter, *this };
  573. // Note we don't always set a new environment but to use RAII we must do this here.
  574. auto* old_environment = interpreter.lexical_environment();
  575. ScopeGuard restore_old_environment = [&] {
  576. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  577. };
  578. size_t per_iteration_bindings_size = 0;
  579. if (m_init) {
  580. if (is<VariableDeclaration>(*m_init) && static_cast<VariableDeclaration const&>(*m_init).declaration_kind() != DeclarationKind::Var) {
  581. auto* loop_environment = new_declarative_environment(*old_environment);
  582. auto& declaration = static_cast<VariableDeclaration const&>(*m_init);
  583. declaration.for_each_bound_name([&](auto const& name) {
  584. if (declaration.declaration_kind() == DeclarationKind::Const) {
  585. MUST(loop_environment->create_immutable_binding(global_object, name, true));
  586. } else {
  587. MUST(loop_environment->create_mutable_binding(global_object, name, false));
  588. ++per_iteration_bindings_size;
  589. }
  590. });
  591. interpreter.vm().running_execution_context().lexical_environment = loop_environment;
  592. }
  593. (void)TRY(m_init->execute(interpreter, global_object));
  594. }
  595. // 14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings ), https://tc39.es/ecma262/#sec-createperiterationenvironment
  596. // NOTE: Our implementation of this AO is heavily dependent on DeclarativeEnvironment using a Vector with constant indices.
  597. // For performance, we can take advantage of the fact that the declarations of the initialization statement are created
  598. // in the same order each time CreatePerIterationEnvironment is invoked.
  599. auto create_per_iteration_environment = [&]() {
  600. // 1. If perIterationBindings has any elements, then
  601. if (per_iteration_bindings_size == 0)
  602. return;
  603. // a. Let lastIterationEnv be the running execution context's LexicalEnvironment.
  604. auto* last_iteration_env = verify_cast<DeclarativeEnvironment>(interpreter.lexical_environment());
  605. // b. Let outer be lastIterationEnv.[[OuterEnv]].
  606. // c. Assert: outer is not null.
  607. VERIFY(last_iteration_env->outer_environment());
  608. // d. Let thisIterationEnv be NewDeclarativeEnvironment(outer).
  609. auto this_iteration_env = DeclarativeEnvironment::create_for_per_iteration_bindings({}, *last_iteration_env, per_iteration_bindings_size);
  610. // e. For each element bn of perIterationBindings, do
  611. // i. Perform ! thisIterationEnv.CreateMutableBinding(bn, false).
  612. // ii. Let lastValue be ? lastIterationEnv.GetBindingValue(bn, true).
  613. // iii. Perform ! thisIterationEnv.InitializeBinding(bn, lastValue).
  614. //
  615. // NOTE: This is handled by DeclarativeEnvironment::create_for_per_iteration_bindings. Step e.ii indicates it may throw,
  616. // but that is not possible. The potential for throwing was added to accommodate support for do-expressions in the
  617. // initialization statement, but that idea was dropped: https://github.com/tc39/ecma262/issues/299#issuecomment-172950045
  618. // f. Set the running execution context's LexicalEnvironment to thisIterationEnv.
  619. interpreter.vm().running_execution_context().lexical_environment = this_iteration_env;
  620. // 2. Return undefined.
  621. };
  622. // 14.7.4.3 ForBodyEvaluation ( test, increment, stmt, perIterationBindings, labelSet ), https://tc39.es/ecma262/#sec-forbodyevaluation
  623. // 1. Let V be undefined.
  624. auto last_value = js_undefined();
  625. // 2. Perform ? CreatePerIterationEnvironment(perIterationBindings).
  626. create_per_iteration_environment();
  627. // 3. Repeat,
  628. while (true) {
  629. // a. If test is not [empty], then
  630. if (m_test) {
  631. // i. Let testRef be the result of evaluating test.
  632. // ii. Let testValue be ? GetValue(testRef).
  633. auto test_value = TRY(m_test->execute(interpreter, global_object)).release_value();
  634. // iii. If ! ToBoolean(testValue) is false, return NormalCompletion(V).
  635. if (!test_value.to_boolean())
  636. return normal_completion(last_value);
  637. }
  638. // b. Let result be the result of evaluating stmt.
  639. auto result = m_body->execute(interpreter, global_object);
  640. // c. If LoopContinues(result, labelSet) is false, return Completion(UpdateEmpty(result, V)).
  641. if (!loop_continues(result, label_set))
  642. return result.update_empty(last_value);
  643. // d. If result.[[Value]] is not empty, set V to result.[[Value]].
  644. if (result.value().has_value())
  645. last_value = *result.value();
  646. // e. Perform ? CreatePerIterationEnvironment(perIterationBindings).
  647. create_per_iteration_environment();
  648. // f. If increment is not [empty], then
  649. if (m_update) {
  650. // i. Let incRef be the result of evaluating increment.
  651. // ii. Perform ? GetValue(incRef).
  652. (void)TRY(m_update->execute(interpreter, global_object));
  653. }
  654. }
  655. VERIFY_NOT_REACHED();
  656. }
  657. struct ForInOfHeadState {
  658. explicit ForInOfHeadState(Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> lhs)
  659. {
  660. lhs.visit(
  661. [&](NonnullRefPtr<ASTNode>& ast_node) {
  662. expression_lhs = ast_node.ptr();
  663. },
  664. [&](NonnullRefPtr<BindingPattern>& pattern) {
  665. pattern_lhs = pattern.ptr();
  666. destructuring = true;
  667. lhs_kind = Assignment;
  668. });
  669. }
  670. ASTNode* expression_lhs = nullptr;
  671. BindingPattern* pattern_lhs = nullptr;
  672. enum LhsKind {
  673. Assignment,
  674. VarBinding,
  675. LexicalBinding
  676. };
  677. LhsKind lhs_kind = Assignment;
  678. bool destructuring = false;
  679. Value rhs_value;
  680. // 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
  681. // Note: This is only steps 6.g through 6.j of the method because we currently implement for-in without an iterator so to prevent duplicated code we do this part here.
  682. ThrowCompletionOr<void> execute_head(Interpreter& interpreter, GlobalObject& global_object, Value next_value) const
  683. {
  684. VERIFY(!next_value.is_empty());
  685. Optional<Reference> lhs_reference;
  686. Environment* iteration_environment = nullptr;
  687. // g. If lhsKind is either assignment or varBinding, then
  688. if (lhs_kind == Assignment || lhs_kind == VarBinding) {
  689. if (!destructuring) {
  690. VERIFY(expression_lhs);
  691. if (is<VariableDeclaration>(*expression_lhs)) {
  692. auto& declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  693. VERIFY(declaration.declarations().first().target().has<NonnullRefPtr<Identifier>>());
  694. lhs_reference = TRY(declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->to_reference(interpreter, global_object));
  695. } else {
  696. VERIFY(is<Identifier>(*expression_lhs) || is<MemberExpression>(*expression_lhs) || is<CallExpression>(*expression_lhs));
  697. auto& expression = static_cast<Expression const&>(*expression_lhs);
  698. lhs_reference = TRY(expression.to_reference(interpreter, global_object));
  699. }
  700. }
  701. }
  702. // h. Else,
  703. else {
  704. VERIFY(expression_lhs && is<VariableDeclaration>(*expression_lhs));
  705. iteration_environment = new_declarative_environment(*interpreter.lexical_environment());
  706. auto& for_declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  707. for_declaration.for_each_bound_name([&](auto const& name) {
  708. if (for_declaration.declaration_kind() == DeclarationKind::Const)
  709. MUST(iteration_environment->create_immutable_binding(global_object, name, false));
  710. else
  711. MUST(iteration_environment->create_mutable_binding(global_object, name, true));
  712. });
  713. interpreter.vm().running_execution_context().lexical_environment = iteration_environment;
  714. if (!destructuring) {
  715. VERIFY(for_declaration.declarations().first().target().has<NonnullRefPtr<Identifier>>());
  716. lhs_reference = MUST(interpreter.vm().resolve_binding(for_declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->string()));
  717. }
  718. }
  719. // i. If destructuring is false, then
  720. if (!destructuring) {
  721. VERIFY(lhs_reference.has_value());
  722. if (lhs_kind == LexicalBinding)
  723. return lhs_reference->initialize_referenced_binding(global_object, next_value);
  724. else
  725. return lhs_reference->put_value(global_object, next_value);
  726. }
  727. // j. Else,
  728. if (lhs_kind == Assignment) {
  729. VERIFY(pattern_lhs);
  730. return interpreter.vm().destructuring_assignment_evaluation(*pattern_lhs, next_value, global_object);
  731. }
  732. VERIFY(expression_lhs && is<VariableDeclaration>(*expression_lhs));
  733. auto& for_declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  734. auto& binding_pattern = for_declaration.declarations().first().target().get<NonnullRefPtr<BindingPattern>>();
  735. VERIFY(lhs_kind == VarBinding || iteration_environment);
  736. // At this point iteration_environment is undefined if lhs_kind == VarBinding which means this does both
  737. // branch j.ii and j.iii because ForBindingInitialization is just a forwarding call to BindingInitialization.
  738. return interpreter.vm().binding_initialization(binding_pattern, next_value, iteration_environment, global_object);
  739. }
  740. };
  741. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  742. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  743. // This method combines ForInOfLoopEvaluation and ForIn/OfHeadEvaluation for similar reason as ForIn/OfBodyEvaluation, to prevent code duplication.
  744. // For the same reason we also skip step 6 and 7 of ForIn/OfHeadEvaluation as this is done by the appropriate for loop type.
  745. static ThrowCompletionOr<ForInOfHeadState> for_in_of_head_execute(Interpreter& interpreter, GlobalObject& global_object, Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> lhs, Expression const& rhs)
  746. {
  747. ForInOfHeadState state(lhs);
  748. if (auto* ast_ptr = lhs.get_pointer<NonnullRefPtr<ASTNode>>(); ast_ptr && is<VariableDeclaration>(*(*ast_ptr))) {
  749. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  750. // ForInOfStatement : for ( var ForBinding in Expression ) Statement
  751. // ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  752. // ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  753. // ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  754. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  755. Environment* new_environment = nullptr;
  756. auto& variable_declaration = static_cast<VariableDeclaration const&>(*(*ast_ptr));
  757. VERIFY(variable_declaration.declarations().size() == 1);
  758. state.destructuring = variable_declaration.declarations().first().target().has<NonnullRefPtr<BindingPattern>>();
  759. if (variable_declaration.declaration_kind() == DeclarationKind::Var) {
  760. state.lhs_kind = ForInOfHeadState::VarBinding;
  761. auto& variable = variable_declaration.declarations().first();
  762. // B.3.5 Initializers in ForIn Statement Heads, https://tc39.es/ecma262/#sec-initializers-in-forin-statement-heads
  763. if (variable.init()) {
  764. VERIFY(variable.target().has<NonnullRefPtr<Identifier>>());
  765. auto& binding_id = variable.target().get<NonnullRefPtr<Identifier>>()->string();
  766. auto reference = TRY(interpreter.vm().resolve_binding(binding_id));
  767. auto result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, *variable.init(), binding_id));
  768. TRY(reference.put_value(global_object, result));
  769. }
  770. } else {
  771. state.lhs_kind = ForInOfHeadState::LexicalBinding;
  772. new_environment = new_declarative_environment(*interpreter.lexical_environment());
  773. variable_declaration.for_each_bound_name([&](auto const& name) {
  774. MUST(new_environment->create_mutable_binding(global_object, name, false));
  775. });
  776. }
  777. if (new_environment) {
  778. // 2.d Set the running execution context's LexicalEnvironment to newEnv.
  779. TemporaryChange<Environment*> scope_change(interpreter.vm().running_execution_context().lexical_environment, new_environment);
  780. // 3. Let exprRef be the result of evaluating expr.
  781. // 5. Let exprValue be ? GetValue(exprRef).
  782. state.rhs_value = TRY(rhs.execute(interpreter, global_object)).release_value();
  783. // Note that since a reference stores its environment it doesn't matter we only reset
  784. // this after step 5. (Also we have no way of separating these steps at this point)
  785. // 4. Set the running execution context's LexicalEnvironment to oldEnv.
  786. } else {
  787. // 3. Let exprRef be the result of evaluating expr.
  788. // 5. Let exprValue be ? GetValue(exprRef).
  789. state.rhs_value = TRY(rhs.execute(interpreter, global_object)).release_value();
  790. }
  791. return state;
  792. }
  793. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  794. // ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  795. // ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  796. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  797. // We can skip step 1, 2 and 4 here (on top of already skipping step 6 and 7).
  798. // 3. Let exprRef be the result of evaluating expr.
  799. // 5. Let exprValue be ? GetValue(exprRef).
  800. state.rhs_value = TRY(rhs.execute(interpreter, global_object)).release_value();
  801. return state;
  802. }
  803. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  804. // BreakableStatement : IterationStatement
  805. Completion ForInStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  806. {
  807. // 1. Let newLabelSet be a new empty List.
  808. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  809. return labelled_evaluation(interpreter, global_object, *this, {});
  810. }
  811. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  812. Completion ForInStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  813. {
  814. InterpreterNodeScope node_scope { interpreter, *this };
  815. auto for_in_head_state = TRY(for_in_of_head_execute(interpreter, global_object, m_lhs, *m_rhs));
  816. auto rhs_result = for_in_head_state.rhs_value;
  817. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  818. // a. If exprValue is undefined or null, then
  819. if (rhs_result.is_nullish()) {
  820. // i. Return Completion { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  821. return { Completion::Type::Break, {}, {} };
  822. }
  823. // b. Let obj be ! ToObject(exprValue).
  824. auto* object = MUST(rhs_result.to_object(global_object));
  825. // 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
  826. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  827. Environment* old_environment = interpreter.lexical_environment();
  828. auto restore_scope = ScopeGuard([&] {
  829. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  830. });
  831. // 3. Let V be undefined.
  832. auto last_value = js_undefined();
  833. while (object) {
  834. auto property_names = TRY(object->enumerable_own_property_names(Object::PropertyKind::Key));
  835. for (auto& value : property_names) {
  836. TRY(for_in_head_state.execute_head(interpreter, global_object, value));
  837. // l. Let result be the result of evaluating stmt.
  838. auto result = m_body->execute(interpreter, global_object);
  839. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  840. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  841. // n. If LoopContinues(result, labelSet) is false, then
  842. if (!loop_continues(result, label_set)) {
  843. // 1. Return Completion(UpdateEmpty(result, V)).
  844. return result.update_empty(last_value);
  845. }
  846. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  847. if (result.value().has_value())
  848. last_value = *result.value();
  849. }
  850. object = TRY(object->internal_get_prototype_of());
  851. }
  852. return last_value;
  853. }
  854. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  855. // BreakableStatement : IterationStatement
  856. Completion ForOfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  857. {
  858. // 1. Let newLabelSet be a new empty List.
  859. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  860. return labelled_evaluation(interpreter, global_object, *this, {});
  861. }
  862. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  863. Completion ForOfStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  864. {
  865. InterpreterNodeScope node_scope { interpreter, *this };
  866. auto for_of_head_state = TRY(for_in_of_head_execute(interpreter, global_object, m_lhs, m_rhs));
  867. auto rhs_result = for_of_head_state.rhs_value;
  868. // 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
  869. // We use get_iterator_values which behaves like ForIn/OfBodyEvaluation with iteratorKind iterate.
  870. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  871. Environment* old_environment = interpreter.lexical_environment();
  872. auto restore_scope = ScopeGuard([&] {
  873. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  874. });
  875. // 3. Let V be undefined.
  876. auto last_value = js_undefined();
  877. Optional<Completion> status;
  878. (void)TRY(get_iterator_values(global_object, rhs_result, [&](Value value) -> Optional<Completion> {
  879. TRY(for_of_head_state.execute_head(interpreter, global_object, value));
  880. // l. Let result be the result of evaluating stmt.
  881. auto result = m_body->execute(interpreter, global_object);
  882. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  883. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  884. // n. If LoopContinues(result, labelSet) is false, then
  885. if (!loop_continues(result, label_set)) {
  886. // 2. Set status to UpdateEmpty(result, V).
  887. status = result.update_empty(last_value);
  888. // 4. Return ? IteratorClose(iteratorRecord, status).
  889. // NOTE: This is done by returning a completion from the callback.
  890. return status;
  891. }
  892. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  893. if (result.value().has_value())
  894. last_value = *result.value();
  895. return {};
  896. }));
  897. // Return `status` set during step n.2. in the callback, or...
  898. // e. If done is true, return NormalCompletion(V).
  899. return status.value_or(normal_completion(last_value));
  900. }
  901. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  902. // BreakableStatement : IterationStatement
  903. Completion ForAwaitOfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  904. {
  905. // 1. Let newLabelSet be a new empty List.
  906. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  907. return labelled_evaluation(interpreter, global_object, *this, {});
  908. }
  909. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  910. Completion ForAwaitOfStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  911. {
  912. InterpreterNodeScope node_scope { interpreter, *this };
  913. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  914. // Note: Performs only steps 1 through 5.
  915. auto for_of_head_state = TRY(for_in_of_head_execute(interpreter, global_object, m_lhs, m_rhs));
  916. auto rhs_result = for_of_head_state.rhs_value;
  917. // NOTE: Perform step 7 from ForIn/OfHeadEvaluation. And since this is always async we only have to do step 7.d.
  918. // d. Return ? GetIterator(exprValue, iteratorHint).
  919. auto iterator = TRY(get_iterator(global_object, rhs_result, IteratorHint::Async));
  920. auto& vm = interpreter.vm();
  921. // 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
  922. // NOTE: Here iteratorKind is always async.
  923. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  924. Environment* old_environment = interpreter.lexical_environment();
  925. auto restore_scope = ScopeGuard([&] {
  926. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  927. });
  928. // 3. Let V be undefined.
  929. auto last_value = js_undefined();
  930. // NOTE: Step 4 and 5 are just extracting properties from the head which is done already in for_in_of_head_execute.
  931. // And these are only used in step 6.g through 6.k which is done with for_of_head_state.execute_head.
  932. // 6. Repeat,
  933. while (true) {
  934. // a. Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
  935. auto next_result = TRY(call(global_object, iterator.next_method, iterator.iterator));
  936. // b. If iteratorKind is async, set nextResult to ? Await(nextResult).
  937. next_result = TRY(await(global_object, next_result));
  938. // c. If Type(nextResult) is not Object, throw a TypeError exception.
  939. if (!next_result.is_object())
  940. return vm.throw_completion<TypeError>(global_object, ErrorType::IterableNextBadReturn);
  941. // d. Let done be ? IteratorComplete(nextResult).
  942. auto done = TRY(iterator_complete(global_object, next_result.as_object()));
  943. // e. If done is true, return NormalCompletion(V).
  944. if (done)
  945. return last_value;
  946. // f. Let nextValue be ? IteratorValue(nextResult).
  947. auto next_value = TRY(iterator_value(global_object, next_result.as_object()));
  948. // NOTE: This performs steps g. through to k.
  949. TRY(for_of_head_state.execute_head(interpreter, global_object, next_value));
  950. // l. Let result be the result of evaluating stmt.
  951. auto result = m_body->execute(interpreter, global_object);
  952. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  953. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  954. // n. If LoopContinues(result, labelSet) is false, then
  955. if (!loop_continues(result, label_set)) {
  956. // 2. Set status to UpdateEmpty(result, V).
  957. auto status = result.update_empty(last_value);
  958. // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  959. return async_iterator_close(global_object, iterator, move(status));
  960. }
  961. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  962. if (result.value().has_value())
  963. last_value = *result.value();
  964. }
  965. VERIFY_NOT_REACHED();
  966. }
  967. // 13.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-exp-operator-runtime-semantics-evaluation
  968. // 13.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-multiplicative-operators-runtime-semantics-evaluation
  969. // 13.8.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-addition-operator-plus-runtime-semantics-evaluation
  970. // 13.8.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-subtraction-operator-minus-runtime-semantics-evaluation
  971. // 13.9.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-left-shift-operator-runtime-semantics-evaluation
  972. // 13.9.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-signed-right-shift-operator-runtime-semantics-evaluation
  973. // 13.9.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unsigned-right-shift-operator-runtime-semantics-evaluation
  974. // 13.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-relational-operators-runtime-semantics-evaluation
  975. // 13.11.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-equality-operators-runtime-semantics-evaluation
  976. Completion BinaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  977. {
  978. InterpreterNodeScope node_scope { interpreter, *this };
  979. // Special case in which we cannot execute the lhs. RelationalExpression : PrivateIdentifier in ShiftExpression
  980. // RelationalExpression : PrivateIdentifier in ShiftExpression, https://tc39.es/ecma262/#sec-relational-operators-runtime-semantics-evaluation
  981. if (m_op == BinaryOp::In && is<PrivateIdentifier>(*m_lhs)) {
  982. auto& private_identifier = static_cast<PrivateIdentifier const&>(*m_lhs).string();
  983. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  984. if (!rhs_result.is_object())
  985. return interpreter.vm().throw_completion<TypeError>(global_object, ErrorType::InOperatorWithObject);
  986. auto* private_environment = interpreter.vm().running_execution_context().private_environment;
  987. VERIFY(private_environment);
  988. auto private_name = private_environment->resolve_private_identifier(private_identifier);
  989. return Value(rhs_result.as_object().private_element_find(private_name) != nullptr);
  990. }
  991. auto lhs_result = TRY(m_lhs->execute(interpreter, global_object)).release_value();
  992. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  993. switch (m_op) {
  994. case BinaryOp::Addition:
  995. return TRY(add(global_object, lhs_result, rhs_result));
  996. case BinaryOp::Subtraction:
  997. return TRY(sub(global_object, lhs_result, rhs_result));
  998. case BinaryOp::Multiplication:
  999. return TRY(mul(global_object, lhs_result, rhs_result));
  1000. case BinaryOp::Division:
  1001. return TRY(div(global_object, lhs_result, rhs_result));
  1002. case BinaryOp::Modulo:
  1003. return TRY(mod(global_object, lhs_result, rhs_result));
  1004. case BinaryOp::Exponentiation:
  1005. return TRY(exp(global_object, lhs_result, rhs_result));
  1006. case BinaryOp::StrictlyEquals:
  1007. return Value(is_strictly_equal(lhs_result, rhs_result));
  1008. case BinaryOp::StrictlyInequals:
  1009. return Value(!is_strictly_equal(lhs_result, rhs_result));
  1010. case BinaryOp::LooselyEquals:
  1011. return Value(TRY(is_loosely_equal(global_object, lhs_result, rhs_result)));
  1012. case BinaryOp::LooselyInequals:
  1013. return Value(!TRY(is_loosely_equal(global_object, lhs_result, rhs_result)));
  1014. case BinaryOp::GreaterThan:
  1015. return TRY(greater_than(global_object, lhs_result, rhs_result));
  1016. case BinaryOp::GreaterThanEquals:
  1017. return TRY(greater_than_equals(global_object, lhs_result, rhs_result));
  1018. case BinaryOp::LessThan:
  1019. return TRY(less_than(global_object, lhs_result, rhs_result));
  1020. case BinaryOp::LessThanEquals:
  1021. return TRY(less_than_equals(global_object, lhs_result, rhs_result));
  1022. case BinaryOp::BitwiseAnd:
  1023. return TRY(bitwise_and(global_object, lhs_result, rhs_result));
  1024. case BinaryOp::BitwiseOr:
  1025. return TRY(bitwise_or(global_object, lhs_result, rhs_result));
  1026. case BinaryOp::BitwiseXor:
  1027. return TRY(bitwise_xor(global_object, lhs_result, rhs_result));
  1028. case BinaryOp::LeftShift:
  1029. return TRY(left_shift(global_object, lhs_result, rhs_result));
  1030. case BinaryOp::RightShift:
  1031. return TRY(right_shift(global_object, lhs_result, rhs_result));
  1032. case BinaryOp::UnsignedRightShift:
  1033. return TRY(unsigned_right_shift(global_object, lhs_result, rhs_result));
  1034. case BinaryOp::In:
  1035. return TRY(in(global_object, lhs_result, rhs_result));
  1036. case BinaryOp::InstanceOf:
  1037. return TRY(instance_of(global_object, lhs_result, rhs_result));
  1038. }
  1039. VERIFY_NOT_REACHED();
  1040. }
  1041. // 13.13.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-binary-logical-operators-runtime-semantics-evaluation
  1042. Completion LogicalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1043. {
  1044. InterpreterNodeScope node_scope { interpreter, *this };
  1045. // 1. Let lref be the result of evaluating <Expression>.
  1046. // 2. Let lval be ? GetValue(lref).
  1047. auto lhs_result = TRY(m_lhs->execute(interpreter, global_object)).release_value();
  1048. switch (m_op) {
  1049. // LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1050. case LogicalOp::And:
  1051. // 3. Let lbool be ! ToBoolean(lval).
  1052. // 4. If lbool is false, return lval.
  1053. if (!lhs_result.to_boolean())
  1054. return lhs_result;
  1055. // 5. Let rref be the result of evaluating BitwiseORExpression.
  1056. // 6. Return ? GetValue(rref).
  1057. return m_rhs->execute(interpreter, global_object);
  1058. // LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1059. case LogicalOp::Or:
  1060. // 3. Let lbool be ! ToBoolean(lval).
  1061. // 4. If lbool is true, return lval.
  1062. if (lhs_result.to_boolean())
  1063. return lhs_result;
  1064. // 5. Let rref be the result of evaluating LogicalANDExpression.
  1065. // 6. Return ? GetValue(rref).
  1066. return m_rhs->execute(interpreter, global_object);
  1067. // CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1068. case LogicalOp::NullishCoalescing:
  1069. // 3. If lval is undefined or null, then
  1070. if (lhs_result.is_nullish()) {
  1071. // a. Let rref be the result of evaluating BitwiseORExpression.
  1072. // b. Return ? GetValue(rref).
  1073. return m_rhs->execute(interpreter, global_object);
  1074. }
  1075. // 4. Otherwise, return lval.
  1076. return lhs_result;
  1077. }
  1078. VERIFY_NOT_REACHED();
  1079. }
  1080. ThrowCompletionOr<Reference> Expression::to_reference(Interpreter&, GlobalObject&) const
  1081. {
  1082. return Reference {};
  1083. }
  1084. ThrowCompletionOr<Reference> Identifier::to_reference(Interpreter& interpreter, GlobalObject&) const
  1085. {
  1086. if (m_cached_environment_coordinate.has_value()) {
  1087. auto* environment = interpreter.vm().running_execution_context().lexical_environment;
  1088. for (size_t i = 0; i < m_cached_environment_coordinate->hops; ++i)
  1089. environment = environment->outer_environment();
  1090. VERIFY(environment);
  1091. VERIFY(environment->is_declarative_environment());
  1092. if (!environment->is_permanently_screwed_by_eval()) {
  1093. return Reference { *environment, string(), interpreter.vm().in_strict_mode(), m_cached_environment_coordinate };
  1094. }
  1095. m_cached_environment_coordinate = {};
  1096. }
  1097. auto reference = TRY(interpreter.vm().resolve_binding(string()));
  1098. if (reference.environment_coordinate().has_value())
  1099. m_cached_environment_coordinate = reference.environment_coordinate();
  1100. return reference;
  1101. }
  1102. ThrowCompletionOr<Reference> MemberExpression::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  1103. {
  1104. // 13.3.7.1 Runtime Semantics: Evaluation
  1105. // SuperProperty : super [ Expression ]
  1106. // SuperProperty : super . IdentifierName
  1107. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  1108. if (is<SuperExpression>(object())) {
  1109. // 1. Let env be GetThisEnvironment().
  1110. auto& environment = get_this_environment(interpreter.vm());
  1111. // 2. Let actualThis be ? env.GetThisBinding().
  1112. auto actual_this = TRY(environment.get_this_binding(global_object));
  1113. PropertyKey property_key;
  1114. if (is_computed()) {
  1115. // SuperProperty : super [ Expression ]
  1116. // 3. Let propertyNameReference be the result of evaluating Expression.
  1117. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  1118. auto property_name_value = TRY(m_property->execute(interpreter, global_object)).release_value();
  1119. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  1120. property_key = TRY(property_name_value.to_property_key(global_object));
  1121. } else {
  1122. // SuperProperty : super . IdentifierName
  1123. // 3. Let propertyKey be StringValue of IdentifierName.
  1124. VERIFY(is<Identifier>(property()));
  1125. property_key = static_cast<Identifier const&>(property()).string();
  1126. }
  1127. // 6. If the code matched by this SuperProperty is strict mode code, let strict be true; else let strict be false.
  1128. bool strict = interpreter.vm().in_strict_mode();
  1129. // 7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  1130. return TRY(make_super_property_reference(global_object, actual_this, property_key, strict));
  1131. }
  1132. auto base_reference = TRY(m_object->to_reference(interpreter, global_object));
  1133. Value base_value;
  1134. if (base_reference.is_valid_reference())
  1135. base_value = TRY(base_reference.get_value(global_object));
  1136. else
  1137. base_value = TRY(m_object->execute(interpreter, global_object)).release_value();
  1138. VERIFY(!base_value.is_empty());
  1139. // From here on equivalent to
  1140. // 13.3.4 EvaluatePropertyAccessWithIdentifierKey ( baseValue, identifierName, strict ), https://tc39.es/ecma262/#sec-evaluate-property-access-with-identifier-key
  1141. PropertyKey property_key;
  1142. if (is_computed()) {
  1143. // Weird order which I can't quite find from the specs.
  1144. auto value = TRY(m_property->execute(interpreter, global_object)).release_value();
  1145. VERIFY(!value.is_empty());
  1146. TRY(require_object_coercible(global_object, base_value));
  1147. property_key = TRY(PropertyKey::from_value(global_object, value));
  1148. } else if (is<PrivateIdentifier>(*m_property)) {
  1149. auto& private_identifier = static_cast<PrivateIdentifier const&>(*m_property);
  1150. return make_private_reference(interpreter.vm(), base_value, private_identifier.string());
  1151. } else {
  1152. property_key = verify_cast<Identifier>(*m_property).string();
  1153. TRY(require_object_coercible(global_object, base_value));
  1154. }
  1155. if (!property_key.is_valid())
  1156. return Reference {};
  1157. auto strict = interpreter.vm().in_strict_mode();
  1158. return Reference { base_value, move(property_key), {}, strict };
  1159. }
  1160. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  1161. // 13.5.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-void-operator-runtime-semantics-evaluation
  1162. // 13.5.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-typeof-operator-runtime-semantics-evaluation
  1163. // 13.5.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unary-plus-operator-runtime-semantics-evaluation
  1164. // 13.5.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unary-minus-operator-runtime-semantics-evaluation
  1165. // 13.5.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-bitwise-not-operator-runtime-semantics-evaluation
  1166. // 13.5.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-logical-not-operator-runtime-semantics-evaluation
  1167. Completion UnaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1168. {
  1169. InterpreterNodeScope node_scope { interpreter, *this };
  1170. auto& vm = interpreter.vm();
  1171. if (m_op == UnaryOp::Delete) {
  1172. auto reference = TRY(m_lhs->to_reference(interpreter, global_object));
  1173. return Value(TRY(reference.delete_(global_object)));
  1174. }
  1175. Value lhs_result;
  1176. if (m_op == UnaryOp::Typeof && is<Identifier>(*m_lhs)) {
  1177. auto reference = TRY(m_lhs->to_reference(interpreter, global_object));
  1178. if (reference.is_unresolvable())
  1179. lhs_result = js_undefined();
  1180. else
  1181. lhs_result = TRY(reference.get_value(global_object));
  1182. VERIFY(!lhs_result.is_empty());
  1183. } else {
  1184. // 1. Let expr be the result of evaluating UnaryExpression.
  1185. lhs_result = TRY(m_lhs->execute(interpreter, global_object)).release_value();
  1186. }
  1187. switch (m_op) {
  1188. case UnaryOp::BitwiseNot:
  1189. return TRY(bitwise_not(global_object, lhs_result));
  1190. case UnaryOp::Not:
  1191. return Value(!lhs_result.to_boolean());
  1192. case UnaryOp::Plus:
  1193. return TRY(unary_plus(global_object, lhs_result));
  1194. case UnaryOp::Minus:
  1195. return TRY(unary_minus(global_object, lhs_result));
  1196. case UnaryOp::Typeof:
  1197. return Value { js_string(vm, lhs_result.typeof()) };
  1198. case UnaryOp::Void:
  1199. return js_undefined();
  1200. case UnaryOp::Delete:
  1201. VERIFY_NOT_REACHED();
  1202. }
  1203. VERIFY_NOT_REACHED();
  1204. }
  1205. Completion SuperExpression::execute(Interpreter&, GlobalObject&) const
  1206. {
  1207. // The semantics for SuperExpression are handled in CallExpression and SuperCall.
  1208. VERIFY_NOT_REACHED();
  1209. }
  1210. Completion ClassElement::execute(Interpreter&, GlobalObject&) const
  1211. {
  1212. // Note: The semantics of class element are handled in class_element_evaluation
  1213. VERIFY_NOT_REACHED();
  1214. }
  1215. static ThrowCompletionOr<ClassElement::ClassElementName> class_key_to_property_name(Interpreter& interpreter, GlobalObject& global_object, Expression const& key)
  1216. {
  1217. if (is<PrivateIdentifier>(key)) {
  1218. auto& private_identifier = static_cast<PrivateIdentifier const&>(key);
  1219. auto* private_environment = interpreter.vm().running_execution_context().private_environment;
  1220. VERIFY(private_environment);
  1221. return ClassElement::ClassElementName { private_environment->resolve_private_identifier(private_identifier.string()) };
  1222. }
  1223. auto prop_key = TRY(key.execute(interpreter, global_object)).release_value();
  1224. if (prop_key.is_object())
  1225. prop_key = TRY(prop_key.to_primitive(global_object, Value::PreferredType::String));
  1226. auto property_key = TRY(PropertyKey::from_value(global_object, prop_key));
  1227. return ClassElement::ClassElementName { property_key };
  1228. }
  1229. // 15.4.5 Runtime Semantics: MethodDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-methoddefinitionevaluation
  1230. ThrowCompletionOr<ClassElement::ClassValue> ClassMethod::class_element_evaluation(Interpreter& interpreter, GlobalObject& global_object, Object& target) const
  1231. {
  1232. auto property_key_or_private_name = TRY(class_key_to_property_name(interpreter, global_object, *m_key));
  1233. auto method_value = TRY(m_function->execute(interpreter, global_object)).release_value();
  1234. auto function_handle = make_handle(&method_value.as_function());
  1235. auto& method_function = static_cast<ECMAScriptFunctionObject&>(method_value.as_function());
  1236. method_function.make_method(target);
  1237. auto set_function_name = [&](String prefix = "") {
  1238. auto name = property_key_or_private_name.visit(
  1239. [&](PropertyKey const& property_key) -> String {
  1240. if (property_key.is_symbol()) {
  1241. auto description = property_key.as_symbol()->description();
  1242. if (description.is_empty())
  1243. return "";
  1244. return String::formatted("[{}]", description);
  1245. } else {
  1246. return property_key.to_string();
  1247. }
  1248. },
  1249. [&](PrivateName const& private_name) -> String {
  1250. return private_name.description;
  1251. });
  1252. update_function_name(method_value, String::formatted("{}{}{}", prefix, prefix.is_empty() ? "" : " ", name));
  1253. };
  1254. if (property_key_or_private_name.has<PropertyKey>()) {
  1255. auto& property_key = property_key_or_private_name.get<PropertyKey>();
  1256. switch (kind()) {
  1257. case ClassMethod::Kind::Method:
  1258. set_function_name();
  1259. TRY(target.define_property_or_throw(property_key, { .value = method_value, .writable = true, .enumerable = false, .configurable = true }));
  1260. break;
  1261. case ClassMethod::Kind::Getter:
  1262. set_function_name("get");
  1263. TRY(target.define_property_or_throw(property_key, { .get = &method_function, .enumerable = true, .configurable = true }));
  1264. break;
  1265. case ClassMethod::Kind::Setter:
  1266. set_function_name("set");
  1267. TRY(target.define_property_or_throw(property_key, { .set = &method_function, .enumerable = true, .configurable = true }));
  1268. break;
  1269. default:
  1270. VERIFY_NOT_REACHED();
  1271. }
  1272. return ClassValue { normal_completion({}) };
  1273. } else {
  1274. auto& private_name = property_key_or_private_name.get<PrivateName>();
  1275. switch (kind()) {
  1276. case Kind::Method:
  1277. set_function_name();
  1278. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Method, method_value } };
  1279. case Kind::Getter:
  1280. set_function_name("get");
  1281. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Accessor, Accessor::create(interpreter.vm(), &method_function, nullptr) } };
  1282. case Kind::Setter:
  1283. set_function_name("set");
  1284. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Accessor, Accessor::create(interpreter.vm(), nullptr, &method_function) } };
  1285. default:
  1286. VERIFY_NOT_REACHED();
  1287. }
  1288. }
  1289. }
  1290. // We use this class to mimic Initializer : = AssignmentExpression of
  1291. // 10.2.1.3 Runtime Semantics: EvaluateBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody
  1292. class ClassFieldInitializerStatement : public Statement {
  1293. public:
  1294. ClassFieldInitializerStatement(SourceRange source_range, NonnullRefPtr<Expression> expression, FlyString field_name)
  1295. : Statement(source_range)
  1296. , m_expression(move(expression))
  1297. , m_class_field_identifier_name(move(field_name))
  1298. {
  1299. }
  1300. Completion execute(Interpreter& interpreter, GlobalObject& global_object) const override
  1301. {
  1302. // 1. Assert: argumentsList is empty.
  1303. VERIFY(interpreter.vm().argument_count() == 0);
  1304. // 2. Assert: functionObject.[[ClassFieldInitializerName]] is not empty.
  1305. VERIFY(!m_class_field_identifier_name.is_empty());
  1306. // 3. If IsAnonymousFunctionDefinition(AssignmentExpression) is true, then
  1307. // a. Let value be NamedEvaluation of Initializer with argument functionObject.[[ClassFieldInitializerName]].
  1308. // 4. Else,
  1309. // a. Let rhs be the result of evaluating AssignmentExpression.
  1310. // b. Let value be ? GetValue(rhs).
  1311. auto value = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_expression, m_class_field_identifier_name));
  1312. // 5. Return Completion { [[Type]]: return, [[Value]]: value, [[Target]]: empty }.
  1313. return { Completion::Type::Return, value, {} };
  1314. }
  1315. void dump(int) const override
  1316. {
  1317. // This should not be dumped as it is never part of an actual AST.
  1318. VERIFY_NOT_REACHED();
  1319. }
  1320. private:
  1321. NonnullRefPtr<Expression> m_expression;
  1322. FlyString m_class_field_identifier_name; // [[ClassFieldIdentifierName]]
  1323. };
  1324. // 15.7.10 Runtime Semantics: ClassFieldDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classfielddefinitionevaluation
  1325. ThrowCompletionOr<ClassElement::ClassValue> ClassField::class_element_evaluation(Interpreter& interpreter, GlobalObject& global_object, Object& target) const
  1326. {
  1327. auto property_key_or_private_name = TRY(class_key_to_property_name(interpreter, global_object, *m_key));
  1328. Handle<ECMAScriptFunctionObject> initializer {};
  1329. if (m_initializer) {
  1330. auto copy_initializer = m_initializer;
  1331. auto name = property_key_or_private_name.visit(
  1332. [&](PropertyKey const& property_key) -> String {
  1333. return property_key.is_number() ? property_key.to_string() : property_key.to_string_or_symbol().to_display_string();
  1334. },
  1335. [&](PrivateName const& private_name) -> String {
  1336. return private_name.description;
  1337. });
  1338. // FIXME: A potential optimization is not creating the functions here since these are never directly accessible.
  1339. auto function_code = create_ast_node<ClassFieldInitializerStatement>(m_initializer->source_range(), copy_initializer.release_nonnull(), name);
  1340. initializer = make_handle(ECMAScriptFunctionObject::create(interpreter.global_object(), String::empty(), String::empty(), *function_code, {}, 0, interpreter.lexical_environment(), interpreter.vm().running_execution_context().private_environment, FunctionKind::Normal, true, false, m_contains_direct_call_to_eval, false));
  1341. initializer->make_method(target);
  1342. }
  1343. return ClassValue {
  1344. ClassFieldDefinition {
  1345. move(property_key_or_private_name),
  1346. move(initializer),
  1347. }
  1348. };
  1349. }
  1350. static Optional<FlyString> nullopt_or_private_identifier_description(Expression const& expression)
  1351. {
  1352. if (is<PrivateIdentifier>(expression))
  1353. return static_cast<PrivateIdentifier const&>(expression).string();
  1354. return {};
  1355. }
  1356. Optional<FlyString> ClassField::private_bound_identifier() const
  1357. {
  1358. return nullopt_or_private_identifier_description(*m_key);
  1359. }
  1360. Optional<FlyString> ClassMethod::private_bound_identifier() const
  1361. {
  1362. return nullopt_or_private_identifier_description(*m_key);
  1363. }
  1364. // 15.7.11 Runtime Semantics: ClassStaticBlockDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classstaticblockdefinitionevaluation
  1365. ThrowCompletionOr<ClassElement::ClassValue> StaticInitializer::class_element_evaluation(Interpreter& interpreter, GlobalObject& global_object, Object& home_object) const
  1366. {
  1367. // 1. Let lex be the running execution context's LexicalEnvironment.
  1368. auto* lexical_environment = interpreter.vm().running_execution_context().lexical_environment;
  1369. // 2. Let privateScope be the running execution context's PrivateEnvironment.
  1370. auto* private_scope = interpreter.vm().running_execution_context().private_environment;
  1371. // 3. Let sourceText be the empty sequence of Unicode code points.
  1372. // 4. Let formalParameters be an instance of the production FormalParameters : [empty] .
  1373. // 5. Let bodyFunction be OrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameters, ClassStaticBlockBody, non-lexical-this, lex, privateScope).
  1374. // Note: The function bodyFunction is never directly accessible to ECMAScript code.
  1375. auto* body_function = ECMAScriptFunctionObject::create(global_object, String::empty(), String::empty(), *m_function_body, {}, 0, lexical_environment, private_scope, FunctionKind::Normal, true, false, m_contains_direct_call_to_eval, false);
  1376. // 6. Perform MakeMethod(bodyFunction, homeObject).
  1377. body_function->make_method(home_object);
  1378. // 7. Return the ClassStaticBlockDefinition Record { [[BodyFunction]]: bodyFunction }.
  1379. return ClassValue { normal_completion(body_function) };
  1380. }
  1381. // 15.7.16 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-class-definitions-runtime-semantics-evaluation
  1382. // ClassExpression : class BindingIdentifier ClassTail
  1383. Completion ClassExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1384. {
  1385. InterpreterNodeScope node_scope { interpreter, *this };
  1386. // 1. Let className be StringValue of BindingIdentifier.
  1387. // 2. Let value be ? ClassDefinitionEvaluation of ClassTail with arguments className and className.
  1388. auto* value = TRY(class_definition_evaluation(interpreter, global_object, m_name, m_name.is_null() ? "" : m_name));
  1389. // 3. Set value.[[SourceText]] to the source text matched by ClassExpression.
  1390. value->set_source_text(m_source_text);
  1391. // 4. Return value.
  1392. return Value { value };
  1393. }
  1394. // 15.7.15 Runtime Semantics: BindingClassDeclarationEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-bindingclassdeclarationevaluation
  1395. static ThrowCompletionOr<Value> binding_class_declaration_evaluation(Interpreter& interpreter, GlobalObject& global_object, ClassExpression const& class_expression)
  1396. {
  1397. // ClassDeclaration : class ClassTail
  1398. if (!class_expression.has_name()) {
  1399. // 1. Let value be ? ClassDefinitionEvaluation of ClassTail with arguments undefined and "default".
  1400. auto value = TRY(class_expression.class_definition_evaluation(interpreter, global_object, {}, "default"));
  1401. // 2. Set value.[[SourceText]] to the source text matched by ClassDeclaration.
  1402. value->set_source_text(class_expression.source_text());
  1403. // 3. Return value.
  1404. return value;
  1405. }
  1406. // ClassDeclaration : class BindingIdentifier ClassTail
  1407. // 1. Let className be StringValue of BindingIdentifier.
  1408. auto class_name = class_expression.name();
  1409. VERIFY(!class_name.is_empty());
  1410. // 2. Let value be ? ClassDefinitionEvaluation of ClassTail with arguments className and className.
  1411. auto value = TRY(class_expression.class_definition_evaluation(interpreter, global_object, class_name, class_name));
  1412. // 3. Set value.[[SourceText]] to the source text matched by ClassDeclaration.
  1413. value->set_source_text(class_expression.source_text());
  1414. // 4. Let env be the running execution context's LexicalEnvironment.
  1415. auto* env = interpreter.lexical_environment();
  1416. // 5. Perform ? InitializeBoundName(className, value, env).
  1417. TRY(initialize_bound_name(global_object, class_name, value, env));
  1418. // 6. Return value.
  1419. return value;
  1420. }
  1421. // 15.7.16 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-class-definitions-runtime-semantics-evaluation
  1422. // ClassDeclaration : class BindingIdentifier ClassTail
  1423. Completion ClassDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1424. {
  1425. InterpreterNodeScope node_scope { interpreter, *this };
  1426. // 1. Perform ? BindingClassDeclarationEvaluation of this ClassDeclaration.
  1427. (void)TRY(binding_class_declaration_evaluation(interpreter, global_object, m_class_expression));
  1428. // 2. Return NormalCompletion(empty).
  1429. return normal_completion({});
  1430. }
  1431. // 15.7.14 Runtime Semantics: ClassDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classdefinitionevaluation
  1432. ThrowCompletionOr<ECMAScriptFunctionObject*> ClassExpression::class_definition_evaluation(Interpreter& interpreter, GlobalObject& global_object, FlyString const& binding_name, FlyString const& class_name) const
  1433. {
  1434. auto& vm = interpreter.vm();
  1435. auto* environment = vm.lexical_environment();
  1436. VERIFY(environment);
  1437. auto* class_scope = new_declarative_environment(*environment);
  1438. // We might not set the lexical environment but we always want to restore it eventually.
  1439. ArmedScopeGuard restore_environment = [&] {
  1440. vm.running_execution_context().lexical_environment = environment;
  1441. };
  1442. if (!binding_name.is_null())
  1443. MUST(class_scope->create_immutable_binding(global_object, binding_name, true));
  1444. auto* outer_private_environment = vm.running_execution_context().private_environment;
  1445. auto* class_private_environment = new_private_environment(vm, outer_private_environment);
  1446. for (auto const& element : m_elements) {
  1447. auto opt_private_name = element.private_bound_identifier();
  1448. if (opt_private_name.has_value())
  1449. class_private_environment->add_private_name({}, opt_private_name.release_value());
  1450. }
  1451. auto* proto_parent = vm.current_realm()->global_object().object_prototype();
  1452. auto* constructor_parent = vm.current_realm()->global_object().function_prototype();
  1453. if (!m_super_class.is_null()) {
  1454. vm.running_execution_context().lexical_environment = class_scope;
  1455. // Note: Since our execute does evaluation and GetValue in once we must check for a valid reference first
  1456. Value super_class;
  1457. auto reference = TRY(m_super_class->to_reference(interpreter, global_object));
  1458. if (reference.is_valid_reference()) {
  1459. super_class = TRY(reference.get_value(global_object));
  1460. } else {
  1461. super_class = TRY(m_super_class->execute(interpreter, global_object)).release_value();
  1462. }
  1463. vm.running_execution_context().lexical_environment = environment;
  1464. if (super_class.is_null()) {
  1465. proto_parent = nullptr;
  1466. } else if (!super_class.is_constructor()) {
  1467. return vm.throw_completion<TypeError>(global_object, ErrorType::ClassExtendsValueNotAConstructorOrNull, super_class.to_string_without_side_effects());
  1468. } else {
  1469. auto super_class_prototype = TRY(super_class.get(global_object, vm.names.prototype));
  1470. if (!super_class_prototype.is_null() && !super_class_prototype.is_object())
  1471. return vm.throw_completion<TypeError>(global_object, ErrorType::ClassExtendsValueInvalidPrototype, super_class_prototype.to_string_without_side_effects());
  1472. if (super_class_prototype.is_null())
  1473. proto_parent = nullptr;
  1474. else
  1475. proto_parent = &super_class_prototype.as_object();
  1476. constructor_parent = &super_class.as_object();
  1477. }
  1478. }
  1479. auto* prototype = Object::create(global_object, proto_parent);
  1480. VERIFY(prototype);
  1481. vm.running_execution_context().lexical_environment = class_scope;
  1482. vm.running_execution_context().private_environment = class_private_environment;
  1483. ScopeGuard restore_private_environment = [&] {
  1484. vm.running_execution_context().private_environment = outer_private_environment;
  1485. };
  1486. // FIXME: Step 14.a is done in the parser. But maybe it shouldn't?
  1487. auto class_constructor_value = TRY(m_constructor->execute(interpreter, global_object)).release_value();
  1488. update_function_name(class_constructor_value, class_name);
  1489. VERIFY(class_constructor_value.is_function() && is<ECMAScriptFunctionObject>(class_constructor_value.as_function()));
  1490. auto* class_constructor = static_cast<ECMAScriptFunctionObject*>(&class_constructor_value.as_function());
  1491. class_constructor->set_home_object(prototype);
  1492. class_constructor->set_is_class_constructor();
  1493. class_constructor->define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  1494. TRY(class_constructor->internal_set_prototype_of(constructor_parent));
  1495. if (!m_super_class.is_null())
  1496. class_constructor->set_constructor_kind(ECMAScriptFunctionObject::ConstructorKind::Derived);
  1497. prototype->define_direct_property(vm.names.constructor, class_constructor, Attribute::Writable | Attribute::Configurable);
  1498. using StaticElement = Variant<ClassElement::ClassFieldDefinition, Handle<ECMAScriptFunctionObject>>;
  1499. Vector<PrivateElement> static_private_methods;
  1500. Vector<PrivateElement> instance_private_methods;
  1501. Vector<ClassElement::ClassFieldDefinition> instance_fields;
  1502. Vector<StaticElement> static_elements;
  1503. for (auto const& element : m_elements) {
  1504. // Note: All ClassElementEvaluation start with evaluating the name (or we fake it).
  1505. auto element_value = TRY(element.class_element_evaluation(interpreter, global_object, element.is_static() ? *class_constructor : *prototype));
  1506. if (element_value.has<PrivateElement>()) {
  1507. auto& container = element.is_static() ? static_private_methods : instance_private_methods;
  1508. auto& private_element = element_value.get<PrivateElement>();
  1509. auto added_to_existing = false;
  1510. // FIXME: We can skip this loop in most cases.
  1511. for (auto& existing : container) {
  1512. if (existing.key == private_element.key) {
  1513. VERIFY(existing.kind == PrivateElement::Kind::Accessor);
  1514. VERIFY(private_element.kind == PrivateElement::Kind::Accessor);
  1515. auto& accessor = private_element.value.as_accessor();
  1516. if (!accessor.getter())
  1517. existing.value.as_accessor().set_setter(accessor.setter());
  1518. else
  1519. existing.value.as_accessor().set_getter(accessor.getter());
  1520. added_to_existing = true;
  1521. }
  1522. }
  1523. if (!added_to_existing)
  1524. container.append(move(element_value.get<PrivateElement>()));
  1525. } else if (auto* class_field_definition_ptr = element_value.get_pointer<ClassElement::ClassFieldDefinition>()) {
  1526. if (element.is_static())
  1527. static_elements.append(move(*class_field_definition_ptr));
  1528. else
  1529. instance_fields.append(move(*class_field_definition_ptr));
  1530. } else if (element.class_element_kind() == ClassElement::ElementKind::StaticInitializer) {
  1531. // We use Completion to hold the ClassStaticBlockDefinition Record.
  1532. VERIFY(element_value.has<Completion>() && element_value.get<Completion>().value().has_value());
  1533. auto& element_object = element_value.get<Completion>().value()->as_object();
  1534. VERIFY(is<ECMAScriptFunctionObject>(element_object));
  1535. static_elements.append(make_handle(static_cast<ECMAScriptFunctionObject*>(&element_object)));
  1536. }
  1537. }
  1538. vm.running_execution_context().lexical_environment = environment;
  1539. restore_environment.disarm();
  1540. if (!binding_name.is_null())
  1541. MUST(class_scope->initialize_binding(global_object, binding_name, class_constructor));
  1542. for (auto& field : instance_fields)
  1543. class_constructor->add_field(field.name, field.initializer.is_null() ? nullptr : field.initializer.cell());
  1544. for (auto& private_method : instance_private_methods)
  1545. class_constructor->add_private_method(private_method);
  1546. for (auto& method : static_private_methods)
  1547. class_constructor->private_method_or_accessor_add(move(method));
  1548. for (auto& element : static_elements) {
  1549. TRY(element.visit(
  1550. [&](ClassElement::ClassFieldDefinition& field) -> ThrowCompletionOr<void> {
  1551. return TRY(class_constructor->define_field(field.name, field.initializer.is_null() ? nullptr : field.initializer.cell()));
  1552. },
  1553. [&](Handle<ECMAScriptFunctionObject> static_block_function) -> ThrowCompletionOr<void> {
  1554. VERIFY(!static_block_function.is_null());
  1555. // We discard any value returned here.
  1556. TRY(call(global_object, *static_block_function.cell(), class_constructor_value));
  1557. return {};
  1558. }));
  1559. }
  1560. return class_constructor;
  1561. }
  1562. void ASTNode::dump(int indent) const
  1563. {
  1564. print_indent(indent);
  1565. outln("{}", class_name());
  1566. }
  1567. void ScopeNode::dump(int indent) const
  1568. {
  1569. ASTNode::dump(indent);
  1570. if (!m_lexical_declarations.is_empty()) {
  1571. print_indent(indent + 1);
  1572. outln("(Lexical declarations)");
  1573. for (auto& declaration : m_lexical_declarations)
  1574. declaration.dump(indent + 2);
  1575. }
  1576. if (!m_var_declarations.is_empty()) {
  1577. print_indent(indent + 1);
  1578. outln("(Variable declarations)");
  1579. for (auto& declaration : m_var_declarations)
  1580. declaration.dump(indent + 2);
  1581. }
  1582. if (!m_functions_hoistable_with_annexB_extension.is_empty()) {
  1583. print_indent(indent + 1);
  1584. outln("(Hoisted functions via annexB extension)");
  1585. for (auto& declaration : m_functions_hoistable_with_annexB_extension)
  1586. declaration.dump(indent + 2);
  1587. }
  1588. if (!m_children.is_empty()) {
  1589. print_indent(indent + 1);
  1590. outln("(Children)");
  1591. for (auto& child : children())
  1592. child.dump(indent + 2);
  1593. }
  1594. }
  1595. void BinaryExpression::dump(int indent) const
  1596. {
  1597. const char* op_string = nullptr;
  1598. switch (m_op) {
  1599. case BinaryOp::Addition:
  1600. op_string = "+";
  1601. break;
  1602. case BinaryOp::Subtraction:
  1603. op_string = "-";
  1604. break;
  1605. case BinaryOp::Multiplication:
  1606. op_string = "*";
  1607. break;
  1608. case BinaryOp::Division:
  1609. op_string = "/";
  1610. break;
  1611. case BinaryOp::Modulo:
  1612. op_string = "%";
  1613. break;
  1614. case BinaryOp::Exponentiation:
  1615. op_string = "**";
  1616. break;
  1617. case BinaryOp::StrictlyEquals:
  1618. op_string = "===";
  1619. break;
  1620. case BinaryOp::StrictlyInequals:
  1621. op_string = "!==";
  1622. break;
  1623. case BinaryOp::LooselyEquals:
  1624. op_string = "==";
  1625. break;
  1626. case BinaryOp::LooselyInequals:
  1627. op_string = "!=";
  1628. break;
  1629. case BinaryOp::GreaterThan:
  1630. op_string = ">";
  1631. break;
  1632. case BinaryOp::GreaterThanEquals:
  1633. op_string = ">=";
  1634. break;
  1635. case BinaryOp::LessThan:
  1636. op_string = "<";
  1637. break;
  1638. case BinaryOp::LessThanEquals:
  1639. op_string = "<=";
  1640. break;
  1641. case BinaryOp::BitwiseAnd:
  1642. op_string = "&";
  1643. break;
  1644. case BinaryOp::BitwiseOr:
  1645. op_string = "|";
  1646. break;
  1647. case BinaryOp::BitwiseXor:
  1648. op_string = "^";
  1649. break;
  1650. case BinaryOp::LeftShift:
  1651. op_string = "<<";
  1652. break;
  1653. case BinaryOp::RightShift:
  1654. op_string = ">>";
  1655. break;
  1656. case BinaryOp::UnsignedRightShift:
  1657. op_string = ">>>";
  1658. break;
  1659. case BinaryOp::In:
  1660. op_string = "in";
  1661. break;
  1662. case BinaryOp::InstanceOf:
  1663. op_string = "instanceof";
  1664. break;
  1665. }
  1666. print_indent(indent);
  1667. outln("{}", class_name());
  1668. m_lhs->dump(indent + 1);
  1669. print_indent(indent + 1);
  1670. outln("{}", op_string);
  1671. m_rhs->dump(indent + 1);
  1672. }
  1673. void LogicalExpression::dump(int indent) const
  1674. {
  1675. const char* op_string = nullptr;
  1676. switch (m_op) {
  1677. case LogicalOp::And:
  1678. op_string = "&&";
  1679. break;
  1680. case LogicalOp::Or:
  1681. op_string = "||";
  1682. break;
  1683. case LogicalOp::NullishCoalescing:
  1684. op_string = "??";
  1685. break;
  1686. }
  1687. print_indent(indent);
  1688. outln("{}", class_name());
  1689. m_lhs->dump(indent + 1);
  1690. print_indent(indent + 1);
  1691. outln("{}", op_string);
  1692. m_rhs->dump(indent + 1);
  1693. }
  1694. void UnaryExpression::dump(int indent) const
  1695. {
  1696. const char* op_string = nullptr;
  1697. switch (m_op) {
  1698. case UnaryOp::BitwiseNot:
  1699. op_string = "~";
  1700. break;
  1701. case UnaryOp::Not:
  1702. op_string = "!";
  1703. break;
  1704. case UnaryOp::Plus:
  1705. op_string = "+";
  1706. break;
  1707. case UnaryOp::Minus:
  1708. op_string = "-";
  1709. break;
  1710. case UnaryOp::Typeof:
  1711. op_string = "typeof ";
  1712. break;
  1713. case UnaryOp::Void:
  1714. op_string = "void ";
  1715. break;
  1716. case UnaryOp::Delete:
  1717. op_string = "delete ";
  1718. break;
  1719. }
  1720. print_indent(indent);
  1721. outln("{}", class_name());
  1722. print_indent(indent + 1);
  1723. outln("{}", op_string);
  1724. m_lhs->dump(indent + 1);
  1725. }
  1726. void CallExpression::dump(int indent) const
  1727. {
  1728. print_indent(indent);
  1729. if (is<NewExpression>(*this))
  1730. outln("CallExpression [new]");
  1731. else
  1732. outln("CallExpression");
  1733. m_callee->dump(indent + 1);
  1734. for (auto& argument : m_arguments)
  1735. argument.value->dump(indent + 1);
  1736. }
  1737. void SuperCall::dump(int indent) const
  1738. {
  1739. print_indent(indent);
  1740. outln("SuperCall");
  1741. for (auto& argument : m_arguments)
  1742. argument.value->dump(indent + 1);
  1743. }
  1744. void ClassDeclaration::dump(int indent) const
  1745. {
  1746. ASTNode::dump(indent);
  1747. m_class_expression->dump(indent + 1);
  1748. }
  1749. ThrowCompletionOr<void> ClassDeclaration::for_each_bound_name(ThrowCompletionOrVoidCallback<FlyString const&>&& callback) const
  1750. {
  1751. if (m_class_expression->name().is_empty())
  1752. return {};
  1753. return callback(m_class_expression->name());
  1754. }
  1755. void ClassExpression::dump(int indent) const
  1756. {
  1757. print_indent(indent);
  1758. outln("ClassExpression: \"{}\"", m_name);
  1759. print_indent(indent);
  1760. outln("(Constructor)");
  1761. m_constructor->dump(indent + 1);
  1762. if (!m_super_class.is_null()) {
  1763. print_indent(indent);
  1764. outln("(Super Class)");
  1765. m_super_class->dump(indent + 1);
  1766. }
  1767. print_indent(indent);
  1768. outln("(Elements)");
  1769. for (auto& method : m_elements)
  1770. method.dump(indent + 1);
  1771. }
  1772. void ClassMethod::dump(int indent) const
  1773. {
  1774. ASTNode::dump(indent);
  1775. print_indent(indent);
  1776. outln("(Key)");
  1777. m_key->dump(indent + 1);
  1778. const char* kind_string = nullptr;
  1779. switch (m_kind) {
  1780. case Kind::Method:
  1781. kind_string = "Method";
  1782. break;
  1783. case Kind::Getter:
  1784. kind_string = "Getter";
  1785. break;
  1786. case Kind::Setter:
  1787. kind_string = "Setter";
  1788. break;
  1789. }
  1790. print_indent(indent);
  1791. outln("Kind: {}", kind_string);
  1792. print_indent(indent);
  1793. outln("Static: {}", is_static());
  1794. print_indent(indent);
  1795. outln("(Function)");
  1796. m_function->dump(indent + 1);
  1797. }
  1798. void ClassField::dump(int indent) const
  1799. {
  1800. ASTNode::dump(indent);
  1801. print_indent(indent);
  1802. outln("(Key)");
  1803. m_key->dump(indent + 1);
  1804. print_indent(indent);
  1805. outln("Static: {}", is_static());
  1806. if (m_initializer) {
  1807. print_indent(indent);
  1808. outln("(Initializer)");
  1809. m_initializer->dump(indent + 1);
  1810. }
  1811. }
  1812. void StaticInitializer::dump(int indent) const
  1813. {
  1814. ASTNode::dump(indent);
  1815. m_function_body->dump(indent + 1);
  1816. }
  1817. void StringLiteral::dump(int indent) const
  1818. {
  1819. print_indent(indent);
  1820. outln("StringLiteral \"{}\"", m_value);
  1821. }
  1822. void SuperExpression::dump(int indent) const
  1823. {
  1824. print_indent(indent);
  1825. outln("super");
  1826. }
  1827. void NumericLiteral::dump(int indent) const
  1828. {
  1829. print_indent(indent);
  1830. outln("NumericLiteral {}", m_value);
  1831. }
  1832. void BigIntLiteral::dump(int indent) const
  1833. {
  1834. print_indent(indent);
  1835. outln("BigIntLiteral {}", m_value);
  1836. }
  1837. void BooleanLiteral::dump(int indent) const
  1838. {
  1839. print_indent(indent);
  1840. outln("BooleanLiteral {}", m_value);
  1841. }
  1842. void NullLiteral::dump(int indent) const
  1843. {
  1844. print_indent(indent);
  1845. outln("null");
  1846. }
  1847. bool BindingPattern::contains_expression() const
  1848. {
  1849. for (auto& entry : entries) {
  1850. if (entry.initializer)
  1851. return true;
  1852. if (auto binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern>>(); binding_ptr && (*binding_ptr)->contains_expression())
  1853. return true;
  1854. }
  1855. return false;
  1856. }
  1857. ThrowCompletionOr<void> BindingPattern::for_each_bound_name(ThrowCompletionOrVoidCallback<FlyString const&>&& callback) const
  1858. {
  1859. for (auto const& entry : entries) {
  1860. auto const& alias = entry.alias;
  1861. if (alias.has<NonnullRefPtr<Identifier>>()) {
  1862. TRY(callback(alias.get<NonnullRefPtr<Identifier>>()->string()));
  1863. } else if (alias.has<NonnullRefPtr<BindingPattern>>()) {
  1864. TRY(alias.get<NonnullRefPtr<BindingPattern>>()->for_each_bound_name(forward<decltype(callback)>(callback)));
  1865. } else {
  1866. auto const& name = entry.name;
  1867. if (name.has<NonnullRefPtr<Identifier>>())
  1868. TRY(callback(name.get<NonnullRefPtr<Identifier>>()->string()));
  1869. }
  1870. }
  1871. return {};
  1872. }
  1873. void BindingPattern::dump(int indent) const
  1874. {
  1875. print_indent(indent);
  1876. outln("BindingPattern {}", kind == Kind::Array ? "Array" : "Object");
  1877. for (auto& entry : entries) {
  1878. print_indent(indent + 1);
  1879. outln("(Property)");
  1880. if (kind == Kind::Object) {
  1881. print_indent(indent + 2);
  1882. outln("(Identifier)");
  1883. if (entry.name.has<NonnullRefPtr<Identifier>>()) {
  1884. entry.name.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1885. } else {
  1886. entry.name.get<NonnullRefPtr<Expression>>()->dump(indent + 3);
  1887. }
  1888. } else if (entry.is_elision()) {
  1889. print_indent(indent + 2);
  1890. outln("(Elision)");
  1891. continue;
  1892. }
  1893. print_indent(indent + 2);
  1894. outln("(Pattern{})", entry.is_rest ? " rest=true" : "");
  1895. if (entry.alias.has<NonnullRefPtr<Identifier>>()) {
  1896. entry.alias.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1897. } else if (entry.alias.has<NonnullRefPtr<BindingPattern>>()) {
  1898. entry.alias.get<NonnullRefPtr<BindingPattern>>()->dump(indent + 3);
  1899. } else if (entry.alias.has<NonnullRefPtr<MemberExpression>>()) {
  1900. entry.alias.get<NonnullRefPtr<MemberExpression>>()->dump(indent + 3);
  1901. } else {
  1902. print_indent(indent + 3);
  1903. outln("<empty>");
  1904. }
  1905. if (entry.initializer) {
  1906. print_indent(indent + 2);
  1907. outln("(Initializer)");
  1908. entry.initializer->dump(indent + 3);
  1909. }
  1910. }
  1911. }
  1912. void FunctionNode::dump(int indent, String const& class_name) const
  1913. {
  1914. print_indent(indent);
  1915. auto is_async = m_kind == FunctionKind::Async || m_kind == FunctionKind::AsyncGenerator;
  1916. auto is_generator = m_kind == FunctionKind::Generator || m_kind == FunctionKind::AsyncGenerator;
  1917. outln("{}{}{} '{}'", class_name, is_async ? " async" : "", is_generator ? "*" : "", name());
  1918. if (m_contains_direct_call_to_eval) {
  1919. print_indent(indent + 1);
  1920. outln("\033[31;1m(direct eval)\033[0m");
  1921. }
  1922. if (!m_parameters.is_empty()) {
  1923. print_indent(indent + 1);
  1924. outln("(Parameters)");
  1925. for (auto& parameter : m_parameters) {
  1926. print_indent(indent + 2);
  1927. if (parameter.is_rest)
  1928. out("...");
  1929. parameter.binding.visit(
  1930. [&](FlyString const& name) {
  1931. outln("{}", name);
  1932. },
  1933. [&](BindingPattern const& pattern) {
  1934. pattern.dump(indent + 2);
  1935. });
  1936. if (parameter.default_value)
  1937. parameter.default_value->dump(indent + 3);
  1938. }
  1939. }
  1940. print_indent(indent + 1);
  1941. outln("(Body)");
  1942. body().dump(indent + 2);
  1943. }
  1944. void FunctionDeclaration::dump(int indent) const
  1945. {
  1946. FunctionNode::dump(indent, class_name());
  1947. }
  1948. ThrowCompletionOr<void> FunctionDeclaration::for_each_bound_name(ThrowCompletionOrVoidCallback<const FlyString&>&& callback) const
  1949. {
  1950. if (name().is_empty())
  1951. return {};
  1952. return callback(name());
  1953. }
  1954. void FunctionExpression::dump(int indent) const
  1955. {
  1956. FunctionNode::dump(indent, class_name());
  1957. }
  1958. void YieldExpression::dump(int indent) const
  1959. {
  1960. ASTNode::dump(indent);
  1961. if (argument())
  1962. argument()->dump(indent + 1);
  1963. }
  1964. void AwaitExpression::dump(int indent) const
  1965. {
  1966. ASTNode::dump(indent);
  1967. m_argument->dump(indent + 1);
  1968. }
  1969. void ReturnStatement::dump(int indent) const
  1970. {
  1971. ASTNode::dump(indent);
  1972. if (argument())
  1973. argument()->dump(indent + 1);
  1974. }
  1975. void IfStatement::dump(int indent) const
  1976. {
  1977. ASTNode::dump(indent);
  1978. print_indent(indent);
  1979. outln("If");
  1980. predicate().dump(indent + 1);
  1981. consequent().dump(indent + 1);
  1982. if (alternate()) {
  1983. print_indent(indent);
  1984. outln("Else");
  1985. alternate()->dump(indent + 1);
  1986. }
  1987. }
  1988. void WhileStatement::dump(int indent) const
  1989. {
  1990. ASTNode::dump(indent);
  1991. print_indent(indent);
  1992. outln("While");
  1993. test().dump(indent + 1);
  1994. body().dump(indent + 1);
  1995. }
  1996. void WithStatement::dump(int indent) const
  1997. {
  1998. ASTNode::dump(indent);
  1999. print_indent(indent + 1);
  2000. outln("Object");
  2001. object().dump(indent + 2);
  2002. print_indent(indent + 1);
  2003. outln("Body");
  2004. body().dump(indent + 2);
  2005. }
  2006. void DoWhileStatement::dump(int indent) const
  2007. {
  2008. ASTNode::dump(indent);
  2009. print_indent(indent);
  2010. outln("DoWhile");
  2011. test().dump(indent + 1);
  2012. body().dump(indent + 1);
  2013. }
  2014. void ForStatement::dump(int indent) const
  2015. {
  2016. ASTNode::dump(indent);
  2017. print_indent(indent);
  2018. outln("For");
  2019. if (init())
  2020. init()->dump(indent + 1);
  2021. if (test())
  2022. test()->dump(indent + 1);
  2023. if (update())
  2024. update()->dump(indent + 1);
  2025. body().dump(indent + 1);
  2026. }
  2027. void ForInStatement::dump(int indent) const
  2028. {
  2029. ASTNode::dump(indent);
  2030. print_indent(indent);
  2031. outln("ForIn");
  2032. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2033. rhs().dump(indent + 1);
  2034. body().dump(indent + 1);
  2035. }
  2036. void ForOfStatement::dump(int indent) const
  2037. {
  2038. ASTNode::dump(indent);
  2039. print_indent(indent);
  2040. outln("ForOf");
  2041. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2042. rhs().dump(indent + 1);
  2043. body().dump(indent + 1);
  2044. }
  2045. void ForAwaitOfStatement::dump(int indent) const
  2046. {
  2047. ASTNode::dump(indent);
  2048. print_indent(indent);
  2049. outln("ForAwaitOf");
  2050. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2051. m_rhs->dump(indent + 1);
  2052. m_body->dump(indent + 1);
  2053. }
  2054. // 13.1.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-identifiers-runtime-semantics-evaluation
  2055. Completion Identifier::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2056. {
  2057. InterpreterNodeScope node_scope { interpreter, *this };
  2058. // 1. Return ? ResolveBinding(StringValue of Identifier).
  2059. auto reference = TRY(interpreter.vm().resolve_binding(m_string));
  2060. // NOTE: The spec wants us to return the reference directly; this is not possible with ASTNode::execute() (short of letting it return a variant).
  2061. // So, instead of calling GetValue at the call site, we do it here.
  2062. return TRY(reference.get_value(global_object));
  2063. }
  2064. void Identifier::dump(int indent) const
  2065. {
  2066. print_indent(indent);
  2067. outln("Identifier \"{}\"", m_string);
  2068. }
  2069. Completion PrivateIdentifier::execute(Interpreter&, GlobalObject&) const
  2070. {
  2071. // Note: This should be handled by either the member expression this is part of
  2072. // or the binary expression in the case of `#foo in bar`.
  2073. VERIFY_NOT_REACHED();
  2074. }
  2075. void PrivateIdentifier::dump(int indent) const
  2076. {
  2077. print_indent(indent);
  2078. outln("PrivateIdentifier \"{}\"", m_string);
  2079. }
  2080. void SpreadExpression::dump(int indent) const
  2081. {
  2082. ASTNode::dump(indent);
  2083. m_target->dump(indent + 1);
  2084. }
  2085. Completion SpreadExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2086. {
  2087. InterpreterNodeScope node_scope { interpreter, *this };
  2088. return m_target->execute(interpreter, global_object);
  2089. }
  2090. // 13.2.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-this-keyword-runtime-semantics-evaluation
  2091. Completion ThisExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2092. {
  2093. InterpreterNodeScope node_scope { interpreter, *this };
  2094. // 1. Return ? ResolveThisBinding().
  2095. return interpreter.vm().resolve_this_binding(global_object);
  2096. }
  2097. void ThisExpression::dump(int indent) const
  2098. {
  2099. ASTNode::dump(indent);
  2100. }
  2101. // 13.15.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation
  2102. Completion AssignmentExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2103. {
  2104. InterpreterNodeScope node_scope { interpreter, *this };
  2105. if (m_op == AssignmentOp::Assignment) {
  2106. // AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  2107. return m_lhs.visit(
  2108. // 1. If LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral, then
  2109. [&](NonnullRefPtr<Expression> const& lhs) -> ThrowCompletionOr<Value> {
  2110. // a. Let lref be the result of evaluating LeftHandSideExpression.
  2111. // b. ReturnIfAbrupt(lref).
  2112. auto reference = TRY(lhs->to_reference(interpreter, global_object));
  2113. Value rhs_result;
  2114. // c. If IsAnonymousFunctionDefinition(AssignmentExpression) and IsIdentifierRef of LeftHandSideExpression are both true, then
  2115. if (lhs->is_identifier()) {
  2116. // i. Let rval be NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  2117. auto& identifier_name = static_cast<Identifier const&>(*lhs).string();
  2118. rhs_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_rhs, identifier_name));
  2119. }
  2120. // d. Else,
  2121. else {
  2122. // i. Let rref be the result of evaluating AssignmentExpression.
  2123. // ii. Let rval be ? GetValue(rref).
  2124. rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2125. }
  2126. // e. Perform ? PutValue(lref, rval).
  2127. TRY(reference.put_value(global_object, rhs_result));
  2128. // f. Return rval.
  2129. return rhs_result;
  2130. },
  2131. // 2. Let assignmentPattern be the AssignmentPattern that is covered by LeftHandSideExpression.
  2132. [&](NonnullRefPtr<BindingPattern> const& pattern) -> ThrowCompletionOr<Value> {
  2133. // 3. Let rref be the result of evaluating AssignmentExpression.
  2134. // 4. Let rval be ? GetValue(rref).
  2135. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2136. // 5. Perform ? DestructuringAssignmentEvaluation of assignmentPattern using rval as the argument.
  2137. TRY(interpreter.vm().destructuring_assignment_evaluation(pattern, rhs_result, global_object));
  2138. // 6. Return rval.
  2139. return rhs_result;
  2140. });
  2141. }
  2142. VERIFY(m_lhs.has<NonnullRefPtr<Expression>>());
  2143. // 1. Let lref be the result of evaluating LeftHandSideExpression.
  2144. auto& lhs_expression = *m_lhs.get<NonnullRefPtr<Expression>>();
  2145. auto reference = TRY(lhs_expression.to_reference(interpreter, global_object));
  2146. // 2. Let lval be ? GetValue(lref).
  2147. auto lhs_result = TRY(reference.get_value(global_object));
  2148. // AssignmentExpression : LeftHandSideExpression {&&=, ||=, ??=} AssignmentExpression
  2149. if (m_op == AssignmentOp::AndAssignment || m_op == AssignmentOp::OrAssignment || m_op == AssignmentOp::NullishAssignment) {
  2150. switch (m_op) {
  2151. // AssignmentExpression : LeftHandSideExpression &&= AssignmentExpression
  2152. case AssignmentOp::AndAssignment:
  2153. // 3. Let lbool be ! ToBoolean(lval).
  2154. // 4. If lbool is false, return lval.
  2155. if (!lhs_result.to_boolean())
  2156. return lhs_result;
  2157. break;
  2158. // AssignmentExpression : LeftHandSideExpression ||= AssignmentExpression
  2159. case AssignmentOp::OrAssignment:
  2160. // 3. Let lbool be ! ToBoolean(lval).
  2161. // 4. If lbool is true, return lval.
  2162. if (lhs_result.to_boolean())
  2163. return lhs_result;
  2164. break;
  2165. // AssignmentExpression : LeftHandSideExpression ??= AssignmentExpression
  2166. case AssignmentOp::NullishAssignment:
  2167. // 3. If lval is neither undefined nor null, return lval.
  2168. if (!lhs_result.is_nullish())
  2169. return lhs_result;
  2170. break;
  2171. default:
  2172. VERIFY_NOT_REACHED();
  2173. }
  2174. Value rhs_result;
  2175. // 5. If IsAnonymousFunctionDefinition(AssignmentExpression) is true and IsIdentifierRef of LeftHandSideExpression is true, then
  2176. if (lhs_expression.is_identifier()) {
  2177. // a. Let rval be NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  2178. auto& identifier_name = static_cast<Identifier const&>(lhs_expression).string();
  2179. rhs_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_rhs, identifier_name));
  2180. }
  2181. // 6. Else,
  2182. else {
  2183. // a. Let rref be the result of evaluating AssignmentExpression.
  2184. // b. Let rval be ? GetValue(rref).
  2185. rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2186. }
  2187. // 7. Perform ? PutValue(lref, rval).
  2188. TRY(reference.put_value(global_object, rhs_result));
  2189. // 8. Return rval.
  2190. return rhs_result;
  2191. }
  2192. // AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
  2193. // 3. Let rref be the result of evaluating AssignmentExpression.
  2194. // 4. Let rval be ? GetValue(rref).
  2195. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2196. // 5. Let assignmentOpText be the source text matched by AssignmentOperator.
  2197. // 6. Let opText be the sequence of Unicode code points associated with assignmentOpText in the following table:
  2198. // 7. Let r be ApplyStringOrNumericBinaryOperator(lval, opText, rval).
  2199. switch (m_op) {
  2200. case AssignmentOp::AdditionAssignment:
  2201. rhs_result = TRY(add(global_object, lhs_result, rhs_result));
  2202. break;
  2203. case AssignmentOp::SubtractionAssignment:
  2204. rhs_result = TRY(sub(global_object, lhs_result, rhs_result));
  2205. break;
  2206. case AssignmentOp::MultiplicationAssignment:
  2207. rhs_result = TRY(mul(global_object, lhs_result, rhs_result));
  2208. break;
  2209. case AssignmentOp::DivisionAssignment:
  2210. rhs_result = TRY(div(global_object, lhs_result, rhs_result));
  2211. break;
  2212. case AssignmentOp::ModuloAssignment:
  2213. rhs_result = TRY(mod(global_object, lhs_result, rhs_result));
  2214. break;
  2215. case AssignmentOp::ExponentiationAssignment:
  2216. rhs_result = TRY(exp(global_object, lhs_result, rhs_result));
  2217. break;
  2218. case AssignmentOp::BitwiseAndAssignment:
  2219. rhs_result = TRY(bitwise_and(global_object, lhs_result, rhs_result));
  2220. break;
  2221. case AssignmentOp::BitwiseOrAssignment:
  2222. rhs_result = TRY(bitwise_or(global_object, lhs_result, rhs_result));
  2223. break;
  2224. case AssignmentOp::BitwiseXorAssignment:
  2225. rhs_result = TRY(bitwise_xor(global_object, lhs_result, rhs_result));
  2226. break;
  2227. case AssignmentOp::LeftShiftAssignment:
  2228. rhs_result = TRY(left_shift(global_object, lhs_result, rhs_result));
  2229. break;
  2230. case AssignmentOp::RightShiftAssignment:
  2231. rhs_result = TRY(right_shift(global_object, lhs_result, rhs_result));
  2232. break;
  2233. case AssignmentOp::UnsignedRightShiftAssignment:
  2234. rhs_result = TRY(unsigned_right_shift(global_object, lhs_result, rhs_result));
  2235. break;
  2236. case AssignmentOp::Assignment:
  2237. case AssignmentOp::AndAssignment:
  2238. case AssignmentOp::OrAssignment:
  2239. case AssignmentOp::NullishAssignment:
  2240. VERIFY_NOT_REACHED();
  2241. }
  2242. // 8. Perform ? PutValue(lref, r).
  2243. TRY(reference.put_value(global_object, rhs_result));
  2244. // 9. Return r.
  2245. return rhs_result;
  2246. }
  2247. // 13.4.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-postfix-increment-operator-runtime-semantics-evaluation
  2248. // 13.4.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-postfix-decrement-operator-runtime-semantics-evaluation
  2249. // 13.4.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-prefix-increment-operator-runtime-semantics-evaluation
  2250. // 13.4.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-prefix-decrement-operator-runtime-semantics-evaluation
  2251. Completion UpdateExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2252. {
  2253. InterpreterNodeScope node_scope { interpreter, *this };
  2254. // 1. Let expr be the result of evaluating <Expression>.
  2255. auto reference = TRY(m_argument->to_reference(interpreter, global_object));
  2256. // 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
  2257. auto old_value = TRY(reference.get_value(global_object));
  2258. old_value = TRY(old_value.to_numeric(global_object));
  2259. Value new_value;
  2260. switch (m_op) {
  2261. case UpdateOp::Increment:
  2262. // 3. If Type(oldValue) is Number, then
  2263. if (old_value.is_number()) {
  2264. // a. Let newValue be ! Number::add(oldValue, 1𝔽).
  2265. new_value = Value(old_value.as_double() + 1);
  2266. }
  2267. // 4. Else,
  2268. else {
  2269. // a. Assert: Type(oldValue) is BigInt.
  2270. // b. Let newValue be ! BigInt::add(oldValue, 1ℤ).
  2271. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  2272. }
  2273. break;
  2274. case UpdateOp::Decrement:
  2275. // 3. If Type(oldValue) is Number, then
  2276. if (old_value.is_number()) {
  2277. // a. Let newValue be ! Number::subtract(oldValue, 1𝔽).
  2278. new_value = Value(old_value.as_double() - 1);
  2279. }
  2280. // 4. Else,
  2281. else {
  2282. // a. Assert: Type(oldValue) is BigInt.
  2283. // b. Let newValue be ! BigInt::subtract(oldValue, 1ℤ).
  2284. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
  2285. }
  2286. break;
  2287. default:
  2288. VERIFY_NOT_REACHED();
  2289. }
  2290. // 5. Perform ? PutValue(expr, newValue).
  2291. TRY(reference.put_value(global_object, new_value));
  2292. // 6. Return newValue.
  2293. // 6. Return oldValue.
  2294. return m_prefixed ? new_value : old_value;
  2295. }
  2296. void AssignmentExpression::dump(int indent) const
  2297. {
  2298. const char* op_string = nullptr;
  2299. switch (m_op) {
  2300. case AssignmentOp::Assignment:
  2301. op_string = "=";
  2302. break;
  2303. case AssignmentOp::AdditionAssignment:
  2304. op_string = "+=";
  2305. break;
  2306. case AssignmentOp::SubtractionAssignment:
  2307. op_string = "-=";
  2308. break;
  2309. case AssignmentOp::MultiplicationAssignment:
  2310. op_string = "*=";
  2311. break;
  2312. case AssignmentOp::DivisionAssignment:
  2313. op_string = "/=";
  2314. break;
  2315. case AssignmentOp::ModuloAssignment:
  2316. op_string = "%=";
  2317. break;
  2318. case AssignmentOp::ExponentiationAssignment:
  2319. op_string = "**=";
  2320. break;
  2321. case AssignmentOp::BitwiseAndAssignment:
  2322. op_string = "&=";
  2323. break;
  2324. case AssignmentOp::BitwiseOrAssignment:
  2325. op_string = "|=";
  2326. break;
  2327. case AssignmentOp::BitwiseXorAssignment:
  2328. op_string = "^=";
  2329. break;
  2330. case AssignmentOp::LeftShiftAssignment:
  2331. op_string = "<<=";
  2332. break;
  2333. case AssignmentOp::RightShiftAssignment:
  2334. op_string = ">>=";
  2335. break;
  2336. case AssignmentOp::UnsignedRightShiftAssignment:
  2337. op_string = ">>>=";
  2338. break;
  2339. case AssignmentOp::AndAssignment:
  2340. op_string = "&&=";
  2341. break;
  2342. case AssignmentOp::OrAssignment:
  2343. op_string = "||=";
  2344. break;
  2345. case AssignmentOp::NullishAssignment:
  2346. op_string = "\?\?=";
  2347. break;
  2348. }
  2349. ASTNode::dump(indent);
  2350. print_indent(indent + 1);
  2351. outln("{}", op_string);
  2352. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2353. m_rhs->dump(indent + 1);
  2354. }
  2355. void UpdateExpression::dump(int indent) const
  2356. {
  2357. const char* op_string = nullptr;
  2358. switch (m_op) {
  2359. case UpdateOp::Increment:
  2360. op_string = "++";
  2361. break;
  2362. case UpdateOp::Decrement:
  2363. op_string = "--";
  2364. break;
  2365. }
  2366. ASTNode::dump(indent);
  2367. if (m_prefixed) {
  2368. print_indent(indent + 1);
  2369. outln("{}", op_string);
  2370. }
  2371. m_argument->dump(indent + 1);
  2372. if (!m_prefixed) {
  2373. print_indent(indent + 1);
  2374. outln("{}", op_string);
  2375. }
  2376. }
  2377. // 14.3.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-let-and-const-declarations-runtime-semantics-evaluation
  2378. // 14.3.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-variable-statement-runtime-semantics-evaluation
  2379. Completion VariableDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2380. {
  2381. InterpreterNodeScope node_scope { interpreter, *this };
  2382. for (auto& declarator : m_declarations) {
  2383. if (auto* init = declarator.init()) {
  2384. TRY(declarator.target().visit(
  2385. [&](NonnullRefPtr<Identifier> const& id) -> ThrowCompletionOr<void> {
  2386. auto reference = TRY(id->to_reference(interpreter, global_object));
  2387. auto initializer_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, *init, id->string()));
  2388. VERIFY(!initializer_result.is_empty());
  2389. if (m_declaration_kind == DeclarationKind::Var)
  2390. return reference.put_value(global_object, initializer_result);
  2391. else
  2392. return reference.initialize_referenced_binding(global_object, initializer_result);
  2393. },
  2394. [&](NonnullRefPtr<BindingPattern> const& pattern) -> ThrowCompletionOr<void> {
  2395. auto initializer_result = TRY(init->execute(interpreter, global_object)).release_value();
  2396. Environment* environment = m_declaration_kind == DeclarationKind::Var ? nullptr : interpreter.lexical_environment();
  2397. return interpreter.vm().binding_initialization(pattern, initializer_result, environment, global_object);
  2398. }));
  2399. } else if (m_declaration_kind != DeclarationKind::Var) {
  2400. VERIFY(declarator.target().has<NonnullRefPtr<Identifier>>());
  2401. auto& identifier = declarator.target().get<NonnullRefPtr<Identifier>>();
  2402. auto reference = TRY(identifier->to_reference(interpreter, global_object));
  2403. TRY(reference.initialize_referenced_binding(global_object, js_undefined()));
  2404. }
  2405. }
  2406. return normal_completion({});
  2407. }
  2408. Completion VariableDeclarator::execute(Interpreter& interpreter, GlobalObject&) const
  2409. {
  2410. InterpreterNodeScope node_scope { interpreter, *this };
  2411. // NOTE: VariableDeclarator execution is handled by VariableDeclaration.
  2412. VERIFY_NOT_REACHED();
  2413. }
  2414. ThrowCompletionOr<void> VariableDeclaration::for_each_bound_name(ThrowCompletionOrVoidCallback<FlyString const&>&& callback) const
  2415. {
  2416. for (auto const& entry : declarations()) {
  2417. TRY(entry.target().visit(
  2418. [&](NonnullRefPtr<Identifier> const& id) {
  2419. return callback(id->string());
  2420. },
  2421. [&](NonnullRefPtr<BindingPattern> const& binding) {
  2422. return binding->for_each_bound_name([&](auto const& name) {
  2423. return callback(name);
  2424. });
  2425. }));
  2426. }
  2427. return {};
  2428. }
  2429. void VariableDeclaration::dump(int indent) const
  2430. {
  2431. const char* declaration_kind_string = nullptr;
  2432. switch (m_declaration_kind) {
  2433. case DeclarationKind::Let:
  2434. declaration_kind_string = "Let";
  2435. break;
  2436. case DeclarationKind::Var:
  2437. declaration_kind_string = "Var";
  2438. break;
  2439. case DeclarationKind::Const:
  2440. declaration_kind_string = "Const";
  2441. break;
  2442. }
  2443. ASTNode::dump(indent);
  2444. print_indent(indent + 1);
  2445. outln("{}", declaration_kind_string);
  2446. for (auto& declarator : m_declarations)
  2447. declarator.dump(indent + 1);
  2448. }
  2449. void VariableDeclarator::dump(int indent) const
  2450. {
  2451. ASTNode::dump(indent);
  2452. m_target.visit([indent](const auto& value) { value->dump(indent + 1); });
  2453. if (m_init)
  2454. m_init->dump(indent + 1);
  2455. }
  2456. void ObjectProperty::dump(int indent) const
  2457. {
  2458. ASTNode::dump(indent);
  2459. if (m_property_type == Type::Spread) {
  2460. print_indent(indent + 1);
  2461. outln("...Spreading");
  2462. m_key->dump(indent + 1);
  2463. } else {
  2464. m_key->dump(indent + 1);
  2465. m_value->dump(indent + 1);
  2466. }
  2467. }
  2468. void ObjectExpression::dump(int indent) const
  2469. {
  2470. ASTNode::dump(indent);
  2471. for (auto& property : m_properties) {
  2472. property.dump(indent + 1);
  2473. }
  2474. }
  2475. void ExpressionStatement::dump(int indent) const
  2476. {
  2477. ASTNode::dump(indent);
  2478. m_expression->dump(indent + 1);
  2479. }
  2480. Completion ObjectProperty::execute(Interpreter& interpreter, GlobalObject&) const
  2481. {
  2482. InterpreterNodeScope node_scope { interpreter, *this };
  2483. // NOTE: ObjectProperty execution is handled by ObjectExpression.
  2484. VERIFY_NOT_REACHED();
  2485. }
  2486. // 13.2.5.4 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-object-initializer-runtime-semantics-evaluation
  2487. Completion ObjectExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2488. {
  2489. InterpreterNodeScope node_scope { interpreter, *this };
  2490. // 1. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
  2491. auto* object = Object::create(global_object, global_object.object_prototype());
  2492. // 2. Perform ? PropertyDefinitionEvaluation of PropertyDefinitionList with argument obj.
  2493. for (auto& property : m_properties) {
  2494. auto key = TRY(property.key().execute(interpreter, global_object)).release_value();
  2495. // PropertyDefinition : ... AssignmentExpression
  2496. if (property.type() == ObjectProperty::Type::Spread) {
  2497. // 4. Return ? CopyDataProperties(object, fromValue, excludedNames).
  2498. TRY(object->copy_data_properties(key, {}, global_object));
  2499. continue;
  2500. }
  2501. auto value = TRY(property.value().execute(interpreter, global_object)).release_value();
  2502. // 8. If isProtoSetter is true, then
  2503. if (property.type() == ObjectProperty::Type::ProtoSetter) {
  2504. // a. If Type(propValue) is either Object or Null, then
  2505. if (value.is_object() || value.is_null()) {
  2506. // i. Perform ! object.[[SetPrototypeOf]](propValue).
  2507. MUST(object->internal_set_prototype_of(value.is_object() ? &value.as_object() : nullptr));
  2508. }
  2509. // b. Return unused.
  2510. continue;
  2511. }
  2512. if (value.is_function() && property.is_method())
  2513. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(object);
  2514. auto property_key = TRY(PropertyKey::from_value(global_object, key));
  2515. auto name = TRY(get_function_property_name(property_key));
  2516. if (property.type() == ObjectProperty::Type::Getter) {
  2517. name = String::formatted("get {}", name);
  2518. } else if (property.type() == ObjectProperty::Type::Setter) {
  2519. name = String::formatted("set {}", name);
  2520. }
  2521. update_function_name(value, name);
  2522. switch (property.type()) {
  2523. case ObjectProperty::Type::Getter:
  2524. VERIFY(value.is_function());
  2525. object->define_direct_accessor(property_key, &value.as_function(), nullptr, Attribute::Configurable | Attribute::Enumerable);
  2526. break;
  2527. case ObjectProperty::Type::Setter:
  2528. VERIFY(value.is_function());
  2529. object->define_direct_accessor(property_key, nullptr, &value.as_function(), Attribute::Configurable | Attribute::Enumerable);
  2530. break;
  2531. case ObjectProperty::Type::KeyValue:
  2532. object->define_direct_property(property_key, value, JS::default_attributes);
  2533. break;
  2534. case ObjectProperty::Type::Spread:
  2535. default:
  2536. VERIFY_NOT_REACHED();
  2537. }
  2538. }
  2539. // 3. Return obj.
  2540. return Value { object };
  2541. }
  2542. void MemberExpression::dump(int indent) const
  2543. {
  2544. print_indent(indent);
  2545. outln("{}(computed={})", class_name(), is_computed());
  2546. m_object->dump(indent + 1);
  2547. m_property->dump(indent + 1);
  2548. }
  2549. String MemberExpression::to_string_approximation() const
  2550. {
  2551. String object_string = "<object>";
  2552. if (is<Identifier>(*m_object))
  2553. object_string = static_cast<Identifier const&>(*m_object).string();
  2554. if (is_computed())
  2555. return String::formatted("{}[<computed>]", object_string);
  2556. return String::formatted("{}.{}", object_string, verify_cast<Identifier>(*m_property).string());
  2557. }
  2558. // 13.3.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-property-accessors-runtime-semantics-evaluation
  2559. Completion MemberExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2560. {
  2561. InterpreterNodeScope node_scope { interpreter, *this };
  2562. auto reference = TRY(to_reference(interpreter, global_object));
  2563. return TRY(reference.get_value(global_object));
  2564. }
  2565. bool MemberExpression::ends_in_private_name() const
  2566. {
  2567. if (is_computed())
  2568. return false;
  2569. if (is<PrivateIdentifier>(*m_property))
  2570. return true;
  2571. if (is<MemberExpression>(*m_property))
  2572. return static_cast<MemberExpression const&>(*m_property).ends_in_private_name();
  2573. return false;
  2574. }
  2575. void OptionalChain::dump(int indent) const
  2576. {
  2577. print_indent(indent);
  2578. outln("{}", class_name());
  2579. m_base->dump(indent + 1);
  2580. for (auto& reference : m_references) {
  2581. reference.visit(
  2582. [&](Call const& call) {
  2583. print_indent(indent + 1);
  2584. outln("Call({})", call.mode == Mode::Optional ? "Optional" : "Not Optional");
  2585. for (auto& argument : call.arguments)
  2586. argument.value->dump(indent + 2);
  2587. },
  2588. [&](ComputedReference const& ref) {
  2589. print_indent(indent + 1);
  2590. outln("ComputedReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2591. ref.expression->dump(indent + 2);
  2592. },
  2593. [&](MemberReference const& ref) {
  2594. print_indent(indent + 1);
  2595. outln("MemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2596. ref.identifier->dump(indent + 2);
  2597. },
  2598. [&](PrivateMemberReference const& ref) {
  2599. print_indent(indent + 1);
  2600. outln("PrivateMemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2601. ref.private_identifier->dump(indent + 2);
  2602. });
  2603. }
  2604. }
  2605. ThrowCompletionOr<OptionalChain::ReferenceAndValue> OptionalChain::to_reference_and_value(JS::Interpreter& interpreter, JS::GlobalObject& global_object) const
  2606. {
  2607. auto base_reference = TRY(m_base->to_reference(interpreter, global_object));
  2608. auto base = base_reference.is_unresolvable()
  2609. ? TRY(m_base->execute(interpreter, global_object)).release_value()
  2610. : TRY(base_reference.get_value(global_object));
  2611. for (auto& reference : m_references) {
  2612. auto is_optional = reference.visit([](auto& ref) { return ref.mode; }) == Mode::Optional;
  2613. if (is_optional && base.is_nullish())
  2614. return ReferenceAndValue { {}, js_undefined() };
  2615. auto expression = reference.visit(
  2616. [&](Call const& call) -> NonnullRefPtr<Expression> {
  2617. return create_ast_node<CallExpression>(source_range(),
  2618. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2619. call.arguments);
  2620. },
  2621. [&](ComputedReference const& ref) -> NonnullRefPtr<Expression> {
  2622. return create_ast_node<MemberExpression>(source_range(),
  2623. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2624. ref.expression,
  2625. true);
  2626. },
  2627. [&](MemberReference const& ref) -> NonnullRefPtr<Expression> {
  2628. return create_ast_node<MemberExpression>(source_range(),
  2629. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2630. ref.identifier,
  2631. false);
  2632. },
  2633. [&](PrivateMemberReference const& ref) -> NonnullRefPtr<Expression> {
  2634. return create_ast_node<MemberExpression>(source_range(),
  2635. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2636. ref.private_identifier,
  2637. false);
  2638. });
  2639. if (is<CallExpression>(*expression)) {
  2640. base_reference = JS::Reference {};
  2641. base = TRY(expression->execute(interpreter, global_object)).release_value();
  2642. } else {
  2643. base_reference = TRY(expression->to_reference(interpreter, global_object));
  2644. base = TRY(base_reference.get_value(global_object));
  2645. }
  2646. }
  2647. return ReferenceAndValue { move(base_reference), base };
  2648. }
  2649. // 13.3.9.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-optional-chaining-evaluation
  2650. Completion OptionalChain::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2651. {
  2652. InterpreterNodeScope node_scope { interpreter, *this };
  2653. return TRY(to_reference_and_value(interpreter, global_object)).value;
  2654. }
  2655. ThrowCompletionOr<JS::Reference> OptionalChain::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  2656. {
  2657. return TRY(to_reference_and_value(interpreter, global_object)).reference;
  2658. }
  2659. void MetaProperty::dump(int indent) const
  2660. {
  2661. String name;
  2662. if (m_type == MetaProperty::Type::NewTarget)
  2663. name = "new.target";
  2664. else if (m_type == MetaProperty::Type::ImportMeta)
  2665. name = "import.meta";
  2666. else
  2667. VERIFY_NOT_REACHED();
  2668. print_indent(indent);
  2669. outln("{} {}", class_name(), name);
  2670. }
  2671. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  2672. Completion MetaProperty::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2673. {
  2674. InterpreterNodeScope node_scope { interpreter, *this };
  2675. // NewTarget : new . target
  2676. if (m_type == MetaProperty::Type::NewTarget) {
  2677. // 1. Return GetNewTarget().
  2678. return interpreter.vm().get_new_target();
  2679. }
  2680. // ImportMeta : import . meta
  2681. if (m_type == MetaProperty::Type::ImportMeta) {
  2682. // 1. Let module be ! GetActiveScriptOrModule().
  2683. auto script_or_module = interpreter.vm().get_active_script_or_module();
  2684. // 2. Assert: module is a Source Text Module Record.
  2685. VERIFY(script_or_module.has<WeakPtr<Module>>());
  2686. VERIFY(script_or_module.get<WeakPtr<Module>>());
  2687. VERIFY(is<SourceTextModule>(*script_or_module.get<WeakPtr<Module>>()));
  2688. auto& module = static_cast<SourceTextModule&>(*script_or_module.get<WeakPtr<Module>>());
  2689. // 3. Let importMeta be module.[[ImportMeta]].
  2690. auto* import_meta = module.import_meta();
  2691. // 4. If importMeta is empty, then
  2692. if (import_meta == nullptr) {
  2693. // a. Set importMeta to ! OrdinaryObjectCreate(null).
  2694. import_meta = Object::create(global_object, nullptr);
  2695. // b. Let importMetaValues be ! HostGetImportMetaProperties(module).
  2696. auto import_meta_values = interpreter.vm().host_get_import_meta_properties(module);
  2697. // c. For each Record { [[Key]], [[Value]] } p of importMetaValues, do
  2698. for (auto& entry : import_meta_values) {
  2699. // i. Perform ! CreateDataPropertyOrThrow(importMeta, p.[[Key]], p.[[Value]]).
  2700. MUST(import_meta->create_data_property_or_throw(entry.key, entry.value));
  2701. }
  2702. // d. Perform ! HostFinalizeImportMeta(importMeta, module).
  2703. interpreter.vm().host_finalize_import_meta(import_meta, module);
  2704. // e. Set module.[[ImportMeta]] to importMeta.
  2705. module.set_import_meta({}, import_meta);
  2706. // f. Return importMeta.
  2707. return Value { import_meta };
  2708. }
  2709. // 5. Else,
  2710. else {
  2711. // a. Assert: Type(importMeta) is Object.
  2712. // Note: This is always true by the type.
  2713. // b. Return importMeta.
  2714. return Value { import_meta };
  2715. }
  2716. }
  2717. VERIFY_NOT_REACHED();
  2718. }
  2719. void ImportCall::dump(int indent) const
  2720. {
  2721. ASTNode::dump(indent);
  2722. print_indent(indent);
  2723. outln("(Specifier)");
  2724. m_specifier->dump(indent + 1);
  2725. if (m_options) {
  2726. outln("(Options)");
  2727. m_options->dump(indent + 1);
  2728. }
  2729. }
  2730. // 13.3.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-import-call-runtime-semantics-evaluation
  2731. // Also includes assertions from proposal: https://tc39.es/proposal-import-assertions/#sec-import-call-runtime-semantics-evaluation
  2732. Completion ImportCall::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2733. {
  2734. InterpreterNodeScope node_scope { interpreter, *this };
  2735. // 2.1.1.1 EvaluateImportCall ( specifierExpression [ , optionsExpression ] ), https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call
  2736. // 1. Let referencingScriptOrModule be ! GetActiveScriptOrModule().
  2737. auto referencing_script_or_module = interpreter.vm().get_active_script_or_module();
  2738. // 2. Let specifierRef be the result of evaluating specifierExpression.
  2739. // 3. Let specifier be ? GetValue(specifierRef).
  2740. auto specifier = TRY(m_specifier->execute(interpreter, global_object));
  2741. auto options_value = js_undefined();
  2742. // 4. If optionsExpression is present, then
  2743. if (m_options) {
  2744. // a. Let optionsRef be the result of evaluating optionsExpression.
  2745. // b. Let options be ? GetValue(optionsRef).
  2746. options_value = TRY(m_options->execute(interpreter, global_object)).release_value();
  2747. }
  2748. // 5. Else,
  2749. // a. Let options be undefined.
  2750. // Note: options_value is undefined by default.
  2751. // 6. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  2752. auto promise_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor()));
  2753. // 7. Let specifierString be ToString(specifier).
  2754. // 8. IfAbruptRejectPromise(specifierString, promiseCapability).
  2755. auto specifier_string = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, specifier->to_string(global_object));
  2756. // 9. Let assertions be a new empty List.
  2757. Vector<ModuleRequest::Assertion> assertions;
  2758. // 10. If options is not undefined, then
  2759. if (!options_value.is_undefined()) {
  2760. // a. If Type(options) is not Object,
  2761. if (!options_value.is_object()) {
  2762. auto* error = TypeError::create(global_object, String::formatted(ErrorType::NotAnObject.message(), "ImportOptions"));
  2763. // i. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »).
  2764. MUST(call(global_object, *promise_capability.reject, js_undefined(), error));
  2765. // ii. Return promiseCapability.[[Promise]].
  2766. return Value { promise_capability.promise };
  2767. }
  2768. // b. Let assertionsObj be Get(options, "assert").
  2769. // c. IfAbruptRejectPromise(assertionsObj, promiseCapability).
  2770. auto assertion_object = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, options_value.get(global_object, interpreter.vm().names.assert));
  2771. // d. If assertionsObj is not undefined,
  2772. if (!assertion_object.is_undefined()) {
  2773. // i. If Type(assertionsObj) is not Object,
  2774. if (!assertion_object.is_object()) {
  2775. auto* error = TypeError::create(global_object, String::formatted(ErrorType::NotAnObject.message(), "ImportOptionsAssertions"));
  2776. // 1. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »).
  2777. MUST(call(global_object, *promise_capability.reject, js_undefined(), error));
  2778. // 2. Return promiseCapability.[[Promise]].
  2779. return Value { promise_capability.promise };
  2780. }
  2781. // ii. Let keys be EnumerableOwnPropertyNames(assertionsObj, key).
  2782. // iii. IfAbruptRejectPromise(keys, promiseCapability).
  2783. auto keys = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, assertion_object.as_object().enumerable_own_property_names(Object::PropertyKind::Key));
  2784. // iv. Let supportedAssertions be ! HostGetSupportedImportAssertions().
  2785. auto supported_assertions = interpreter.vm().host_get_supported_import_assertions();
  2786. // v. For each String key of keys,
  2787. for (auto const& key : keys) {
  2788. auto property_key = MUST(key.to_property_key(global_object));
  2789. // 1. Let value be Get(assertionsObj, key).
  2790. // 2. IfAbruptRejectPromise(value, promiseCapability).
  2791. auto value = TRY_OR_REJECT_WITH_VALUE(global_object, promise_capability, assertion_object.get(global_object, property_key));
  2792. // 3. If Type(value) is not String, then
  2793. if (!value.is_string()) {
  2794. auto* error = TypeError::create(global_object, String::formatted(ErrorType::NotAString.message(), "Import Assertion option value"));
  2795. // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »).
  2796. MUST(call(global_object, *promise_capability.reject, js_undefined(), error));
  2797. // b. Return promiseCapability.[[Promise]].
  2798. return Value { promise_capability.promise };
  2799. }
  2800. // 4. If supportedAssertions contains key, then
  2801. if (supported_assertions.contains_slow(property_key.to_string())) {
  2802. // a. Append { [[Key]]: key, [[Value]]: value } to assertions.
  2803. assertions.empend(property_key.to_string(), value.as_string().string());
  2804. }
  2805. }
  2806. }
  2807. // e. Sort assertions by the code point order of the [[Key]] of each element. NOTE: This sorting is observable only in that hosts are prohibited from distinguishing among assertions by the order they occur in.
  2808. // Note: This is done when constructing the ModuleRequest.
  2809. }
  2810. // 11. Let moduleRequest be a new ModuleRequest Record { [[Specifier]]: specifierString, [[Assertions]]: assertions }.
  2811. ModuleRequest request { specifier_string, assertions };
  2812. // 12. Perform ! HostImportModuleDynamically(referencingScriptOrModule, moduleRequest, promiseCapability).
  2813. interpreter.vm().host_import_module_dynamically(referencing_script_or_module, move(request), promise_capability);
  2814. // 13. Return promiseCapability.[[Promise]].
  2815. return Value { promise_capability.promise };
  2816. }
  2817. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2818. Completion StringLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2819. {
  2820. InterpreterNodeScope node_scope { interpreter, *this };
  2821. // 1. Return the SV of StringLiteral as defined in 12.8.4.2.
  2822. return Value { js_string(interpreter.heap(), m_value) };
  2823. }
  2824. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2825. Completion NumericLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2826. {
  2827. InterpreterNodeScope node_scope { interpreter, *this };
  2828. // 1. Return the NumericValue of NumericLiteral as defined in 12.8.3.
  2829. return Value(m_value);
  2830. }
  2831. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2832. Completion BigIntLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2833. {
  2834. InterpreterNodeScope node_scope { interpreter, *this };
  2835. // 1. Return the NumericValue of NumericLiteral as defined in 12.8.3.
  2836. Crypto::SignedBigInteger integer;
  2837. if (m_value[0] == '0' && m_value.length() >= 3) {
  2838. if (m_value[1] == 'x' || m_value[1] == 'X') {
  2839. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3))) };
  2840. } else if (m_value[1] == 'o' || m_value[1] == 'O') {
  2841. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3))) };
  2842. } else if (m_value[1] == 'b' || m_value[1] == 'B') {
  2843. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3))) };
  2844. }
  2845. }
  2846. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1))) };
  2847. }
  2848. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2849. Completion BooleanLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2850. {
  2851. InterpreterNodeScope node_scope { interpreter, *this };
  2852. // 1. If BooleanLiteral is the token false, return false.
  2853. // 2. If BooleanLiteral is the token true, return true.
  2854. return Value(m_value);
  2855. }
  2856. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2857. Completion NullLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2858. {
  2859. InterpreterNodeScope node_scope { interpreter, *this };
  2860. // 1. Return null.
  2861. return js_null();
  2862. }
  2863. void RegExpLiteral::dump(int indent) const
  2864. {
  2865. print_indent(indent);
  2866. outln("{} (/{}/{})", class_name(), pattern(), flags());
  2867. }
  2868. // 13.2.7.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation
  2869. Completion RegExpLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2870. {
  2871. InterpreterNodeScope node_scope { interpreter, *this };
  2872. // 1. Let pattern be ! CodePointsToString(BodyText of RegularExpressionLiteral).
  2873. auto pattern = this->pattern();
  2874. // 2. Let flags be ! CodePointsToString(FlagText of RegularExpressionLiteral).
  2875. auto flags = this->flags();
  2876. // 3. Return RegExpCreate(pattern, flags).
  2877. Regex<ECMA262> regex(parsed_regex(), parsed_pattern(), parsed_flags());
  2878. return Value { RegExpObject::create(global_object, move(regex), move(pattern), move(flags)) };
  2879. }
  2880. void ArrayExpression::dump(int indent) const
  2881. {
  2882. ASTNode::dump(indent);
  2883. for (auto& element : m_elements) {
  2884. if (element) {
  2885. element->dump(indent + 1);
  2886. } else {
  2887. print_indent(indent + 1);
  2888. outln("<empty>");
  2889. }
  2890. }
  2891. }
  2892. // 13.2.4.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-array-initializer-runtime-semantics-evaluation
  2893. Completion ArrayExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2894. {
  2895. InterpreterNodeScope node_scope { interpreter, *this };
  2896. // 1. Let array be ! ArrayCreate(0).
  2897. auto* array = MUST(Array::create(global_object, 0));
  2898. // 2. Let len be the result of performing ArrayAccumulation of ElementList with arguments array and 0.
  2899. // 3. ReturnIfAbrupt(len).
  2900. array->indexed_properties();
  2901. size_t index = 0;
  2902. for (auto& element : m_elements) {
  2903. auto value = Value();
  2904. if (element) {
  2905. value = TRY(element->execute(interpreter, global_object)).release_value();
  2906. if (is<SpreadExpression>(*element)) {
  2907. (void)TRY(get_iterator_values(global_object, value, [&](Value iterator_value) -> Optional<Completion> {
  2908. array->indexed_properties().put(index++, iterator_value, default_attributes);
  2909. return {};
  2910. }));
  2911. continue;
  2912. }
  2913. }
  2914. array->indexed_properties().put(index++, value, default_attributes);
  2915. }
  2916. // 4. Return array.
  2917. return Value { array };
  2918. }
  2919. void TemplateLiteral::dump(int indent) const
  2920. {
  2921. ASTNode::dump(indent);
  2922. for (auto& expression : m_expressions)
  2923. expression.dump(indent + 1);
  2924. }
  2925. // 13.2.8.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-template-literals-runtime-semantics-evaluation
  2926. Completion TemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2927. {
  2928. InterpreterNodeScope node_scope { interpreter, *this };
  2929. StringBuilder string_builder;
  2930. for (auto& expression : m_expressions) {
  2931. // 1. Let head be the TV of TemplateHead as defined in 12.8.6.
  2932. // 2. Let subRef be the result of evaluating Expression.
  2933. // 3. Let sub be ? GetValue(subRef).
  2934. auto sub = TRY(expression.execute(interpreter, global_object)).release_value();
  2935. // 4. Let middle be ? ToString(sub).
  2936. auto string = TRY(sub.to_string(global_object));
  2937. string_builder.append(string);
  2938. // 5. Let tail be the result of evaluating TemplateSpans.
  2939. // 6. ReturnIfAbrupt(tail).
  2940. }
  2941. // 7. Return the string-concatenation of head, middle, and tail.
  2942. return Value { js_string(interpreter.heap(), string_builder.build()) };
  2943. }
  2944. void TaggedTemplateLiteral::dump(int indent) const
  2945. {
  2946. ASTNode::dump(indent);
  2947. print_indent(indent + 1);
  2948. outln("(Tag)");
  2949. m_tag->dump(indent + 2);
  2950. print_indent(indent + 1);
  2951. outln("(Template Literal)");
  2952. m_template_literal->dump(indent + 2);
  2953. }
  2954. // 13.3.11.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-tagged-templates-runtime-semantics-evaluation
  2955. Completion TaggedTemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2956. {
  2957. InterpreterNodeScope node_scope { interpreter, *this };
  2958. auto& vm = interpreter.vm();
  2959. auto tag = TRY(m_tag->execute(interpreter, global_object)).release_value();
  2960. auto& expressions = m_template_literal->expressions();
  2961. auto* strings = MUST(Array::create(global_object, 0));
  2962. MarkedVector<Value> arguments(vm.heap());
  2963. arguments.append(strings);
  2964. for (size_t i = 0; i < expressions.size(); ++i) {
  2965. auto value = TRY(expressions[i].execute(interpreter, global_object)).release_value();
  2966. // tag`${foo}` -> "", foo, "" -> tag(["", ""], foo)
  2967. // tag`foo${bar}baz${qux}` -> "foo", bar, "baz", qux, "" -> tag(["foo", "baz", ""], bar, qux)
  2968. if (i % 2 == 0) {
  2969. strings->indexed_properties().append(value);
  2970. } else {
  2971. arguments.append(value);
  2972. }
  2973. }
  2974. auto* raw_strings = MUST(Array::create(global_object, 0));
  2975. for (auto& raw_string : m_template_literal->raw_strings()) {
  2976. auto value = TRY(raw_string.execute(interpreter, global_object)).release_value();
  2977. raw_strings->indexed_properties().append(value);
  2978. }
  2979. strings->define_direct_property(vm.names.raw, raw_strings, 0);
  2980. return call(global_object, tag, js_undefined(), move(arguments));
  2981. }
  2982. void TryStatement::dump(int indent) const
  2983. {
  2984. ASTNode::dump(indent);
  2985. print_indent(indent);
  2986. outln("(Block)");
  2987. block().dump(indent + 1);
  2988. if (handler()) {
  2989. print_indent(indent);
  2990. outln("(Handler)");
  2991. handler()->dump(indent + 1);
  2992. }
  2993. if (finalizer()) {
  2994. print_indent(indent);
  2995. outln("(Finalizer)");
  2996. finalizer()->dump(indent + 1);
  2997. }
  2998. }
  2999. void CatchClause::dump(int indent) const
  3000. {
  3001. print_indent(indent);
  3002. m_parameter.visit(
  3003. [&](FlyString const& parameter) {
  3004. if (parameter.is_null())
  3005. outln("CatchClause");
  3006. else
  3007. outln("CatchClause ({})", parameter);
  3008. },
  3009. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  3010. outln("CatchClause");
  3011. print_indent(indent);
  3012. outln("(Parameter)");
  3013. pattern->dump(indent + 2);
  3014. });
  3015. body().dump(indent + 1);
  3016. }
  3017. void ThrowStatement::dump(int indent) const
  3018. {
  3019. ASTNode::dump(indent);
  3020. argument().dump(indent + 1);
  3021. }
  3022. // 14.15.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-try-statement-runtime-semantics-evaluation
  3023. Completion TryStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3024. {
  3025. InterpreterNodeScope node_scope { interpreter, *this };
  3026. auto& vm = interpreter.vm();
  3027. // 14.15.2 Runtime Semantics: CatchClauseEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-catchclauseevaluation
  3028. auto catch_clause_evaluation = [&](Value thrown_value) {
  3029. // 1. Let oldEnv be the running execution context's LexicalEnvironment.
  3030. auto* old_environment = vm.running_execution_context().lexical_environment;
  3031. // 2. Let catchEnv be NewDeclarativeEnvironment(oldEnv).
  3032. auto* catch_environment = new_declarative_environment(*old_environment);
  3033. m_handler->parameter().visit(
  3034. [&](FlyString const& parameter) {
  3035. // 3. For each element argName of the BoundNames of CatchParameter, do
  3036. // a. Perform ! catchEnv.CreateMutableBinding(argName, false).
  3037. MUST(catch_environment->create_mutable_binding(global_object, parameter, false));
  3038. },
  3039. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  3040. // 3. For each element argName of the BoundNames of CatchParameter, do
  3041. pattern->for_each_bound_name([&](auto& name) {
  3042. // a. Perform ! catchEnv.CreateMutableBinding(argName, false).
  3043. MUST(catch_environment->create_mutable_binding(global_object, name, false));
  3044. });
  3045. });
  3046. // 4. Set the running execution context's LexicalEnvironment to catchEnv.
  3047. vm.running_execution_context().lexical_environment = catch_environment;
  3048. // 5. Let status be BindingInitialization of CatchParameter with arguments thrownValue and catchEnv.
  3049. auto status = m_handler->parameter().visit(
  3050. [&](FlyString const& parameter) {
  3051. return catch_environment->initialize_binding(global_object, parameter, thrown_value);
  3052. },
  3053. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  3054. return vm.binding_initialization(pattern, thrown_value, catch_environment, global_object);
  3055. });
  3056. // 6. If status is an abrupt completion, then
  3057. if (status.is_error()) {
  3058. // a. Set the running execution context's LexicalEnvironment to oldEnv.
  3059. vm.running_execution_context().lexical_environment = old_environment;
  3060. // b. Return Completion(status).
  3061. return status.release_error();
  3062. }
  3063. // 7. Let B be the result of evaluating Block.
  3064. auto handler_result = m_handler->body().execute(interpreter, global_object);
  3065. // 8. Set the running execution context's LexicalEnvironment to oldEnv.
  3066. vm.running_execution_context().lexical_environment = old_environment;
  3067. // 9. Return Completion(B).
  3068. return handler_result;
  3069. };
  3070. Completion result;
  3071. // 1. Let B be the result of evaluating Block.
  3072. auto block_result = m_block->execute(interpreter, global_object);
  3073. // TryStatement : try Block Catch
  3074. // TryStatement : try Block Catch Finally
  3075. if (m_handler) {
  3076. // 2. If B.[[Type]] is throw, let C be CatchClauseEvaluation of Catch with argument B.[[Value]].
  3077. if (block_result.type() == Completion::Type::Throw)
  3078. result = catch_clause_evaluation(*block_result.value());
  3079. // 3. Else, let C be B.
  3080. else
  3081. result = move(block_result);
  3082. } else {
  3083. // TryStatement : try Block Finally
  3084. // This variant doesn't have C & uses B in the finalizer step.
  3085. result = move(block_result);
  3086. }
  3087. // TryStatement : try Block Finally
  3088. // TryStatement : try Block Catch Finally
  3089. if (m_finalizer) {
  3090. // 4. Let F be the result of evaluating Finally.
  3091. auto finalizer_result = m_finalizer->execute(interpreter, global_object);
  3092. // 5. If F.[[Type]] is normal, set F to C.
  3093. if (finalizer_result.type() == Completion::Type::Normal)
  3094. finalizer_result = move(result);
  3095. // 6. Return Completion(UpdateEmpty(F, undefined)).
  3096. return finalizer_result.update_empty(js_undefined());
  3097. }
  3098. // 4. Return Completion(UpdateEmpty(C, undefined)).
  3099. return result.update_empty(js_undefined());
  3100. }
  3101. Completion CatchClause::execute(Interpreter& interpreter, GlobalObject&) const
  3102. {
  3103. InterpreterNodeScope node_scope { interpreter, *this };
  3104. // NOTE: CatchClause execution is handled by TryStatement.
  3105. VERIFY_NOT_REACHED();
  3106. return {};
  3107. }
  3108. // 14.14.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-throw-statement-runtime-semantics-evaluation
  3109. Completion ThrowStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3110. {
  3111. InterpreterNodeScope node_scope { interpreter, *this };
  3112. // 1. Let exprRef be the result of evaluating Expression.
  3113. // 2. Let exprValue be ? GetValue(exprRef).
  3114. auto value = TRY(m_argument->execute(interpreter, global_object)).release_value();
  3115. // 3. Return ThrowCompletion(exprValue).
  3116. return throw_completion(value);
  3117. }
  3118. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  3119. // BreakableStatement : SwitchStatement
  3120. Completion SwitchStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3121. {
  3122. // 1. Let newLabelSet be a new empty List.
  3123. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  3124. return labelled_evaluation(interpreter, global_object, *this, {});
  3125. }
  3126. // NOTE: Since we don't have the 'BreakableStatement' from the spec as a separate ASTNode that wraps IterationStatement / SwitchStatement,
  3127. // execute() needs to take care of LabelledEvaluation, which in turn calls execute_impl().
  3128. // 14.12.4 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-switch-statement-runtime-semantics-evaluation
  3129. Completion SwitchStatement::execute_impl(Interpreter& interpreter, GlobalObject& global_object) const
  3130. {
  3131. InterpreterNodeScope node_scope { interpreter, *this };
  3132. auto& vm = interpreter.vm();
  3133. // 14.12.3 CaseClauseIsSelected ( C, input ), https://tc39.es/ecma262/#sec-runtime-semantics-caseclauseisselected
  3134. auto case_clause_is_selected = [&](auto const& case_clause, auto input) -> ThrowCompletionOr<bool> {
  3135. // 1. Assert: C is an instance of the production CaseClause : case Expression : StatementList[opt] .
  3136. VERIFY(case_clause.test());
  3137. // 2. Let exprRef be the result of evaluating the Expression of C.
  3138. // 3. Let clauseSelector be ? GetValue(exprRef).
  3139. auto clause_selector = TRY(case_clause.test()->execute(interpreter, global_object)).release_value();
  3140. // 4. Return IsStrictlyEqual(input, clauseSelector).
  3141. return is_strictly_equal(input, clause_selector);
  3142. };
  3143. // 14.12.2 Runtime Semantics: CaseBlockEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-caseblockevaluation
  3144. auto case_block_evaluation = [&](auto input) {
  3145. // CaseBlock : { }
  3146. if (m_cases.is_empty()) {
  3147. // 1. Return NormalCompletion(undefined).
  3148. return normal_completion(js_undefined());
  3149. }
  3150. NonnullRefPtrVector<SwitchCase> case_clauses_1;
  3151. NonnullRefPtrVector<SwitchCase> case_clauses_2;
  3152. RefPtr<SwitchCase> default_clause;
  3153. for (auto const& switch_case : m_cases) {
  3154. if (!switch_case.test())
  3155. default_clause = switch_case;
  3156. else if (!default_clause)
  3157. case_clauses_1.append(switch_case);
  3158. else
  3159. case_clauses_2.append(switch_case);
  3160. }
  3161. // CaseBlock : { CaseClauses }
  3162. if (!default_clause) {
  3163. VERIFY(!case_clauses_1.is_empty());
  3164. VERIFY(case_clauses_2.is_empty());
  3165. // 1. Let V be undefined.
  3166. auto last_value = js_undefined();
  3167. // 2. Let A be the List of CaseClause items in CaseClauses, in source text order.
  3168. // NOTE: A is case_clauses_1.
  3169. // 3. Let found be false.
  3170. auto found = false;
  3171. // 4. For each CaseClause C of A, do
  3172. for (auto const& case_clause : case_clauses_1) {
  3173. // a. If found is false, then
  3174. if (!found) {
  3175. // i. Set found to ? CaseClauseIsSelected(C, input).
  3176. found = TRY(case_clause_is_selected(case_clause, input));
  3177. }
  3178. // b. If found is true, then
  3179. if (found) {
  3180. // i. Let R be the result of evaluating C.
  3181. auto result = case_clause.evaluate_statements(interpreter, global_object);
  3182. // ii. If R.[[Value]] is not empty, set V to R.[[Value]].
  3183. if (result.value().has_value())
  3184. last_value = *result.value();
  3185. // iii. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3186. if (result.is_abrupt())
  3187. return result.update_empty(last_value);
  3188. }
  3189. }
  3190. // 5. Return NormalCompletion(V).
  3191. return normal_completion(last_value);
  3192. }
  3193. // CaseBlock : { CaseClauses[opt] DefaultClause CaseClauses[opt] }
  3194. else {
  3195. // 1. Let V be undefined.
  3196. auto last_value = js_undefined();
  3197. // 2. If the first CaseClauses is present, then
  3198. // a. Let A be the List of CaseClause items in the first CaseClauses, in source text order.
  3199. // 3. Else,
  3200. // a. Let A be « ».
  3201. // NOTE: A is case_clauses_1.
  3202. // 4. Let found be false.
  3203. auto found = false;
  3204. // 5. For each CaseClause C of A, do
  3205. for (auto const& case_clause : case_clauses_1) {
  3206. // a. If found is false, then
  3207. if (!found) {
  3208. // i. Set found to ? CaseClauseIsSelected(C, input).
  3209. found = TRY(case_clause_is_selected(case_clause, input));
  3210. }
  3211. // b. If found is true, then
  3212. if (found) {
  3213. // i. Let R be the result of evaluating C.
  3214. auto result = case_clause.evaluate_statements(interpreter, global_object);
  3215. // ii. If R.[[Value]] is not empty, set V to R.[[Value]].
  3216. if (result.value().has_value())
  3217. last_value = *result.value();
  3218. // iii. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3219. if (result.is_abrupt())
  3220. return result.update_empty(last_value);
  3221. }
  3222. }
  3223. // 6. Let foundInB be false.
  3224. auto found_in_b = false;
  3225. // 7. If the second CaseClauses is present, then
  3226. // a. Let B be the List of CaseClause items in the second CaseClauses, in source text order.
  3227. // 8. Else,
  3228. // a. Let B be « ».
  3229. // NOTE: B is case_clauses_2.
  3230. // 9. If found is false, then
  3231. if (!found) {
  3232. // a. For each CaseClause C of B, do
  3233. for (auto const& case_clause : case_clauses_2) {
  3234. // i. If foundInB is false, then
  3235. if (!found_in_b) {
  3236. // 1. Set foundInB to ? CaseClauseIsSelected(C, input).
  3237. found_in_b = TRY(case_clause_is_selected(case_clause, input));
  3238. }
  3239. // ii. If foundInB is true, then
  3240. if (found_in_b) {
  3241. // 1. Let R be the result of evaluating CaseClause C.
  3242. auto result = case_clause.evaluate_statements(interpreter, global_object);
  3243. // 2. If R.[[Value]] is not empty, set V to R.[[Value]].
  3244. if (result.value().has_value())
  3245. last_value = *result.value();
  3246. // 3. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3247. if (result.is_abrupt())
  3248. return result.update_empty(last_value);
  3249. }
  3250. }
  3251. }
  3252. // 10. If foundInB is true, return NormalCompletion(V).
  3253. if (found_in_b)
  3254. return normal_completion(last_value);
  3255. // 11. Let R be the result of evaluating DefaultClause.
  3256. auto result = default_clause->evaluate_statements(interpreter, global_object);
  3257. // 12. If R.[[Value]] is not empty, set V to R.[[Value]].
  3258. if (result.value().has_value())
  3259. last_value = *result.value();
  3260. // 13. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3261. if (result.is_abrupt())
  3262. return result.update_empty(last_value);
  3263. // 14. NOTE: The following is another complete iteration of the second CaseClauses.
  3264. // 15. For each CaseClause C of B, do
  3265. for (auto const& case_clause : case_clauses_2) {
  3266. // a. Let R be the result of evaluating CaseClause C.
  3267. result = case_clause.evaluate_statements(interpreter, global_object);
  3268. // b. If R.[[Value]] is not empty, set V to R.[[Value]].
  3269. if (result.value().has_value())
  3270. last_value = *result.value();
  3271. // c. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3272. if (result.is_abrupt())
  3273. return result.update_empty(last_value);
  3274. }
  3275. // 16. Return NormalCompletion(V).
  3276. return normal_completion(last_value);
  3277. }
  3278. VERIFY_NOT_REACHED();
  3279. };
  3280. // SwitchStatement : switch ( Expression ) CaseBlock
  3281. // 1. Let exprRef be the result of evaluating Expression.
  3282. // 2. Let switchValue be ? GetValue(exprRef).
  3283. auto switch_value = TRY(m_discriminant->execute(interpreter, global_object)).release_value();
  3284. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
  3285. auto* old_environment = interpreter.lexical_environment();
  3286. // Optimization: Avoid creating a lexical environment if there are no lexical declarations.
  3287. if (has_lexical_declarations()) {
  3288. // 4. Let blockEnv be NewDeclarativeEnvironment(oldEnv).
  3289. auto* block_environment = new_declarative_environment(*old_environment);
  3290. // 5. Perform BlockDeclarationInstantiation(CaseBlock, blockEnv).
  3291. block_declaration_instantiation(global_object, block_environment);
  3292. // 6. Set the running execution context's LexicalEnvironment to blockEnv.
  3293. vm.running_execution_context().lexical_environment = block_environment;
  3294. }
  3295. // 7. Let R be CaseBlockEvaluation of CaseBlock with argument switchValue.
  3296. auto result = case_block_evaluation(switch_value);
  3297. // 8. Set the running execution context's LexicalEnvironment to oldEnv.
  3298. vm.running_execution_context().lexical_environment = old_environment;
  3299. // 9. Return R.
  3300. return result;
  3301. }
  3302. Completion SwitchCase::execute(Interpreter& interpreter, GlobalObject&) const
  3303. {
  3304. InterpreterNodeScope node_scope { interpreter, *this };
  3305. // NOTE: SwitchCase execution is handled by SwitchStatement.
  3306. VERIFY_NOT_REACHED();
  3307. return {};
  3308. }
  3309. // 14.9.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-break-statement-runtime-semantics-evaluation
  3310. Completion BreakStatement::execute(Interpreter& interpreter, GlobalObject&) const
  3311. {
  3312. InterpreterNodeScope node_scope { interpreter, *this };
  3313. // BreakStatement : break ;
  3314. if (m_target_label.is_null()) {
  3315. // 1. Return Completion { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  3316. return { Completion::Type::Break, {}, {} };
  3317. }
  3318. // BreakStatement : break LabelIdentifier ;
  3319. // 1. Let label be the StringValue of LabelIdentifier.
  3320. // 2. Return Completion { [[Type]]: break, [[Value]]: empty, [[Target]]: label }.
  3321. return { Completion::Type::Break, {}, m_target_label };
  3322. }
  3323. // 14.8.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-continue-statement-runtime-semantics-evaluation
  3324. Completion ContinueStatement::execute(Interpreter& interpreter, GlobalObject&) const
  3325. {
  3326. InterpreterNodeScope node_scope { interpreter, *this };
  3327. // ContinueStatement : continue ;
  3328. if (m_target_label.is_null()) {
  3329. // 1. Return Completion { [[Type]]: continue, [[Value]]: empty, [[Target]]: empty }.
  3330. return { Completion::Type::Continue, {}, {} };
  3331. }
  3332. // ContinueStatement : continue LabelIdentifier ;
  3333. // 1. Let label be the StringValue of LabelIdentifier.
  3334. // 2. Return Completion { [[Type]]: continue, [[Value]]: empty, [[Target]]: label }.
  3335. return { Completion::Type::Continue, {}, m_target_label };
  3336. }
  3337. void SwitchStatement::dump(int indent) const
  3338. {
  3339. ASTNode::dump(indent);
  3340. m_discriminant->dump(indent + 1);
  3341. for (auto& switch_case : m_cases) {
  3342. switch_case.dump(indent + 1);
  3343. }
  3344. }
  3345. void SwitchCase::dump(int indent) const
  3346. {
  3347. print_indent(indent + 1);
  3348. if (m_test) {
  3349. outln("(Test)");
  3350. m_test->dump(indent + 2);
  3351. } else {
  3352. outln("(Default)");
  3353. }
  3354. print_indent(indent + 1);
  3355. outln("(Consequent)");
  3356. ScopeNode::dump(indent + 2);
  3357. }
  3358. // 13.14.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-conditional-operator-runtime-semantics-evaluation
  3359. Completion ConditionalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3360. {
  3361. InterpreterNodeScope node_scope { interpreter, *this };
  3362. // 1. Let lref be the result of evaluating ShortCircuitExpression.
  3363. // 2. Let lval be ! ToBoolean(? GetValue(lref)).
  3364. auto test_result = TRY(m_test->execute(interpreter, global_object)).release_value();
  3365. // 3. If lval is true, then
  3366. if (test_result.to_boolean()) {
  3367. // a. Let trueRef be the result of evaluating the first AssignmentExpression.
  3368. // b. Return ? GetValue(trueRef).
  3369. return m_consequent->execute(interpreter, global_object);
  3370. }
  3371. // 4. Else,
  3372. else {
  3373. // a. Let falseRef be the result of evaluating the second AssignmentExpression.
  3374. // b. Return ? GetValue(falseRef).
  3375. return m_alternate->execute(interpreter, global_object);
  3376. }
  3377. }
  3378. void ConditionalExpression::dump(int indent) const
  3379. {
  3380. ASTNode::dump(indent);
  3381. print_indent(indent + 1);
  3382. outln("(Test)");
  3383. m_test->dump(indent + 2);
  3384. print_indent(indent + 1);
  3385. outln("(Consequent)");
  3386. m_consequent->dump(indent + 2);
  3387. print_indent(indent + 1);
  3388. outln("(Alternate)");
  3389. m_alternate->dump(indent + 2);
  3390. }
  3391. void SequenceExpression::dump(int indent) const
  3392. {
  3393. ASTNode::dump(indent);
  3394. for (auto& expression : m_expressions)
  3395. expression.dump(indent + 1);
  3396. }
  3397. // 13.16.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-comma-operator-runtime-semantics-evaluation
  3398. Completion SequenceExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3399. {
  3400. InterpreterNodeScope node_scope { interpreter, *this };
  3401. // NOTE: Not sure why the last node is an AssignmentExpression in the spec :yakfused:
  3402. // 1. Let lref be the result of evaluating Expression.
  3403. // 2. Perform ? GetValue(lref).
  3404. // 3. Let rref be the result of evaluating AssignmentExpression.
  3405. // 4. Return ? GetValue(rref).
  3406. Value last_value;
  3407. for (auto const& expression : m_expressions)
  3408. last_value = TRY(expression.execute(interpreter, global_object)).release_value();
  3409. return { move(last_value) };
  3410. }
  3411. // 14.16.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-debugger-statement-runtime-semantics-evaluation
  3412. Completion DebuggerStatement::execute(Interpreter& interpreter, GlobalObject&) const
  3413. {
  3414. InterpreterNodeScope node_scope { interpreter, *this };
  3415. Completion result;
  3416. // 1. If an implementation-defined debugging facility is available and enabled, then
  3417. if (false) {
  3418. // a. Perform an implementation-defined debugging action.
  3419. // b. Let result be an implementation-defined Completion value.
  3420. }
  3421. // 2. Else,
  3422. else {
  3423. // a. Let result be NormalCompletion(empty).
  3424. result = normal_completion({});
  3425. }
  3426. // 3. Return result.
  3427. return result;
  3428. }
  3429. ThrowCompletionOr<void> ScopeNode::for_each_lexically_scoped_declaration(ThrowCompletionOrVoidCallback<Declaration const&>&& callback) const
  3430. {
  3431. for (auto& declaration : m_lexical_declarations)
  3432. TRY(callback(declaration));
  3433. return {};
  3434. }
  3435. ThrowCompletionOr<void> ScopeNode::for_each_lexically_declared_name(ThrowCompletionOrVoidCallback<FlyString const&>&& callback) const
  3436. {
  3437. for (auto const& declaration : m_lexical_declarations) {
  3438. TRY(declaration.for_each_bound_name([&](auto const& name) {
  3439. return callback(name);
  3440. }));
  3441. }
  3442. return {};
  3443. }
  3444. ThrowCompletionOr<void> ScopeNode::for_each_var_declared_name(ThrowCompletionOrVoidCallback<FlyString const&>&& callback) const
  3445. {
  3446. for (auto& declaration : m_var_declarations) {
  3447. TRY(declaration.for_each_bound_name([&](auto const& name) {
  3448. return callback(name);
  3449. }));
  3450. }
  3451. return {};
  3452. }
  3453. ThrowCompletionOr<void> ScopeNode::for_each_var_function_declaration_in_reverse_order(ThrowCompletionOrVoidCallback<FunctionDeclaration const&>&& callback) const
  3454. {
  3455. for (ssize_t i = m_var_declarations.size() - 1; i >= 0; i--) {
  3456. auto& declaration = m_var_declarations[i];
  3457. if (is<FunctionDeclaration>(declaration))
  3458. TRY(callback(static_cast<FunctionDeclaration const&>(declaration)));
  3459. }
  3460. return {};
  3461. }
  3462. ThrowCompletionOr<void> ScopeNode::for_each_var_scoped_variable_declaration(ThrowCompletionOrVoidCallback<VariableDeclaration const&>&& callback) const
  3463. {
  3464. for (auto& declaration : m_var_declarations) {
  3465. if (!is<FunctionDeclaration>(declaration)) {
  3466. VERIFY(is<VariableDeclaration>(declaration));
  3467. TRY(callback(static_cast<VariableDeclaration const&>(declaration)));
  3468. }
  3469. }
  3470. return {};
  3471. }
  3472. ThrowCompletionOr<void> ScopeNode::for_each_function_hoistable_with_annexB_extension(ThrowCompletionOrVoidCallback<FunctionDeclaration&>&& callback) const
  3473. {
  3474. for (auto& function : m_functions_hoistable_with_annexB_extension) {
  3475. // We need const_cast here since it might have to set a property on function declaration.
  3476. TRY(callback(const_cast<FunctionDeclaration&>(function)));
  3477. }
  3478. return {};
  3479. }
  3480. void ScopeNode::add_lexical_declaration(NonnullRefPtr<Declaration> declaration)
  3481. {
  3482. m_lexical_declarations.append(move(declaration));
  3483. }
  3484. void ScopeNode::add_var_scoped_declaration(NonnullRefPtr<Declaration> declaration)
  3485. {
  3486. m_var_declarations.append(move(declaration));
  3487. }
  3488. void ScopeNode::add_hoisted_function(NonnullRefPtr<FunctionDeclaration> declaration)
  3489. {
  3490. m_functions_hoistable_with_annexB_extension.append(move(declaration));
  3491. }
  3492. // 16.2.1.11 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-module-semantics-runtime-semantics-evaluation
  3493. Completion ImportStatement::execute(Interpreter& interpreter, GlobalObject&) const
  3494. {
  3495. InterpreterNodeScope node_scope { interpreter, *this };
  3496. // 1. Return NormalCompletion(empty).
  3497. return normal_completion({});
  3498. }
  3499. FlyString ExportStatement::local_name_for_default = "*default*";
  3500. // 16.2.3.7 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-exports-runtime-semantics-evaluation
  3501. Completion ExportStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3502. {
  3503. InterpreterNodeScope node_scope { interpreter, *this };
  3504. if (!is_default_export()) {
  3505. if (m_statement) {
  3506. // 1. Return the result of evaluating <Thing>.
  3507. return m_statement->execute(interpreter, global_object);
  3508. }
  3509. // 1. Return NormalCompletion(empty).
  3510. return normal_completion({});
  3511. }
  3512. VERIFY(m_statement);
  3513. // ExportDeclaration : export default HoistableDeclaration
  3514. if (is<FunctionDeclaration>(*m_statement)) {
  3515. // 1. Return the result of evaluating HoistableDeclaration.
  3516. return m_statement->execute(interpreter, global_object);
  3517. }
  3518. // ExportDeclaration : export default ClassDeclaration
  3519. // ClassDeclaration: class BindingIdentifier[?Yield, ?Await] ClassTail[?Yield, ?Await]
  3520. if (is<ClassDeclaration>(*m_statement)) {
  3521. auto const& class_declaration = static_cast<ClassDeclaration const&>(*m_statement);
  3522. // 1. Let value be ? BindingClassDeclarationEvaluation of ClassDeclaration.
  3523. auto value = TRY(binding_class_declaration_evaluation(interpreter, global_object, class_declaration.m_class_expression));
  3524. // 2. Let className be the sole element of BoundNames of ClassDeclaration.
  3525. // 3. If className is "*default*", then
  3526. // Note: We never go into step 3. since a ClassDeclaration always has a name and "*default*" is not a class name.
  3527. (void)value;
  3528. // 4. Return NormalCompletion(empty).
  3529. return normal_completion({});
  3530. }
  3531. // ExportDeclaration : export default ClassDeclaration
  3532. // ClassDeclaration: [+Default] class ClassTail [?Yield, ?Await]
  3533. if (is<ClassExpression>(*m_statement)) {
  3534. auto& class_expression = static_cast<ClassExpression const&>(*m_statement);
  3535. // 1. Let value be ? BindingClassDeclarationEvaluation of ClassDeclaration.
  3536. auto value = TRY(binding_class_declaration_evaluation(interpreter, global_object, class_expression));
  3537. // 2. Let className be the sole element of BoundNames of ClassDeclaration.
  3538. // 3. If className is "*default*", then
  3539. if (!class_expression.has_name()) {
  3540. // Note: This can only occur if the class does not have a name since "*default*" is normally not valid.
  3541. // a. Let env be the running execution context's LexicalEnvironment.
  3542. auto* env = interpreter.lexical_environment();
  3543. // b. Perform ? InitializeBoundName("*default*", value, env).
  3544. TRY(initialize_bound_name(global_object, ExportStatement::local_name_for_default, value, env));
  3545. }
  3546. // 4. Return NormalCompletion(empty).
  3547. return normal_completion({});
  3548. }
  3549. // ExportDeclaration : export default AssignmentExpression ;
  3550. // 1. If IsAnonymousFunctionDefinition(AssignmentExpression) is true, then
  3551. // a. Let value be ? NamedEvaluation of AssignmentExpression with argument "default".
  3552. // 2. Else,
  3553. // a. Let rhs be the result of evaluating AssignmentExpression.
  3554. // b. Let value be ? GetValue(rhs).
  3555. auto value = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, *m_statement, "default"));
  3556. // 3. Let env be the running execution context's LexicalEnvironment.
  3557. auto* env = interpreter.lexical_environment();
  3558. // 4. Perform ? InitializeBoundName("*default*", value, env).
  3559. TRY(initialize_bound_name(global_object, ExportStatement::local_name_for_default, value, env));
  3560. // 5. Return NormalCompletion(empty).
  3561. return normal_completion({});
  3562. }
  3563. static void dump_assert_clauses(ModuleRequest const& request)
  3564. {
  3565. if (!request.assertions.is_empty()) {
  3566. out("[ ");
  3567. for (auto& assertion : request.assertions)
  3568. out("{}: {}, ", assertion.key, assertion.value);
  3569. out(" ]");
  3570. }
  3571. }
  3572. void ExportStatement::dump(int indent) const
  3573. {
  3574. ASTNode::dump(indent);
  3575. print_indent(indent + 1);
  3576. outln("(ExportEntries)");
  3577. auto string_or_null = [](String const& string) -> String {
  3578. if (string.is_empty()) {
  3579. return "null";
  3580. }
  3581. return String::formatted("\"{}\"", string);
  3582. };
  3583. for (auto& entry : m_entries) {
  3584. print_indent(indent + 2);
  3585. out("ExportName: {}, ImportName: {}, LocalName: {}, ModuleRequest: ",
  3586. string_or_null(entry.export_name),
  3587. entry.is_module_request() ? string_or_null(entry.local_or_import_name) : "null",
  3588. entry.is_module_request() ? "null" : string_or_null(entry.local_or_import_name));
  3589. if (entry.is_module_request()) {
  3590. out("{}", entry.m_module_request->module_specifier);
  3591. dump_assert_clauses(*entry.m_module_request);
  3592. outln();
  3593. } else {
  3594. outln("null");
  3595. }
  3596. }
  3597. if (m_statement) {
  3598. print_indent(indent + 1);
  3599. outln("(Statement)");
  3600. m_statement->dump(indent + 2);
  3601. }
  3602. }
  3603. void ImportStatement::dump(int indent) const
  3604. {
  3605. ASTNode::dump(indent);
  3606. print_indent(indent + 1);
  3607. if (m_entries.is_empty()) {
  3608. // direct from "module" import
  3609. outln("Entire module '{}'", m_module_request.module_specifier);
  3610. dump_assert_clauses(m_module_request);
  3611. } else {
  3612. outln("(ExportEntries) from {}", m_module_request.module_specifier);
  3613. dump_assert_clauses(m_module_request);
  3614. for (auto& entry : m_entries) {
  3615. print_indent(indent + 2);
  3616. outln("ImportName: {}, LocalName: {}", entry.import_name, entry.local_name);
  3617. }
  3618. }
  3619. }
  3620. bool ExportStatement::has_export(FlyString const& export_name) const
  3621. {
  3622. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  3623. return entry.export_name == export_name;
  3624. });
  3625. }
  3626. bool ImportStatement::has_bound_name(FlyString const& name) const
  3627. {
  3628. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  3629. return entry.local_name == name;
  3630. });
  3631. }
  3632. // 14.2.3 BlockDeclarationInstantiation ( code, env ), https://tc39.es/ecma262/#sec-blockdeclarationinstantiation
  3633. void ScopeNode::block_declaration_instantiation(GlobalObject& global_object, Environment* environment) const
  3634. {
  3635. // See also B.3.2.6 Changes to BlockDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-blockdeclarationinstantiation
  3636. VERIFY(environment);
  3637. auto* private_environment = global_object.vm().running_execution_context().private_environment;
  3638. // Note: All the calls here are ! and thus we do not need to TRY this callback.
  3639. for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  3640. auto is_constant_declaration = declaration.is_constant_declaration();
  3641. declaration.for_each_bound_name([&](auto const& name) {
  3642. if (is_constant_declaration) {
  3643. MUST(environment->create_immutable_binding(global_object, name, true));
  3644. } else {
  3645. if (!MUST(environment->has_binding(name)))
  3646. MUST(environment->create_mutable_binding(global_object, name, false));
  3647. }
  3648. });
  3649. if (is<FunctionDeclaration>(declaration)) {
  3650. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  3651. auto* function = ECMAScriptFunctionObject::create(global_object, function_declaration.name(), function_declaration.source_text(), function_declaration.body(), function_declaration.parameters(), function_declaration.function_length(), environment, private_environment, function_declaration.kind(), function_declaration.is_strict_mode(), function_declaration.might_need_arguments_object(), function_declaration.contains_direct_call_to_eval());
  3652. VERIFY(is<DeclarativeEnvironment>(*environment));
  3653. static_cast<DeclarativeEnvironment&>(*environment).initialize_or_set_mutable_binding({}, global_object, function_declaration.name(), function);
  3654. }
  3655. });
  3656. }
  3657. // 16.1.7 GlobalDeclarationInstantiation ( script, env ), https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  3658. ThrowCompletionOr<void> Program::global_declaration_instantiation(Interpreter& interpreter, GlobalObject& global_object, GlobalEnvironment& global_environment) const
  3659. {
  3660. // 1. Let lexNames be the LexicallyDeclaredNames of script.
  3661. // 2. Let varNames be the VarDeclaredNames of script.
  3662. // 3. For each element name of lexNames, do
  3663. TRY(for_each_lexically_declared_name([&](FlyString const& name) -> ThrowCompletionOr<void> {
  3664. // a. If env.HasVarDeclaration(name) is true, throw a SyntaxError exception.
  3665. if (global_environment.has_var_declaration(name))
  3666. return interpreter.vm().throw_completion<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  3667. // b. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  3668. if (global_environment.has_lexical_declaration(name))
  3669. return interpreter.vm().throw_completion<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  3670. // c. Let hasRestrictedGlobal be ? env.HasRestrictedGlobalProperty(name).
  3671. auto has_restricted_global = TRY(global_environment.has_restricted_global_property(name));
  3672. // d. If hasRestrictedGlobal is true, throw a SyntaxError exception.
  3673. if (has_restricted_global)
  3674. return interpreter.vm().throw_completion<SyntaxError>(global_object, ErrorType::RestrictedGlobalProperty, name);
  3675. return {};
  3676. }));
  3677. // 4. For each element name of varNames, do
  3678. TRY(for_each_var_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
  3679. // a. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  3680. if (global_environment.has_lexical_declaration(name))
  3681. return interpreter.vm().throw_completion<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  3682. return {};
  3683. }));
  3684. // 5. Let varDeclarations be the VarScopedDeclarations of script.
  3685. // 6. Let functionsToInitialize be a new empty List.
  3686. Vector<FunctionDeclaration const&> functions_to_initialize;
  3687. // 7. Let declaredFunctionNames be a new empty List.
  3688. HashTable<FlyString> declared_function_names;
  3689. // 8. For each element d of varDeclarations, in reverse List order, do
  3690. TRY(for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) -> ThrowCompletionOr<void> {
  3691. // a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then
  3692. // i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
  3693. // Note: This is checked in for_each_var_function_declaration_in_reverse_order.
  3694. // ii. NOTE: If there are multiple function declarations for the same name, the last declaration is used.
  3695. // iii. Let fn be the sole element of the BoundNames of d.
  3696. // iv. If fn is not an element of declaredFunctionNames, then
  3697. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  3698. return {};
  3699. // 1. Let fnDefinable be ? env.CanDeclareGlobalFunction(fn).
  3700. auto function_definable = TRY(global_environment.can_declare_global_function(function.name()));
  3701. // 2. If fnDefinable is false, throw a TypeError exception.
  3702. if (!function_definable)
  3703. return interpreter.vm().throw_completion<TypeError>(global_object, ErrorType::CannotDeclareGlobalFunction, function.name());
  3704. // 3. Append fn to declaredFunctionNames.
  3705. // Note: Already done in step iv. above.
  3706. // 4. Insert d as the first element of functionsToInitialize.
  3707. functions_to_initialize.append(function);
  3708. return {};
  3709. }));
  3710. // 9. Let declaredVarNames be a new empty List.
  3711. HashTable<FlyString> declared_var_names;
  3712. // 10. For each element d of varDeclarations, do
  3713. TRY(for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
  3714. // a. If d is a VariableDeclaration, a ForBinding, or a BindingIdentifier, then
  3715. // Note: This is done in for_each_var_scoped_variable_declaration.
  3716. // i. For each String vn of the BoundNames of d, do
  3717. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  3718. // 1. If vn is not an element of declaredFunctionNames, then
  3719. if (declared_function_names.contains(name))
  3720. return {};
  3721. // a. Let vnDefinable be ? env.CanDeclareGlobalVar(vn).
  3722. auto var_definable = TRY(global_environment.can_declare_global_var(name));
  3723. // b. If vnDefinable is false, throw a TypeError exception.
  3724. if (!var_definable)
  3725. return interpreter.vm().throw_completion<TypeError>(global_object, ErrorType::CannotDeclareGlobalVariable, name);
  3726. // c. If vn is not an element of declaredVarNames, then
  3727. // i. Append vn to declaredVarNames.
  3728. declared_var_names.set(name);
  3729. return {};
  3730. });
  3731. }));
  3732. // 11. NOTE: No abnormal terminations occur after this algorithm step if the global object is an ordinary object. However, if the global object is a Proxy exotic object it may exhibit behaviours that cause abnormal terminations in some of the following steps.
  3733. // 12. NOTE: Annex B.3.2.2 adds additional steps at this point.
  3734. // 12. Let strict be IsStrict of script.
  3735. // 13. If strict is false, then
  3736. if (!m_is_strict_mode) {
  3737. // a. Let declaredFunctionOrVarNames be the list-concatenation of declaredFunctionNames and declaredVarNames.
  3738. // b. For each FunctionDeclaration f that is directly contained in the StatementList of a Block, CaseClause, or DefaultClause Contained within script, do
  3739. TRY(for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) -> ThrowCompletionOr<void> {
  3740. // i. Let F be StringValue of the BindingIdentifier of f.
  3741. auto& function_name = function_declaration.name();
  3742. // ii. If replacing the FunctionDeclaration f with a VariableStatement that has F as a BindingIdentifier would not produce any Early Errors for script, then
  3743. // Note: This step is already performed during parsing and for_each_function_hoistable_with_annexB_extension so this always passes here.
  3744. // 1. If env.HasLexicalDeclaration(F) is false, then
  3745. if (global_environment.has_lexical_declaration(function_name))
  3746. return {};
  3747. // a. Let fnDefinable be ? env.CanDeclareGlobalVar(F).
  3748. auto function_definable = TRY(global_environment.can_declare_global_function(function_name));
  3749. // b. If fnDefinable is true, then
  3750. if (!function_definable)
  3751. return {};
  3752. // i. NOTE: A var binding for F is only instantiated here if it is neither a VarDeclaredName nor the name of another FunctionDeclaration.
  3753. // ii. If declaredFunctionOrVarNames does not contain F, then
  3754. if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
  3755. // i. Perform ? env.CreateGlobalVarBinding(F, false).
  3756. TRY(global_environment.create_global_var_binding(function_name, false));
  3757. // ii. Append F to declaredFunctionOrVarNames.
  3758. declared_function_names.set(function_name);
  3759. }
  3760. // iii. When the FunctionDeclaration f is evaluated, perform the following steps in place of the FunctionDeclaration Evaluation algorithm provided in 15.2.6:
  3761. // i. Let genv be the running execution context's VariableEnvironment.
  3762. // ii. Let benv be the running execution context's LexicalEnvironment.
  3763. // iii. Let fobj be ! benv.GetBindingValue(F, false).
  3764. // iv. Perform ? genv.SetMutableBinding(F, fobj, false).
  3765. // v. Return NormalCompletion(empty).
  3766. function_declaration.set_should_do_additional_annexB_steps();
  3767. return {};
  3768. }));
  3769. // We should not use declared function names below here anymore since these functions are not in there in the spec.
  3770. declared_function_names.clear();
  3771. }
  3772. // 13. Let lexDeclarations be the LexicallyScopedDeclarations of script.
  3773. // 14. Let privateEnv be null.
  3774. PrivateEnvironment* private_environment = nullptr;
  3775. // 15. For each element d of lexDeclarations, do
  3776. TRY(for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  3777. // a. NOTE: Lexically declared names are only instantiated here but not initialized.
  3778. // b. For each element dn of the BoundNames of d, do
  3779. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  3780. // i. If IsConstantDeclaration of d is true, then
  3781. if (declaration.is_constant_declaration()) {
  3782. // 1. Perform ? env.CreateImmutableBinding(dn, true).
  3783. TRY(global_environment.create_immutable_binding(global_object, name, true));
  3784. }
  3785. // ii. Else,
  3786. else {
  3787. // 1. Perform ? env.CreateMutableBinding(dn, false).
  3788. TRY(global_environment.create_mutable_binding(global_object, name, false));
  3789. }
  3790. return {};
  3791. });
  3792. }));
  3793. // 16. For each Parse Node f of functionsToInitialize, do
  3794. for (auto& declaration : functions_to_initialize) {
  3795. // a. Let fn be the sole element of the BoundNames of f.
  3796. // b. Let fo be InstantiateFunctionObject of f with arguments env and privateEnv.
  3797. auto* function = ECMAScriptFunctionObject::create(global_object, declaration.name(), declaration.source_text(), declaration.body(), declaration.parameters(), declaration.function_length(), &global_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object(), declaration.contains_direct_call_to_eval());
  3798. // c. Perform ? env.CreateGlobalFunctionBinding(fn, fo, false).
  3799. TRY(global_environment.create_global_function_binding(declaration.name(), function, false));
  3800. }
  3801. // 17. For each String vn of declaredVarNames, do
  3802. for (auto& var_name : declared_var_names) {
  3803. // a. Perform ? env.CreateGlobalVarBinding(vn, false).
  3804. TRY(global_environment.create_global_var_binding(var_name, false));
  3805. }
  3806. // 18. Return NormalCompletion(empty).
  3807. return {};
  3808. }
  3809. ModuleRequest::ModuleRequest(FlyString module_specifier_, Vector<Assertion> assertions_)
  3810. : module_specifier(move(module_specifier_))
  3811. , assertions(move(assertions_))
  3812. {
  3813. // Perform step 10.e. from EvaluateImportCall, https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call
  3814. // or step 2. from 2.7 Static Semantics: AssertClauseToAssertions, https://tc39.es/proposal-import-assertions/#sec-assert-clause-to-assertions
  3815. // e. / 2. Sort assertions by the code point order of the [[Key]] of each element.
  3816. // NOTE: This sorting is observable only in that hosts are prohibited from distinguishing among assertions by the order they occur in.
  3817. quick_sort(assertions, [](Assertion const& lhs, Assertion const& rhs) {
  3818. return lhs.key < rhs.key;
  3819. });
  3820. }
  3821. }