AST.cpp 199 KB

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