You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1838 lines
57 KiB

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