JavascriptParser.js 151 KB

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