AST.cpp 189 KB

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