AST.cpp 191 KB

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