AST.cpp 186 KB

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