JavascriptParser.js 161 KB

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