JavascriptParser.js 162 KB

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