AST.cpp 181 KB

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