AST.cpp 202 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977
  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;
  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(), 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. if (m_cached_environment_coordinate.index == EnvironmentCoordinate::global_marker) {
  1220. environment = &interpreter.vm().current_realm()->global_environment();
  1221. } else {
  1222. environment = interpreter.vm().running_execution_context().lexical_environment;
  1223. for (size_t i = 0; i < m_cached_environment_coordinate.hops; ++i)
  1224. environment = environment->outer_environment();
  1225. VERIFY(environment);
  1226. VERIFY(environment->is_declarative_environment());
  1227. }
  1228. if (!environment->is_permanently_screwed_by_eval()) {
  1229. return Reference { *environment, string(), interpreter.vm().in_strict_mode(), m_cached_environment_coordinate };
  1230. }
  1231. m_cached_environment_coordinate = {};
  1232. }
  1233. auto reference = TRY(interpreter.vm().resolve_binding(string()));
  1234. if (reference.environment_coordinate().has_value())
  1235. m_cached_environment_coordinate = reference.environment_coordinate().value();
  1236. return reference;
  1237. }
  1238. ThrowCompletionOr<Reference> MemberExpression::to_reference(Interpreter& interpreter) const
  1239. {
  1240. auto& vm = interpreter.vm();
  1241. // 13.3.7.1 Runtime Semantics: Evaluation
  1242. // SuperProperty : super [ Expression ]
  1243. // SuperProperty : super . IdentifierName
  1244. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  1245. if (is<SuperExpression>(object())) {
  1246. // 1. Let env be GetThisEnvironment().
  1247. auto environment = get_this_environment(vm);
  1248. // 2. Let actualThis be ? env.GetThisBinding().
  1249. auto actual_this = TRY(environment->get_this_binding(vm));
  1250. PropertyKey property_key;
  1251. if (is_computed()) {
  1252. // SuperProperty : super [ Expression ]
  1253. // 3. Let propertyNameReference be the result of evaluating Expression.
  1254. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  1255. auto property_name_value = TRY(m_property->execute(interpreter)).release_value();
  1256. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  1257. property_key = TRY(property_name_value.to_property_key(vm));
  1258. } else {
  1259. // SuperProperty : super . IdentifierName
  1260. // 3. Let propertyKey be StringValue of IdentifierName.
  1261. VERIFY(is<Identifier>(property()));
  1262. property_key = static_cast<Identifier const&>(property()).string();
  1263. }
  1264. // 6. If the source text matched by this SuperProperty is strict mode code, let strict be true; else let strict be false.
  1265. bool strict = interpreter.vm().in_strict_mode();
  1266. // 7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  1267. return TRY(make_super_property_reference(vm, actual_this, property_key, strict));
  1268. }
  1269. auto base_reference = TRY(m_object->to_reference(interpreter));
  1270. Value base_value;
  1271. if (base_reference.is_valid_reference())
  1272. base_value = TRY(base_reference.get_value(vm));
  1273. else
  1274. base_value = TRY(m_object->execute(interpreter)).release_value();
  1275. VERIFY(!base_value.is_empty());
  1276. // From here on equivalent to
  1277. // 13.3.4 EvaluatePropertyAccessWithIdentifierKey ( baseValue, identifierName, strict ), https://tc39.es/ecma262/#sec-evaluate-property-access-with-identifier-key
  1278. PropertyKey property_key;
  1279. if (is_computed()) {
  1280. // Weird order which I can't quite find from the specs.
  1281. auto value = TRY(m_property->execute(interpreter)).release_value();
  1282. VERIFY(!value.is_empty());
  1283. TRY(require_object_coercible(vm, base_value));
  1284. property_key = TRY(value.to_property_key(vm));
  1285. } else if (is<PrivateIdentifier>(*m_property)) {
  1286. auto& private_identifier = static_cast<PrivateIdentifier const&>(*m_property);
  1287. return make_private_reference(interpreter.vm(), base_value, private_identifier.string());
  1288. } else {
  1289. property_key = verify_cast<Identifier>(*m_property).string();
  1290. TRY(require_object_coercible(vm, base_value));
  1291. }
  1292. if (!property_key.is_valid())
  1293. return Reference {};
  1294. auto strict = interpreter.vm().in_strict_mode();
  1295. return Reference { base_value, move(property_key), {}, strict };
  1296. }
  1297. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  1298. // 13.5.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-void-operator-runtime-semantics-evaluation
  1299. // 13.5.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-typeof-operator-runtime-semantics-evaluation
  1300. // 13.5.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unary-plus-operator-runtime-semantics-evaluation
  1301. // 13.5.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unary-minus-operator-runtime-semantics-evaluation
  1302. // 13.5.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-bitwise-not-operator-runtime-semantics-evaluation
  1303. // 13.5.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-logical-not-operator-runtime-semantics-evaluation
  1304. Completion UnaryExpression::execute(Interpreter& interpreter) const
  1305. {
  1306. InterpreterNodeScope node_scope { interpreter, *this };
  1307. auto& vm = interpreter.vm();
  1308. if (m_op == UnaryOp::Delete) {
  1309. auto reference = TRY(m_lhs->to_reference(interpreter));
  1310. return Value(TRY(reference.delete_(vm)));
  1311. }
  1312. Value lhs_result;
  1313. if (m_op == UnaryOp::Typeof && is<Identifier>(*m_lhs)) {
  1314. auto reference = TRY(m_lhs->to_reference(interpreter));
  1315. if (reference.is_unresolvable())
  1316. lhs_result = js_undefined();
  1317. else
  1318. lhs_result = TRY(reference.get_value(vm));
  1319. VERIFY(!lhs_result.is_empty());
  1320. } else {
  1321. // 1. Let expr be the result of evaluating UnaryExpression.
  1322. lhs_result = TRY(m_lhs->execute(interpreter)).release_value();
  1323. }
  1324. switch (m_op) {
  1325. case UnaryOp::BitwiseNot:
  1326. return TRY(bitwise_not(vm, lhs_result));
  1327. case UnaryOp::Not:
  1328. return Value(!lhs_result.to_boolean());
  1329. case UnaryOp::Plus:
  1330. return TRY(unary_plus(vm, lhs_result));
  1331. case UnaryOp::Minus:
  1332. return TRY(unary_minus(vm, lhs_result));
  1333. case UnaryOp::Typeof:
  1334. return Value { MUST_OR_THROW_OOM(PrimitiveString::create(vm, lhs_result.typeof())) };
  1335. case UnaryOp::Void:
  1336. return js_undefined();
  1337. case UnaryOp::Delete:
  1338. VERIFY_NOT_REACHED();
  1339. }
  1340. VERIFY_NOT_REACHED();
  1341. }
  1342. Completion SuperExpression::execute(Interpreter&) const
  1343. {
  1344. // The semantics for SuperExpression are handled in CallExpression and SuperCall.
  1345. VERIFY_NOT_REACHED();
  1346. }
  1347. Completion ClassElement::execute(Interpreter&) const
  1348. {
  1349. // Note: The semantics of class element are handled in class_element_evaluation
  1350. VERIFY_NOT_REACHED();
  1351. }
  1352. static ThrowCompletionOr<ClassElementName> class_key_to_property_name(Interpreter& interpreter, Expression const& key)
  1353. {
  1354. auto& vm = interpreter.vm();
  1355. if (is<PrivateIdentifier>(key)) {
  1356. auto& private_identifier = static_cast<PrivateIdentifier const&>(key);
  1357. auto private_environment = interpreter.vm().running_execution_context().private_environment;
  1358. VERIFY(private_environment);
  1359. return ClassElementName { private_environment->resolve_private_identifier(private_identifier.string()) };
  1360. }
  1361. auto prop_key = TRY(key.execute(interpreter)).release_value();
  1362. if (prop_key.is_object())
  1363. prop_key = TRY(prop_key.to_primitive(vm, Value::PreferredType::String));
  1364. auto property_key = TRY(PropertyKey::from_value(vm, prop_key));
  1365. return ClassElementName { property_key };
  1366. }
  1367. // 15.4.5 Runtime Semantics: MethodDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-methoddefinitionevaluation
  1368. ThrowCompletionOr<ClassElement::ClassValue> ClassMethod::class_element_evaluation(Interpreter& interpreter, Object& target) const
  1369. {
  1370. auto property_key_or_private_name = TRY(class_key_to_property_name(interpreter, *m_key));
  1371. auto method_value = TRY(m_function->execute(interpreter)).release_value();
  1372. auto function_handle = make_handle(&method_value.as_function());
  1373. auto& method_function = static_cast<ECMAScriptFunctionObject&>(method_value.as_function());
  1374. method_function.make_method(target);
  1375. auto set_function_name = [&](DeprecatedString prefix = "") {
  1376. auto name = property_key_or_private_name.visit(
  1377. [&](PropertyKey const& property_key) -> DeprecatedString {
  1378. if (property_key.is_symbol()) {
  1379. auto description = property_key.as_symbol()->description();
  1380. if (!description.has_value() || description->is_empty())
  1381. return "";
  1382. return DeprecatedString::formatted("[{}]", *description);
  1383. } else {
  1384. return property_key.to_string();
  1385. }
  1386. },
  1387. [&](PrivateName const& private_name) -> DeprecatedString {
  1388. return private_name.description;
  1389. });
  1390. update_function_name(method_value, DeprecatedString::formatted("{}{}{}", prefix, prefix.is_empty() ? "" : " ", name));
  1391. };
  1392. if (property_key_or_private_name.has<PropertyKey>()) {
  1393. auto& property_key = property_key_or_private_name.get<PropertyKey>();
  1394. switch (kind()) {
  1395. case ClassMethod::Kind::Method:
  1396. set_function_name();
  1397. TRY(target.define_property_or_throw(property_key, { .value = method_value, .writable = true, .enumerable = false, .configurable = true }));
  1398. break;
  1399. case ClassMethod::Kind::Getter:
  1400. set_function_name("get");
  1401. TRY(target.define_property_or_throw(property_key, { .get = &method_function, .enumerable = true, .configurable = true }));
  1402. break;
  1403. case ClassMethod::Kind::Setter:
  1404. set_function_name("set");
  1405. TRY(target.define_property_or_throw(property_key, { .set = &method_function, .enumerable = true, .configurable = true }));
  1406. break;
  1407. default:
  1408. VERIFY_NOT_REACHED();
  1409. }
  1410. return ClassValue { normal_completion({}) };
  1411. } else {
  1412. auto& private_name = property_key_or_private_name.get<PrivateName>();
  1413. switch (kind()) {
  1414. case Kind::Method:
  1415. set_function_name();
  1416. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Method, make_handle(method_value) } };
  1417. case Kind::Getter:
  1418. set_function_name("get");
  1419. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Accessor, make_handle(Value(Accessor::create(interpreter.vm(), &method_function, nullptr))) } };
  1420. case Kind::Setter:
  1421. set_function_name("set");
  1422. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Accessor, make_handle(Value(Accessor::create(interpreter.vm(), nullptr, &method_function))) } };
  1423. default:
  1424. VERIFY_NOT_REACHED();
  1425. }
  1426. }
  1427. }
  1428. Completion ClassFieldInitializerStatement::execute(Interpreter& interpreter) const
  1429. {
  1430. // 1. Assert: argumentsList is empty.
  1431. VERIFY(interpreter.vm().argument_count() == 0);
  1432. // 2. Assert: functionObject.[[ClassFieldInitializerName]] is not empty.
  1433. VERIFY(!m_class_field_identifier_name.is_empty());
  1434. // 3. If IsAnonymousFunctionDefinition(AssignmentExpression) is true, then
  1435. // a. Let value be ? NamedEvaluation of Initializer with argument functionObject.[[ClassFieldInitializerName]].
  1436. // 4. Else,
  1437. // a. Let rhs be the result of evaluating AssignmentExpression.
  1438. // b. Let value be ? GetValue(rhs).
  1439. auto value = TRY(interpreter.vm().named_evaluation_if_anonymous_function(m_expression, m_class_field_identifier_name));
  1440. // 5. Return Completion Record { [[Type]]: return, [[Value]]: value, [[Target]]: empty }.
  1441. return { Completion::Type::Return, value, {} };
  1442. }
  1443. void ClassFieldInitializerStatement::dump(int) const
  1444. {
  1445. // This should not be dumped as it is never part of an actual AST.
  1446. VERIFY_NOT_REACHED();
  1447. }
  1448. // 15.7.10 Runtime Semantics: ClassFieldDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classfielddefinitionevaluation
  1449. ThrowCompletionOr<ClassElement::ClassValue> ClassField::class_element_evaluation(Interpreter& interpreter, Object& target) const
  1450. {
  1451. auto& vm = interpreter.vm();
  1452. auto& realm = *vm.current_realm();
  1453. auto property_key_or_private_name = TRY(class_key_to_property_name(interpreter, *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, interpreter.lexical_environment(), interpreter.vm().running_execution_context().private_environment, FunctionKind::Normal, true, false, m_contains_direct_call_to_eval, false, property_key_or_private_name));
  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(Interpreter& interpreter, Object& home_object) const
  1492. {
  1493. auto& vm = interpreter.vm();
  1494. auto& realm = *vm.current_realm();
  1495. // 1. Let lex be the running execution context's LexicalEnvironment.
  1496. auto lexical_environment = interpreter.vm().running_execution_context().lexical_environment;
  1497. // 2. Let privateEnv be the running execution context's PrivateEnvironment.
  1498. auto private_environment = interpreter.vm().running_execution_context().private_environment;
  1499. // 3. Let sourceText be the empty sequence of Unicode code points.
  1500. // 4. Let formalParameters be an instance of the production FormalParameters : [empty] .
  1501. // 5. Let bodyFunction be OrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameters, ClassStaticBlockBody, non-lexical-this, lex, privateEnv).
  1502. // Note: The function bodyFunction is never directly accessible to ECMAScript code.
  1503. auto body_function = ECMAScriptFunctionObject::create(realm, DeprecatedString::empty(), DeprecatedString::empty(), *m_function_body, {}, 0, lexical_environment, private_environment, FunctionKind::Normal, true, false, m_contains_direct_call_to_eval, false);
  1504. // 6. Perform MakeMethod(bodyFunction, homeObject).
  1505. body_function->make_method(home_object);
  1506. // 7. Return the ClassStaticBlockDefinition Record { [[BodyFunction]]: bodyFunction }.
  1507. return ClassValue { normal_completion(body_function) };
  1508. }
  1509. // 15.7.16 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-class-definitions-runtime-semantics-evaluation
  1510. // ClassExpression : class BindingIdentifier ClassTail
  1511. Completion ClassExpression::execute(Interpreter& interpreter) const
  1512. {
  1513. InterpreterNodeScope node_scope { interpreter, *this };
  1514. // 1. Let className be StringValue of BindingIdentifier.
  1515. // 2. Let value be ? ClassDefinitionEvaluation of ClassTail with arguments className and className.
  1516. auto* value = TRY(class_definition_evaluation(interpreter, m_name, m_name.is_null() ? "" : m_name));
  1517. // 3. Set value.[[SourceText]] to the source text matched by ClassExpression.
  1518. value->set_source_text(m_source_text);
  1519. // 4. Return value.
  1520. return Value { value };
  1521. }
  1522. // 15.7.15 Runtime Semantics: BindingClassDeclarationEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-bindingclassdeclarationevaluation
  1523. static ThrowCompletionOr<Value> binding_class_declaration_evaluation(Interpreter& interpreter, ClassExpression const& class_expression)
  1524. {
  1525. auto& vm = interpreter.vm();
  1526. // ClassDeclaration : class ClassTail
  1527. if (!class_expression.has_name()) {
  1528. // 1. Let value be ? ClassDefinitionEvaluation of ClassTail with arguments undefined and "default".
  1529. auto value = TRY(class_expression.class_definition_evaluation(interpreter, {}, "default"));
  1530. // 2. Set value.[[SourceText]] to the source text matched by ClassDeclaration.
  1531. value->set_source_text(class_expression.source_text());
  1532. // 3. Return value.
  1533. return value;
  1534. }
  1535. // ClassDeclaration : class BindingIdentifier ClassTail
  1536. // 1. Let className be StringValue of BindingIdentifier.
  1537. auto class_name = class_expression.name();
  1538. VERIFY(!class_name.is_empty());
  1539. // 2. Let value be ? ClassDefinitionEvaluation of ClassTail with arguments className and className.
  1540. auto value = TRY(class_expression.class_definition_evaluation(interpreter, class_name, class_name));
  1541. // 3. Set value.[[SourceText]] to the source text matched by ClassDeclaration.
  1542. value->set_source_text(class_expression.source_text());
  1543. // 4. Let env be the running execution context's LexicalEnvironment.
  1544. auto* env = interpreter.lexical_environment();
  1545. // 5. Perform ? InitializeBoundName(className, value, env).
  1546. TRY(initialize_bound_name(vm, class_name, value, env));
  1547. // 6. Return value.
  1548. return value;
  1549. }
  1550. // 15.7.16 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-class-definitions-runtime-semantics-evaluation
  1551. // ClassDeclaration : class BindingIdentifier ClassTail
  1552. Completion ClassDeclaration::execute(Interpreter& interpreter) const
  1553. {
  1554. InterpreterNodeScope node_scope { interpreter, *this };
  1555. // 1. Perform ? BindingClassDeclarationEvaluation of this ClassDeclaration.
  1556. (void)TRY(binding_class_declaration_evaluation(interpreter, m_class_expression));
  1557. // 2. Return empty.
  1558. return Optional<Value> {};
  1559. }
  1560. // 15.7.14 Runtime Semantics: ClassDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classdefinitionevaluation
  1561. ThrowCompletionOr<ECMAScriptFunctionObject*> ClassExpression::class_definition_evaluation(Interpreter& interpreter, DeprecatedFlyString const& binding_name, DeprecatedFlyString const& class_name) const
  1562. {
  1563. auto& vm = interpreter.vm();
  1564. auto& realm = *vm.current_realm();
  1565. auto* environment = vm.lexical_environment();
  1566. VERIFY(environment);
  1567. auto class_environment = new_declarative_environment(*environment);
  1568. // We might not set the lexical environment but we always want to restore it eventually.
  1569. ArmedScopeGuard restore_environment = [&] {
  1570. vm.running_execution_context().lexical_environment = environment;
  1571. };
  1572. if (!binding_name.is_null())
  1573. MUST(class_environment->create_immutable_binding(vm, binding_name, true));
  1574. auto outer_private_environment = vm.running_execution_context().private_environment;
  1575. auto class_private_environment = new_private_environment(vm, outer_private_environment);
  1576. for (auto const& element : m_elements) {
  1577. auto opt_private_name = element->private_bound_identifier();
  1578. if (opt_private_name.has_value())
  1579. class_private_environment->add_private_name({}, opt_private_name.release_value());
  1580. }
  1581. auto proto_parent = GCPtr { realm.intrinsics().object_prototype() };
  1582. auto constructor_parent = realm.intrinsics().function_prototype();
  1583. if (!m_super_class.is_null()) {
  1584. vm.running_execution_context().lexical_environment = class_environment;
  1585. // Note: Since our execute does evaluation and GetValue in once we must check for a valid reference first
  1586. Value super_class;
  1587. auto reference = TRY(m_super_class->to_reference(interpreter));
  1588. if (reference.is_valid_reference()) {
  1589. super_class = TRY(reference.get_value(vm));
  1590. } else {
  1591. super_class = TRY(m_super_class->execute(interpreter)).release_value();
  1592. }
  1593. vm.running_execution_context().lexical_environment = environment;
  1594. if (super_class.is_null()) {
  1595. proto_parent = nullptr;
  1596. } else if (!super_class.is_constructor()) {
  1597. return vm.throw_completion<TypeError>(ErrorType::ClassExtendsValueNotAConstructorOrNull, TRY_OR_THROW_OOM(vm, super_class.to_string_without_side_effects()));
  1598. } else {
  1599. auto super_class_prototype = TRY(super_class.get(vm, vm.names.prototype));
  1600. if (!super_class_prototype.is_null() && !super_class_prototype.is_object())
  1601. return vm.throw_completion<TypeError>(ErrorType::ClassExtendsValueInvalidPrototype, TRY_OR_THROW_OOM(vm, super_class_prototype.to_string_without_side_effects()));
  1602. if (super_class_prototype.is_null())
  1603. proto_parent = nullptr;
  1604. else
  1605. proto_parent = super_class_prototype.as_object();
  1606. constructor_parent = super_class.as_object();
  1607. }
  1608. }
  1609. auto prototype = Object::create(realm, proto_parent);
  1610. VERIFY(prototype);
  1611. vm.running_execution_context().lexical_environment = class_environment;
  1612. vm.running_execution_context().private_environment = class_private_environment;
  1613. ScopeGuard restore_private_environment = [&] {
  1614. vm.running_execution_context().private_environment = outer_private_environment;
  1615. };
  1616. // FIXME: Step 14.a is done in the parser. By using a synthetic super(...args) which does not call @@iterator of %Array.prototype%
  1617. auto class_constructor_value = TRY(m_constructor->execute(interpreter)).release_value();
  1618. update_function_name(class_constructor_value, class_name);
  1619. VERIFY(class_constructor_value.is_function() && is<ECMAScriptFunctionObject>(class_constructor_value.as_function()));
  1620. auto* class_constructor = static_cast<ECMAScriptFunctionObject*>(&class_constructor_value.as_function());
  1621. class_constructor->set_home_object(prototype);
  1622. class_constructor->set_is_class_constructor();
  1623. class_constructor->define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  1624. TRY(class_constructor->internal_set_prototype_of(constructor_parent));
  1625. if (!m_super_class.is_null())
  1626. class_constructor->set_constructor_kind(ECMAScriptFunctionObject::ConstructorKind::Derived);
  1627. prototype->define_direct_property(vm.names.constructor, class_constructor, Attribute::Writable | Attribute::Configurable);
  1628. using StaticElement = Variant<ClassFieldDefinition, Handle<ECMAScriptFunctionObject>>;
  1629. Vector<PrivateElement> static_private_methods;
  1630. Vector<PrivateElement> instance_private_methods;
  1631. Vector<ClassFieldDefinition> instance_fields;
  1632. Vector<StaticElement> static_elements;
  1633. for (auto const& element : m_elements) {
  1634. // Note: All ClassElementEvaluation start with evaluating the name (or we fake it).
  1635. auto element_value = TRY(element->class_element_evaluation(interpreter, element->is_static() ? *class_constructor : *prototype));
  1636. if (element_value.has<PrivateElement>()) {
  1637. auto& container = element->is_static() ? static_private_methods : instance_private_methods;
  1638. auto& private_element = element_value.get<PrivateElement>();
  1639. auto added_to_existing = false;
  1640. // FIXME: We can skip this loop in most cases.
  1641. for (auto& existing : container) {
  1642. if (existing.key == private_element.key) {
  1643. VERIFY(existing.kind == PrivateElement::Kind::Accessor);
  1644. VERIFY(private_element.kind == PrivateElement::Kind::Accessor);
  1645. auto& accessor = private_element.value.value().as_accessor();
  1646. if (!accessor.getter())
  1647. existing.value.value().as_accessor().set_setter(accessor.setter());
  1648. else
  1649. existing.value.value().as_accessor().set_getter(accessor.getter());
  1650. added_to_existing = true;
  1651. }
  1652. }
  1653. if (!added_to_existing)
  1654. container.append(move(element_value.get<PrivateElement>()));
  1655. } else if (auto* class_field_definition_ptr = element_value.get_pointer<ClassFieldDefinition>()) {
  1656. if (element->is_static())
  1657. static_elements.append(move(*class_field_definition_ptr));
  1658. else
  1659. instance_fields.append(move(*class_field_definition_ptr));
  1660. } else if (element->class_element_kind() == ClassElement::ElementKind::StaticInitializer) {
  1661. // We use Completion to hold the ClassStaticBlockDefinition Record.
  1662. VERIFY(element_value.has<Completion>() && element_value.get<Completion>().value().has_value());
  1663. auto& element_object = element_value.get<Completion>().value()->as_object();
  1664. VERIFY(is<ECMAScriptFunctionObject>(element_object));
  1665. static_elements.append(make_handle(static_cast<ECMAScriptFunctionObject*>(&element_object)));
  1666. }
  1667. }
  1668. vm.running_execution_context().lexical_environment = environment;
  1669. restore_environment.disarm();
  1670. if (!binding_name.is_null())
  1671. MUST(class_environment->initialize_binding(vm, binding_name, class_constructor, Environment::InitializeBindingHint::Normal));
  1672. for (auto& field : instance_fields)
  1673. class_constructor->add_field(field);
  1674. for (auto& private_method : instance_private_methods)
  1675. class_constructor->add_private_method(private_method);
  1676. for (auto& method : static_private_methods)
  1677. TRY(class_constructor->private_method_or_accessor_add(move(method)));
  1678. for (auto& element : static_elements) {
  1679. TRY(element.visit(
  1680. [&](ClassFieldDefinition& field) -> ThrowCompletionOr<void> {
  1681. return TRY(class_constructor->define_field(field));
  1682. },
  1683. [&](Handle<ECMAScriptFunctionObject> static_block_function) -> ThrowCompletionOr<void> {
  1684. VERIFY(!static_block_function.is_null());
  1685. // We discard any value returned here.
  1686. TRY(call(vm, *static_block_function.cell(), class_constructor_value));
  1687. return {};
  1688. }));
  1689. }
  1690. return class_constructor;
  1691. }
  1692. void ASTNode::dump(int indent) const
  1693. {
  1694. print_indent(indent);
  1695. outln("{}", class_name());
  1696. }
  1697. void ScopeNode::dump(int indent) const
  1698. {
  1699. ASTNode::dump(indent);
  1700. if (!m_lexical_declarations.is_empty()) {
  1701. print_indent(indent + 1);
  1702. outln("(Lexical declarations)");
  1703. for (auto& declaration : m_lexical_declarations)
  1704. declaration->dump(indent + 2);
  1705. }
  1706. if (!m_var_declarations.is_empty()) {
  1707. print_indent(indent + 1);
  1708. outln("(Variable declarations)");
  1709. for (auto& declaration : m_var_declarations)
  1710. declaration->dump(indent + 2);
  1711. }
  1712. if (!m_functions_hoistable_with_annexB_extension.is_empty()) {
  1713. print_indent(indent + 1);
  1714. outln("(Hoisted functions via annexB extension)");
  1715. for (auto& declaration : m_functions_hoistable_with_annexB_extension)
  1716. declaration->dump(indent + 2);
  1717. }
  1718. if (!m_children.is_empty()) {
  1719. print_indent(indent + 1);
  1720. outln("(Children)");
  1721. for (auto& child : children())
  1722. child->dump(indent + 2);
  1723. }
  1724. }
  1725. void BinaryExpression::dump(int indent) const
  1726. {
  1727. char const* op_string = nullptr;
  1728. switch (m_op) {
  1729. case BinaryOp::Addition:
  1730. op_string = "+";
  1731. break;
  1732. case BinaryOp::Subtraction:
  1733. op_string = "-";
  1734. break;
  1735. case BinaryOp::Multiplication:
  1736. op_string = "*";
  1737. break;
  1738. case BinaryOp::Division:
  1739. op_string = "/";
  1740. break;
  1741. case BinaryOp::Modulo:
  1742. op_string = "%";
  1743. break;
  1744. case BinaryOp::Exponentiation:
  1745. op_string = "**";
  1746. break;
  1747. case BinaryOp::StrictlyEquals:
  1748. op_string = "===";
  1749. break;
  1750. case BinaryOp::StrictlyInequals:
  1751. op_string = "!==";
  1752. break;
  1753. case BinaryOp::LooselyEquals:
  1754. op_string = "==";
  1755. break;
  1756. case BinaryOp::LooselyInequals:
  1757. op_string = "!=";
  1758. break;
  1759. case BinaryOp::GreaterThan:
  1760. op_string = ">";
  1761. break;
  1762. case BinaryOp::GreaterThanEquals:
  1763. op_string = ">=";
  1764. break;
  1765. case BinaryOp::LessThan:
  1766. op_string = "<";
  1767. break;
  1768. case BinaryOp::LessThanEquals:
  1769. op_string = "<=";
  1770. break;
  1771. case BinaryOp::BitwiseAnd:
  1772. op_string = "&";
  1773. break;
  1774. case BinaryOp::BitwiseOr:
  1775. op_string = "|";
  1776. break;
  1777. case BinaryOp::BitwiseXor:
  1778. op_string = "^";
  1779. break;
  1780. case BinaryOp::LeftShift:
  1781. op_string = "<<";
  1782. break;
  1783. case BinaryOp::RightShift:
  1784. op_string = ">>";
  1785. break;
  1786. case BinaryOp::UnsignedRightShift:
  1787. op_string = ">>>";
  1788. break;
  1789. case BinaryOp::In:
  1790. op_string = "in";
  1791. break;
  1792. case BinaryOp::InstanceOf:
  1793. op_string = "instanceof";
  1794. break;
  1795. }
  1796. print_indent(indent);
  1797. outln("{}", class_name());
  1798. m_lhs->dump(indent + 1);
  1799. print_indent(indent + 1);
  1800. outln("{}", op_string);
  1801. m_rhs->dump(indent + 1);
  1802. }
  1803. void LogicalExpression::dump(int indent) const
  1804. {
  1805. char const* op_string = nullptr;
  1806. switch (m_op) {
  1807. case LogicalOp::And:
  1808. op_string = "&&";
  1809. break;
  1810. case LogicalOp::Or:
  1811. op_string = "||";
  1812. break;
  1813. case LogicalOp::NullishCoalescing:
  1814. op_string = "??";
  1815. break;
  1816. }
  1817. print_indent(indent);
  1818. outln("{}", class_name());
  1819. m_lhs->dump(indent + 1);
  1820. print_indent(indent + 1);
  1821. outln("{}", op_string);
  1822. m_rhs->dump(indent + 1);
  1823. }
  1824. void UnaryExpression::dump(int indent) const
  1825. {
  1826. char const* op_string = nullptr;
  1827. switch (m_op) {
  1828. case UnaryOp::BitwiseNot:
  1829. op_string = "~";
  1830. break;
  1831. case UnaryOp::Not:
  1832. op_string = "!";
  1833. break;
  1834. case UnaryOp::Plus:
  1835. op_string = "+";
  1836. break;
  1837. case UnaryOp::Minus:
  1838. op_string = "-";
  1839. break;
  1840. case UnaryOp::Typeof:
  1841. op_string = "typeof ";
  1842. break;
  1843. case UnaryOp::Void:
  1844. op_string = "void ";
  1845. break;
  1846. case UnaryOp::Delete:
  1847. op_string = "delete ";
  1848. break;
  1849. }
  1850. print_indent(indent);
  1851. outln("{}", class_name());
  1852. print_indent(indent + 1);
  1853. outln("{}", op_string);
  1854. m_lhs->dump(indent + 1);
  1855. }
  1856. void CallExpression::dump(int indent) const
  1857. {
  1858. print_indent(indent);
  1859. if (is<NewExpression>(*this))
  1860. outln("CallExpression [new]");
  1861. else
  1862. outln("CallExpression");
  1863. m_callee->dump(indent + 1);
  1864. for (auto& argument : arguments())
  1865. argument.value->dump(indent + 1);
  1866. }
  1867. void SuperCall::dump(int indent) const
  1868. {
  1869. print_indent(indent);
  1870. outln("SuperCall");
  1871. for (auto& argument : m_arguments)
  1872. argument.value->dump(indent + 1);
  1873. }
  1874. void ClassDeclaration::dump(int indent) const
  1875. {
  1876. ASTNode::dump(indent);
  1877. m_class_expression->dump(indent + 1);
  1878. }
  1879. ThrowCompletionOr<void> ClassDeclaration::for_each_bound_name(ThrowCompletionOrVoidCallback<DeprecatedFlyString const&>&& callback) const
  1880. {
  1881. if (m_class_expression->name().is_empty())
  1882. return {};
  1883. return callback(m_class_expression->name());
  1884. }
  1885. void ClassExpression::dump(int indent) const
  1886. {
  1887. print_indent(indent);
  1888. outln("ClassExpression: \"{}\"", m_name);
  1889. print_indent(indent);
  1890. outln("(Constructor)");
  1891. m_constructor->dump(indent + 1);
  1892. if (!m_super_class.is_null()) {
  1893. print_indent(indent);
  1894. outln("(Super Class)");
  1895. m_super_class->dump(indent + 1);
  1896. }
  1897. print_indent(indent);
  1898. outln("(Elements)");
  1899. for (auto& method : m_elements)
  1900. method->dump(indent + 1);
  1901. }
  1902. void ClassMethod::dump(int indent) const
  1903. {
  1904. ASTNode::dump(indent);
  1905. print_indent(indent);
  1906. outln("(Key)");
  1907. m_key->dump(indent + 1);
  1908. char const* kind_string = nullptr;
  1909. switch (m_kind) {
  1910. case Kind::Method:
  1911. kind_string = "Method";
  1912. break;
  1913. case Kind::Getter:
  1914. kind_string = "Getter";
  1915. break;
  1916. case Kind::Setter:
  1917. kind_string = "Setter";
  1918. break;
  1919. }
  1920. print_indent(indent);
  1921. outln("Kind: {}", kind_string);
  1922. print_indent(indent);
  1923. outln("Static: {}", is_static());
  1924. print_indent(indent);
  1925. outln("(Function)");
  1926. m_function->dump(indent + 1);
  1927. }
  1928. void ClassField::dump(int indent) const
  1929. {
  1930. ASTNode::dump(indent);
  1931. print_indent(indent);
  1932. outln("(Key)");
  1933. m_key->dump(indent + 1);
  1934. print_indent(indent);
  1935. outln("Static: {}", is_static());
  1936. if (m_initializer) {
  1937. print_indent(indent);
  1938. outln("(Initializer)");
  1939. m_initializer->dump(indent + 1);
  1940. }
  1941. }
  1942. void StaticInitializer::dump(int indent) const
  1943. {
  1944. ASTNode::dump(indent);
  1945. m_function_body->dump(indent + 1);
  1946. }
  1947. void StringLiteral::dump(int indent) const
  1948. {
  1949. print_indent(indent);
  1950. outln("StringLiteral \"{}\"", m_value);
  1951. }
  1952. void SuperExpression::dump(int indent) const
  1953. {
  1954. print_indent(indent);
  1955. outln("super");
  1956. }
  1957. void NumericLiteral::dump(int indent) const
  1958. {
  1959. print_indent(indent);
  1960. outln("NumericLiteral {}", m_value);
  1961. }
  1962. void BigIntLiteral::dump(int indent) const
  1963. {
  1964. print_indent(indent);
  1965. outln("BigIntLiteral {}", m_value);
  1966. }
  1967. void BooleanLiteral::dump(int indent) const
  1968. {
  1969. print_indent(indent);
  1970. outln("BooleanLiteral {}", m_value);
  1971. }
  1972. void NullLiteral::dump(int indent) const
  1973. {
  1974. print_indent(indent);
  1975. outln("null");
  1976. }
  1977. bool BindingPattern::contains_expression() const
  1978. {
  1979. for (auto& entry : entries) {
  1980. if (entry.initializer)
  1981. return true;
  1982. if (auto binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern const>>(); binding_ptr && (*binding_ptr)->contains_expression())
  1983. return true;
  1984. }
  1985. return false;
  1986. }
  1987. ThrowCompletionOr<void> BindingPattern::for_each_bound_name(ThrowCompletionOrVoidCallback<DeprecatedFlyString const&>&& callback) const
  1988. {
  1989. for (auto const& entry : entries) {
  1990. auto const& alias = entry.alias;
  1991. if (alias.has<NonnullRefPtr<Identifier const>>()) {
  1992. TRY(callback(alias.get<NonnullRefPtr<Identifier const>>()->string()));
  1993. } else if (alias.has<NonnullRefPtr<BindingPattern const>>()) {
  1994. TRY(alias.get<NonnullRefPtr<BindingPattern const>>()->for_each_bound_name(forward<decltype(callback)>(callback)));
  1995. } else {
  1996. auto const& name = entry.name;
  1997. if (name.has<NonnullRefPtr<Identifier const>>())
  1998. TRY(callback(name.get<NonnullRefPtr<Identifier const>>()->string()));
  1999. }
  2000. }
  2001. return {};
  2002. }
  2003. void BindingPattern::dump(int indent) const
  2004. {
  2005. print_indent(indent);
  2006. outln("BindingPattern {}", kind == Kind::Array ? "Array" : "Object");
  2007. for (auto& entry : entries) {
  2008. print_indent(indent + 1);
  2009. outln("(Property)");
  2010. if (kind == Kind::Object) {
  2011. print_indent(indent + 2);
  2012. outln("(Identifier)");
  2013. if (entry.name.has<NonnullRefPtr<Identifier const>>()) {
  2014. entry.name.get<NonnullRefPtr<Identifier const>>()->dump(indent + 3);
  2015. } else {
  2016. entry.name.get<NonnullRefPtr<Expression const>>()->dump(indent + 3);
  2017. }
  2018. } else if (entry.is_elision()) {
  2019. print_indent(indent + 2);
  2020. outln("(Elision)");
  2021. continue;
  2022. }
  2023. print_indent(indent + 2);
  2024. outln("(Pattern{})", entry.is_rest ? " rest=true" : "");
  2025. if (entry.alias.has<NonnullRefPtr<Identifier const>>()) {
  2026. entry.alias.get<NonnullRefPtr<Identifier const>>()->dump(indent + 3);
  2027. } else if (entry.alias.has<NonnullRefPtr<BindingPattern const>>()) {
  2028. entry.alias.get<NonnullRefPtr<BindingPattern const>>()->dump(indent + 3);
  2029. } else if (entry.alias.has<NonnullRefPtr<MemberExpression const>>()) {
  2030. entry.alias.get<NonnullRefPtr<MemberExpression const>>()->dump(indent + 3);
  2031. } else {
  2032. print_indent(indent + 3);
  2033. outln("<empty>");
  2034. }
  2035. if (entry.initializer) {
  2036. print_indent(indent + 2);
  2037. outln("(Initializer)");
  2038. entry.initializer->dump(indent + 3);
  2039. }
  2040. }
  2041. }
  2042. void FunctionNode::dump(int indent, DeprecatedString const& class_name) const
  2043. {
  2044. print_indent(indent);
  2045. auto is_async = m_kind == FunctionKind::Async || m_kind == FunctionKind::AsyncGenerator;
  2046. auto is_generator = m_kind == FunctionKind::Generator || m_kind == FunctionKind::AsyncGenerator;
  2047. outln("{}{}{} '{}'", class_name, is_async ? " async" : "", is_generator ? "*" : "", name());
  2048. if (m_contains_direct_call_to_eval) {
  2049. print_indent(indent + 1);
  2050. outln("\033[31;1m(direct eval)\033[0m");
  2051. }
  2052. if (!m_parameters.is_empty()) {
  2053. print_indent(indent + 1);
  2054. outln("(Parameters)");
  2055. for (auto& parameter : m_parameters) {
  2056. print_indent(indent + 2);
  2057. if (parameter.is_rest)
  2058. out("...");
  2059. parameter.binding.visit(
  2060. [&](DeprecatedFlyString const& name) {
  2061. outln("{}", name);
  2062. },
  2063. [&](BindingPattern const& pattern) {
  2064. pattern.dump(indent + 2);
  2065. });
  2066. if (parameter.default_value)
  2067. parameter.default_value->dump(indent + 3);
  2068. }
  2069. }
  2070. print_indent(indent + 1);
  2071. outln("(Body)");
  2072. body().dump(indent + 2);
  2073. }
  2074. void FunctionDeclaration::dump(int indent) const
  2075. {
  2076. FunctionNode::dump(indent, class_name());
  2077. }
  2078. ThrowCompletionOr<void> FunctionDeclaration::for_each_bound_name(ThrowCompletionOrVoidCallback<DeprecatedFlyString const&>&& callback) const
  2079. {
  2080. if (name().is_empty())
  2081. return {};
  2082. return callback(name());
  2083. }
  2084. void FunctionExpression::dump(int indent) const
  2085. {
  2086. FunctionNode::dump(indent, class_name());
  2087. }
  2088. void YieldExpression::dump(int indent) const
  2089. {
  2090. ASTNode::dump(indent);
  2091. if (argument())
  2092. argument()->dump(indent + 1);
  2093. }
  2094. void AwaitExpression::dump(int indent) const
  2095. {
  2096. ASTNode::dump(indent);
  2097. m_argument->dump(indent + 1);
  2098. }
  2099. void ReturnStatement::dump(int indent) const
  2100. {
  2101. ASTNode::dump(indent);
  2102. if (argument())
  2103. argument()->dump(indent + 1);
  2104. }
  2105. void IfStatement::dump(int indent) const
  2106. {
  2107. ASTNode::dump(indent);
  2108. print_indent(indent);
  2109. outln("If");
  2110. predicate().dump(indent + 1);
  2111. consequent().dump(indent + 1);
  2112. if (alternate()) {
  2113. print_indent(indent);
  2114. outln("Else");
  2115. alternate()->dump(indent + 1);
  2116. }
  2117. }
  2118. void WhileStatement::dump(int indent) const
  2119. {
  2120. ASTNode::dump(indent);
  2121. print_indent(indent);
  2122. outln("While");
  2123. test().dump(indent + 1);
  2124. body().dump(indent + 1);
  2125. }
  2126. void WithStatement::dump(int indent) const
  2127. {
  2128. ASTNode::dump(indent);
  2129. print_indent(indent + 1);
  2130. outln("Object");
  2131. object().dump(indent + 2);
  2132. print_indent(indent + 1);
  2133. outln("Body");
  2134. body().dump(indent + 2);
  2135. }
  2136. void DoWhileStatement::dump(int indent) const
  2137. {
  2138. ASTNode::dump(indent);
  2139. print_indent(indent);
  2140. outln("DoWhile");
  2141. test().dump(indent + 1);
  2142. body().dump(indent + 1);
  2143. }
  2144. void ForStatement::dump(int indent) const
  2145. {
  2146. ASTNode::dump(indent);
  2147. print_indent(indent);
  2148. outln("For");
  2149. if (init())
  2150. init()->dump(indent + 1);
  2151. if (test())
  2152. test()->dump(indent + 1);
  2153. if (update())
  2154. update()->dump(indent + 1);
  2155. body().dump(indent + 1);
  2156. }
  2157. void ForInStatement::dump(int indent) const
  2158. {
  2159. ASTNode::dump(indent);
  2160. print_indent(indent);
  2161. outln("ForIn");
  2162. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2163. rhs().dump(indent + 1);
  2164. body().dump(indent + 1);
  2165. }
  2166. void ForOfStatement::dump(int indent) const
  2167. {
  2168. ASTNode::dump(indent);
  2169. print_indent(indent);
  2170. outln("ForOf");
  2171. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2172. rhs().dump(indent + 1);
  2173. body().dump(indent + 1);
  2174. }
  2175. void ForAwaitOfStatement::dump(int indent) const
  2176. {
  2177. ASTNode::dump(indent);
  2178. print_indent(indent);
  2179. outln("ForAwaitOf");
  2180. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2181. m_rhs->dump(indent + 1);
  2182. m_body->dump(indent + 1);
  2183. }
  2184. // 13.1.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-identifiers-runtime-semantics-evaluation
  2185. Completion Identifier::execute(Interpreter& interpreter) const
  2186. {
  2187. InterpreterNodeScope node_scope { interpreter, *this };
  2188. auto& vm = interpreter.vm();
  2189. // 1. Return ? ResolveBinding(StringValue of Identifier).
  2190. // OPTIMIZATION: We call Identifier::to_reference() here, which acts as a caching layer around ResolveBinding.
  2191. auto reference = TRY(to_reference(interpreter));
  2192. // NOTE: The spec wants us to return the reference directly; this is not possible with ASTNode::execute() (short of letting it return a variant).
  2193. // So, instead of calling GetValue at the call site, we do it here.
  2194. return TRY(reference.get_value(vm));
  2195. }
  2196. void Identifier::dump(int indent) const
  2197. {
  2198. print_indent(indent);
  2199. outln("Identifier \"{}\"", m_string);
  2200. }
  2201. Completion PrivateIdentifier::execute(Interpreter&) const
  2202. {
  2203. // Note: This should be handled by either the member expression this is part of
  2204. // or the binary expression in the case of `#foo in bar`.
  2205. VERIFY_NOT_REACHED();
  2206. }
  2207. void PrivateIdentifier::dump(int indent) const
  2208. {
  2209. print_indent(indent);
  2210. outln("PrivateIdentifier \"{}\"", m_string);
  2211. }
  2212. void SpreadExpression::dump(int indent) const
  2213. {
  2214. ASTNode::dump(indent);
  2215. m_target->dump(indent + 1);
  2216. }
  2217. Completion SpreadExpression::execute(Interpreter& interpreter) const
  2218. {
  2219. InterpreterNodeScope node_scope { interpreter, *this };
  2220. return m_target->execute(interpreter);
  2221. }
  2222. // 13.2.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-this-keyword-runtime-semantics-evaluation
  2223. Completion ThisExpression::execute(Interpreter& interpreter) const
  2224. {
  2225. InterpreterNodeScope node_scope { interpreter, *this };
  2226. auto& vm = interpreter.vm();
  2227. // 1. Return ? ResolveThisBinding().
  2228. return vm.resolve_this_binding();
  2229. }
  2230. void ThisExpression::dump(int indent) const
  2231. {
  2232. ASTNode::dump(indent);
  2233. }
  2234. // 13.15.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation
  2235. Completion AssignmentExpression::execute(Interpreter& interpreter) const
  2236. {
  2237. InterpreterNodeScope node_scope { interpreter, *this };
  2238. auto& vm = interpreter.vm();
  2239. if (m_op == AssignmentOp::Assignment) {
  2240. // AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  2241. return m_lhs.visit(
  2242. // 1. If LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral, then
  2243. [&](NonnullRefPtr<Expression const> const& lhs) -> ThrowCompletionOr<Value> {
  2244. // a. Let lref be the result of evaluating LeftHandSideExpression.
  2245. // b. ReturnIfAbrupt(lref).
  2246. auto reference = TRY(lhs->to_reference(interpreter));
  2247. Value rhs_result;
  2248. // c. If IsAnonymousFunctionDefinition(AssignmentExpression) and IsIdentifierRef of LeftHandSideExpression are both true, then
  2249. if (lhs->is_identifier()) {
  2250. // i. Let rval be ? NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  2251. auto& identifier_name = static_cast<Identifier const&>(*lhs).string();
  2252. rhs_result = TRY(vm.named_evaluation_if_anonymous_function(m_rhs, identifier_name));
  2253. }
  2254. // d. Else,
  2255. else {
  2256. // i. Let rref be the result of evaluating AssignmentExpression.
  2257. // ii. Let rval be ? GetValue(rref).
  2258. rhs_result = TRY(m_rhs->execute(interpreter)).release_value();
  2259. }
  2260. // e. Perform ? PutValue(lref, rval).
  2261. TRY(reference.put_value(vm, rhs_result));
  2262. // f. Return rval.
  2263. return rhs_result;
  2264. },
  2265. // 2. Let assignmentPattern be the AssignmentPattern that is covered by LeftHandSideExpression.
  2266. [&](NonnullRefPtr<BindingPattern const> const& pattern) -> ThrowCompletionOr<Value> {
  2267. // 3. Let rref be the result of evaluating AssignmentExpression.
  2268. // 4. Let rval be ? GetValue(rref).
  2269. auto rhs_result = TRY(m_rhs->execute(interpreter)).release_value();
  2270. // 5. Perform ? DestructuringAssignmentEvaluation of assignmentPattern with argument rval.
  2271. TRY(vm.destructuring_assignment_evaluation(pattern, rhs_result));
  2272. // 6. Return rval.
  2273. return rhs_result;
  2274. });
  2275. }
  2276. VERIFY(m_lhs.has<NonnullRefPtr<Expression const>>());
  2277. // 1. Let lref be the result of evaluating LeftHandSideExpression.
  2278. auto& lhs_expression = *m_lhs.get<NonnullRefPtr<Expression const>>();
  2279. auto reference = TRY(lhs_expression.to_reference(interpreter));
  2280. // 2. Let lval be ? GetValue(lref).
  2281. auto lhs_result = TRY(reference.get_value(vm));
  2282. // AssignmentExpression : LeftHandSideExpression {&&=, ||=, ??=} AssignmentExpression
  2283. if (m_op == AssignmentOp::AndAssignment || m_op == AssignmentOp::OrAssignment || m_op == AssignmentOp::NullishAssignment) {
  2284. switch (m_op) {
  2285. // AssignmentExpression : LeftHandSideExpression &&= AssignmentExpression
  2286. case AssignmentOp::AndAssignment:
  2287. // 3. Let lbool be ToBoolean(lval).
  2288. // 4. If lbool is false, return lval.
  2289. if (!lhs_result.to_boolean())
  2290. return lhs_result;
  2291. break;
  2292. // AssignmentExpression : LeftHandSideExpression ||= AssignmentExpression
  2293. case AssignmentOp::OrAssignment:
  2294. // 3. Let lbool be ToBoolean(lval).
  2295. // 4. If lbool is true, return lval.
  2296. if (lhs_result.to_boolean())
  2297. return lhs_result;
  2298. break;
  2299. // AssignmentExpression : LeftHandSideExpression ??= AssignmentExpression
  2300. case AssignmentOp::NullishAssignment:
  2301. // 3. If lval is neither undefined nor null, return lval.
  2302. if (!lhs_result.is_nullish())
  2303. return lhs_result;
  2304. break;
  2305. default:
  2306. VERIFY_NOT_REACHED();
  2307. }
  2308. Value rhs_result;
  2309. // 5. If IsAnonymousFunctionDefinition(AssignmentExpression) is true and IsIdentifierRef of LeftHandSideExpression is true, then
  2310. if (lhs_expression.is_identifier()) {
  2311. // a. Let rval be ? NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  2312. auto& identifier_name = static_cast<Identifier const&>(lhs_expression).string();
  2313. rhs_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(m_rhs, identifier_name));
  2314. }
  2315. // 6. Else,
  2316. else {
  2317. // a. Let rref be the result of evaluating AssignmentExpression.
  2318. // b. Let rval be ? GetValue(rref).
  2319. rhs_result = TRY(m_rhs->execute(interpreter)).release_value();
  2320. }
  2321. // 7. Perform ? PutValue(lref, rval).
  2322. TRY(reference.put_value(vm, rhs_result));
  2323. // 8. Return rval.
  2324. return rhs_result;
  2325. }
  2326. // AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
  2327. // 3. Let rref be the result of evaluating AssignmentExpression.
  2328. // 4. Let rval be ? GetValue(rref).
  2329. auto rhs_result = TRY(m_rhs->execute(interpreter)).release_value();
  2330. // 5. Let assignmentOpText be the source text matched by AssignmentOperator.
  2331. // 6. Let opText be the sequence of Unicode code points associated with assignmentOpText in the following table:
  2332. // 7. Let r be ? ApplyStringOrNumericBinaryOperator(lval, opText, rval).
  2333. switch (m_op) {
  2334. case AssignmentOp::AdditionAssignment:
  2335. rhs_result = TRY(add(vm, lhs_result, rhs_result));
  2336. break;
  2337. case AssignmentOp::SubtractionAssignment:
  2338. rhs_result = TRY(sub(vm, lhs_result, rhs_result));
  2339. break;
  2340. case AssignmentOp::MultiplicationAssignment:
  2341. rhs_result = TRY(mul(vm, lhs_result, rhs_result));
  2342. break;
  2343. case AssignmentOp::DivisionAssignment:
  2344. rhs_result = TRY(div(vm, lhs_result, rhs_result));
  2345. break;
  2346. case AssignmentOp::ModuloAssignment:
  2347. rhs_result = TRY(mod(vm, lhs_result, rhs_result));
  2348. break;
  2349. case AssignmentOp::ExponentiationAssignment:
  2350. rhs_result = TRY(exp(vm, lhs_result, rhs_result));
  2351. break;
  2352. case AssignmentOp::BitwiseAndAssignment:
  2353. rhs_result = TRY(bitwise_and(vm, lhs_result, rhs_result));
  2354. break;
  2355. case AssignmentOp::BitwiseOrAssignment:
  2356. rhs_result = TRY(bitwise_or(vm, lhs_result, rhs_result));
  2357. break;
  2358. case AssignmentOp::BitwiseXorAssignment:
  2359. rhs_result = TRY(bitwise_xor(vm, lhs_result, rhs_result));
  2360. break;
  2361. case AssignmentOp::LeftShiftAssignment:
  2362. rhs_result = TRY(left_shift(vm, lhs_result, rhs_result));
  2363. break;
  2364. case AssignmentOp::RightShiftAssignment:
  2365. rhs_result = TRY(right_shift(vm, lhs_result, rhs_result));
  2366. break;
  2367. case AssignmentOp::UnsignedRightShiftAssignment:
  2368. rhs_result = TRY(unsigned_right_shift(vm, lhs_result, rhs_result));
  2369. break;
  2370. case AssignmentOp::Assignment:
  2371. case AssignmentOp::AndAssignment:
  2372. case AssignmentOp::OrAssignment:
  2373. case AssignmentOp::NullishAssignment:
  2374. VERIFY_NOT_REACHED();
  2375. }
  2376. // 8. Perform ? PutValue(lref, r).
  2377. TRY(reference.put_value(vm, rhs_result));
  2378. // 9. Return r.
  2379. return rhs_result;
  2380. }
  2381. // 13.4.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-postfix-increment-operator-runtime-semantics-evaluation
  2382. // 13.4.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-postfix-decrement-operator-runtime-semantics-evaluation
  2383. // 13.4.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-prefix-increment-operator-runtime-semantics-evaluation
  2384. // 13.4.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-prefix-decrement-operator-runtime-semantics-evaluation
  2385. Completion UpdateExpression::execute(Interpreter& interpreter) const
  2386. {
  2387. InterpreterNodeScope node_scope { interpreter, *this };
  2388. auto& vm = interpreter.vm();
  2389. // 1. Let expr be the result of evaluating <Expression>.
  2390. auto reference = TRY(m_argument->to_reference(interpreter));
  2391. // 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
  2392. auto old_value = TRY(reference.get_value(vm));
  2393. old_value = TRY(old_value.to_numeric(vm));
  2394. Value new_value;
  2395. switch (m_op) {
  2396. case UpdateOp::Increment:
  2397. // 3. If Type(oldValue) is Number, then
  2398. if (old_value.is_number()) {
  2399. // a. Let newValue be Number::add(oldValue, 1𝔽).
  2400. new_value = Value(old_value.as_double() + 1);
  2401. }
  2402. // 4. Else,
  2403. else {
  2404. // a. Assert: Type(oldValue) is BigInt.
  2405. // b. Let newValue be BigInt::add(oldValue, 1ℤ).
  2406. new_value = BigInt::create(vm, old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  2407. }
  2408. break;
  2409. case UpdateOp::Decrement:
  2410. // 3. If Type(oldValue) is Number, then
  2411. if (old_value.is_number()) {
  2412. // a. Let newValue be Number::subtract(oldValue, 1𝔽).
  2413. new_value = Value(old_value.as_double() - 1);
  2414. }
  2415. // 4. Else,
  2416. else {
  2417. // a. Assert: Type(oldValue) is BigInt.
  2418. // b. Let newValue be BigInt::subtract(oldValue, 1ℤ).
  2419. new_value = BigInt::create(vm, old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
  2420. }
  2421. break;
  2422. default:
  2423. VERIFY_NOT_REACHED();
  2424. }
  2425. // 5. Perform ? PutValue(expr, newValue).
  2426. TRY(reference.put_value(vm, new_value));
  2427. // 6. Return newValue.
  2428. // 6. Return oldValue.
  2429. return m_prefixed ? new_value : old_value;
  2430. }
  2431. void AssignmentExpression::dump(int indent) const
  2432. {
  2433. char const* op_string = nullptr;
  2434. switch (m_op) {
  2435. case AssignmentOp::Assignment:
  2436. op_string = "=";
  2437. break;
  2438. case AssignmentOp::AdditionAssignment:
  2439. op_string = "+=";
  2440. break;
  2441. case AssignmentOp::SubtractionAssignment:
  2442. op_string = "-=";
  2443. break;
  2444. case AssignmentOp::MultiplicationAssignment:
  2445. op_string = "*=";
  2446. break;
  2447. case AssignmentOp::DivisionAssignment:
  2448. op_string = "/=";
  2449. break;
  2450. case AssignmentOp::ModuloAssignment:
  2451. op_string = "%=";
  2452. break;
  2453. case AssignmentOp::ExponentiationAssignment:
  2454. op_string = "**=";
  2455. break;
  2456. case AssignmentOp::BitwiseAndAssignment:
  2457. op_string = "&=";
  2458. break;
  2459. case AssignmentOp::BitwiseOrAssignment:
  2460. op_string = "|=";
  2461. break;
  2462. case AssignmentOp::BitwiseXorAssignment:
  2463. op_string = "^=";
  2464. break;
  2465. case AssignmentOp::LeftShiftAssignment:
  2466. op_string = "<<=";
  2467. break;
  2468. case AssignmentOp::RightShiftAssignment:
  2469. op_string = ">>=";
  2470. break;
  2471. case AssignmentOp::UnsignedRightShiftAssignment:
  2472. op_string = ">>>=";
  2473. break;
  2474. case AssignmentOp::AndAssignment:
  2475. op_string = "&&=";
  2476. break;
  2477. case AssignmentOp::OrAssignment:
  2478. op_string = "||=";
  2479. break;
  2480. case AssignmentOp::NullishAssignment:
  2481. op_string = "\?\?=";
  2482. break;
  2483. }
  2484. ASTNode::dump(indent);
  2485. print_indent(indent + 1);
  2486. outln("{}", op_string);
  2487. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2488. m_rhs->dump(indent + 1);
  2489. }
  2490. void UpdateExpression::dump(int indent) const
  2491. {
  2492. char const* op_string = nullptr;
  2493. switch (m_op) {
  2494. case UpdateOp::Increment:
  2495. op_string = "++";
  2496. break;
  2497. case UpdateOp::Decrement:
  2498. op_string = "--";
  2499. break;
  2500. }
  2501. ASTNode::dump(indent);
  2502. if (m_prefixed) {
  2503. print_indent(indent + 1);
  2504. outln("{}", op_string);
  2505. }
  2506. m_argument->dump(indent + 1);
  2507. if (!m_prefixed) {
  2508. print_indent(indent + 1);
  2509. outln("{}", op_string);
  2510. }
  2511. }
  2512. // 14.3.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-let-and-const-declarations-runtime-semantics-evaluation
  2513. // 14.3.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-variable-statement-runtime-semantics-evaluation
  2514. Completion VariableDeclaration::execute(Interpreter& interpreter) const
  2515. {
  2516. InterpreterNodeScope node_scope { interpreter, *this };
  2517. auto& vm = interpreter.vm();
  2518. for (auto& declarator : m_declarations) {
  2519. if (auto* init = declarator->init()) {
  2520. TRY(declarator->target().visit(
  2521. [&](NonnullRefPtr<Identifier const> const& id) -> ThrowCompletionOr<void> {
  2522. auto reference = TRY(id->to_reference(interpreter));
  2523. auto initializer_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(*init, id->string()));
  2524. VERIFY(!initializer_result.is_empty());
  2525. if (m_declaration_kind == DeclarationKind::Var)
  2526. return reference.put_value(vm, initializer_result);
  2527. else
  2528. return reference.initialize_referenced_binding(vm, initializer_result);
  2529. },
  2530. [&](NonnullRefPtr<BindingPattern const> const& pattern) -> ThrowCompletionOr<void> {
  2531. auto initializer_result = TRY(init->execute(interpreter)).release_value();
  2532. Environment* environment = m_declaration_kind == DeclarationKind::Var ? nullptr : interpreter.lexical_environment();
  2533. return vm.binding_initialization(pattern, initializer_result, environment);
  2534. }));
  2535. } else if (m_declaration_kind != DeclarationKind::Var) {
  2536. VERIFY(declarator->target().has<NonnullRefPtr<Identifier const>>());
  2537. auto& identifier = declarator->target().get<NonnullRefPtr<Identifier const>>();
  2538. auto reference = TRY(identifier->to_reference(interpreter));
  2539. TRY(reference.initialize_referenced_binding(vm, js_undefined()));
  2540. }
  2541. }
  2542. return normal_completion({});
  2543. }
  2544. Completion VariableDeclarator::execute(Interpreter& interpreter) const
  2545. {
  2546. InterpreterNodeScope node_scope { interpreter, *this };
  2547. // NOTE: VariableDeclarator execution is handled by VariableDeclaration.
  2548. VERIFY_NOT_REACHED();
  2549. }
  2550. ThrowCompletionOr<void> VariableDeclaration::for_each_bound_name(ThrowCompletionOrVoidCallback<DeprecatedFlyString const&>&& callback) const
  2551. {
  2552. for (auto const& entry : declarations()) {
  2553. TRY(entry->target().visit(
  2554. [&](NonnullRefPtr<Identifier const> const& id) {
  2555. return callback(id->string());
  2556. },
  2557. [&](NonnullRefPtr<BindingPattern const> const& binding) {
  2558. return binding->for_each_bound_name([&](auto const& name) {
  2559. return callback(name);
  2560. });
  2561. }));
  2562. }
  2563. return {};
  2564. }
  2565. void VariableDeclaration::dump(int indent) const
  2566. {
  2567. char const* declaration_kind_string = nullptr;
  2568. switch (m_declaration_kind) {
  2569. case DeclarationKind::Let:
  2570. declaration_kind_string = "Let";
  2571. break;
  2572. case DeclarationKind::Var:
  2573. declaration_kind_string = "Var";
  2574. break;
  2575. case DeclarationKind::Const:
  2576. declaration_kind_string = "Const";
  2577. break;
  2578. }
  2579. ASTNode::dump(indent);
  2580. print_indent(indent + 1);
  2581. outln("{}", declaration_kind_string);
  2582. for (auto& declarator : m_declarations)
  2583. declarator->dump(indent + 1);
  2584. }
  2585. // 6.2.1.2 Runtime Semantics: Evaluation, https://tc39.es/proposal-explicit-resource-management/#sec-let-and-const-declarations-runtime-semantics-evaluation
  2586. Completion UsingDeclaration::execute(Interpreter& interpreter) const
  2587. {
  2588. // 1. Let next be BindingEvaluation of BindingList with parameter sync-dispose.
  2589. InterpreterNodeScope node_scope { interpreter, *this };
  2590. auto& vm = interpreter.vm();
  2591. for (auto& declarator : m_declarations) {
  2592. VERIFY(declarator->target().has<NonnullRefPtr<Identifier const>>());
  2593. VERIFY(declarator->init());
  2594. auto& id = declarator->target().get<NonnullRefPtr<Identifier const>>();
  2595. // 2. ReturnIfAbrupt(next).
  2596. auto reference = TRY(id->to_reference(interpreter));
  2597. auto initializer_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(*declarator->init(), id->string()));
  2598. VERIFY(!initializer_result.is_empty());
  2599. TRY(reference.initialize_referenced_binding(vm, initializer_result, Environment::InitializeBindingHint::SyncDispose));
  2600. }
  2601. // 3. Return empty.
  2602. return normal_completion({});
  2603. }
  2604. ThrowCompletionOr<void> UsingDeclaration::for_each_bound_name(ThrowCompletionOrVoidCallback<DeprecatedFlyString const&>&& callback) const
  2605. {
  2606. for (auto const& entry : m_declarations) {
  2607. VERIFY(entry->target().has<NonnullRefPtr<Identifier const>>());
  2608. TRY(callback(entry->target().get<NonnullRefPtr<Identifier const>>()->string()));
  2609. }
  2610. return {};
  2611. }
  2612. void UsingDeclaration::dump(int indent) const
  2613. {
  2614. ASTNode::dump(indent);
  2615. print_indent(indent + 1);
  2616. for (auto& declarator : m_declarations)
  2617. declarator->dump(indent + 1);
  2618. }
  2619. void VariableDeclarator::dump(int indent) const
  2620. {
  2621. ASTNode::dump(indent);
  2622. m_target.visit([indent](auto const& value) { value->dump(indent + 1); });
  2623. if (m_init)
  2624. m_init->dump(indent + 1);
  2625. }
  2626. void ObjectProperty::dump(int indent) const
  2627. {
  2628. ASTNode::dump(indent);
  2629. if (m_property_type == Type::Spread) {
  2630. print_indent(indent + 1);
  2631. outln("...Spreading");
  2632. m_key->dump(indent + 1);
  2633. } else {
  2634. m_key->dump(indent + 1);
  2635. m_value->dump(indent + 1);
  2636. }
  2637. }
  2638. void ObjectExpression::dump(int indent) const
  2639. {
  2640. ASTNode::dump(indent);
  2641. for (auto& property : m_properties) {
  2642. property->dump(indent + 1);
  2643. }
  2644. }
  2645. void ExpressionStatement::dump(int indent) const
  2646. {
  2647. ASTNode::dump(indent);
  2648. m_expression->dump(indent + 1);
  2649. }
  2650. Completion ObjectProperty::execute(Interpreter& interpreter) const
  2651. {
  2652. InterpreterNodeScope node_scope { interpreter, *this };
  2653. // NOTE: ObjectProperty execution is handled by ObjectExpression.
  2654. VERIFY_NOT_REACHED();
  2655. }
  2656. // 13.2.5.4 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-object-initializer-runtime-semantics-evaluation
  2657. Completion ObjectExpression::execute(Interpreter& interpreter) const
  2658. {
  2659. InterpreterNodeScope node_scope { interpreter, *this };
  2660. auto& vm = interpreter.vm();
  2661. auto& realm = *vm.current_realm();
  2662. // 1. Let obj be OrdinaryObjectCreate(%Object.prototype%).
  2663. auto object = Object::create(realm, realm.intrinsics().object_prototype());
  2664. // 2. Perform ? PropertyDefinitionEvaluation of PropertyDefinitionList with argument obj.
  2665. for (auto& property : m_properties) {
  2666. auto key = TRY(property->key().execute(interpreter)).release_value();
  2667. // PropertyDefinition : ... AssignmentExpression
  2668. if (property->type() == ObjectProperty::Type::Spread) {
  2669. // 4. Perform ? CopyDataProperties(object, fromValue, excludedNames).
  2670. TRY(object->copy_data_properties(vm, key, {}));
  2671. // 5. Return unused.
  2672. continue;
  2673. }
  2674. auto value = TRY(property->value().execute(interpreter)).release_value();
  2675. // 8. If isProtoSetter is true, then
  2676. if (property->type() == ObjectProperty::Type::ProtoSetter) {
  2677. // a. If Type(propValue) is either Object or Null, then
  2678. if (value.is_object() || value.is_null()) {
  2679. // i. Perform ! object.[[SetPrototypeOf]](propValue).
  2680. MUST(object->internal_set_prototype_of(value.is_object() ? &value.as_object() : nullptr));
  2681. }
  2682. // b. Return unused.
  2683. continue;
  2684. }
  2685. auto property_key = TRY(PropertyKey::from_value(vm, key));
  2686. if (property->is_method()) {
  2687. VERIFY(value.is_function());
  2688. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(object);
  2689. auto name = MUST(get_function_property_name(property_key));
  2690. if (property->type() == ObjectProperty::Type::Getter) {
  2691. name = DeprecatedString::formatted("get {}", name);
  2692. } else if (property->type() == ObjectProperty::Type::Setter) {
  2693. name = DeprecatedString::formatted("set {}", name);
  2694. }
  2695. update_function_name(value, name);
  2696. }
  2697. switch (property->type()) {
  2698. case ObjectProperty::Type::Getter:
  2699. VERIFY(value.is_function());
  2700. object->define_direct_accessor(property_key, &value.as_function(), nullptr, Attribute::Configurable | Attribute::Enumerable);
  2701. break;
  2702. case ObjectProperty::Type::Setter:
  2703. VERIFY(value.is_function());
  2704. object->define_direct_accessor(property_key, nullptr, &value.as_function(), Attribute::Configurable | Attribute::Enumerable);
  2705. break;
  2706. case ObjectProperty::Type::KeyValue:
  2707. object->define_direct_property(property_key, value, default_attributes);
  2708. break;
  2709. case ObjectProperty::Type::Spread:
  2710. default:
  2711. VERIFY_NOT_REACHED();
  2712. }
  2713. }
  2714. // 3. Return obj.
  2715. return Value { object };
  2716. }
  2717. void MemberExpression::dump(int indent) const
  2718. {
  2719. print_indent(indent);
  2720. outln("{}(computed={})", class_name(), is_computed());
  2721. m_object->dump(indent + 1);
  2722. m_property->dump(indent + 1);
  2723. }
  2724. DeprecatedString MemberExpression::to_string_approximation() const
  2725. {
  2726. DeprecatedString object_string = "<object>";
  2727. if (is<Identifier>(*m_object))
  2728. object_string = static_cast<Identifier const&>(*m_object).string();
  2729. if (is_computed())
  2730. return DeprecatedString::formatted("{}[<computed>]", object_string);
  2731. if (is<PrivateIdentifier>(*m_property))
  2732. return DeprecatedString::formatted("{}.{}", object_string, verify_cast<PrivateIdentifier>(*m_property).string());
  2733. return DeprecatedString::formatted("{}.{}", object_string, verify_cast<Identifier>(*m_property).string());
  2734. }
  2735. // 13.3.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-property-accessors-runtime-semantics-evaluation
  2736. Completion MemberExpression::execute(Interpreter& interpreter) const
  2737. {
  2738. InterpreterNodeScope node_scope { interpreter, *this };
  2739. auto& vm = interpreter.vm();
  2740. auto reference = TRY(to_reference(interpreter));
  2741. return TRY(reference.get_value(vm));
  2742. }
  2743. bool MemberExpression::ends_in_private_name() const
  2744. {
  2745. if (is_computed())
  2746. return false;
  2747. if (is<PrivateIdentifier>(*m_property))
  2748. return true;
  2749. if (is<MemberExpression>(*m_property))
  2750. return static_cast<MemberExpression const&>(*m_property).ends_in_private_name();
  2751. return false;
  2752. }
  2753. void OptionalChain::dump(int indent) const
  2754. {
  2755. print_indent(indent);
  2756. outln("{}", class_name());
  2757. m_base->dump(indent + 1);
  2758. for (auto& reference : m_references) {
  2759. reference.visit(
  2760. [&](Call const& call) {
  2761. print_indent(indent + 1);
  2762. outln("Call({})", call.mode == Mode::Optional ? "Optional" : "Not Optional");
  2763. for (auto& argument : call.arguments)
  2764. argument.value->dump(indent + 2);
  2765. },
  2766. [&](ComputedReference const& ref) {
  2767. print_indent(indent + 1);
  2768. outln("ComputedReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2769. ref.expression->dump(indent + 2);
  2770. },
  2771. [&](MemberReference const& ref) {
  2772. print_indent(indent + 1);
  2773. outln("MemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2774. ref.identifier->dump(indent + 2);
  2775. },
  2776. [&](PrivateMemberReference const& ref) {
  2777. print_indent(indent + 1);
  2778. outln("PrivateMemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2779. ref.private_identifier->dump(indent + 2);
  2780. });
  2781. }
  2782. }
  2783. ThrowCompletionOr<OptionalChain::ReferenceAndValue> OptionalChain::to_reference_and_value(Interpreter& interpreter) const
  2784. {
  2785. auto& vm = interpreter.vm();
  2786. auto base_reference = TRY(m_base->to_reference(interpreter));
  2787. auto base = base_reference.is_unresolvable()
  2788. ? TRY(m_base->execute(interpreter)).release_value()
  2789. : TRY(base_reference.get_value(vm));
  2790. for (auto& reference : m_references) {
  2791. auto is_optional = reference.visit([](auto& ref) { return ref.mode; }) == Mode::Optional;
  2792. if (is_optional && base.is_nullish())
  2793. return ReferenceAndValue { {}, js_undefined() };
  2794. auto expression = reference.visit(
  2795. [&](Call const& call) -> NonnullRefPtr<Expression const> {
  2796. return CallExpression::create(source_range(),
  2797. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2798. call.arguments, InvocationStyleEnum::Parenthesized, InsideParenthesesEnum::NotInsideParentheses);
  2799. },
  2800. [&](ComputedReference const& ref) -> NonnullRefPtr<Expression const> {
  2801. return create_ast_node<MemberExpression>(source_range(),
  2802. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2803. ref.expression,
  2804. true);
  2805. },
  2806. [&](MemberReference const& ref) -> NonnullRefPtr<Expression const> {
  2807. return create_ast_node<MemberExpression>(source_range(),
  2808. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2809. ref.identifier,
  2810. false);
  2811. },
  2812. [&](PrivateMemberReference const& ref) -> NonnullRefPtr<Expression const> {
  2813. return create_ast_node<MemberExpression>(source_range(),
  2814. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2815. ref.private_identifier,
  2816. false);
  2817. });
  2818. if (is<CallExpression>(*expression)) {
  2819. base_reference = JS::Reference {};
  2820. base = TRY(expression->execute(interpreter)).release_value();
  2821. } else {
  2822. base_reference = TRY(expression->to_reference(interpreter));
  2823. base = TRY(base_reference.get_value(vm));
  2824. }
  2825. }
  2826. return ReferenceAndValue { move(base_reference), base };
  2827. }
  2828. // 13.3.9.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-optional-chaining-evaluation
  2829. Completion OptionalChain::execute(Interpreter& interpreter) const
  2830. {
  2831. InterpreterNodeScope node_scope { interpreter, *this };
  2832. return TRY(to_reference_and_value(interpreter)).value;
  2833. }
  2834. ThrowCompletionOr<JS::Reference> OptionalChain::to_reference(Interpreter& interpreter) const
  2835. {
  2836. return TRY(to_reference_and_value(interpreter)).reference;
  2837. }
  2838. void MetaProperty::dump(int indent) const
  2839. {
  2840. DeprecatedString name;
  2841. if (m_type == MetaProperty::Type::NewTarget)
  2842. name = "new.target";
  2843. else if (m_type == MetaProperty::Type::ImportMeta)
  2844. name = "import.meta";
  2845. else
  2846. VERIFY_NOT_REACHED();
  2847. print_indent(indent);
  2848. outln("{} {}", class_name(), name);
  2849. }
  2850. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  2851. Completion MetaProperty::execute(Interpreter& interpreter) const
  2852. {
  2853. InterpreterNodeScope node_scope { interpreter, *this };
  2854. auto& vm = interpreter.vm();
  2855. auto& realm = *vm.current_realm();
  2856. // NewTarget : new . target
  2857. if (m_type == MetaProperty::Type::NewTarget) {
  2858. // 1. Return GetNewTarget().
  2859. return interpreter.vm().get_new_target();
  2860. }
  2861. // ImportMeta : import . meta
  2862. if (m_type == MetaProperty::Type::ImportMeta) {
  2863. // 1. Let module be GetActiveScriptOrModule().
  2864. auto script_or_module = interpreter.vm().get_active_script_or_module();
  2865. // 2. Assert: module is a Source Text Module Record.
  2866. VERIFY(script_or_module.has<NonnullGCPtr<Module>>());
  2867. VERIFY(script_or_module.get<NonnullGCPtr<Module>>());
  2868. VERIFY(is<SourceTextModule>(*script_or_module.get<NonnullGCPtr<Module>>()));
  2869. auto& module = static_cast<SourceTextModule&>(*script_or_module.get<NonnullGCPtr<Module>>());
  2870. // 3. Let importMeta be module.[[ImportMeta]].
  2871. auto* import_meta = module.import_meta();
  2872. // 4. If importMeta is empty, then
  2873. if (import_meta == nullptr) {
  2874. // a. Set importMeta to OrdinaryObjectCreate(null).
  2875. import_meta = Object::create(realm, nullptr);
  2876. // b. Let importMetaValues be HostGetImportMetaProperties(module).
  2877. auto import_meta_values = interpreter.vm().host_get_import_meta_properties(module);
  2878. // c. For each Record { [[Key]], [[Value]] } p of importMetaValues, do
  2879. for (auto& entry : import_meta_values) {
  2880. // i. Perform ! CreateDataPropertyOrThrow(importMeta, p.[[Key]], p.[[Value]]).
  2881. MUST(import_meta->create_data_property_or_throw(entry.key, entry.value));
  2882. }
  2883. // d. Perform HostFinalizeImportMeta(importMeta, module).
  2884. interpreter.vm().host_finalize_import_meta(import_meta, module);
  2885. // e. Set module.[[ImportMeta]] to importMeta.
  2886. module.set_import_meta({}, import_meta);
  2887. // f. Return importMeta.
  2888. return Value { import_meta };
  2889. }
  2890. // 5. Else,
  2891. else {
  2892. // a. Assert: Type(importMeta) is Object.
  2893. // Note: This is always true by the type.
  2894. // b. Return importMeta.
  2895. return Value { import_meta };
  2896. }
  2897. }
  2898. VERIFY_NOT_REACHED();
  2899. }
  2900. void ImportCall::dump(int indent) const
  2901. {
  2902. ASTNode::dump(indent);
  2903. print_indent(indent);
  2904. outln("(Specifier)");
  2905. m_specifier->dump(indent + 1);
  2906. if (m_options) {
  2907. outln("(Options)");
  2908. m_options->dump(indent + 1);
  2909. }
  2910. }
  2911. // 13.3.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-import-call-runtime-semantics-evaluation
  2912. // Also includes assertions from proposal: https://tc39.es/proposal-import-assertions/#sec-import-call-runtime-semantics-evaluation
  2913. Completion ImportCall::execute(Interpreter& interpreter) const
  2914. {
  2915. InterpreterNodeScope node_scope { interpreter, *this };
  2916. auto& vm = interpreter.vm();
  2917. auto& realm = *vm.current_realm();
  2918. // 2.1.1.1 EvaluateImportCall ( specifierExpression [ , optionsExpression ] ), https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call
  2919. // 1. Let referencingScriptOrModule be GetActiveScriptOrModule().
  2920. auto referencing_script_or_module = vm.get_active_script_or_module();
  2921. // 2. Let specifierRef be the result of evaluating specifierExpression.
  2922. // 3. Let specifier be ? GetValue(specifierRef).
  2923. auto specifier = TRY(m_specifier->execute(interpreter));
  2924. auto options_value = js_undefined();
  2925. // 4. If optionsExpression is present, then
  2926. if (m_options) {
  2927. // a. Let optionsRef be the result of evaluating optionsExpression.
  2928. // b. Let options be ? GetValue(optionsRef).
  2929. options_value = TRY(m_options->execute(interpreter)).release_value();
  2930. }
  2931. // 5. Else,
  2932. // a. Let options be undefined.
  2933. // Note: options_value is undefined by default.
  2934. // 6. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  2935. auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  2936. // 7. Let specifierString be Completion(ToString(specifier)).
  2937. // 8. IfAbruptRejectPromise(specifierString, promiseCapability).
  2938. auto specifier_string = TRY_OR_REJECT_WITH_VALUE(vm, promise_capability, specifier->to_deprecated_string(vm));
  2939. // 9. Let assertions be a new empty List.
  2940. Vector<ModuleRequest::Assertion> assertions;
  2941. // 10. If options is not undefined, then
  2942. if (!options_value.is_undefined()) {
  2943. // a. If Type(options) is not Object,
  2944. if (!options_value.is_object()) {
  2945. auto error = TypeError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted(ErrorType::NotAnObject.message(), "ImportOptions")));
  2946. // i. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »).
  2947. MUST(call(vm, *promise_capability->reject(), js_undefined(), error));
  2948. // ii. Return promiseCapability.[[Promise]].
  2949. return Value { promise_capability->promise() };
  2950. }
  2951. // b. Let assertionsObj be Get(options, "assert").
  2952. // c. IfAbruptRejectPromise(assertionsObj, promiseCapability).
  2953. auto assertion_object = TRY_OR_REJECT_WITH_VALUE(vm, promise_capability, options_value.get(vm, vm.names.assert));
  2954. // d. If assertionsObj is not undefined,
  2955. if (!assertion_object.is_undefined()) {
  2956. // i. If Type(assertionsObj) is not Object,
  2957. if (!assertion_object.is_object()) {
  2958. auto error = TypeError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted(ErrorType::NotAnObject.message(), "ImportOptionsAssertions")));
  2959. // 1. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »).
  2960. MUST(call(vm, *promise_capability->reject(), js_undefined(), error));
  2961. // 2. Return promiseCapability.[[Promise]].
  2962. return Value { promise_capability->promise() };
  2963. }
  2964. // ii. Let keys be EnumerableOwnPropertyNames(assertionsObj, key).
  2965. // iii. IfAbruptRejectPromise(keys, promiseCapability).
  2966. auto keys = TRY_OR_REJECT_WITH_VALUE(vm, promise_capability, assertion_object.as_object().enumerable_own_property_names(Object::PropertyKind::Key));
  2967. // iv. Let supportedAssertions be ! HostGetSupportedImportAssertions().
  2968. auto supported_assertions = vm.host_get_supported_import_assertions();
  2969. // v. For each String key of keys,
  2970. for (auto const& key : keys) {
  2971. auto property_key = MUST(key.to_property_key(vm));
  2972. // 1. Let value be Get(assertionsObj, key).
  2973. // 2. IfAbruptRejectPromise(value, promiseCapability).
  2974. auto value = TRY_OR_REJECT_WITH_VALUE(vm, promise_capability, assertion_object.get(vm, property_key));
  2975. // 3. If Type(value) is not String, then
  2976. if (!value.is_string()) {
  2977. auto error = TypeError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted(ErrorType::NotAString.message(), "Import Assertion option value")));
  2978. // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »).
  2979. MUST(call(vm, *promise_capability->reject(), js_undefined(), error));
  2980. // b. Return promiseCapability.[[Promise]].
  2981. return Value { promise_capability->promise() };
  2982. }
  2983. // 4. If supportedAssertions contains key, then
  2984. if (supported_assertions.contains_slow(property_key.to_string())) {
  2985. // a. Append { [[Key]]: key, [[Value]]: value } to assertions.
  2986. assertions.empend(property_key.to_string(), TRY(value.as_string().deprecated_string()));
  2987. }
  2988. }
  2989. }
  2990. // e. Sort assertions by the code point order of the [[Key]] of each element. NOTE: This sorting is observable only in that hosts are prohibited from distinguishing among assertions by the order they occur in.
  2991. // Note: This is done when constructing the ModuleRequest.
  2992. }
  2993. // 11. Let moduleRequest be a new ModuleRequest Record { [[Specifier]]: specifierString, [[Assertions]]: assertions }.
  2994. ModuleRequest request { specifier_string, assertions };
  2995. // 12. Perform HostImportModuleDynamically(referencingScriptOrModule, moduleRequest, promiseCapability).
  2996. MUST_OR_THROW_OOM(interpreter.vm().host_import_module_dynamically(referencing_script_or_module, move(request), promise_capability));
  2997. // 13. Return promiseCapability.[[Promise]].
  2998. return Value { promise_capability->promise() };
  2999. }
  3000. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  3001. Completion StringLiteral::execute(Interpreter& interpreter) const
  3002. {
  3003. InterpreterNodeScope node_scope { interpreter, *this };
  3004. auto& vm = interpreter.vm();
  3005. // 1. Return the SV of StringLiteral as defined in 12.8.4.2.
  3006. return Value { PrimitiveString::create(vm, m_value) };
  3007. }
  3008. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  3009. Completion NumericLiteral::execute(Interpreter& interpreter) const
  3010. {
  3011. InterpreterNodeScope node_scope { interpreter, *this };
  3012. // 1. Return the NumericValue of NumericLiteral as defined in 12.8.3.
  3013. return Value(m_value);
  3014. }
  3015. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  3016. Completion BigIntLiteral::execute(Interpreter& interpreter) const
  3017. {
  3018. InterpreterNodeScope node_scope { interpreter, *this };
  3019. auto& vm = interpreter.vm();
  3020. // 1. Return the NumericValue of NumericLiteral as defined in 12.8.3.
  3021. Crypto::SignedBigInteger integer;
  3022. if (m_value[0] == '0' && m_value.length() >= 3) {
  3023. if (m_value[1] == 'x' || m_value[1] == 'X') {
  3024. return Value { BigInt::create(vm, Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3))) };
  3025. } else if (m_value[1] == 'o' || m_value[1] == 'O') {
  3026. return Value { BigInt::create(vm, Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3))) };
  3027. } else if (m_value[1] == 'b' || m_value[1] == 'B') {
  3028. return Value { BigInt::create(vm, Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3))) };
  3029. }
  3030. }
  3031. return Value { BigInt::create(vm, Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1))) };
  3032. }
  3033. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  3034. Completion BooleanLiteral::execute(Interpreter& interpreter) const
  3035. {
  3036. InterpreterNodeScope node_scope { interpreter, *this };
  3037. // 1. If BooleanLiteral is the token false, return false.
  3038. // 2. If BooleanLiteral is the token true, return true.
  3039. return Value(m_value);
  3040. }
  3041. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  3042. Completion NullLiteral::execute(Interpreter& interpreter) const
  3043. {
  3044. InterpreterNodeScope node_scope { interpreter, *this };
  3045. // 1. Return null.
  3046. return js_null();
  3047. }
  3048. void RegExpLiteral::dump(int indent) const
  3049. {
  3050. print_indent(indent);
  3051. outln("{} (/{}/{})", class_name(), pattern(), flags());
  3052. }
  3053. // 13.2.7.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation
  3054. Completion RegExpLiteral::execute(Interpreter& interpreter) const
  3055. {
  3056. InterpreterNodeScope node_scope { interpreter, *this };
  3057. auto& vm = interpreter.vm();
  3058. auto& realm = *vm.current_realm();
  3059. // 1. Let pattern be CodePointsToString(BodyText of RegularExpressionLiteral).
  3060. auto pattern = this->pattern();
  3061. // 2. Let flags be CodePointsToString(FlagText of RegularExpressionLiteral).
  3062. auto flags = this->flags();
  3063. // 3. Return ! RegExpCreate(pattern, flags).
  3064. Regex<ECMA262> regex(parsed_regex(), parsed_pattern(), parsed_flags());
  3065. // NOTE: We bypass RegExpCreate and subsequently RegExpAlloc as an optimization to use the already parsed values.
  3066. auto regexp_object = RegExpObject::create(realm, move(regex), move(pattern), move(flags));
  3067. // RegExpAlloc has these two steps from the 'Legacy RegExp features' proposal.
  3068. regexp_object->set_realm(*vm.current_realm());
  3069. // We don't need to check 'If SameValue(newTarget, thisRealm.[[Intrinsics]].[[%RegExp%]]) is true'
  3070. // here as we know RegExpCreate calls RegExpAlloc with %RegExp% for newTarget.
  3071. regexp_object->set_legacy_features_enabled(true);
  3072. return Value { regexp_object };
  3073. }
  3074. void ArrayExpression::dump(int indent) const
  3075. {
  3076. ASTNode::dump(indent);
  3077. for (auto& element : m_elements) {
  3078. if (element) {
  3079. element->dump(indent + 1);
  3080. } else {
  3081. print_indent(indent + 1);
  3082. outln("<empty>");
  3083. }
  3084. }
  3085. }
  3086. // 13.2.4.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-array-initializer-runtime-semantics-evaluation
  3087. Completion ArrayExpression::execute(Interpreter& interpreter) const
  3088. {
  3089. InterpreterNodeScope node_scope { interpreter, *this };
  3090. auto& vm = interpreter.vm();
  3091. auto& realm = *vm.current_realm();
  3092. // 1. Let array be ! ArrayCreate(0).
  3093. auto array = MUST(Array::create(realm, 0));
  3094. // 2. Perform ? ArrayAccumulation of ElementList with arguments array and 0.
  3095. array->indexed_properties();
  3096. size_t index = 0;
  3097. for (auto& element : m_elements) {
  3098. auto value = Value();
  3099. if (element) {
  3100. value = TRY(element->execute(interpreter)).release_value();
  3101. if (is<SpreadExpression>(*element)) {
  3102. (void)TRY(get_iterator_values(vm, value, [&](Value iterator_value) -> Optional<Completion> {
  3103. array->indexed_properties().put(index++, iterator_value, default_attributes);
  3104. return {};
  3105. }));
  3106. continue;
  3107. }
  3108. }
  3109. array->indexed_properties().put(index++, value, default_attributes);
  3110. }
  3111. // 3. Return array.
  3112. return Value { array };
  3113. }
  3114. void TemplateLiteral::dump(int indent) const
  3115. {
  3116. ASTNode::dump(indent);
  3117. for (auto& expression : m_expressions)
  3118. expression->dump(indent + 1);
  3119. }
  3120. // 13.2.8.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-template-literals-runtime-semantics-evaluation
  3121. Completion TemplateLiteral::execute(Interpreter& interpreter) const
  3122. {
  3123. InterpreterNodeScope node_scope { interpreter, *this };
  3124. auto& vm = interpreter.vm();
  3125. StringBuilder string_builder;
  3126. for (auto& expression : m_expressions) {
  3127. // 1. Let head be the TV of TemplateHead as defined in 12.8.6.
  3128. // 2. Let subRef be the result of evaluating Expression.
  3129. // 3. Let sub be ? GetValue(subRef).
  3130. auto sub = TRY(expression->execute(interpreter)).release_value();
  3131. // 4. Let middle be ? ToString(sub).
  3132. auto string = TRY(sub.to_deprecated_string(vm));
  3133. string_builder.append(string);
  3134. // 5. Let tail be the result of evaluating TemplateSpans.
  3135. // 6. ReturnIfAbrupt(tail).
  3136. }
  3137. // 7. Return the string-concatenation of head, middle, and tail.
  3138. return Value { PrimitiveString::create(vm, string_builder.to_deprecated_string()) };
  3139. }
  3140. void TaggedTemplateLiteral::dump(int indent) const
  3141. {
  3142. ASTNode::dump(indent);
  3143. print_indent(indent + 1);
  3144. outln("(Tag)");
  3145. m_tag->dump(indent + 2);
  3146. print_indent(indent + 1);
  3147. outln("(Template Literal)");
  3148. m_template_literal->dump(indent + 2);
  3149. }
  3150. // 13.3.11.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-tagged-templates-runtime-semantics-evaluation
  3151. Completion TaggedTemplateLiteral::execute(Interpreter& interpreter) const
  3152. {
  3153. InterpreterNodeScope node_scope { interpreter, *this };
  3154. auto& vm = interpreter.vm();
  3155. // NOTE: This is both
  3156. // MemberExpression : MemberExpression TemplateLiteral
  3157. // CallExpression : CallExpression TemplateLiteral
  3158. // 1. Let tagRef be ? Evaluation of MemberExpression.
  3159. // 1. Let tagRef be ? Evaluation of CallExpression.
  3160. // 2. Let tagFunc be ? GetValue(tagRef).
  3161. // NOTE: This is much more complicated than the spec because we have to
  3162. // handle every type of reference. If we handle evaluation closer
  3163. // to the spec this could be improved.
  3164. Value tag_this_value;
  3165. Value tag;
  3166. if (auto tag_reference = TRY(m_tag->to_reference(interpreter)); tag_reference.is_valid_reference()) {
  3167. tag = TRY(tag_reference.get_value(vm));
  3168. if (tag_reference.is_environment_reference()) {
  3169. auto& environment = tag_reference.base_environment();
  3170. if (environment.has_this_binding())
  3171. tag_this_value = TRY(environment.get_this_binding(vm));
  3172. else
  3173. tag_this_value = js_undefined();
  3174. } else {
  3175. tag_this_value = tag_reference.get_this_value();
  3176. }
  3177. } else {
  3178. auto result = TRY(m_tag->execute(interpreter));
  3179. VERIFY(result.has_value());
  3180. tag = result.release_value();
  3181. tag_this_value = js_undefined();
  3182. }
  3183. // 3. Let thisCall be this CallExpression.
  3184. // 3. Let thisCall be this MemberExpression.
  3185. // FIXME: 4. Let tailCall be IsInTailPosition(thisCall).
  3186. // NOTE: A tagged template is a function call where the arguments of the call are derived from a
  3187. // TemplateLiteral (13.2.8). The actual arguments include a template object (13.2.8.3)
  3188. // and the values produced by evaluating the expressions embedded within the TemplateLiteral.
  3189. auto template_ = TRY(get_template_object(interpreter));
  3190. MarkedVector<Value> arguments(interpreter.vm().heap());
  3191. arguments.append(template_);
  3192. auto& expressions = m_template_literal->expressions();
  3193. // tag`${foo}` -> "", foo, "" -> tag(["", ""], foo)
  3194. // tag`foo${bar}baz${qux}` -> "foo", bar, "baz", qux, "" -> tag(["foo", "baz", ""], bar, qux)
  3195. // So we want all the odd expressions
  3196. for (size_t i = 1; i < expressions.size(); i += 2)
  3197. arguments.append(TRY(expressions[i]->execute(interpreter)).release_value());
  3198. // 5. Return ? EvaluateCall(tagFunc, tagRef, TemplateLiteral, tailCall).
  3199. return call(vm, tag, tag_this_value, move(arguments));
  3200. }
  3201. // 13.2.8.3 GetTemplateObject ( templateLiteral ), https://tc39.es/ecma262/#sec-gettemplateobject
  3202. ThrowCompletionOr<Value> TaggedTemplateLiteral::get_template_object(Interpreter& interpreter) const
  3203. {
  3204. auto& vm = interpreter.vm();
  3205. // 1. Let realm be the current Realm Record.
  3206. auto& realm = *vm.current_realm();
  3207. // 2. Let templateRegistry be realm.[[TemplateMap]].
  3208. // 3. For each element e of templateRegistry, do
  3209. // a. If e.[[Site]] is the same Parse Node as templateLiteral, then
  3210. // i. Return e.[[Array]].
  3211. // NOTE: Instead of caching on the realm we cache on the Parse Node side as
  3212. // this makes it easier to track whether it is the same parse node.
  3213. if (auto cached_value_or_end = m_cached_values.find(&realm); cached_value_or_end != m_cached_values.end())
  3214. return Value { cached_value_or_end->value.cell() };
  3215. // 4. Let rawStrings be TemplateStrings of templateLiteral with argument true.
  3216. auto& raw_strings = m_template_literal->raw_strings();
  3217. // 5. Let cookedStrings be TemplateStrings of templateLiteral with argument false.
  3218. auto& expressions = m_template_literal->expressions();
  3219. // 6. Let count be the number of elements in the List cookedStrings.
  3220. // NOTE: Only the even expression in expression are the cooked strings
  3221. // so we use rawStrings for the size here
  3222. VERIFY(raw_strings.size() == (expressions.size() + 1) / 2);
  3223. auto count = raw_strings.size();
  3224. // 7. Assert: count ≤ 2^32 - 1.
  3225. VERIFY(count <= 0xffffffff);
  3226. // 8. Let template be ! ArrayCreate(count).
  3227. // NOTE: We don't set count since we push the values using append which
  3228. // would then append after count. Same for 9.
  3229. auto template_ = MUST(Array::create(realm, 0));
  3230. // 9. Let rawObj be ! ArrayCreate(count).
  3231. auto raw_obj = MUST(Array::create(realm, 0));
  3232. // 10. Let index be 0.
  3233. // 11. Repeat, while index < count,
  3234. for (size_t i = 0; i < count; ++i) {
  3235. auto cooked_string_index = i * 2;
  3236. // a. Let prop be ! ToString(𝔽(index)).
  3237. // b. Let cookedValue be cookedStrings[index].
  3238. auto cooked_value = TRY(expressions[cooked_string_index]->execute(interpreter)).release_value();
  3239. // NOTE: If the string contains invalid escapes we get a null expression here,
  3240. // which we then convert to the expected `undefined` TV. See
  3241. // 12.9.6.1 Static Semantics: TV, https://tc39.es/ecma262/#sec-static-semantics-tv
  3242. if (cooked_value.is_null())
  3243. cooked_value = js_undefined();
  3244. // c. Perform ! DefinePropertyOrThrow(template, prop, PropertyDescriptor { [[Value]]: cookedValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false }).
  3245. template_->indexed_properties().append(cooked_value);
  3246. // d. Let rawValue be the String value rawStrings[index].
  3247. // e. Perform ! DefinePropertyOrThrow(rawObj, prop, PropertyDescriptor { [[Value]]: rawValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false }).
  3248. raw_obj->indexed_properties().append(TRY(raw_strings[i]->execute(interpreter)).release_value());
  3249. // f. Set index to index + 1.
  3250. }
  3251. // 12. Perform ! SetIntegrityLevel(rawObj, frozen).
  3252. MUST(raw_obj->set_integrity_level(Object::IntegrityLevel::Frozen));
  3253. // 13. Perform ! DefinePropertyOrThrow(template, "raw", PropertyDescriptor { [[Value]]: rawObj, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).
  3254. template_->define_direct_property(interpreter.vm().names.raw, raw_obj, 0);
  3255. // 14. Perform ! SetIntegrityLevel(template, frozen).
  3256. MUST(template_->set_integrity_level(Object::IntegrityLevel::Frozen));
  3257. // 15. Append the Record { [[Site]]: templateLiteral, [[Array]]: template } to templateRegistry.
  3258. m_cached_values.set(&realm, make_handle(template_));
  3259. // 16. Return template.
  3260. return template_;
  3261. }
  3262. void TryStatement::dump(int indent) const
  3263. {
  3264. ASTNode::dump(indent);
  3265. print_indent(indent);
  3266. outln("(Block)");
  3267. block().dump(indent + 1);
  3268. if (handler()) {
  3269. print_indent(indent);
  3270. outln("(Handler)");
  3271. handler()->dump(indent + 1);
  3272. }
  3273. if (finalizer()) {
  3274. print_indent(indent);
  3275. outln("(Finalizer)");
  3276. finalizer()->dump(indent + 1);
  3277. }
  3278. }
  3279. void CatchClause::dump(int indent) const
  3280. {
  3281. print_indent(indent);
  3282. m_parameter.visit(
  3283. [&](DeprecatedFlyString const& parameter) {
  3284. if (parameter.is_null())
  3285. outln("CatchClause");
  3286. else
  3287. outln("CatchClause ({})", parameter);
  3288. },
  3289. [&](NonnullRefPtr<BindingPattern const> const& pattern) {
  3290. outln("CatchClause");
  3291. print_indent(indent);
  3292. outln("(Parameter)");
  3293. pattern->dump(indent + 2);
  3294. });
  3295. body().dump(indent + 1);
  3296. }
  3297. void ThrowStatement::dump(int indent) const
  3298. {
  3299. ASTNode::dump(indent);
  3300. argument().dump(indent + 1);
  3301. }
  3302. // 14.15.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-try-statement-runtime-semantics-evaluation
  3303. Completion TryStatement::execute(Interpreter& interpreter) const
  3304. {
  3305. InterpreterNodeScope node_scope { interpreter, *this };
  3306. auto& vm = interpreter.vm();
  3307. // 14.15.2 Runtime Semantics: CatchClauseEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-catchclauseevaluation
  3308. auto catch_clause_evaluation = [&](Value thrown_value) {
  3309. // 1. Let oldEnv be the running execution context's LexicalEnvironment.
  3310. auto old_environment = vm.running_execution_context().lexical_environment;
  3311. // 2. Let catchEnv be NewDeclarativeEnvironment(oldEnv).
  3312. auto catch_environment = new_declarative_environment(*old_environment);
  3313. m_handler->parameter().visit(
  3314. [&](DeprecatedFlyString const& parameter) {
  3315. // 3. For each element argName of the BoundNames of CatchParameter, do
  3316. // a. Perform ! catchEnv.CreateMutableBinding(argName, false).
  3317. MUST(catch_environment->create_mutable_binding(vm, parameter, false));
  3318. },
  3319. [&](NonnullRefPtr<BindingPattern const> const& pattern) {
  3320. // 3. For each element argName of the BoundNames of CatchParameter, do
  3321. // NOTE: Due to the use of MUST with `create_mutable_binding` below, an exception should not result from `for_each_bound_name`.
  3322. MUST(pattern->for_each_bound_name([&](auto& name) {
  3323. // a. Perform ! catchEnv.CreateMutableBinding(argName, false).
  3324. MUST(catch_environment->create_mutable_binding(vm, name, false));
  3325. }));
  3326. });
  3327. // 4. Set the running execution context's LexicalEnvironment to catchEnv.
  3328. vm.running_execution_context().lexical_environment = catch_environment;
  3329. // 5. Let status be Completion(BindingInitialization of CatchParameter with arguments thrownValue and catchEnv).
  3330. auto status = m_handler->parameter().visit(
  3331. [&](DeprecatedFlyString const& parameter) {
  3332. return catch_environment->initialize_binding(vm, parameter, thrown_value, Environment::InitializeBindingHint::Normal);
  3333. },
  3334. [&](NonnullRefPtr<BindingPattern const> const& pattern) {
  3335. return vm.binding_initialization(pattern, thrown_value, catch_environment);
  3336. });
  3337. // 6. If status is an abrupt completion, then
  3338. if (status.is_error()) {
  3339. // a. Set the running execution context's LexicalEnvironment to oldEnv.
  3340. vm.running_execution_context().lexical_environment = old_environment;
  3341. // b. Return ? status.
  3342. return status.release_error();
  3343. }
  3344. // 7. Let B be the result of evaluating Block.
  3345. auto handler_result = m_handler->body().execute(interpreter);
  3346. // 8. Set the running execution context's LexicalEnvironment to oldEnv.
  3347. vm.running_execution_context().lexical_environment = old_environment;
  3348. // 9. Return ? B.
  3349. return handler_result;
  3350. };
  3351. Completion result;
  3352. // 1. Let B be the result of evaluating Block.
  3353. auto block_result = m_block->execute(interpreter);
  3354. // TryStatement : try Block Catch
  3355. // TryStatement : try Block Catch Finally
  3356. if (m_handler) {
  3357. // 2. If B.[[Type]] is throw, let C be Completion(CatchClauseEvaluation of Catch with argument B.[[Value]]).
  3358. if (block_result.type() == Completion::Type::Throw)
  3359. result = catch_clause_evaluation(*block_result.value());
  3360. // 3. Else, let C be B.
  3361. else
  3362. result = move(block_result);
  3363. } else {
  3364. // TryStatement : try Block Finally
  3365. // This variant doesn't have C & uses B in the finalizer step.
  3366. result = move(block_result);
  3367. }
  3368. // TryStatement : try Block Finally
  3369. // TryStatement : try Block Catch Finally
  3370. if (m_finalizer) {
  3371. // 4. Let F be the result of evaluating Finally.
  3372. auto finalizer_result = m_finalizer->execute(interpreter);
  3373. // 5. If F.[[Type]] is normal, set F to C.
  3374. if (finalizer_result.type() == Completion::Type::Normal)
  3375. finalizer_result = move(result);
  3376. // 6. Return ? UpdateEmpty(F, undefined).
  3377. return finalizer_result.update_empty(js_undefined());
  3378. }
  3379. // 4. Return ? UpdateEmpty(C, undefined).
  3380. return result.update_empty(js_undefined());
  3381. }
  3382. Completion CatchClause::execute(Interpreter& interpreter) const
  3383. {
  3384. InterpreterNodeScope node_scope { interpreter, *this };
  3385. // NOTE: CatchClause execution is handled by TryStatement.
  3386. VERIFY_NOT_REACHED();
  3387. return {};
  3388. }
  3389. // 14.14.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-throw-statement-runtime-semantics-evaluation
  3390. Completion ThrowStatement::execute(Interpreter& interpreter) const
  3391. {
  3392. InterpreterNodeScope node_scope { interpreter, *this };
  3393. // 1. Let exprRef be the result of evaluating Expression.
  3394. // 2. Let exprValue be ? GetValue(exprRef).
  3395. auto value = TRY(m_argument->execute(interpreter)).release_value();
  3396. // 3. Return ThrowCompletion(exprValue).
  3397. return throw_completion(value);
  3398. }
  3399. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  3400. // BreakableStatement : SwitchStatement
  3401. Completion SwitchStatement::execute(Interpreter& interpreter) const
  3402. {
  3403. // 1. Let newLabelSet be a new empty List.
  3404. // 2. Return ? LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  3405. return labelled_evaluation(interpreter, *this, {});
  3406. }
  3407. // NOTE: Since we don't have the 'BreakableStatement' from the spec as a separate ASTNode that wraps IterationStatement / SwitchStatement,
  3408. // execute() needs to take care of LabelledEvaluation, which in turn calls execute_impl().
  3409. // 14.12.4 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-switch-statement-runtime-semantics-evaluation
  3410. Completion SwitchStatement::execute_impl(Interpreter& interpreter) const
  3411. {
  3412. InterpreterNodeScope node_scope { interpreter, *this };
  3413. auto& vm = interpreter.vm();
  3414. // 14.12.3 CaseClauseIsSelected ( C, input ), https://tc39.es/ecma262/#sec-runtime-semantics-caseclauseisselected
  3415. auto case_clause_is_selected = [&](auto const& case_clause, auto input) -> ThrowCompletionOr<bool> {
  3416. // 1. Assert: C is an instance of the production CaseClause : case Expression : StatementList[opt] .
  3417. VERIFY(case_clause->test());
  3418. // 2. Let exprRef be the result of evaluating the Expression of C.
  3419. // 3. Let clauseSelector be ? GetValue(exprRef).
  3420. auto clause_selector = TRY(case_clause->test()->execute(interpreter)).release_value();
  3421. // 4. Return IsStrictlyEqual(input, clauseSelector).
  3422. return is_strictly_equal(input, clause_selector);
  3423. };
  3424. // 14.12.2 Runtime Semantics: CaseBlockEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-caseblockevaluation
  3425. auto case_block_evaluation = [&](auto input) -> Completion {
  3426. // CaseBlock : { }
  3427. if (m_cases.is_empty()) {
  3428. // 1. Return undefined.
  3429. return js_undefined();
  3430. }
  3431. Vector<NonnullRefPtr<SwitchCase const>> case_clauses_1;
  3432. Vector<NonnullRefPtr<SwitchCase const>> case_clauses_2;
  3433. RefPtr<SwitchCase const> default_clause;
  3434. for (auto const& switch_case : m_cases) {
  3435. if (!switch_case->test())
  3436. default_clause = switch_case;
  3437. else if (!default_clause)
  3438. case_clauses_1.append(switch_case);
  3439. else
  3440. case_clauses_2.append(switch_case);
  3441. }
  3442. // CaseBlock : { CaseClauses }
  3443. if (!default_clause) {
  3444. VERIFY(!case_clauses_1.is_empty());
  3445. VERIFY(case_clauses_2.is_empty());
  3446. // 1. Let V be undefined.
  3447. auto last_value = js_undefined();
  3448. // 2. Let A be the List of CaseClause items in CaseClauses, in source text order.
  3449. // NOTE: A is case_clauses_1.
  3450. // 3. Let found be false.
  3451. auto found = false;
  3452. // 4. For each CaseClause C of A, do
  3453. for (auto const& case_clause : case_clauses_1) {
  3454. // a. If found is false, then
  3455. if (!found) {
  3456. // i. Set found to ? CaseClauseIsSelected(C, input).
  3457. found = TRY(case_clause_is_selected(case_clause, input));
  3458. }
  3459. // b. If found is true, then
  3460. if (found) {
  3461. // i. Let R be the result of evaluating C.
  3462. auto result = case_clause->evaluate_statements(interpreter);
  3463. // ii. If R.[[Value]] is not empty, set V to R.[[Value]].
  3464. if (result.value().has_value())
  3465. last_value = *result.value();
  3466. // iii. If R is an abrupt completion, return ? UpdateEmpty(R, V).
  3467. if (result.is_abrupt())
  3468. return result.update_empty(last_value);
  3469. }
  3470. }
  3471. // 5. Return V.
  3472. return last_value;
  3473. }
  3474. // CaseBlock : { CaseClauses[opt] DefaultClause CaseClauses[opt] }
  3475. else {
  3476. // 1. Let V be undefined.
  3477. auto last_value = js_undefined();
  3478. // 2. If the first CaseClauses is present, then
  3479. // a. Let A be the List of CaseClause items in the first CaseClauses, in source text order.
  3480. // 3. Else,
  3481. // a. Let A be a new empty List.
  3482. // NOTE: A is case_clauses_1.
  3483. // 4. Let found be false.
  3484. auto found = false;
  3485. // 5. For each CaseClause C of A, do
  3486. for (auto const& case_clause : case_clauses_1) {
  3487. // a. If found is false, then
  3488. if (!found) {
  3489. // i. Set found to ? CaseClauseIsSelected(C, input).
  3490. found = TRY(case_clause_is_selected(case_clause, input));
  3491. }
  3492. // b. If found is true, then
  3493. if (found) {
  3494. // i. Let R be the result of evaluating C.
  3495. auto result = case_clause->evaluate_statements(interpreter);
  3496. // ii. If R.[[Value]] is not empty, set V to R.[[Value]].
  3497. if (result.value().has_value())
  3498. last_value = *result.value();
  3499. // iii. If R is an abrupt completion, return ? UpdateEmpty(R, V).
  3500. if (result.is_abrupt())
  3501. return result.update_empty(last_value);
  3502. }
  3503. }
  3504. // 6. Let foundInB be false.
  3505. auto found_in_b = false;
  3506. // 7. If the second CaseClauses is present, then
  3507. // a. Let B be the List of CaseClause items in the second CaseClauses, in source text order.
  3508. // 8. Else,
  3509. // a. Let B be a new empty List.
  3510. // NOTE: B is case_clauses_2.
  3511. // 9. If found is false, then
  3512. if (!found) {
  3513. // a. For each CaseClause C of B, do
  3514. for (auto const& case_clause : case_clauses_2) {
  3515. // i. If foundInB is false, then
  3516. if (!found_in_b) {
  3517. // 1. Set foundInB to ? CaseClauseIsSelected(C, input).
  3518. found_in_b = TRY(case_clause_is_selected(case_clause, input));
  3519. }
  3520. // ii. If foundInB is true, then
  3521. if (found_in_b) {
  3522. // 1. Let R be the result of evaluating CaseClause C.
  3523. auto result = case_clause->evaluate_statements(interpreter);
  3524. // 2. If R.[[Value]] is not empty, set V to R.[[Value]].
  3525. if (result.value().has_value())
  3526. last_value = *result.value();
  3527. // 3. If R is an abrupt completion, return ? UpdateEmpty(R, V).
  3528. if (result.is_abrupt())
  3529. return result.update_empty(last_value);
  3530. }
  3531. }
  3532. }
  3533. // 10. If foundInB is true, return V.
  3534. if (found_in_b)
  3535. return last_value;
  3536. // 11. Let R be the result of evaluating DefaultClause.
  3537. auto result = default_clause->evaluate_statements(interpreter);
  3538. // 12. If R.[[Value]] is not empty, set V to R.[[Value]].
  3539. if (result.value().has_value())
  3540. last_value = *result.value();
  3541. // 13. If R is an abrupt completion, return ? UpdateEmpty(R, V).
  3542. if (result.is_abrupt())
  3543. return result.update_empty(last_value);
  3544. // 14. NOTE: The following is another complete iteration of the second CaseClauses.
  3545. // 15. For each CaseClause C of B, do
  3546. for (auto const& case_clause : case_clauses_2) {
  3547. // a. Let R be the result of evaluating CaseClause C.
  3548. result = case_clause->evaluate_statements(interpreter);
  3549. // b. If R.[[Value]] is not empty, set V to R.[[Value]].
  3550. if (result.value().has_value())
  3551. last_value = *result.value();
  3552. // c. If R is an abrupt completion, return ? UpdateEmpty(R, V).
  3553. if (result.is_abrupt())
  3554. return result.update_empty(last_value);
  3555. }
  3556. // 16. Return V.
  3557. return last_value;
  3558. }
  3559. VERIFY_NOT_REACHED();
  3560. };
  3561. // SwitchStatement : switch ( Expression ) CaseBlock
  3562. // 1. Let exprRef be the result of evaluating Expression.
  3563. // 2. Let switchValue be ? GetValue(exprRef).
  3564. auto switch_value = TRY(m_discriminant->execute(interpreter)).release_value();
  3565. Completion result;
  3566. // Optimization: Avoid creating a lexical environment if there are no lexical declarations.
  3567. if (has_lexical_declarations()) {
  3568. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
  3569. auto* old_environment = interpreter.lexical_environment();
  3570. // 4. Let blockEnv be NewDeclarativeEnvironment(oldEnv).
  3571. auto block_environment = new_declarative_environment(*old_environment);
  3572. // 5. Perform BlockDeclarationInstantiation(CaseBlock, blockEnv).
  3573. block_declaration_instantiation(vm, block_environment);
  3574. // 6. Set the running execution context's LexicalEnvironment to blockEnv.
  3575. vm.running_execution_context().lexical_environment = block_environment;
  3576. // 7. Let R be Completion(CaseBlockEvaluation of CaseBlock with argument switchValue).
  3577. result = case_block_evaluation(switch_value);
  3578. // 8. Let env be blockEnv's LexicalEnvironment.
  3579. // FIXME: blockEnv doesn't have a lexical env it is one?? Probably a spec issue
  3580. // 9. Set R to DisposeResources(env, R).
  3581. result = dispose_resources(vm, block_environment, result);
  3582. // 10. Set the running execution context's LexicalEnvironment to oldEnv.
  3583. vm.running_execution_context().lexical_environment = old_environment;
  3584. } else {
  3585. result = case_block_evaluation(switch_value);
  3586. }
  3587. // 11. Return R.
  3588. return result;
  3589. }
  3590. Completion SwitchCase::execute(Interpreter& interpreter) const
  3591. {
  3592. InterpreterNodeScope node_scope { interpreter, *this };
  3593. // NOTE: SwitchCase execution is handled by SwitchStatement.
  3594. VERIFY_NOT_REACHED();
  3595. return {};
  3596. }
  3597. // 14.9.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-break-statement-runtime-semantics-evaluation
  3598. Completion BreakStatement::execute(Interpreter& interpreter) const
  3599. {
  3600. InterpreterNodeScope node_scope { interpreter, *this };
  3601. // BreakStatement : break ;
  3602. if (m_target_label.is_null()) {
  3603. // 1. Return Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  3604. return { Completion::Type::Break, {}, {} };
  3605. }
  3606. // BreakStatement : break LabelIdentifier ;
  3607. // 1. Let label be the StringValue of LabelIdentifier.
  3608. // 2. Return Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: label }.
  3609. return { Completion::Type::Break, {}, m_target_label };
  3610. }
  3611. // 14.8.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-continue-statement-runtime-semantics-evaluation
  3612. Completion ContinueStatement::execute(Interpreter& interpreter) const
  3613. {
  3614. InterpreterNodeScope node_scope { interpreter, *this };
  3615. // ContinueStatement : continue ;
  3616. if (m_target_label.is_null()) {
  3617. // 1. Return Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: empty }.
  3618. return { Completion::Type::Continue, {}, {} };
  3619. }
  3620. // ContinueStatement : continue LabelIdentifier ;
  3621. // 1. Let label be the StringValue of LabelIdentifier.
  3622. // 2. Return Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: label }.
  3623. return { Completion::Type::Continue, {}, m_target_label };
  3624. }
  3625. void SwitchStatement::dump(int indent) const
  3626. {
  3627. ASTNode::dump(indent);
  3628. m_discriminant->dump(indent + 1);
  3629. for (auto& switch_case : m_cases) {
  3630. switch_case->dump(indent + 1);
  3631. }
  3632. }
  3633. void SwitchCase::dump(int indent) const
  3634. {
  3635. print_indent(indent + 1);
  3636. if (m_test) {
  3637. outln("(Test)");
  3638. m_test->dump(indent + 2);
  3639. } else {
  3640. outln("(Default)");
  3641. }
  3642. print_indent(indent + 1);
  3643. outln("(Consequent)");
  3644. ScopeNode::dump(indent + 2);
  3645. }
  3646. // 13.14.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-conditional-operator-runtime-semantics-evaluation
  3647. Completion ConditionalExpression::execute(Interpreter& interpreter) const
  3648. {
  3649. InterpreterNodeScope node_scope { interpreter, *this };
  3650. // 1. Let lref be the result of evaluating ShortCircuitExpression.
  3651. // 2. Let lval be ToBoolean(? GetValue(lref)).
  3652. auto test_result = TRY(m_test->execute(interpreter)).release_value();
  3653. // 3. If lval is true, then
  3654. if (test_result.to_boolean()) {
  3655. // a. Let trueRef be the result of evaluating the first AssignmentExpression.
  3656. // b. Return ? GetValue(trueRef).
  3657. return m_consequent->execute(interpreter);
  3658. }
  3659. // 4. Else,
  3660. else {
  3661. // a. Let falseRef be the result of evaluating the second AssignmentExpression.
  3662. // b. Return ? GetValue(falseRef).
  3663. return m_alternate->execute(interpreter);
  3664. }
  3665. }
  3666. void ConditionalExpression::dump(int indent) const
  3667. {
  3668. ASTNode::dump(indent);
  3669. print_indent(indent + 1);
  3670. outln("(Test)");
  3671. m_test->dump(indent + 2);
  3672. print_indent(indent + 1);
  3673. outln("(Consequent)");
  3674. m_consequent->dump(indent + 2);
  3675. print_indent(indent + 1);
  3676. outln("(Alternate)");
  3677. m_alternate->dump(indent + 2);
  3678. }
  3679. void SequenceExpression::dump(int indent) const
  3680. {
  3681. ASTNode::dump(indent);
  3682. for (auto& expression : m_expressions)
  3683. expression->dump(indent + 1);
  3684. }
  3685. // 13.16.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-comma-operator-runtime-semantics-evaluation
  3686. Completion SequenceExpression::execute(Interpreter& interpreter) const
  3687. {
  3688. InterpreterNodeScope node_scope { interpreter, *this };
  3689. // NOTE: Not sure why the last node is an AssignmentExpression in the spec :yakfused:
  3690. // 1. Let lref be the result of evaluating Expression.
  3691. // 2. Perform ? GetValue(lref).
  3692. // 3. Let rref be the result of evaluating AssignmentExpression.
  3693. // 4. Return ? GetValue(rref).
  3694. Value last_value;
  3695. for (auto const& expression : m_expressions)
  3696. last_value = TRY(expression->execute(interpreter)).release_value();
  3697. return { move(last_value) };
  3698. }
  3699. // 14.16.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-debugger-statement-runtime-semantics-evaluation
  3700. Completion DebuggerStatement::execute(Interpreter& interpreter) const
  3701. {
  3702. InterpreterNodeScope node_scope { interpreter, *this };
  3703. Completion result;
  3704. // 1. If an implementation-defined debugging facility is available and enabled, then
  3705. if (false) {
  3706. // a. Perform an implementation-defined debugging action.
  3707. // b. Return a new implementation-defined Completion Record.
  3708. VERIFY_NOT_REACHED();
  3709. }
  3710. // 2. Else,
  3711. else {
  3712. // a. Return empty.
  3713. return Optional<Value> {};
  3714. }
  3715. }
  3716. ThrowCompletionOr<void> ScopeNode::for_each_lexically_scoped_declaration(ThrowCompletionOrVoidCallback<Declaration const&>&& callback) const
  3717. {
  3718. for (auto& declaration : m_lexical_declarations)
  3719. TRY(callback(declaration));
  3720. return {};
  3721. }
  3722. ThrowCompletionOr<void> ScopeNode::for_each_lexically_declared_name(ThrowCompletionOrVoidCallback<DeprecatedFlyString const&>&& callback) const
  3723. {
  3724. for (auto const& declaration : m_lexical_declarations) {
  3725. TRY(declaration->for_each_bound_name([&](auto const& name) {
  3726. return callback(name);
  3727. }));
  3728. }
  3729. return {};
  3730. }
  3731. ThrowCompletionOr<void> ScopeNode::for_each_var_declared_name(ThrowCompletionOrVoidCallback<DeprecatedFlyString const&>&& callback) const
  3732. {
  3733. for (auto& declaration : m_var_declarations) {
  3734. TRY(declaration->for_each_bound_name([&](auto const& name) {
  3735. return callback(name);
  3736. }));
  3737. }
  3738. return {};
  3739. }
  3740. ThrowCompletionOr<void> ScopeNode::for_each_var_function_declaration_in_reverse_order(ThrowCompletionOrVoidCallback<FunctionDeclaration const&>&& callback) const
  3741. {
  3742. for (ssize_t i = m_var_declarations.size() - 1; i >= 0; i--) {
  3743. auto& declaration = m_var_declarations[i];
  3744. if (is<FunctionDeclaration>(declaration))
  3745. TRY(callback(static_cast<FunctionDeclaration const&>(*declaration)));
  3746. }
  3747. return {};
  3748. }
  3749. ThrowCompletionOr<void> ScopeNode::for_each_var_scoped_variable_declaration(ThrowCompletionOrVoidCallback<VariableDeclaration const&>&& callback) const
  3750. {
  3751. for (auto& declaration : m_var_declarations) {
  3752. if (!is<FunctionDeclaration>(declaration)) {
  3753. VERIFY(is<VariableDeclaration>(declaration));
  3754. TRY(callback(static_cast<VariableDeclaration const&>(*declaration)));
  3755. }
  3756. }
  3757. return {};
  3758. }
  3759. ThrowCompletionOr<void> ScopeNode::for_each_function_hoistable_with_annexB_extension(ThrowCompletionOrVoidCallback<FunctionDeclaration&>&& callback) const
  3760. {
  3761. for (auto& function : m_functions_hoistable_with_annexB_extension) {
  3762. // We need const_cast here since it might have to set a property on function declaration.
  3763. TRY(callback(const_cast<FunctionDeclaration&>(*function)));
  3764. }
  3765. return {};
  3766. }
  3767. void ScopeNode::add_lexical_declaration(NonnullRefPtr<Declaration const> declaration)
  3768. {
  3769. m_lexical_declarations.append(move(declaration));
  3770. }
  3771. void ScopeNode::add_var_scoped_declaration(NonnullRefPtr<Declaration const> declaration)
  3772. {
  3773. m_var_declarations.append(move(declaration));
  3774. }
  3775. void ScopeNode::add_hoisted_function(NonnullRefPtr<FunctionDeclaration const> declaration)
  3776. {
  3777. m_functions_hoistable_with_annexB_extension.append(move(declaration));
  3778. }
  3779. // 16.2.1.11 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-module-semantics-runtime-semantics-evaluation
  3780. Completion ImportStatement::execute(Interpreter& interpreter) const
  3781. {
  3782. InterpreterNodeScope node_scope { interpreter, *this };
  3783. // 1. Return empty.
  3784. return Optional<Value> {};
  3785. }
  3786. DeprecatedFlyString ExportStatement::local_name_for_default = "*default*";
  3787. // 16.2.3.7 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-exports-runtime-semantics-evaluation
  3788. Completion ExportStatement::execute(Interpreter& interpreter) const
  3789. {
  3790. InterpreterNodeScope node_scope { interpreter, *this };
  3791. auto& vm = interpreter.vm();
  3792. if (!is_default_export()) {
  3793. if (m_statement) {
  3794. // 1. Return the result of evaluating <Thing>.
  3795. return m_statement->execute(interpreter);
  3796. }
  3797. // 1. Return empty.
  3798. return Optional<Value> {};
  3799. }
  3800. VERIFY(m_statement);
  3801. // ExportDeclaration : export default HoistableDeclaration
  3802. if (is<FunctionDeclaration>(*m_statement)) {
  3803. // 1. Return the result of evaluating HoistableDeclaration.
  3804. return m_statement->execute(interpreter);
  3805. }
  3806. // ExportDeclaration : export default ClassDeclaration
  3807. // ClassDeclaration: class BindingIdentifier[?Yield, ?Await] ClassTail[?Yield, ?Await]
  3808. if (is<ClassDeclaration>(*m_statement)) {
  3809. auto const& class_declaration = static_cast<ClassDeclaration const&>(*m_statement);
  3810. // 1. Let value be ? BindingClassDeclarationEvaluation of ClassDeclaration.
  3811. auto value = TRY(binding_class_declaration_evaluation(interpreter, class_declaration.m_class_expression));
  3812. // 2. Let className be the sole element of BoundNames of ClassDeclaration.
  3813. // 3. If className is "*default*", then
  3814. // Note: We never go into step 3. since a ClassDeclaration always has a name and "*default*" is not a class name.
  3815. (void)value;
  3816. // 4. Return empty.
  3817. return Optional<Value> {};
  3818. }
  3819. // ExportDeclaration : export default ClassDeclaration
  3820. // ClassDeclaration: [+Default] class ClassTail [?Yield, ?Await]
  3821. if (is<ClassExpression>(*m_statement)) {
  3822. auto& class_expression = static_cast<ClassExpression const&>(*m_statement);
  3823. // 1. Let value be ? BindingClassDeclarationEvaluation of ClassDeclaration.
  3824. auto value = TRY(binding_class_declaration_evaluation(interpreter, class_expression));
  3825. // 2. Let className be the sole element of BoundNames of ClassDeclaration.
  3826. // 3. If className is "*default*", then
  3827. if (!class_expression.has_name()) {
  3828. // Note: This can only occur if the class does not have a name since "*default*" is normally not valid.
  3829. // a. Let env be the running execution context's LexicalEnvironment.
  3830. auto* env = interpreter.lexical_environment();
  3831. // b. Perform ? InitializeBoundName("*default*", value, env).
  3832. TRY(initialize_bound_name(vm, ExportStatement::local_name_for_default, value, env));
  3833. }
  3834. // 4. Return empty.
  3835. return Optional<Value> {};
  3836. }
  3837. // ExportDeclaration : export default AssignmentExpression ;
  3838. // 1. If IsAnonymousFunctionDefinition(AssignmentExpression) is true, then
  3839. // a. Let value be ? NamedEvaluation of AssignmentExpression with argument "default".
  3840. // 2. Else,
  3841. // a. Let rhs be the result of evaluating AssignmentExpression.
  3842. // b. Let value be ? GetValue(rhs).
  3843. auto value = TRY(vm.named_evaluation_if_anonymous_function(*m_statement, "default"));
  3844. // 3. Let env be the running execution context's LexicalEnvironment.
  3845. auto* env = interpreter.lexical_environment();
  3846. // 4. Perform ? InitializeBoundName("*default*", value, env).
  3847. TRY(initialize_bound_name(vm, ExportStatement::local_name_for_default, value, env));
  3848. // 5. Return empty.
  3849. return Optional<Value> {};
  3850. }
  3851. static void dump_assert_clauses(ModuleRequest const& request)
  3852. {
  3853. if (!request.assertions.is_empty()) {
  3854. out("[ ");
  3855. for (auto& assertion : request.assertions)
  3856. out("{}: {}, ", assertion.key, assertion.value);
  3857. out(" ]");
  3858. }
  3859. }
  3860. void ExportStatement::dump(int indent) const
  3861. {
  3862. ASTNode::dump(indent);
  3863. print_indent(indent + 1);
  3864. outln("(ExportEntries)");
  3865. auto string_or_null = [](DeprecatedString const& string) -> DeprecatedString {
  3866. if (string.is_empty()) {
  3867. return "null";
  3868. }
  3869. return DeprecatedString::formatted("\"{}\"", string);
  3870. };
  3871. for (auto& entry : m_entries) {
  3872. print_indent(indent + 2);
  3873. out("ExportName: {}, ImportName: {}, LocalName: {}, ModuleRequest: ",
  3874. string_or_null(entry.export_name),
  3875. entry.is_module_request() ? string_or_null(entry.local_or_import_name) : "null",
  3876. entry.is_module_request() ? "null" : string_or_null(entry.local_or_import_name));
  3877. if (entry.is_module_request()) {
  3878. out("{}", entry.m_module_request->module_specifier);
  3879. dump_assert_clauses(*entry.m_module_request);
  3880. outln();
  3881. } else {
  3882. outln("null");
  3883. }
  3884. }
  3885. if (m_statement) {
  3886. print_indent(indent + 1);
  3887. outln("(Statement)");
  3888. m_statement->dump(indent + 2);
  3889. }
  3890. }
  3891. void ImportStatement::dump(int indent) const
  3892. {
  3893. ASTNode::dump(indent);
  3894. print_indent(indent + 1);
  3895. if (m_entries.is_empty()) {
  3896. // direct from "module" import
  3897. outln("Entire module '{}'", m_module_request.module_specifier);
  3898. dump_assert_clauses(m_module_request);
  3899. } else {
  3900. outln("(ExportEntries) from {}", m_module_request.module_specifier);
  3901. dump_assert_clauses(m_module_request);
  3902. for (auto& entry : m_entries) {
  3903. print_indent(indent + 2);
  3904. outln("ImportName: {}, LocalName: {}", entry.import_name, entry.local_name);
  3905. }
  3906. }
  3907. }
  3908. bool ExportStatement::has_export(DeprecatedFlyString const& export_name) const
  3909. {
  3910. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  3911. // Make sure that empty exported names does not overlap with anything
  3912. if (entry.kind != ExportEntry::Kind::NamedExport)
  3913. return false;
  3914. return entry.export_name == export_name;
  3915. });
  3916. }
  3917. bool ImportStatement::has_bound_name(DeprecatedFlyString const& name) const
  3918. {
  3919. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  3920. return entry.local_name == name;
  3921. });
  3922. }
  3923. // 14.2.3 BlockDeclarationInstantiation ( code, env ), https://tc39.es/ecma262/#sec-blockdeclarationinstantiation
  3924. void ScopeNode::block_declaration_instantiation(VM& vm, Environment* environment) const
  3925. {
  3926. // See also B.3.2.6 Changes to BlockDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-blockdeclarationinstantiation
  3927. auto& realm = *vm.current_realm();
  3928. VERIFY(environment);
  3929. auto private_environment = vm.running_execution_context().private_environment;
  3930. // Note: All the calls here are ! and thus we do not need to TRY this callback.
  3931. // We use MUST to ensure it does not throw and to avoid discarding the returned ThrowCompletionOr<void>.
  3932. MUST(for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  3933. auto is_constant_declaration = declaration.is_constant_declaration();
  3934. // NOTE: Due to the use of MUST with `create_immutable_binding` and `create_mutable_binding` below,
  3935. // an exception should not result from `for_each_bound_name`.
  3936. MUST(declaration.for_each_bound_name([&](auto const& name) {
  3937. if (is_constant_declaration) {
  3938. MUST(environment->create_immutable_binding(vm, name, true));
  3939. } else {
  3940. if (!MUST(environment->has_binding(name)))
  3941. MUST(environment->create_mutable_binding(vm, name, false));
  3942. }
  3943. }));
  3944. if (is<FunctionDeclaration>(declaration)) {
  3945. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  3946. auto function = ECMAScriptFunctionObject::create(realm, function_declaration.name(), function_declaration.source_text(), function_declaration.body(), function_declaration.parameters(), function_declaration.function_length(), environment, private_environment, function_declaration.kind(), function_declaration.is_strict_mode(), function_declaration.might_need_arguments_object(), function_declaration.contains_direct_call_to_eval());
  3947. VERIFY(is<DeclarativeEnvironment>(*environment));
  3948. static_cast<DeclarativeEnvironment&>(*environment).initialize_or_set_mutable_binding({}, vm, function_declaration.name(), function);
  3949. }
  3950. }));
  3951. }
  3952. // 16.1.7 GlobalDeclarationInstantiation ( script, env ), https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  3953. ThrowCompletionOr<void> Program::global_declaration_instantiation(VM& vm, GlobalEnvironment& global_environment) const
  3954. {
  3955. auto& realm = *vm.current_realm();
  3956. // 1. Let lexNames be the LexicallyDeclaredNames of script.
  3957. // 2. Let varNames be the VarDeclaredNames of script.
  3958. // 3. For each element name of lexNames, do
  3959. TRY(for_each_lexically_declared_name([&](DeprecatedFlyString const& name) -> ThrowCompletionOr<void> {
  3960. // a. If env.HasVarDeclaration(name) is true, throw a SyntaxError exception.
  3961. if (global_environment.has_var_declaration(name))
  3962. return vm.throw_completion<SyntaxError>(ErrorType::TopLevelVariableAlreadyDeclared, name);
  3963. // b. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  3964. if (global_environment.has_lexical_declaration(name))
  3965. return vm.throw_completion<SyntaxError>(ErrorType::TopLevelVariableAlreadyDeclared, name);
  3966. // c. Let hasRestrictedGlobal be ? env.HasRestrictedGlobalProperty(name).
  3967. auto has_restricted_global = TRY(global_environment.has_restricted_global_property(name));
  3968. // d. If hasRestrictedGlobal is true, throw a SyntaxError exception.
  3969. if (has_restricted_global)
  3970. return vm.throw_completion<SyntaxError>(ErrorType::RestrictedGlobalProperty, name);
  3971. return {};
  3972. }));
  3973. // 4. For each element name of varNames, do
  3974. TRY(for_each_var_declared_name([&](auto const& name) -> ThrowCompletionOr<void> {
  3975. // a. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  3976. if (global_environment.has_lexical_declaration(name))
  3977. return vm.throw_completion<SyntaxError>(ErrorType::TopLevelVariableAlreadyDeclared, name);
  3978. return {};
  3979. }));
  3980. // 5. Let varDeclarations be the VarScopedDeclarations of script.
  3981. // 6. Let functionsToInitialize be a new empty List.
  3982. Vector<FunctionDeclaration const&> functions_to_initialize;
  3983. // 7. Let declaredFunctionNames be a new empty List.
  3984. HashTable<DeprecatedFlyString> declared_function_names;
  3985. // 8. For each element d of varDeclarations, in reverse List order, do
  3986. TRY(for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) -> ThrowCompletionOr<void> {
  3987. // a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then
  3988. // i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
  3989. // Note: This is checked in for_each_var_function_declaration_in_reverse_order.
  3990. // ii. NOTE: If there are multiple function declarations for the same name, the last declaration is used.
  3991. // iii. Let fn be the sole element of the BoundNames of d.
  3992. // iv. If fn is not an element of declaredFunctionNames, then
  3993. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  3994. return {};
  3995. // 1. Let fnDefinable be ? env.CanDeclareGlobalFunction(fn).
  3996. auto function_definable = TRY(global_environment.can_declare_global_function(function.name()));
  3997. // 2. If fnDefinable is false, throw a TypeError exception.
  3998. if (!function_definable)
  3999. return vm.throw_completion<TypeError>(ErrorType::CannotDeclareGlobalFunction, function.name());
  4000. // 3. Append fn to declaredFunctionNames.
  4001. // Note: Already done in step iv. above.
  4002. // 4. Insert d as the first element of functionsToInitialize.
  4003. // NOTE: Since prepending is much slower, we just append
  4004. // and iterate in reverse order in step 16 below.
  4005. functions_to_initialize.append(function);
  4006. return {};
  4007. }));
  4008. // 9. Let declaredVarNames be a new empty List.
  4009. HashTable<DeprecatedFlyString> declared_var_names;
  4010. // 10. For each element d of varDeclarations, do
  4011. TRY(for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
  4012. // a. If d is a VariableDeclaration, a ForBinding, or a BindingIdentifier, then
  4013. // Note: This is done in for_each_var_scoped_variable_declaration.
  4014. // i. For each String vn of the BoundNames of d, do
  4015. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  4016. // 1. If vn is not an element of declaredFunctionNames, then
  4017. if (declared_function_names.contains(name))
  4018. return {};
  4019. // a. Let vnDefinable be ? env.CanDeclareGlobalVar(vn).
  4020. auto var_definable = TRY(global_environment.can_declare_global_var(name));
  4021. // b. If vnDefinable is false, throw a TypeError exception.
  4022. if (!var_definable)
  4023. return vm.throw_completion<TypeError>(ErrorType::CannotDeclareGlobalVariable, name);
  4024. // c. If vn is not an element of declaredVarNames, then
  4025. // i. Append vn to declaredVarNames.
  4026. declared_var_names.set(name);
  4027. return {};
  4028. });
  4029. }));
  4030. // 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.
  4031. // 12. NOTE: Annex B.3.2.2 adds additional steps at this point.
  4032. // 12. Let strict be IsStrict of script.
  4033. // 13. If strict is false, then
  4034. if (!m_is_strict_mode) {
  4035. // a. Let declaredFunctionOrVarNames be the list-concatenation of declaredFunctionNames and declaredVarNames.
  4036. // b. For each FunctionDeclaration f that is directly contained in the StatementList of a Block, CaseClause, or DefaultClause Contained within script, do
  4037. TRY(for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) -> ThrowCompletionOr<void> {
  4038. // i. Let F be StringValue of the BindingIdentifier of f.
  4039. auto& function_name = function_declaration.name();
  4040. // ii. If replacing the FunctionDeclaration f with a VariableStatement that has F as a BindingIdentifier would not produce any Early Errors for script, then
  4041. // Note: This step is already performed during parsing and for_each_function_hoistable_with_annexB_extension so this always passes here.
  4042. // 1. If env.HasLexicalDeclaration(F) is false, then
  4043. if (global_environment.has_lexical_declaration(function_name))
  4044. return {};
  4045. // a. Let fnDefinable be ? env.CanDeclareGlobalVar(F).
  4046. auto function_definable = TRY(global_environment.can_declare_global_function(function_name));
  4047. // b. If fnDefinable is true, then
  4048. if (!function_definable)
  4049. return {};
  4050. // i. NOTE: A var binding for F is only instantiated here if it is neither a VarDeclaredName nor the name of another FunctionDeclaration.
  4051. // ii. If declaredFunctionOrVarNames does not contain F, then
  4052. if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
  4053. // i. Perform ? env.CreateGlobalVarBinding(F, false).
  4054. TRY(global_environment.create_global_var_binding(function_name, false));
  4055. // ii. Append F to declaredFunctionOrVarNames.
  4056. declared_function_names.set(function_name);
  4057. }
  4058. // iii. When the FunctionDeclaration f is evaluated, perform the following steps in place of the FunctionDeclaration Evaluation algorithm provided in 15.2.6:
  4059. // i. Let genv be the running execution context's VariableEnvironment.
  4060. // ii. Let benv be the running execution context's LexicalEnvironment.
  4061. // iii. Let fobj be ! benv.GetBindingValue(F, false).
  4062. // iv. Perform ? genv.SetMutableBinding(F, fobj, false).
  4063. // v. Return unused.
  4064. function_declaration.set_should_do_additional_annexB_steps();
  4065. return {};
  4066. }));
  4067. // We should not use declared function names below here anymore since these functions are not in there in the spec.
  4068. declared_function_names.clear();
  4069. }
  4070. // 13. Let lexDeclarations be the LexicallyScopedDeclarations of script.
  4071. // 14. Let privateEnv be null.
  4072. PrivateEnvironment* private_environment = nullptr;
  4073. // 15. For each element d of lexDeclarations, do
  4074. TRY(for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  4075. // a. NOTE: Lexically declared names are only instantiated here but not initialized.
  4076. // b. For each element dn of the BoundNames of d, do
  4077. return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> {
  4078. // i. If IsConstantDeclaration of d is true, then
  4079. if (declaration.is_constant_declaration()) {
  4080. // 1. Perform ? env.CreateImmutableBinding(dn, true).
  4081. TRY(global_environment.create_immutable_binding(vm, name, true));
  4082. }
  4083. // ii. Else,
  4084. else {
  4085. // 1. Perform ? env.CreateMutableBinding(dn, false).
  4086. TRY(global_environment.create_mutable_binding(vm, name, false));
  4087. }
  4088. return {};
  4089. });
  4090. }));
  4091. // 16. For each Parse Node f of functionsToInitialize, do
  4092. // NOTE: We iterate in reverse order since we appended the functions
  4093. // instead of prepending. We append because prepending is much slower
  4094. // and we only use the created vector here.
  4095. for (auto& declaration : functions_to_initialize.in_reverse()) {
  4096. // a. Let fn be the sole element of the BoundNames of f.
  4097. // b. Let fo be InstantiateFunctionObject of f with arguments env and privateEnv.
  4098. auto function = ECMAScriptFunctionObject::create(realm, declaration.name(), declaration.source_text(), declaration.body(), declaration.parameters(), declaration.function_length(), &global_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object(), declaration.contains_direct_call_to_eval());
  4099. // c. Perform ? env.CreateGlobalFunctionBinding(fn, fo, false).
  4100. TRY(global_environment.create_global_function_binding(declaration.name(), function, false));
  4101. }
  4102. // 17. For each String vn of declaredVarNames, do
  4103. for (auto& var_name : declared_var_names) {
  4104. // a. Perform ? env.CreateGlobalVarBinding(vn, false).
  4105. TRY(global_environment.create_global_var_binding(var_name, false));
  4106. }
  4107. // 18. Return unused.
  4108. return {};
  4109. }
  4110. ModuleRequest::ModuleRequest(DeprecatedFlyString module_specifier_, Vector<Assertion> assertions_)
  4111. : module_specifier(move(module_specifier_))
  4112. , assertions(move(assertions_))
  4113. {
  4114. // Perform step 10.e. from EvaluateImportCall, https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call
  4115. // or step 2. from 2.7 Static Semantics: AssertClauseToAssertions, https://tc39.es/proposal-import-assertions/#sec-assert-clause-to-assertions
  4116. // e. / 2. Sort assertions by the code point order of the [[Key]] of each element.
  4117. // NOTE: This sorting is observable only in that hosts are prohibited from distinguishing among assertions by the order they occur in.
  4118. quick_sort(assertions, [](Assertion const& lhs, Assertion const& rhs) {
  4119. return lhs.key < rhs.key;
  4120. });
  4121. }
  4122. DeprecatedString SourceRange::filename() const
  4123. {
  4124. return code->filename().to_deprecated_string();
  4125. }
  4126. NonnullRefPtr<CallExpression> CallExpression::create(SourceRange source_range, NonnullRefPtr<Expression const> callee, ReadonlySpan<Argument> arguments, InvocationStyleEnum invocation_style, InsideParenthesesEnum inside_parens)
  4127. {
  4128. return ASTNodeWithTailArray::create<CallExpression>(arguments.size(), move(source_range), move(callee), arguments, invocation_style, inside_parens);
  4129. }
  4130. NonnullRefPtr<NewExpression> NewExpression::create(SourceRange source_range, NonnullRefPtr<Expression const> callee, ReadonlySpan<Argument> arguments, InvocationStyleEnum invocation_style, InsideParenthesesEnum inside_parens)
  4131. {
  4132. return ASTNodeWithTailArray::create<NewExpression>(arguments.size(), move(source_range), move(callee), arguments, invocation_style, inside_parens);
  4133. }
  4134. }