JavascriptParser.js 152 KB

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