JavascriptParser.js 152 KB

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