AST.cpp 189 KB

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