JavascriptParser.js 141 KB

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