JavascriptParser.js 113 KB

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