版博士V2.0程序
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.
 
 
 
 

687 lines
25 KiB

  1. /**
  2. * @fileoverview Abstraction of JavaScript source code.
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const
  10. { isCommentToken } = require("@eslint-community/eslint-utils"),
  11. TokenStore = require("./token-store"),
  12. astUtils = require("../shared/ast-utils"),
  13. Traverser = require("../shared/traverser");
  14. //------------------------------------------------------------------------------
  15. // Type Definitions
  16. //------------------------------------------------------------------------------
  17. /** @typedef {import("eslint-scope").Variable} Variable */
  18. //------------------------------------------------------------------------------
  19. // Private
  20. //------------------------------------------------------------------------------
  21. /**
  22. * Validates that the given AST has the required information.
  23. * @param {ASTNode} ast The Program node of the AST to check.
  24. * @throws {Error} If the AST doesn't contain the correct information.
  25. * @returns {void}
  26. * @private
  27. */
  28. function validate(ast) {
  29. if (!ast.tokens) {
  30. throw new Error("AST is missing the tokens array.");
  31. }
  32. if (!ast.comments) {
  33. throw new Error("AST is missing the comments array.");
  34. }
  35. if (!ast.loc) {
  36. throw new Error("AST is missing location information.");
  37. }
  38. if (!ast.range) {
  39. throw new Error("AST is missing range information");
  40. }
  41. }
  42. /**
  43. * Check to see if its a ES6 export declaration.
  44. * @param {ASTNode} astNode An AST node.
  45. * @returns {boolean} whether the given node represents an export declaration.
  46. * @private
  47. */
  48. function looksLikeExport(astNode) {
  49. return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" ||
  50. astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier";
  51. }
  52. /**
  53. * Merges two sorted lists into a larger sorted list in O(n) time.
  54. * @param {Token[]} tokens The list of tokens.
  55. * @param {Token[]} comments The list of comments.
  56. * @returns {Token[]} A sorted list of tokens and comments.
  57. * @private
  58. */
  59. function sortedMerge(tokens, comments) {
  60. const result = [];
  61. let tokenIndex = 0;
  62. let commentIndex = 0;
  63. while (tokenIndex < tokens.length || commentIndex < comments.length) {
  64. if (commentIndex >= comments.length || tokenIndex < tokens.length && tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) {
  65. result.push(tokens[tokenIndex++]);
  66. } else {
  67. result.push(comments[commentIndex++]);
  68. }
  69. }
  70. return result;
  71. }
  72. /**
  73. * Determines if two nodes or tokens overlap.
  74. * @param {ASTNode|Token} first The first node or token to check.
  75. * @param {ASTNode|Token} second The second node or token to check.
  76. * @returns {boolean} True if the two nodes or tokens overlap.
  77. * @private
  78. */
  79. function nodesOrTokensOverlap(first, second) {
  80. return (first.range[0] <= second.range[0] && first.range[1] >= second.range[0]) ||
  81. (second.range[0] <= first.range[0] && second.range[1] >= first.range[0]);
  82. }
  83. /**
  84. * Determines if two nodes or tokens have at least one whitespace character
  85. * between them. Order does not matter. Returns false if the given nodes or
  86. * tokens overlap.
  87. * @param {SourceCode} sourceCode The source code object.
  88. * @param {ASTNode|Token} first The first node or token to check between.
  89. * @param {ASTNode|Token} second The second node or token to check between.
  90. * @param {boolean} checkInsideOfJSXText If `true` is present, check inside of JSXText tokens for backward compatibility.
  91. * @returns {boolean} True if there is a whitespace character between
  92. * any of the tokens found between the two given nodes or tokens.
  93. * @public
  94. */
  95. function isSpaceBetween(sourceCode, first, second, checkInsideOfJSXText) {
  96. if (nodesOrTokensOverlap(first, second)) {
  97. return false;
  98. }
  99. const [startingNodeOrToken, endingNodeOrToken] = first.range[1] <= second.range[0]
  100. ? [first, second]
  101. : [second, first];
  102. const firstToken = sourceCode.getLastToken(startingNodeOrToken) || startingNodeOrToken;
  103. const finalToken = sourceCode.getFirstToken(endingNodeOrToken) || endingNodeOrToken;
  104. let currentToken = firstToken;
  105. while (currentToken !== finalToken) {
  106. const nextToken = sourceCode.getTokenAfter(currentToken, { includeComments: true });
  107. if (
  108. currentToken.range[1] !== nextToken.range[0] ||
  109. /*
  110. * For backward compatibility, check spaces in JSXText.
  111. * https://github.com/eslint/eslint/issues/12614
  112. */
  113. (
  114. checkInsideOfJSXText &&
  115. nextToken !== finalToken &&
  116. nextToken.type === "JSXText" &&
  117. /\s/u.test(nextToken.value)
  118. )
  119. ) {
  120. return true;
  121. }
  122. currentToken = nextToken;
  123. }
  124. return false;
  125. }
  126. //------------------------------------------------------------------------------
  127. // Public Interface
  128. //------------------------------------------------------------------------------
  129. const caches = Symbol("caches");
  130. /**
  131. * Represents parsed source code.
  132. */
  133. class SourceCode extends TokenStore {
  134. /**
  135. * @param {string|Object} textOrConfig The source code text or config object.
  136. * @param {string} textOrConfig.text The source code text.
  137. * @param {ASTNode} textOrConfig.ast The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
  138. * @param {Object|null} textOrConfig.parserServices The parser services.
  139. * @param {ScopeManager|null} textOrConfig.scopeManager The scope of this source code.
  140. * @param {Object|null} textOrConfig.visitorKeys The visitor keys to traverse AST.
  141. * @param {ASTNode} [astIfNoConfig] The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
  142. */
  143. constructor(textOrConfig, astIfNoConfig) {
  144. let text, ast, parserServices, scopeManager, visitorKeys;
  145. // Process overloading.
  146. if (typeof textOrConfig === "string") {
  147. text = textOrConfig;
  148. ast = astIfNoConfig;
  149. } else if (typeof textOrConfig === "object" && textOrConfig !== null) {
  150. text = textOrConfig.text;
  151. ast = textOrConfig.ast;
  152. parserServices = textOrConfig.parserServices;
  153. scopeManager = textOrConfig.scopeManager;
  154. visitorKeys = textOrConfig.visitorKeys;
  155. }
  156. validate(ast);
  157. super(ast.tokens, ast.comments);
  158. /**
  159. * General purpose caching for the class.
  160. */
  161. this[caches] = new Map([
  162. ["scopes", new WeakMap()]
  163. ]);
  164. /**
  165. * The flag to indicate that the source code has Unicode BOM.
  166. * @type {boolean}
  167. */
  168. this.hasBOM = (text.charCodeAt(0) === 0xFEFF);
  169. /**
  170. * The original text source code.
  171. * BOM was stripped from this text.
  172. * @type {string}
  173. */
  174. this.text = (this.hasBOM ? text.slice(1) : text);
  175. /**
  176. * The parsed AST for the source code.
  177. * @type {ASTNode}
  178. */
  179. this.ast = ast;
  180. /**
  181. * The parser services of this source code.
  182. * @type {Object}
  183. */
  184. this.parserServices = parserServices || {};
  185. /**
  186. * The scope of this source code.
  187. * @type {ScopeManager|null}
  188. */
  189. this.scopeManager = scopeManager || null;
  190. /**
  191. * The visitor keys to traverse AST.
  192. * @type {Object}
  193. */
  194. this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS;
  195. // Check the source text for the presence of a shebang since it is parsed as a standard line comment.
  196. const shebangMatched = this.text.match(astUtils.shebangPattern);
  197. const hasShebang = shebangMatched && ast.comments.length && ast.comments[0].value === shebangMatched[1];
  198. if (hasShebang) {
  199. ast.comments[0].type = "Shebang";
  200. }
  201. this.tokensAndComments = sortedMerge(ast.tokens, ast.comments);
  202. /**
  203. * The source code split into lines according to ECMA-262 specification.
  204. * This is done to avoid each rule needing to do so separately.
  205. * @type {string[]}
  206. */
  207. this.lines = [];
  208. this.lineStartIndices = [0];
  209. const lineEndingPattern = astUtils.createGlobalLinebreakMatcher();
  210. let match;
  211. /*
  212. * Previously, this was implemented using a regex that
  213. * matched a sequence of non-linebreak characters followed by a
  214. * linebreak, then adding the lengths of the matches. However,
  215. * this caused a catastrophic backtracking issue when the end
  216. * of a file contained a large number of non-newline characters.
  217. * To avoid this, the current implementation just matches newlines
  218. * and uses match.index to get the correct line start indices.
  219. */
  220. while ((match = lineEndingPattern.exec(this.text))) {
  221. this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1], match.index));
  222. this.lineStartIndices.push(match.index + match[0].length);
  223. }
  224. this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1]));
  225. // Cache for comments found using getComments().
  226. this._commentCache = new WeakMap();
  227. // don't allow modification of this object
  228. Object.freeze(this);
  229. Object.freeze(this.lines);
  230. }
  231. /**
  232. * Split the source code into multiple lines based on the line delimiters.
  233. * @param {string} text Source code as a string.
  234. * @returns {string[]} Array of source code lines.
  235. * @public
  236. */
  237. static splitLines(text) {
  238. return text.split(astUtils.createGlobalLinebreakMatcher());
  239. }
  240. /**
  241. * Gets the source code for the given node.
  242. * @param {ASTNode} [node] The AST node to get the text for.
  243. * @param {int} [beforeCount] The number of characters before the node to retrieve.
  244. * @param {int} [afterCount] The number of characters after the node to retrieve.
  245. * @returns {string} The text representing the AST node.
  246. * @public
  247. */
  248. getText(node, beforeCount, afterCount) {
  249. if (node) {
  250. return this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0),
  251. node.range[1] + (afterCount || 0));
  252. }
  253. return this.text;
  254. }
  255. /**
  256. * Gets the entire source text split into an array of lines.
  257. * @returns {Array} The source text as an array of lines.
  258. * @public
  259. */
  260. getLines() {
  261. return this.lines;
  262. }
  263. /**
  264. * Retrieves an array containing all comments in the source code.
  265. * @returns {ASTNode[]} An array of comment nodes.
  266. * @public
  267. */
  268. getAllComments() {
  269. return this.ast.comments;
  270. }
  271. /**
  272. * Gets all comments for the given node.
  273. * @param {ASTNode} node The AST node to get the comments for.
  274. * @returns {Object} An object containing a leading and trailing array
  275. * of comments indexed by their position.
  276. * @public
  277. * @deprecated replaced by getCommentsBefore(), getCommentsAfter(), and getCommentsInside().
  278. */
  279. getComments(node) {
  280. if (this._commentCache.has(node)) {
  281. return this._commentCache.get(node);
  282. }
  283. const comments = {
  284. leading: [],
  285. trailing: []
  286. };
  287. /*
  288. * Return all comments as leading comments of the Program node when
  289. * there is no executable code.
  290. */
  291. if (node.type === "Program") {
  292. if (node.body.length === 0) {
  293. comments.leading = node.comments;
  294. }
  295. } else {
  296. /*
  297. * Return comments as trailing comments of nodes that only contain
  298. * comments (to mimic the comment attachment behavior present in Espree).
  299. */
  300. if ((node.type === "BlockStatement" || node.type === "ClassBody") && node.body.length === 0 ||
  301. node.type === "ObjectExpression" && node.properties.length === 0 ||
  302. node.type === "ArrayExpression" && node.elements.length === 0 ||
  303. node.type === "SwitchStatement" && node.cases.length === 0
  304. ) {
  305. comments.trailing = this.getTokens(node, {
  306. includeComments: true,
  307. filter: isCommentToken
  308. });
  309. }
  310. /*
  311. * Iterate over tokens before and after node and collect comment tokens.
  312. * Do not include comments that exist outside of the parent node
  313. * to avoid duplication.
  314. */
  315. let currentToken = this.getTokenBefore(node, { includeComments: true });
  316. while (currentToken && isCommentToken(currentToken)) {
  317. if (node.parent && node.parent.type !== "Program" && (currentToken.start < node.parent.start)) {
  318. break;
  319. }
  320. comments.leading.push(currentToken);
  321. currentToken = this.getTokenBefore(currentToken, { includeComments: true });
  322. }
  323. comments.leading.reverse();
  324. currentToken = this.getTokenAfter(node, { includeComments: true });
  325. while (currentToken && isCommentToken(currentToken)) {
  326. if (node.parent && node.parent.type !== "Program" && (currentToken.end > node.parent.end)) {
  327. break;
  328. }
  329. comments.trailing.push(currentToken);
  330. currentToken = this.getTokenAfter(currentToken, { includeComments: true });
  331. }
  332. }
  333. this._commentCache.set(node, comments);
  334. return comments;
  335. }
  336. /**
  337. * Retrieves the JSDoc comment for a given node.
  338. * @param {ASTNode} node The AST node to get the comment for.
  339. * @returns {Token|null} The Block comment token containing the JSDoc comment
  340. * for the given node or null if not found.
  341. * @public
  342. * @deprecated
  343. */
  344. getJSDocComment(node) {
  345. /**
  346. * Checks for the presence of a JSDoc comment for the given node and returns it.
  347. * @param {ASTNode} astNode The AST node to get the comment for.
  348. * @returns {Token|null} The Block comment token containing the JSDoc comment
  349. * for the given node or null if not found.
  350. * @private
  351. */
  352. const findJSDocComment = astNode => {
  353. const tokenBefore = this.getTokenBefore(astNode, { includeComments: true });
  354. if (
  355. tokenBefore &&
  356. isCommentToken(tokenBefore) &&
  357. tokenBefore.type === "Block" &&
  358. tokenBefore.value.charAt(0) === "*" &&
  359. astNode.loc.start.line - tokenBefore.loc.end.line <= 1
  360. ) {
  361. return tokenBefore;
  362. }
  363. return null;
  364. };
  365. let parent = node.parent;
  366. switch (node.type) {
  367. case "ClassDeclaration":
  368. case "FunctionDeclaration":
  369. return findJSDocComment(looksLikeExport(parent) ? parent : node);
  370. case "ClassExpression":
  371. return findJSDocComment(parent.parent);
  372. case "ArrowFunctionExpression":
  373. case "FunctionExpression":
  374. if (parent.type !== "CallExpression" && parent.type !== "NewExpression") {
  375. while (
  376. !this.getCommentsBefore(parent).length &&
  377. !/Function/u.test(parent.type) &&
  378. parent.type !== "MethodDefinition" &&
  379. parent.type !== "Property"
  380. ) {
  381. parent = parent.parent;
  382. if (!parent) {
  383. break;
  384. }
  385. }
  386. if (parent && parent.type !== "FunctionDeclaration" && parent.type !== "Program") {
  387. return findJSDocComment(parent);
  388. }
  389. }
  390. return findJSDocComment(node);
  391. // falls through
  392. default:
  393. return null;
  394. }
  395. }
  396. /**
  397. * Gets the deepest node containing a range index.
  398. * @param {int} index Range index of the desired node.
  399. * @returns {ASTNode} The node if found or null if not found.
  400. * @public
  401. */
  402. getNodeByRangeIndex(index) {
  403. let result = null;
  404. Traverser.traverse(this.ast, {
  405. visitorKeys: this.visitorKeys,
  406. enter(node) {
  407. if (node.range[0] <= index && index < node.range[1]) {
  408. result = node;
  409. } else {
  410. this.skip();
  411. }
  412. },
  413. leave(node) {
  414. if (node === result) {
  415. this.break();
  416. }
  417. }
  418. });
  419. return result;
  420. }
  421. /**
  422. * Determines if two nodes or tokens have at least one whitespace character
  423. * between them. Order does not matter. Returns false if the given nodes or
  424. * tokens overlap.
  425. * @param {ASTNode|Token} first The first node or token to check between.
  426. * @param {ASTNode|Token} second The second node or token to check between.
  427. * @returns {boolean} True if there is a whitespace character between
  428. * any of the tokens found between the two given nodes or tokens.
  429. * @public
  430. */
  431. isSpaceBetween(first, second) {
  432. return isSpaceBetween(this, first, second, false);
  433. }
  434. /**
  435. * Determines if two nodes or tokens have at least one whitespace character
  436. * between them. Order does not matter. Returns false if the given nodes or
  437. * tokens overlap.
  438. * For backward compatibility, this method returns true if there are
  439. * `JSXText` tokens that contain whitespaces between the two.
  440. * @param {ASTNode|Token} first The first node or token to check between.
  441. * @param {ASTNode|Token} second The second node or token to check between.
  442. * @returns {boolean} True if there is a whitespace character between
  443. * any of the tokens found between the two given nodes or tokens.
  444. * @deprecated in favor of isSpaceBetween().
  445. * @public
  446. */
  447. isSpaceBetweenTokens(first, second) {
  448. return isSpaceBetween(this, first, second, true);
  449. }
  450. /**
  451. * Converts a source text index into a (line, column) pair.
  452. * @param {number} index The index of a character in a file
  453. * @throws {TypeError} If non-numeric index or index out of range.
  454. * @returns {Object} A {line, column} location object with a 0-indexed column
  455. * @public
  456. */
  457. getLocFromIndex(index) {
  458. if (typeof index !== "number") {
  459. throw new TypeError("Expected `index` to be a number.");
  460. }
  461. if (index < 0 || index > this.text.length) {
  462. throw new RangeError(`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`);
  463. }
  464. /*
  465. * For an argument of this.text.length, return the location one "spot" past the last character
  466. * of the file. If the last character is a linebreak, the location will be column 0 of the next
  467. * line; otherwise, the location will be in the next column on the same line.
  468. *
  469. * See getIndexFromLoc for the motivation for this special case.
  470. */
  471. if (index === this.text.length) {
  472. return { line: this.lines.length, column: this.lines[this.lines.length - 1].length };
  473. }
  474. /*
  475. * To figure out which line index is on, determine the last place at which index could
  476. * be inserted into lineStartIndices to keep the list sorted.
  477. */
  478. const lineNumber = index >= this.lineStartIndices[this.lineStartIndices.length - 1]
  479. ? this.lineStartIndices.length
  480. : this.lineStartIndices.findIndex(el => index < el);
  481. return { line: lineNumber, column: index - this.lineStartIndices[lineNumber - 1] };
  482. }
  483. /**
  484. * Converts a (line, column) pair into a range index.
  485. * @param {Object} loc A line/column location
  486. * @param {number} loc.line The line number of the location (1-indexed)
  487. * @param {number} loc.column The column number of the location (0-indexed)
  488. * @throws {TypeError|RangeError} If `loc` is not an object with a numeric
  489. * `line` and `column`, if the `line` is less than or equal to zero or
  490. * the line or column is out of the expected range.
  491. * @returns {number} The range index of the location in the file.
  492. * @public
  493. */
  494. getIndexFromLoc(loc) {
  495. if (typeof loc !== "object" || typeof loc.line !== "number" || typeof loc.column !== "number") {
  496. throw new TypeError("Expected `loc` to be an object with numeric `line` and `column` properties.");
  497. }
  498. if (loc.line <= 0) {
  499. throw new RangeError(`Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`);
  500. }
  501. if (loc.line > this.lineStartIndices.length) {
  502. throw new RangeError(`Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`);
  503. }
  504. const lineStartIndex = this.lineStartIndices[loc.line - 1];
  505. const lineEndIndex = loc.line === this.lineStartIndices.length ? this.text.length : this.lineStartIndices[loc.line];
  506. const positionIndex = lineStartIndex + loc.column;
  507. /*
  508. * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of
  509. * the given line, provided that the line number is valid element of this.lines. Since the
  510. * last element of this.lines is an empty string for files with trailing newlines, add a
  511. * special case where getting the index for the first location after the end of the file
  512. * will return the length of the file, rather than throwing an error. This allows rules to
  513. * use getIndexFromLoc consistently without worrying about edge cases at the end of a file.
  514. */
  515. if (
  516. loc.line === this.lineStartIndices.length && positionIndex > lineEndIndex ||
  517. loc.line < this.lineStartIndices.length && positionIndex >= lineEndIndex
  518. ) {
  519. throw new RangeError(`Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`);
  520. }
  521. return positionIndex;
  522. }
  523. /**
  524. * Gets the scope for the given node
  525. * @param {ASTNode} currentNode The node to get the scope of
  526. * @returns {eslint-scope.Scope} The scope information for this node
  527. * @throws {TypeError} If the `currentNode` argument is missing.
  528. */
  529. getScope(currentNode) {
  530. if (!currentNode) {
  531. throw new TypeError("Missing required argument: node.");
  532. }
  533. // check cache first
  534. const cache = this[caches].get("scopes");
  535. const cachedScope = cache.get(currentNode);
  536. if (cachedScope) {
  537. return cachedScope;
  538. }
  539. // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
  540. const inner = currentNode.type !== "Program";
  541. for (let node = currentNode; node; node = node.parent) {
  542. const scope = this.scopeManager.acquire(node, inner);
  543. if (scope) {
  544. if (scope.type === "function-expression-name") {
  545. cache.set(currentNode, scope.childScopes[0]);
  546. return scope.childScopes[0];
  547. }
  548. cache.set(currentNode, scope);
  549. return scope;
  550. }
  551. }
  552. cache.set(currentNode, this.scopeManager.scopes[0]);
  553. return this.scopeManager.scopes[0];
  554. }
  555. /**
  556. * Gets all of the declared variables in the scope associated
  557. * with `node`. This is a convenience method that passes through
  558. * to the same method on the `scopeManager`.
  559. * @param {ASTNode} node The node from which to retrieve the scope to check.
  560. * @returns {Array<Variable>} An array of variable nodes representing
  561. * the declared variables in the scope associated with `node`.
  562. */
  563. getDeclaredVariables(node) {
  564. return this.scopeManager.getDeclaredVariables(node);
  565. }
  566. /* eslint-disable class-methods-use-this -- node is owned by SourceCode */
  567. /**
  568. * Gets all the ancestors of a given node
  569. * @param {ASTNode} node The node
  570. * @returns {Array<ASTNode>} All the ancestor nodes in the AST, not including the provided node, starting
  571. * from the root node at index 0 and going inwards to the parent node.
  572. * @throws {TypeError} When `node` is missing.
  573. */
  574. getAncestors(node) {
  575. if (!node) {
  576. throw new TypeError("Missing required argument: node.");
  577. }
  578. const ancestorsStartingAtParent = [];
  579. for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
  580. ancestorsStartingAtParent.push(ancestor);
  581. }
  582. return ancestorsStartingAtParent.reverse();
  583. }
  584. /* eslint-enable class-methods-use-this -- node is owned by SourceCode */
  585. }
  586. module.exports = SourceCode;