AST.cpp 190 KB

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