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.

1758 lines
59 KiB

4 years ago
  1. /**
  2. * @fileoverview Common utils for AST.
  3. * @author Gyandeep Singh
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const esutils = require("esutils");
  10. const espree = require("espree");
  11. const lodash = require("lodash");
  12. const {
  13. breakableTypePattern,
  14. createGlobalLinebreakMatcher,
  15. lineBreakPattern,
  16. shebangPattern
  17. } = require("../../shared/ast-utils");
  18. //------------------------------------------------------------------------------
  19. // Helpers
  20. //------------------------------------------------------------------------------
  21. const anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u;
  22. const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u;
  23. const arrayOrTypedArrayPattern = /Array$/u;
  24. const arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/u;
  25. const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u;
  26. const thisTagPattern = /^[\s*]*@this/mu;
  27. const COMMENTS_IGNORE_PATTERN = /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u;
  28. const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]);
  29. // A set of node types that can contain a list of statements
  30. const STATEMENT_LIST_PARENTS = new Set(["Program", "BlockStatement", "SwitchCase"]);
  31. const DECIMAL_INTEGER_PATTERN = /^(0|[1-9]\d*)$/u;
  32. const OCTAL_ESCAPE_PATTERN = /^(?:[^\\]|\\[^0-7]|\\0(?![0-9]))*\\(?:[1-7]|0[0-9])/u;
  33. /**
  34. * Checks reference if is non initializer and writable.
  35. * @param {Reference} reference A reference to check.
  36. * @param {int} index The index of the reference in the references.
  37. * @param {Reference[]} references The array that the reference belongs to.
  38. * @returns {boolean} Success/Failure
  39. * @private
  40. */
  41. function isModifyingReference(reference, index, references) {
  42. const identifier = reference.identifier;
  43. /*
  44. * Destructuring assignments can have multiple default value, so
  45. * possibly there are multiple writeable references for the same
  46. * identifier.
  47. */
  48. const modifyingDifferentIdentifier = index === 0 ||
  49. references[index - 1].identifier !== identifier;
  50. return (identifier &&
  51. reference.init === false &&
  52. reference.isWrite() &&
  53. modifyingDifferentIdentifier
  54. );
  55. }
  56. /**
  57. * Checks whether the given string starts with uppercase or not.
  58. * @param {string} s The string to check.
  59. * @returns {boolean} `true` if the string starts with uppercase.
  60. */
  61. function startsWithUpperCase(s) {
  62. return s[0] !== s[0].toLocaleLowerCase();
  63. }
  64. /**
  65. * Checks whether or not a node is a constructor.
  66. * @param {ASTNode} node A function node to check.
  67. * @returns {boolean} Wehether or not a node is a constructor.
  68. */
  69. function isES5Constructor(node) {
  70. return (node.id && startsWithUpperCase(node.id.name));
  71. }
  72. /**
  73. * Finds a function node from ancestors of a node.
  74. * @param {ASTNode} node A start node to find.
  75. * @returns {Node|null} A found function node.
  76. */
  77. function getUpperFunction(node) {
  78. for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
  79. if (anyFunctionPattern.test(currentNode.type)) {
  80. return currentNode;
  81. }
  82. }
  83. return null;
  84. }
  85. /**
  86. * Checks whether a given node is a function node or not.
  87. * The following types are function nodes:
  88. *
  89. * - ArrowFunctionExpression
  90. * - FunctionDeclaration
  91. * - FunctionExpression
  92. * @param {ASTNode|null} node A node to check.
  93. * @returns {boolean} `true` if the node is a function node.
  94. */
  95. function isFunction(node) {
  96. return Boolean(node && anyFunctionPattern.test(node.type));
  97. }
  98. /**
  99. * Checks whether a given node is a loop node or not.
  100. * The following types are loop nodes:
  101. *
  102. * - DoWhileStatement
  103. * - ForInStatement
  104. * - ForOfStatement
  105. * - ForStatement
  106. * - WhileStatement
  107. * @param {ASTNode|null} node A node to check.
  108. * @returns {boolean} `true` if the node is a loop node.
  109. */
  110. function isLoop(node) {
  111. return Boolean(node && anyLoopPattern.test(node.type));
  112. }
  113. /**
  114. * Checks whether the given node is in a loop or not.
  115. * @param {ASTNode} node The node to check.
  116. * @returns {boolean} `true` if the node is in a loop.
  117. */
  118. function isInLoop(node) {
  119. for (let currentNode = node; currentNode && !isFunction(currentNode); currentNode = currentNode.parent) {
  120. if (isLoop(currentNode)) {
  121. return true;
  122. }
  123. }
  124. return false;
  125. }
  126. /**
  127. * Determines whether the given node is a `null` literal.
  128. * @param {ASTNode} node The node to check
  129. * @returns {boolean} `true` if the node is a `null` literal
  130. */
  131. function isNullLiteral(node) {
  132. /*
  133. * Checking `node.value === null` does not guarantee that a literal is a null literal.
  134. * When parsing values that cannot be represented in the current environment (e.g. unicode
  135. * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to
  136. * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check
  137. * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020
  138. */
  139. return node.type === "Literal" && node.value === null && !node.regex && !node.bigint;
  140. }
  141. /**
  142. * Checks whether or not a node is `null` or `undefined`.
  143. * @param {ASTNode} node A node to check.
  144. * @returns {boolean} Whether or not the node is a `null` or `undefined`.
  145. * @public
  146. */
  147. function isNullOrUndefined(node) {
  148. return (
  149. isNullLiteral(node) ||
  150. (node.type === "Identifier" && node.name === "undefined") ||
  151. (node.type === "UnaryExpression" && node.operator === "void")
  152. );
  153. }
  154. /**
  155. * Checks whether or not a node is callee.
  156. * @param {ASTNode} node A node to check.
  157. * @returns {boolean} Whether or not the node is callee.
  158. */
  159. function isCallee(node) {
  160. return node.parent.type === "CallExpression" && node.parent.callee === node;
  161. }
  162. /**
  163. * Returns the result of the string conversion applied to the evaluated value of the given expression node,
  164. * if it can be determined statically.
  165. *
  166. * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only.
  167. * In all other cases, this function returns `null`.
  168. * @param {ASTNode} node Expression node.
  169. * @returns {string|null} String value if it can be determined. Otherwise, `null`.
  170. */
  171. function getStaticStringValue(node) {
  172. switch (node.type) {
  173. case "Literal":
  174. if (node.value === null) {
  175. if (isNullLiteral(node)) {
  176. return String(node.value); // "null"
  177. }
  178. if (node.regex) {
  179. return `/${node.regex.pattern}/${node.regex.flags}`;
  180. }
  181. if (node.bigint) {
  182. return node.bigint;
  183. }
  184. // Otherwise, this is an unknown literal. The function will return null.
  185. } else {
  186. return String(node.value);
  187. }
  188. break;
  189. case "TemplateLiteral":
  190. if (node.expressions.length === 0 && node.quasis.length === 1) {
  191. return node.quasis[0].value.cooked;
  192. }
  193. break;
  194. // no default
  195. }
  196. return null;
  197. }
  198. /**
  199. * Gets the property name of a given node.
  200. * The node can be a MemberExpression, a Property, or a MethodDefinition.
  201. *
  202. * If the name is dynamic, this returns `null`.
  203. *
  204. * For examples:
  205. *
  206. * a.b // => "b"
  207. * a["b"] // => "b"
  208. * a['b'] // => "b"
  209. * a[`b`] // => "b"
  210. * a[100] // => "100"
  211. * a[b] // => null
  212. * a["a" + "b"] // => null
  213. * a[tag`b`] // => null
  214. * a[`${b}`] // => null
  215. *
  216. * let a = {b: 1} // => "b"
  217. * let a = {["b"]: 1} // => "b"
  218. * let a = {['b']: 1} // => "b"
  219. * let a = {[`b`]: 1} // => "b"
  220. * let a = {[100]: 1} // => "100"
  221. * let a = {[b]: 1} // => null
  222. * let a = {["a" + "b"]: 1} // => null
  223. * let a = {[tag`b`]: 1} // => null
  224. * let a = {[`${b}`]: 1} // => null
  225. * @param {ASTNode} node The node to get.
  226. * @returns {string|null} The property name if static. Otherwise, null.
  227. */
  228. function getStaticPropertyName(node) {
  229. let prop;
  230. switch (node && node.type) {
  231. case "ChainExpression":
  232. return getStaticPropertyName(node.expression);
  233. case "Property":
  234. case "MethodDefinition":
  235. prop = node.key;
  236. break;
  237. case "MemberExpression":
  238. prop = node.property;
  239. break;
  240. // no default
  241. }
  242. if (prop) {
  243. if (prop.type === "Identifier" && !node.computed) {
  244. return prop.name;
  245. }
  246. return getStaticStringValue(prop);
  247. }
  248. return null;
  249. }
  250. /**
  251. * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it.
  252. * @param {ASTNode} node The node to address.
  253. * @returns {ASTNode} The `ChainExpression#expression` value if the node is a `ChainExpression` node. Otherwise, the node.
  254. */
  255. function skipChainExpression(node) {
  256. return node && node.type === "ChainExpression" ? node.expression : node;
  257. }
  258. /**
  259. * Check if the `actual` is an expected value.
  260. * @param {string} actual The string value to check.
  261. * @param {string | RegExp} expected The expected string value or pattern.
  262. * @returns {boolean} `true` if the `actual` is an expected value.
  263. */
  264. function checkText(actual, expected) {
  265. return typeof expected === "string"
  266. ? actual === expected
  267. : expected.test(actual);
  268. }
  269. /**
  270. * Check if a given node is an Identifier node with a given name.
  271. * @param {ASTNode} node The node to check.
  272. * @param {string | RegExp} name The expected name or the expected pattern of the object name.
  273. * @returns {boolean} `true` if the node is an Identifier node with the name.
  274. */
  275. function isSpecificId(node, name) {
  276. return node.type === "Identifier" && checkText(node.name, name);
  277. }
  278. /**
  279. * Check if a given node is member access with a given object name and property name pair.
  280. * This is regardless of optional or not.
  281. * @param {ASTNode} node The node to check.
  282. * @param {string | RegExp | null} objectName The expected name or the expected pattern of the object name. If this is nullish, this method doesn't check object.
  283. * @param {string | RegExp | null} propertyName The expected name or the expected pattern of the property name. If this is nullish, this method doesn't check property.
  284. * @returns {boolean} `true` if the node is member access with the object name and property name pair.
  285. * The node is a `MemberExpression` or `ChainExpression`.
  286. */
  287. function isSpecificMemberAccess(node, objectName, propertyName) {
  288. const checkNode = skipChainExpression(node);
  289. if (checkNode.type !== "MemberExpression") {
  290. return false;
  291. }
  292. if (objectName && !isSpecificId(checkNode.object, objectName)) {
  293. return false;
  294. }
  295. if (propertyName) {
  296. const actualPropertyName = getStaticPropertyName(checkNode);
  297. if (typeof actualPropertyName !== "string" || !checkText(actualPropertyName, propertyName)) {
  298. return false;
  299. }
  300. }
  301. return true;
  302. }
  303. /**
  304. * Check if two literal nodes are the same value.
  305. * @param {ASTNode} left The Literal node to compare.
  306. * @param {ASTNode} right The other Literal node to compare.
  307. * @returns {boolean} `true` if the two literal nodes are the same value.
  308. */
  309. function equalLiteralValue(left, right) {
  310. // RegExp literal.
  311. if (left.regex || right.regex) {
  312. return Boolean(
  313. left.regex &&
  314. right.regex &&
  315. left.regex.pattern === right.regex.pattern &&
  316. left.regex.flags === right.regex.flags
  317. );
  318. }
  319. // BigInt literal.
  320. if (left.bigint || right.bigint) {
  321. return left.bigint === right.bigint;
  322. }
  323. return left.value === right.value;
  324. }
  325. /**
  326. * Check if two expressions reference the same value. For example:
  327. * a = a
  328. * a.b = a.b
  329. * a[0] = a[0]
  330. * a['b'] = a['b']
  331. * @param {ASTNode} left The left side of the comparison.
  332. * @param {ASTNode} right The right side of the comparison.
  333. * @param {boolean} [disableStaticComputedKey] Don't address `a.b` and `a["b"]` are the same if `true`. For backward compatibility.
  334. * @returns {boolean} `true` if both sides match and reference the same value.
  335. */
  336. function isSameReference(left, right, disableStaticComputedKey = false) {
  337. if (left.type !== right.type) {
  338. // Handle `a.b` and `a?.b` are samely.
  339. if (left.type === "ChainExpression") {
  340. return isSameReference(left.expression, right, disableStaticComputedKey);
  341. }
  342. if (right.type === "ChainExpression") {
  343. return isSameReference(left, right.expression, disableStaticComputedKey);
  344. }
  345. return false;
  346. }
  347. switch (left.type) {
  348. case "Super":
  349. case "ThisExpression":
  350. return true;
  351. case "Identifier":
  352. return left.name === right.name;
  353. case "Literal":
  354. return equalLiteralValue(left, right);
  355. case "ChainExpression":
  356. return isSameReference(left.expression, right.expression, disableStaticComputedKey);
  357. case "MemberExpression": {
  358. if (!disableStaticComputedKey) {
  359. const nameA = getStaticPropertyName(left);
  360. // x.y = x["y"]
  361. if (nameA !== null) {
  362. return (
  363. isSameReference(left.object, right.object, disableStaticComputedKey) &&
  364. nameA === getStaticPropertyName(right)
  365. );
  366. }
  367. }
  368. /*
  369. * x[0] = x[0]
  370. * x[y] = x[y]
  371. * x.y = x.y
  372. */
  373. return (
  374. left.computed === right.computed &&
  375. isSameReference(left.object, right.object, disableStaticComputedKey) &&
  376. isSameReference(left.property, right.property, disableStaticComputedKey)
  377. );
  378. }
  379. default:
  380. return false;
  381. }
  382. }
  383. /**
  384. * Checks whether or not a node is `Reflect.apply`.
  385. * @param {ASTNode} node A node to check.
  386. * @returns {boolean} Whether or not the node is a `Reflect.apply`.
  387. */
  388. function isReflectApply(node) {
  389. return isSpecificMemberAccess(node, "Reflect", "apply");
  390. }
  391. /**
  392. * Checks whether or not a node is `Array.from`.
  393. * @param {ASTNode} node A node to check.
  394. * @returns {boolean} Whether or not the node is a `Array.from`.
  395. */
  396. function isArrayFromMethod(node) {
  397. return isSpecificMemberAccess(node, arrayOrTypedArrayPattern, "from");
  398. }
  399. /**
  400. * Checks whether or not a node is a method which has `thisArg`.
  401. * @param {ASTNode} node A node to check.
  402. * @returns {boolean} Whether or not the node is a method which has `thisArg`.
  403. */
  404. function isMethodWhichHasThisArg(node) {
  405. return isSpecificMemberAccess(node, null, arrayMethodPattern);
  406. }
  407. /**
  408. * Creates the negate function of the given function.
  409. * @param {Function} f The function to negate.
  410. * @returns {Function} Negated function.
  411. */
  412. function negate(f) {
  413. return token => !f(token);
  414. }
  415. /**
  416. * Checks whether or not a node has a `@this` tag in its comments.
  417. * @param {ASTNode} node A node to check.
  418. * @param {SourceCode} sourceCode A SourceCode instance to get comments.
  419. * @returns {boolean} Whether or not the node has a `@this` tag in its comments.
  420. */
  421. function hasJSDocThisTag(node, sourceCode) {
  422. const jsdocComment = sourceCode.getJSDocComment(node);
  423. if (jsdocComment && thisTagPattern.test(jsdocComment.value)) {
  424. return true;
  425. }
  426. // Checks `@this` in its leading comments for callbacks,
  427. // because callbacks don't have its JSDoc comment.
  428. // e.g.
  429. // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); });
  430. return sourceCode.getCommentsBefore(node).some(comment => thisTagPattern.test(comment.value));
  431. }
  432. /**
  433. * Determines if a node is surrounded by parentheses.
  434. * @param {SourceCode} sourceCode The ESLint source code object
  435. * @param {ASTNode} node The node to be checked.
  436. * @returns {boolean} True if the node is parenthesised.
  437. * @private
  438. */
  439. function isParenthesised(sourceCode, node) {
  440. const previousToken = sourceCode.getTokenBefore(node),
  441. nextToken = sourceCode.getTokenAfter(node);
  442. return Boolean(previousToken && nextToken) &&
  443. previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
  444. nextToken.value === ")" && nextToken.range[0] >= node.range[1];
  445. }
  446. /**
  447. * Checks if the given token is an arrow token or not.
  448. * @param {Token} token The token to check.
  449. * @returns {boolean} `true` if the token is an arrow token.
  450. */
  451. function isArrowToken(token) {
  452. return token.value === "=>" && token.type === "Punctuator";
  453. }
  454. /**
  455. * Checks if the given token is a comma token or not.
  456. * @param {Token} token The token to check.
  457. * @returns {boolean} `true` if the token is a comma token.
  458. */
  459. function isCommaToken(token) {
  460. return token.value === "," && token.type === "Punctuator";
  461. }
  462. /**
  463. * Checks if the given token is a dot token or not.
  464. * @param {Token} token The token to check.
  465. * @returns {boolean} `true` if the token is a dot token.
  466. */
  467. function isDotToken(token) {
  468. return token.value === "." && token.type === "Punctuator";
  469. }
  470. /**
  471. * Checks if the given token is a `?.` token or not.
  472. * @param {Token} token The token to check.
  473. * @returns {boolean} `true` if the token is a `?.` token.
  474. */
  475. function isQuestionDotToken(token) {
  476. return token.value === "?." && token.type === "Punctuator";
  477. }
  478. /**
  479. * Checks if the given token is a semicolon token or not.
  480. * @param {Token} token The token to check.
  481. * @returns {boolean} `true` if the token is a semicolon token.
  482. */
  483. function isSemicolonToken(token) {
  484. return token.value === ";" && token.type === "Punctuator";
  485. }
  486. /**
  487. * Checks if the given token is a colon token or not.
  488. * @param {Token} token The token to check.
  489. * @returns {boolean} `true` if the token is a colon token.
  490. */
  491. function isColonToken(token) {
  492. return token.value === ":" && token.type === "Punctuator";
  493. }
  494. /**
  495. * Checks if the given token is an opening parenthesis token or not.
  496. * @param {Token} token The token to check.
  497. * @returns {boolean} `true` if the token is an opening parenthesis token.
  498. */
  499. function isOpeningParenToken(token) {
  500. return token.value === "(" && token.type === "Punctuator";
  501. }
  502. /**
  503. * Checks if the given token is a closing parenthesis token or not.
  504. * @param {Token} token The token to check.
  505. * @returns {boolean} `true` if the token is a closing parenthesis token.
  506. */
  507. function isClosingParenToken(token) {
  508. return token.value === ")" && token.type === "Punctuator";
  509. }
  510. /**
  511. * Checks if the given token is an opening square bracket token or not.
  512. * @param {Token} token The token to check.
  513. * @returns {boolean} `true` if the token is an opening square bracket token.
  514. */
  515. function isOpeningBracketToken(token) {
  516. return token.value === "[" && token.type === "Punctuator";
  517. }
  518. /**
  519. * Checks if the given token is a closing square bracket token or not.
  520. * @param {Token} token The token to check.
  521. * @returns {boolean} `true` if the token is a closing square bracket token.
  522. */
  523. function isClosingBracketToken(token) {
  524. return token.value === "]" && token.type === "Punctuator";
  525. }
  526. /**
  527. * Checks if the given token is an opening brace token or not.
  528. * @param {Token} token The token to check.
  529. * @returns {boolean} `true` if the token is an opening brace token.
  530. */
  531. function isOpeningBraceToken(token) {
  532. return token.value === "{" && token.type === "Punctuator";
  533. }
  534. /**
  535. * Checks if the given token is a closing brace token or not.
  536. * @param {Token} token The token to check.
  537. * @returns {boolean} `true` if the token is a closing brace token.
  538. */
  539. function isClosingBraceToken(token) {
  540. return token.value === "}" && token.type === "Punctuator";
  541. }
  542. /**
  543. * Checks if the given token is a comment token or not.
  544. * @param {Token} token The token to check.
  545. * @returns {boolean} `true` if the token is a comment token.
  546. */
  547. function isCommentToken(token) {
  548. return token.type === "Line" || token.type === "Block" || token.type === "Shebang";
  549. }
  550. /**
  551. * Checks if the given token is a keyword token or not.
  552. * @param {Token} token The token to check.
  553. * @returns {boolean} `true` if the token is a keyword token.
  554. */
  555. function isKeywordToken(token) {
  556. return token.type === "Keyword";
  557. }
  558. /**
  559. * Gets the `(` token of the given function node.
  560. * @param {ASTNode} node The function node to get.
  561. * @param {SourceCode} sourceCode The source code object to get tokens.
  562. * @returns {Token} `(` token.
  563. */
  564. function getOpeningParenOfParams(node, sourceCode) {
  565. return node.id
  566. ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  567. : sourceCode.getFirstToken(node, isOpeningParenToken);
  568. }
  569. /**
  570. * Checks whether or not the tokens of two given nodes are same.
  571. * @param {ASTNode} left A node 1 to compare.
  572. * @param {ASTNode} right A node 2 to compare.
  573. * @param {SourceCode} sourceCode The ESLint source code object.
  574. * @returns {boolean} the source code for the given node.
  575. */
  576. function equalTokens(left, right, sourceCode) {
  577. const tokensL = sourceCode.getTokens(left);
  578. const tokensR = sourceCode.getTokens(right);
  579. if (tokensL.length !== tokensR.length) {
  580. return false;
  581. }
  582. for (let i = 0; i < tokensL.length; ++i) {
  583. if (tokensL[i].type !== tokensR[i].type ||
  584. tokensL[i].value !== tokensR[i].value
  585. ) {
  586. return false;
  587. }
  588. }
  589. return true;
  590. }
  591. /**
  592. * Check if the given node is a true logical expression or not.
  593. *
  594. * The three binary expressions logical-or (`||`), logical-and (`&&`), and
  595. * coalesce (`??`) are known as `ShortCircuitExpression`.
  596. * But ESTree represents those by `LogicalExpression` node.
  597. *
  598. * This function rejects coalesce expressions of `LogicalExpression` node.
  599. * @param {ASTNode} node The node to check.
  600. * @returns {boolean} `true` if the node is `&&` or `||`.
  601. * @see https://tc39.es/ecma262/#prod-ShortCircuitExpression
  602. */
  603. function isLogicalExpression(node) {
  604. return (
  605. node.type === "LogicalExpression" &&
  606. (node.operator === "&&" || node.operator === "||")
  607. );
  608. }
  609. /**
  610. * Check if the given node is a nullish coalescing expression or not.
  611. *
  612. * The three binary expressions logical-or (`||`), logical-and (`&&`), and
  613. * coalesce (`??`) are known as `ShortCircuitExpression`.
  614. * But ESTree represents those by `LogicalExpression` node.
  615. *
  616. * This function finds only coalesce expressions of `LogicalExpression` node.
  617. * @param {ASTNode} node The node to check.
  618. * @returns {boolean} `true` if the node is `??`.
  619. */
  620. function isCoalesceExpression(node) {
  621. return node.type === "LogicalExpression" && node.operator === "??";
  622. }
  623. /**
  624. * Check if given two nodes are the pair of a logical expression and a coalesce expression.
  625. * @param {ASTNode} left A node to check.
  626. * @param {ASTNode} right Another node to check.
  627. * @returns {boolean} `true` if the two nodes are the pair of a logical expression and a coalesce expression.
  628. */
  629. function isMixedLogicalAndCoalesceExpressions(left, right) {
  630. return (
  631. (isLogicalExpression(left) && isCoalesceExpression(right)) ||
  632. (isCoalesceExpression(left) && isLogicalExpression(right))
  633. );
  634. }
  635. //------------------------------------------------------------------------------
  636. // Public Interface
  637. //------------------------------------------------------------------------------
  638. module.exports = {
  639. COMMENTS_IGNORE_PATTERN,
  640. LINEBREAKS,
  641. LINEBREAK_MATCHER: lineBreakPattern,
  642. SHEBANG_MATCHER: shebangPattern,
  643. STATEMENT_LIST_PARENTS,
  644. /**
  645. * Determines whether two adjacent tokens are on the same line.
  646. * @param {Object} left The left token object.
  647. * @param {Object} right The right token object.
  648. * @returns {boolean} Whether or not the tokens are on the same line.
  649. * @public
  650. */
  651. isTokenOnSameLine(left, right) {
  652. return left.loc.end.line === right.loc.start.line;
  653. },
  654. isNullOrUndefined,
  655. isCallee,
  656. isES5Constructor,
  657. getUpperFunction,
  658. isFunction,
  659. isLoop,
  660. isInLoop,
  661. isArrayFromMethod,
  662. isParenthesised,
  663. createGlobalLinebreakMatcher,
  664. equalTokens,
  665. isArrowToken,
  666. isClosingBraceToken,
  667. isClosingBracketToken,
  668. isClosingParenToken,
  669. isColonToken,
  670. isCommaToken,
  671. isCommentToken,
  672. isDotToken,
  673. isQuestionDotToken,
  674. isKeywordToken,
  675. isNotClosingBraceToken: negate(isClosingBraceToken),
  676. isNotClosingBracketToken: negate(isClosingBracketToken),
  677. isNotClosingParenToken: negate(isClosingParenToken),
  678. isNotColonToken: negate(isColonToken),
  679. isNotCommaToken: negate(isCommaToken),
  680. isNotDotToken: negate(isDotToken),
  681. isNotQuestionDotToken: negate(isQuestionDotToken),
  682. isNotOpeningBraceToken: negate(isOpeningBraceToken),
  683. isNotOpeningBracketToken: negate(isOpeningBracketToken),
  684. isNotOpeningParenToken: negate(isOpeningParenToken),
  685. isNotSemicolonToken: negate(isSemicolonToken),
  686. isOpeningBraceToken,
  687. isOpeningBracketToken,
  688. isOpeningParenToken,
  689. isSemicolonToken,
  690. /**
  691. * Checks whether or not a given node is a string literal.
  692. * @param {ASTNode} node A node to check.
  693. * @returns {boolean} `true` if the node is a string literal.
  694. */
  695. isStringLiteral(node) {
  696. return (
  697. (node.type === "Literal" && typeof node.value === "string") ||
  698. node.type === "TemplateLiteral"
  699. );
  700. },
  701. /**
  702. * Checks whether a given node is a breakable statement or not.
  703. * The node is breakable if the node is one of the following type:
  704. *
  705. * - DoWhileStatement
  706. * - ForInStatement
  707. * - ForOfStatement
  708. * - ForStatement
  709. * - SwitchStatement
  710. * - WhileStatement
  711. * @param {ASTNode} node A node to check.
  712. * @returns {boolean} `true` if the node is breakable.
  713. */
  714. isBreakableStatement(node) {
  715. return breakableTypePattern.test(node.type);
  716. },
  717. /**
  718. * Gets references which are non initializer and writable.
  719. * @param {Reference[]} references An array of references.
  720. * @returns {Reference[]} An array of only references which are non initializer and writable.
  721. * @public
  722. */
  723. getModifyingReferences(references) {
  724. return references.filter(isModifyingReference);
  725. },
  726. /**
  727. * Validate that a string passed in is surrounded by the specified character
  728. * @param {string} val The text to check.
  729. * @param {string} character The character to see if it's surrounded by.
  730. * @returns {boolean} True if the text is surrounded by the character, false if not.
  731. * @private
  732. */
  733. isSurroundedBy(val, character) {
  734. return val[0] === character && val[val.length - 1] === character;
  735. },
  736. /**
  737. * Returns whether the provided node is an ESLint directive comment or not
  738. * @param {Line|Block} node The comment token to be checked
  739. * @returns {boolean} `true` if the node is an ESLint directive comment
  740. */
  741. isDirectiveComment(node) {
  742. const comment = node.value.trim();
  743. return (
  744. node.type === "Line" && comment.indexOf("eslint-") === 0 ||
  745. node.type === "Block" && (
  746. comment.indexOf("global ") === 0 ||
  747. comment.indexOf("eslint ") === 0 ||
  748. comment.indexOf("eslint-") === 0
  749. )
  750. );
  751. },
  752. /**
  753. * Gets the trailing statement of a given node.
  754. *
  755. * if (code)
  756. * consequent;
  757. *
  758. * When taking this `IfStatement`, returns `consequent;` statement.
  759. * @param {ASTNode} A node to get.
  760. * @returns {ASTNode|null} The trailing statement's node.
  761. */
  762. getTrailingStatement: esutils.ast.trailingStatement,
  763. /**
  764. * Finds the variable by a given name in a given scope and its upper scopes.
  765. * @param {eslint-scope.Scope} initScope A scope to start find.
  766. * @param {string} name A variable name to find.
  767. * @returns {eslint-scope.Variable|null} A found variable or `null`.
  768. */
  769. getVariableByName(initScope, name) {
  770. let scope = initScope;
  771. while (scope) {
  772. const variable = scope.set.get(name);
  773. if (variable) {
  774. return variable;
  775. }
  776. scope = scope.upper;
  777. }
  778. return null;
  779. },
  780. /**
  781. * Checks whether or not a given function node is the default `this` binding.
  782. *
  783. * First, this checks the node:
  784. *
  785. * - The function name does not start with uppercase. It's a convention to capitalize the names
  786. * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`.
  787. * - The function does not have a JSDoc comment that has a @this tag.
  788. *
  789. * Next, this checks the location of the node.
  790. * If the location is below, this judges `this` is valid.
  791. *
  792. * - The location is not on an object literal.
  793. * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous
  794. * functions only, as the name of the variable is considered to be the name of the function in this case.
  795. * This check is not performed if `capIsConstructor` is set to `false`.
  796. * - The location is not on an ES2015 class.
  797. * - Its `bind`/`call`/`apply` method is not called directly.
  798. * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given.
  799. * @param {ASTNode} node A function node to check.
  800. * @param {SourceCode} sourceCode A SourceCode instance to get comments.
  801. * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts
  802. * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors.
  803. * @returns {boolean} The function node is the default `this` binding.
  804. */
  805. isDefaultThisBinding(node, sourceCode, { capIsConstructor = true } = {}) {
  806. if (
  807. (capIsConstructor && isES5Constructor(node)) ||
  808. hasJSDocThisTag(node, sourceCode)
  809. ) {
  810. return false;
  811. }
  812. const isAnonymous = node.id === null;
  813. let currentNode = node;
  814. while (currentNode) {
  815. const parent = currentNode.parent;
  816. switch (parent.type) {
  817. /*
  818. * Looks up the destination.
  819. * e.g., obj.foo = nativeFoo || function foo() { ... };
  820. */
  821. case "LogicalExpression":
  822. case "ConditionalExpression":
  823. case "ChainExpression":
  824. currentNode = parent;
  825. break;
  826. /*
  827. * If the upper function is IIFE, checks the destination of the return value.
  828. * e.g.
  829. * obj.foo = (function() {
  830. * // setup...
  831. * return function foo() { ... };
  832. * })();
  833. * obj.foo = (() =>
  834. * function foo() { ... }
  835. * )();
  836. */
  837. case "ReturnStatement": {
  838. const func = getUpperFunction(parent);
  839. if (func === null || !isCallee(func)) {
  840. return true;
  841. }
  842. currentNode = func.parent;
  843. break;
  844. }
  845. case "ArrowFunctionExpression":
  846. if (currentNode !== parent.body || !isCallee(parent)) {
  847. return true;
  848. }
  849. currentNode = parent.parent;
  850. break;
  851. /*
  852. * e.g.
  853. * var obj = { foo() { ... } };
  854. * var obj = { foo: function() { ... } };
  855. * class A { constructor() { ... } }
  856. * class A { foo() { ... } }
  857. * class A { get foo() { ... } }
  858. * class A { set foo() { ... } }
  859. * class A { static foo() { ... } }
  860. */
  861. case "Property":
  862. case "MethodDefinition":
  863. return parent.value !== currentNode;
  864. /*
  865. * e.g.
  866. * obj.foo = function foo() { ... };
  867. * Foo = function() { ... };
  868. * [obj.foo = function foo() { ... }] = a;
  869. * [Foo = function() { ... }] = a;
  870. */
  871. case "AssignmentExpression":
  872. case "AssignmentPattern":
  873. if (parent.left.type === "MemberExpression") {
  874. return false;
  875. }
  876. if (
  877. capIsConstructor &&
  878. isAnonymous &&
  879. parent.left.type === "Identifier" &&
  880. startsWithUpperCase(parent.left.name)
  881. ) {
  882. return false;
  883. }
  884. return true;
  885. /*
  886. * e.g.
  887. * var Foo = function() { ... };
  888. */
  889. case "VariableDeclarator":
  890. return !(
  891. capIsConstructor &&
  892. isAnonymous &&
  893. parent.init === currentNode &&
  894. parent.id.type === "Identifier" &&
  895. startsWithUpperCase(parent.id.name)
  896. );
  897. /*
  898. * e.g.
  899. * var foo = function foo() { ... }.bind(obj);
  900. * (function foo() { ... }).call(obj);
  901. * (function foo() { ... }).apply(obj, []);
  902. */
  903. case "MemberExpression":
  904. if (
  905. parent.object === currentNode &&
  906. isSpecificMemberAccess(parent, null, bindOrCallOrApplyPattern)
  907. ) {
  908. const maybeCalleeNode = parent.parent.type === "ChainExpression"
  909. ? parent.parent
  910. : parent;
  911. return !(
  912. isCallee(maybeCalleeNode) &&
  913. maybeCalleeNode.parent.arguments.length >= 1 &&
  914. !isNullOrUndefined(maybeCalleeNode.parent.arguments[0])
  915. );
  916. }
  917. return true;
  918. /*
  919. * e.g.
  920. * Reflect.apply(function() {}, obj, []);
  921. * Array.from([], function() {}, obj);
  922. * list.forEach(function() {}, obj);
  923. */
  924. case "CallExpression":
  925. if (isReflectApply(parent.callee)) {
  926. return (
  927. parent.arguments.length !== 3 ||
  928. parent.arguments[0] !== currentNode ||
  929. isNullOrUndefined(parent.arguments[1])
  930. );
  931. }
  932. if (isArrayFromMethod(parent.callee)) {
  933. return (
  934. parent.arguments.length !== 3 ||
  935. parent.arguments[1] !== currentNode ||
  936. isNullOrUndefined(parent.arguments[2])
  937. );
  938. }
  939. if (isMethodWhichHasThisArg(parent.callee)) {
  940. return (
  941. parent.arguments.length !== 2 ||
  942. parent.arguments[0] !== currentNode ||
  943. isNullOrUndefined(parent.arguments[1])
  944. );
  945. }
  946. return true;
  947. // Otherwise `this` is default.
  948. default:
  949. return true;
  950. }
  951. }
  952. /* istanbul ignore next */
  953. return true;
  954. },
  955. /**
  956. * Get the precedence level based on the node type
  957. * @param {ASTNode} node node to evaluate
  958. * @returns {int} precedence level
  959. * @private
  960. */
  961. getPrecedence(node) {
  962. switch (node.type) {
  963. case "SequenceExpression":
  964. return 0;
  965. case "AssignmentExpression":
  966. case "ArrowFunctionExpression":
  967. case "YieldExpression":
  968. return 1;
  969. case "ConditionalExpression":
  970. return 3;
  971. case "LogicalExpression":
  972. switch (node.operator) {
  973. case "||":
  974. case "??":
  975. return 4;
  976. case "&&":
  977. return 5;
  978. // no default
  979. }
  980. /* falls through */
  981. case "BinaryExpression":
  982. switch (node.operator) {
  983. case "|":
  984. return 6;
  985. case "^":
  986. return 7;
  987. case "&":
  988. return 8;
  989. case "==":
  990. case "!=":
  991. case "===":
  992. case "!==":
  993. return 9;
  994. case "<":
  995. case "<=":
  996. case ">":
  997. case ">=":
  998. case "in":
  999. case "instanceof":
  1000. return 10;
  1001. case "<<":
  1002. case ">>":
  1003. case ">>>":
  1004. return 11;
  1005. case "+":
  1006. case "-":
  1007. return 12;
  1008. case "*":
  1009. case "/":
  1010. case "%":
  1011. return 13;
  1012. case "**":
  1013. return 15;
  1014. // no default
  1015. }
  1016. /* falls through */
  1017. case "UnaryExpression":
  1018. case "AwaitExpression":
  1019. return 16;
  1020. case "UpdateExpression":
  1021. return 17;
  1022. case "CallExpression":
  1023. case "ChainExpression":
  1024. case "ImportExpression":
  1025. return 18;
  1026. case "NewExpression":
  1027. return 19;
  1028. default:
  1029. return 20;
  1030. }
  1031. },
  1032. /**
  1033. * Checks whether the given node is an empty block node or not.
  1034. * @param {ASTNode|null} node The node to check.
  1035. * @returns {boolean} `true` if the node is an empty block.
  1036. */
  1037. isEmptyBlock(node) {
  1038. return Boolean(node && node.type === "BlockStatement" && node.body.length === 0);
  1039. },
  1040. /**
  1041. * Checks whether the given node is an empty function node or not.
  1042. * @param {ASTNode|null} node The node to check.
  1043. * @returns {boolean} `true` if the node is an empty function.
  1044. */
  1045. isEmptyFunction(node) {
  1046. return isFunction(node) && module.exports.isEmptyBlock(node.body);
  1047. },
  1048. /**
  1049. * Get directives from directive prologue of a Program or Function node.
  1050. * @param {ASTNode} node The node to check.
  1051. * @returns {ASTNode[]} The directives found in the directive prologue.
  1052. */
  1053. getDirectivePrologue(node) {
  1054. const directives = [];
  1055. // Directive prologues only occur at the top of files or functions.
  1056. if (
  1057. node.type === "Program" ||
  1058. node.type === "FunctionDeclaration" ||
  1059. node.type === "FunctionExpression" ||
  1060. /*
  1061. * Do not check arrow functions with implicit return.
  1062. * `() => "use strict";` returns the string `"use strict"`.
  1063. */
  1064. (node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement")
  1065. ) {
  1066. const statements = node.type === "Program" ? node.body : node.body.body;
  1067. for (const statement of statements) {
  1068. if (
  1069. statement.type === "ExpressionStatement" &&
  1070. statement.expression.type === "Literal"
  1071. ) {
  1072. directives.push(statement);
  1073. } else {
  1074. break;
  1075. }
  1076. }
  1077. }
  1078. return directives;
  1079. },
  1080. /**
  1081. * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added
  1082. * after the node will be parsed as a decimal point, rather than a property-access dot.
  1083. * @param {ASTNode} node The node to check.
  1084. * @returns {boolean} `true` if this node is a decimal integer.
  1085. * @example
  1086. *
  1087. * 5 // true
  1088. * 5. // false
  1089. * 5.0 // false
  1090. * 05 // false
  1091. * 0x5 // false
  1092. * 0b101 // false
  1093. * 0o5 // false
  1094. * 5e0 // false
  1095. * '5' // false
  1096. * 5n // false
  1097. */
  1098. isDecimalInteger(node) {
  1099. return node.type === "Literal" && typeof node.value === "number" &&
  1100. DECIMAL_INTEGER_PATTERN.test(node.raw);
  1101. },
  1102. /**
  1103. * Determines whether this token is a decimal integer numeric token.
  1104. * This is similar to isDecimalInteger(), but for tokens.
  1105. * @param {Token} token The token to check.
  1106. * @returns {boolean} `true` if this token is a decimal integer.
  1107. */
  1108. isDecimalIntegerNumericToken(token) {
  1109. return token.type === "Numeric" && DECIMAL_INTEGER_PATTERN.test(token.value);
  1110. },
  1111. /**
  1112. * Gets the name and kind of the given function node.
  1113. *
  1114. * - `function foo() {}` .................... `function 'foo'`
  1115. * - `(function foo() {})` .................. `function 'foo'`
  1116. * - `(function() {})` ...................... `function`
  1117. * - `function* foo() {}` ................... `generator function 'foo'`
  1118. * - `(function* foo() {})` ................. `generator function 'foo'`
  1119. * - `(function*() {})` ..................... `generator function`
  1120. * - `() => {}` ............................. `arrow function`
  1121. * - `async () => {}` ....................... `async arrow function`
  1122. * - `({ foo: function foo() {} })` ......... `method 'foo'`
  1123. * - `({ foo: function() {} })` ............. `method 'foo'`
  1124. * - `({ ['foo']: function() {} })` ......... `method 'foo'`
  1125. * - `({ [foo]: function() {} })` ........... `method`
  1126. * - `({ foo() {} })` ....................... `method 'foo'`
  1127. * - `({ foo: function* foo() {} })` ........ `generator method 'foo'`
  1128. * - `({ foo: function*() {} })` ............ `generator method 'foo'`
  1129. * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'`
  1130. * - `({ [foo]: function*() {} })` .......... `generator method`
  1131. * - `({ *foo() {} })` ...................... `generator method 'foo'`
  1132. * - `({ foo: async function foo() {} })` ... `async method 'foo'`
  1133. * - `({ foo: async function() {} })` ....... `async method 'foo'`
  1134. * - `({ ['foo']: async function() {} })` ... `async method 'foo'`
  1135. * - `({ [foo]: async function() {} })` ..... `async method`
  1136. * - `({ async foo() {} })` ................. `async method 'foo'`
  1137. * - `({ get foo() {} })` ................... `getter 'foo'`
  1138. * - `({ set foo(a) {} })` .................. `setter 'foo'`
  1139. * - `class A { constructor() {} }` ......... `constructor`
  1140. * - `class A { foo() {} }` ................. `method 'foo'`
  1141. * - `class A { *foo() {} }` ................ `generator method 'foo'`
  1142. * - `class A { async foo() {} }` ........... `async method 'foo'`
  1143. * - `class A { ['foo']() {} }` ............. `method 'foo'`
  1144. * - `class A { *['foo']() {} }` ............ `generator method 'foo'`
  1145. * - `class A { async ['foo']() {} }` ....... `async method 'foo'`
  1146. * - `class A { [foo]() {} }` ............... `method`
  1147. * - `class A { *[foo]() {} }` .............. `generator method`
  1148. * - `class A { async [foo]() {} }` ......... `async method`
  1149. * - `class A { get foo() {} }` ............. `getter 'foo'`
  1150. * - `class A { set foo(a) {} }` ............ `setter 'foo'`
  1151. * - `class A { static foo() {} }` .......... `static method 'foo'`
  1152. * - `class A { static *foo() {} }` ......... `static generator method 'foo'`
  1153. * - `class A { static async foo() {} }` .... `static async method 'foo'`
  1154. * - `class A { static get foo() {} }` ...... `static getter 'foo'`
  1155. * - `class A { static set foo(a) {} }` ..... `static setter 'foo'`
  1156. * @param {ASTNode} node The function node to get.
  1157. * @returns {string} The name and kind of the function node.
  1158. */
  1159. getFunctionNameWithKind(node) {
  1160. const parent = node.parent;
  1161. const tokens = [];
  1162. if (parent.type === "MethodDefinition" && parent.static) {
  1163. tokens.push("static");
  1164. }
  1165. if (node.async) {
  1166. tokens.push("async");
  1167. }
  1168. if (node.generator) {
  1169. tokens.push("generator");
  1170. }
  1171. if (node.type === "ArrowFunctionExpression") {
  1172. tokens.push("arrow", "function");
  1173. } else if (parent.type === "Property" || parent.type === "MethodDefinition") {
  1174. if (parent.kind === "constructor") {
  1175. return "constructor";
  1176. }
  1177. if (parent.kind === "get") {
  1178. tokens.push("getter");
  1179. } else if (parent.kind === "set") {
  1180. tokens.push("setter");
  1181. } else {
  1182. tokens.push("method");
  1183. }
  1184. } else {
  1185. tokens.push("function");
  1186. }
  1187. if (node.id) {
  1188. tokens.push(`'${node.id.name}'`);
  1189. } else {
  1190. const name = getStaticPropertyName(parent);
  1191. if (name !== null) {
  1192. tokens.push(`'${name}'`);
  1193. }
  1194. }
  1195. return tokens.join(" ");
  1196. },
  1197. /**
  1198. * Gets the location of the given function node for reporting.
  1199. *
  1200. * - `function foo() {}`
  1201. * ^^^^^^^^^^^^
  1202. * - `(function foo() {})`
  1203. * ^^^^^^^^^^^^
  1204. * - `(function() {})`
  1205. * ^^^^^^^^
  1206. * - `function* foo() {}`
  1207. * ^^^^^^^^^^^^^
  1208. * - `(function* foo() {})`
  1209. * ^^^^^^^^^^^^^
  1210. * - `(function*() {})`
  1211. * ^^^^^^^^^
  1212. * - `() => {}`
  1213. * ^^
  1214. * - `async () => {}`
  1215. * ^^
  1216. * - `({ foo: function foo() {} })`
  1217. * ^^^^^^^^^^^^^^^^^
  1218. * - `({ foo: function() {} })`
  1219. * ^^^^^^^^^^^^^
  1220. * - `({ ['foo']: function() {} })`
  1221. * ^^^^^^^^^^^^^^^^^
  1222. * - `({ [foo]: function() {} })`
  1223. * ^^^^^^^^^^^^^^^
  1224. * - `({ foo() {} })`
  1225. * ^^^
  1226. * - `({ foo: function* foo() {} })`
  1227. * ^^^^^^^^^^^^^^^^^^
  1228. * - `({ foo: function*() {} })`
  1229. * ^^^^^^^^^^^^^^
  1230. * - `({ ['foo']: function*() {} })`
  1231. * ^^^^^^^^^^^^^^^^^^
  1232. * - `({ [foo]: function*() {} })`
  1233. * ^^^^^^^^^^^^^^^^
  1234. * - `({ *foo() {} })`
  1235. * ^^^^
  1236. * - `({ foo: async function foo() {} })`
  1237. * ^^^^^^^^^^^^^^^^^^^^^^^
  1238. * - `({ foo: async function() {} })`
  1239. * ^^^^^^^^^^^^^^^^^^^
  1240. * - `({ ['foo']: async function() {} })`
  1241. * ^^^^^^^^^^^^^^^^^^^^^^^
  1242. * - `({ [foo]: async function() {} })`
  1243. * ^^^^^^^^^^^^^^^^^^^^^
  1244. * - `({ async foo() {} })`
  1245. * ^^^^^^^^^
  1246. * - `({ get foo() {} })`
  1247. * ^^^^^^^
  1248. * - `({ set foo(a) {} })`
  1249. * ^^^^^^^
  1250. * - `class A { constructor() {} }`
  1251. * ^^^^^^^^^^^
  1252. * - `class A { foo() {} }`
  1253. * ^^^
  1254. * - `class A { *foo() {} }`
  1255. * ^^^^
  1256. * - `class A { async foo() {} }`
  1257. * ^^^^^^^^^
  1258. * - `class A { ['foo']() {} }`
  1259. * ^^^^^^^
  1260. * - `class A { *['foo']() {} }`
  1261. * ^^^^^^^^
  1262. * - `class A { async ['foo']() {} }`
  1263. * ^^^^^^^^^^^^^
  1264. * - `class A { [foo]() {} }`
  1265. * ^^^^^
  1266. * - `class A { *[foo]() {} }`
  1267. * ^^^^^^
  1268. * - `class A { async [foo]() {} }`
  1269. * ^^^^^^^^^^^
  1270. * - `class A { get foo() {} }`
  1271. * ^^^^^^^
  1272. * - `class A { set foo(a) {} }`
  1273. * ^^^^^^^
  1274. * - `class A { static foo() {} }`
  1275. * ^^^^^^^^^^
  1276. * - `class A { static *foo() {} }`
  1277. * ^^^^^^^^^^^
  1278. * - `class A { static async foo() {} }`
  1279. * ^^^^^^^^^^^^^^^^
  1280. * - `class A { static get foo() {} }`
  1281. * ^^^^^^^^^^^^^^
  1282. * - `class A { static set foo(a) {} }`
  1283. * ^^^^^^^^^^^^^^
  1284. * @param {ASTNode} node The function node to get.
  1285. * @param {SourceCode} sourceCode The source code object to get tokens.
  1286. * @returns {string} The location of the function node for reporting.
  1287. */
  1288. getFunctionHeadLoc(node, sourceCode) {
  1289. const parent = node.parent;
  1290. let start = null;
  1291. let end = null;
  1292. if (node.type === "ArrowFunctionExpression") {
  1293. const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
  1294. start = arrowToken.loc.start;
  1295. end = arrowToken.loc.end;
  1296. } else if (parent.type === "Property" || parent.type === "MethodDefinition") {
  1297. start = parent.loc.start;
  1298. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  1299. } else {
  1300. start = node.loc.start;
  1301. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  1302. }
  1303. return {
  1304. start: Object.assign({}, start),
  1305. end: Object.assign({}, end)
  1306. };
  1307. },
  1308. /**
  1309. * Gets next location when the result is not out of bound, otherwise returns null.
  1310. *
  1311. * Assumptions:
  1312. *
  1313. * - The given location represents a valid location in the given source code.
  1314. * - Columns are 0-based.
  1315. * - Lines are 1-based.
  1316. * - Column immediately after the last character in a line (not incl. linebreaks) is considered to be a valid location.
  1317. * - If the source code ends with a linebreak, `sourceCode.lines` array will have an extra element (empty string) at the end.
  1318. * The start (column 0) of that extra line is considered to be a valid location.
  1319. *
  1320. * Examples of successive locations (line, column):
  1321. *
  1322. * code: foo
  1323. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> null
  1324. *
  1325. * code: foo<LF>
  1326. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
  1327. *
  1328. * code: foo<CR><LF>
  1329. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
  1330. *
  1331. * code: a<LF>b
  1332. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> null
  1333. *
  1334. * code: a<LF>b<LF>
  1335. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
  1336. *
  1337. * code: a<CR><LF>b<CR><LF>
  1338. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
  1339. *
  1340. * code: a<LF><LF>
  1341. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (3, 0) -> null
  1342. *
  1343. * code: <LF>
  1344. * locations: (1, 0) -> (2, 0) -> null
  1345. *
  1346. * code:
  1347. * locations: (1, 0) -> null
  1348. * @param {SourceCode} sourceCode The sourceCode
  1349. * @param {{line: number, column: number}} location The location
  1350. * @returns {{line: number, column: number} | null} Next location
  1351. */
  1352. getNextLocation(sourceCode, { line, column }) {
  1353. if (column < sourceCode.lines[line - 1].length) {
  1354. return {
  1355. line,
  1356. column: column + 1
  1357. };
  1358. }
  1359. if (line < sourceCode.lines.length) {
  1360. return {
  1361. line: line + 1,
  1362. column: 0
  1363. };
  1364. }
  1365. return null;
  1366. },
  1367. /**
  1368. * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses
  1369. * surrounding the node.
  1370. * @param {SourceCode} sourceCode The source code object
  1371. * @param {ASTNode} node An expression node
  1372. * @returns {string} The text representing the node, with all surrounding parentheses included
  1373. */
  1374. getParenthesisedText(sourceCode, node) {
  1375. let leftToken = sourceCode.getFirstToken(node);
  1376. let rightToken = sourceCode.getLastToken(node);
  1377. while (
  1378. sourceCode.getTokenBefore(leftToken) &&
  1379. sourceCode.getTokenBefore(leftToken).type === "Punctuator" &&
  1380. sourceCode.getTokenBefore(leftToken).value === "(" &&
  1381. sourceCode.getTokenAfter(rightToken) &&
  1382. sourceCode.getTokenAfter(rightToken).type === "Punctuator" &&
  1383. sourceCode.getTokenAfter(rightToken).value === ")"
  1384. ) {
  1385. leftToken = sourceCode.getTokenBefore(leftToken);
  1386. rightToken = sourceCode.getTokenAfter(rightToken);
  1387. }
  1388. return sourceCode.getText().slice(leftToken.range[0], rightToken.range[1]);
  1389. },
  1390. /*
  1391. * Determine if a node has a possiblity to be an Error object
  1392. * @param {ASTNode} node ASTNode to check
  1393. * @returns {boolean} True if there is a chance it contains an Error obj
  1394. */
  1395. couldBeError(node) {
  1396. switch (node.type) {
  1397. case "Identifier":
  1398. case "CallExpression":
  1399. case "NewExpression":
  1400. case "MemberExpression":
  1401. case "TaggedTemplateExpression":
  1402. case "YieldExpression":
  1403. case "AwaitExpression":
  1404. case "ChainExpression":
  1405. return true; // possibly an error object.
  1406. case "AssignmentExpression":
  1407. return module.exports.couldBeError(node.right);
  1408. case "SequenceExpression": {
  1409. const exprs = node.expressions;
  1410. return exprs.length !== 0 && module.exports.couldBeError(exprs[exprs.length - 1]);
  1411. }
  1412. case "LogicalExpression":
  1413. return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right);
  1414. case "ConditionalExpression":
  1415. return module.exports.couldBeError(node.consequent) || module.exports.couldBeError(node.alternate);
  1416. default:
  1417. return false;
  1418. }
  1419. },
  1420. /**
  1421. * Check if a given node is a numeric literal or not.
  1422. * @param {ASTNode} node The node to check.
  1423. * @returns {boolean} `true` if the node is a number or bigint literal.
  1424. */
  1425. isNumericLiteral(node) {
  1426. return (
  1427. node.type === "Literal" &&
  1428. (typeof node.value === "number" || Boolean(node.bigint))
  1429. );
  1430. },
  1431. /**
  1432. * Determines whether two tokens can safely be placed next to each other without merging into a single token
  1433. * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used.
  1434. * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used.
  1435. * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed
  1436. * next to each other, behavior is undefined (although it should return `true` in most cases).
  1437. */
  1438. canTokensBeAdjacent(leftValue, rightValue) {
  1439. const espreeOptions = {
  1440. ecmaVersion: espree.latestEcmaVersion,
  1441. comment: true,
  1442. range: true
  1443. };
  1444. let leftToken;
  1445. if (typeof leftValue === "string") {
  1446. let tokens;
  1447. try {
  1448. tokens = espree.tokenize(leftValue, espreeOptions);
  1449. } catch {
  1450. return false;
  1451. }
  1452. const comments = tokens.comments;
  1453. leftToken = tokens[tokens.length - 1];
  1454. if (comments.length) {
  1455. const lastComment = comments[comments.length - 1];
  1456. if (lastComment.range[0] > leftToken.range[0]) {
  1457. leftToken = lastComment;
  1458. }
  1459. }
  1460. } else {
  1461. leftToken = leftValue;
  1462. }
  1463. if (leftToken.type === "Shebang") {
  1464. return false;
  1465. }
  1466. let rightToken;
  1467. if (typeof rightValue === "string") {
  1468. let tokens;
  1469. try {
  1470. tokens = espree.tokenize(rightValue, espreeOptions);
  1471. } catch {
  1472. return false;
  1473. }
  1474. const comments = tokens.comments;
  1475. rightToken = tokens[0];
  1476. if (comments.length) {
  1477. const firstComment = comments[0];
  1478. if (firstComment.range[0] < rightToken.range[0]) {
  1479. rightToken = firstComment;
  1480. }
  1481. }
  1482. } else {
  1483. rightToken = rightValue;
  1484. }
  1485. if (leftToken.type === "Punctuator" || rightToken.type === "Punctuator") {
  1486. if (leftToken.type === "Punctuator" && rightToken.type === "Punctuator") {
  1487. const PLUS_TOKENS = new Set(["+", "++"]);
  1488. const MINUS_TOKENS = new Set(["-", "--"]);
  1489. return !(
  1490. PLUS_TOKENS.has(leftToken.value) && PLUS_TOKENS.has(rightToken.value) ||
  1491. MINUS_TOKENS.has(leftToken.value) && MINUS_TOKENS.has(rightToken.value)
  1492. );
  1493. }
  1494. if (leftToken.type === "Punctuator" && leftToken.value === "/") {
  1495. return !["Block", "Line", "RegularExpression"].includes(rightToken.type);
  1496. }
  1497. return true;
  1498. }
  1499. if (
  1500. leftToken.type === "String" || rightToken.type === "String" ||
  1501. leftToken.type === "Template" || rightToken.type === "Template"
  1502. ) {
  1503. return true;
  1504. }
  1505. if (leftToken.type !== "Numeric" && rightToken.type === "Numeric" && rightToken.value.startsWith(".")) {
  1506. return true;
  1507. }
  1508. if (leftToken.type === "Block" || rightToken.type === "Block" || rightToken.type === "Line") {
  1509. return true;
  1510. }
  1511. return false;
  1512. },
  1513. /**
  1514. * Get the `loc` object of a given name in a `/*globals` directive comment.
  1515. * @param {SourceCode} sourceCode The source code to convert index to loc.
  1516. * @param {Comment} comment The `/*globals` directive comment which include the name.
  1517. * @param {string} name The name to find.
  1518. * @returns {SourceLocation} The `loc` object.
  1519. */
  1520. getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) {
  1521. const namePattern = new RegExp(`[\\s,]${lodash.escapeRegExp(name)}(?:$|[\\s,:])`, "gu");
  1522. // To ignore the first text "global".
  1523. namePattern.lastIndex = comment.value.indexOf("global") + 6;
  1524. // Search a given variable name.
  1525. const match = namePattern.exec(comment.value);
  1526. // Convert the index to loc.
  1527. const start = sourceCode.getLocFromIndex(
  1528. comment.range[0] +
  1529. "/*".length +
  1530. (match ? match.index + 1 : 0)
  1531. );
  1532. const end = {
  1533. line: start.line,
  1534. column: start.column + (match ? name.length : 1)
  1535. };
  1536. return { start, end };
  1537. },
  1538. /**
  1539. * Determines whether the given raw string contains an octal escape sequence.
  1540. *
  1541. * "\1", "\2" ... "\7"
  1542. * "\00", "\01" ... "\09"
  1543. *
  1544. * "\0", when not followed by a digit, is not an octal escape sequence.
  1545. * @param {string} rawString A string in its raw representation.
  1546. * @returns {boolean} `true` if the string contains at least one octal escape sequence.
  1547. */
  1548. hasOctalEscapeSequence(rawString) {
  1549. return OCTAL_ESCAPE_PATTERN.test(rawString);
  1550. },
  1551. isLogicalExpression,
  1552. isCoalesceExpression,
  1553. isMixedLogicalAndCoalesceExpressions,
  1554. isNullLiteral,
  1555. getStaticStringValue,
  1556. getStaticPropertyName,
  1557. skipChainExpression,
  1558. isSpecificId,
  1559. isSpecificMemberAccess,
  1560. equalLiteralValue,
  1561. isSameReference
  1562. };