JavascriptParser.js 133 KB

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