AST.cpp 202 KB

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