AST.cpp 190 KB

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