AST.cpp 200 KB

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