index.js 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828
  1. /*! @author Toru Nagashima <https://github.com/mysticatea> */
  2. 'use strict';
  3. Object.defineProperty(exports, '__esModule', { value: true });
  4. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  5. var evk = _interopDefault(require('eslint-visitor-keys'));
  6. /**
  7. * Get the innermost scope which contains a given location.
  8. * @param {Scope} initialScope The initial scope to search.
  9. * @param {Node} node The location to search.
  10. * @returns {Scope} The innermost scope.
  11. */
  12. function getInnermostScope(initialScope, node) {
  13. const location = node.range[0];
  14. let scope = initialScope;
  15. let found = false;
  16. do {
  17. found = false;
  18. for (const childScope of scope.childScopes) {
  19. const range = childScope.block.range;
  20. if (range[0] <= location && location < range[1]) {
  21. scope = childScope;
  22. found = true;
  23. break
  24. }
  25. }
  26. } while (found)
  27. return scope
  28. }
  29. /**
  30. * Find the variable of a given name.
  31. * @param {Scope} initialScope The scope to start finding.
  32. * @param {string|Node} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
  33. * @returns {Variable|null} The found variable or null.
  34. */
  35. function findVariable(initialScope, nameOrNode) {
  36. let name = "";
  37. let scope = initialScope;
  38. if (typeof nameOrNode === "string") {
  39. name = nameOrNode;
  40. } else {
  41. name = nameOrNode.name;
  42. scope = getInnermostScope(scope, nameOrNode);
  43. }
  44. while (scope != null) {
  45. const variable = scope.set.get(name);
  46. if (variable != null) {
  47. return variable
  48. }
  49. scope = scope.upper;
  50. }
  51. return null
  52. }
  53. /**
  54. * Negate the result of `this` calling.
  55. * @param {Token} token The token to check.
  56. * @returns {boolean} `true` if the result of `this(token)` is `false`.
  57. */
  58. function negate0(token) {
  59. return !this(token) //eslint-disable-line no-invalid-this
  60. }
  61. /**
  62. * Creates the negate function of the given function.
  63. * @param {function(Token):boolean} f - The function to negate.
  64. * @returns {function(Token):boolean} Negated function.
  65. */
  66. function negate(f) {
  67. return negate0.bind(f)
  68. }
  69. /**
  70. * Checks if the given token is an arrow token or not.
  71. * @param {Token} token - The token to check.
  72. * @returns {boolean} `true` if the token is an arrow token.
  73. */
  74. function isArrowToken(token) {
  75. return token.value === "=>" && token.type === "Punctuator"
  76. }
  77. /**
  78. * Checks if the given token is a comma token or not.
  79. * @param {Token} token - The token to check.
  80. * @returns {boolean} `true` if the token is a comma token.
  81. */
  82. function isCommaToken(token) {
  83. return token.value === "," && token.type === "Punctuator"
  84. }
  85. /**
  86. * Checks if the given token is a semicolon token or not.
  87. * @param {Token} token - The token to check.
  88. * @returns {boolean} `true` if the token is a semicolon token.
  89. */
  90. function isSemicolonToken(token) {
  91. return token.value === ";" && token.type === "Punctuator"
  92. }
  93. /**
  94. * Checks if the given token is a colon token or not.
  95. * @param {Token} token - The token to check.
  96. * @returns {boolean} `true` if the token is a colon token.
  97. */
  98. function isColonToken(token) {
  99. return token.value === ":" && token.type === "Punctuator"
  100. }
  101. /**
  102. * Checks if the given token is an opening parenthesis token or not.
  103. * @param {Token} token - The token to check.
  104. * @returns {boolean} `true` if the token is an opening parenthesis token.
  105. */
  106. function isOpeningParenToken(token) {
  107. return token.value === "(" && token.type === "Punctuator"
  108. }
  109. /**
  110. * Checks if the given token is a closing parenthesis token or not.
  111. * @param {Token} token - The token to check.
  112. * @returns {boolean} `true` if the token is a closing parenthesis token.
  113. */
  114. function isClosingParenToken(token) {
  115. return token.value === ")" && token.type === "Punctuator"
  116. }
  117. /**
  118. * Checks if the given token is an opening square bracket token or not.
  119. * @param {Token} token - The token to check.
  120. * @returns {boolean} `true` if the token is an opening square bracket token.
  121. */
  122. function isOpeningBracketToken(token) {
  123. return token.value === "[" && token.type === "Punctuator"
  124. }
  125. /**
  126. * Checks if the given token is a closing square bracket token or not.
  127. * @param {Token} token - The token to check.
  128. * @returns {boolean} `true` if the token is a closing square bracket token.
  129. */
  130. function isClosingBracketToken(token) {
  131. return token.value === "]" && token.type === "Punctuator"
  132. }
  133. /**
  134. * Checks if the given token is an opening brace token or not.
  135. * @param {Token} token - The token to check.
  136. * @returns {boolean} `true` if the token is an opening brace token.
  137. */
  138. function isOpeningBraceToken(token) {
  139. return token.value === "{" && token.type === "Punctuator"
  140. }
  141. /**
  142. * Checks if the given token is a closing brace token or not.
  143. * @param {Token} token - The token to check.
  144. * @returns {boolean} `true` if the token is a closing brace token.
  145. */
  146. function isClosingBraceToken(token) {
  147. return token.value === "}" && token.type === "Punctuator"
  148. }
  149. /**
  150. * Checks if the given token is a comment token or not.
  151. * @param {Token} token - The token to check.
  152. * @returns {boolean} `true` if the token is a comment token.
  153. */
  154. function isCommentToken(token) {
  155. return (
  156. token.type === "Line" ||
  157. token.type === "Block" ||
  158. token.type === "Shebang"
  159. )
  160. }
  161. const isNotArrowToken = negate(isArrowToken);
  162. const isNotCommaToken = negate(isCommaToken);
  163. const isNotSemicolonToken = negate(isSemicolonToken);
  164. const isNotColonToken = negate(isColonToken);
  165. const isNotOpeningParenToken = negate(isOpeningParenToken);
  166. const isNotClosingParenToken = negate(isClosingParenToken);
  167. const isNotOpeningBracketToken = negate(isOpeningBracketToken);
  168. const isNotClosingBracketToken = negate(isClosingBracketToken);
  169. const isNotOpeningBraceToken = negate(isOpeningBraceToken);
  170. const isNotClosingBraceToken = negate(isClosingBraceToken);
  171. const isNotCommentToken = negate(isCommentToken);
  172. /**
  173. * Get the `(` token of the given function node.
  174. * @param {Node} node - The function node to get.
  175. * @param {SourceCode} sourceCode - The source code object to get tokens.
  176. * @returns {Token} `(` token.
  177. */
  178. function getOpeningParenOfParams(node, sourceCode) {
  179. return node.id
  180. ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  181. : sourceCode.getFirstToken(node, isOpeningParenToken)
  182. }
  183. /**
  184. * Get the location of the given function node for reporting.
  185. * @param {Node} node - The function node to get.
  186. * @param {SourceCode} sourceCode - The source code object to get tokens.
  187. * @returns {string} The location of the function node for reporting.
  188. */
  189. function getFunctionHeadLocation(node, sourceCode) {
  190. const parent = node.parent;
  191. let start = null;
  192. let end = null;
  193. if (node.type === "ArrowFunctionExpression") {
  194. const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
  195. start = arrowToken.loc.start;
  196. end = arrowToken.loc.end;
  197. } else if (
  198. parent.type === "Property" ||
  199. parent.type === "MethodDefinition"
  200. ) {
  201. start = parent.loc.start;
  202. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  203. } else {
  204. start = node.loc.start;
  205. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  206. }
  207. return {
  208. start: Object.assign({}, start),
  209. end: Object.assign({}, end),
  210. }
  211. }
  212. /* globals BigInt, globalThis, global, self, window */
  213. const globalObject =
  214. typeof globalThis !== "undefined"
  215. ? globalThis
  216. : typeof self !== "undefined"
  217. ? self
  218. : typeof window !== "undefined"
  219. ? window
  220. : typeof global !== "undefined"
  221. ? global
  222. : {};
  223. const builtinNames = Object.freeze(
  224. new Set([
  225. "Array",
  226. "ArrayBuffer",
  227. "BigInt",
  228. "BigInt64Array",
  229. "BigUint64Array",
  230. "Boolean",
  231. "DataView",
  232. "Date",
  233. "decodeURI",
  234. "decodeURIComponent",
  235. "encodeURI",
  236. "encodeURIComponent",
  237. "escape",
  238. "Float32Array",
  239. "Float64Array",
  240. "Function",
  241. "Infinity",
  242. "Int16Array",
  243. "Int32Array",
  244. "Int8Array",
  245. "isFinite",
  246. "isNaN",
  247. "isPrototypeOf",
  248. "JSON",
  249. "Map",
  250. "Math",
  251. "NaN",
  252. "Number",
  253. "Object",
  254. "parseFloat",
  255. "parseInt",
  256. "Promise",
  257. "Proxy",
  258. "Reflect",
  259. "RegExp",
  260. "Set",
  261. "String",
  262. "Symbol",
  263. "Uint16Array",
  264. "Uint32Array",
  265. "Uint8Array",
  266. "Uint8ClampedArray",
  267. "undefined",
  268. "unescape",
  269. "WeakMap",
  270. "WeakSet",
  271. ])
  272. );
  273. const callAllowed = new Set(
  274. [
  275. Array.isArray,
  276. typeof BigInt === "function" ? BigInt : undefined,
  277. Boolean,
  278. Date,
  279. Date.parse,
  280. decodeURI,
  281. decodeURIComponent,
  282. encodeURI,
  283. encodeURIComponent,
  284. escape,
  285. isFinite,
  286. isNaN,
  287. isPrototypeOf,
  288. ...Object.getOwnPropertyNames(Math)
  289. .map(k => Math[k])
  290. .filter(f => typeof f === "function"),
  291. Number,
  292. Number.isFinite,
  293. Number.isNaN,
  294. Number.parseFloat,
  295. Number.parseInt,
  296. Object,
  297. Object.entries,
  298. Object.is,
  299. Object.isExtensible,
  300. Object.isFrozen,
  301. Object.isSealed,
  302. Object.keys,
  303. Object.values,
  304. parseFloat,
  305. parseInt,
  306. RegExp,
  307. String,
  308. String.fromCharCode,
  309. String.fromCodePoint,
  310. String.raw,
  311. Symbol,
  312. Symbol.for,
  313. Symbol.keyFor,
  314. unescape,
  315. ].filter(f => typeof f === "function")
  316. );
  317. const callPassThrough = new Set([
  318. Object.freeze,
  319. Object.preventExtensions,
  320. Object.seal,
  321. ]);
  322. /**
  323. * Get the property descriptor.
  324. * @param {object} object The object to get.
  325. * @param {string|number|symbol} name The property name to get.
  326. */
  327. function getPropertyDescriptor(object, name) {
  328. let x = object;
  329. while ((typeof x === "object" || typeof x === "function") && x !== null) {
  330. const d = Object.getOwnPropertyDescriptor(x, name);
  331. if (d) {
  332. return d
  333. }
  334. x = Object.getPrototypeOf(x);
  335. }
  336. return null
  337. }
  338. /**
  339. * Check if a property is getter or not.
  340. * @param {object} object The object to check.
  341. * @param {string|number|symbol} name The property name to check.
  342. */
  343. function isGetter(object, name) {
  344. const d = getPropertyDescriptor(object, name);
  345. return d != null && d.get != null
  346. }
  347. /**
  348. * Get the element values of a given node list.
  349. * @param {Node[]} nodeList The node list to get values.
  350. * @param {Scope|undefined} initialScope The initial scope to find variables.
  351. * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
  352. */
  353. function getElementValues(nodeList, initialScope) {
  354. const valueList = [];
  355. for (let i = 0; i < nodeList.length; ++i) {
  356. const elementNode = nodeList[i];
  357. if (elementNode == null) {
  358. valueList.length = i + 1;
  359. } else if (elementNode.type === "SpreadElement") {
  360. const argument = getStaticValueR(elementNode.argument, initialScope);
  361. if (argument == null) {
  362. return null
  363. }
  364. valueList.push(...argument.value);
  365. } else {
  366. const element = getStaticValueR(elementNode, initialScope);
  367. if (element == null) {
  368. return null
  369. }
  370. valueList.push(element.value);
  371. }
  372. }
  373. return valueList
  374. }
  375. const operations = Object.freeze({
  376. ArrayExpression(node, initialScope) {
  377. const elements = getElementValues(node.elements, initialScope);
  378. return elements != null ? { value: elements } : null
  379. },
  380. AssignmentExpression(node, initialScope) {
  381. if (node.operator === "=") {
  382. return getStaticValueR(node.right, initialScope)
  383. }
  384. return null
  385. },
  386. //eslint-disable-next-line complexity
  387. BinaryExpression(node, initialScope) {
  388. if (node.operator === "in" || node.operator === "instanceof") {
  389. // Not supported.
  390. return null
  391. }
  392. const left = getStaticValueR(node.left, initialScope);
  393. const right = getStaticValueR(node.right, initialScope);
  394. if (left != null && right != null) {
  395. switch (node.operator) {
  396. case "==":
  397. return { value: left.value == right.value } //eslint-disable-line eqeqeq
  398. case "!=":
  399. return { value: left.value != right.value } //eslint-disable-line eqeqeq
  400. case "===":
  401. return { value: left.value === right.value }
  402. case "!==":
  403. return { value: left.value !== right.value }
  404. case "<":
  405. return { value: left.value < right.value }
  406. case "<=":
  407. return { value: left.value <= right.value }
  408. case ">":
  409. return { value: left.value > right.value }
  410. case ">=":
  411. return { value: left.value >= right.value }
  412. case "<<":
  413. return { value: left.value << right.value }
  414. case ">>":
  415. return { value: left.value >> right.value }
  416. case ">>>":
  417. return { value: left.value >>> right.value }
  418. case "+":
  419. return { value: left.value + right.value }
  420. case "-":
  421. return { value: left.value - right.value }
  422. case "*":
  423. return { value: left.value * right.value }
  424. case "/":
  425. return { value: left.value / right.value }
  426. case "%":
  427. return { value: left.value % right.value }
  428. case "**":
  429. return { value: Math.pow(left.value, right.value) }
  430. case "|":
  431. return { value: left.value | right.value }
  432. case "^":
  433. return { value: left.value ^ right.value }
  434. case "&":
  435. return { value: left.value & right.value }
  436. // no default
  437. }
  438. }
  439. return null
  440. },
  441. CallExpression(node, initialScope) {
  442. const calleeNode = node.callee;
  443. const args = getElementValues(node.arguments, initialScope);
  444. if (args != null) {
  445. if (calleeNode.type === "MemberExpression") {
  446. const object = getStaticValueR(calleeNode.object, initialScope);
  447. const property = calleeNode.computed
  448. ? getStaticValueR(calleeNode.property, initialScope)
  449. : { value: calleeNode.property.name };
  450. if (object != null && property != null) {
  451. const receiver = object.value;
  452. const methodName = property.value;
  453. if (callAllowed.has(receiver[methodName])) {
  454. return { value: receiver[methodName](...args) }
  455. }
  456. if (callPassThrough.has(receiver[methodName])) {
  457. return { value: args[0] }
  458. }
  459. }
  460. } else {
  461. const callee = getStaticValueR(calleeNode, initialScope);
  462. if (callee != null) {
  463. const func = callee.value;
  464. if (callAllowed.has(func)) {
  465. return { value: func(...args) }
  466. }
  467. if (callPassThrough.has(func)) {
  468. return { value: args[0] }
  469. }
  470. }
  471. }
  472. }
  473. return null
  474. },
  475. ConditionalExpression(node, initialScope) {
  476. const test = getStaticValueR(node.test, initialScope);
  477. if (test != null) {
  478. return test.value
  479. ? getStaticValueR(node.consequent, initialScope)
  480. : getStaticValueR(node.alternate, initialScope)
  481. }
  482. return null
  483. },
  484. ExpressionStatement(node, initialScope) {
  485. return getStaticValueR(node.expression, initialScope)
  486. },
  487. Identifier(node, initialScope) {
  488. if (initialScope != null) {
  489. const variable = findVariable(initialScope, node);
  490. // Built-in globals.
  491. if (
  492. variable != null &&
  493. variable.defs.length === 0 &&
  494. builtinNames.has(variable.name) &&
  495. variable.name in globalObject
  496. ) {
  497. return { value: globalObject[variable.name] }
  498. }
  499. // Constants.
  500. if (variable != null && variable.defs.length === 1) {
  501. const def = variable.defs[0];
  502. if (
  503. def.parent &&
  504. def.parent.kind === "const" &&
  505. // TODO(mysticatea): don't support destructuring here.
  506. def.node.id.type === "Identifier"
  507. ) {
  508. return getStaticValueR(def.node.init, initialScope)
  509. }
  510. }
  511. }
  512. return null
  513. },
  514. Literal(node) {
  515. //istanbul ignore if : this is implementation-specific behavior.
  516. if ((node.regex != null || node.bigint != null) && node.value == null) {
  517. // It was a RegExp/BigInt literal, but Node.js didn't support it.
  518. return null
  519. }
  520. return { value: node.value }
  521. },
  522. LogicalExpression(node, initialScope) {
  523. const left = getStaticValueR(node.left, initialScope);
  524. if (left != null) {
  525. if (
  526. (node.operator === "||" && Boolean(left.value) === true) ||
  527. (node.operator === "&&" && Boolean(left.value) === false)
  528. ) {
  529. return left
  530. }
  531. const right = getStaticValueR(node.right, initialScope);
  532. if (right != null) {
  533. return right
  534. }
  535. }
  536. return null
  537. },
  538. MemberExpression(node, initialScope) {
  539. const object = getStaticValueR(node.object, initialScope);
  540. const property = node.computed
  541. ? getStaticValueR(node.property, initialScope)
  542. : { value: node.property.name };
  543. if (
  544. object != null &&
  545. property != null &&
  546. !isGetter(object.value, property.value)
  547. ) {
  548. return { value: object.value[property.value] }
  549. }
  550. return null
  551. },
  552. NewExpression(node, initialScope) {
  553. const callee = getStaticValueR(node.callee, initialScope);
  554. const args = getElementValues(node.arguments, initialScope);
  555. if (callee != null && args != null) {
  556. const Func = callee.value;
  557. if (callAllowed.has(Func)) {
  558. return { value: new Func(...args) }
  559. }
  560. }
  561. return null
  562. },
  563. ObjectExpression(node, initialScope) {
  564. const object = {};
  565. for (const propertyNode of node.properties) {
  566. if (propertyNode.type === "Property") {
  567. if (propertyNode.kind !== "init") {
  568. return null
  569. }
  570. const key = propertyNode.computed
  571. ? getStaticValueR(propertyNode.key, initialScope)
  572. : { value: propertyNode.key.name };
  573. const value = getStaticValueR(propertyNode.value, initialScope);
  574. if (key == null || value == null) {
  575. return null
  576. }
  577. object[key.value] = value.value;
  578. } else if (
  579. propertyNode.type === "SpreadElement" ||
  580. propertyNode.type === "ExperimentalSpreadProperty"
  581. ) {
  582. const argument = getStaticValueR(
  583. propertyNode.argument,
  584. initialScope
  585. );
  586. if (argument == null) {
  587. return null
  588. }
  589. Object.assign(object, argument.value);
  590. } else {
  591. return null
  592. }
  593. }
  594. return { value: object }
  595. },
  596. SequenceExpression(node, initialScope) {
  597. const last = node.expressions[node.expressions.length - 1];
  598. return getStaticValueR(last, initialScope)
  599. },
  600. TaggedTemplateExpression(node, initialScope) {
  601. const tag = getStaticValueR(node.tag, initialScope);
  602. const expressions = getElementValues(
  603. node.quasi.expressions,
  604. initialScope
  605. );
  606. if (tag != null && expressions != null) {
  607. const func = tag.value;
  608. const strings = node.quasi.quasis.map(q => q.value.cooked);
  609. strings.raw = node.quasi.quasis.map(q => q.value.raw);
  610. if (func === String.raw) {
  611. return { value: func(strings, ...expressions) }
  612. }
  613. }
  614. return null
  615. },
  616. TemplateLiteral(node, initialScope) {
  617. const expressions = getElementValues(node.expressions, initialScope);
  618. if (expressions != null) {
  619. let value = node.quasis[0].value.cooked;
  620. for (let i = 0; i < expressions.length; ++i) {
  621. value += expressions[i];
  622. value += node.quasis[i + 1].value.cooked;
  623. }
  624. return { value }
  625. }
  626. return null
  627. },
  628. UnaryExpression(node, initialScope) {
  629. if (node.operator === "delete") {
  630. // Not supported.
  631. return null
  632. }
  633. if (node.operator === "void") {
  634. return { value: undefined }
  635. }
  636. const arg = getStaticValueR(node.argument, initialScope);
  637. if (arg != null) {
  638. switch (node.operator) {
  639. case "-":
  640. return { value: -arg.value }
  641. case "+":
  642. return { value: +arg.value } //eslint-disable-line no-implicit-coercion
  643. case "!":
  644. return { value: !arg.value }
  645. case "~":
  646. return { value: ~arg.value }
  647. case "typeof":
  648. return { value: typeof arg.value }
  649. // no default
  650. }
  651. }
  652. return null
  653. },
  654. });
  655. /**
  656. * Get the value of a given node if it's a static value.
  657. * @param {Node} node The node to get.
  658. * @param {Scope|undefined} initialScope The scope to start finding variable.
  659. * @returns {{value:any}|null} The static value of the node, or `null`.
  660. */
  661. function getStaticValueR(node, initialScope) {
  662. if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
  663. return operations[node.type](node, initialScope)
  664. }
  665. return null
  666. }
  667. /**
  668. * Get the value of a given node if it's a static value.
  669. * @param {Node} node The node to get.
  670. * @param {Scope} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.
  671. * @returns {{value:any}|null} The static value of the node, or `null`.
  672. */
  673. function getStaticValue(node, initialScope = null) {
  674. try {
  675. return getStaticValueR(node, initialScope)
  676. } catch (_error) {
  677. return null
  678. }
  679. }
  680. /**
  681. * Get the value of a given node if it's a literal or a template literal.
  682. * @param {Node} node The node to get.
  683. * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant.
  684. * @returns {string|null} The value of the node, or `null`.
  685. */
  686. function getStringIfConstant(node, initialScope = null) {
  687. // Handle the literals that the platform doesn't support natively.
  688. if (node && node.type === "Literal" && node.value === null) {
  689. if (node.regex) {
  690. return `/${node.regex.pattern}/${node.regex.flags}`
  691. }
  692. if (node.bigint) {
  693. return node.bigint
  694. }
  695. }
  696. const evaluated = getStaticValue(node, initialScope);
  697. return evaluated && String(evaluated.value)
  698. }
  699. /**
  700. * Get the property name from a MemberExpression node or a Property node.
  701. * @param {Node} node The node to get.
  702. * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
  703. * @returns {string|null} The property name of the node.
  704. */
  705. function getPropertyName(node, initialScope) {
  706. switch (node.type) {
  707. case "MemberExpression":
  708. if (node.computed) {
  709. return getStringIfConstant(node.property, initialScope)
  710. }
  711. return node.property.name
  712. case "Property":
  713. case "MethodDefinition":
  714. if (node.computed) {
  715. return getStringIfConstant(node.key, initialScope)
  716. }
  717. if (node.key.type === "Literal") {
  718. return String(node.key.value)
  719. }
  720. return node.key.name
  721. // no default
  722. }
  723. return null
  724. }
  725. /**
  726. * Get the name and kind of the given function node.
  727. * @param {ASTNode} node - The function node to get.
  728. * @returns {string} The name and kind of the function node.
  729. */
  730. function getFunctionNameWithKind(node) {
  731. const parent = node.parent;
  732. const tokens = [];
  733. if (parent.type === "MethodDefinition" && parent.static) {
  734. tokens.push("static");
  735. }
  736. if (node.async) {
  737. tokens.push("async");
  738. }
  739. if (node.generator) {
  740. tokens.push("generator");
  741. }
  742. if (node.type === "ArrowFunctionExpression") {
  743. tokens.push("arrow", "function");
  744. } else if (
  745. parent.type === "Property" ||
  746. parent.type === "MethodDefinition"
  747. ) {
  748. if (parent.kind === "constructor") {
  749. return "constructor"
  750. }
  751. if (parent.kind === "get") {
  752. tokens.push("getter");
  753. } else if (parent.kind === "set") {
  754. tokens.push("setter");
  755. } else {
  756. tokens.push("method");
  757. }
  758. } else {
  759. tokens.push("function");
  760. }
  761. if (node.id) {
  762. tokens.push(`'${node.id.name}'`);
  763. } else {
  764. const name = getPropertyName(parent);
  765. if (name) {
  766. tokens.push(`'${name}'`);
  767. }
  768. }
  769. return tokens.join(" ")
  770. }
  771. const typeConversionBinaryOps = Object.freeze(
  772. new Set([
  773. "==",
  774. "!=",
  775. "<",
  776. "<=",
  777. ">",
  778. ">=",
  779. "<<",
  780. ">>",
  781. ">>>",
  782. "+",
  783. "-",
  784. "*",
  785. "/",
  786. "%",
  787. "|",
  788. "^",
  789. "&",
  790. "in",
  791. ])
  792. );
  793. const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"]));
  794. const visitor = Object.freeze(
  795. Object.assign(Object.create(null), {
  796. $visit(node, options, visitorKeys) {
  797. const { type } = node;
  798. if (typeof this[type] === "function") {
  799. return this[type](node, options, visitorKeys)
  800. }
  801. return this.$visitChildren(node, options, visitorKeys)
  802. },
  803. $visitChildren(node, options, visitorKeys) {
  804. const { type } = node;
  805. for (const key of visitorKeys[type] || evk.getKeys(node)) {
  806. const value = node[key];
  807. if (Array.isArray(value)) {
  808. for (const element of value) {
  809. if (
  810. element &&
  811. this.$visit(element, options, visitorKeys)
  812. ) {
  813. return true
  814. }
  815. }
  816. } else if (value && this.$visit(value, options, visitorKeys)) {
  817. return true
  818. }
  819. }
  820. return false
  821. },
  822. ArrowFunctionExpression() {
  823. return false
  824. },
  825. AssignmentExpression() {
  826. return true
  827. },
  828. AwaitExpression() {
  829. return true
  830. },
  831. BinaryExpression(node, options, visitorKeys) {
  832. if (
  833. options.considerImplicitTypeConversion &&
  834. typeConversionBinaryOps.has(node.operator) &&
  835. (node.left.type !== "Literal" || node.right.type !== "Literal")
  836. ) {
  837. return true
  838. }
  839. return this.$visitChildren(node, options, visitorKeys)
  840. },
  841. CallExpression() {
  842. return true
  843. },
  844. FunctionExpression() {
  845. return false
  846. },
  847. ImportExpression() {
  848. return true
  849. },
  850. MemberExpression(node, options, visitorKeys) {
  851. if (options.considerGetters) {
  852. return true
  853. }
  854. if (
  855. options.considerImplicitTypeConversion &&
  856. node.computed &&
  857. node.property.type !== "Literal"
  858. ) {
  859. return true
  860. }
  861. return this.$visitChildren(node, options, visitorKeys)
  862. },
  863. MethodDefinition(node, options, visitorKeys) {
  864. if (
  865. options.considerImplicitTypeConversion &&
  866. node.computed &&
  867. node.key.type !== "Literal"
  868. ) {
  869. return true
  870. }
  871. return this.$visitChildren(node, options, visitorKeys)
  872. },
  873. NewExpression() {
  874. return true
  875. },
  876. Property(node, options, visitorKeys) {
  877. if (
  878. options.considerImplicitTypeConversion &&
  879. node.computed &&
  880. node.key.type !== "Literal"
  881. ) {
  882. return true
  883. }
  884. return this.$visitChildren(node, options, visitorKeys)
  885. },
  886. UnaryExpression(node, options, visitorKeys) {
  887. if (node.operator === "delete") {
  888. return true
  889. }
  890. if (
  891. options.considerImplicitTypeConversion &&
  892. typeConversionUnaryOps.has(node.operator) &&
  893. node.argument.type !== "Literal"
  894. ) {
  895. return true
  896. }
  897. return this.$visitChildren(node, options, visitorKeys)
  898. },
  899. UpdateExpression() {
  900. return true
  901. },
  902. YieldExpression() {
  903. return true
  904. },
  905. })
  906. );
  907. /**
  908. * Check whether a given node has any side effect or not.
  909. * @param {Node} node The node to get.
  910. * @param {SourceCode} sourceCode The source code object.
  911. * @param {object} [options] The option object.
  912. * @param {boolean} [options.considerGetters=false] If `true` then it considers member accesses as the node which has side effects.
  913. * @param {boolean} [options.considerImplicitTypeConversion=false] If `true` then it considers implicit type conversion as the node which has side effects.
  914. * @param {object} [options.visitorKeys=evk.KEYS] The keys to traverse nodes. Use `context.getSourceCode().visitorKeys`.
  915. * @returns {boolean} `true` if the node has a certain side effect.
  916. */
  917. function hasSideEffect(
  918. node,
  919. sourceCode,
  920. { considerGetters = false, considerImplicitTypeConversion = false } = {}
  921. ) {
  922. return visitor.$visit(
  923. node,
  924. { considerGetters, considerImplicitTypeConversion },
  925. sourceCode.visitorKeys || evk.KEYS
  926. )
  927. }
  928. /**
  929. * Get the left parenthesis of the parent node syntax if it exists.
  930. * E.g., `if (a) {}` then the `(`.
  931. * @param {Node} node The AST node to check.
  932. * @param {SourceCode} sourceCode The source code object to get tokens.
  933. * @returns {Token|null} The left parenthesis of the parent node syntax
  934. */
  935. function getParentSyntaxParen(node, sourceCode) {
  936. const parent = node.parent;
  937. switch (parent.type) {
  938. case "CallExpression":
  939. case "NewExpression":
  940. if (parent.arguments.length === 1 && parent.arguments[0] === node) {
  941. return sourceCode.getTokenAfter(
  942. parent.callee,
  943. isOpeningParenToken
  944. )
  945. }
  946. return null
  947. case "DoWhileStatement":
  948. if (parent.test === node) {
  949. return sourceCode.getTokenAfter(
  950. parent.body,
  951. isOpeningParenToken
  952. )
  953. }
  954. return null
  955. case "IfStatement":
  956. case "WhileStatement":
  957. if (parent.test === node) {
  958. return sourceCode.getFirstToken(parent, 1)
  959. }
  960. return null
  961. case "ImportExpression":
  962. if (parent.source === node) {
  963. return sourceCode.getFirstToken(parent, 1)
  964. }
  965. return null
  966. case "SwitchStatement":
  967. if (parent.discriminant === node) {
  968. return sourceCode.getFirstToken(parent, 1)
  969. }
  970. return null
  971. case "WithStatement":
  972. if (parent.object === node) {
  973. return sourceCode.getFirstToken(parent, 1)
  974. }
  975. return null
  976. default:
  977. return null
  978. }
  979. }
  980. /**
  981. * Check whether a given node is parenthesized or not.
  982. * @param {number} times The number of parantheses.
  983. * @param {Node} node The AST node to check.
  984. * @param {SourceCode} sourceCode The source code object to get tokens.
  985. * @returns {boolean} `true` if the node is parenthesized the given times.
  986. */
  987. /**
  988. * Check whether a given node is parenthesized or not.
  989. * @param {Node} node The AST node to check.
  990. * @param {SourceCode} sourceCode The source code object to get tokens.
  991. * @returns {boolean} `true` if the node is parenthesized.
  992. */
  993. function isParenthesized(
  994. timesOrNode,
  995. nodeOrSourceCode,
  996. optionalSourceCode
  997. ) {
  998. let times, node, sourceCode, maybeLeftParen, maybeRightParen;
  999. if (typeof timesOrNode === "number") {
  1000. times = timesOrNode | 0;
  1001. node = nodeOrSourceCode;
  1002. sourceCode = optionalSourceCode;
  1003. if (!(times >= 1)) {
  1004. throw new TypeError("'times' should be a positive integer.")
  1005. }
  1006. } else {
  1007. times = 1;
  1008. node = timesOrNode;
  1009. sourceCode = nodeOrSourceCode;
  1010. }
  1011. if (node == null) {
  1012. return false
  1013. }
  1014. maybeLeftParen = maybeRightParen = node;
  1015. do {
  1016. maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen);
  1017. maybeRightParen = sourceCode.getTokenAfter(maybeRightParen);
  1018. } while (
  1019. maybeLeftParen != null &&
  1020. maybeRightParen != null &&
  1021. isOpeningParenToken(maybeLeftParen) &&
  1022. isClosingParenToken(maybeRightParen) &&
  1023. // Avoid false positive such as `if (a) {}`
  1024. maybeLeftParen !== getParentSyntaxParen(node, sourceCode) &&
  1025. --times > 0
  1026. )
  1027. return times === 0
  1028. }
  1029. /**
  1030. * @author Toru Nagashima <https://github.com/mysticatea>
  1031. * See LICENSE file in root directory for full license.
  1032. */
  1033. const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu;
  1034. /** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
  1035. const internal = new WeakMap();
  1036. /**
  1037. * Check whether a given character is escaped or not.
  1038. * @param {string} str The string to check.
  1039. * @param {number} index The location of the character to check.
  1040. * @returns {boolean} `true` if the character is escaped.
  1041. */
  1042. function isEscaped(str, index) {
  1043. let escaped = false;
  1044. for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
  1045. escaped = !escaped;
  1046. }
  1047. return escaped
  1048. }
  1049. /**
  1050. * Replace a given string by a given matcher.
  1051. * @param {PatternMatcher} matcher The pattern matcher.
  1052. * @param {string} str The string to be replaced.
  1053. * @param {string} replacement The new substring to replace each matched part.
  1054. * @returns {string} The replaced string.
  1055. */
  1056. function replaceS(matcher, str, replacement) {
  1057. const chunks = [];
  1058. let index = 0;
  1059. /** @type {RegExpExecArray} */
  1060. let match = null;
  1061. /**
  1062. * @param {string} key The placeholder.
  1063. * @returns {string} The replaced string.
  1064. */
  1065. function replacer(key) {
  1066. switch (key) {
  1067. case "$$":
  1068. return "$"
  1069. case "$&":
  1070. return match[0]
  1071. case "$`":
  1072. return str.slice(0, match.index)
  1073. case "$'":
  1074. return str.slice(match.index + match[0].length)
  1075. default: {
  1076. const i = key.slice(1);
  1077. if (i in match) {
  1078. return match[i]
  1079. }
  1080. return key
  1081. }
  1082. }
  1083. }
  1084. for (match of matcher.execAll(str)) {
  1085. chunks.push(str.slice(index, match.index));
  1086. chunks.push(replacement.replace(placeholder, replacer));
  1087. index = match.index + match[0].length;
  1088. }
  1089. chunks.push(str.slice(index));
  1090. return chunks.join("")
  1091. }
  1092. /**
  1093. * Replace a given string by a given matcher.
  1094. * @param {PatternMatcher} matcher The pattern matcher.
  1095. * @param {string} str The string to be replaced.
  1096. * @param {(...strs[])=>string} replace The function to replace each matched part.
  1097. * @returns {string} The replaced string.
  1098. */
  1099. function replaceF(matcher, str, replace) {
  1100. const chunks = [];
  1101. let index = 0;
  1102. for (const match of matcher.execAll(str)) {
  1103. chunks.push(str.slice(index, match.index));
  1104. chunks.push(String(replace(...match, match.index, match.input)));
  1105. index = match.index + match[0].length;
  1106. }
  1107. chunks.push(str.slice(index));
  1108. return chunks.join("")
  1109. }
  1110. /**
  1111. * The class to find patterns as considering escape sequences.
  1112. */
  1113. class PatternMatcher {
  1114. /**
  1115. * Initialize this matcher.
  1116. * @param {RegExp} pattern The pattern to match.
  1117. * @param {{escaped:boolean}} options The options.
  1118. */
  1119. constructor(pattern, { escaped = false } = {}) {
  1120. if (!(pattern instanceof RegExp)) {
  1121. throw new TypeError("'pattern' should be a RegExp instance.")
  1122. }
  1123. if (!pattern.flags.includes("g")) {
  1124. throw new Error("'pattern' should contains 'g' flag.")
  1125. }
  1126. internal.set(this, {
  1127. pattern: new RegExp(pattern.source, pattern.flags),
  1128. escaped: Boolean(escaped),
  1129. });
  1130. }
  1131. /**
  1132. * Find the pattern in a given string.
  1133. * @param {string} str The string to find.
  1134. * @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
  1135. */
  1136. *execAll(str) {
  1137. const { pattern, escaped } = internal.get(this);
  1138. let match = null;
  1139. let lastIndex = 0;
  1140. pattern.lastIndex = 0;
  1141. while ((match = pattern.exec(str)) != null) {
  1142. if (escaped || !isEscaped(str, match.index)) {
  1143. lastIndex = pattern.lastIndex;
  1144. yield match;
  1145. pattern.lastIndex = lastIndex;
  1146. }
  1147. }
  1148. }
  1149. /**
  1150. * Check whether the pattern is found in a given string.
  1151. * @param {string} str The string to check.
  1152. * @returns {boolean} `true` if the pattern was found in the string.
  1153. */
  1154. test(str) {
  1155. const it = this.execAll(str);
  1156. const ret = it.next();
  1157. return !ret.done
  1158. }
  1159. /**
  1160. * Replace a given string.
  1161. * @param {string} str The string to be replaced.
  1162. * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
  1163. * @returns {string} The replaced string.
  1164. */
  1165. [Symbol.replace](str, replacer) {
  1166. return typeof replacer === "function"
  1167. ? replaceF(this, String(str), replacer)
  1168. : replaceS(this, String(str), String(replacer))
  1169. }
  1170. }
  1171. const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u;
  1172. const has = Function.call.bind(Object.hasOwnProperty);
  1173. const READ = Symbol("read");
  1174. const CALL = Symbol("call");
  1175. const CONSTRUCT = Symbol("construct");
  1176. const ESM = Symbol("esm");
  1177. const requireCall = { require: { [CALL]: true } };
  1178. /**
  1179. * Check whether a given variable is modified or not.
  1180. * @param {Variable} variable The variable to check.
  1181. * @returns {boolean} `true` if the variable is modified.
  1182. */
  1183. function isModifiedGlobal(variable) {
  1184. return (
  1185. variable == null ||
  1186. variable.defs.length !== 0 ||
  1187. variable.references.some(r => r.isWrite())
  1188. )
  1189. }
  1190. /**
  1191. * Check if the value of a given node is passed through to the parent syntax as-is.
  1192. * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.
  1193. * @param {Node} node A node to check.
  1194. * @returns {boolean} `true` if the node is passed through.
  1195. */
  1196. function isPassThrough(node) {
  1197. const parent = node.parent;
  1198. switch (parent && parent.type) {
  1199. case "ConditionalExpression":
  1200. return parent.consequent === node || parent.alternate === node
  1201. case "LogicalExpression":
  1202. return true
  1203. case "SequenceExpression":
  1204. return parent.expressions[parent.expressions.length - 1] === node
  1205. default:
  1206. return false
  1207. }
  1208. }
  1209. /**
  1210. * The reference tracker.
  1211. */
  1212. class ReferenceTracker {
  1213. /**
  1214. * Initialize this tracker.
  1215. * @param {Scope} globalScope The global scope.
  1216. * @param {object} [options] The options.
  1217. * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
  1218. * @param {string[]} [options.globalObjectNames=["global","self","window"]] The variable names for Global Object.
  1219. */
  1220. constructor(
  1221. globalScope,
  1222. {
  1223. mode = "strict",
  1224. globalObjectNames = ["global", "self", "window"],
  1225. } = {}
  1226. ) {
  1227. this.variableStack = [];
  1228. this.globalScope = globalScope;
  1229. this.mode = mode;
  1230. this.globalObjectNames = globalObjectNames.slice(0);
  1231. }
  1232. /**
  1233. * Iterate the references of global variables.
  1234. * @param {object} traceMap The trace map.
  1235. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1236. */
  1237. *iterateGlobalReferences(traceMap) {
  1238. for (const key of Object.keys(traceMap)) {
  1239. const nextTraceMap = traceMap[key];
  1240. const path = [key];
  1241. const variable = this.globalScope.set.get(key);
  1242. if (isModifiedGlobal(variable)) {
  1243. continue
  1244. }
  1245. yield* this._iterateVariableReferences(
  1246. variable,
  1247. path,
  1248. nextTraceMap,
  1249. true
  1250. );
  1251. }
  1252. for (const key of this.globalObjectNames) {
  1253. const path = [];
  1254. const variable = this.globalScope.set.get(key);
  1255. if (isModifiedGlobal(variable)) {
  1256. continue
  1257. }
  1258. yield* this._iterateVariableReferences(
  1259. variable,
  1260. path,
  1261. traceMap,
  1262. false
  1263. );
  1264. }
  1265. }
  1266. /**
  1267. * Iterate the references of CommonJS modules.
  1268. * @param {object} traceMap The trace map.
  1269. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1270. */
  1271. *iterateCjsReferences(traceMap) {
  1272. for (const { node } of this.iterateGlobalReferences(requireCall)) {
  1273. const key = getStringIfConstant(node.arguments[0]);
  1274. if (key == null || !has(traceMap, key)) {
  1275. continue
  1276. }
  1277. const nextTraceMap = traceMap[key];
  1278. const path = [key];
  1279. if (nextTraceMap[READ]) {
  1280. yield {
  1281. node,
  1282. path,
  1283. type: READ,
  1284. info: nextTraceMap[READ],
  1285. };
  1286. }
  1287. yield* this._iteratePropertyReferences(node, path, nextTraceMap);
  1288. }
  1289. }
  1290. /**
  1291. * Iterate the references of ES modules.
  1292. * @param {object} traceMap The trace map.
  1293. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1294. */
  1295. *iterateEsmReferences(traceMap) {
  1296. const programNode = this.globalScope.block;
  1297. for (const node of programNode.body) {
  1298. if (!IMPORT_TYPE.test(node.type) || node.source == null) {
  1299. continue
  1300. }
  1301. const moduleId = node.source.value;
  1302. if (!has(traceMap, moduleId)) {
  1303. continue
  1304. }
  1305. const nextTraceMap = traceMap[moduleId];
  1306. const path = [moduleId];
  1307. if (nextTraceMap[READ]) {
  1308. yield { node, path, type: READ, info: nextTraceMap[READ] };
  1309. }
  1310. if (node.type === "ExportAllDeclaration") {
  1311. for (const key of Object.keys(nextTraceMap)) {
  1312. const exportTraceMap = nextTraceMap[key];
  1313. if (exportTraceMap[READ]) {
  1314. yield {
  1315. node,
  1316. path: path.concat(key),
  1317. type: READ,
  1318. info: exportTraceMap[READ],
  1319. };
  1320. }
  1321. }
  1322. } else {
  1323. for (const specifier of node.specifiers) {
  1324. const esm = has(nextTraceMap, ESM);
  1325. const it = this._iterateImportReferences(
  1326. specifier,
  1327. path,
  1328. esm
  1329. ? nextTraceMap
  1330. : this.mode === "legacy"
  1331. ? Object.assign(
  1332. { default: nextTraceMap },
  1333. nextTraceMap
  1334. )
  1335. : { default: nextTraceMap }
  1336. );
  1337. if (esm) {
  1338. yield* it;
  1339. } else {
  1340. for (const report of it) {
  1341. report.path = report.path.filter(exceptDefault);
  1342. if (
  1343. report.path.length >= 2 ||
  1344. report.type !== READ
  1345. ) {
  1346. yield report;
  1347. }
  1348. }
  1349. }
  1350. }
  1351. }
  1352. }
  1353. }
  1354. /**
  1355. * Iterate the references for a given variable.
  1356. * @param {Variable} variable The variable to iterate that references.
  1357. * @param {string[]} path The current path.
  1358. * @param {object} traceMap The trace map.
  1359. * @param {boolean} shouldReport = The flag to report those references.
  1360. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1361. */
  1362. *_iterateVariableReferences(variable, path, traceMap, shouldReport) {
  1363. if (this.variableStack.includes(variable)) {
  1364. return
  1365. }
  1366. this.variableStack.push(variable);
  1367. try {
  1368. for (const reference of variable.references) {
  1369. if (!reference.isRead()) {
  1370. continue
  1371. }
  1372. const node = reference.identifier;
  1373. if (shouldReport && traceMap[READ]) {
  1374. yield { node, path, type: READ, info: traceMap[READ] };
  1375. }
  1376. yield* this._iteratePropertyReferences(node, path, traceMap);
  1377. }
  1378. } finally {
  1379. this.variableStack.pop();
  1380. }
  1381. }
  1382. /**
  1383. * Iterate the references for a given AST node.
  1384. * @param rootNode The AST node to iterate references.
  1385. * @param {string[]} path The current path.
  1386. * @param {object} traceMap The trace map.
  1387. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1388. */
  1389. //eslint-disable-next-line complexity
  1390. *_iteratePropertyReferences(rootNode, path, traceMap) {
  1391. let node = rootNode;
  1392. while (isPassThrough(node)) {
  1393. node = node.parent;
  1394. }
  1395. const parent = node.parent;
  1396. if (parent.type === "MemberExpression") {
  1397. if (parent.object === node) {
  1398. const key = getPropertyName(parent);
  1399. if (key == null || !has(traceMap, key)) {
  1400. return
  1401. }
  1402. path = path.concat(key); //eslint-disable-line no-param-reassign
  1403. const nextTraceMap = traceMap[key];
  1404. if (nextTraceMap[READ]) {
  1405. yield {
  1406. node: parent,
  1407. path,
  1408. type: READ,
  1409. info: nextTraceMap[READ],
  1410. };
  1411. }
  1412. yield* this._iteratePropertyReferences(
  1413. parent,
  1414. path,
  1415. nextTraceMap
  1416. );
  1417. }
  1418. return
  1419. }
  1420. if (parent.type === "CallExpression") {
  1421. if (parent.callee === node && traceMap[CALL]) {
  1422. yield { node: parent, path, type: CALL, info: traceMap[CALL] };
  1423. }
  1424. return
  1425. }
  1426. if (parent.type === "NewExpression") {
  1427. if (parent.callee === node && traceMap[CONSTRUCT]) {
  1428. yield {
  1429. node: parent,
  1430. path,
  1431. type: CONSTRUCT,
  1432. info: traceMap[CONSTRUCT],
  1433. };
  1434. }
  1435. return
  1436. }
  1437. if (parent.type === "AssignmentExpression") {
  1438. if (parent.right === node) {
  1439. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  1440. yield* this._iteratePropertyReferences(parent, path, traceMap);
  1441. }
  1442. return
  1443. }
  1444. if (parent.type === "AssignmentPattern") {
  1445. if (parent.right === node) {
  1446. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  1447. }
  1448. return
  1449. }
  1450. if (parent.type === "VariableDeclarator") {
  1451. if (parent.init === node) {
  1452. yield* this._iterateLhsReferences(parent.id, path, traceMap);
  1453. }
  1454. }
  1455. }
  1456. /**
  1457. * Iterate the references for a given Pattern node.
  1458. * @param {Node} patternNode The Pattern node to iterate references.
  1459. * @param {string[]} path The current path.
  1460. * @param {object} traceMap The trace map.
  1461. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1462. */
  1463. *_iterateLhsReferences(patternNode, path, traceMap) {
  1464. if (patternNode.type === "Identifier") {
  1465. const variable = findVariable(this.globalScope, patternNode);
  1466. if (variable != null) {
  1467. yield* this._iterateVariableReferences(
  1468. variable,
  1469. path,
  1470. traceMap,
  1471. false
  1472. );
  1473. }
  1474. return
  1475. }
  1476. if (patternNode.type === "ObjectPattern") {
  1477. for (const property of patternNode.properties) {
  1478. const key = getPropertyName(property);
  1479. if (key == null || !has(traceMap, key)) {
  1480. continue
  1481. }
  1482. const nextPath = path.concat(key);
  1483. const nextTraceMap = traceMap[key];
  1484. if (nextTraceMap[READ]) {
  1485. yield {
  1486. node: property,
  1487. path: nextPath,
  1488. type: READ,
  1489. info: nextTraceMap[READ],
  1490. };
  1491. }
  1492. yield* this._iterateLhsReferences(
  1493. property.value,
  1494. nextPath,
  1495. nextTraceMap
  1496. );
  1497. }
  1498. return
  1499. }
  1500. if (patternNode.type === "AssignmentPattern") {
  1501. yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
  1502. }
  1503. }
  1504. /**
  1505. * Iterate the references for a given ModuleSpecifier node.
  1506. * @param {Node} specifierNode The ModuleSpecifier node to iterate references.
  1507. * @param {string[]} path The current path.
  1508. * @param {object} traceMap The trace map.
  1509. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1510. */
  1511. *_iterateImportReferences(specifierNode, path, traceMap) {
  1512. const type = specifierNode.type;
  1513. if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
  1514. const key =
  1515. type === "ImportDefaultSpecifier"
  1516. ? "default"
  1517. : specifierNode.imported.name;
  1518. if (!has(traceMap, key)) {
  1519. return
  1520. }
  1521. path = path.concat(key); //eslint-disable-line no-param-reassign
  1522. const nextTraceMap = traceMap[key];
  1523. if (nextTraceMap[READ]) {
  1524. yield {
  1525. node: specifierNode,
  1526. path,
  1527. type: READ,
  1528. info: nextTraceMap[READ],
  1529. };
  1530. }
  1531. yield* this._iterateVariableReferences(
  1532. findVariable(this.globalScope, specifierNode.local),
  1533. path,
  1534. nextTraceMap,
  1535. false
  1536. );
  1537. return
  1538. }
  1539. if (type === "ImportNamespaceSpecifier") {
  1540. yield* this._iterateVariableReferences(
  1541. findVariable(this.globalScope, specifierNode.local),
  1542. path,
  1543. traceMap,
  1544. false
  1545. );
  1546. return
  1547. }
  1548. if (type === "ExportSpecifier") {
  1549. const key = specifierNode.local.name;
  1550. if (!has(traceMap, key)) {
  1551. return
  1552. }
  1553. path = path.concat(key); //eslint-disable-line no-param-reassign
  1554. const nextTraceMap = traceMap[key];
  1555. if (nextTraceMap[READ]) {
  1556. yield {
  1557. node: specifierNode,
  1558. path,
  1559. type: READ,
  1560. info: nextTraceMap[READ],
  1561. };
  1562. }
  1563. }
  1564. }
  1565. }
  1566. ReferenceTracker.READ = READ;
  1567. ReferenceTracker.CALL = CALL;
  1568. ReferenceTracker.CONSTRUCT = CONSTRUCT;
  1569. ReferenceTracker.ESM = ESM;
  1570. /**
  1571. * This is a predicate function for Array#filter.
  1572. * @param {string} name A name part.
  1573. * @param {number} index The index of the name.
  1574. * @returns {boolean} `false` if it's default.
  1575. */
  1576. function exceptDefault(name, index) {
  1577. return !(index === 1 && name === "default")
  1578. }
  1579. var index = {
  1580. CALL,
  1581. CONSTRUCT,
  1582. ESM,
  1583. findVariable,
  1584. getFunctionHeadLocation,
  1585. getFunctionNameWithKind,
  1586. getInnermostScope,
  1587. getPropertyName,
  1588. getStaticValue,
  1589. getStringIfConstant,
  1590. hasSideEffect,
  1591. isArrowToken,
  1592. isClosingBraceToken,
  1593. isClosingBracketToken,
  1594. isClosingParenToken,
  1595. isColonToken,
  1596. isCommaToken,
  1597. isCommentToken,
  1598. isNotArrowToken,
  1599. isNotClosingBraceToken,
  1600. isNotClosingBracketToken,
  1601. isNotClosingParenToken,
  1602. isNotColonToken,
  1603. isNotCommaToken,
  1604. isNotCommentToken,
  1605. isNotOpeningBraceToken,
  1606. isNotOpeningBracketToken,
  1607. isNotOpeningParenToken,
  1608. isNotSemicolonToken,
  1609. isOpeningBraceToken,
  1610. isOpeningBracketToken,
  1611. isOpeningParenToken,
  1612. isParenthesized,
  1613. isSemicolonToken,
  1614. PatternMatcher,
  1615. READ,
  1616. ReferenceTracker,
  1617. };
  1618. exports.CALL = CALL;
  1619. exports.CONSTRUCT = CONSTRUCT;
  1620. exports.ESM = ESM;
  1621. exports.PatternMatcher = PatternMatcher;
  1622. exports.READ = READ;
  1623. exports.ReferenceTracker = ReferenceTracker;
  1624. exports.default = index;
  1625. exports.findVariable = findVariable;
  1626. exports.getFunctionHeadLocation = getFunctionHeadLocation;
  1627. exports.getFunctionNameWithKind = getFunctionNameWithKind;
  1628. exports.getInnermostScope = getInnermostScope;
  1629. exports.getPropertyName = getPropertyName;
  1630. exports.getStaticValue = getStaticValue;
  1631. exports.getStringIfConstant = getStringIfConstant;
  1632. exports.hasSideEffect = hasSideEffect;
  1633. exports.isArrowToken = isArrowToken;
  1634. exports.isClosingBraceToken = isClosingBraceToken;
  1635. exports.isClosingBracketToken = isClosingBracketToken;
  1636. exports.isClosingParenToken = isClosingParenToken;
  1637. exports.isColonToken = isColonToken;
  1638. exports.isCommaToken = isCommaToken;
  1639. exports.isCommentToken = isCommentToken;
  1640. exports.isNotArrowToken = isNotArrowToken;
  1641. exports.isNotClosingBraceToken = isNotClosingBraceToken;
  1642. exports.isNotClosingBracketToken = isNotClosingBracketToken;
  1643. exports.isNotClosingParenToken = isNotClosingParenToken;
  1644. exports.isNotColonToken = isNotColonToken;
  1645. exports.isNotCommaToken = isNotCommaToken;
  1646. exports.isNotCommentToken = isNotCommentToken;
  1647. exports.isNotOpeningBraceToken = isNotOpeningBraceToken;
  1648. exports.isNotOpeningBracketToken = isNotOpeningBracketToken;
  1649. exports.isNotOpeningParenToken = isNotOpeningParenToken;
  1650. exports.isNotSemicolonToken = isNotSemicolonToken;
  1651. exports.isOpeningBraceToken = isOpeningBraceToken;
  1652. exports.isOpeningBracketToken = isOpeningBracketToken;
  1653. exports.isOpeningParenToken = isOpeningParenToken;
  1654. exports.isParenthesized = isParenthesized;
  1655. exports.isSemicolonToken = isSemicolonToken;
  1656. //# sourceMappingURL=index.js.map