AST.cpp 202 KB

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