AST.cpp 202 KB

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