JavascriptParser.js 167 KB

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