JavascriptParser.js 148 KB

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