JavascriptParser.js 195 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { HookMap, SyncBailHook } = require("tapable");
  7. const NormalModule = require("../NormalModule");
  8. const Parser = require("../Parser");
  9. const WebpackError = require("../WebpackError");
  10. const StackedMap = require("../util/StackedMap");
  11. const {
  12. CompilerHintNotationRegExp,
  13. createMagicCommentContext,
  14. getCommentsInRange,
  15. parseCommentOptionsInRange
  16. } = require("../util/magicComment");
  17. const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
  18. const {
  19. LEGACY_ASSERT_ATTRIBUTES,
  20. WebpackParser,
  21. buildLineStarts,
  22. hasOctalEscape,
  23. isIdentifierChar,
  24. positionAt
  25. } = require("./syntax");
  26. /** @typedef {typeof import("acorn").Parser} AcornParser */
  27. /**
  28. * @import {
  29. * Options as AcornOptions,
  30. * ecmaVersion as EcmaVersion
  31. * } from "acorn"
  32. */
  33. /**
  34. * @import {
  35. * AssignmentExpression,
  36. * BinaryExpression,
  37. * BlockStatement,
  38. * SequenceExpression,
  39. * CallExpression,
  40. * StaticBlock,
  41. * ClassDeclaration,
  42. * ForStatement,
  43. * SwitchStatement,
  44. * ClassExpression,
  45. * SourceLocation,
  46. * ConditionalExpression,
  47. * Declaration,
  48. * PrivateIdentifier,
  49. * PropertyDefinition,
  50. * Expression,
  51. * ImportDeclaration,
  52. * Identifier,
  53. * VariableDeclaration,
  54. * IfStatement,
  55. * LabeledStatement,
  56. * Literal,
  57. * LogicalExpression,
  58. * ChainExpression,
  59. * MemberExpression,
  60. * YieldExpression,
  61. * MetaProperty,
  62. * Property,
  63. * AssignmentPattern,
  64. * Pattern,
  65. * UpdateExpression,
  66. * ObjectExpression,
  67. * UnaryExpression,
  68. * ArrayExpression,
  69. * ArrayPattern,
  70. * AwaitExpression,
  71. * ThisExpression,
  72. * RestElement,
  73. * ObjectPattern,
  74. * SwitchCase,
  75. * CatchClause,
  76. * VariableDeclarator,
  77. * ForInStatement,
  78. * ForOfStatement,
  79. * ReturnStatement,
  80. * WithStatement,
  81. * ThrowStatement,
  82. * MethodDefinition,
  83. * NewExpression,
  84. * SpreadElement,
  85. * FunctionExpression,
  86. * WhileStatement,
  87. * ArrowFunctionExpression,
  88. * ExpressionStatement,
  89. * ExportAllDeclaration,
  90. * ExportNamedDeclaration,
  91. * FunctionDeclaration,
  92. * DoWhileStatement,
  93. * TryStatement,
  94. * Node,
  95. * Program,
  96. * Directive,
  97. * Statement,
  98. * ExportDefaultDeclaration,
  99. * Super,
  100. * TaggedTemplateExpression,
  101. * TemplateLiteral,
  102. * ModuleDeclaration,
  103. * MaybeNamedFunctionDeclaration,
  104. * MaybeNamedClassDeclaration
  105. * } from "estree"
  106. */
  107. /** @import { DependencyLocation } from "../Dependency" */
  108. /** @typedef {import("estree").Comment & { start: number, end: number, loc?: SourceLocation | null }} Comment */
  109. /**
  110. * Defines the shared type used by this module.
  111. * @template T
  112. * @typedef {import("tapable").AsArray<T>} AsArray<T>
  113. */
  114. /** @import { ParserState, PreparsedAst } from "../Parser" */
  115. /** @import LocalModule from "../dependencies/LocalModule" */
  116. /**
  117. * @import {
  118. * HarmonyStarExportsList
  119. * } from "../dependencies/HarmonyExportImportedSpecifierDependency"
  120. */
  121. /**
  122. * Defines the known javascript parser state type used by this module.
  123. * @typedef {object} KnownJavascriptParserState
  124. * @property {Set<string>=} harmonyNamedExports
  125. * @property {InstanceType<HarmonyStarExportsList>=} harmonyStarExports
  126. * @property {number=} lastHarmonyImportOrder
  127. * @property {LocalModule[]=} localModules
  128. */
  129. /** @typedef {ParserState & KnownJavascriptParserState} JavascriptParserState */
  130. /** @import Compilation from "../Compilation" */
  131. /** @import Module from "../Module" */
  132. /** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges }} GetInfoResult */
  133. /** @typedef {{ consequent?: EXPECTED_OBJECT, alternate?: EXPECTED_OBJECT }} GuardCollection per-branch guard frames pushed onto the parser state guard stack */
  134. /** @typedef {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} StatementPathItem */
  135. /** @typedef {(ident: string) => void} OnIdentString */
  136. /** @typedef {(ident: string, identifier: Identifier) => void} OnIdent */
  137. /** @typedef {StatementPathItem[]} StatementPath */
  138. /** @typedef {Set<DestructuringAssignmentProperty>} DestructuringAssignmentProperties */
  139. // TODO remove cast when @types/estree has been updated to import phases
  140. /** @typedef {import("estree").ImportExpression & { phase?: "defer" | "source" }} ImportExpression */
  141. /** @type {string[]} */
  142. const EMPTY_ARRAY = [];
  143. /**
  144. * Getter that reverses `arr` in place on first access and caches it. Lighter
  145. * than `memoize(() => arr.reverse())` (one closure instead of two) and called
  146. * per member expression on hot parse paths.
  147. * @template T
  148. * @param {T[]} arr array reversed lazily on first access
  149. * @returns {() => T[]} getter returning the reversed array
  150. */
  151. const lazyReverse = (arr) => {
  152. let reversed = false;
  153. return () => {
  154. if (!reversed) {
  155. arr.reverse();
  156. reversed = true;
  157. }
  158. return arr;
  159. };
  160. };
  161. const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01;
  162. const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10;
  163. const ALLOWED_MEMBER_TYPES_ALL = 0b11;
  164. // Shared `() => false` so the members-optionals fallback in walkCallExpression
  165. // doesn't allocate a fresh closure per identifier-rooted call.
  166. const RETURN_FALSE = () => false;
  167. // Shared `() => []` for the member-less identifier/this evaluation results,
  168. // replacing three fresh closures per evaluated free variable.
  169. const RETURN_EMPTY_ARRAY = () => [];
  170. // Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API
  171. let parser = /** @type {AcornParser} */ (WebpackParser);
  172. /** @typedef {Record<string, string> & { _isLegacyAssert?: boolean }} ImportAttributes */
  173. // Conceptually pairs with ./syntax's LEGACY_ASSERT_ATTRIBUTES marker, but is
  174. // pinned here by its public `JavascriptParser.getImportAttributes` typing.
  175. /**
  176. * Gets import attributes.
  177. * @param {ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration | ImportExpression} node node with assertions
  178. * @returns {ImportAttributes | undefined} import attributes
  179. */
  180. const getImportAttributes = (node) => {
  181. if (node.type === "ImportExpression") {
  182. if (
  183. node.options &&
  184. node.options.type === "ObjectExpression" &&
  185. node.options.properties[0] &&
  186. node.options.properties[0].type === "Property" &&
  187. node.options.properties[0].key.type === "Identifier" &&
  188. (node.options.properties[0].key.name === "with" ||
  189. node.options.properties[0].key.name === "assert") &&
  190. node.options.properties[0].value.type === "ObjectExpression" &&
  191. node.options.properties[0].value.properties.length > 0
  192. ) {
  193. const properties =
  194. /** @type {Property[]} */
  195. (node.options.properties[0].value.properties);
  196. const result = /** @type {ImportAttributes} */ ({});
  197. for (const property of properties) {
  198. const key =
  199. /** @type {string} */
  200. (
  201. property.key.type === "Identifier"
  202. ? property.key.name
  203. : /** @type {Literal} */ (property.key).value
  204. );
  205. result[key] =
  206. /** @type {string} */
  207. (/** @type {Literal} */ (property.value).value);
  208. }
  209. const key =
  210. node.options.properties[0].key.type === "Identifier"
  211. ? node.options.properties[0].key.name
  212. : /** @type {Literal} */ (node.options.properties[0].key).value;
  213. if (key === "assert") {
  214. result._isLegacyAssert = true;
  215. }
  216. return result;
  217. }
  218. return;
  219. }
  220. if (node.attributes === undefined || node.attributes.length === 0) {
  221. return;
  222. }
  223. const result = /** @type {ImportAttributes} */ ({});
  224. for (const attribute of node.attributes) {
  225. const key =
  226. /** @type {string} */
  227. (
  228. attribute.key.type === "Identifier"
  229. ? attribute.key.name
  230. : attribute.key.value
  231. );
  232. result[key] = /** @type {string} */ (attribute.value.value);
  233. }
  234. if (/** @type {EXPECTED_ANY} */ (node.attributes)[LEGACY_ASSERT_ATTRIBUTES]) {
  235. result._isLegacyAssert = true;
  236. }
  237. return result;
  238. };
  239. /** @typedef {typeof VariableInfoFlags.Evaluated | typeof VariableInfoFlags.Free | typeof VariableInfoFlags.Normal | typeof VariableInfoFlags.Tagged} VariableInfoFlagsType */
  240. const VariableInfoFlags = Object.freeze({
  241. Evaluated: 0b000,
  242. Free: 0b001,
  243. Normal: 0b010,
  244. Tagged: 0b100
  245. });
  246. class VariableInfo {
  247. /**
  248. * Creates an instance of VariableInfo.
  249. * @param {ScopeInfo} declaredScope scope in which the variable is declared
  250. * @param {string | undefined} name which name the variable use, defined name or free name or tagged name
  251. * @param {VariableInfoFlagsType} flags how the variable is created
  252. * @param {TagInfo | undefined} tagInfo info about tags
  253. */
  254. constructor(declaredScope, name, flags, tagInfo) {
  255. /** @type {ScopeInfo} */
  256. this.declaredScope = declaredScope;
  257. /** @type {string | undefined} */
  258. this.name = name;
  259. /** @type {VariableInfoFlagsType} */
  260. this.flags = flags;
  261. /** @type {TagInfo | undefined} */
  262. this.tagInfo = tagInfo;
  263. }
  264. /**
  265. * Checks whether this variable info is free.
  266. * @returns {boolean} the variable is free or not
  267. */
  268. isFree() {
  269. return (this.flags & VariableInfoFlags.Free) > 0;
  270. }
  271. /**
  272. * Checks whether this variable info is tagged.
  273. * @returns {boolean} the variable is tagged by tagVariable or not
  274. */
  275. isTagged() {
  276. return (this.flags & VariableInfoFlags.Tagged) > 0;
  277. }
  278. }
  279. /** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */
  280. /** @typedef {Literal | string | null | undefined} ImportSource */
  281. /**
  282. * Defines the internal parse options type used by this module.
  283. * @typedef {Omit<ParseOptions, "sourceType" | "ecmaVersion"> & { sourceType: "module" | "script" | "auto" }} InternalParseOptions
  284. */
  285. /**
  286. * Defines the parse options type used by this module.
  287. * @typedef {object} ParseOptions
  288. * @property {"module" | "script"} sourceType
  289. * @property {EcmaVersion} ecmaVersion
  290. * @property {boolean=} locations
  291. * @property {boolean=} comments
  292. * @property {boolean=} ranges
  293. * @property {boolean=} allowHashBang
  294. * @property {boolean=} allowReturnOutsideFunction
  295. * @property {boolean=} lazyNodes internal: serve `range` lazily and skip acorn's location/range tracking
  296. * @property {Comment[]=} lazyComments internal: collect comments here without slicing their text eagerly
  297. * @property {boolean=} importPhases enable parsing of the import phase proposals (import defer / import source)
  298. * @property {boolean=} moduleFallback internal: for `auto`, let the parser downgrade module->script in place instead of re-parsing
  299. */
  300. /**
  301. * Defines the parse result type used by this module.
  302. * @typedef {object} ParseResult
  303. * @property {Program} ast
  304. * @property {Comment[]} comments
  305. */
  306. /**
  307. * Defines the parse function type used by this module.
  308. * @typedef {(code: string, options: ParseOptions) => ParseResult} ParseFunction
  309. */
  310. /** @typedef {symbol} Tag */
  311. /**
  312. * @import {
  313. * HarmonySettings
  314. * } from "../dependencies/HarmonyImportDependencyParserPlugin"
  315. */
  316. /** @import { ImportSettings } from "../dependencies/ImportParserPlugin" */
  317. /**
  318. * @import {
  319. * CommonJsImportSettings
  320. * } from "../dependencies/CommonJsImportsParserPlugin"
  321. */
  322. /** @import { CompatibilitySettings } from "../CompatibilityPlugin" */
  323. /** @import { TopLevelSymbol } from "../optimize/InnerGraph" */
  324. /** @typedef {HarmonySettings | ImportSettings | CommonJsImportSettings | TopLevelSymbol | CompatibilitySettings} KnownTagData */
  325. /** @typedef {KnownTagData | Record<string, EXPECTED_ANY>} TagData */
  326. /**
  327. * Defines the tag info type used by this module.
  328. * @typedef {object} TagInfo
  329. * @property {Tag} tag
  330. * @property {TagData=} data
  331. * @property {TagInfo | undefined} next
  332. */
  333. /** @typedef {string[]} CalleeMembers */
  334. /** @typedef {string[]} Members */
  335. /** @typedef {boolean[]} MembersOptionals */
  336. /** @typedef {Range[]} MemberRanges */
  337. const SCOPE_INFO_TERMINATED_RETURN = 1;
  338. const SCOPE_INFO_TERMINATED_THROW = 2;
  339. /**
  340. * Defines the scope info type used by this module.
  341. * @typedef {object} ScopeInfo
  342. * @property {StackedMap<string, VariableInfo | ScopeInfo>} definitions
  343. * @property {boolean | "arrow"} topLevelScope
  344. * @property {boolean | string} inShorthand
  345. * @property {boolean} inTaggedTemplateTag
  346. * @property {boolean} inTry
  347. * @property {boolean} isStrict
  348. * @property {boolean} isAsmJs
  349. * @property {undefined | 1 | 2} terminated
  350. */
  351. /** @typedef {[number, number]} Range */
  352. /**
  353. * Defines the destructuring assignment property type used by this module.
  354. * Carries only the range — consumers derive line/column via `getLocation`.
  355. * @typedef {object} DestructuringAssignmentProperty
  356. * @property {string} id
  357. * @property {Range} range
  358. * @property {Set<DestructuringAssignmentProperty> | undefined=} pattern
  359. * @property {boolean | string} shorthand
  360. */
  361. /**
  362. * Helper function for joining two ranges into a single range. This is useful
  363. * when working with AST nodes, as it allows you to combine the ranges of child nodes
  364. * to create the range of the _parent node_.
  365. * @param {Range} startRange start range to join
  366. * @param {Range} endRange end range to join
  367. * @returns {Range} joined range
  368. * @example
  369. * ```js
  370. * const startRange = [0, 5];
  371. * const endRange = [10, 15];
  372. * const joinedRange = joinRanges(startRange, endRange);
  373. * console.log(joinedRange); // [0, 15]
  374. * ```
  375. */
  376. const joinRanges = (startRange, endRange) => {
  377. if (!endRange) return startRange;
  378. if (!startRange) return endRange;
  379. return [startRange[0], endRange[1]];
  380. };
  381. /**
  382. * Helper function used to generate a string representation of a
  383. * [member expression](https://github.com/estree/estree/blob/master/es5.md#memberexpression).
  384. * @param {string} object object to name
  385. * @param {Members} membersReversed reversed list of members
  386. * @returns {string} member expression as a string
  387. * @example
  388. * ```js
  389. * const membersReversed = ["property1", "property2", "property3"]; // Members parsed from the AST
  390. * const name = objectAndMembersToName("myObject", membersReversed);
  391. *
  392. * console.log(name); // "myObject.property1.property2.property3"
  393. * ```
  394. */
  395. const objectAndMembersToName = (object, membersReversed) => {
  396. let name = object;
  397. for (let i = membersReversed.length - 1; i >= 0; i--) {
  398. name = `${name}.${membersReversed[i]}`;
  399. }
  400. return name;
  401. };
  402. /**
  403. * Grabs the name of a given expression and returns it as a string or undefined. Has particular
  404. * handling for [Identifiers](https://github.com/estree/estree/blob/master/es5.md#identifier),
  405. * [ThisExpressions](https://github.com/estree/estree/blob/master/es5.md#identifier), and
  406. * [MetaProperties](https://github.com/estree/estree/blob/master/es2015.md#metaproperty) which is
  407. * specifically for handling the `new.target` meta property.
  408. * @param {Expression | SpreadElement | Super} expression expression
  409. * @returns {string | "this" | undefined} name or variable info
  410. */
  411. const getRootName = (expression) => {
  412. switch (expression.type) {
  413. case "Identifier":
  414. return expression.name;
  415. case "ThisExpression":
  416. return "this";
  417. case "MetaProperty":
  418. return `${expression.meta.name}.${expression.property.name}`;
  419. default:
  420. return undefined;
  421. }
  422. };
  423. /**
  424. * @param {string} type AST node type
  425. * @returns {boolean} true for FunctionExpression or ArrowFunctionExpression
  426. */
  427. const isFunctionExpression = (type) =>
  428. type === "FunctionExpression" || type === "ArrowFunctionExpression";
  429. /**
  430. * @param {FunctionExpression | ArrowFunctionExpression} fn function
  431. * @returns {boolean} true when all params are plain identifiers
  432. */
  433. const isSimpleFunction = (fn) => {
  434. const params = fn.params;
  435. for (let i = 0; i < params.length; i++) {
  436. if (params[i].type !== "Identifier") return false;
  437. }
  438. return true;
  439. };
  440. /** @type {ParseOptions} */
  441. const defaultParserOptions = {
  442. sourceType: "module",
  443. ecmaVersion: "latest",
  444. ranges: false,
  445. locations: false,
  446. comments: false,
  447. // https://github.com/tc39/proposal-hashbang
  448. allowHashBang: true
  449. };
  450. // reused by _parse for every non-custom parse — all fields are reset per parse
  451. /** @type {ParseOptions} */
  452. const REUSED_PARSER_OPTIONS = { ...defaultParserOptions };
  453. // Read-only snippet ASTs for `evaluate()`, released with the compilation;
  454. // DefinePlugin evaluates the same strings once per usage per module.
  455. /** @type {WeakMap<Compilation, Map<string, Program>>} */
  456. const evaluateAstCaches = new WeakMap();
  457. // The inner map is strong while the compilation lives, so cap it
  458. const EVALUATE_AST_CACHE_LIMIT = 4096;
  459. const CLASS_NAME = "JavascriptParser";
  460. // Reserved words in strict mode, so unusable as binding names there (12.7.2).
  461. const STRICT_MODE_RESERVED_WORDS = new Set([
  462. "implements",
  463. "interface",
  464. "let",
  465. "package",
  466. "private",
  467. "protected",
  468. "public",
  469. "static",
  470. "yield"
  471. ]);
  472. const STRICT_MODE_OUTPUT_REASON =
  473. "The output is an ES module, which runs in strict mode.";
  474. // `await` is reserved by the module goal rather than by strict mode itself.
  475. const MODULE_GOAL_OUTPUT_REASON =
  476. 'The output is an ES module, where "await" is a reserved word.';
  477. class JavascriptParser extends Parser {
  478. /**
  479. * Creates an instance of JavascriptParser.
  480. * @param {"module" | "script" | "auto"=} sourceType default source type
  481. * @param {{ parse?: ParseFunction, typescript?: boolean, importPhases?: boolean, strictModeViolations?: "error" | "warn" | false }=} options parser options
  482. */
  483. constructor(sourceType = "auto", options = {}) {
  484. super();
  485. this.hooks = Object.freeze({
  486. /** @type {HookMap<SyncBailHook<[UnaryExpression], BasicEvaluatedExpression | null | undefined>>} */
  487. evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])),
  488. /** @type {HookMap<SyncBailHook<[Expression | SpreadElement | PrivateIdentifier | Super], BasicEvaluatedExpression | null | undefined>>} */
  489. evaluate: new HookMap(() => new SyncBailHook(["expression"])),
  490. /** @type {HookMap<SyncBailHook<[Identifier | ThisExpression | MemberExpression | MetaProperty], BasicEvaluatedExpression | null | undefined>>} */
  491. evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])),
  492. /** @type {HookMap<SyncBailHook<[Identifier | ThisExpression | MemberExpression], BasicEvaluatedExpression | null | undefined>>} */
  493. evaluateDefinedIdentifier: new HookMap(
  494. () => new SyncBailHook(["expression"])
  495. ),
  496. /**
  497. * @type {HookMap<SyncBailHook<[NewExpression], BasicEvaluatedExpression | null | undefined>>}
  498. * @since 5.73.0
  499. */
  500. evaluateNewExpression: new HookMap(
  501. () => new SyncBailHook(["expression"])
  502. ),
  503. /**
  504. * @type {HookMap<SyncBailHook<[CallExpression], BasicEvaluatedExpression | null | undefined>>}
  505. * @since 5.73.0
  506. */
  507. evaluateCallExpression: new HookMap(
  508. () => new SyncBailHook(["expression"])
  509. ),
  510. /** @type {HookMap<SyncBailHook<[CallExpression, BasicEvaluatedExpression], BasicEvaluatedExpression | null | undefined>>} */
  511. evaluateCallExpressionMember: new HookMap(
  512. () => new SyncBailHook(["expression", "param"])
  513. ),
  514. /** @type {HookMap<SyncBailHook<[Expression | Declaration | PrivateIdentifier | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration, number], boolean | void>>} */
  515. isPure: new HookMap(
  516. () => new SyncBailHook(["expression", "commentsStartPosition"])
  517. ),
  518. /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration], boolean | void>} */
  519. preStatement: new SyncBailHook(["statement"]),
  520. /**
  521. * @type {HookMap<SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration], boolean | void>>}
  522. * @since 5.109.0
  523. */
  524. preStatementByType: new HookMap(() => new SyncBailHook(["statement"])),
  525. /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration], boolean | void>} */
  526. blockPreStatement: new SyncBailHook(["declaration"]),
  527. /**
  528. * @type {HookMap<SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration], boolean | void>>}
  529. * @since 5.109.0
  530. */
  531. blockPreStatementByType: new HookMap(
  532. () => new SyncBailHook(["declaration"])
  533. ),
  534. /** @type {SyncBailHook<[Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
  535. statement: new SyncBailHook(["statement"]),
  536. /** @type {SyncBailHook<[IfStatement], boolean | void>} */
  537. statementIf: new SyncBailHook(["statement"]),
  538. /**
  539. * @type {SyncBailHook<[Expression], GuardCollection | void>}
  540. * @since 5.105.0
  541. */
  542. collectGuards: new SyncBailHook(["expression"]),
  543. /** @type {SyncBailHook<[Expression, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
  544. classExtendsExpression: new SyncBailHook([
  545. "expression",
  546. "classDefinition"
  547. ]),
  548. /** @type {SyncBailHook<[MethodDefinition | PropertyDefinition | StaticBlock, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>} */
  549. classBodyElement: new SyncBailHook(["element", "classDefinition"]),
  550. /**
  551. * @type {SyncBailHook<[Expression, MethodDefinition | PropertyDefinition, ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration], boolean | void>}
  552. * @since 5.36.0
  553. */
  554. classBodyValue: new SyncBailHook([
  555. "expression",
  556. "element",
  557. "classDefinition"
  558. ]),
  559. /** @type {HookMap<SyncBailHook<[LabeledStatement], boolean | void>>} */
  560. label: new HookMap(() => new SyncBailHook(["statement"])),
  561. /** @type {SyncBailHook<[ImportDeclaration, ImportSource], boolean | void>} */
  562. import: new SyncBailHook(["statement", "source"]),
  563. /** @type {SyncBailHook<[ImportDeclaration, ImportSource, string | null, string], boolean | void>} */
  564. importSpecifier: new SyncBailHook([
  565. "statement",
  566. "source",
  567. "exportName",
  568. "identifierName"
  569. ]),
  570. /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration], boolean | void>} */
  571. export: new SyncBailHook(["statement"]),
  572. /** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource], boolean | void>} */
  573. exportImport: new SyncBailHook(["statement", "source"]),
  574. /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration | ExportAllDeclaration, Declaration], boolean | void>} */
  575. exportDeclaration: new SyncBailHook(["statement", "declaration"]),
  576. /** @type {SyncBailHook<[ExportDefaultDeclaration, MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression], boolean | void>} */
  577. exportExpression: new SyncBailHook(["statement", "node"]),
  578. /** @type {SyncBailHook<[ExportDefaultDeclaration | ExportNamedDeclaration | ExportAllDeclaration, string, string, number | undefined], boolean | void>} */
  579. exportSpecifier: new SyncBailHook([
  580. "statement",
  581. "identifierName",
  582. "exportName",
  583. "index"
  584. ]),
  585. /** @type {SyncBailHook<[ExportNamedDeclaration | ExportAllDeclaration, ImportSource, string | null, string | null, number | undefined], boolean | void>} */
  586. exportImportSpecifier: new SyncBailHook([
  587. "statement",
  588. "source",
  589. "identifierName",
  590. "exportName",
  591. "index"
  592. ]),
  593. /** @type {SyncBailHook<[VariableDeclarator, VariableDeclaration], boolean | void>} */
  594. preDeclarator: new SyncBailHook(["declarator", "statement"]),
  595. /** @type {SyncBailHook<[VariableDeclarator, Statement], boolean | void>} */
  596. declarator: new SyncBailHook(["declarator", "statement"]),
  597. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  598. varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])),
  599. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  600. varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])),
  601. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  602. varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])),
  603. /**
  604. * @type {HookMap<SyncBailHook<[Identifier], boolean | void>>}
  605. * @since 5.100.0
  606. */
  607. varDeclarationUsing: new HookMap(() => new SyncBailHook(["declaration"])),
  608. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  609. varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])),
  610. /** @type {HookMap<SyncBailHook<[Identifier], boolean | void>>} */
  611. pattern: new HookMap(() => new SyncBailHook(["pattern"])),
  612. /**
  613. * @type {SyncBailHook<[Expression], boolean | void>}
  614. * @since 5.101.3
  615. */
  616. collectDestructuringAssignmentProperties: new SyncBailHook([
  617. "expression"
  618. ]),
  619. /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
  620. canRename: new HookMap(() => new SyncBailHook(["initExpression"])),
  621. /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
  622. rename: new HookMap(() => new SyncBailHook(["initExpression"])),
  623. /** @type {HookMap<SyncBailHook<[AssignmentExpression], boolean | void>>} */
  624. assign: new HookMap(() => new SyncBailHook(["expression"])),
  625. /** @type {HookMap<SyncBailHook<[AssignmentExpression, Members], boolean | void>>} */
  626. assignMemberChain: new HookMap(
  627. () => new SyncBailHook(["expression", "members"])
  628. ),
  629. /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
  630. typeof: new HookMap(() => new SyncBailHook(["expression"])),
  631. /** @type {SyncBailHook<[ImportExpression, CallExpression?], boolean | void>} */
  632. importCall: new SyncBailHook(["expression", "importThen"]),
  633. /** @type {SyncBailHook<[Expression | ForOfStatement | VariableDeclaration], boolean | void>} */
  634. topLevelAwait: new SyncBailHook(["expression"]),
  635. /** @type {HookMap<SyncBailHook<[CallExpression], boolean | void>>} */
  636. call: new HookMap(() => new SyncBailHook(["expression"])),
  637. /** Something like "a.b()" */
  638. /** @type {HookMap<SyncBailHook<[CallExpression, Members, MembersOptionals, MemberRanges], boolean | void>>} */
  639. callMemberChain: new HookMap(
  640. () =>
  641. new SyncBailHook([
  642. "expression",
  643. "members",
  644. "membersOptionals",
  645. "memberRanges"
  646. ])
  647. ),
  648. /** Something like "a.b().c.d" */
  649. /** @type {HookMap<SyncBailHook<[Expression, CalleeMembers, CallExpression, Members, MemberRanges], boolean | void>>} */
  650. memberChainOfCallMemberChain: new HookMap(
  651. () =>
  652. new SyncBailHook([
  653. "expression",
  654. "calleeMembers",
  655. "callExpression",
  656. "members",
  657. "memberRanges"
  658. ])
  659. ),
  660. /** Something like "a.b().c.d()"" */
  661. /** @type {HookMap<SyncBailHook<[CallExpression, CalleeMembers, CallExpression, Members, MemberRanges], boolean | void>>} */
  662. callMemberChainOfCallMemberChain: new HookMap(
  663. () =>
  664. new SyncBailHook([
  665. "expression",
  666. "calleeMembers",
  667. "innerCallExpression",
  668. "members",
  669. "memberRanges"
  670. ])
  671. ),
  672. /** @type {SyncBailHook<[ChainExpression], boolean | void>} */
  673. optionalChaining: new SyncBailHook(["optionalChaining"]),
  674. /** @type {HookMap<SyncBailHook<[NewExpression], boolean | void>>} */
  675. new: new HookMap(() => new SyncBailHook(["expression"])),
  676. /**
  677. * @type {SyncBailHook<[BinaryExpression], boolean | void>}
  678. * @since 5.71.0
  679. */
  680. binaryExpression: new SyncBailHook(["binaryExpression"]),
  681. /** @type {HookMap<SyncBailHook<[Expression], boolean | void>>} */
  682. expression: new HookMap(() => new SyncBailHook(["expression"])),
  683. /** @type {HookMap<SyncBailHook<[MemberExpression, Members, MembersOptionals, MemberRanges], boolean | void>>} */
  684. expressionMemberChain: new HookMap(
  685. () =>
  686. new SyncBailHook([
  687. "expression",
  688. "members",
  689. "membersOptionals",
  690. "memberRanges"
  691. ])
  692. ),
  693. /** @type {HookMap<SyncBailHook<[MemberExpression, Members], boolean | void>>} */
  694. unhandledExpressionMemberChain: new HookMap(
  695. () => new SyncBailHook(["expression", "members"])
  696. ),
  697. /** @type {SyncBailHook<[ConditionalExpression], boolean | void>} */
  698. expressionConditionalOperator: new SyncBailHook(["expression"]),
  699. /** @type {SyncBailHook<[LogicalExpression], boolean | void>} */
  700. expressionLogicalOperator: new SyncBailHook(["expression"]),
  701. /** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */
  702. program: new SyncBailHook(["ast", "comments"]),
  703. /**
  704. * @type {SyncBailHook<[ThrowStatement | ReturnStatement], boolean | void>}
  705. * @since 5.99.0
  706. */
  707. terminate: new SyncBailHook(["statement"]),
  708. /** @type {SyncBailHook<[Program, Comment[]], boolean | void>} */
  709. finish: new SyncBailHook(["ast", "comments"]),
  710. /**
  711. * @type {SyncBailHook<[Statement], boolean | void>}
  712. * @since 5.99.9
  713. */
  714. unusedStatement: new SyncBailHook(["statement"])
  715. });
  716. this.sourceType = sourceType;
  717. this.options = options;
  718. /** @type {ScopeInfo} */
  719. this.scope = /** @type {EXPECTED_ANY} */ (undefined);
  720. /** @type {JavascriptParserState} */
  721. this.state = /** @type {EXPECTED_ANY} */ (undefined);
  722. /** @type {Comment[] | undefined} */
  723. this.comments = undefined;
  724. // ASI overrides keyed by statement-end offset: true forces an ASI
  725. // position, false forces a real semicolon. Absent offsets are derived
  726. // from the source text. Allocated lazily by set/unsetAsiPosition.
  727. /** @type {Map<number, boolean> | undefined} */
  728. this.semicolons = undefined;
  729. /** @type {StatementPath | undefined} */
  730. this.statementPath = undefined;
  731. /** @type {Statement | ModuleDeclaration | Expression | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | undefined} */
  732. this.prevStatement = undefined;
  733. /** @type {WeakMap<Expression, DestructuringAssignmentProperties> | undefined} */
  734. this.destructuringAssignmentProperties = undefined;
  735. /** @type {TagData | undefined} */
  736. this.currentTagData = undefined;
  737. // True while parsing a loose module whose code is emitted as strict ESM.
  738. this._strictInModuleOutput = false;
  739. // Source text of the current parse, for offset → line/column mapping.
  740. /** @type {string | undefined} */
  741. this._source = undefined;
  742. // Offset of each line's first character, built on first getLocation use.
  743. /** @type {number[] | undefined} */
  744. this._lineStarts = undefined;
  745. // True while only the parser's own taps sit on evaluate.for("Identifier");
  746. // recomputed per parse, gates the defined-identifier fast paths.
  747. this._evalIdentOwnTaps = false;
  748. this.magicCommentContext = createMagicCommentContext();
  749. // Reused for enterPatterns on every scope entry to avoid per-scope closures.
  750. /** @type {OnIdentString} */
  751. this._defineVariable = (ident) => this.defineVariable(ident);
  752. this._initializeEvaluating();
  753. // keyed taps are free for every other member chain, and a shadowed
  754. // `arguments` binding never dispatches the free-variable hooks
  755. this.hooks.expressionMemberChain
  756. .for("arguments")
  757. .tap(CLASS_NAME, (expression, members) => {
  758. if (this._strictInModuleOutput) {
  759. this._checkStrictModeArgumentsMember(members[0], expression);
  760. }
  761. });
  762. this.hooks.callMemberChain
  763. .for("arguments")
  764. .tap(CLASS_NAME, (expression, members) => {
  765. // longer chains re-enter the member walk, which reports them
  766. if (this._strictInModuleOutput && members.length === 1) {
  767. this._checkStrictModeArgumentsMember(members[0], expression);
  768. }
  769. });
  770. }
  771. _initializeEvaluating() {
  772. this.hooks.evaluate.for("Literal").tap(CLASS_NAME, (_expr) => {
  773. const expr = /** @type {Literal} */ (_expr);
  774. switch (typeof expr.value) {
  775. case "number":
  776. return new BasicEvaluatedExpression()
  777. .setNumber(expr.value)
  778. .setRange(/** @type {Range} */ (expr.range));
  779. case "bigint":
  780. return new BasicEvaluatedExpression()
  781. .setBigInt(expr.value)
  782. .setRange(/** @type {Range} */ (expr.range));
  783. case "string":
  784. return new BasicEvaluatedExpression()
  785. .setString(expr.value)
  786. .setRange(/** @type {Range} */ (expr.range));
  787. case "boolean":
  788. return new BasicEvaluatedExpression()
  789. .setBoolean(expr.value)
  790. .setRange(/** @type {Range} */ (expr.range));
  791. }
  792. if (expr.value === null) {
  793. return new BasicEvaluatedExpression()
  794. .setNull()
  795. .setRange(/** @type {Range} */ (expr.range));
  796. }
  797. if (expr.value instanceof RegExp) {
  798. return new BasicEvaluatedExpression()
  799. .setRegExp(expr.value)
  800. .setRange(/** @type {Range} */ (expr.range));
  801. }
  802. });
  803. this.hooks.evaluate.for("NewExpression").tap(CLASS_NAME, (_expr) => {
  804. const expr = /** @type {NewExpression} */ (_expr);
  805. const callee = expr.callee;
  806. if (callee.type !== "Identifier") return;
  807. if (callee.name !== "RegExp") {
  808. return this.callHooksForName(
  809. this.hooks.evaluateNewExpression,
  810. callee.name,
  811. expr
  812. );
  813. } else if (
  814. expr.arguments.length > 2 ||
  815. this.getVariableInfo("RegExp") !== "RegExp"
  816. ) {
  817. return;
  818. }
  819. /** @type {undefined | string} */
  820. let regExp;
  821. const arg1 = expr.arguments[0];
  822. if (arg1) {
  823. if (arg1.type === "SpreadElement") return;
  824. const evaluatedRegExp = this.evaluateExpression(arg1);
  825. if (!evaluatedRegExp) return;
  826. regExp = evaluatedRegExp.asString();
  827. if (!regExp) return;
  828. } else {
  829. return (
  830. new BasicEvaluatedExpression()
  831. // eslint-disable-next-line prefer-regex-literals
  832. .setRegExp(new RegExp(""))
  833. .setRange(/** @type {Range} */ (expr.range))
  834. );
  835. }
  836. /** @type {undefined | string} */
  837. let flags;
  838. const arg2 = expr.arguments[1];
  839. if (arg2) {
  840. if (arg2.type === "SpreadElement") return;
  841. const evaluatedFlags = this.evaluateExpression(arg2);
  842. if (!evaluatedFlags) return;
  843. if (!evaluatedFlags.isUndefined()) {
  844. flags = evaluatedFlags.asString();
  845. if (
  846. flags === undefined ||
  847. !BasicEvaluatedExpression.isValidRegExpFlags(flags)
  848. ) {
  849. return;
  850. }
  851. }
  852. }
  853. return new BasicEvaluatedExpression()
  854. .setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp))
  855. .setRange(/** @type {Range} */ (expr.range));
  856. });
  857. this.hooks.evaluate.for("LogicalExpression").tap(CLASS_NAME, (_expr) => {
  858. const expr = /** @type {LogicalExpression} */ (_expr);
  859. const left = this.evaluateExpression(expr.left);
  860. let returnRight = false;
  861. /** @type {boolean | undefined} */
  862. let allowedRight;
  863. if (expr.operator === "&&") {
  864. const leftAsBool = left.asBool();
  865. if (leftAsBool === false) {
  866. return left.setRange(/** @type {Range} */ (expr.range));
  867. }
  868. returnRight = leftAsBool === true;
  869. allowedRight = false;
  870. } else if (expr.operator === "||") {
  871. const leftAsBool = left.asBool();
  872. if (leftAsBool === true) {
  873. return left.setRange(/** @type {Range} */ (expr.range));
  874. }
  875. returnRight = leftAsBool === false;
  876. allowedRight = true;
  877. } else if (expr.operator === "??") {
  878. const leftAsNullish = left.asNullish();
  879. if (leftAsNullish === false) {
  880. return left.setRange(/** @type {Range} */ (expr.range));
  881. }
  882. if (leftAsNullish !== true) return;
  883. returnRight = true;
  884. } else {
  885. return;
  886. }
  887. const right = this.evaluateExpression(expr.right);
  888. if (returnRight) {
  889. if (left.couldHaveSideEffects()) right.setSideEffects();
  890. return right.setRange(/** @type {Range} */ (expr.range));
  891. }
  892. const asBool = right.asBool();
  893. if (allowedRight === true && asBool === true) {
  894. return new BasicEvaluatedExpression()
  895. .setRange(/** @type {Range} */ (expr.range))
  896. .setTruthy();
  897. } else if (allowedRight === false && asBool === false) {
  898. return new BasicEvaluatedExpression()
  899. .setRange(/** @type {Range} */ (expr.range))
  900. .setFalsy();
  901. }
  902. });
  903. /**
  904. * In simple logical cases, we can use valueAsExpression to assist us in evaluating the expression on
  905. * either side of a [BinaryExpression](https://github.com/estree/estree/blob/master/es5.md#binaryexpression).
  906. * This supports scenarios in webpack like conditionally `import()`'ing modules based on some simple evaluation:
  907. *
  908. * ```js
  909. * if (1 === 3) {
  910. * import("./moduleA"); // webpack will auto evaluate this and not import the modules
  911. * }
  912. * ```
  913. *
  914. * Additional scenarios include evaluation of strings inside of dynamic import statements:
  915. *
  916. * ```js
  917. * const foo = "foo";
  918. * const bar = "bar";
  919. *
  920. * import("./" + foo + bar); // webpack will auto evaluate this into import("./foobar")
  921. * ```
  922. * @param {boolean | number | bigint | string} value the value to convert to an expression
  923. * @param {BinaryExpression | UnaryExpression} expr the expression being evaluated
  924. * @param {boolean} sideEffects whether the expression has side effects
  925. * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
  926. * @example
  927. *
  928. * ```js
  929. * const binaryExpr = new BinaryExpression("+",
  930. * { type: "Literal", value: 2 },
  931. * { type: "Literal", value: 3 }
  932. * );
  933. *
  934. * const leftValue = 2;
  935. * const rightValue = 3;
  936. *
  937. * const leftExpr = valueAsExpression(leftValue, binaryExpr.left, false);
  938. * const rightExpr = valueAsExpression(rightValue, binaryExpr.right, false);
  939. * const result = new BasicEvaluatedExpression()
  940. * .setNumber(leftExpr.number + rightExpr.number)
  941. * .setRange(binaryExpr.range);
  942. *
  943. * console.log(result.number); // Output: 5
  944. * ```
  945. */
  946. const valueAsExpression = (value, expr, sideEffects) => {
  947. switch (typeof value) {
  948. case "boolean":
  949. return new BasicEvaluatedExpression()
  950. .setBoolean(value)
  951. .setSideEffects(sideEffects)
  952. .setRange(/** @type {Range} */ (expr.range));
  953. case "number":
  954. return new BasicEvaluatedExpression()
  955. .setNumber(value)
  956. .setSideEffects(sideEffects)
  957. .setRange(/** @type {Range} */ (expr.range));
  958. case "bigint":
  959. return new BasicEvaluatedExpression()
  960. .setBigInt(value)
  961. .setSideEffects(sideEffects)
  962. .setRange(/** @type {Range} */ (expr.range));
  963. case "string":
  964. return new BasicEvaluatedExpression()
  965. .setString(value)
  966. .setSideEffects(sideEffects)
  967. .setRange(/** @type {Range} */ (expr.range));
  968. }
  969. };
  970. this.hooks.evaluate.for("BinaryExpression").tap(CLASS_NAME, (_expr) => {
  971. const expr = /** @type {BinaryExpression} */ (_expr);
  972. /**
  973. * Evaluates a binary expression if and only if it is a const operation (e.g. 1 + 2, "a" + "b", etc.).
  974. * @template T
  975. * @param {(leftOperand: T, rightOperand: T) => boolean | number | bigint | string} operandHandler the handler for the operation (e.g. (a, b) => a + b)
  976. * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
  977. */
  978. const handleConstOperation = (operandHandler) => {
  979. const left = this.evaluateExpression(expr.left);
  980. if (!left.isCompileTimeValue()) return;
  981. const right = this.evaluateExpression(expr.right);
  982. if (!right.isCompileTimeValue()) return;
  983. const result = operandHandler(
  984. /** @type {T} */ (left.asCompileTimeValue()),
  985. /** @type {T} */ (right.asCompileTimeValue())
  986. );
  987. return valueAsExpression(
  988. result,
  989. expr,
  990. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  991. );
  992. };
  993. /**
  994. * Helper function to determine if two booleans are always different. This is used in `handleStrictEqualityComparison`
  995. * to determine if an expressions boolean or nullish conversion is equal or not.
  996. * @param {boolean} a first boolean to compare
  997. * @param {boolean} b second boolean to compare
  998. * @returns {boolean} true if the two booleans are always different, false otherwise
  999. */
  1000. const isAlwaysDifferent = (a, b) =>
  1001. (a === true && b === false) || (a === false && b === true);
  1002. /**
  1003. * Handle template string compare.
  1004. * @param {BasicEvaluatedExpression} left left
  1005. * @param {BasicEvaluatedExpression} right right
  1006. * @param {BasicEvaluatedExpression} res res
  1007. * @param {boolean} eql true for "===" and false for "!=="
  1008. * @returns {BasicEvaluatedExpression | undefined} result
  1009. */
  1010. const handleTemplateStringCompare = (left, right, res, eql) => {
  1011. /**
  1012. * Returns value.
  1013. * @param {BasicEvaluatedExpression[]} parts parts
  1014. * @returns {string} value
  1015. */
  1016. const getPrefix = (parts) => {
  1017. let value = "";
  1018. for (const p of parts) {
  1019. const v = p.asString();
  1020. if (v !== undefined) value += v;
  1021. else break;
  1022. }
  1023. return value;
  1024. };
  1025. /**
  1026. * Returns value.
  1027. * @param {BasicEvaluatedExpression[]} parts parts
  1028. * @returns {string} value
  1029. */
  1030. const getSuffix = (parts) => {
  1031. let value = "";
  1032. for (let i = parts.length - 1; i >= 0; i--) {
  1033. const v = parts[i].asString();
  1034. if (v !== undefined) value = v + value;
  1035. else break;
  1036. }
  1037. return value;
  1038. };
  1039. const leftPrefix = getPrefix(
  1040. /** @type {BasicEvaluatedExpression[]} */ (left.parts)
  1041. );
  1042. const rightPrefix = getPrefix(
  1043. /** @type {BasicEvaluatedExpression[]} */ (right.parts)
  1044. );
  1045. const leftSuffix = getSuffix(
  1046. /** @type {BasicEvaluatedExpression[]} */ (left.parts)
  1047. );
  1048. const rightSuffix = getSuffix(
  1049. /** @type {BasicEvaluatedExpression[]} */ (right.parts)
  1050. );
  1051. const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length);
  1052. const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length);
  1053. const prefixMismatch =
  1054. lenPrefix > 0 &&
  1055. leftPrefix.slice(0, lenPrefix) !== rightPrefix.slice(0, lenPrefix);
  1056. const suffixMismatch =
  1057. lenSuffix > 0 &&
  1058. leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix);
  1059. if (prefixMismatch || suffixMismatch) {
  1060. return res
  1061. .setBoolean(!eql)
  1062. .setSideEffects(
  1063. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  1064. );
  1065. }
  1066. };
  1067. /**
  1068. * Helper function to handle BinaryExpressions using strict equality comparisons (e.g. "===" and "!==").
  1069. * @param {boolean} eql true for "===" and false for "!=="
  1070. * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
  1071. */
  1072. const handleStrictEqualityComparison = (eql) => {
  1073. const left = this.evaluateExpression(expr.left);
  1074. const right = this.evaluateExpression(expr.right);
  1075. const res = new BasicEvaluatedExpression();
  1076. res.setRange(/** @type {Range} */ (expr.range));
  1077. const leftConst = left.isCompileTimeValue();
  1078. const rightConst = right.isCompileTimeValue();
  1079. if (leftConst && rightConst) {
  1080. return res
  1081. .setBoolean(
  1082. eql === (left.asCompileTimeValue() === right.asCompileTimeValue())
  1083. )
  1084. .setSideEffects(
  1085. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  1086. );
  1087. }
  1088. if (left.isArray() && right.isArray()) {
  1089. return res
  1090. .setBoolean(!eql)
  1091. .setSideEffects(
  1092. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  1093. );
  1094. }
  1095. if (left.isTemplateString() && right.isTemplateString()) {
  1096. return handleTemplateStringCompare(left, right, res, eql);
  1097. }
  1098. const leftPrimitive = left.isPrimitiveType();
  1099. const rightPrimitive = right.isPrimitiveType();
  1100. if (
  1101. // Primitive !== Object or
  1102. // compile-time object types are never equal to something at runtime
  1103. (leftPrimitive === false && (leftConst || rightPrimitive === true)) ||
  1104. (rightPrimitive === false &&
  1105. (rightConst || leftPrimitive === true)) ||
  1106. // Different nullish or boolish status also means not equal
  1107. isAlwaysDifferent(
  1108. /** @type {boolean} */ (left.asBool()),
  1109. /** @type {boolean} */ (right.asBool())
  1110. ) ||
  1111. isAlwaysDifferent(
  1112. /** @type {boolean} */ (left.asNullish()),
  1113. /** @type {boolean} */ (right.asNullish())
  1114. )
  1115. ) {
  1116. return res
  1117. .setBoolean(!eql)
  1118. .setSideEffects(
  1119. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  1120. );
  1121. }
  1122. };
  1123. /**
  1124. * Helper function to handle BinaryExpressions using abstract equality comparisons (e.g. "==" and "!=").
  1125. * @param {boolean} eql true for "==" and false for "!="
  1126. * @returns {BasicEvaluatedExpression | undefined} the evaluated expression
  1127. */
  1128. const handleAbstractEqualityComparison = (eql) => {
  1129. const left = this.evaluateExpression(expr.left);
  1130. const right = this.evaluateExpression(expr.right);
  1131. const res = new BasicEvaluatedExpression();
  1132. res.setRange(/** @type {Range} */ (expr.range));
  1133. const leftConst = left.isCompileTimeValue();
  1134. const rightConst = right.isCompileTimeValue();
  1135. if (leftConst && rightConst) {
  1136. return res
  1137. .setBoolean(
  1138. eql ===
  1139. // eslint-disable-next-line eqeqeq
  1140. (left.asCompileTimeValue() == right.asCompileTimeValue())
  1141. )
  1142. .setSideEffects(
  1143. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  1144. );
  1145. }
  1146. if (left.isArray() && right.isArray()) {
  1147. return res
  1148. .setBoolean(!eql)
  1149. .setSideEffects(
  1150. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  1151. );
  1152. }
  1153. if (left.isTemplateString() && right.isTemplateString()) {
  1154. return handleTemplateStringCompare(left, right, res, eql);
  1155. }
  1156. };
  1157. if (expr.operator === "+") {
  1158. const left = this.evaluateExpression(expr.left);
  1159. const right = this.evaluateExpression(expr.right);
  1160. const res = new BasicEvaluatedExpression();
  1161. if (left.isString()) {
  1162. if (right.isString()) {
  1163. res.setString(
  1164. /** @type {string} */ (left.string) +
  1165. /** @type {string} */ (right.string)
  1166. );
  1167. } else if (right.isNumber()) {
  1168. res.setString(/** @type {string} */ (left.string) + right.number);
  1169. } else if (
  1170. right.isWrapped() &&
  1171. right.prefix &&
  1172. right.prefix.isString()
  1173. ) {
  1174. // "left" + ("prefix" + inner + "postfix")
  1175. // => ("leftPrefix" + inner + "postfix")
  1176. res.setWrapped(
  1177. new BasicEvaluatedExpression()
  1178. .setString(
  1179. /** @type {string} */ (left.string) +
  1180. /** @type {string} */ (right.prefix.string)
  1181. )
  1182. .setRange(
  1183. joinRanges(
  1184. /** @type {Range} */ (left.range),
  1185. /** @type {Range} */ (right.prefix.range)
  1186. )
  1187. ),
  1188. right.postfix,
  1189. right.wrappedInnerExpressions
  1190. );
  1191. } else if (right.isWrapped()) {
  1192. // "left" + ([null] + inner + "postfix")
  1193. // => ("left" + inner + "postfix")
  1194. res.setWrapped(left, right.postfix, right.wrappedInnerExpressions);
  1195. } else {
  1196. // "left" + expr
  1197. // => ("left" + expr + "")
  1198. res.setWrapped(left, null, [right]);
  1199. }
  1200. } else if (left.isNumber()) {
  1201. if (right.isString()) {
  1202. res.setString(left.number + /** @type {string} */ (right.string));
  1203. } else if (right.isNumber()) {
  1204. res.setNumber(
  1205. /** @type {number} */ (left.number) +
  1206. /** @type {number} */ (right.number)
  1207. );
  1208. } else {
  1209. return;
  1210. }
  1211. } else if (left.isBigInt()) {
  1212. if (right.isBigInt()) {
  1213. res.setBigInt(
  1214. /** @type {bigint} */ (left.bigint) +
  1215. /** @type {bigint} */ (right.bigint)
  1216. );
  1217. }
  1218. } else if (left.isWrapped()) {
  1219. if (left.postfix && left.postfix.isString() && right.isString()) {
  1220. // ("prefix" + inner + "postfix") + "right"
  1221. // => ("prefix" + inner + "postfixRight")
  1222. res.setWrapped(
  1223. left.prefix,
  1224. new BasicEvaluatedExpression()
  1225. .setString(
  1226. /** @type {string} */ (left.postfix.string) +
  1227. /** @type {string} */ (right.string)
  1228. )
  1229. .setRange(
  1230. joinRanges(
  1231. /** @type {Range} */ (left.postfix.range),
  1232. /** @type {Range} */ (right.range)
  1233. )
  1234. ),
  1235. left.wrappedInnerExpressions
  1236. );
  1237. } else if (
  1238. left.postfix &&
  1239. left.postfix.isString() &&
  1240. right.isNumber()
  1241. ) {
  1242. // ("prefix" + inner + "postfix") + 123
  1243. // => ("prefix" + inner + "postfix123")
  1244. res.setWrapped(
  1245. left.prefix,
  1246. new BasicEvaluatedExpression()
  1247. .setString(
  1248. /** @type {string} */ (left.postfix.string) +
  1249. /** @type {number} */ (right.number)
  1250. )
  1251. .setRange(
  1252. joinRanges(
  1253. /** @type {Range} */ (left.postfix.range),
  1254. /** @type {Range} */ (right.range)
  1255. )
  1256. ),
  1257. left.wrappedInnerExpressions
  1258. );
  1259. } else if (right.isString()) {
  1260. // ("prefix" + inner + [null]) + "right"
  1261. // => ("prefix" + inner + "right")
  1262. res.setWrapped(left.prefix, right, left.wrappedInnerExpressions);
  1263. } else if (right.isNumber()) {
  1264. // ("prefix" + inner + [null]) + 123
  1265. // => ("prefix" + inner + "123")
  1266. res.setWrapped(
  1267. left.prefix,
  1268. new BasicEvaluatedExpression()
  1269. .setString(String(right.number))
  1270. .setRange(/** @type {Range} */ (right.range)),
  1271. left.wrappedInnerExpressions
  1272. );
  1273. } else if (right.isWrapped()) {
  1274. // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2")
  1275. // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2")
  1276. res.setWrapped(
  1277. left.prefix,
  1278. right.postfix,
  1279. left.wrappedInnerExpressions &&
  1280. right.wrappedInnerExpressions && [
  1281. ...left.wrappedInnerExpressions,
  1282. ...(left.postfix ? [left.postfix] : []),
  1283. ...(right.prefix ? [right.prefix] : []),
  1284. ...right.wrappedInnerExpressions
  1285. ]
  1286. );
  1287. } else {
  1288. // ("prefix" + inner + postfix) + expr
  1289. // => ("prefix" + inner + postfix + expr + [null])
  1290. res.setWrapped(
  1291. left.prefix,
  1292. null,
  1293. left.wrappedInnerExpressions && [
  1294. ...left.wrappedInnerExpressions,
  1295. ...(left.postfix ? [left.postfix, right] : [right])
  1296. ]
  1297. );
  1298. }
  1299. } else if (right.isString()) {
  1300. // left + "right"
  1301. // => ([null] + left + "right")
  1302. res.setWrapped(null, right, [left]);
  1303. } else if (right.isWrapped()) {
  1304. // left + (prefix + inner + "postfix")
  1305. // => ([null] + left + prefix + inner + "postfix")
  1306. res.setWrapped(
  1307. null,
  1308. right.postfix,
  1309. right.wrappedInnerExpressions && [
  1310. ...(right.prefix ? [left, right.prefix] : [left]),
  1311. ...right.wrappedInnerExpressions
  1312. ]
  1313. );
  1314. } else {
  1315. return;
  1316. }
  1317. if (left.couldHaveSideEffects() || right.couldHaveSideEffects()) {
  1318. res.setSideEffects();
  1319. }
  1320. res.setRange(/** @type {Range} */ (expr.range));
  1321. return res;
  1322. } else if (expr.operator === "-") {
  1323. return handleConstOperation((l, r) => l - r);
  1324. } else if (expr.operator === "*") {
  1325. return handleConstOperation((l, r) => l * r);
  1326. } else if (expr.operator === "/") {
  1327. return handleConstOperation((l, r) => l / r);
  1328. } else if (expr.operator === "**") {
  1329. return handleConstOperation((l, r) => l ** r);
  1330. } else if (expr.operator === "===") {
  1331. return handleStrictEqualityComparison(true);
  1332. } else if (expr.operator === "==") {
  1333. return handleAbstractEqualityComparison(true);
  1334. } else if (expr.operator === "!==") {
  1335. return handleStrictEqualityComparison(false);
  1336. } else if (expr.operator === "!=") {
  1337. return handleAbstractEqualityComparison(false);
  1338. } else if (expr.operator === "&") {
  1339. return handleConstOperation((l, r) => l & r);
  1340. } else if (expr.operator === "|") {
  1341. return handleConstOperation((l, r) => l | r);
  1342. } else if (expr.operator === "^") {
  1343. return handleConstOperation((l, r) => l ^ r);
  1344. } else if (expr.operator === ">>>") {
  1345. return handleConstOperation((l, r) => l >>> r);
  1346. } else if (expr.operator === ">>") {
  1347. return handleConstOperation((l, r) => l >> r);
  1348. } else if (expr.operator === "<<") {
  1349. return handleConstOperation((l, r) => l << r);
  1350. } else if (expr.operator === "<") {
  1351. return handleConstOperation((l, r) => l < r);
  1352. } else if (expr.operator === ">") {
  1353. return handleConstOperation((l, r) => l > r);
  1354. } else if (expr.operator === "<=") {
  1355. return handleConstOperation((l, r) => l <= r);
  1356. } else if (expr.operator === ">=") {
  1357. return handleConstOperation((l, r) => l >= r);
  1358. } else if (expr.operator === "in") {
  1359. // `x in y` always evaluates to a boolean, so it is never nullish
  1360. const left = this.evaluateExpression(expr.left);
  1361. const right = this.evaluateExpression(expr.right);
  1362. return new BasicEvaluatedExpression()
  1363. .setNullish(false)
  1364. .setSideEffects(
  1365. left.couldHaveSideEffects() || right.couldHaveSideEffects()
  1366. )
  1367. .setRange(/** @type {Range} */ (expr.range));
  1368. }
  1369. });
  1370. this.hooks.evaluate.for("UnaryExpression").tap(CLASS_NAME, (_expr) => {
  1371. const expr = /** @type {UnaryExpression} */ (_expr);
  1372. /**
  1373. * Evaluates a UnaryExpression if and only if it is a basic const operator (e.g. +a, -a, ~a).
  1374. * @template T
  1375. * @param {(operand: T) => boolean | number | bigint | string} operandHandler handler for the operand
  1376. * @returns {BasicEvaluatedExpression | undefined} evaluated expression
  1377. */
  1378. const handleConstOperation = (operandHandler) => {
  1379. const argument = this.evaluateExpression(expr.argument);
  1380. if (!argument.isCompileTimeValue()) return;
  1381. const result = operandHandler(
  1382. /** @type {T} */ (argument.asCompileTimeValue())
  1383. );
  1384. return valueAsExpression(result, expr, argument.couldHaveSideEffects());
  1385. };
  1386. if (expr.operator === "typeof") {
  1387. switch (expr.argument.type) {
  1388. case "Identifier": {
  1389. const res = this.callHooksForName(
  1390. this.hooks.evaluateTypeof,
  1391. expr.argument.name,
  1392. expr
  1393. );
  1394. if (res !== undefined) return res;
  1395. break;
  1396. }
  1397. case "MetaProperty": {
  1398. const res = this.callHooksForName(
  1399. this.hooks.evaluateTypeof,
  1400. /** @type {string} */
  1401. (getRootName(expr.argument)),
  1402. expr
  1403. );
  1404. if (res !== undefined) return res;
  1405. break;
  1406. }
  1407. case "MemberExpression": {
  1408. const res = this.callHooksForExpression(
  1409. this.hooks.evaluateTypeof,
  1410. expr.argument,
  1411. expr
  1412. );
  1413. if (res !== undefined) return res;
  1414. break;
  1415. }
  1416. case "ChainExpression": {
  1417. const res = this.callHooksForExpression(
  1418. this.hooks.evaluateTypeof,
  1419. expr.argument.expression,
  1420. expr
  1421. );
  1422. if (res !== undefined) return res;
  1423. break;
  1424. }
  1425. case "FunctionExpression": {
  1426. return new BasicEvaluatedExpression()
  1427. .setString("function")
  1428. .setRange(/** @type {Range} */ (expr.range));
  1429. }
  1430. }
  1431. const arg = this.evaluateExpression(expr.argument);
  1432. if (arg.isUnknown()) return;
  1433. if (arg.isString()) {
  1434. return new BasicEvaluatedExpression()
  1435. .setString("string")
  1436. .setRange(/** @type {Range} */ (expr.range));
  1437. }
  1438. if (arg.isWrapped()) {
  1439. return new BasicEvaluatedExpression()
  1440. .setString("string")
  1441. .setSideEffects()
  1442. .setRange(/** @type {Range} */ (expr.range));
  1443. }
  1444. if (arg.isUndefined()) {
  1445. return new BasicEvaluatedExpression()
  1446. .setString("undefined")
  1447. .setRange(/** @type {Range} */ (expr.range));
  1448. }
  1449. if (arg.isNumber()) {
  1450. return new BasicEvaluatedExpression()
  1451. .setString("number")
  1452. .setRange(/** @type {Range} */ (expr.range));
  1453. }
  1454. if (arg.isBigInt()) {
  1455. return new BasicEvaluatedExpression()
  1456. .setString("bigint")
  1457. .setRange(/** @type {Range} */ (expr.range));
  1458. }
  1459. if (arg.isBoolean()) {
  1460. return new BasicEvaluatedExpression()
  1461. .setString("boolean")
  1462. .setRange(/** @type {Range} */ (expr.range));
  1463. }
  1464. if (arg.isConstArray() || arg.isRegExp() || arg.isNull()) {
  1465. return new BasicEvaluatedExpression()
  1466. .setString("object")
  1467. .setRange(/** @type {Range} */ (expr.range));
  1468. }
  1469. if (arg.isArray()) {
  1470. return new BasicEvaluatedExpression()
  1471. .setString("object")
  1472. .setSideEffects(arg.couldHaveSideEffects())
  1473. .setRange(/** @type {Range} */ (expr.range));
  1474. }
  1475. } else if (expr.operator === "!") {
  1476. const argument = this.evaluateExpression(expr.argument);
  1477. const bool = argument.asBool();
  1478. if (typeof bool !== "boolean") return;
  1479. return new BasicEvaluatedExpression()
  1480. .setBoolean(!bool)
  1481. .setSideEffects(argument.couldHaveSideEffects())
  1482. .setRange(/** @type {Range} */ (expr.range));
  1483. } else if (expr.operator === "~") {
  1484. return handleConstOperation((v) => ~v);
  1485. } else if (expr.operator === "+") {
  1486. // eslint-disable-next-line no-implicit-coercion
  1487. return handleConstOperation((v) => +v);
  1488. } else if (expr.operator === "-") {
  1489. return handleConstOperation((v) => -v);
  1490. }
  1491. });
  1492. this.hooks.evaluateTypeof
  1493. .for("undefined")
  1494. .tap(CLASS_NAME, (expr) =>
  1495. new BasicEvaluatedExpression()
  1496. .setString("undefined")
  1497. .setRange(/** @type {Range} */ (expr.range))
  1498. );
  1499. this.hooks.evaluate.for("Identifier").tap(CLASS_NAME, (expr) => {
  1500. if (/** @type {Identifier} */ (expr).name === "undefined") {
  1501. return new BasicEvaluatedExpression()
  1502. .setUndefined()
  1503. .setRange(/** @type {Range} */ (expr.range));
  1504. }
  1505. });
  1506. /**
  1507. * Tap evaluate with variable info.
  1508. * @param {"Identifier" | "ThisExpression" | "MemberExpression"} exprType expression type name
  1509. * @param {(node: Expression | SpreadElement) => GetInfoResult | undefined} getInfo get info
  1510. * @returns {void}
  1511. */
  1512. const tapEvaluateWithVariableInfo = (exprType, getInfo) => {
  1513. /** @type {Expression | undefined} */
  1514. let cachedExpression;
  1515. /** @type {GetInfoResult | undefined} */
  1516. let cachedInfo;
  1517. this.hooks.evaluate.for(exprType).tap(CLASS_NAME, (expr) => {
  1518. const expression =
  1519. /** @type {Identifier | ThisExpression | MemberExpression} */ (expr);
  1520. const info = getInfo(expression);
  1521. // Cache the result (even when undefined) so the stage-100 tap below
  1522. // reuses it instead of recomputing getInfo — getMemberExpressionInfo
  1523. // is expensive and previously ran twice for every rejected member.
  1524. cachedExpression = expression;
  1525. cachedInfo = info;
  1526. if (info !== undefined) {
  1527. return this.callHooksForInfoWithFallback(
  1528. this.hooks.evaluateIdentifier,
  1529. info.name,
  1530. (_name) => undefined,
  1531. (name) => {
  1532. const hook = this.hooks.evaluateDefinedIdentifier.get(name);
  1533. if (hook !== undefined) {
  1534. return hook.call(expression);
  1535. }
  1536. },
  1537. expression
  1538. );
  1539. }
  1540. });
  1541. this.hooks.evaluate
  1542. .for(exprType)
  1543. .tap({ name: CLASS_NAME, stage: 100 }, (expr) => {
  1544. const expression =
  1545. /** @type {Identifier | ThisExpression | MemberExpression} */
  1546. (expr);
  1547. const info =
  1548. cachedExpression === expression ? cachedInfo : getInfo(expression);
  1549. if (info !== undefined) {
  1550. return new BasicEvaluatedExpression()
  1551. .setIdentifier(
  1552. info.name,
  1553. info.rootInfo,
  1554. info.getMembers,
  1555. info.getMembersOptionals,
  1556. info.getMemberRanges
  1557. )
  1558. .setRange(/** @type {Range} */ (expression.range));
  1559. }
  1560. });
  1561. this.hooks.finish.tap(CLASS_NAME, () => {
  1562. // Cleanup for GC
  1563. cachedExpression = cachedInfo = undefined;
  1564. });
  1565. };
  1566. tapEvaluateWithVariableInfo("Identifier", (expr) => {
  1567. const info = this.getVariableInfo(/** @type {Identifier} */ (expr).name);
  1568. if (
  1569. typeof info === "string" ||
  1570. (info instanceof VariableInfo &&
  1571. (info.isFree() ||
  1572. info.isTagged() ||
  1573. // Walk `tagInfo` in `callHooksForInfo` if tagInfo is present.
  1574. info.tagInfo !== undefined))
  1575. ) {
  1576. return {
  1577. name: info,
  1578. rootInfo: info,
  1579. getMembers: RETURN_EMPTY_ARRAY,
  1580. getMembersOptionals: RETURN_EMPTY_ARRAY,
  1581. getMemberRanges: RETURN_EMPTY_ARRAY
  1582. };
  1583. }
  1584. });
  1585. tapEvaluateWithVariableInfo("ThisExpression", (_expr) => {
  1586. const info = this.getVariableInfo("this");
  1587. if (
  1588. typeof info === "string" ||
  1589. (info instanceof VariableInfo && (info.isFree() || info.isTagged()))
  1590. ) {
  1591. return {
  1592. name: info,
  1593. rootInfo: info,
  1594. getMembers: RETURN_EMPTY_ARRAY,
  1595. getMembersOptionals: RETURN_EMPTY_ARRAY,
  1596. getMemberRanges: RETURN_EMPTY_ARRAY
  1597. };
  1598. }
  1599. });
  1600. this.hooks.evaluate.for("MetaProperty").tap(CLASS_NAME, (expr) => {
  1601. const metaProperty = /** @type {MetaProperty} */ (expr);
  1602. return this.callHooksForName(
  1603. this.hooks.evaluateIdentifier,
  1604. /** @type {string} */
  1605. (getRootName(metaProperty)),
  1606. metaProperty
  1607. );
  1608. });
  1609. tapEvaluateWithVariableInfo("MemberExpression", (expr) =>
  1610. this.getMemberExpressionInfo(
  1611. /** @type {MemberExpression} */ (expr),
  1612. ALLOWED_MEMBER_TYPES_EXPRESSION
  1613. )
  1614. );
  1615. this.hooks.evaluate.for("CallExpression").tap(CLASS_NAME, (expression) => {
  1616. const expr = /** @type {CallExpression} */ (expression);
  1617. if (
  1618. expr.callee.type === "MemberExpression" &&
  1619. expr.callee.property.type ===
  1620. (expr.callee.computed ? "Literal" : "Identifier")
  1621. ) {
  1622. // type Super also possible here
  1623. const param = this.evaluateExpression(
  1624. /** @type {Expression} */ (expr.callee.object)
  1625. );
  1626. const property =
  1627. expr.callee.property.type === "Literal"
  1628. ? `${expr.callee.property.value}`
  1629. : expr.callee.property.name;
  1630. const hook = this.hooks.evaluateCallExpressionMember.get(property);
  1631. if (hook !== undefined) {
  1632. return hook.call(expr, param);
  1633. }
  1634. } else if (expr.callee.type === "Identifier") {
  1635. return this.callHooksForName(
  1636. this.hooks.evaluateCallExpression,
  1637. expr.callee.name,
  1638. expr
  1639. );
  1640. }
  1641. });
  1642. this.hooks.evaluateCallExpressionMember
  1643. .for("indexOf")
  1644. .tap(CLASS_NAME, (expr, param) => {
  1645. if (!param.isString()) return;
  1646. if (expr.arguments.length === 0) return;
  1647. const [arg1, arg2] = expr.arguments;
  1648. if (arg1.type === "SpreadElement") return;
  1649. const arg1Eval = this.evaluateExpression(arg1);
  1650. if (!arg1Eval.isString()) return;
  1651. const arg1Value = /** @type {string} */ (arg1Eval.string);
  1652. /** @type {number} */
  1653. let result;
  1654. if (arg2) {
  1655. if (arg2.type === "SpreadElement") return;
  1656. const arg2Eval = this.evaluateExpression(arg2);
  1657. if (!arg2Eval.isNumber()) return;
  1658. result = /** @type {string} */ (param.string).indexOf(
  1659. arg1Value,
  1660. arg2Eval.number
  1661. );
  1662. } else {
  1663. result = /** @type {string} */ (param.string).indexOf(arg1Value);
  1664. }
  1665. return new BasicEvaluatedExpression()
  1666. .setNumber(result)
  1667. .setSideEffects(param.couldHaveSideEffects())
  1668. .setRange(/** @type {Range} */ (expr.range));
  1669. });
  1670. this.hooks.evaluateCallExpressionMember
  1671. .for("replace")
  1672. .tap(CLASS_NAME, (expr, param) => {
  1673. if (!param.isString()) return;
  1674. if (expr.arguments.length !== 2) return;
  1675. if (expr.arguments[0].type === "SpreadElement") return;
  1676. if (expr.arguments[1].type === "SpreadElement") return;
  1677. const arg1 = this.evaluateExpression(expr.arguments[0]);
  1678. const arg2 = this.evaluateExpression(expr.arguments[1]);
  1679. if (!arg1.isString() && !arg1.isRegExp()) return;
  1680. const arg1Value = /** @type {string | RegExp} */ (
  1681. arg1.regExp || arg1.string
  1682. );
  1683. if (!arg2.isString()) return;
  1684. const arg2Value = /** @type {string} */ (arg2.string);
  1685. return new BasicEvaluatedExpression()
  1686. .setString(
  1687. /** @type {string} */ (param.string).replace(arg1Value, arg2Value)
  1688. )
  1689. .setSideEffects(param.couldHaveSideEffects())
  1690. .setRange(/** @type {Range} */ (expr.range));
  1691. });
  1692. for (const fn of ["substr", "substring", "slice"]) {
  1693. this.hooks.evaluateCallExpressionMember
  1694. .for(fn)
  1695. .tap(CLASS_NAME, (expr, param) => {
  1696. if (!param.isString()) return;
  1697. /** @type {BasicEvaluatedExpression} */
  1698. let arg1;
  1699. /** @type {string} */
  1700. let result;
  1701. const str = /** @type {string} */ (param.string);
  1702. switch (expr.arguments.length) {
  1703. case 1:
  1704. if (expr.arguments[0].type === "SpreadElement") return;
  1705. arg1 = this.evaluateExpression(expr.arguments[0]);
  1706. if (!arg1.isNumber()) return;
  1707. result = str[
  1708. /** @type {"substr" | "substring" | "slice"} */ (fn)
  1709. ](/** @type {number} */ (arg1.number));
  1710. break;
  1711. case 2: {
  1712. if (expr.arguments[0].type === "SpreadElement") return;
  1713. if (expr.arguments[1].type === "SpreadElement") return;
  1714. arg1 = this.evaluateExpression(expr.arguments[0]);
  1715. const arg2 = this.evaluateExpression(expr.arguments[1]);
  1716. if (!arg1.isNumber()) return;
  1717. if (!arg2.isNumber()) return;
  1718. result = str[
  1719. /** @type {"substr" | "substring" | "slice"} */ (fn)
  1720. ](
  1721. /** @type {number} */ (arg1.number),
  1722. /** @type {number} */ (arg2.number)
  1723. );
  1724. break;
  1725. }
  1726. default:
  1727. return;
  1728. }
  1729. return new BasicEvaluatedExpression()
  1730. .setString(result)
  1731. .setSideEffects(param.couldHaveSideEffects())
  1732. .setRange(/** @type {Range} */ (expr.range));
  1733. });
  1734. }
  1735. /**
  1736. * Gets simplified template result.
  1737. * @param {"cooked" | "raw"} kind kind of values to get
  1738. * @param {TemplateLiteral} templateLiteralExpr TemplateLiteral expr
  1739. * @returns {{ quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[] }} Simplified template
  1740. */
  1741. const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => {
  1742. /** @type {BasicEvaluatedExpression[]} */
  1743. const quasis = [];
  1744. /** @type {BasicEvaluatedExpression[]} */
  1745. const parts = [];
  1746. for (let i = 0; i < templateLiteralExpr.quasis.length; i++) {
  1747. const quasiExpr = templateLiteralExpr.quasis[i];
  1748. const quasi = quasiExpr.value[kind];
  1749. if (i > 0) {
  1750. const prevExpr = parts[parts.length - 1];
  1751. const expr = this.evaluateExpression(
  1752. templateLiteralExpr.expressions[i - 1]
  1753. );
  1754. const exprAsString = expr.asString();
  1755. if (
  1756. typeof exprAsString === "string" &&
  1757. !expr.couldHaveSideEffects()
  1758. ) {
  1759. // We can merge quasi + expr + quasi when expr
  1760. // is a const string
  1761. prevExpr.setString(prevExpr.string + exprAsString + quasi);
  1762. prevExpr.setRange([
  1763. /** @type {Range} */ (prevExpr.range)[0],
  1764. /** @type {Range} */ (quasiExpr.range)[1]
  1765. ]);
  1766. // We unset the expression as it doesn't match to a single expression
  1767. prevExpr.setExpression(undefined);
  1768. continue;
  1769. }
  1770. parts.push(expr);
  1771. }
  1772. const part = new BasicEvaluatedExpression()
  1773. .setString(/** @type {string} */ (quasi))
  1774. .setRange(/** @type {Range} */ (quasiExpr.range))
  1775. .setExpression(quasiExpr);
  1776. quasis.push(part);
  1777. parts.push(part);
  1778. }
  1779. return {
  1780. quasis,
  1781. parts
  1782. };
  1783. };
  1784. this.hooks.evaluate.for("TemplateLiteral").tap(CLASS_NAME, (_node) => {
  1785. const node = /** @type {TemplateLiteral} */ (_node);
  1786. const { quasis, parts } = getSimplifiedTemplateResult("cooked", node);
  1787. if (parts.length === 1) {
  1788. return parts[0].setRange(/** @type {Range} */ (node.range));
  1789. }
  1790. return new BasicEvaluatedExpression()
  1791. .setTemplateString(quasis, parts, "cooked")
  1792. .setRange(/** @type {Range} */ (node.range));
  1793. });
  1794. this.hooks.evaluate
  1795. .for("TaggedTemplateExpression")
  1796. .tap(CLASS_NAME, (_node) => {
  1797. const node = /** @type {TaggedTemplateExpression} */ (_node);
  1798. const tag = this.evaluateExpression(node.tag);
  1799. if (tag.isIdentifier() && tag.identifier === "String.raw") {
  1800. const { quasis, parts } = getSimplifiedTemplateResult(
  1801. "raw",
  1802. node.quasi
  1803. );
  1804. return new BasicEvaluatedExpression()
  1805. .setTemplateString(quasis, parts, "raw")
  1806. .setRange(/** @type {Range} */ (node.range));
  1807. }
  1808. });
  1809. this.hooks.evaluateCallExpressionMember
  1810. .for("concat")
  1811. .tap(CLASS_NAME, (expr, param) => {
  1812. if (!param.isString() && !param.isWrapped()) return;
  1813. /** @type {undefined | BasicEvaluatedExpression} */
  1814. let stringSuffix;
  1815. let hasUnknownParams = false;
  1816. /** @type {BasicEvaluatedExpression[]} */
  1817. const innerExpressions = [];
  1818. for (let i = expr.arguments.length - 1; i >= 0; i--) {
  1819. const arg = expr.arguments[i];
  1820. if (arg.type === "SpreadElement") return;
  1821. const argExpr = this.evaluateExpression(arg);
  1822. if (
  1823. hasUnknownParams ||
  1824. (!argExpr.isString() && !argExpr.isNumber())
  1825. ) {
  1826. hasUnknownParams = true;
  1827. innerExpressions.push(argExpr);
  1828. continue;
  1829. }
  1830. const value = argExpr.isString()
  1831. ? /** @type {string} */ (argExpr.string)
  1832. : String(argExpr.number);
  1833. /** @type {string} */
  1834. const newString =
  1835. value +
  1836. (stringSuffix ? /** @type {string} */ (stringSuffix.string) : "");
  1837. const newRange = /** @type {Range} */ ([
  1838. /** @type {Range} */ (argExpr.range)[0],
  1839. /** @type {Range} */ ((stringSuffix || argExpr).range)[1]
  1840. ]);
  1841. stringSuffix = new BasicEvaluatedExpression()
  1842. .setString(newString)
  1843. .setSideEffects(
  1844. (stringSuffix && stringSuffix.couldHaveSideEffects()) ||
  1845. argExpr.couldHaveSideEffects()
  1846. )
  1847. .setRange(newRange);
  1848. }
  1849. if (hasUnknownParams) {
  1850. const prefix = param.isString() ? param : param.prefix;
  1851. const inner =
  1852. param.isWrapped() && param.wrappedInnerExpressions
  1853. ? [
  1854. ...param.wrappedInnerExpressions,
  1855. ...innerExpressions.reverse()
  1856. ]
  1857. : innerExpressions.reverse();
  1858. return new BasicEvaluatedExpression()
  1859. .setWrapped(prefix, stringSuffix, inner)
  1860. .setRange(/** @type {Range} */ (expr.range));
  1861. } else if (param.isWrapped()) {
  1862. const postfix = stringSuffix || param.postfix;
  1863. const inner = param.wrappedInnerExpressions
  1864. ? [...param.wrappedInnerExpressions, ...innerExpressions.reverse()]
  1865. : innerExpressions.reverse();
  1866. return new BasicEvaluatedExpression()
  1867. .setWrapped(param.prefix, postfix, inner)
  1868. .setRange(/** @type {Range} */ (expr.range));
  1869. }
  1870. const newString =
  1871. /** @type {string} */ (param.string) +
  1872. (stringSuffix ? stringSuffix.string : "");
  1873. return new BasicEvaluatedExpression()
  1874. .setString(newString)
  1875. .setSideEffects(
  1876. (stringSuffix && stringSuffix.couldHaveSideEffects()) ||
  1877. param.couldHaveSideEffects()
  1878. )
  1879. .setRange(/** @type {Range} */ (expr.range));
  1880. });
  1881. this.hooks.evaluateCallExpressionMember
  1882. .for("split")
  1883. .tap(CLASS_NAME, (expr, param) => {
  1884. if (!param.isString()) return;
  1885. if (expr.arguments.length !== 1) return;
  1886. if (expr.arguments[0].type === "SpreadElement") return;
  1887. /** @type {string[]} */
  1888. let result;
  1889. const arg = this.evaluateExpression(expr.arguments[0]);
  1890. if (arg.isString()) {
  1891. result =
  1892. /** @type {string} */
  1893. (param.string).split(/** @type {string} */ (arg.string));
  1894. } else if (arg.isRegExp()) {
  1895. result = /** @type {string} */ (param.string).split(
  1896. /** @type {RegExp} */ (arg.regExp)
  1897. );
  1898. } else {
  1899. return;
  1900. }
  1901. return new BasicEvaluatedExpression()
  1902. .setArray(result)
  1903. .setSideEffects(param.couldHaveSideEffects())
  1904. .setRange(/** @type {Range} */ (expr.range));
  1905. });
  1906. this.hooks.evaluate
  1907. .for("ConditionalExpression")
  1908. .tap(CLASS_NAME, (_expr) => {
  1909. const expr = /** @type {ConditionalExpression} */ (_expr);
  1910. const condition = this.evaluateExpression(expr.test);
  1911. const conditionValue = condition.asBool();
  1912. /** @type {BasicEvaluatedExpression} */
  1913. let res;
  1914. if (conditionValue === undefined) {
  1915. const consequent = this.evaluateExpression(expr.consequent);
  1916. const alternate = this.evaluateExpression(expr.alternate);
  1917. res = new BasicEvaluatedExpression();
  1918. if (consequent.isConditional()) {
  1919. res.setOptions(
  1920. /** @type {BasicEvaluatedExpression[]} */ (consequent.options)
  1921. );
  1922. } else {
  1923. res.setOptions([consequent]);
  1924. }
  1925. if (alternate.isConditional()) {
  1926. res.addOptions(
  1927. /** @type {BasicEvaluatedExpression[]} */ (alternate.options)
  1928. );
  1929. } else {
  1930. res.addOptions([alternate]);
  1931. }
  1932. } else {
  1933. res = this.evaluateExpression(
  1934. conditionValue ? expr.consequent : expr.alternate
  1935. );
  1936. if (condition.couldHaveSideEffects()) res.setSideEffects();
  1937. }
  1938. res.setRange(/** @type {Range} */ (expr.range));
  1939. return res;
  1940. });
  1941. this.hooks.evaluate.for("ArrayExpression").tap(CLASS_NAME, (_expr) => {
  1942. const expr = /** @type {ArrayExpression} */ (_expr);
  1943. const items = expr.elements.map(
  1944. (element) =>
  1945. element !== null &&
  1946. element.type !== "SpreadElement" &&
  1947. this.evaluateExpression(element)
  1948. );
  1949. if (!items.every(Boolean)) return;
  1950. return new BasicEvaluatedExpression()
  1951. .setItems(/** @type {BasicEvaluatedExpression[]} */ (items))
  1952. .setRange(/** @type {Range} */ (expr.range));
  1953. });
  1954. this.hooks.evaluate.for("ChainExpression").tap(CLASS_NAME, (_expr) => {
  1955. const expr = /** @type {ChainExpression} */ (_expr);
  1956. /** @type {Expression[]} */
  1957. const optionalExpressionsStack = [];
  1958. /** @type {Expression | Super} */
  1959. let next = expr.expression;
  1960. while (
  1961. next.type === "MemberExpression" ||
  1962. next.type === "CallExpression"
  1963. ) {
  1964. if (next.type === "MemberExpression") {
  1965. if (next.optional) {
  1966. // SuperNode can not be optional
  1967. optionalExpressionsStack.push(
  1968. /** @type {Expression} */ (next.object)
  1969. );
  1970. }
  1971. next = next.object;
  1972. } else {
  1973. if (next.optional) {
  1974. // SuperNode can not be optional
  1975. optionalExpressionsStack.push(
  1976. /** @type {Expression} */ (next.callee)
  1977. );
  1978. }
  1979. next = next.callee;
  1980. }
  1981. }
  1982. while (optionalExpressionsStack.length > 0) {
  1983. const expression =
  1984. /** @type {Expression} */
  1985. (optionalExpressionsStack.pop());
  1986. const evaluated = this.evaluateExpression(expression);
  1987. if (evaluated.asNullish()) {
  1988. return evaluated.setRange(/** @type {Range} */ (_expr.range));
  1989. }
  1990. }
  1991. return this.evaluateExpression(expr.expression);
  1992. });
  1993. this.hooks.evaluate.for("SequenceExpression").tap(CLASS_NAME, (_expr) => {
  1994. const expr = /** @type {SequenceExpression} */ (_expr);
  1995. if (!expr.range) return;
  1996. let commentsStartPos = /** @type {Range} */ (expr.range)[0];
  1997. for (let i = 0; i < expr.expressions.length - 1; i++) {
  1998. const item = expr.expressions[i];
  1999. if (!item.range) return;
  2000. if (!this.isPure(item, commentsStartPos)) return;
  2001. commentsStartPos = /** @type {Range} */ (item.range)[1];
  2002. }
  2003. const last = expr.expressions[expr.expressions.length - 1];
  2004. const evaluated = this.evaluateExpression(last);
  2005. if (!evaluated.isCompileTimeValue()) return;
  2006. return evaluated.setRange(/** @type {Range} */ (expr.range));
  2007. });
  2008. }
  2009. /**
  2010. * Destructuring assignment properties for.
  2011. * @param {Expression} node node
  2012. * @returns {DestructuringAssignmentProperties | undefined} destructured identifiers
  2013. */
  2014. destructuringAssignmentPropertiesFor(node) {
  2015. if (!this.destructuringAssignmentProperties) return;
  2016. return this.destructuringAssignmentProperties.get(node);
  2017. }
  2018. /**
  2019. * Gets rename identifier.
  2020. * @param {Expression | SpreadElement} expr expression
  2021. * @returns {string | VariableInfo | undefined} identifier
  2022. */
  2023. getRenameIdentifier(expr) {
  2024. if (
  2025. expr.type === "Identifier" &&
  2026. this._evalIdentOwnTaps &&
  2027. expr.name !== "undefined" &&
  2028. this._isDefinedPlainVariable(expr.name)
  2029. ) {
  2030. // the evaluation could only fall through — never an identifier result
  2031. return;
  2032. }
  2033. const result = this.evaluateExpression(expr);
  2034. if (result.isIdentifier()) {
  2035. return result.identifier;
  2036. }
  2037. }
  2038. /**
  2039. * Processes the provided classy.
  2040. * @param {ClassExpression | ClassDeclaration | MaybeNamedClassDeclaration} classy a class node
  2041. * @returns {void}
  2042. */
  2043. walkClass(classy) {
  2044. if (
  2045. classy.superClass &&
  2046. !this.hooks.classExtendsExpression.call(classy.superClass, classy)
  2047. ) {
  2048. this.walkExpression(classy.superClass);
  2049. }
  2050. if (classy.body && classy.body.type === "ClassBody") {
  2051. /** @type {Identifier[]} */
  2052. const scopeParams = [];
  2053. // Add class name in scope for recursive calls
  2054. if (classy.id) {
  2055. scopeParams.push(classy.id);
  2056. }
  2057. this.inClassScope(true, scopeParams, () => {
  2058. for (const classElement of classy.body.body) {
  2059. if (!this.hooks.classBodyElement.call(classElement, classy)) {
  2060. if (classElement.type === "StaticBlock") {
  2061. const wasTopLevel = this.scope.topLevelScope;
  2062. this.scope.topLevelScope = false;
  2063. this.walkBlockStatement(classElement);
  2064. this.scope.topLevelScope = wasTopLevel;
  2065. } else {
  2066. if (classElement.computed && classElement.key) {
  2067. this.walkExpression(classElement.key);
  2068. }
  2069. if (
  2070. classElement.value &&
  2071. !this.hooks.classBodyValue.call(
  2072. classElement.value,
  2073. classElement,
  2074. classy
  2075. )
  2076. ) {
  2077. const wasTopLevel = this.scope.topLevelScope;
  2078. this.scope.topLevelScope = false;
  2079. this.walkExpression(classElement.value);
  2080. this.scope.topLevelScope = wasTopLevel;
  2081. }
  2082. }
  2083. }
  2084. }
  2085. });
  2086. }
  2087. }
  2088. /**
  2089. * Module pre walking iterates the scope for import entries
  2090. * @param {(Statement | ModuleDeclaration)[]} statements statements
  2091. */
  2092. modulePreWalkStatements(statements) {
  2093. for (let index = 0, len = statements.length; index < len; index++) {
  2094. const statement = statements[index];
  2095. /** @type {StatementPath} */
  2096. (this.statementPath).push(statement);
  2097. switch (statement.type) {
  2098. case "ImportDeclaration":
  2099. this.modulePreWalkImportDeclaration(statement);
  2100. break;
  2101. case "ExportAllDeclaration":
  2102. this.modulePreWalkExportAllDeclaration(statement);
  2103. break;
  2104. case "ExportNamedDeclaration":
  2105. this.modulePreWalkExportNamedDeclaration(statement);
  2106. break;
  2107. }
  2108. this.prevStatement =
  2109. /** @type {StatementPath} */
  2110. (this.statementPath).pop();
  2111. }
  2112. }
  2113. /**
  2114. * Pre walking iterates the scope for variable declarations
  2115. * @param {(Statement | ModuleDeclaration)[]} statements statements
  2116. */
  2117. preWalkStatements(statements) {
  2118. for (let index = 0, len = statements.length; index < len; index++) {
  2119. const statement = statements[index];
  2120. this.preWalkStatement(statement);
  2121. }
  2122. }
  2123. /**
  2124. * Block pre walking iterates the scope for block variable declarations
  2125. * @param {(Statement | ModuleDeclaration)[]} statements statements
  2126. */
  2127. blockPreWalkStatements(statements) {
  2128. for (let index = 0, len = statements.length; index < len; index++) {
  2129. const statement = statements[index];
  2130. this.blockPreWalkStatement(statement);
  2131. }
  2132. }
  2133. /**
  2134. * Walking iterates the statements and expressions and processes them
  2135. * @param {(Statement | ModuleDeclaration)[]} statements statements
  2136. */
  2137. walkStatements(statements) {
  2138. let onlyFunctionDeclaration = false;
  2139. for (let index = 0, len = statements.length; index < len; index++) {
  2140. const statement = statements[index];
  2141. if (
  2142. onlyFunctionDeclaration &&
  2143. statement.type !== "FunctionDeclaration" &&
  2144. this.hooks.unusedStatement.call(/** @type {Statement} */ (statement))
  2145. ) {
  2146. continue;
  2147. }
  2148. this.walkStatement(statement);
  2149. if (this.scope.terminated) {
  2150. onlyFunctionDeclaration = true;
  2151. }
  2152. }
  2153. }
  2154. /**
  2155. * Walking iterates the statements and expressions and processes them
  2156. * @param {Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration} statement statement
  2157. */
  2158. preWalkStatement(statement) {
  2159. /** @type {StatementPath} */
  2160. (this.statementPath).push(statement);
  2161. const { preStatement, preStatementByType } = this.hooks;
  2162. // skip the broadcast entirely when nothing taps it; type-keyed taps
  2163. // only run for their statement type
  2164. let bail =
  2165. preStatement.taps.length !== 0 ? preStatement.call(statement) : undefined;
  2166. if (!bail) {
  2167. const typed = preStatementByType.get(statement.type);
  2168. if (typed !== undefined) bail = typed.call(statement);
  2169. }
  2170. if (bail) {
  2171. this.prevStatement =
  2172. /** @type {StatementPath} */
  2173. (this.statementPath).pop();
  2174. return;
  2175. }
  2176. // cases ordered by measured statement frequency; the commonest statements
  2177. // (expressions, returns) intentionally match nothing here
  2178. switch (statement.type) {
  2179. case "VariableDeclaration":
  2180. this.preWalkVariableDeclaration(statement);
  2181. break;
  2182. case "IfStatement":
  2183. this.preWalkIfStatement(statement);
  2184. break;
  2185. case "BlockStatement":
  2186. this.preWalkBlockStatement(statement);
  2187. break;
  2188. case "FunctionDeclaration":
  2189. this.preWalkFunctionDeclaration(statement);
  2190. break;
  2191. case "ForStatement":
  2192. this.preWalkForStatement(statement);
  2193. break;
  2194. case "TryStatement":
  2195. this.preWalkTryStatement(statement);
  2196. break;
  2197. case "SwitchStatement":
  2198. this.preWalkSwitchStatement(statement);
  2199. break;
  2200. case "WhileStatement":
  2201. this.preWalkWhileStatement(statement);
  2202. break;
  2203. case "ForInStatement":
  2204. this.preWalkForInStatement(statement);
  2205. break;
  2206. case "ForOfStatement":
  2207. this.preWalkForOfStatement(statement);
  2208. break;
  2209. case "DoWhileStatement":
  2210. this.preWalkDoWhileStatement(statement);
  2211. break;
  2212. case "LabeledStatement":
  2213. this.preWalkLabeledStatement(statement);
  2214. break;
  2215. case "WithStatement":
  2216. this.preWalkWithStatement(statement);
  2217. break;
  2218. }
  2219. this.prevStatement =
  2220. /** @type {StatementPath} */
  2221. (this.statementPath).pop();
  2222. }
  2223. /**
  2224. * Block pre walk statement.
  2225. * @param {Statement | ModuleDeclaration | MaybeNamedClassDeclaration | MaybeNamedFunctionDeclaration} statement statement
  2226. */
  2227. blockPreWalkStatement(statement) {
  2228. /** @type {StatementPath} */
  2229. (this.statementPath).push(statement);
  2230. const { blockPreStatement, blockPreStatementByType } = this.hooks;
  2231. let bail =
  2232. blockPreStatement.taps.length !== 0
  2233. ? blockPreStatement.call(statement)
  2234. : undefined;
  2235. if (!bail) {
  2236. const typed = blockPreStatementByType.get(statement.type);
  2237. if (typed !== undefined) bail = typed.call(statement);
  2238. }
  2239. if (bail) {
  2240. this.prevStatement =
  2241. /** @type {StatementPath} */
  2242. (this.statementPath).pop();
  2243. return;
  2244. }
  2245. // cases ordered by measured statement frequency
  2246. switch (statement.type) {
  2247. case "VariableDeclaration":
  2248. this.blockPreWalkVariableDeclaration(statement);
  2249. break;
  2250. case "ExpressionStatement":
  2251. this.blockPreWalkExpressionStatement(statement);
  2252. break;
  2253. case "ClassDeclaration":
  2254. this.blockPreWalkClassDeclaration(statement);
  2255. break;
  2256. case "ExportNamedDeclaration":
  2257. this.blockPreWalkExportNamedDeclaration(statement);
  2258. break;
  2259. case "ExportDefaultDeclaration":
  2260. this.blockPreWalkExportDefaultDeclaration(statement);
  2261. }
  2262. this.prevStatement =
  2263. /** @type {StatementPath} */
  2264. (this.statementPath).pop();
  2265. }
  2266. /**
  2267. * Processes the provided statement.
  2268. * @param {Statement | ModuleDeclaration | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} statement statement
  2269. */
  2270. walkStatement(statement) {
  2271. /** @type {StatementPath} */
  2272. (this.statementPath).push(statement);
  2273. const { statement: statementHook } = this.hooks;
  2274. if (
  2275. statementHook.taps.length !== 0 &&
  2276. statementHook.call(statement) !== undefined
  2277. ) {
  2278. this.prevStatement =
  2279. /** @type {StatementPath} */
  2280. (this.statementPath).pop();
  2281. return;
  2282. }
  2283. // cases ordered by measured statement frequency; V8 compiles this to
  2284. // sequential compares, so hot types must come first
  2285. switch (statement.type) {
  2286. case "ExpressionStatement":
  2287. this.walkExpressionStatement(statement);
  2288. break;
  2289. case "VariableDeclaration":
  2290. this.walkVariableDeclaration(statement);
  2291. break;
  2292. case "ReturnStatement":
  2293. this.walkReturnStatement(statement);
  2294. break;
  2295. case "IfStatement":
  2296. this.walkIfStatement(statement);
  2297. break;
  2298. case "BlockStatement":
  2299. this.walkBlockStatement(statement);
  2300. break;
  2301. case "FunctionDeclaration":
  2302. this.walkFunctionDeclaration(statement);
  2303. break;
  2304. case "ForStatement":
  2305. this.walkForStatement(statement);
  2306. break;
  2307. case "TryStatement":
  2308. this.walkTryStatement(statement);
  2309. break;
  2310. case "SwitchStatement":
  2311. this.walkSwitchStatement(statement);
  2312. break;
  2313. case "ThrowStatement":
  2314. this.walkThrowStatement(statement);
  2315. break;
  2316. case "WhileStatement":
  2317. this.walkWhileStatement(statement);
  2318. break;
  2319. case "ClassDeclaration":
  2320. this.walkClassDeclaration(statement);
  2321. break;
  2322. case "ForInStatement":
  2323. this.walkForInStatement(statement);
  2324. break;
  2325. case "ForOfStatement":
  2326. this.walkForOfStatement(statement);
  2327. break;
  2328. case "DoWhileStatement":
  2329. this.walkDoWhileStatement(statement);
  2330. break;
  2331. case "ExportNamedDeclaration":
  2332. this.walkExportNamedDeclaration(statement);
  2333. break;
  2334. case "ExportDefaultDeclaration":
  2335. this.walkExportDefaultDeclaration(statement);
  2336. break;
  2337. case "LabeledStatement":
  2338. this.walkLabeledStatement(statement);
  2339. break;
  2340. case "WithStatement":
  2341. this.walkWithStatement(statement);
  2342. break;
  2343. }
  2344. this.prevStatement =
  2345. /** @type {StatementPath} */
  2346. (this.statementPath).pop();
  2347. }
  2348. /**
  2349. * Walks a statements that is nested within a parent statement
  2350. * and can potentially be a non-block statement.
  2351. * This enforces the nested statement to never be in ASI position.
  2352. * @param {Statement} statement the nested statement
  2353. */
  2354. walkNestedStatement(statement) {
  2355. this.prevStatement = undefined;
  2356. this.walkStatement(statement);
  2357. }
  2358. // Real Statements
  2359. /**
  2360. * Pre walk block statement.
  2361. * @param {BlockStatement} statement block statement
  2362. */
  2363. preWalkBlockStatement(statement) {
  2364. this.preWalkStatements(statement.body);
  2365. }
  2366. /**
  2367. * Walk block statement.
  2368. * @param {BlockStatement | StaticBlock} statement block statement
  2369. */
  2370. walkBlockStatement(statement) {
  2371. this.inBlockScope(() => {
  2372. const body = statement.body;
  2373. const prev = this.prevStatement;
  2374. this.blockPreWalkStatements(body);
  2375. this.prevStatement = prev;
  2376. this.walkStatements(body);
  2377. }, true);
  2378. }
  2379. /**
  2380. * Walk expression statement.
  2381. * @param {ExpressionStatement} statement expression statement
  2382. */
  2383. walkExpressionStatement(statement) {
  2384. this.walkExpression(statement.expression);
  2385. }
  2386. /**
  2387. * Pre walk if statement.
  2388. * @param {IfStatement} statement if statement
  2389. */
  2390. preWalkIfStatement(statement) {
  2391. this.preWalkStatement(statement.consequent);
  2392. if (statement.alternate) {
  2393. this.preWalkStatement(statement.alternate);
  2394. }
  2395. }
  2396. /**
  2397. * Walks a conditional branch with its guard frame (if any) pushed onto the
  2398. * parser-state guard stack for the duration of the branch body.
  2399. * @param {EXPECTED_OBJECT | undefined | null} frame guard frame, or falsy when the branch is unguarded
  2400. * @param {() => void} walk branch walk
  2401. * @returns {void}
  2402. */
  2403. walkGuardedBranch(frame, walk) {
  2404. if (!frame) {
  2405. walk();
  2406. return;
  2407. }
  2408. const stack = this.state.guardStack || (this.state.guardStack = []);
  2409. stack.push(frame);
  2410. try {
  2411. walk();
  2412. } finally {
  2413. stack.pop();
  2414. }
  2415. }
  2416. /**
  2417. * Processes the provided statement.
  2418. * @param {IfStatement} statement if statement
  2419. */
  2420. walkIfStatement(statement) {
  2421. const result = this.hooks.statementIf.call(statement);
  2422. if (result === undefined) {
  2423. const guard = this.hooks.collectGuards.call(statement.test);
  2424. this.walkExpression(statement.test);
  2425. this.walkGuardedBranch(guard ? guard.consequent : undefined, () =>
  2426. this.walkNestedStatement(statement.consequent)
  2427. );
  2428. const consequentTerminated = this.scope.terminated;
  2429. this.scope.terminated = undefined;
  2430. if (statement.alternate) {
  2431. const alternate = statement.alternate;
  2432. this.walkGuardedBranch(guard ? guard.alternate : undefined, () =>
  2433. this.walkNestedStatement(alternate)
  2434. );
  2435. }
  2436. const alternateTerminated = this.scope.terminated;
  2437. this.scope.terminated =
  2438. consequentTerminated && alternateTerminated
  2439. ? alternateTerminated
  2440. : undefined;
  2441. } else if (result) {
  2442. this.walkNestedStatement(statement.consequent);
  2443. } else if (statement.alternate) {
  2444. this.walkNestedStatement(statement.alternate);
  2445. }
  2446. }
  2447. /**
  2448. * Pre walk labeled statement.
  2449. * @param {LabeledStatement} statement with statement
  2450. */
  2451. preWalkLabeledStatement(statement) {
  2452. this.preWalkStatement(statement.body);
  2453. }
  2454. /**
  2455. * Walk labeled statement.
  2456. * @param {LabeledStatement} statement with statement
  2457. */
  2458. walkLabeledStatement(statement) {
  2459. const hook = this.hooks.label.get(statement.label.name);
  2460. if (hook !== undefined) {
  2461. const result = hook.call(statement);
  2462. if (result === true) return;
  2463. }
  2464. this.inBlockScope(() => {
  2465. this.walkNestedStatement(statement.body);
  2466. });
  2467. }
  2468. /**
  2469. * Pre walk with statement.
  2470. * @param {WithStatement} statement with statement
  2471. */
  2472. preWalkWithStatement(statement) {
  2473. this.preWalkStatement(statement.body);
  2474. }
  2475. /**
  2476. * Walk with statement.
  2477. * @param {WithStatement} statement with statement
  2478. */
  2479. walkWithStatement(statement) {
  2480. if (this._strictInModuleOutput) {
  2481. this._reportStrictModeViolation(
  2482. "`with` statements are not allowed",
  2483. statement
  2484. );
  2485. }
  2486. this.inBlockScope(() => {
  2487. this.walkExpression(statement.object);
  2488. this.walkNestedStatement(statement.body);
  2489. });
  2490. }
  2491. /**
  2492. * Pre walk switch statement.
  2493. * @param {SwitchStatement} statement switch statement
  2494. */
  2495. preWalkSwitchStatement(statement) {
  2496. this.preWalkSwitchCases(statement.cases);
  2497. }
  2498. /**
  2499. * Walk switch statement.
  2500. * @param {SwitchStatement} statement switch statement
  2501. */
  2502. walkSwitchStatement(statement) {
  2503. this.walkExpression(statement.discriminant);
  2504. this.walkSwitchCases(statement.cases);
  2505. }
  2506. /**
  2507. * Walk terminating statement.
  2508. * @param {ReturnStatement | ThrowStatement} statement return or throw statement
  2509. */
  2510. walkTerminatingStatement(statement) {
  2511. if (statement.argument) this.walkExpression(statement.argument);
  2512. // Skip top level scope because to handle `export` and `module.exports` after terminate
  2513. if (this.scope.topLevelScope === true) return;
  2514. if (this.hooks.terminate.call(statement)) {
  2515. this.scope.terminated =
  2516. statement.type === "ReturnStatement"
  2517. ? SCOPE_INFO_TERMINATED_RETURN
  2518. : SCOPE_INFO_TERMINATED_THROW;
  2519. }
  2520. }
  2521. /**
  2522. * Walk return statement.
  2523. * @param {ReturnStatement} statement return statement
  2524. */
  2525. walkReturnStatement(statement) {
  2526. this.walkTerminatingStatement(statement);
  2527. }
  2528. /**
  2529. * Walk throw statement.
  2530. * @param {ThrowStatement} statement return statement
  2531. */
  2532. walkThrowStatement(statement) {
  2533. this.walkTerminatingStatement(statement);
  2534. }
  2535. /**
  2536. * Pre walk try statement.
  2537. * @param {TryStatement} statement try statement
  2538. */
  2539. preWalkTryStatement(statement) {
  2540. this.preWalkStatement(statement.block);
  2541. if (statement.handler) this.preWalkCatchClause(statement.handler);
  2542. if (statement.finalizer) this.preWalkStatement(statement.finalizer);
  2543. }
  2544. /**
  2545. * Walk try statement.
  2546. * @param {TryStatement} statement try statement
  2547. */
  2548. walkTryStatement(statement) {
  2549. if (this.scope.inTry) {
  2550. this.walkStatement(statement.block);
  2551. } else {
  2552. this.scope.inTry = true;
  2553. this.walkStatement(statement.block);
  2554. this.scope.inTry = false;
  2555. }
  2556. const tryTerminated = this.scope.terminated;
  2557. this.scope.terminated = undefined;
  2558. if (statement.handler) this.walkCatchClause(statement.handler);
  2559. const handlerTerminated = this.scope.terminated;
  2560. this.scope.terminated = undefined;
  2561. if (statement.finalizer) {
  2562. this.walkStatement(statement.finalizer);
  2563. }
  2564. const finalizerTerminated = this.scope.terminated;
  2565. this.scope.terminated = undefined;
  2566. if (finalizerTerminated) {
  2567. this.scope.terminated = finalizerTerminated;
  2568. } else if (
  2569. tryTerminated &&
  2570. (statement.handler ? handlerTerminated : true)
  2571. ) {
  2572. this.scope.terminated = handlerTerminated || tryTerminated;
  2573. }
  2574. }
  2575. /**
  2576. * Pre walk while statement.
  2577. * @param {WhileStatement} statement while statement
  2578. */
  2579. preWalkWhileStatement(statement) {
  2580. this.preWalkStatement(statement.body);
  2581. }
  2582. /**
  2583. * Walk while statement.
  2584. * @param {WhileStatement} statement while statement
  2585. */
  2586. walkWhileStatement(statement) {
  2587. this.inBlockScope(() => {
  2588. this.walkExpression(statement.test);
  2589. this.walkNestedStatement(statement.body);
  2590. });
  2591. }
  2592. /**
  2593. * Pre walk do while statement.
  2594. * @param {DoWhileStatement} statement do while statement
  2595. */
  2596. preWalkDoWhileStatement(statement) {
  2597. this.preWalkStatement(statement.body);
  2598. }
  2599. /**
  2600. * Walk do while statement.
  2601. * @param {DoWhileStatement} statement do while statement
  2602. */
  2603. walkDoWhileStatement(statement) {
  2604. this.inBlockScope(() => {
  2605. this.walkNestedStatement(statement.body);
  2606. this.walkExpression(statement.test);
  2607. });
  2608. }
  2609. /**
  2610. * Pre walk for statement.
  2611. * @param {ForStatement} statement for statement
  2612. */
  2613. preWalkForStatement(statement) {
  2614. if (statement.init && statement.init.type === "VariableDeclaration") {
  2615. this.preWalkStatement(statement.init);
  2616. }
  2617. this.preWalkStatement(statement.body);
  2618. }
  2619. /**
  2620. * Walk for statement.
  2621. * @param {ForStatement} statement for statement
  2622. */
  2623. walkForStatement(statement) {
  2624. this.inBlockScope(() => {
  2625. if (statement.init) {
  2626. if (statement.init.type === "VariableDeclaration") {
  2627. this.blockPreWalkVariableDeclaration(statement.init);
  2628. this.prevStatement = undefined;
  2629. this.walkStatement(statement.init);
  2630. } else {
  2631. this.walkExpression(statement.init);
  2632. }
  2633. }
  2634. if (statement.test) {
  2635. this.walkExpression(statement.test);
  2636. }
  2637. if (statement.update) {
  2638. this.walkExpression(statement.update);
  2639. }
  2640. const body = statement.body;
  2641. if (body.type === "BlockStatement") {
  2642. // no need to add additional scope
  2643. const prev = this.prevStatement;
  2644. this.blockPreWalkStatements(body.body);
  2645. this.prevStatement = prev;
  2646. this.walkStatements(body.body);
  2647. } else {
  2648. this.walkNestedStatement(body);
  2649. }
  2650. });
  2651. }
  2652. /**
  2653. * Pre walk for in statement.
  2654. * @param {ForInStatement} statement for statement
  2655. */
  2656. preWalkForInStatement(statement) {
  2657. if (statement.left.type === "VariableDeclaration") {
  2658. this.preWalkVariableDeclaration(statement.left);
  2659. }
  2660. this.preWalkStatement(statement.body);
  2661. }
  2662. /**
  2663. * Walk for in statement.
  2664. * @param {ForInStatement} statement for statement
  2665. */
  2666. walkForInStatement(statement) {
  2667. this.inBlockScope(() => {
  2668. if (statement.left.type === "VariableDeclaration") {
  2669. this.blockPreWalkVariableDeclaration(statement.left);
  2670. this.walkVariableDeclaration(statement.left);
  2671. } else {
  2672. this.walkPattern(statement.left);
  2673. }
  2674. this.walkExpression(statement.right);
  2675. const body = statement.body;
  2676. if (body.type === "BlockStatement") {
  2677. // no need to add additional scope
  2678. const prev = this.prevStatement;
  2679. this.blockPreWalkStatements(body.body);
  2680. this.prevStatement = prev;
  2681. this.walkStatements(body.body);
  2682. } else {
  2683. this.walkNestedStatement(body);
  2684. }
  2685. });
  2686. }
  2687. /**
  2688. * Pre walk for of statement.
  2689. * @param {ForOfStatement} statement statement
  2690. */
  2691. preWalkForOfStatement(statement) {
  2692. if (statement.await && this.scope.topLevelScope === true) {
  2693. this.hooks.topLevelAwait.call(statement);
  2694. }
  2695. if (statement.left.type === "VariableDeclaration") {
  2696. this.preWalkVariableDeclaration(statement.left);
  2697. }
  2698. this.preWalkStatement(statement.body);
  2699. }
  2700. /**
  2701. * Walk for of statement.
  2702. * @param {ForOfStatement} statement for statement
  2703. */
  2704. walkForOfStatement(statement) {
  2705. this.inBlockScope(() => {
  2706. if (statement.left.type === "VariableDeclaration") {
  2707. this.blockPreWalkVariableDeclaration(statement.left);
  2708. this.walkVariableDeclaration(statement.left);
  2709. } else {
  2710. this.walkPattern(statement.left);
  2711. }
  2712. this.walkExpression(statement.right);
  2713. const body = statement.body;
  2714. if (body.type === "BlockStatement") {
  2715. // no need to add additional scope
  2716. const prev = this.prevStatement;
  2717. this.blockPreWalkStatements(body.body);
  2718. this.prevStatement = prev;
  2719. this.walkStatements(body.body);
  2720. } else {
  2721. this.walkNestedStatement(body);
  2722. }
  2723. });
  2724. }
  2725. /**
  2726. * Pre walk function declaration.
  2727. * @param {FunctionDeclaration | MaybeNamedFunctionDeclaration} statement function declaration
  2728. */
  2729. preWalkFunctionDeclaration(statement) {
  2730. if (statement.id) {
  2731. if (this._strictInModuleOutput) {
  2732. this._checkStrictModeBinding(statement.id.name, statement.id);
  2733. }
  2734. this.defineVariable(statement.id.name);
  2735. }
  2736. }
  2737. /**
  2738. * Walk function declaration.
  2739. * @param {FunctionDeclaration | MaybeNamedFunctionDeclaration} statement function declaration
  2740. */
  2741. walkFunctionDeclaration(statement) {
  2742. const wasTopLevel = this.scope.topLevelScope;
  2743. this.scope.topLevelScope = false;
  2744. if (this._strictInModuleOutput) {
  2745. this._checkStrictModeParams(statement.params);
  2746. }
  2747. this.inFunctionScope(true, statement.params, () => {
  2748. for (const param of statement.params) {
  2749. this.walkPattern(param);
  2750. }
  2751. this.detectMode(statement.body.body);
  2752. const prev = this.prevStatement;
  2753. this.preWalkStatement(statement.body);
  2754. this.prevStatement = prev;
  2755. this.walkStatement(statement.body);
  2756. });
  2757. this.scope.topLevelScope = wasTopLevel;
  2758. }
  2759. /**
  2760. * Block pre walk expression statement.
  2761. * @param {ExpressionStatement} statement expression statement
  2762. */
  2763. blockPreWalkExpressionStatement(statement) {
  2764. const expression = statement.expression;
  2765. switch (expression.type) {
  2766. case "AssignmentExpression":
  2767. this.preWalkAssignmentExpression(expression);
  2768. }
  2769. }
  2770. /**
  2771. * Pre walk assignment expression.
  2772. * @param {AssignmentExpression} expression assignment expression
  2773. */
  2774. preWalkAssignmentExpression(expression) {
  2775. this.enterDestructuringAssignment(expression.left, expression.right);
  2776. }
  2777. /**
  2778. * Enter destructuring assignment.
  2779. * @param {Pattern} pattern pattern
  2780. * @param {Expression} expression assignment expression
  2781. * @returns {Expression | undefined} destructuring expression
  2782. */
  2783. enterDestructuringAssignment(pattern, expression) {
  2784. if (
  2785. pattern.type !== "ObjectPattern" ||
  2786. !this.destructuringAssignmentProperties
  2787. ) {
  2788. return;
  2789. }
  2790. const expr =
  2791. expression.type === "AwaitExpression" ? expression.argument : expression;
  2792. const destructuring =
  2793. expr.type === "AssignmentExpression"
  2794. ? this.enterDestructuringAssignment(expr.left, expr.right)
  2795. : this.hooks.collectDestructuringAssignmentProperties.call(expr)
  2796. ? expr
  2797. : undefined;
  2798. if (destructuring) {
  2799. const keys = this._preWalkObjectPattern(pattern);
  2800. if (!keys) return;
  2801. // check multiple assignments
  2802. if (this.destructuringAssignmentProperties.has(destructuring)) {
  2803. const set =
  2804. /** @type {DestructuringAssignmentProperties} */
  2805. (this.destructuringAssignmentProperties.get(destructuring));
  2806. for (const id of keys) set.add(id);
  2807. } else {
  2808. this.destructuringAssignmentProperties.set(destructuring, keys);
  2809. }
  2810. }
  2811. return destructuring;
  2812. }
  2813. /**
  2814. * Module pre walk import declaration.
  2815. * @param {ImportDeclaration} statement statement
  2816. */
  2817. modulePreWalkImportDeclaration(statement) {
  2818. const source = /** @type {ImportSource} */ (statement.source.value);
  2819. this.hooks.import.call(statement, source);
  2820. for (const specifier of statement.specifiers) {
  2821. const name = specifier.local.name;
  2822. switch (specifier.type) {
  2823. case "ImportDefaultSpecifier":
  2824. if (
  2825. !this.hooks.importSpecifier.call(statement, source, "default", name)
  2826. ) {
  2827. this.defineVariable(name);
  2828. }
  2829. break;
  2830. case "ImportSpecifier":
  2831. if (
  2832. !this.hooks.importSpecifier.call(
  2833. statement,
  2834. source,
  2835. /** @type {Identifier} */
  2836. (specifier.imported).name ||
  2837. /** @type {string} */
  2838. (
  2839. /** @type {Literal} */
  2840. (specifier.imported).value
  2841. ),
  2842. name
  2843. )
  2844. ) {
  2845. this.defineVariable(name);
  2846. }
  2847. break;
  2848. case "ImportNamespaceSpecifier":
  2849. if (!this.hooks.importSpecifier.call(statement, source, null, name)) {
  2850. this.defineVariable(name);
  2851. }
  2852. break;
  2853. default:
  2854. this.defineVariable(name);
  2855. }
  2856. }
  2857. }
  2858. /**
  2859. * Processes the provided declaration.
  2860. * @param {Declaration} declaration declaration
  2861. * @param {OnIdent} onIdent on ident callback
  2862. */
  2863. enterDeclaration(declaration, onIdent) {
  2864. switch (declaration.type) {
  2865. case "VariableDeclaration":
  2866. for (const declarator of declaration.declarations) {
  2867. switch (declarator.type) {
  2868. case "VariableDeclarator": {
  2869. this.enterPattern(declarator.id, onIdent);
  2870. break;
  2871. }
  2872. }
  2873. }
  2874. break;
  2875. case "FunctionDeclaration":
  2876. this.enterPattern(declaration.id, onIdent);
  2877. break;
  2878. case "ClassDeclaration":
  2879. this.enterPattern(declaration.id, onIdent);
  2880. break;
  2881. }
  2882. }
  2883. /**
  2884. * Module pre walk export named declaration.
  2885. * @param {ExportNamedDeclaration} statement statement
  2886. */
  2887. modulePreWalkExportNamedDeclaration(statement) {
  2888. if (!statement.source) return;
  2889. const source = /** @type {ImportSource} */ (statement.source.value);
  2890. this.hooks.exportImport.call(statement, source);
  2891. if (statement.specifiers) {
  2892. for (
  2893. let specifierIndex = 0;
  2894. specifierIndex < statement.specifiers.length;
  2895. specifierIndex++
  2896. ) {
  2897. const specifier = statement.specifiers[specifierIndex];
  2898. switch (specifier.type) {
  2899. case "ExportSpecifier": {
  2900. const localName =
  2901. /** @type {Identifier} */ (specifier.local).name ||
  2902. /** @type {string} */ (
  2903. /** @type {Literal} */ (specifier.local).value
  2904. );
  2905. const name =
  2906. /** @type {Identifier} */
  2907. (specifier.exported).name ||
  2908. /** @type {string} */
  2909. (/** @type {Literal} */ (specifier.exported).value);
  2910. this.hooks.exportImportSpecifier.call(
  2911. statement,
  2912. source,
  2913. localName,
  2914. name,
  2915. specifierIndex
  2916. );
  2917. break;
  2918. }
  2919. }
  2920. }
  2921. }
  2922. }
  2923. /**
  2924. * Block pre walk export named declaration.
  2925. * @param {ExportNamedDeclaration} statement statement
  2926. */
  2927. blockPreWalkExportNamedDeclaration(statement) {
  2928. if (statement.source) return;
  2929. this.hooks.export.call(statement);
  2930. if (
  2931. statement.declaration &&
  2932. !this.hooks.exportDeclaration.call(statement, statement.declaration)
  2933. ) {
  2934. const prev = this.prevStatement;
  2935. this.preWalkStatement(statement.declaration);
  2936. this.prevStatement = prev;
  2937. this.blockPreWalkStatement(statement.declaration);
  2938. let index = 0;
  2939. this.enterDeclaration(statement.declaration, (def) => {
  2940. this.hooks.exportSpecifier.call(statement, def, def, index++);
  2941. });
  2942. }
  2943. if (statement.specifiers) {
  2944. for (
  2945. let specifierIndex = 0;
  2946. specifierIndex < statement.specifiers.length;
  2947. specifierIndex++
  2948. ) {
  2949. const specifier = statement.specifiers[specifierIndex];
  2950. switch (specifier.type) {
  2951. case "ExportSpecifier": {
  2952. const localName =
  2953. /** @type {Identifier} */ (specifier.local).name ||
  2954. /** @type {string} */ (
  2955. /** @type {Literal} */ (specifier.local).value
  2956. );
  2957. const name =
  2958. /** @type {Identifier} */
  2959. (specifier.exported).name ||
  2960. /** @type {string} */
  2961. (/** @type {Literal} */ (specifier.exported).value);
  2962. this.hooks.exportSpecifier.call(
  2963. statement,
  2964. localName,
  2965. name,
  2966. specifierIndex
  2967. );
  2968. break;
  2969. }
  2970. }
  2971. }
  2972. }
  2973. }
  2974. /**
  2975. * Walk export named declaration.
  2976. * @param {ExportNamedDeclaration} statement the statement
  2977. */
  2978. walkExportNamedDeclaration(statement) {
  2979. if (statement.declaration) {
  2980. this.walkStatement(statement.declaration);
  2981. }
  2982. }
  2983. /**
  2984. * Block pre walk export default declaration.
  2985. * @param {ExportDefaultDeclaration} statement statement
  2986. */
  2987. blockPreWalkExportDefaultDeclaration(statement) {
  2988. if (
  2989. statement.declaration.type === "FunctionDeclaration" ||
  2990. statement.declaration.type === "ClassDeclaration"
  2991. ) {
  2992. const prev = this.prevStatement;
  2993. this.preWalkStatement(statement.declaration);
  2994. this.prevStatement = prev;
  2995. this.blockPreWalkStatement(statement.declaration);
  2996. }
  2997. if (
  2998. /** @type {MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */
  2999. (statement.declaration).id &&
  3000. statement.declaration.type !== "FunctionExpression" &&
  3001. statement.declaration.type !== "ClassExpression"
  3002. ) {
  3003. const declaration =
  3004. /** @type {MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration} */
  3005. (statement.declaration);
  3006. this.hooks.exportSpecifier.call(
  3007. statement,
  3008. /** @type {Identifier} */
  3009. (declaration.id).name,
  3010. "default",
  3011. undefined
  3012. );
  3013. }
  3014. }
  3015. /**
  3016. * Walk export default declaration.
  3017. * @param {ExportDefaultDeclaration} statement statement
  3018. */
  3019. walkExportDefaultDeclaration(statement) {
  3020. this.hooks.export.call(statement);
  3021. if (
  3022. /** @type {FunctionDeclaration | ClassDeclaration} */
  3023. (statement.declaration).id &&
  3024. statement.declaration.type !== "FunctionExpression" &&
  3025. statement.declaration.type !== "ClassExpression"
  3026. ) {
  3027. const declaration =
  3028. /** @type {FunctionDeclaration | ClassDeclaration} */
  3029. (statement.declaration);
  3030. if (!this.hooks.exportDeclaration.call(statement, declaration)) {
  3031. this.walkStatement(declaration);
  3032. }
  3033. } else {
  3034. // Acorn parses `export default function() {}` as `FunctionDeclaration` and
  3035. // `export default class {}` as `ClassDeclaration`, both with `id = null`.
  3036. // These nodes must be treated as expressions.
  3037. if (
  3038. statement.declaration.type === "FunctionDeclaration" ||
  3039. statement.declaration.type === "ClassDeclaration"
  3040. ) {
  3041. this.walkStatement(statement.declaration);
  3042. } else {
  3043. this.walkExpression(statement.declaration);
  3044. }
  3045. this.hooks.exportExpression.call(statement, statement.declaration);
  3046. }
  3047. }
  3048. /**
  3049. * Module pre walk export all declaration.
  3050. * @param {ExportAllDeclaration} statement statement
  3051. */
  3052. modulePreWalkExportAllDeclaration(statement) {
  3053. const source = /** @type {ImportSource} */ (statement.source.value);
  3054. const name = statement.exported
  3055. ? /** @type {Identifier} */
  3056. (statement.exported).name ||
  3057. /** @type {string} */
  3058. (/** @type {Literal} */ (statement.exported).value)
  3059. : null;
  3060. this.hooks.exportImport.call(statement, source);
  3061. this.hooks.exportImportSpecifier.call(statement, source, null, name, 0);
  3062. }
  3063. /**
  3064. * Pre walk variable declaration.
  3065. * @param {VariableDeclaration} statement variable declaration
  3066. */
  3067. preWalkVariableDeclaration(statement) {
  3068. if (statement.kind !== "var") return;
  3069. this._preWalkVariableDeclaration(statement, this.hooks.varDeclarationVar);
  3070. }
  3071. /**
  3072. * Block pre walk variable declaration.
  3073. * @param {VariableDeclaration} statement variable declaration
  3074. */
  3075. blockPreWalkVariableDeclaration(statement) {
  3076. if (statement.kind === "var") return;
  3077. if (statement.kind === "await using" && this.scope.topLevelScope === true) {
  3078. this.hooks.topLevelAwait.call(statement);
  3079. }
  3080. const hookMap =
  3081. statement.kind === "const"
  3082. ? this.hooks.varDeclarationConst
  3083. : statement.kind === "using" || statement.kind === "await using"
  3084. ? this.hooks.varDeclarationUsing
  3085. : this.hooks.varDeclarationLet;
  3086. this._preWalkVariableDeclaration(statement, hookMap);
  3087. }
  3088. /**
  3089. * Pre walk variable declaration.
  3090. * @param {VariableDeclaration} statement variable declaration
  3091. * @param {HookMap<SyncBailHook<[Identifier], boolean | void>>} hookMap map of hooks
  3092. */
  3093. _preWalkVariableDeclaration(statement, hookMap) {
  3094. /** @type {OnIdent | undefined} */
  3095. let onIdent;
  3096. const checkStrictBindings = this._strictInModuleOutput;
  3097. for (const declarator of statement.declarations) {
  3098. if (declarator.type !== "VariableDeclarator") continue;
  3099. this.preWalkVariableDeclarator(declarator);
  3100. if (this.hooks.preDeclarator.call(declarator, statement)) continue;
  3101. const id = declarator.id;
  3102. if (id.type === "Identifier") {
  3103. if (checkStrictBindings) this._checkStrictModeBinding(id.name, id);
  3104. // fast path: plain `const x =` skips the enterPattern dispatch and
  3105. // the per-declaration onIdent closure (only patterns need it)
  3106. if (!this.callHooksForName(this.hooks.pattern, id.name, id)) {
  3107. this._defineVariableForDeclaration(id.name, id, hookMap);
  3108. }
  3109. } else {
  3110. if (onIdent === undefined) {
  3111. onIdent = (name, ident) => {
  3112. if (checkStrictBindings) this._checkStrictModeBinding(name, ident);
  3113. this._defineVariableForDeclaration(name, ident, hookMap);
  3114. };
  3115. }
  3116. this.enterPattern(id, onIdent);
  3117. }
  3118. }
  3119. }
  3120. /**
  3121. * Defines a declared variable unless a declaration hook handles it.
  3122. * @param {string} name variable name
  3123. * @param {Identifier} ident identifier node
  3124. * @param {HookMap<SyncBailHook<[Identifier], boolean | void>>} hookMap kind-specific declaration hooks
  3125. * @returns {void}
  3126. */
  3127. _defineVariableForDeclaration(name, ident, hookMap) {
  3128. let hook = hookMap.get(name);
  3129. if (hook === undefined || !hook.call(ident)) {
  3130. hook = this.hooks.varDeclaration.get(name);
  3131. if (hook === undefined || !hook.call(ident)) {
  3132. this.defineVariable(name);
  3133. }
  3134. }
  3135. }
  3136. /**
  3137. * Pre walk object pattern.
  3138. * @param {ObjectPattern} objectPattern object pattern
  3139. * @returns {DestructuringAssignmentProperties | undefined} set of names or undefined if not all keys are identifiers
  3140. */
  3141. _preWalkObjectPattern(objectPattern) {
  3142. /** @type {DestructuringAssignmentProperties} */
  3143. const props = new Set();
  3144. const properties = objectPattern.properties;
  3145. for (let i = 0; i < properties.length; i++) {
  3146. const property = properties[i];
  3147. if (property.type !== "Property") return;
  3148. if (property.shorthand) {
  3149. if (property.value.type === "Identifier") {
  3150. this.scope.inShorthand = property.value.name;
  3151. } else if (
  3152. property.value.type === "AssignmentPattern" &&
  3153. property.value.left.type === "Identifier"
  3154. ) {
  3155. this.scope.inShorthand = property.value.left.name;
  3156. }
  3157. }
  3158. const key = property.key;
  3159. if (key.type === "Identifier" && !property.computed) {
  3160. const pattern =
  3161. property.value.type === "ObjectPattern"
  3162. ? this._preWalkObjectPattern(property.value)
  3163. : property.value.type === "ArrayPattern"
  3164. ? this._preWalkArrayPattern(property.value)
  3165. : undefined;
  3166. props.add({
  3167. id: key.name,
  3168. range: /** @type {Range} */ (key.range),
  3169. pattern,
  3170. shorthand: this.scope.inShorthand
  3171. });
  3172. } else {
  3173. const id = this.evaluateExpression(key);
  3174. const str = id.asString();
  3175. if (str) {
  3176. const pattern =
  3177. property.value.type === "ObjectPattern"
  3178. ? this._preWalkObjectPattern(property.value)
  3179. : property.value.type === "ArrayPattern"
  3180. ? this._preWalkArrayPattern(property.value)
  3181. : undefined;
  3182. props.add({
  3183. id: str,
  3184. range: /** @type {Range} */ (key.range),
  3185. pattern,
  3186. shorthand: this.scope.inShorthand
  3187. });
  3188. } else {
  3189. // could not evaluate key
  3190. return;
  3191. }
  3192. }
  3193. this.scope.inShorthand = false;
  3194. }
  3195. return props;
  3196. }
  3197. /**
  3198. * Pre walk array pattern.
  3199. * @param {ArrayPattern} arrayPattern array pattern
  3200. * @returns {Set<DestructuringAssignmentProperty> | undefined} set of names or undefined if not all keys are identifiers
  3201. */
  3202. _preWalkArrayPattern(arrayPattern) {
  3203. /** @type {Set<DestructuringAssignmentProperty>} */
  3204. const props = new Set();
  3205. const elements = arrayPattern.elements;
  3206. for (let i = 0; i < elements.length; i++) {
  3207. const element = elements[i];
  3208. if (!element) continue;
  3209. if (element.type === "RestElement") return;
  3210. const pattern =
  3211. element.type === "ObjectPattern"
  3212. ? this._preWalkObjectPattern(element)
  3213. : element.type === "ArrayPattern"
  3214. ? this._preWalkArrayPattern(element)
  3215. : undefined;
  3216. props.add({
  3217. id: `${i}`,
  3218. range: /** @type {Range} */ (element.range),
  3219. pattern,
  3220. shorthand: false
  3221. });
  3222. }
  3223. return props;
  3224. }
  3225. /**
  3226. * Pre walk variable declarator.
  3227. * @param {VariableDeclarator} declarator variable declarator
  3228. */
  3229. preWalkVariableDeclarator(declarator) {
  3230. if (declarator.init) {
  3231. this.enterDestructuringAssignment(declarator.id, declarator.init);
  3232. }
  3233. }
  3234. /**
  3235. * Walk variable declaration.
  3236. * @param {VariableDeclaration} statement variable declaration
  3237. */
  3238. walkVariableDeclaration(statement) {
  3239. for (const declarator of statement.declarations) {
  3240. switch (declarator.type) {
  3241. case "VariableDeclarator": {
  3242. const renameIdentifier =
  3243. declarator.init && this.getRenameIdentifier(declarator.init);
  3244. if (renameIdentifier && declarator.id.type === "Identifier") {
  3245. const hook = this.hooks.canRename.get(renameIdentifier);
  3246. if (
  3247. hook !== undefined &&
  3248. hook.call(/** @type {Expression} */ (declarator.init))
  3249. ) {
  3250. // renaming with "var a = b;"
  3251. const hook = this.hooks.rename.get(renameIdentifier);
  3252. if (
  3253. hook === undefined ||
  3254. !hook.call(/** @type {Expression} */ (declarator.init))
  3255. ) {
  3256. this.setVariable(declarator.id.name, renameIdentifier);
  3257. }
  3258. break;
  3259. }
  3260. }
  3261. if (!this.hooks.declarator.call(declarator, statement)) {
  3262. this.walkPattern(declarator.id);
  3263. if (declarator.init) this.walkExpression(declarator.init);
  3264. }
  3265. break;
  3266. }
  3267. }
  3268. }
  3269. }
  3270. /**
  3271. * Block pre walk class declaration.
  3272. * @param {ClassDeclaration | MaybeNamedClassDeclaration} statement class declaration
  3273. */
  3274. blockPreWalkClassDeclaration(statement) {
  3275. if (statement.id) {
  3276. // only `await` reaches here: acorn rejects the other names itself,
  3277. // since a class body is always strict even in a loose script
  3278. if (this._strictInModuleOutput) {
  3279. this._checkStrictModeBinding(statement.id.name, statement.id);
  3280. }
  3281. this.defineVariable(statement.id.name);
  3282. }
  3283. }
  3284. /**
  3285. * Walk class declaration.
  3286. * @param {ClassDeclaration | MaybeNamedClassDeclaration} statement class declaration
  3287. */
  3288. walkClassDeclaration(statement) {
  3289. this.walkClass(statement);
  3290. }
  3291. /**
  3292. * Pre walk switch cases.
  3293. * @param {SwitchCase[]} switchCases switch statement
  3294. */
  3295. preWalkSwitchCases(switchCases) {
  3296. for (let index = 0, len = switchCases.length; index < len; index++) {
  3297. const switchCase = switchCases[index];
  3298. this.preWalkStatements(switchCase.consequent);
  3299. }
  3300. }
  3301. /**
  3302. * Processes the provided switch case.
  3303. * @param {SwitchCase[]} switchCases switch statement
  3304. */
  3305. walkSwitchCases(switchCases) {
  3306. this.inBlockScope(() => {
  3307. const len = switchCases.length;
  3308. // we need to pre walk all statements first since we can have invalid code
  3309. // import A from "module";
  3310. // switch(1) {
  3311. // case 1:
  3312. // console.log(A); // should fail at runtime
  3313. // case 2:
  3314. // const A = 1;
  3315. // }
  3316. for (let index = 0; index < len; index++) {
  3317. const switchCase = switchCases[index];
  3318. if (switchCase.consequent.length > 0) {
  3319. const prev = this.prevStatement;
  3320. this.blockPreWalkStatements(switchCase.consequent);
  3321. this.prevStatement = prev;
  3322. }
  3323. }
  3324. for (let index = 0; index < len; index++) {
  3325. const switchCase = switchCases[index];
  3326. if (switchCase.test) {
  3327. this.walkExpression(switchCase.test);
  3328. }
  3329. if (switchCase.consequent.length > 0) {
  3330. this.walkStatements(switchCase.consequent);
  3331. this.scope.terminated = undefined;
  3332. }
  3333. }
  3334. });
  3335. }
  3336. /**
  3337. * Pre walk catch clause.
  3338. * @param {CatchClause} catchClause catch clause
  3339. */
  3340. preWalkCatchClause(catchClause) {
  3341. this.preWalkStatement(catchClause.body);
  3342. }
  3343. /**
  3344. * Processes the provided catch clause.
  3345. * @param {CatchClause} catchClause catch clause
  3346. */
  3347. walkCatchClause(catchClause) {
  3348. this.inBlockScope(() => {
  3349. // Error binding is optional in catch clause since ECMAScript 2019
  3350. if (catchClause.param !== null) {
  3351. this.enterPattern(catchClause.param, (ident, identifier) => {
  3352. if (this._strictInModuleOutput) {
  3353. this._checkStrictModeBinding(ident, identifier);
  3354. }
  3355. this.defineVariable(ident);
  3356. });
  3357. this.walkPattern(catchClause.param);
  3358. }
  3359. const prev = this.prevStatement;
  3360. this.blockPreWalkStatement(catchClause.body);
  3361. this.prevStatement = prev;
  3362. this.walkStatement(catchClause.body);
  3363. }, true);
  3364. }
  3365. /**
  3366. * Processes the provided pattern.
  3367. * @param {Pattern} pattern pattern
  3368. */
  3369. walkPattern(pattern) {
  3370. switch (pattern.type) {
  3371. // plain identifier bindings are the common case and walk nothing
  3372. case "Identifier":
  3373. break;
  3374. case "ObjectPattern":
  3375. this.walkObjectPattern(pattern);
  3376. break;
  3377. case "ArrayPattern":
  3378. this.walkArrayPattern(pattern);
  3379. break;
  3380. case "AssignmentPattern":
  3381. this.walkAssignmentPattern(pattern);
  3382. break;
  3383. case "MemberExpression":
  3384. this.walkMemberExpression(pattern);
  3385. break;
  3386. case "RestElement":
  3387. this.walkRestElement(pattern);
  3388. break;
  3389. }
  3390. }
  3391. /**
  3392. * Walk assignment pattern.
  3393. * @param {AssignmentPattern} pattern assignment pattern
  3394. */
  3395. walkAssignmentPattern(pattern) {
  3396. this.walkExpression(pattern.right);
  3397. this.walkPattern(pattern.left);
  3398. }
  3399. /**
  3400. * Walk object pattern.
  3401. * @param {ObjectPattern} pattern pattern
  3402. */
  3403. walkObjectPattern(pattern) {
  3404. for (let i = 0, len = pattern.properties.length; i < len; i++) {
  3405. const prop = pattern.properties[i];
  3406. if (prop) {
  3407. if (prop.type === "RestElement") {
  3408. continue;
  3409. }
  3410. if (prop.computed) this.walkExpression(prop.key);
  3411. if (prop.value) this.walkPattern(prop.value);
  3412. }
  3413. }
  3414. }
  3415. /**
  3416. * Walk array pattern.
  3417. * @param {ArrayPattern} pattern array pattern
  3418. */
  3419. walkArrayPattern(pattern) {
  3420. for (let i = 0, len = pattern.elements.length; i < len; i++) {
  3421. const element = pattern.elements[i];
  3422. if (element) this.walkPattern(element);
  3423. }
  3424. }
  3425. /**
  3426. * Processes the provided pattern.
  3427. * @param {RestElement} pattern rest element
  3428. */
  3429. walkRestElement(pattern) {
  3430. this.walkPattern(pattern.argument);
  3431. }
  3432. /**
  3433. * Processes the provided expression.
  3434. * @param {(Expression | SpreadElement | null)[]} expressions expressions
  3435. */
  3436. walkExpressions(expressions) {
  3437. for (let i = 0, len = expressions.length; i < len; i++) {
  3438. const expression = expressions[i];
  3439. if (expression) {
  3440. this.walkExpression(expression);
  3441. }
  3442. }
  3443. }
  3444. /**
  3445. * Processes the provided expression.
  3446. * @param {Expression | SpreadElement | PrivateIdentifier | Super} expression expression
  3447. */
  3448. walkExpression(expression) {
  3449. // cases ordered by measured node frequency (identifiers are ~40% of all
  3450. // expressions) — V8 compiles this to sequential compares, so hot types
  3451. // must come first
  3452. switch (expression.type) {
  3453. case "Identifier":
  3454. this.walkIdentifier(expression);
  3455. break;
  3456. case "MemberExpression":
  3457. this.walkMemberExpression(expression);
  3458. break;
  3459. case "Literal":
  3460. if (this._strictInModuleOutput) {
  3461. this._checkStrictModeLiteral(expression);
  3462. }
  3463. break;
  3464. case "CallExpression":
  3465. this.walkCallExpression(expression);
  3466. break;
  3467. case "BinaryExpression":
  3468. this.walkBinaryExpression(expression);
  3469. break;
  3470. case "AssignmentExpression":
  3471. this.walkAssignmentExpression(expression);
  3472. break;
  3473. case "UnaryExpression":
  3474. this.walkUnaryExpression(expression);
  3475. break;
  3476. case "LogicalExpression":
  3477. this.walkLogicalExpression(expression);
  3478. break;
  3479. case "ArrowFunctionExpression":
  3480. this.walkArrowFunctionExpression(expression);
  3481. break;
  3482. case "ThisExpression":
  3483. this.walkThisExpression(expression);
  3484. break;
  3485. case "ConditionalExpression":
  3486. this.walkConditionalExpression(expression);
  3487. break;
  3488. case "ArrayExpression":
  3489. this.walkArrayExpression(expression);
  3490. break;
  3491. case "ObjectExpression":
  3492. this.walkObjectExpression(expression);
  3493. break;
  3494. case "FunctionExpression":
  3495. this.walkFunctionExpression(expression);
  3496. break;
  3497. case "NewExpression":
  3498. this.walkNewExpression(expression);
  3499. break;
  3500. case "TemplateLiteral":
  3501. this.walkTemplateLiteral(expression);
  3502. break;
  3503. case "SpreadElement":
  3504. this.walkSpreadElement(expression);
  3505. break;
  3506. case "SequenceExpression":
  3507. this.walkSequenceExpression(expression);
  3508. break;
  3509. case "UpdateExpression":
  3510. this.walkUpdateExpression(expression);
  3511. break;
  3512. case "AwaitExpression":
  3513. this.walkAwaitExpression(expression);
  3514. break;
  3515. case "ChainExpression":
  3516. this.walkChainExpression(expression);
  3517. break;
  3518. case "ClassExpression":
  3519. this.walkClassExpression(expression);
  3520. break;
  3521. case "ImportExpression":
  3522. this.walkImportExpression(expression);
  3523. break;
  3524. case "MetaProperty":
  3525. this.walkMetaProperty(expression);
  3526. break;
  3527. case "TaggedTemplateExpression":
  3528. this.walkTaggedTemplateExpression(expression);
  3529. break;
  3530. case "YieldExpression":
  3531. this.walkYieldExpression(expression);
  3532. break;
  3533. }
  3534. }
  3535. /**
  3536. * Reports octal number literals (`0777`) and octal string escapes (`"\47"`),
  3537. * both SyntaxErrors in strict-mode ESM output.
  3538. * @param {Literal} expression literal
  3539. */
  3540. _checkStrictModeLiteral(expression) {
  3541. const raw = /** @type {string | undefined} */ (expression.raw);
  3542. if (raw === undefined) return;
  3543. if (typeof expression.value === "number") {
  3544. // Legacy octal (`0777`) or non-octal decimal (`08`) integer literal.
  3545. if (
  3546. raw.length > 1 &&
  3547. raw.charCodeAt(0) === 48 &&
  3548. raw.charCodeAt(1) >= 48 &&
  3549. raw.charCodeAt(1) <= 57
  3550. ) {
  3551. this._reportStrictModeViolation(
  3552. "Octal literals are not allowed",
  3553. expression
  3554. );
  3555. }
  3556. } else if (typeof expression.value === "string" && hasOctalEscape(raw)) {
  3557. this._reportStrictModeViolation(
  3558. "Octal escape sequences are not allowed",
  3559. expression
  3560. );
  3561. }
  3562. }
  3563. /**
  3564. * Walk await expression.
  3565. * @param {AwaitExpression} expression await expression
  3566. */
  3567. walkAwaitExpression(expression) {
  3568. if (this.scope.topLevelScope === true) {
  3569. this.hooks.topLevelAwait.call(expression);
  3570. }
  3571. this.walkExpression(expression.argument);
  3572. }
  3573. /**
  3574. * Walk array expression.
  3575. * @param {ArrayExpression} expression array expression
  3576. */
  3577. walkArrayExpression(expression) {
  3578. if (expression.elements) {
  3579. this.walkExpressions(expression.elements);
  3580. }
  3581. }
  3582. /**
  3583. * Walk spread element.
  3584. * @param {SpreadElement} expression spread element
  3585. */
  3586. walkSpreadElement(expression) {
  3587. if (expression.argument) {
  3588. this.walkExpression(expression.argument);
  3589. }
  3590. }
  3591. /**
  3592. * Walk object expression.
  3593. * @param {ObjectExpression} expression object expression
  3594. */
  3595. walkObjectExpression(expression) {
  3596. for (
  3597. let propIndex = 0, len = expression.properties.length;
  3598. propIndex < len;
  3599. propIndex++
  3600. ) {
  3601. const prop = expression.properties[propIndex];
  3602. this.walkProperty(prop);
  3603. }
  3604. }
  3605. /**
  3606. * Processes the provided prop.
  3607. * @param {Property | SpreadElement} prop property or spread element
  3608. */
  3609. walkProperty(prop) {
  3610. if (prop.type === "SpreadElement") {
  3611. this.walkExpression(prop.argument);
  3612. return;
  3613. }
  3614. if (prop.computed) {
  3615. this.walkExpression(prop.key);
  3616. }
  3617. if (prop.shorthand && prop.value && prop.value.type === "Identifier") {
  3618. this.scope.inShorthand = prop.value.name;
  3619. this.walkIdentifier(prop.value);
  3620. this.scope.inShorthand = false;
  3621. } else {
  3622. this.walkExpression(
  3623. /** @type {Exclude<Property["value"], AssignmentPattern | ObjectPattern | ArrayPattern | RestElement>} */
  3624. (prop.value)
  3625. );
  3626. }
  3627. }
  3628. /**
  3629. * Walk function expression.
  3630. * @param {FunctionExpression} expression arrow function expression
  3631. */
  3632. walkFunctionExpression(expression) {
  3633. const wasTopLevel = this.scope.topLevelScope;
  3634. this.scope.topLevelScope = false;
  3635. // Only copy params when the function name must be added (recursive calls);
  3636. // inFunctionScope reads params without mutating, like arrow functions.
  3637. const scopeParams = expression.id
  3638. ? [...expression.params, expression.id]
  3639. : expression.params;
  3640. if (this._strictInModuleOutput) {
  3641. this._checkStrictModeParams(expression.params);
  3642. if (expression.id) {
  3643. this._checkStrictModeBinding(expression.id.name, expression.id);
  3644. }
  3645. }
  3646. this.inFunctionScope(true, scopeParams, () => {
  3647. for (const param of expression.params) {
  3648. this.walkPattern(param);
  3649. }
  3650. this.detectMode(expression.body.body);
  3651. const prev = this.prevStatement;
  3652. this.preWalkStatement(expression.body);
  3653. this.prevStatement = prev;
  3654. this.walkStatement(expression.body);
  3655. });
  3656. this.scope.topLevelScope = wasTopLevel;
  3657. }
  3658. /**
  3659. * Walk arrow function expression.
  3660. * @param {ArrowFunctionExpression} expression arrow function expression
  3661. */
  3662. walkArrowFunctionExpression(expression) {
  3663. const wasTopLevel = this.scope.topLevelScope;
  3664. this.scope.topLevelScope = wasTopLevel ? "arrow" : false;
  3665. if (this._strictInModuleOutput) {
  3666. this._checkStrictModeParams(expression.params);
  3667. }
  3668. this.inFunctionScope(false, expression.params, () => {
  3669. for (const param of expression.params) {
  3670. this.walkPattern(param);
  3671. }
  3672. if (expression.body.type === "BlockStatement") {
  3673. this.detectMode(expression.body.body);
  3674. const prev = this.prevStatement;
  3675. this.preWalkStatement(expression.body);
  3676. this.prevStatement = prev;
  3677. this.walkStatement(expression.body);
  3678. } else {
  3679. this.walkExpression(expression.body);
  3680. }
  3681. });
  3682. this.scope.topLevelScope = wasTopLevel;
  3683. }
  3684. /**
  3685. * Walk sequence expression.
  3686. * @param {SequenceExpression} expression the sequence
  3687. */
  3688. walkSequenceExpression(expression) {
  3689. if (!expression.expressions) return;
  3690. // We treat sequence expressions like statements when they are one statement level
  3691. // This has some benefits for optimizations that only work on statement level
  3692. const currentStatement =
  3693. /** @type {StatementPath} */
  3694. (this.statementPath)[
  3695. /** @type {StatementPath} */
  3696. (this.statementPath).length - 1
  3697. ];
  3698. if (
  3699. currentStatement === expression ||
  3700. (currentStatement.type === "ExpressionStatement" &&
  3701. currentStatement.expression === expression)
  3702. ) {
  3703. const old =
  3704. /** @type {StatementPathItem} */
  3705. (/** @type {StatementPath} */ (this.statementPath).pop());
  3706. const prev = this.prevStatement;
  3707. for (const expr of expression.expressions) {
  3708. /** @type {StatementPath} */
  3709. (this.statementPath).push(expr);
  3710. this.walkExpression(expr);
  3711. this.prevStatement =
  3712. /** @type {StatementPath} */
  3713. (this.statementPath).pop();
  3714. }
  3715. this.prevStatement = prev;
  3716. /** @type {StatementPath} */
  3717. (this.statementPath).push(old);
  3718. } else {
  3719. this.walkExpressions(expression.expressions);
  3720. }
  3721. }
  3722. /**
  3723. * Walk update expression.
  3724. * @param {UpdateExpression} expression the update expression
  3725. */
  3726. walkUpdateExpression(expression) {
  3727. if (
  3728. this._strictInModuleOutput &&
  3729. expression.argument.type === "Identifier"
  3730. ) {
  3731. this._checkStrictModeAssignTarget(expression.argument.name, expression);
  3732. }
  3733. this.walkExpression(expression.argument);
  3734. }
  3735. /**
  3736. * Reports `arguments.callee` / `arguments.caller` — both throw a TypeError
  3737. * once the module runs in strict-mode ESM output.
  3738. * @param {string} name accessed member name
  3739. * @param {Expression} node node to report the violation at
  3740. */
  3741. _checkStrictModeArgumentsMember(name, node) {
  3742. if ((name === "callee" || name === "caller") && !this.scope.isStrict) {
  3743. this._reportStrictModeViolation(
  3744. `Accessing "arguments.${name}" is not allowed`,
  3745. node
  3746. );
  3747. }
  3748. }
  3749. /**
  3750. * Reports an assignment or update target that breaks in strict-mode ESM
  3751. * output: `eval` / `arguments` are a SyntaxError, the read-only globals
  3752. * (`undefined`, `NaN`, `Infinity`) a TypeError instead of a silent no-op.
  3753. * @param {string} name target identifier name
  3754. * @param {AssignmentExpression | UpdateExpression} node node to report the violation at
  3755. */
  3756. _checkStrictModeAssignTarget(name, node) {
  3757. if (name === "eval" || name === "arguments") {
  3758. this._reportStrictModeViolation(
  3759. `Assigning to "${name}" is not allowed`,
  3760. node
  3761. );
  3762. } else if (
  3763. (name === "undefined" || name === "NaN" || name === "Infinity") &&
  3764. !this.scope.isStrict &&
  3765. !this.isVariableDefined(name)
  3766. ) {
  3767. this._reportStrictModeViolation(
  3768. `Assigning to the read-only global "${name}" is not allowed`,
  3769. node
  3770. );
  3771. }
  3772. }
  3773. /**
  3774. * Reports a binding name a loose script allows but strict-mode ESM output
  3775. * rejects — the whole bundle fails to parse, so this is never merely latent.
  3776. * @param {string} name binding name
  3777. * @param {Statement | Expression | Identifier} node node to report the violation at
  3778. */
  3779. _checkStrictModeBinding(name, node) {
  3780. if (name === "eval" || name === "arguments") {
  3781. this._reportStrictModeViolation(
  3782. `"${name}" is not allowed as a binding name`,
  3783. node
  3784. );
  3785. } else if (STRICT_MODE_RESERVED_WORDS.has(name)) {
  3786. this._reportStrictModeViolation(
  3787. `"${name}" is a reserved word in strict mode and is not allowed as a binding name`,
  3788. node
  3789. );
  3790. } else if (name === "await") {
  3791. this._reportStrictModeViolation(
  3792. '"await" is not allowed as a binding name',
  3793. node,
  3794. MODULE_GOAL_OUTPUT_REASON
  3795. );
  3796. }
  3797. }
  3798. /**
  3799. * Reports strict-mode-only errors in a function's parameter list: a duplicate
  3800. * simple parameter, or a parameter named `eval` / `arguments`.
  3801. * @param {(import("estree").Pattern)[]} params function parameters
  3802. */
  3803. _checkStrictModeParams(params) {
  3804. /** @type {Set<string> | undefined} */
  3805. let seen;
  3806. for (const param of params) {
  3807. if (param.type !== "Identifier") continue;
  3808. const name = param.name;
  3809. if (name === "eval" || name === "arguments") {
  3810. this._reportStrictModeViolation(
  3811. `"${name}" is not allowed as a parameter name`,
  3812. param
  3813. );
  3814. } else if (STRICT_MODE_RESERVED_WORDS.has(name)) {
  3815. this._reportStrictModeViolation(
  3816. `"${name}" is a reserved word in strict mode and is not allowed as a parameter name`,
  3817. param
  3818. );
  3819. } else if (name === "await") {
  3820. this._reportStrictModeViolation(
  3821. '"await" is not allowed as a parameter name',
  3822. param,
  3823. MODULE_GOAL_OUTPUT_REASON
  3824. );
  3825. }
  3826. if (seen === undefined) seen = new Set();
  3827. if (seen.has(name)) {
  3828. this._reportStrictModeViolation(
  3829. `Duplicate parameter name "${name}" is not allowed`,
  3830. param
  3831. );
  3832. } else {
  3833. seen.add(name);
  3834. }
  3835. }
  3836. }
  3837. /**
  3838. * Walk unary expression.
  3839. * @param {UnaryExpression} expression the unary expression
  3840. */
  3841. walkUnaryExpression(expression) {
  3842. if (expression.operator === "typeof") {
  3843. const result = this.callHooksForExpression(
  3844. this.hooks.typeof,
  3845. expression.argument,
  3846. expression
  3847. );
  3848. if (result === true) return;
  3849. if (expression.argument.type === "ChainExpression") {
  3850. const result = this.callHooksForExpression(
  3851. this.hooks.typeof,
  3852. expression.argument.expression,
  3853. expression
  3854. );
  3855. if (result === true) return;
  3856. }
  3857. } else if (
  3858. this._strictInModuleOutput &&
  3859. expression.operator === "delete" &&
  3860. expression.argument.type === "Identifier"
  3861. ) {
  3862. this._reportStrictModeViolation(
  3863. `Deleting the unqualified identifier "${expression.argument.name}" is not allowed`,
  3864. expression
  3865. );
  3866. }
  3867. this.walkExpression(expression.argument);
  3868. }
  3869. /**
  3870. * Reports a construct that a loose script allows but that breaks once the
  3871. * module is emitted as strict-mode ESM output. Severity comes from the
  3872. * `strictModeViolations` parser option (`false` disables the checks upfront).
  3873. * The location is computed here, on the rare violation path only.
  3874. * @param {string} reason what is not allowed
  3875. * @param {Statement | Expression | Identifier} node node to report the violation at
  3876. * @param {string=} outputReason why the output rejects it, defaults to strict mode
  3877. */
  3878. _reportStrictModeViolation(reason, node, outputReason) {
  3879. const diagnostic = new WebpackError(
  3880. `${reason}. ${outputReason === undefined ? STRICT_MODE_OUTPUT_REASON : outputReason}`
  3881. );
  3882. diagnostic.loc = this.getLocation(node);
  3883. if (this.options.strictModeViolations === "error") {
  3884. this.state.module.addError(diagnostic);
  3885. } else {
  3886. this.state.module.addWarning(diagnostic);
  3887. }
  3888. }
  3889. /**
  3890. * Walk left right expression.
  3891. * @param {LogicalExpression | BinaryExpression} expression the expression
  3892. */
  3893. walkLeftRightExpression(expression) {
  3894. this.walkExpression(expression.left);
  3895. this.walkExpression(expression.right);
  3896. }
  3897. /**
  3898. * Walk binary expression.
  3899. * @param {BinaryExpression} expression the binary expression
  3900. */
  3901. walkBinaryExpression(expression) {
  3902. if (this.hooks.binaryExpression.call(expression) === undefined) {
  3903. this.walkLeftRightExpression(expression);
  3904. }
  3905. }
  3906. /**
  3907. * Walk logical expression.
  3908. * @param {LogicalExpression} expression the logical expression
  3909. */
  3910. walkLogicalExpression(expression) {
  3911. const result = this.hooks.expressionLogicalOperator.call(expression);
  3912. if (result === undefined) {
  3913. this.walkLeftRightExpression(expression);
  3914. } else if (result) {
  3915. this.walkExpression(expression.right);
  3916. }
  3917. }
  3918. /**
  3919. * Walk assignment expression.
  3920. * @param {AssignmentExpression} expression assignment expression
  3921. */
  3922. walkAssignmentExpression(expression) {
  3923. if (expression.left.type === "Identifier") {
  3924. if (this._strictInModuleOutput) {
  3925. this._checkStrictModeAssignTarget(expression.left.name, expression);
  3926. }
  3927. const renameIdentifier = this.getRenameIdentifier(expression.right);
  3928. if (
  3929. renameIdentifier &&
  3930. this.callHooksForInfo(
  3931. this.hooks.canRename,
  3932. renameIdentifier,
  3933. expression.right
  3934. )
  3935. ) {
  3936. // renaming "a = b;"
  3937. if (
  3938. !this.callHooksForInfo(
  3939. this.hooks.rename,
  3940. renameIdentifier,
  3941. expression.right
  3942. )
  3943. ) {
  3944. this.setVariable(
  3945. expression.left.name,
  3946. typeof renameIdentifier === "string"
  3947. ? this.getVariableInfo(renameIdentifier)
  3948. : renameIdentifier
  3949. );
  3950. }
  3951. return;
  3952. }
  3953. this.walkExpression(expression.right);
  3954. this.enterPattern(expression.left, (name, _decl) => {
  3955. if (!this.callHooksForName(this.hooks.assign, name, expression)) {
  3956. this.walkExpression(
  3957. /** @type {MemberExpression} */
  3958. (expression.left)
  3959. );
  3960. }
  3961. });
  3962. } else if (expression.left.type.endsWith("Pattern")) {
  3963. this.walkExpression(expression.right);
  3964. this.enterPattern(expression.left, (name, _decl) => {
  3965. if (!this.callHooksForName(this.hooks.assign, name, expression)) {
  3966. this.defineVariable(name);
  3967. }
  3968. });
  3969. this.walkPattern(expression.left);
  3970. } else if (expression.left.type === "MemberExpression") {
  3971. const exprName = this.getMemberExpressionInfo(
  3972. expression.left,
  3973. ALLOWED_MEMBER_TYPES_EXPRESSION
  3974. );
  3975. if (
  3976. exprName &&
  3977. this.callHooksForInfo(
  3978. this.hooks.assignMemberChain,
  3979. exprName.rootInfo,
  3980. expression,
  3981. exprName.getMembers()
  3982. )
  3983. ) {
  3984. return;
  3985. }
  3986. this.walkExpression(expression.right);
  3987. this.walkExpression(expression.left);
  3988. } else {
  3989. this.walkExpression(expression.right);
  3990. this.walkExpression(
  3991. /** @type {Exclude<AssignmentExpression["left"], Identifier | RestElement | MemberExpression | ObjectPattern | ArrayPattern | AssignmentPattern>} */
  3992. (expression.left)
  3993. );
  3994. }
  3995. }
  3996. /**
  3997. * Walk conditional expression.
  3998. * @param {ConditionalExpression} expression conditional expression
  3999. */
  4000. walkConditionalExpression(expression) {
  4001. const result = this.hooks.expressionConditionalOperator.call(expression);
  4002. if (result === undefined) {
  4003. const guard = this.hooks.collectGuards.call(expression.test);
  4004. this.walkExpression(expression.test);
  4005. this.walkGuardedBranch(guard ? guard.consequent : undefined, () =>
  4006. this.walkExpression(expression.consequent)
  4007. );
  4008. if (expression.alternate) {
  4009. const alternate = expression.alternate;
  4010. this.walkGuardedBranch(guard ? guard.alternate : undefined, () =>
  4011. this.walkExpression(alternate)
  4012. );
  4013. }
  4014. } else if (result) {
  4015. this.walkExpression(expression.consequent);
  4016. } else if (expression.alternate) {
  4017. this.walkExpression(expression.alternate);
  4018. }
  4019. }
  4020. /**
  4021. * Walk new expression.
  4022. * @param {NewExpression} expression new expression
  4023. */
  4024. walkNewExpression(expression) {
  4025. const result = this.callHooksForExpression(
  4026. this.hooks.new,
  4027. expression.callee,
  4028. expression
  4029. );
  4030. if (result === true) return;
  4031. this.walkExpression(expression.callee);
  4032. if (expression.arguments) {
  4033. this.walkExpressions(expression.arguments);
  4034. }
  4035. }
  4036. /**
  4037. * Walk yield expression.
  4038. * @param {YieldExpression} expression yield expression
  4039. */
  4040. walkYieldExpression(expression) {
  4041. if (expression.argument) {
  4042. this.walkExpression(expression.argument);
  4043. }
  4044. }
  4045. /**
  4046. * Walk template literal.
  4047. * @param {TemplateLiteral} expression template literal
  4048. */
  4049. walkTemplateLiteral(expression) {
  4050. if (expression.expressions) {
  4051. this.walkExpressions(expression.expressions);
  4052. }
  4053. }
  4054. /**
  4055. * Walk tagged template expression.
  4056. * @param {TaggedTemplateExpression} expression tagged template expression
  4057. */
  4058. walkTaggedTemplateExpression(expression) {
  4059. if (expression.tag) {
  4060. this.scope.inTaggedTemplateTag = true;
  4061. this.walkExpression(expression.tag);
  4062. this.scope.inTaggedTemplateTag = false;
  4063. }
  4064. if (expression.quasi && expression.quasi.expressions) {
  4065. this.walkExpressions(expression.quasi.expressions);
  4066. }
  4067. }
  4068. /**
  4069. * Walk class expression.
  4070. * @param {ClassExpression} expression the class expression
  4071. */
  4072. walkClassExpression(expression) {
  4073. // only `await` reaches here, as for class declarations
  4074. if (this._strictInModuleOutput && expression.id) {
  4075. this._checkStrictModeBinding(expression.id.name, expression.id);
  4076. }
  4077. this.walkClass(expression);
  4078. }
  4079. /**
  4080. * Walk chain expression.
  4081. * @param {ChainExpression} expression expression
  4082. */
  4083. walkChainExpression(expression) {
  4084. const result = this.hooks.optionalChaining.call(expression);
  4085. if (result === undefined) {
  4086. if (expression.expression.type === "CallExpression") {
  4087. this.walkCallExpression(expression.expression);
  4088. } else {
  4089. this.walkMemberExpression(expression.expression);
  4090. }
  4091. }
  4092. }
  4093. /**
  4094. * Processes the provided function expression.
  4095. * @private
  4096. * @param {FunctionExpression | ArrowFunctionExpression} functionExpression function expression
  4097. * @param {(Expression | SpreadElement)[]} options options
  4098. * @param {Expression | SpreadElement | null} currentThis current this
  4099. */
  4100. _walkIIFE(functionExpression, options, currentThis) {
  4101. /**
  4102. * Returns var info.
  4103. * @param {Expression | SpreadElement} argOrThis arg or this
  4104. * @returns {string | VariableInfo | undefined} var info
  4105. */
  4106. const getVarInfo = (argOrThis) => {
  4107. const renameIdentifier = this.getRenameIdentifier(argOrThis);
  4108. if (
  4109. renameIdentifier &&
  4110. this.callHooksForInfo(
  4111. this.hooks.canRename,
  4112. renameIdentifier,
  4113. /** @type {Expression} */
  4114. (argOrThis)
  4115. ) &&
  4116. !this.callHooksForInfo(
  4117. this.hooks.rename,
  4118. renameIdentifier,
  4119. /** @type {Expression} */
  4120. (argOrThis)
  4121. )
  4122. ) {
  4123. return typeof renameIdentifier === "string"
  4124. ? /** @type {string} */ (this.getVariableInfo(renameIdentifier))
  4125. : renameIdentifier;
  4126. }
  4127. this.walkExpression(argOrThis);
  4128. };
  4129. const { params, type } = functionExpression;
  4130. const arrow = type === "ArrowFunctionExpression";
  4131. // the walk skips walkFunctionExpression for a called function expression
  4132. if (this._strictInModuleOutput) {
  4133. this._checkStrictModeParams(params);
  4134. if (type === "FunctionExpression" && functionExpression.id) {
  4135. this._checkStrictModeBinding(
  4136. functionExpression.id.name,
  4137. functionExpression.id
  4138. );
  4139. }
  4140. }
  4141. const renameThis = currentThis ? getVarInfo(currentThis) : null;
  4142. const varInfoForArgs = options.map(getVarInfo);
  4143. const wasTopLevel = this.scope.topLevelScope;
  4144. this.scope.topLevelScope = wasTopLevel && arrow ? "arrow" : false;
  4145. const scopeParams =
  4146. /** @type {(Identifier | string)[]} */
  4147. (params.filter((identifier, idx) => !varInfoForArgs[idx]));
  4148. // Add function name in scope for recursive calls
  4149. if (
  4150. functionExpression.type === "FunctionExpression" &&
  4151. functionExpression.id
  4152. ) {
  4153. scopeParams.push(functionExpression.id.name);
  4154. }
  4155. this.inFunctionScope(true, scopeParams, () => {
  4156. if (renameThis && !arrow) {
  4157. this.setVariable("this", renameThis);
  4158. }
  4159. for (let i = 0; i < varInfoForArgs.length; i++) {
  4160. const varInfo = varInfoForArgs[i];
  4161. if (!varInfo) continue;
  4162. if (!params[i] || params[i].type !== "Identifier") continue;
  4163. this.setVariable(/** @type {Identifier} */ (params[i]).name, varInfo);
  4164. }
  4165. if (functionExpression.body.type === "BlockStatement") {
  4166. this.detectMode(functionExpression.body.body);
  4167. const prev = this.prevStatement;
  4168. this.preWalkStatement(functionExpression.body);
  4169. this.prevStatement = prev;
  4170. this.walkStatement(functionExpression.body);
  4171. } else {
  4172. this.walkExpression(functionExpression.body);
  4173. }
  4174. });
  4175. this.scope.topLevelScope = wasTopLevel;
  4176. }
  4177. /**
  4178. * Walk import expression.
  4179. * @param {ImportExpression} expression import expression
  4180. */
  4181. walkImportExpression(expression) {
  4182. const result = this.hooks.importCall.call(expression);
  4183. if (result === true) return;
  4184. this.walkExpression(expression.source);
  4185. }
  4186. /**
  4187. * Walk call expression.
  4188. * @param {CallExpression} expression expression
  4189. */
  4190. walkCallExpression(expression) {
  4191. if (
  4192. expression.callee.type === "MemberExpression" &&
  4193. isFunctionExpression(expression.callee.object.type) &&
  4194. !expression.callee.computed &&
  4195. /** @type {boolean} */
  4196. (
  4197. /** @type {Identifier} */
  4198. (expression.callee.property).name === "call" ||
  4199. /** @type {Identifier} */
  4200. (expression.callee.property).name === "bind"
  4201. ) &&
  4202. expression.arguments.length > 0 &&
  4203. isSimpleFunction(
  4204. /** @type {FunctionExpression | ArrowFunctionExpression} */
  4205. (expression.callee.object)
  4206. )
  4207. ) {
  4208. // (function(…) { }.call/bind(?, …))
  4209. this._walkIIFE(
  4210. /** @type {FunctionExpression | ArrowFunctionExpression} */
  4211. (expression.callee.object),
  4212. expression.arguments.slice(1),
  4213. expression.arguments[0]
  4214. );
  4215. } else if (
  4216. isFunctionExpression(expression.callee.type) &&
  4217. isSimpleFunction(
  4218. /** @type {FunctionExpression | ArrowFunctionExpression} */
  4219. (expression.callee)
  4220. )
  4221. ) {
  4222. // (function(…) { }(…))
  4223. this._walkIIFE(
  4224. /** @type {FunctionExpression | ArrowFunctionExpression} */
  4225. (expression.callee),
  4226. expression.arguments,
  4227. null
  4228. );
  4229. } else {
  4230. if (expression.callee.type === "MemberExpression") {
  4231. // callMemberChainOfCallMemberChain only applies to call-rooted
  4232. // chains (e.g. `a().b()`); for the common identifier/this-rooted
  4233. // callee the CALL lookup always rejects, so gate on the cheap root.
  4234. if (
  4235. this.getMemberExpressionRoot(expression.callee).type ===
  4236. "CallExpression"
  4237. ) {
  4238. const exprInfo = this.getMemberExpressionInfo(
  4239. expression.callee,
  4240. ALLOWED_MEMBER_TYPES_CALL_EXPRESSION
  4241. );
  4242. if (exprInfo && exprInfo.type === "call") {
  4243. const result = this.callHooksForInfo(
  4244. this.hooks.callMemberChainOfCallMemberChain,
  4245. exprInfo.rootInfo,
  4246. expression,
  4247. exprInfo.getCalleeMembers(),
  4248. exprInfo.call,
  4249. exprInfo.getMembers(),
  4250. exprInfo.getMemberRanges()
  4251. );
  4252. if (result === true) return;
  4253. }
  4254. }
  4255. // import("./m").then(m => { ... })
  4256. if (
  4257. expression.callee.object.type === "ImportExpression" &&
  4258. expression.callee.property.type === "Identifier" &&
  4259. expression.callee.property.name === "then"
  4260. ) {
  4261. const result = this.hooks.importCall.call(
  4262. expression.callee.object,
  4263. expression
  4264. );
  4265. if (result === true) return;
  4266. }
  4267. }
  4268. if (
  4269. expression.callee.type === "Identifier" &&
  4270. this._evalIdentOwnTaps &&
  4271. expression.callee.name !== "undefined" &&
  4272. this._isDefinedPlainVariable(expression.callee.name)
  4273. ) {
  4274. // a defined, untagged callee can only evaluate to the fallthrough
  4275. // result, so no call hooks apply — walk callee and arguments
  4276. // directly, skipping the hook dispatch and its result object
  4277. this.walkExpression(expression.callee);
  4278. if (expression.arguments) this.walkExpressions(expression.arguments);
  4279. return;
  4280. }
  4281. const callee = this.evaluateExpression(expression.callee);
  4282. if (callee.isIdentifier()) {
  4283. const members =
  4284. /** @type {NonNullable<BasicEvaluatedExpression["getMembers"]>} */
  4285. (callee.getMembers)();
  4286. const result1 = this.callHooksForInfo(
  4287. this.hooks.callMemberChain,
  4288. /** @type {NonNullable<BasicEvaluatedExpression["rootInfo"]>} */
  4289. (callee.rootInfo),
  4290. expression,
  4291. members,
  4292. callee.getMembersOptionals
  4293. ? callee.getMembersOptionals()
  4294. : members.map(RETURN_FALSE),
  4295. callee.getMemberRanges ? callee.getMemberRanges() : []
  4296. );
  4297. if (result1 === true) return;
  4298. const result2 = this.callHooksForInfo(
  4299. this.hooks.call,
  4300. /** @type {NonNullable<BasicEvaluatedExpression["identifier"]>} */
  4301. (callee.identifier),
  4302. expression
  4303. );
  4304. if (result2 === true) return;
  4305. }
  4306. if (expression.callee) {
  4307. if (expression.callee.type === "MemberExpression") {
  4308. // because of call context we need to walk the call context as expression
  4309. this.walkExpression(expression.callee.object);
  4310. if (expression.callee.computed === true) {
  4311. this.walkExpression(expression.callee.property);
  4312. }
  4313. } else {
  4314. this.walkExpression(expression.callee);
  4315. }
  4316. }
  4317. if (expression.arguments) this.walkExpressions(expression.arguments);
  4318. }
  4319. }
  4320. /**
  4321. * Walk member expression.
  4322. * @param {MemberExpression} expression member expression
  4323. */
  4324. walkMemberExpression(expression) {
  4325. const exprInfo = this.getMemberExpressionInfo(
  4326. expression,
  4327. ALLOWED_MEMBER_TYPES_ALL
  4328. );
  4329. if (exprInfo) {
  4330. switch (exprInfo.type) {
  4331. case "expression": {
  4332. const result1 = this.callHooksForInfo(
  4333. this.hooks.expression,
  4334. exprInfo.name,
  4335. expression
  4336. );
  4337. if (result1 === true) return;
  4338. const members = exprInfo.getMembers();
  4339. const membersOptionals = exprInfo.getMembersOptionals();
  4340. const memberRanges = exprInfo.getMemberRanges();
  4341. const result2 = this.callHooksForInfo(
  4342. this.hooks.expressionMemberChain,
  4343. exprInfo.rootInfo,
  4344. expression,
  4345. members,
  4346. membersOptionals,
  4347. memberRanges
  4348. );
  4349. if (result2 === true) return;
  4350. this.walkMemberExpressionWithExpressionName(
  4351. expression,
  4352. exprInfo.name,
  4353. exprInfo.rootInfo,
  4354. [...members],
  4355. () =>
  4356. this.callHooksForInfo(
  4357. this.hooks.unhandledExpressionMemberChain,
  4358. exprInfo.rootInfo,
  4359. expression,
  4360. members
  4361. )
  4362. );
  4363. return;
  4364. }
  4365. case "call": {
  4366. const result = this.callHooksForInfo(
  4367. this.hooks.memberChainOfCallMemberChain,
  4368. exprInfo.rootInfo,
  4369. expression,
  4370. exprInfo.getCalleeMembers(),
  4371. exprInfo.call,
  4372. exprInfo.getMembers(),
  4373. exprInfo.getMemberRanges()
  4374. );
  4375. if (result === true) return;
  4376. // Fast skip over the member chain as we already called memberChainOfCallMemberChain
  4377. // and call computed property are literals anyway
  4378. this.walkExpression(exprInfo.call);
  4379. return;
  4380. }
  4381. }
  4382. }
  4383. this.walkExpression(expression.object);
  4384. if (expression.computed === true) this.walkExpression(expression.property);
  4385. }
  4386. /**
  4387. * Walk member expression with expression name.
  4388. * @template R
  4389. * @param {MemberExpression} expression member expression
  4390. * @param {string} name name
  4391. * @param {string | VariableInfo} rootInfo root info
  4392. * @param {Members} members members
  4393. * @param {() => R | undefined} onUnhandled on unhandled callback
  4394. */
  4395. walkMemberExpressionWithExpressionName(
  4396. expression,
  4397. name,
  4398. rootInfo,
  4399. members,
  4400. onUnhandled
  4401. ) {
  4402. if (expression.object.type === "MemberExpression") {
  4403. // optimize the case where expression.object is a MemberExpression too.
  4404. // we can keep info here when calling walkMemberExpression directly
  4405. // Read the property from `members` (already extracted by
  4406. // extractMemberExpressionChain) since the AST node may be a
  4407. // TemplateLiteral, which has neither .name nor .value.
  4408. const property = members[members.length - 1];
  4409. name = name.slice(0, -property.length - 1);
  4410. members.pop();
  4411. const result = this.callHooksForInfo(
  4412. this.hooks.expression,
  4413. name,
  4414. expression.object
  4415. );
  4416. if (result === true) return;
  4417. this.walkMemberExpressionWithExpressionName(
  4418. expression.object,
  4419. name,
  4420. rootInfo,
  4421. members,
  4422. onUnhandled
  4423. );
  4424. } else if (!onUnhandled || !onUnhandled()) {
  4425. this.walkExpression(expression.object);
  4426. }
  4427. if (expression.computed === true) this.walkExpression(expression.property);
  4428. }
  4429. /**
  4430. * Walk this expression.
  4431. * @param {ThisExpression} expression this expression
  4432. */
  4433. walkThisExpression(expression) {
  4434. this.callHooksForName(this.hooks.expression, "this", expression);
  4435. }
  4436. /**
  4437. * Processes the provided expression.
  4438. * @param {Identifier} expression identifier
  4439. */
  4440. walkIdentifier(expression) {
  4441. this.callHooksForName(this.hooks.expression, expression.name, expression);
  4442. }
  4443. /**
  4444. * Walk meta property.
  4445. * @param {MetaProperty} metaProperty meta property
  4446. */
  4447. walkMetaProperty(metaProperty) {
  4448. this.hooks.expression.for(getRootName(metaProperty)).call(metaProperty);
  4449. }
  4450. /**
  4451. * Call hooks for expression.
  4452. * @template T
  4453. * @template R
  4454. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
  4455. * @param {Expression | Super} expr expression
  4456. * @param {AsArray<T>} args args for the hook
  4457. * @returns {R | undefined} result of hook
  4458. */
  4459. callHooksForExpression(hookMap, expr, ...args) {
  4460. return this.callHooksForExpressionWithFallback(
  4461. hookMap,
  4462. expr,
  4463. undefined,
  4464. undefined,
  4465. ...args
  4466. );
  4467. }
  4468. /**
  4469. * Call hooks for expression with fallback.
  4470. * @template T
  4471. * @template R
  4472. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
  4473. * @param {Expression | Super} expr expression info
  4474. * @param {((name: string, rootInfo: string | ScopeInfo | VariableInfo, getMembers: () => Members) => R) | undefined} fallback callback when variable in not handled by hooks
  4475. * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined
  4476. * @param {AsArray<T>} args args for the hook
  4477. * @returns {R | undefined} result of hook
  4478. */
  4479. callHooksForExpressionWithFallback(
  4480. hookMap,
  4481. expr,
  4482. fallback,
  4483. defined,
  4484. ...args
  4485. ) {
  4486. const exprName = this.getMemberExpressionInfo(
  4487. expr,
  4488. ALLOWED_MEMBER_TYPES_EXPRESSION
  4489. );
  4490. if (exprName !== undefined) {
  4491. const members = exprName.getMembers();
  4492. return this.callHooksForInfoWithFallback(
  4493. hookMap,
  4494. members.length === 0 ? exprName.rootInfo : exprName.name,
  4495. fallback &&
  4496. ((name) => fallback(name, exprName.rootInfo, exprName.getMembers)),
  4497. defined && (() => defined(exprName.name)),
  4498. ...args
  4499. );
  4500. }
  4501. }
  4502. /**
  4503. * Call hooks for name.
  4504. * @template T
  4505. * @template R
  4506. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
  4507. * @param {string} name key in map
  4508. * @param {AsArray<T>} args args for the hook
  4509. * @returns {R | undefined} result of hook
  4510. */
  4511. callHooksForName(hookMap, name, ...args) {
  4512. return this._callHooksForInfo(
  4513. hookMap,
  4514. this.getVariableInfo(name),
  4515. undefined,
  4516. undefined,
  4517. args
  4518. );
  4519. }
  4520. /**
  4521. * Call hooks for info.
  4522. * @template T
  4523. * @template R
  4524. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks that should be called
  4525. * @param {ExportedVariableInfo} info variable info
  4526. * @param {AsArray<T>} args args for the hook
  4527. * @returns {R | undefined} result of hook
  4528. */
  4529. callHooksForInfo(hookMap, info, ...args) {
  4530. return this._callHooksForInfo(hookMap, info, undefined, undefined, args);
  4531. }
  4532. /**
  4533. * Call hooks for info with fallback.
  4534. * @template T
  4535. * @template R
  4536. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
  4537. * @param {ExportedVariableInfo} info variable info
  4538. * @param {((name: string) => R | undefined) | undefined} fallback callback when variable in not handled by hooks
  4539. * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined
  4540. * @param {AsArray<T>} args args for the hook
  4541. * @returns {R | undefined} result of hook
  4542. */
  4543. callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) {
  4544. return this._callHooksForInfo(hookMap, info, fallback, defined, args);
  4545. }
  4546. /**
  4547. * Shared core for the callHooksFor* helpers. Takes `args` as an already
  4548. * collected array so the public wrappers each allocate it once instead of
  4549. * re-collecting it through several rest-parameter layers (hot per identifier).
  4550. * @template T
  4551. * @template R
  4552. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks that should be called
  4553. * @param {ExportedVariableInfo} info variable info
  4554. * @param {((name: string) => R | undefined) | undefined} fallback callback when variable is not handled by hooks
  4555. * @param {((result?: string) => R | undefined) | undefined} defined callback when variable is defined
  4556. * @param {AsArray<T>} args args for the hook
  4557. * @returns {R | undefined} result of hook
  4558. */
  4559. _callHooksForInfo(hookMap, info, fallback, defined, args) {
  4560. /** @type {string} */
  4561. let name;
  4562. if (typeof info === "string") {
  4563. name = info;
  4564. } else {
  4565. if (!(info instanceof VariableInfo)) {
  4566. if (defined !== undefined) {
  4567. return defined();
  4568. }
  4569. return;
  4570. }
  4571. let tagInfo = info.tagInfo;
  4572. while (tagInfo !== undefined) {
  4573. const hook = hookMap.get(tagInfo.tag);
  4574. if (hook !== undefined) {
  4575. this.currentTagData = tagInfo.data;
  4576. const result = hook.call(...args);
  4577. this.currentTagData = undefined;
  4578. if (result !== undefined) return result;
  4579. }
  4580. tagInfo = tagInfo.next;
  4581. }
  4582. if (!info.isFree() && !info.isTagged()) {
  4583. if (defined !== undefined) {
  4584. return defined();
  4585. }
  4586. return;
  4587. }
  4588. name = /** @type {string} */ (info.name);
  4589. }
  4590. const hook = hookMap.get(name);
  4591. if (hook !== undefined) {
  4592. const result = hook.call(...args);
  4593. if (result !== undefined) return result;
  4594. }
  4595. if (fallback !== undefined) {
  4596. return fallback(name);
  4597. }
  4598. }
  4599. /**
  4600. * Call hooks for name with fallback.
  4601. * @template T
  4602. * @template R
  4603. * @param {HookMap<SyncBailHook<T, R>>} hookMap hooks the should be called
  4604. * @param {string} name key in map
  4605. * @param {((value: string) => R | undefined) | undefined} fallback callback when variable in not handled by hooks
  4606. * @param {(() => R) | undefined} defined callback when variable is defined
  4607. * @param {AsArray<T>} args args for the hook
  4608. * @returns {R | undefined} result of hook
  4609. */
  4610. callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) {
  4611. return this._callHooksForInfo(
  4612. hookMap,
  4613. this.getVariableInfo(name),
  4614. fallback,
  4615. defined,
  4616. args
  4617. );
  4618. }
  4619. /**
  4620. * Processes the provided param.
  4621. * @deprecated
  4622. * @param {(string | Pattern | Property)[]} params scope params
  4623. * @param {() => void} fn inner function
  4624. * @returns {void}
  4625. */
  4626. inScope(params, fn) {
  4627. const oldScope = this.scope;
  4628. this.scope = {
  4629. topLevelScope: oldScope.topLevelScope,
  4630. inTry: false,
  4631. inShorthand: false,
  4632. inTaggedTemplateTag: false,
  4633. isStrict: oldScope.isStrict,
  4634. isAsmJs: oldScope.isAsmJs,
  4635. terminated: undefined,
  4636. definitions: oldScope.definitions.createChild()
  4637. };
  4638. this.undefineVariable("this");
  4639. this.enterPatterns(params, this._defineVariable);
  4640. fn();
  4641. this.scope = oldScope;
  4642. }
  4643. /**
  4644. * Processes the provided has thi.
  4645. * @param {boolean} hasThis true, when this is defined
  4646. * @param {Identifier[]} params scope params
  4647. * @param {() => void} fn inner function
  4648. * @returns {void}
  4649. */
  4650. inClassScope(hasThis, params, fn) {
  4651. const oldScope = this.scope;
  4652. this.scope = {
  4653. topLevelScope: oldScope.topLevelScope,
  4654. inTry: false,
  4655. inShorthand: false,
  4656. inTaggedTemplateTag: false,
  4657. isStrict: oldScope.isStrict,
  4658. isAsmJs: oldScope.isAsmJs,
  4659. terminated: undefined,
  4660. definitions: oldScope.definitions.createChild()
  4661. };
  4662. if (hasThis) {
  4663. this.undefineVariable("this");
  4664. }
  4665. this.enterPatterns(params, this._defineVariable);
  4666. fn();
  4667. this.scope = oldScope;
  4668. }
  4669. /**
  4670. * Processes the provided has thi.
  4671. * @param {boolean} hasThis true, when this is defined
  4672. * @param {(Pattern | string)[]} params scope params
  4673. * @param {() => void} fn inner function
  4674. * @returns {void}
  4675. */
  4676. inFunctionScope(hasThis, params, fn) {
  4677. const oldScope = this.scope;
  4678. this.scope = {
  4679. topLevelScope: oldScope.topLevelScope,
  4680. inTry: false,
  4681. inShorthand: false,
  4682. inTaggedTemplateTag: false,
  4683. isStrict: oldScope.isStrict,
  4684. isAsmJs: oldScope.isAsmJs,
  4685. terminated: undefined,
  4686. definitions: oldScope.definitions.createChild()
  4687. };
  4688. if (hasThis) {
  4689. this.undefineVariable("this");
  4690. }
  4691. this.enterPatterns(params, this._defineVariable);
  4692. fn();
  4693. this.scope = oldScope;
  4694. }
  4695. /**
  4696. * Processes the provided fn.
  4697. * @param {() => void} fn inner function
  4698. * @param {boolean} inExecutedPath executed state
  4699. * @returns {void}
  4700. */
  4701. inBlockScope(fn, inExecutedPath = false) {
  4702. const oldScope = this.scope;
  4703. this.scope = {
  4704. topLevelScope: oldScope.topLevelScope,
  4705. inTry: oldScope.inTry,
  4706. inShorthand: false,
  4707. inTaggedTemplateTag: false,
  4708. isStrict: oldScope.isStrict,
  4709. isAsmJs: oldScope.isAsmJs,
  4710. terminated: oldScope.terminated,
  4711. definitions: oldScope.definitions.createChild()
  4712. };
  4713. fn();
  4714. const terminated = this.scope.terminated;
  4715. if (inExecutedPath && terminated) {
  4716. oldScope.terminated = terminated;
  4717. }
  4718. this.scope = oldScope;
  4719. }
  4720. /**
  4721. * Processes the provided statement.
  4722. * @param {(Directive | Statement | ModuleDeclaration)[]} statements statements
  4723. */
  4724. detectMode(statements) {
  4725. const statement = statements.length >= 1 ? statements[0] : undefined;
  4726. if (
  4727. statement === undefined ||
  4728. statement.type !== "ExpressionStatement" ||
  4729. statement.expression.type !== "Literal"
  4730. ) {
  4731. return;
  4732. }
  4733. const value = /** @type {Literal} */ (statement.expression).value;
  4734. if (value === "use strict") {
  4735. this.scope.isStrict = true;
  4736. } else if (value === "use asm") {
  4737. this.scope.isAsmJs = true;
  4738. }
  4739. }
  4740. /**
  4741. * Processes the provided pattern.
  4742. * @param {(string | Pattern | Property)[]} patterns patterns
  4743. * @param {OnIdentString} onIdent on ident callback
  4744. */
  4745. enterPatterns(patterns, onIdent) {
  4746. for (let i = 0, len = patterns.length; i < len; i++) {
  4747. const pattern = patterns[i];
  4748. if (typeof pattern !== "string") {
  4749. this.enterPattern(pattern, onIdent);
  4750. } else if (pattern) {
  4751. onIdent(pattern);
  4752. }
  4753. }
  4754. }
  4755. /**
  4756. * Processes the provided pattern.
  4757. * @param {Pattern | Property} pattern pattern
  4758. * @param {OnIdent} onIdent on ident callback
  4759. */
  4760. enterPattern(pattern, onIdent) {
  4761. if (!pattern) return;
  4762. // plain identifiers dominate bindings, so match them first
  4763. switch (pattern.type) {
  4764. case "Identifier":
  4765. this.enterIdentifier(pattern, onIdent);
  4766. break;
  4767. case "ObjectPattern":
  4768. this.enterObjectPattern(pattern, onIdent);
  4769. break;
  4770. case "Property":
  4771. if (pattern.shorthand && pattern.value.type === "Identifier") {
  4772. this.scope.inShorthand = pattern.value.name;
  4773. this.enterIdentifier(pattern.value, onIdent);
  4774. this.scope.inShorthand = false;
  4775. } else {
  4776. this.enterPattern(/** @type {Pattern} */ (pattern.value), onIdent);
  4777. }
  4778. break;
  4779. case "ArrayPattern":
  4780. this.enterArrayPattern(pattern, onIdent);
  4781. break;
  4782. case "AssignmentPattern":
  4783. this.enterAssignmentPattern(pattern, onIdent);
  4784. break;
  4785. case "RestElement":
  4786. this.enterRestElement(pattern, onIdent);
  4787. break;
  4788. }
  4789. }
  4790. /**
  4791. * Processes the provided pattern.
  4792. * @param {Identifier} pattern identifier pattern
  4793. * @param {OnIdent} onIdent callback
  4794. */
  4795. enterIdentifier(pattern, onIdent) {
  4796. if (!this.callHooksForName(this.hooks.pattern, pattern.name, pattern)) {
  4797. onIdent(pattern.name, pattern);
  4798. }
  4799. }
  4800. /**
  4801. * Enter object pattern.
  4802. * @param {ObjectPattern} pattern object pattern
  4803. * @param {OnIdent} onIdent callback
  4804. */
  4805. enterObjectPattern(pattern, onIdent) {
  4806. for (
  4807. let propIndex = 0, len = pattern.properties.length;
  4808. propIndex < len;
  4809. propIndex++
  4810. ) {
  4811. const prop = pattern.properties[propIndex];
  4812. this.enterPattern(prop, onIdent);
  4813. }
  4814. }
  4815. /**
  4816. * Enter array pattern.
  4817. * @param {ArrayPattern} pattern object pattern
  4818. * @param {OnIdent} onIdent callback
  4819. */
  4820. enterArrayPattern(pattern, onIdent) {
  4821. for (
  4822. let elementIndex = 0, len = pattern.elements.length;
  4823. elementIndex < len;
  4824. elementIndex++
  4825. ) {
  4826. const element = pattern.elements[elementIndex];
  4827. if (element) {
  4828. this.enterPattern(element, onIdent);
  4829. }
  4830. }
  4831. }
  4832. /**
  4833. * Enter rest element.
  4834. * @param {RestElement} pattern object pattern
  4835. * @param {OnIdent} onIdent callback
  4836. */
  4837. enterRestElement(pattern, onIdent) {
  4838. this.enterPattern(pattern.argument, onIdent);
  4839. }
  4840. /**
  4841. * Enter assignment pattern.
  4842. * @param {AssignmentPattern} pattern object pattern
  4843. * @param {OnIdent} onIdent callback
  4844. */
  4845. enterAssignmentPattern(pattern, onIdent) {
  4846. this.enterPattern(pattern.left, onIdent);
  4847. }
  4848. /**
  4849. * Evaluate expression.
  4850. * @param {Expression | SpreadElement | PrivateIdentifier | Super} expression expression node
  4851. * @returns {BasicEvaluatedExpression} evaluation result
  4852. */
  4853. evaluateExpression(expression) {
  4854. try {
  4855. const hook = this.hooks.evaluate.get(expression.type);
  4856. if (hook !== undefined) {
  4857. const result = hook.call(expression);
  4858. if (result !== undefined && result !== null) {
  4859. result.setExpression(expression);
  4860. return result;
  4861. }
  4862. }
  4863. } catch (err) {
  4864. // eslint-disable-next-line no-console
  4865. console.warn(err);
  4866. // ignore error
  4867. }
  4868. // no setRange: the range is served lazily from the expression on first
  4869. // read, so plain results don't materialize the node's range array at all
  4870. return new BasicEvaluatedExpression().setExpression(expression);
  4871. }
  4872. /**
  4873. * Returns parsed string.
  4874. * @param {Expression} expression expression
  4875. * @returns {string} parsed string
  4876. */
  4877. parseString(expression) {
  4878. switch (expression.type) {
  4879. case "BinaryExpression":
  4880. if (expression.operator === "+") {
  4881. return (
  4882. this.parseString(/** @type {Expression} */ (expression.left)) +
  4883. this.parseString(expression.right)
  4884. );
  4885. }
  4886. break;
  4887. case "Literal":
  4888. return String(expression.value);
  4889. }
  4890. throw new Error(
  4891. `${expression.type} is not supported as parameter for require`
  4892. );
  4893. }
  4894. /** @typedef {{ range?: Range, value: string, code: boolean, conditional: false | CalculatedStringResult[] }} CalculatedStringResult */
  4895. /**
  4896. * Parses calculated string.
  4897. * @param {Expression} expression expression
  4898. * @returns {CalculatedStringResult} result
  4899. */
  4900. parseCalculatedString(expression) {
  4901. switch (expression.type) {
  4902. case "BinaryExpression":
  4903. if (expression.operator === "+") {
  4904. const left = this.parseCalculatedString(
  4905. /** @type {Expression} */
  4906. (expression.left)
  4907. );
  4908. const right = this.parseCalculatedString(expression.right);
  4909. if (left.code) {
  4910. return {
  4911. range: left.range,
  4912. value: left.value,
  4913. code: true,
  4914. conditional: false
  4915. };
  4916. } else if (right.code) {
  4917. return {
  4918. range: [
  4919. /** @type {Range} */
  4920. (left.range)[0],
  4921. right.range
  4922. ? right.range[1]
  4923. : /** @type {Range} */ (left.range)[1]
  4924. ],
  4925. value: left.value + right.value,
  4926. code: true,
  4927. conditional: false
  4928. };
  4929. }
  4930. return {
  4931. range: [
  4932. /** @type {Range} */
  4933. (left.range)[0],
  4934. /** @type {Range} */
  4935. (right.range)[1]
  4936. ],
  4937. value: left.value + right.value,
  4938. code: false,
  4939. conditional: false
  4940. };
  4941. }
  4942. break;
  4943. case "ConditionalExpression": {
  4944. const consequent = this.parseCalculatedString(expression.consequent);
  4945. const alternate = this.parseCalculatedString(expression.alternate);
  4946. /** @type {CalculatedStringResult[]} */
  4947. const items = [];
  4948. if (consequent.conditional) {
  4949. items.push(...consequent.conditional);
  4950. } else if (!consequent.code) {
  4951. items.push(consequent);
  4952. } else {
  4953. break;
  4954. }
  4955. if (alternate.conditional) {
  4956. items.push(...alternate.conditional);
  4957. } else if (!alternate.code) {
  4958. items.push(alternate);
  4959. } else {
  4960. break;
  4961. }
  4962. return {
  4963. range: undefined,
  4964. value: "",
  4965. code: true,
  4966. conditional: items
  4967. };
  4968. }
  4969. case "Literal":
  4970. return {
  4971. range: expression.range,
  4972. value: String(expression.value),
  4973. code: false,
  4974. conditional: false
  4975. };
  4976. }
  4977. return {
  4978. range: undefined,
  4979. value: "",
  4980. code: true,
  4981. conditional: false
  4982. };
  4983. }
  4984. /**
  4985. * Parses the provided source and updates the parser state.
  4986. * @param {string | Buffer | PreparsedAst} source the source to parse
  4987. * @param {ParserState} state the parser state
  4988. * @returns {ParserState} the parser state
  4989. */
  4990. parse(source, state) {
  4991. if (source === null) {
  4992. throw new Error("source must not be null");
  4993. }
  4994. if (Buffer.isBuffer(source)) {
  4995. source = source.toString("utf8");
  4996. // Keep `state.source` as a string so downstream walkers can read
  4997. // the original text without re-decoding the Buffer on every use.
  4998. state.source = source;
  4999. }
  5000. let ast;
  5001. /** @type {Comment[]} */
  5002. let comments;
  5003. if (typeof source === "object") {
  5004. ast = /** @type {Program} */ (source);
  5005. comments = source.comments;
  5006. } else {
  5007. ({ ast, comments } = JavascriptParser._parse(
  5008. source,
  5009. {
  5010. sourceType: this.sourceType,
  5011. // line/column locations are derived from node offsets via
  5012. // getLocation — parsers never need to track them
  5013. locations: false,
  5014. ranges: true,
  5015. comments: true,
  5016. importPhases: this.options.importPhases === true
  5017. },
  5018. this.options.parse
  5019. ));
  5020. }
  5021. const oldScope = this.scope;
  5022. const oldState = this.state;
  5023. const oldComments = this.comments;
  5024. const oldSemicolons = this.semicolons;
  5025. const oldStatementPath = this.statementPath;
  5026. const oldPrevStatement = this.prevStatement;
  5027. const oldStrictInModuleOutput = this._strictInModuleOutput;
  5028. const oldSource = this._source;
  5029. const oldLineStarts = this._lineStarts;
  5030. // a preparsed AST carries no text, but the build passes the module
  5031. // source in the state — offsets still map for it
  5032. this._source =
  5033. typeof source === "string"
  5034. ? source
  5035. : typeof state.source === "string"
  5036. ? state.source
  5037. : undefined;
  5038. this._lineStarts = undefined;
  5039. this.scope = {
  5040. topLevelScope: true,
  5041. inTry: false,
  5042. inShorthand: false,
  5043. inTaggedTemplateTag: false,
  5044. isStrict: false,
  5045. isAsmJs: false,
  5046. terminated: undefined,
  5047. definitions: new StackedMap()
  5048. };
  5049. this.state = state;
  5050. this.comments = comments;
  5051. this.semicolons = undefined;
  5052. // evaluating a defined, untagged identifier can only fall through when
  5053. // every `evaluate.for("Identifier")` tap is the parser's own — plugins
  5054. // tapping or intercepting it disable the callee/rename fast paths
  5055. const identifierEvalHook = this.hooks.evaluate.get("Identifier");
  5056. this._evalIdentOwnTaps =
  5057. identifierEvalHook !== undefined &&
  5058. identifierEvalHook.interceptors.length === 0 &&
  5059. identifierEvalHook.taps.every((tap) => tap.name === CLASS_NAME);
  5060. this.statementPath = [];
  5061. this.prevStatement = undefined;
  5062. // The output is emitted as strict-mode ESM, but this module was parsed as
  5063. // a loose script — acorn skipped the strict early errors that will break
  5064. // the bundle at runtime. Enables the strict-mode diagnostics below.
  5065. this._strictInModuleOutput =
  5066. this.options.strictModeViolations !== false &&
  5067. state.compilation !== undefined &&
  5068. state.compilation.runtimeTemplate.isModule();
  5069. if (this.hooks.program.call(ast, comments) === undefined) {
  5070. this.destructuringAssignmentProperties = new WeakMap();
  5071. this.detectMode(ast.body);
  5072. // a strict program (ESM source, `"use strict"`) keeps its behavior in
  5073. // strict output — drop the flag so the walk pays no per-node checks
  5074. if (this._strictInModuleOutput && this.scope.isStrict) {
  5075. this._strictInModuleOutput = false;
  5076. }
  5077. this.modulePreWalkStatements(ast.body);
  5078. this.prevStatement = undefined;
  5079. this.preWalkStatements(ast.body);
  5080. this.prevStatement = undefined;
  5081. this.blockPreWalkStatements(ast.body);
  5082. this.prevStatement = undefined;
  5083. this.walkStatements(ast.body);
  5084. this.destructuringAssignmentProperties = undefined;
  5085. }
  5086. this.hooks.finish.call(ast, comments);
  5087. this.scope = oldScope;
  5088. this.state = oldState;
  5089. this.comments = oldComments;
  5090. this.semicolons = oldSemicolons;
  5091. this.statementPath = oldStatementPath;
  5092. this.prevStatement = oldPrevStatement;
  5093. this._strictInModuleOutput = oldStrictInModuleOutput;
  5094. // release — these retain the whole source string and its line table
  5095. this._source = oldSource;
  5096. this._lineStarts = oldLineStarts;
  5097. return state;
  5098. }
  5099. /**
  5100. * Returns evaluation result.
  5101. * @param {string} source source code
  5102. * @returns {BasicEvaluatedExpression} evaluation result
  5103. */
  5104. evaluate(source) {
  5105. const importPhases = this.options.importPhases === true;
  5106. const compilation = this.state && this.state.compilation;
  5107. /** @type {Map<string, Program> | undefined} */
  5108. let cache;
  5109. // custom parse functions are not necessarily pure, do not cache for them
  5110. if (compilation !== undefined && typeof this.options.parse !== "function") {
  5111. cache = evaluateAstCaches.get(compilation);
  5112. if (cache === undefined) {
  5113. cache = new Map();
  5114. evaluateAstCaches.set(compilation, cache);
  5115. }
  5116. }
  5117. const cacheKey =
  5118. cache === undefined
  5119. ? undefined
  5120. : `${this.sourceType}|${importPhases}|${source}`;
  5121. let ast =
  5122. cacheKey === undefined
  5123. ? undefined
  5124. : /** @type {Map<string, Program>} */ (cache).get(cacheKey);
  5125. if (ast === undefined) {
  5126. ({ ast } = JavascriptParser._parse(
  5127. `(${source})`,
  5128. {
  5129. sourceType: this.sourceType,
  5130. importPhases
  5131. },
  5132. this.options.parse
  5133. ));
  5134. if (cacheKey !== undefined) {
  5135. const map = /** @type {Map<string, Program>} */ (cache);
  5136. if (map.size >= EVALUATE_AST_CACHE_LIMIT) map.clear();
  5137. map.set(cacheKey, ast);
  5138. }
  5139. }
  5140. if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") {
  5141. throw new Error("evaluate: Source is not a expression");
  5142. }
  5143. return this.evaluateExpression(ast.body[0].expression);
  5144. }
  5145. /**
  5146. * Checks whether this javascript parser is pure.
  5147. * @param {Expression | Declaration | PrivateIdentifier | MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | null | undefined} expr an expression
  5148. * @param {number} commentsStartPos source position from which annotation comments are checked
  5149. * @returns {boolean} true, when the expression is pure
  5150. */
  5151. isPure(expr, commentsStartPos) {
  5152. if (!expr) return true;
  5153. const result = this.hooks.isPure
  5154. .for(expr.type)
  5155. .call(expr, commentsStartPos);
  5156. if (typeof result === "boolean") return result;
  5157. switch (expr.type) {
  5158. case "ClassDeclaration":
  5159. case "ClassExpression": {
  5160. if (expr.body.type !== "ClassBody") return false;
  5161. if (
  5162. expr.superClass &&
  5163. !this.isPure(expr.superClass, /** @type {Range} */ (expr.range)[0])
  5164. ) {
  5165. return false;
  5166. }
  5167. const items = expr.body.body;
  5168. return items.every((item) => {
  5169. if (item.type === "StaticBlock") {
  5170. return false;
  5171. }
  5172. if (
  5173. item.computed &&
  5174. item.key &&
  5175. !this.isPure(
  5176. item.key,
  5177. /** @type {Range} */
  5178. (item.range)[0]
  5179. )
  5180. ) {
  5181. return false;
  5182. }
  5183. if (
  5184. item.static &&
  5185. item.value &&
  5186. !this.isPure(
  5187. item.value,
  5188. item.key
  5189. ? /** @type {Range} */ (item.key.range)[1]
  5190. : /** @type {Range} */ (item.range)[0]
  5191. )
  5192. ) {
  5193. return false;
  5194. }
  5195. if (
  5196. expr.superClass &&
  5197. item.type === "MethodDefinition" &&
  5198. item.kind === "constructor"
  5199. ) {
  5200. return false;
  5201. }
  5202. return true;
  5203. });
  5204. }
  5205. case "TemplateLiteral":
  5206. // Thread `commentsStartPos` through the interpolations so a
  5207. // /*#__PURE__*/ comment that sits inside `${ ... }` (or before
  5208. // the first interpolation) is part of the scanned range when
  5209. // the inner expression's purity is evaluated.
  5210. return expr.expressions.every((e) => {
  5211. const pureFlag = this.isPure(e, commentsStartPos);
  5212. commentsStartPos = /** @type {Range} */ (e.range)[1];
  5213. return pureFlag;
  5214. });
  5215. case "FunctionDeclaration":
  5216. case "FunctionExpression":
  5217. case "ArrowFunctionExpression":
  5218. case "ThisExpression":
  5219. case "Literal":
  5220. case "Identifier":
  5221. case "PrivateIdentifier":
  5222. return true;
  5223. case "VariableDeclaration":
  5224. return expr.declarations.every((decl) =>
  5225. this.isPure(decl.init, /** @type {Range} */ (decl.range)[0])
  5226. );
  5227. case "ArrayExpression":
  5228. return expr.elements.every((element) => {
  5229. if (element === null) return true;
  5230. if (element.type === "SpreadElement") return false;
  5231. const pureFlag = this.isPure(element, commentsStartPos);
  5232. commentsStartPos = /** @type {Range} */ (element.range)[1];
  5233. return pureFlag;
  5234. });
  5235. case "ObjectExpression": {
  5236. return expr.properties.every((property) => {
  5237. if (property.type === "SpreadElement") return false;
  5238. if (
  5239. property.computed &&
  5240. !this.isPure(property.key, commentsStartPos)
  5241. ) {
  5242. return false;
  5243. }
  5244. const pureFlag = this.isPure(
  5245. /** @type {Exclude<Property["value"], AssignmentPattern | ObjectPattern | ArrayPattern | RestElement>} */
  5246. (property.value),
  5247. /** @type {Range} */ (property.key.range)[1]
  5248. );
  5249. commentsStartPos = /** @type {Range} */ (property.range)[1];
  5250. return pureFlag;
  5251. });
  5252. }
  5253. case "ChainExpression":
  5254. return this.isPure(expr.expression, commentsStartPos);
  5255. case "UnaryExpression":
  5256. // Safe unary operators — produce their result without invoking
  5257. // user code on the operand:
  5258. // - `typeof` returns a type tag and never throws, even for
  5259. // undeclared identifiers; no coercion.
  5260. // - `void` evaluates the operand and discards it, returning
  5261. // `undefined`; pure iff the operand is pure.
  5262. // - `!` coerces via ToBoolean, which is defined to not call
  5263. // any user code (objects → true, etc.).
  5264. // Other operators (`+`, `-`, `~`, `delete`) fall through to
  5265. // the generic evaluator which can still recognize literal
  5266. // cases (e.g. `-1`, `+5`).
  5267. if (
  5268. expr.operator === "typeof" ||
  5269. expr.operator === "void" ||
  5270. expr.operator === "!"
  5271. ) {
  5272. return this.isPure(expr.argument, commentsStartPos);
  5273. }
  5274. break;
  5275. case "MetaProperty":
  5276. return true;
  5277. case "BinaryExpression":
  5278. // Strict (in)equality compares without coercion and never invokes
  5279. // user code on its operands, so the result is pure iff both sides
  5280. // are pure. All other binary operators may invoke `valueOf` /
  5281. // `toString` / `[Symbol.hasInstance]` / Proxy traps and fall through
  5282. // to the generic evaluator, which can still recognize the cases
  5283. // where both sides evaluate to known primitive literals.
  5284. if (expr.operator === "===" || expr.operator === "!==") {
  5285. return (
  5286. this.isPure(expr.left, commentsStartPos) &&
  5287. this.isPure(expr.right, /** @type {Range} */ (expr.left.range)[1])
  5288. );
  5289. }
  5290. break;
  5291. case "ConditionalExpression":
  5292. return (
  5293. this.isPure(expr.test, commentsStartPos) &&
  5294. this.isPure(
  5295. expr.consequent,
  5296. /** @type {Range} */ (expr.test.range)[1]
  5297. ) &&
  5298. this.isPure(
  5299. expr.alternate,
  5300. /** @type {Range} */ (expr.consequent.range)[1]
  5301. )
  5302. );
  5303. case "LogicalExpression":
  5304. return (
  5305. this.isPure(expr.left, commentsStartPos) &&
  5306. this.isPure(expr.right, /** @type {Range} */ (expr.left.range)[1])
  5307. );
  5308. case "SequenceExpression":
  5309. return expr.expressions.every((expr) => {
  5310. const pureFlag = this.isPure(expr, commentsStartPos);
  5311. commentsStartPos = /** @type {Range} */ (expr.range)[1];
  5312. return pureFlag;
  5313. });
  5314. case "CallExpression": {
  5315. const pureFlag =
  5316. /** @type {Range} */ (expr.range)[0] - commentsStartPos > 12 &&
  5317. this.getComments([
  5318. commentsStartPos,
  5319. /** @type {Range} */ (expr.range)[0]
  5320. ]).some(
  5321. (comment) =>
  5322. comment.type === "Block" &&
  5323. CompilerHintNotationRegExp.Pure.test(comment.value)
  5324. );
  5325. if (!pureFlag) return false;
  5326. commentsStartPos = /** @type {Range} */ (expr.callee.range)[1];
  5327. return expr.arguments.every((arg) => {
  5328. if (arg.type === "SpreadElement") return false;
  5329. const pureFlag = this.isPure(arg, commentsStartPos);
  5330. commentsStartPos = /** @type {Range} */ (arg.range)[1];
  5331. return pureFlag;
  5332. });
  5333. }
  5334. case "NewExpression": {
  5335. const pureFlag =
  5336. /** @type {Range} */ (expr.range)[0] - commentsStartPos > 12 &&
  5337. this.getComments([
  5338. commentsStartPos,
  5339. /** @type {Range} */ (expr.range)[0]
  5340. ]).some(
  5341. (comment) =>
  5342. comment.type === "Block" &&
  5343. CompilerHintNotationRegExp.Pure.test(comment.value)
  5344. );
  5345. if (!pureFlag) return false;
  5346. commentsStartPos = /** @type {Range} */ (expr.callee.range)[1];
  5347. return expr.arguments.every((arg) => {
  5348. if (arg.type === "SpreadElement") return false;
  5349. const pureFlag = this.isPure(arg, commentsStartPos);
  5350. commentsStartPos = /** @type {Range} */ (arg.range)[1];
  5351. return pureFlag;
  5352. });
  5353. }
  5354. case "TaggedTemplateExpression": {
  5355. const pureFlag =
  5356. /** @type {Range} */ (expr.range)[0] - commentsStartPos > 12 &&
  5357. this.getComments([
  5358. commentsStartPos,
  5359. /** @type {Range} */ (expr.range)[0]
  5360. ]).some(
  5361. (comment) =>
  5362. comment.type === "Block" &&
  5363. CompilerHintNotationRegExp.Pure.test(comment.value)
  5364. );
  5365. if (!pureFlag) return false;
  5366. commentsStartPos = /** @type {Range} */ (expr.tag.range)[1];
  5367. return expr.quasi.expressions.every((e) => {
  5368. const pureFlag = this.isPure(e, commentsStartPos);
  5369. commentsStartPos = /** @type {Range} */ (e.range)[1];
  5370. return pureFlag;
  5371. });
  5372. }
  5373. }
  5374. const evaluated = this.evaluateExpression(expr);
  5375. return !evaluated.couldHaveSideEffects();
  5376. }
  5377. /**
  5378. * Returns the location of a node or comment, computed from its offsets so
  5379. * ASTs from parsers without location support work too. Falls back to the
  5380. * node's own `loc` only when no source text is available (preparsed ASTs).
  5381. * Offsets can only be mapped while parsing — callbacks deferred past the
  5382. * `parse()` call must take the location upfront.
  5383. * @param {{ start?: number, end?: number, range?: Range, loc?: SourceLocation | null }} node node or comment
  5384. * @returns {DependencyLocation} location of the node
  5385. */
  5386. getLocation(node) {
  5387. const source = this._source;
  5388. if (source !== undefined) {
  5389. const start =
  5390. typeof node.start === "number"
  5391. ? node.start
  5392. : node.range
  5393. ? node.range[0]
  5394. : undefined;
  5395. if (start !== undefined) {
  5396. const end =
  5397. typeof node.end === "number"
  5398. ? node.end
  5399. : node.range
  5400. ? node.range[1]
  5401. : start;
  5402. const lineStarts =
  5403. this._lineStarts || (this._lineStarts = buildLineStarts(source));
  5404. return {
  5405. start: positionAt(lineStarts, start),
  5406. end: positionAt(lineStarts, end)
  5407. };
  5408. }
  5409. }
  5410. return /** @type {DependencyLocation} */ (node.loc);
  5411. }
  5412. /**
  5413. * Returns comments in the range.
  5414. * @param {Range} range range
  5415. * @returns {Comment[]} comments in the range
  5416. */
  5417. getComments(range) {
  5418. return getCommentsInRange(
  5419. /** @type {(Comment & { range: [number, number] })[]} */ (this.comments),
  5420. range
  5421. );
  5422. }
  5423. /**
  5424. * Reports whether `identifier` may occur as a word in the source text of
  5425. * `range`. A conservative pre-filter for expensive AST scans: `false` means
  5426. * it certainly does not occur, while a match inside a comment or a string
  5427. * yields `true`. Also `true` when no source text is available (preparsed
  5428. * AST), so callers must stay correct without the filter.
  5429. * @param {Range} range range to search
  5430. * @param {string} identifier identifier to look for
  5431. * @returns {boolean} false when the identifier certainly does not occur
  5432. */
  5433. sourceMayContainIdentifier(range, identifier) {
  5434. const source = this._source;
  5435. if (source === undefined) return true;
  5436. const end = range[1];
  5437. const length = identifier.length;
  5438. for (
  5439. let index = source.indexOf(identifier, range[0]);
  5440. index !== -1 && index + length <= end;
  5441. index = source.indexOf(identifier, index + length)
  5442. ) {
  5443. if (
  5444. (index === 0 || !isIdentifierChar(source.charCodeAt(index - 1))) &&
  5445. (index + length === source.length ||
  5446. !isIdentifierChar(source.charCodeAt(index + length)))
  5447. ) {
  5448. return true;
  5449. }
  5450. }
  5451. return false;
  5452. }
  5453. /**
  5454. * First significant char code at or after `pos`, skipping whitespace,
  5455. * comments and grouping `)` (a parenthesized node's range excludes its
  5456. * wrapping parens, so a `,`/`;` separator can sit behind them), or -1 at
  5457. * end of source.
  5458. * @param {string} source source text
  5459. * @param {number} pos start offset
  5460. * @returns {number} char code of the next token, or -1
  5461. */
  5462. _nextTokenCharCode(source, pos) {
  5463. const len = source.length;
  5464. for (let i = pos; i < len; i++) {
  5465. const c = source.charCodeAt(i);
  5466. // whitespace and line terminators acorn skips between tokens
  5467. if (
  5468. c === 32 ||
  5469. c === 9 ||
  5470. c === 10 ||
  5471. c === 13 ||
  5472. c === 11 ||
  5473. c === 12 ||
  5474. c === 41 /* ) */ ||
  5475. c === 0xa0 ||
  5476. c === 0xfeff ||
  5477. c === 0x2028 ||
  5478. c === 0x2029
  5479. ) {
  5480. continue;
  5481. }
  5482. if (c === 47 /* / */) {
  5483. const n = source.charCodeAt(i + 1);
  5484. if (n === 47 /* / */) {
  5485. i += 2;
  5486. while (i < len) {
  5487. const cc = source.charCodeAt(i);
  5488. if (cc === 10 || cc === 13 || cc === 0x2028 || cc === 0x2029) break;
  5489. i++;
  5490. }
  5491. continue;
  5492. }
  5493. if (n === 42 /* * */) {
  5494. i += 2;
  5495. while (
  5496. i < len &&
  5497. !(source.charCodeAt(i) === 42 && source.charCodeAt(i + 1) === 47)
  5498. ) {
  5499. i++;
  5500. }
  5501. i++;
  5502. continue;
  5503. }
  5504. }
  5505. return c;
  5506. }
  5507. return -1;
  5508. }
  5509. /**
  5510. * Whether a statement ending at `pos` relies on ASI (no real separator).
  5511. * Derived from the source text unless overridden by set/unsetAsiPosition.
  5512. * A statement terminated by a real `;` or continued by a `,` (a sequence
  5513. * element) is not an ASI position; anything else (newline, `}`, eof) is.
  5514. * @param {number} pos statement end offset
  5515. * @returns {boolean} true when ASI inserts a semicolon at this position
  5516. */
  5517. _isAsiPosition(pos) {
  5518. if (this.semicolons !== undefined) {
  5519. const override = this.semicolons.get(pos);
  5520. if (override !== undefined) return override;
  5521. }
  5522. const source = this._source;
  5523. if (source === undefined) return true;
  5524. // a real semicolon is the statement's last char (exclusive end at pos)
  5525. if (source.charCodeAt(pos - 1) === 59 /* ; */) return false;
  5526. const next = this._nextTokenCharCode(source, pos);
  5527. return next !== 44 /* , */ && next !== 59; /* ; */
  5528. }
  5529. /**
  5530. * Checks whether this javascript parser is asi position.
  5531. * @param {number} pos source code position
  5532. * @returns {boolean} true when a semicolon has been inserted before this position, false if not
  5533. */
  5534. isAsiPosition(pos) {
  5535. const currentStatement =
  5536. /** @type {StatementPath} */
  5537. (this.statementPath)[
  5538. /** @type {StatementPath} */
  5539. (this.statementPath).length - 1
  5540. ];
  5541. if (currentStatement === undefined) throw new Error("Not in statement");
  5542. const range = /** @type {Range} */ (currentStatement.range);
  5543. return (
  5544. // Either asking directly for the end position of the current statement
  5545. (range[1] === pos && this._isAsiPosition(pos)) ||
  5546. // Or asking for the start position of the current statement,
  5547. // here we have to check multiple things
  5548. (range[0] === pos &&
  5549. // is there a previous statement which might be relevant?
  5550. this.prevStatement !== undefined &&
  5551. // is the end position of the previous statement an ASI position?
  5552. this._isAsiPosition(/** @type {Range} */ (this.prevStatement.range)[1]))
  5553. );
  5554. }
  5555. /**
  5556. * Updates asi position using the provided po.
  5557. * @param {number} pos source code position
  5558. * @returns {void}
  5559. */
  5560. setAsiPosition(pos) {
  5561. (this.semicolons || (this.semicolons = new Map())).set(pos, true);
  5562. }
  5563. /**
  5564. * Unset asi position.
  5565. * @param {number} pos source code position
  5566. * @returns {void}
  5567. */
  5568. unsetAsiPosition(pos) {
  5569. (this.semicolons || (this.semicolons = new Map())).set(pos, false);
  5570. }
  5571. /**
  5572. * Checks whether this javascript parser is statement level expression.
  5573. * @param {Expression} expr expression
  5574. * @returns {boolean} true, when the expression is a statement level expression
  5575. */
  5576. isStatementLevelExpression(expr) {
  5577. const currentStatement =
  5578. /** @type {StatementPath} */
  5579. (this.statementPath)[
  5580. /** @type {StatementPath} */
  5581. (this.statementPath).length - 1
  5582. ];
  5583. return (
  5584. expr === currentStatement ||
  5585. (currentStatement.type === "ExpressionStatement" &&
  5586. currentStatement.expression === expr)
  5587. );
  5588. }
  5589. /**
  5590. * Returns tag data.
  5591. * @param {string} name name
  5592. * @param {Tag} tag tag info
  5593. * @returns {TagData | undefined} tag data
  5594. */
  5595. getTagData(name, tag) {
  5596. const info = this.scope.definitions.get(name);
  5597. if (info instanceof VariableInfo) {
  5598. let tagInfo = info.tagInfo;
  5599. while (tagInfo !== undefined) {
  5600. if (tagInfo.tag === tag) return tagInfo.data;
  5601. tagInfo = tagInfo.next;
  5602. }
  5603. }
  5604. }
  5605. /**
  5606. * Processes the provided name.
  5607. * @param {string} name name
  5608. * @param {Tag} tag tag info
  5609. * @param {TagData=} data data
  5610. * @param {VariableInfoFlagsType=} flags flags
  5611. */
  5612. tagVariable(name, tag, data, flags = VariableInfoFlags.Tagged) {
  5613. const oldInfo = this.scope.definitions.get(name);
  5614. /** @type {VariableInfo} */
  5615. let newInfo;
  5616. if (oldInfo === undefined) {
  5617. newInfo = new VariableInfo(this.scope, name, flags, {
  5618. tag,
  5619. data,
  5620. next: undefined
  5621. });
  5622. } else if (oldInfo instanceof VariableInfo) {
  5623. newInfo = new VariableInfo(
  5624. oldInfo.declaredScope,
  5625. oldInfo.name,
  5626. /** @type {VariableInfoFlagsType} */ (oldInfo.flags | flags),
  5627. {
  5628. tag,
  5629. data,
  5630. next: oldInfo.tagInfo
  5631. }
  5632. );
  5633. } else {
  5634. newInfo = new VariableInfo(oldInfo, name, flags, {
  5635. tag,
  5636. data,
  5637. next: undefined
  5638. });
  5639. }
  5640. this.scope.definitions.set(name, newInfo);
  5641. }
  5642. /**
  5643. * Processes the provided name.
  5644. * @param {string} name variable name
  5645. */
  5646. defineVariable(name) {
  5647. const oldInfo = this.scope.definitions.get(name);
  5648. // Don't redefine variable in same scope to keep existing tags
  5649. if (
  5650. oldInfo instanceof VariableInfo &&
  5651. oldInfo.declaredScope === this.scope
  5652. ) {
  5653. return;
  5654. }
  5655. this.scope.definitions.set(name, this.scope);
  5656. }
  5657. /**
  5658. * Processes the provided name.
  5659. * @param {string} name variable name
  5660. */
  5661. undefineVariable(name) {
  5662. this.scope.definitions.delete(name);
  5663. }
  5664. /**
  5665. * Checks whether this javascript parser is variable defined.
  5666. * @param {string} name variable name
  5667. * @returns {boolean} true, when variable is defined
  5668. */
  5669. isVariableDefined(name) {
  5670. const info = this.scope.definitions.get(name);
  5671. if (info === undefined) return false;
  5672. if (info instanceof VariableInfo) {
  5673. return !info.isFree();
  5674. }
  5675. return true;
  5676. }
  5677. /**
  5678. * Whether evaluating an identifier of this name can only fall through:
  5679. * the exact negative of the identifier evaluator's `getInfo` — defined in
  5680. * some scope and neither free nor tagged nor carrying tag info.
  5681. * @param {string} name variable name
  5682. * @returns {boolean} true when the identifier evaluates to nothing
  5683. */
  5684. _isDefinedPlainVariable(name) {
  5685. const info = this.scope.definitions.get(name);
  5686. if (info === undefined) return false;
  5687. if (info instanceof VariableInfo) {
  5688. return !(info.isFree() || info.isTagged() || info.tagInfo !== undefined);
  5689. }
  5690. return true;
  5691. }
  5692. /**
  5693. * Gets variable info.
  5694. * @param {string} name variable name
  5695. * @returns {ExportedVariableInfo} info for this variable
  5696. */
  5697. getVariableInfo(name) {
  5698. const value = this.scope.definitions.get(name);
  5699. if (value === undefined) {
  5700. return name;
  5701. }
  5702. return value;
  5703. }
  5704. /**
  5705. * Updates variable using the provided name.
  5706. * @param {string} name variable name
  5707. * @param {ExportedVariableInfo} variableInfo new info for this variable
  5708. * @returns {void}
  5709. */
  5710. setVariable(name, variableInfo) {
  5711. if (typeof variableInfo === "string") {
  5712. if (variableInfo === name) {
  5713. this.scope.definitions.delete(name);
  5714. } else {
  5715. this.scope.definitions.set(
  5716. name,
  5717. new VariableInfo(
  5718. this.scope,
  5719. variableInfo,
  5720. VariableInfoFlags.Free,
  5721. undefined
  5722. )
  5723. );
  5724. }
  5725. } else {
  5726. this.scope.definitions.set(name, variableInfo);
  5727. }
  5728. }
  5729. /**
  5730. * Evaluated variable.
  5731. * @param {TagInfo} tagInfo tag info
  5732. * @returns {VariableInfo} variable info
  5733. */
  5734. evaluatedVariable(tagInfo) {
  5735. return new VariableInfo(
  5736. this.scope,
  5737. undefined,
  5738. VariableInfoFlags.Evaluated,
  5739. tagInfo
  5740. );
  5741. }
  5742. /**
  5743. * Parses comment options.
  5744. * @param {Range} range range of the comment
  5745. * @returns {{ options: Record<string, EXPECTED_ANY> | null, errors: (Error & { comment: Comment })[] | null }} result
  5746. */
  5747. parseCommentOptions(range) {
  5748. return parseCommentOptionsInRange(
  5749. /** @type {(Comment & { range: [number, number], value: string })[]} */ (
  5750. this.comments
  5751. ),
  5752. range,
  5753. this.magicCommentContext
  5754. );
  5755. }
  5756. /**
  5757. * Finds the root object of a member expression chain without allocating the
  5758. * member arrays. The traversal/break logic must stay in sync with
  5759. * `extractMemberExpressionChain`; it lets `getMemberExpressionInfo` reject
  5760. * unrecognized roots (~77% of calls) before paying for the arrays.
  5761. * @param {Expression | Super} expression a member expression
  5762. * @returns {Expression | Super} the root object of the chain
  5763. */
  5764. getMemberExpressionRoot(expression) {
  5765. /** @type {Node} */
  5766. let expr = expression;
  5767. while (expr.type === "MemberExpression") {
  5768. if (expr.computed) {
  5769. const prop = expr.property;
  5770. if (
  5771. prop.type !== "Literal" &&
  5772. !(
  5773. prop.type === "TemplateLiteral" &&
  5774. prop.expressions.length === 0 &&
  5775. typeof prop.quasis[0].value.cooked === "string"
  5776. )
  5777. ) {
  5778. break;
  5779. }
  5780. } else if (expr.property.type !== "Identifier") {
  5781. break;
  5782. }
  5783. expr = expr.object;
  5784. }
  5785. return /** @type {Expression | Super} */ (expr);
  5786. }
  5787. /**
  5788. * Extract member expression chain.
  5789. * @param {Expression | Super} expression a member expression
  5790. * @returns {{ members: Members, object: Expression | Super, membersOptionals: MembersOptionals, memberRanges: MemberRanges }} member names (reverse order) and remaining object
  5791. */
  5792. extractMemberExpressionChain(expression) {
  5793. /** @type {Node} */
  5794. let expr = expression;
  5795. /** @type {Members} */
  5796. const members = [];
  5797. /** @type {MembersOptionals} */
  5798. const membersOptionals = [];
  5799. /** @type {MemberRanges} */
  5800. const memberRanges = [];
  5801. while (expr.type === "MemberExpression") {
  5802. if (expr.computed) {
  5803. const prop = expr.property;
  5804. if (prop.type === "Literal") {
  5805. members.push(`${prop.value}`); // the literal
  5806. } else if (
  5807. prop.type === "TemplateLiteral" &&
  5808. prop.expressions.length === 0 &&
  5809. typeof prop.quasis[0].value.cooked === "string"
  5810. ) {
  5811. // `[`url`]` is statically a string just like `["url"]`
  5812. members.push(prop.quasis[0].value.cooked);
  5813. } else {
  5814. break;
  5815. }
  5816. memberRanges.push(/** @type {Range} */ (expr.object.range)); // the range of the expression fragment before the property
  5817. } else {
  5818. if (expr.property.type !== "Identifier") break;
  5819. members.push(expr.property.name); // the identifier
  5820. memberRanges.push(/** @type {Range} */ (expr.object.range)); // the range of the expression fragment before the identifier
  5821. }
  5822. membersOptionals.push(expr.optional);
  5823. expr = expr.object;
  5824. }
  5825. return {
  5826. members,
  5827. membersOptionals,
  5828. memberRanges,
  5829. object: expr
  5830. };
  5831. }
  5832. /**
  5833. * Gets free info from variable.
  5834. * @param {string} varName variable name
  5835. * @returns {{ name: string, info: VariableInfo | string } | undefined} name of the free variable and variable info for that
  5836. */
  5837. getFreeInfoFromVariable(varName) {
  5838. const info = this.getVariableInfo(varName);
  5839. /** @type {string} */
  5840. let name;
  5841. if (info instanceof VariableInfo && info.name) {
  5842. if (!info.isFree()) return;
  5843. name = info.name;
  5844. } else if (typeof info !== "string") {
  5845. return;
  5846. } else {
  5847. name = info;
  5848. }
  5849. return { info, name };
  5850. }
  5851. /**
  5852. * Gets name info from variable.
  5853. * @param {string} varName variable name
  5854. * @returns {{ name: string, info: VariableInfo | string } | undefined} name of the free variable and variable info for that
  5855. */
  5856. getNameInfoFromVariable(varName) {
  5857. const info = this.getVariableInfo(varName);
  5858. /** @type {string} */
  5859. let name;
  5860. if (info instanceof VariableInfo && info.name) {
  5861. if (!info.isFree() && !info.isTagged()) return;
  5862. name = info.name;
  5863. } else if (typeof info !== "string") {
  5864. return;
  5865. } else {
  5866. name = info;
  5867. }
  5868. return { info, name };
  5869. }
  5870. /** @typedef {{ type: "call", call: CallExpression, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => CalleeMembers, name: string, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges }} CallExpressionInfo */
  5871. /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => Members, getMembersOptionals: () => MembersOptionals, getMemberRanges: () => MemberRanges }} ExpressionExpressionInfo */
  5872. /**
  5873. * Gets member expression info.
  5874. * @param {Expression | Super} expression a member expression
  5875. * @param {number} allowedTypes which types should be returned, presented in bit mask
  5876. * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info
  5877. */
  5878. getMemberExpressionInfo(expression, allowedTypes) {
  5879. // Resolve the root first (no allocation); most calls reject here and so
  5880. // never build the member arrays via extractMemberExpressionChain.
  5881. const object = this.getMemberExpressionRoot(expression);
  5882. switch (object.type) {
  5883. case "CallExpression": {
  5884. if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) return;
  5885. const calleeExpr = object.callee;
  5886. const callee =
  5887. calleeExpr.type === "MemberExpression"
  5888. ? this.getMemberExpressionRoot(calleeExpr)
  5889. : calleeExpr;
  5890. const rootName = getRootName(callee);
  5891. if (!rootName) return;
  5892. const result = this.getNameInfoFromVariable(rootName);
  5893. if (!result) return;
  5894. const { info: rootInfo, name: resolvedRoot } = result;
  5895. const rootMembers =
  5896. calleeExpr.type === "MemberExpression"
  5897. ? this.extractMemberExpressionChain(calleeExpr).members
  5898. : EMPTY_ARRAY;
  5899. const { members, membersOptionals, memberRanges } =
  5900. this.extractMemberExpressionChain(expression);
  5901. const calleeName = objectAndMembersToName(resolvedRoot, rootMembers);
  5902. return {
  5903. type: "call",
  5904. call: object,
  5905. calleeName,
  5906. rootInfo,
  5907. getCalleeMembers: lazyReverse(rootMembers),
  5908. name: objectAndMembersToName(`${calleeName}()`, members),
  5909. getMembers: lazyReverse(members),
  5910. getMembersOptionals: lazyReverse(membersOptionals),
  5911. getMemberRanges: lazyReverse(memberRanges)
  5912. };
  5913. }
  5914. case "Identifier":
  5915. case "MetaProperty":
  5916. case "ThisExpression": {
  5917. if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0) return;
  5918. const rootName = getRootName(object);
  5919. if (!rootName) return;
  5920. const result = this.getNameInfoFromVariable(rootName);
  5921. if (!result) return;
  5922. const { info: rootInfo, name: resolvedRoot } = result;
  5923. const { members, membersOptionals, memberRanges } =
  5924. this.extractMemberExpressionChain(expression);
  5925. return {
  5926. type: "expression",
  5927. name: objectAndMembersToName(resolvedRoot, members),
  5928. rootInfo,
  5929. getMembers: lazyReverse(members),
  5930. getMembersOptionals: lazyReverse(membersOptionals),
  5931. getMemberRanges: lazyReverse(memberRanges)
  5932. };
  5933. }
  5934. }
  5935. }
  5936. /**
  5937. * Gets name for expression.
  5938. * @param {Expression} expression an expression
  5939. * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => Members } | undefined} name info
  5940. */
  5941. getNameForExpression(expression) {
  5942. return this.getMemberExpressionInfo(
  5943. expression,
  5944. ALLOWED_MEMBER_TYPES_EXPRESSION
  5945. );
  5946. }
  5947. /**
  5948. * Get module parse function.
  5949. * @param {Compilation} compilation compilation
  5950. * @param {Module} module module
  5951. * @returns {ParseFunction | undefined} parser
  5952. */
  5953. static _getModuleParseFunction(compilation, module) {
  5954. // Get from module if available
  5955. if (
  5956. module instanceof NormalModule &&
  5957. module.parser instanceof JavascriptParser
  5958. ) {
  5959. return module.parser.options.parse;
  5960. }
  5961. // Fallback to the global javascript parse function
  5962. if (typeof compilation.options.module.parser.javascript !== "undefined") {
  5963. return compilation.options.module.parser.javascript.parse;
  5964. }
  5965. }
  5966. /**
  5967. * Returns parse result.
  5968. * @param {string} code source code
  5969. * @param {InternalParseOptions} options parsing options
  5970. * @param {ParseFunction=} customParse custom function to parse
  5971. * @returns {ParseResult} parse result
  5972. */
  5973. static _parse(code, options, customParse) {
  5974. const type = options ? options.sourceType : "module";
  5975. /** @type {ParseOptions} */
  5976. let parserOptions;
  5977. if (typeof customParse === "function") {
  5978. // a user parse function may retain the options object — keep it fresh
  5979. parserOptions = {
  5980. ...defaultParserOptions,
  5981. allowReturnOutsideFunction: type === "script",
  5982. ...options,
  5983. sourceType: type === "auto" ? "module" : type
  5984. };
  5985. } else {
  5986. // reuse one options object across parses (parsing is synchronous) to
  5987. // skip re-materializing it per module; acorn copies it via getOptions.
  5988. // Every non-default key a caller may pass must be reset here.
  5989. parserOptions = REUSED_PARSER_OPTIONS;
  5990. parserOptions.importPhases = false;
  5991. Object.assign(parserOptions, defaultParserOptions);
  5992. parserOptions.allowReturnOutsideFunction = type === "script";
  5993. if (options) Object.assign(parserOptions, options);
  5994. parserOptions.sourceType = type === "auto" ? "module" : type;
  5995. // let WebpackParser downgrade module->script in place on script-only
  5996. // syntax so `auto` avoids a second full parse in the common case
  5997. parserOptions.moduleFallback = type === "auto";
  5998. }
  5999. const wantRanges = parserOptions.ranges === true;
  6000. /**
  6001. * Returns parse result.
  6002. * @param {string} code source code
  6003. * @param {ParseOptions} options parsing options
  6004. * @returns {ParseResult} parse result
  6005. */
  6006. const internalParse = (code, options) => {
  6007. if (typeof customParse === "function") {
  6008. return customParse(code, options);
  6009. }
  6010. /** @type {Comment[]} */
  6011. const comments = [];
  6012. // Whenever ranges are wanted (the main parse path and the concatenation
  6013. // re-parse), have the parser plugin serve `range` on demand instead of
  6014. // eagerly. `wantRanges` is hoisted since the auto-fallback re-enters
  6015. // with the same (mutated) options object.
  6016. options.lazyNodes = wantRanges;
  6017. if (wantRanges) {
  6018. // the lazy plugin replaces acorn's native tracking — disabling it
  6019. // here lets WebpackParser skip its defensive options copy
  6020. options.locations = false;
  6021. options.ranges = false;
  6022. }
  6023. if (options.comments) {
  6024. if (wantRanges) {
  6025. // the parser plugin collects the comments itself, deferring the
  6026. // text slice until some hook actually reads `value`
  6027. options.lazyComments = comments;
  6028. } else {
  6029. /** @type {AcornOptions} */
  6030. (options).onComment =
  6031. /** @type {import("acorn").Comment[]} */
  6032. (/** @type {unknown} */ (comments));
  6033. }
  6034. }
  6035. const ast =
  6036. /** @type {Program} */
  6037. (parser.parse(code, /** @type {AcornOptions} */ (options)));
  6038. return { ast, comments };
  6039. };
  6040. /** @type {Program | undefined} */
  6041. let ast;
  6042. /** @type {Comment[] | undefined} */
  6043. let comments;
  6044. let error;
  6045. let threw = false;
  6046. try {
  6047. ({ ast, comments } = internalParse(code, parserOptions));
  6048. } catch (err) {
  6049. error = err;
  6050. threw = true;
  6051. }
  6052. if (threw && type === "auto") {
  6053. parserOptions.sourceType = "script";
  6054. parserOptions.allowReturnOutsideFunction = true;
  6055. // the retry is already a full script parse — no in-place downgrade
  6056. parserOptions.moduleFallback = false;
  6057. try {
  6058. ({ ast, comments } = internalParse(code, parserOptions));
  6059. threw = false;
  6060. } catch (_err) {
  6061. // we use the error from first parse try
  6062. // so nothing to do here
  6063. }
  6064. }
  6065. // release per-parse state retained on the (possibly reused) options
  6066. // object — the comments array retains source text slices
  6067. parserOptions.lazyComments = undefined;
  6068. /** @type {AcornOptions} */
  6069. (parserOptions).onComment = undefined;
  6070. if (threw) {
  6071. throw error;
  6072. }
  6073. return /** @type {ParseResult} */ ({ ast, comments });
  6074. }
  6075. /**
  6076. * Returns parser.
  6077. * @param {((BaseParser: AcornParser) => AcornParser)[]} plugins parser plugin
  6078. * @returns {typeof JavascriptParser} parser
  6079. */
  6080. static extend(...plugins) {
  6081. parser = parser.extend(...plugins);
  6082. return JavascriptParser;
  6083. }
  6084. }
  6085. JavascriptParser.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL;
  6086. JavascriptParser.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION =
  6087. ALLOWED_MEMBER_TYPES_CALL_EXPRESSION;
  6088. JavascriptParser.ALLOWED_MEMBER_TYPES_EXPRESSION =
  6089. ALLOWED_MEMBER_TYPES_EXPRESSION;
  6090. JavascriptParser.VariableInfo = VariableInfo;
  6091. JavascriptParser.VariableInfoFlags = VariableInfoFlags;
  6092. JavascriptParser.getImportAttributes = getImportAttributes;
  6093. module.exports = JavascriptParser;