JavascriptParser.js 142 KB

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