AST.cpp 190 KB

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