AST.cpp 191 KB

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