source-code.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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. globals = require("../../../../conf/globals"),
  15. {
  16. directivesPattern
  17. } = require("../../../shared/directives"),
  18. CodePathAnalyzer = require("../../../linter/code-path-analysis/code-path-analyzer"),
  19. createEmitter = require("../../../linter/safe-emitter"),
  20. { ConfigCommentParser, VisitNodeStep, CallMethodStep, Directive } = require("@eslint/plugin-kit"),
  21. eslintScope = require("eslint-scope");
  22. //------------------------------------------------------------------------------
  23. // Type Definitions
  24. //------------------------------------------------------------------------------
  25. /** @typedef {import("eslint-scope").Variable} Variable */
  26. /** @typedef {import("eslint-scope").Scope} Scope */
  27. /** @typedef {import("@eslint/core").SourceCode} ISourceCode */
  28. /** @typedef {import("@eslint/core").Directive} IDirective */
  29. /** @typedef {import("@eslint/core").TraversalStep} ITraversalStep */
  30. //------------------------------------------------------------------------------
  31. // Private
  32. //------------------------------------------------------------------------------
  33. const commentParser = new ConfigCommentParser();
  34. const CODE_PATH_EVENTS = [
  35. "onCodePathStart",
  36. "onCodePathEnd",
  37. "onCodePathSegmentStart",
  38. "onCodePathSegmentEnd",
  39. "onCodePathSegmentLoop",
  40. "onUnreachableCodePathSegmentStart",
  41. "onUnreachableCodePathSegmentEnd"
  42. ];
  43. /**
  44. * Validates that the given AST has the required information.
  45. * @param {ASTNode} ast The Program node of the AST to check.
  46. * @throws {Error} If the AST doesn't contain the correct information.
  47. * @returns {void}
  48. * @private
  49. */
  50. function validate(ast) {
  51. if (!ast.tokens) {
  52. throw new Error("AST is missing the tokens array.");
  53. }
  54. if (!ast.comments) {
  55. throw new Error("AST is missing the comments array.");
  56. }
  57. if (!ast.loc) {
  58. throw new Error("AST is missing location information.");
  59. }
  60. if (!ast.range) {
  61. throw new Error("AST is missing range information");
  62. }
  63. }
  64. /**
  65. * Retrieves globals for the given ecmaVersion.
  66. * @param {number} ecmaVersion The version to retrieve globals for.
  67. * @returns {Object} The globals for the given ecmaVersion.
  68. */
  69. function getGlobalsForEcmaVersion(ecmaVersion) {
  70. switch (ecmaVersion) {
  71. case 3:
  72. return globals.es3;
  73. case 5:
  74. return globals.es5;
  75. default:
  76. if (ecmaVersion < 2015) {
  77. return globals[`es${ecmaVersion + 2009}`];
  78. }
  79. return globals[`es${ecmaVersion}`];
  80. }
  81. }
  82. /**
  83. * Check to see if its a ES6 export declaration.
  84. * @param {ASTNode} astNode An AST node.
  85. * @returns {boolean} whether the given node represents an export declaration.
  86. * @private
  87. */
  88. function looksLikeExport(astNode) {
  89. return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" ||
  90. astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier";
  91. }
  92. /**
  93. * Merges two sorted lists into a larger sorted list in O(n) time.
  94. * @param {Token[]} tokens The list of tokens.
  95. * @param {Token[]} comments The list of comments.
  96. * @returns {Token[]} A sorted list of tokens and comments.
  97. * @private
  98. */
  99. function sortedMerge(tokens, comments) {
  100. const result = [];
  101. let tokenIndex = 0;
  102. let commentIndex = 0;
  103. while (tokenIndex < tokens.length || commentIndex < comments.length) {
  104. if (commentIndex >= comments.length || tokenIndex < tokens.length && tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) {
  105. result.push(tokens[tokenIndex++]);
  106. } else {
  107. result.push(comments[commentIndex++]);
  108. }
  109. }
  110. return result;
  111. }
  112. /**
  113. * Normalizes a value for a global in a config
  114. * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
  115. * a global directive comment
  116. * @returns {("readable"|"writeable"|"off")} The value normalized as a string
  117. * @throws Error if global value is invalid
  118. */
  119. function normalizeConfigGlobal(configuredValue) {
  120. switch (configuredValue) {
  121. case "off":
  122. return "off";
  123. case true:
  124. case "true":
  125. case "writeable":
  126. case "writable":
  127. return "writable";
  128. case null:
  129. case false:
  130. case "false":
  131. case "readable":
  132. case "readonly":
  133. return "readonly";
  134. default:
  135. throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
  136. }
  137. }
  138. /**
  139. * Determines if two nodes or tokens overlap.
  140. * @param {ASTNode|Token} first The first node or token to check.
  141. * @param {ASTNode|Token} second The second node or token to check.
  142. * @returns {boolean} True if the two nodes or tokens overlap.
  143. * @private
  144. */
  145. function nodesOrTokensOverlap(first, second) {
  146. return (first.range[0] <= second.range[0] && first.range[1] >= second.range[0]) ||
  147. (second.range[0] <= first.range[0] && second.range[1] >= first.range[0]);
  148. }
  149. /**
  150. * Determines if two nodes or tokens have at least one whitespace character
  151. * between them. Order does not matter. Returns false if the given nodes or
  152. * tokens overlap.
  153. * @param {SourceCode} sourceCode The source code object.
  154. * @param {ASTNode|Token} first The first node or token to check between.
  155. * @param {ASTNode|Token} second The second node or token to check between.
  156. * @param {boolean} checkInsideOfJSXText If `true` is present, check inside of JSXText tokens for backward compatibility.
  157. * @returns {boolean} True if there is a whitespace character between
  158. * any of the tokens found between the two given nodes or tokens.
  159. * @public
  160. */
  161. function isSpaceBetween(sourceCode, first, second, checkInsideOfJSXText) {
  162. if (nodesOrTokensOverlap(first, second)) {
  163. return false;
  164. }
  165. const [startingNodeOrToken, endingNodeOrToken] = first.range[1] <= second.range[0]
  166. ? [first, second]
  167. : [second, first];
  168. const firstToken = sourceCode.getLastToken(startingNodeOrToken) || startingNodeOrToken;
  169. const finalToken = sourceCode.getFirstToken(endingNodeOrToken) || endingNodeOrToken;
  170. let currentToken = firstToken;
  171. while (currentToken !== finalToken) {
  172. const nextToken = sourceCode.getTokenAfter(currentToken, { includeComments: true });
  173. if (
  174. currentToken.range[1] !== nextToken.range[0] ||
  175. /*
  176. * For backward compatibility, check spaces in JSXText.
  177. * https://github.com/eslint/eslint/issues/12614
  178. */
  179. (
  180. checkInsideOfJSXText &&
  181. nextToken !== finalToken &&
  182. nextToken.type === "JSXText" &&
  183. /\s/u.test(nextToken.value)
  184. )
  185. ) {
  186. return true;
  187. }
  188. currentToken = nextToken;
  189. }
  190. return false;
  191. }
  192. //-----------------------------------------------------------------------------
  193. // Directive Comments
  194. //-----------------------------------------------------------------------------
  195. /**
  196. * Ensures that variables representing built-in properties of the Global Object,
  197. * and any globals declared by special block comments, are present in the global
  198. * scope.
  199. * @param {Scope} globalScope The global scope.
  200. * @param {Object|undefined} configGlobals The globals declared in configuration
  201. * @param {Object|undefined} inlineGlobals The globals declared in the source code
  202. * @returns {void}
  203. */
  204. function addDeclaredGlobals(globalScope, configGlobals = {}, inlineGlobals = {}) {
  205. // Define configured global variables.
  206. for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(inlineGlobals)])) {
  207. /*
  208. * `normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would
  209. * typically be caught when validating a config anyway (validity for inline global comments is checked separately).
  210. */
  211. const configValue = configGlobals[id] === void 0 ? void 0 : normalizeConfigGlobal(configGlobals[id]);
  212. const commentValue = inlineGlobals[id] && inlineGlobals[id].value;
  213. const value = commentValue || configValue;
  214. const sourceComments = inlineGlobals[id] && inlineGlobals[id].comments;
  215. if (value === "off") {
  216. continue;
  217. }
  218. let variable = globalScope.set.get(id);
  219. if (!variable) {
  220. variable = new eslintScope.Variable(id, globalScope);
  221. globalScope.variables.push(variable);
  222. globalScope.set.set(id, variable);
  223. }
  224. variable.eslintImplicitGlobalSetting = configValue;
  225. variable.eslintExplicitGlobal = sourceComments !== void 0;
  226. variable.eslintExplicitGlobalComments = sourceComments;
  227. variable.writeable = (value === "writable");
  228. }
  229. /*
  230. * "through" contains all references which definitions cannot be found.
  231. * Since we augment the global scope using configuration, we need to update
  232. * references and remove the ones that were added by configuration.
  233. */
  234. globalScope.through = globalScope.through.filter(reference => {
  235. const name = reference.identifier.name;
  236. const variable = globalScope.set.get(name);
  237. if (variable) {
  238. /*
  239. * Links the variable and the reference.
  240. * And this reference is removed from `Scope#through`.
  241. */
  242. reference.resolved = variable;
  243. variable.references.push(reference);
  244. return false;
  245. }
  246. return true;
  247. });
  248. }
  249. /**
  250. * Sets the given variable names as exported so they won't be triggered by
  251. * the `no-unused-vars` rule.
  252. * @param {eslint.Scope} globalScope The global scope to define exports in.
  253. * @param {Record<string,string>} variables An object whose keys are the variable
  254. * names to export.
  255. * @returns {void}
  256. */
  257. function markExportedVariables(globalScope, variables) {
  258. Object.keys(variables).forEach(name => {
  259. const variable = globalScope.set.get(name);
  260. if (variable) {
  261. variable.eslintUsed = true;
  262. variable.eslintExported = true;
  263. }
  264. });
  265. }
  266. //------------------------------------------------------------------------------
  267. // Public Interface
  268. //------------------------------------------------------------------------------
  269. const caches = Symbol("caches");
  270. /**
  271. * Represents parsed source code.
  272. * @implements {ISourceCode}
  273. */
  274. class SourceCode extends TokenStore {
  275. /**
  276. * The cache of steps that were taken while traversing the source code.
  277. * @type {Array<ITraversalStep>}
  278. */
  279. #steps;
  280. /**
  281. * Creates a new instance.
  282. * @param {string|Object} textOrConfig The source code text or config object.
  283. * @param {string} textOrConfig.text The source code text.
  284. * @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.
  285. * @param {boolean} textOrConfig.hasBOM Indicates if the text has a Unicode BOM.
  286. * @param {Object|null} textOrConfig.parserServices The parser services.
  287. * @param {ScopeManager|null} textOrConfig.scopeManager The scope of this source code.
  288. * @param {Object|null} textOrConfig.visitorKeys The visitor keys to traverse AST.
  289. * @param {ASTNode} [astIfNoConfig] The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
  290. */
  291. constructor(textOrConfig, astIfNoConfig) {
  292. let text, hasBOM, ast, parserServices, scopeManager, visitorKeys;
  293. // Process overloading of arguments
  294. if (typeof textOrConfig === "string") {
  295. text = textOrConfig;
  296. ast = astIfNoConfig;
  297. hasBOM = false;
  298. } else if (typeof textOrConfig === "object" && textOrConfig !== null) {
  299. text = textOrConfig.text;
  300. ast = textOrConfig.ast;
  301. hasBOM = textOrConfig.hasBOM;
  302. parserServices = textOrConfig.parserServices;
  303. scopeManager = textOrConfig.scopeManager;
  304. visitorKeys = textOrConfig.visitorKeys;
  305. }
  306. validate(ast);
  307. super(ast.tokens, ast.comments);
  308. /**
  309. * General purpose caching for the class.
  310. */
  311. this[caches] = new Map([
  312. ["scopes", new WeakMap()],
  313. ["vars", new Map()],
  314. ["configNodes", void 0]
  315. ]);
  316. /**
  317. * Indicates if the AST is ESTree compatible.
  318. * @type {boolean}
  319. */
  320. this.isESTree = ast.type === "Program";
  321. /*
  322. * Backwards compatibility for BOM handling.
  323. *
  324. * The `hasBOM` property has been available on the `SourceCode` object
  325. * for a long time and is used to indicate if the source contains a BOM.
  326. * The linter strips the BOM and just passes the `hasBOM` property to the
  327. * `SourceCode` constructor to make it easier for languages to not deal with
  328. * the BOM.
  329. *
  330. * However, the text passed in to the `SourceCode` constructor might still
  331. * have a BOM if the constructor is called outside of the linter, so we still
  332. * need to check for the BOM in the text.
  333. */
  334. const textHasBOM = text.charCodeAt(0) === 0xFEFF;
  335. /**
  336. * The flag to indicate that the source code has Unicode BOM.
  337. * @type {boolean}
  338. */
  339. this.hasBOM = textHasBOM || !!hasBOM;
  340. /**
  341. * The original text source code.
  342. * BOM was stripped from this text.
  343. * @type {string}
  344. */
  345. this.text = (textHasBOM ? text.slice(1) : text);
  346. /**
  347. * The parsed AST for the source code.
  348. * @type {ASTNode}
  349. */
  350. this.ast = ast;
  351. /**
  352. * The parser services of this source code.
  353. * @type {Object}
  354. */
  355. this.parserServices = parserServices || {};
  356. /**
  357. * The scope of this source code.
  358. * @type {ScopeManager|null}
  359. */
  360. this.scopeManager = scopeManager || null;
  361. /**
  362. * The visitor keys to traverse AST.
  363. * @type {Object}
  364. */
  365. this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS;
  366. // Check the source text for the presence of a shebang since it is parsed as a standard line comment.
  367. const shebangMatched = this.text.match(astUtils.shebangPattern);
  368. const hasShebang = shebangMatched && ast.comments.length && ast.comments[0].value === shebangMatched[1];
  369. if (hasShebang) {
  370. ast.comments[0].type = "Shebang";
  371. }
  372. this.tokensAndComments = sortedMerge(ast.tokens, ast.comments);
  373. /**
  374. * The source code split into lines according to ECMA-262 specification.
  375. * This is done to avoid each rule needing to do so separately.
  376. * @type {string[]}
  377. */
  378. this.lines = [];
  379. this.lineStartIndices = [0];
  380. const lineEndingPattern = astUtils.createGlobalLinebreakMatcher();
  381. let match;
  382. /*
  383. * Previously, this was implemented using a regex that
  384. * matched a sequence of non-linebreak characters followed by a
  385. * linebreak, then adding the lengths of the matches. However,
  386. * this caused a catastrophic backtracking issue when the end
  387. * of a file contained a large number of non-newline characters.
  388. * To avoid this, the current implementation just matches newlines
  389. * and uses match.index to get the correct line start indices.
  390. */
  391. while ((match = lineEndingPattern.exec(this.text))) {
  392. this.lines.push(this.text.slice(this.lineStartIndices.at(-1), match.index));
  393. this.lineStartIndices.push(match.index + match[0].length);
  394. }
  395. this.lines.push(this.text.slice(this.lineStartIndices.at(-1)));
  396. // don't allow further modification of this object
  397. Object.freeze(this);
  398. Object.freeze(this.lines);
  399. }
  400. /**
  401. * Split the source code into multiple lines based on the line delimiters.
  402. * @param {string} text Source code as a string.
  403. * @returns {string[]} Array of source code lines.
  404. * @public
  405. */
  406. static splitLines(text) {
  407. return text.split(astUtils.createGlobalLinebreakMatcher());
  408. }
  409. /**
  410. * Gets the source code for the given node.
  411. * @param {ASTNode} [node] The AST node to get the text for.
  412. * @param {int} [beforeCount] The number of characters before the node to retrieve.
  413. * @param {int} [afterCount] The number of characters after the node to retrieve.
  414. * @returns {string} The text representing the AST node.
  415. * @public
  416. */
  417. getText(node, beforeCount, afterCount) {
  418. if (node) {
  419. return this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0),
  420. node.range[1] + (afterCount || 0));
  421. }
  422. return this.text;
  423. }
  424. /**
  425. * Gets the entire source text split into an array of lines.
  426. * @returns {Array} The source text as an array of lines.
  427. * @public
  428. */
  429. getLines() {
  430. return this.lines;
  431. }
  432. /**
  433. * Retrieves an array containing all comments in the source code.
  434. * @returns {ASTNode[]} An array of comment nodes.
  435. * @public
  436. */
  437. getAllComments() {
  438. return this.ast.comments;
  439. }
  440. /**
  441. * Retrieves the JSDoc comment for a given node.
  442. * @param {ASTNode} node The AST node to get the comment for.
  443. * @returns {Token|null} The Block comment token containing the JSDoc comment
  444. * for the given node or null if not found.
  445. * @public
  446. * @deprecated
  447. */
  448. getJSDocComment(node) {
  449. /**
  450. * Checks for the presence of a JSDoc comment for the given node and returns it.
  451. * @param {ASTNode} astNode The AST node to get the comment for.
  452. * @returns {Token|null} The Block comment token containing the JSDoc comment
  453. * for the given node or null if not found.
  454. * @private
  455. */
  456. const findJSDocComment = astNode => {
  457. const tokenBefore = this.getTokenBefore(astNode, { includeComments: true });
  458. if (
  459. tokenBefore &&
  460. isCommentToken(tokenBefore) &&
  461. tokenBefore.type === "Block" &&
  462. tokenBefore.value.charAt(0) === "*" &&
  463. astNode.loc.start.line - tokenBefore.loc.end.line <= 1
  464. ) {
  465. return tokenBefore;
  466. }
  467. return null;
  468. };
  469. let parent = node.parent;
  470. switch (node.type) {
  471. case "ClassDeclaration":
  472. case "FunctionDeclaration":
  473. return findJSDocComment(looksLikeExport(parent) ? parent : node);
  474. case "ClassExpression":
  475. return findJSDocComment(parent.parent);
  476. case "ArrowFunctionExpression":
  477. case "FunctionExpression":
  478. if (parent.type !== "CallExpression" && parent.type !== "NewExpression") {
  479. while (
  480. !this.getCommentsBefore(parent).length &&
  481. !/Function/u.test(parent.type) &&
  482. parent.type !== "MethodDefinition" &&
  483. parent.type !== "Property"
  484. ) {
  485. parent = parent.parent;
  486. if (!parent) {
  487. break;
  488. }
  489. }
  490. if (parent && parent.type !== "FunctionDeclaration" && parent.type !== "Program") {
  491. return findJSDocComment(parent);
  492. }
  493. }
  494. return findJSDocComment(node);
  495. // falls through
  496. default:
  497. return null;
  498. }
  499. }
  500. /**
  501. * Gets the deepest node containing a range index.
  502. * @param {int} index Range index of the desired node.
  503. * @returns {ASTNode} The node if found or null if not found.
  504. * @public
  505. */
  506. getNodeByRangeIndex(index) {
  507. let result = null;
  508. Traverser.traverse(this.ast, {
  509. visitorKeys: this.visitorKeys,
  510. enter(node) {
  511. if (node.range[0] <= index && index < node.range[1]) {
  512. result = node;
  513. } else {
  514. this.skip();
  515. }
  516. },
  517. leave(node) {
  518. if (node === result) {
  519. this.break();
  520. }
  521. }
  522. });
  523. return result;
  524. }
  525. /**
  526. * Determines if two nodes or tokens have at least one whitespace character
  527. * between them. Order does not matter. Returns false if the given nodes or
  528. * tokens overlap.
  529. * @param {ASTNode|Token} first The first node or token to check between.
  530. * @param {ASTNode|Token} second The second node or token to check between.
  531. * @returns {boolean} True if there is a whitespace character between
  532. * any of the tokens found between the two given nodes or tokens.
  533. * @public
  534. */
  535. isSpaceBetween(first, second) {
  536. return isSpaceBetween(this, first, second, false);
  537. }
  538. /**
  539. * Determines if two nodes or tokens have at least one whitespace character
  540. * between them. Order does not matter. Returns false if the given nodes or
  541. * tokens overlap.
  542. * For backward compatibility, this method returns true if there are
  543. * `JSXText` tokens that contain whitespaces between the two.
  544. * @param {ASTNode|Token} first The first node or token to check between.
  545. * @param {ASTNode|Token} second The second node or token to check between.
  546. * @returns {boolean} True if there is a whitespace character between
  547. * any of the tokens found between the two given nodes or tokens.
  548. * @deprecated in favor of isSpaceBetween().
  549. * @public
  550. */
  551. isSpaceBetweenTokens(first, second) {
  552. return isSpaceBetween(this, first, second, true);
  553. }
  554. /**
  555. * Converts a source text index into a (line, column) pair.
  556. * @param {number} index The index of a character in a file
  557. * @throws {TypeError} If non-numeric index or index out of range.
  558. * @returns {Object} A {line, column} location object with a 0-indexed column
  559. * @public
  560. */
  561. getLocFromIndex(index) {
  562. if (typeof index !== "number") {
  563. throw new TypeError("Expected `index` to be a number.");
  564. }
  565. if (index < 0 || index > this.text.length) {
  566. throw new RangeError(`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`);
  567. }
  568. /*
  569. * For an argument of this.text.length, return the location one "spot" past the last character
  570. * of the file. If the last character is a linebreak, the location will be column 0 of the next
  571. * line; otherwise, the location will be in the next column on the same line.
  572. *
  573. * See getIndexFromLoc for the motivation for this special case.
  574. */
  575. if (index === this.text.length) {
  576. return { line: this.lines.length, column: this.lines.at(-1).length };
  577. }
  578. /*
  579. * To figure out which line index is on, determine the last place at which index could
  580. * be inserted into lineStartIndices to keep the list sorted.
  581. */
  582. const lineNumber = index >= this.lineStartIndices.at(-1)
  583. ? this.lineStartIndices.length
  584. : this.lineStartIndices.findIndex(el => index < el);
  585. return { line: lineNumber, column: index - this.lineStartIndices[lineNumber - 1] };
  586. }
  587. /**
  588. * Converts a (line, column) pair into a range index.
  589. * @param {Object} loc A line/column location
  590. * @param {number} loc.line The line number of the location (1-indexed)
  591. * @param {number} loc.column The column number of the location (0-indexed)
  592. * @throws {TypeError|RangeError} If `loc` is not an object with a numeric
  593. * `line` and `column`, if the `line` is less than or equal to zero or
  594. * the line or column is out of the expected range.
  595. * @returns {number} The range index of the location in the file.
  596. * @public
  597. */
  598. getIndexFromLoc(loc) {
  599. if (typeof loc !== "object" || typeof loc.line !== "number" || typeof loc.column !== "number") {
  600. throw new TypeError("Expected `loc` to be an object with numeric `line` and `column` properties.");
  601. }
  602. if (loc.line <= 0) {
  603. throw new RangeError(`Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`);
  604. }
  605. if (loc.line > this.lineStartIndices.length) {
  606. throw new RangeError(`Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`);
  607. }
  608. const lineStartIndex = this.lineStartIndices[loc.line - 1];
  609. const lineEndIndex = loc.line === this.lineStartIndices.length ? this.text.length : this.lineStartIndices[loc.line];
  610. const positionIndex = lineStartIndex + loc.column;
  611. /*
  612. * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of
  613. * the given line, provided that the line number is valid element of this.lines. Since the
  614. * last element of this.lines is an empty string for files with trailing newlines, add a
  615. * special case where getting the index for the first location after the end of the file
  616. * will return the length of the file, rather than throwing an error. This allows rules to
  617. * use getIndexFromLoc consistently without worrying about edge cases at the end of a file.
  618. */
  619. if (
  620. loc.line === this.lineStartIndices.length && positionIndex > lineEndIndex ||
  621. loc.line < this.lineStartIndices.length && positionIndex >= lineEndIndex
  622. ) {
  623. throw new RangeError(`Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`);
  624. }
  625. return positionIndex;
  626. }
  627. /**
  628. * Gets the scope for the given node
  629. * @param {ASTNode} currentNode The node to get the scope of
  630. * @returns {Scope} The scope information for this node
  631. * @throws {TypeError} If the `currentNode` argument is missing.
  632. */
  633. getScope(currentNode) {
  634. if (!currentNode) {
  635. throw new TypeError("Missing required argument: node.");
  636. }
  637. // check cache first
  638. const cache = this[caches].get("scopes");
  639. const cachedScope = cache.get(currentNode);
  640. if (cachedScope) {
  641. return cachedScope;
  642. }
  643. // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
  644. const inner = currentNode.type !== "Program";
  645. for (let node = currentNode; node; node = node.parent) {
  646. const scope = this.scopeManager.acquire(node, inner);
  647. if (scope) {
  648. if (scope.type === "function-expression-name") {
  649. cache.set(currentNode, scope.childScopes[0]);
  650. return scope.childScopes[0];
  651. }
  652. cache.set(currentNode, scope);
  653. return scope;
  654. }
  655. }
  656. cache.set(currentNode, this.scopeManager.scopes[0]);
  657. return this.scopeManager.scopes[0];
  658. }
  659. /**
  660. * Get the variables that `node` defines.
  661. * This is a convenience method that passes through
  662. * to the same method on the `scopeManager`.
  663. * @param {ASTNode} node The node for which the variables are obtained.
  664. * @returns {Array<Variable>} An array of variable nodes representing
  665. * the variables that `node` defines.
  666. */
  667. getDeclaredVariables(node) {
  668. return this.scopeManager.getDeclaredVariables(node);
  669. }
  670. /* eslint-disable class-methods-use-this -- node is owned by SourceCode */
  671. /**
  672. * Gets all the ancestors of a given node
  673. * @param {ASTNode} node The node
  674. * @returns {Array<ASTNode>} All the ancestor nodes in the AST, not including the provided node, starting
  675. * from the root node at index 0 and going inwards to the parent node.
  676. * @throws {TypeError} When `node` is missing.
  677. */
  678. getAncestors(node) {
  679. if (!node) {
  680. throw new TypeError("Missing required argument: node.");
  681. }
  682. const ancestorsStartingAtParent = [];
  683. for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
  684. ancestorsStartingAtParent.push(ancestor);
  685. }
  686. return ancestorsStartingAtParent.reverse();
  687. }
  688. /**
  689. * Returns the location of the given node or token.
  690. * @param {ASTNode|Token} nodeOrToken The node or token to get the location of.
  691. * @returns {SourceLocation} The location of the node or token.
  692. */
  693. getLoc(nodeOrToken) {
  694. return nodeOrToken.loc;
  695. }
  696. /**
  697. * Returns the range of the given node or token.
  698. * @param {ASTNode|Token} nodeOrToken The node or token to get the range of.
  699. * @returns {[number, number]} The range of the node or token.
  700. */
  701. getRange(nodeOrToken) {
  702. return nodeOrToken.range;
  703. }
  704. /* eslint-enable class-methods-use-this -- node is owned by SourceCode */
  705. /**
  706. * Marks a variable as used in the current scope
  707. * @param {string} name The name of the variable to mark as used.
  708. * @param {ASTNode} [refNode] The closest node to the variable reference.
  709. * @returns {boolean} True if the variable was found and marked as used, false if not.
  710. */
  711. markVariableAsUsed(name, refNode = this.ast) {
  712. const currentScope = this.getScope(refNode);
  713. let initialScope = currentScope;
  714. /*
  715. * When we are in an ESM or CommonJS module, we need to start searching
  716. * from the top-level scope, not the global scope. For ESM the top-level
  717. * scope is the module scope; for CommonJS the top-level scope is the
  718. * outer function scope.
  719. *
  720. * Without this check, we might miss a variable declared with `var` at
  721. * the top-level because it won't exist in the global scope.
  722. */
  723. if (
  724. currentScope.type === "global" &&
  725. currentScope.childScopes.length > 0 &&
  726. // top-level scopes refer to a `Program` node
  727. currentScope.childScopes[0].block === this.ast
  728. ) {
  729. initialScope = currentScope.childScopes[0];
  730. }
  731. for (let scope = initialScope; scope; scope = scope.upper) {
  732. const variable = scope.variables.find(scopeVar => scopeVar.name === name);
  733. if (variable) {
  734. variable.eslintUsed = true;
  735. return true;
  736. }
  737. }
  738. return false;
  739. }
  740. /**
  741. * Returns an array of all inline configuration nodes found in the
  742. * source code.
  743. * @returns {Array<Token>} An array of all inline configuration nodes.
  744. */
  745. getInlineConfigNodes() {
  746. // check the cache first
  747. let configNodes = this[caches].get("configNodes");
  748. if (configNodes) {
  749. return configNodes;
  750. }
  751. // calculate fresh config nodes
  752. configNodes = this.ast.comments.filter(comment => {
  753. // shebang comments are never directives
  754. if (comment.type === "Shebang") {
  755. return false;
  756. }
  757. const directive = commentParser.parseDirective(comment.value);
  758. if (!directive) {
  759. return false;
  760. }
  761. if (!directivesPattern.test(directive.label)) {
  762. return false;
  763. }
  764. // only certain comment types are supported as line comments
  765. return comment.type !== "Line" || !!/^eslint-disable-(next-)?line$/u.test(directive.label);
  766. });
  767. this[caches].set("configNodes", configNodes);
  768. return configNodes;
  769. }
  770. /**
  771. * Returns an all directive nodes that enable or disable rules along with any problems
  772. * encountered while parsing the directives.
  773. * @returns {{problems:Array<Problem>,directives:Array<Directive>}} Information
  774. * that ESLint needs to further process the directives.
  775. */
  776. getDisableDirectives() {
  777. // check the cache first
  778. const cachedDirectives = this[caches].get("disableDirectives");
  779. if (cachedDirectives) {
  780. return cachedDirectives;
  781. }
  782. const problems = [];
  783. const directives = [];
  784. this.getInlineConfigNodes().forEach(comment => {
  785. // Step 1: Parse the directive
  786. const {
  787. label,
  788. value,
  789. justification: justificationPart
  790. } = commentParser.parseDirective(comment.value);
  791. // Step 2: Extract the directive value
  792. const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(label);
  793. if (comment.type === "Line" && !lineCommentSupported) {
  794. return;
  795. }
  796. // Step 3: Validate the directive does not span multiple lines
  797. if (label === "eslint-disable-line" && comment.loc.start.line !== comment.loc.end.line) {
  798. const message = `${label} comment should not span multiple lines.`;
  799. problems.push({
  800. ruleId: null,
  801. message,
  802. loc: comment.loc
  803. });
  804. return;
  805. }
  806. // Step 4: Extract the directive value and create the Directive object
  807. switch (label) {
  808. case "eslint-disable":
  809. case "eslint-enable":
  810. case "eslint-disable-next-line":
  811. case "eslint-disable-line": {
  812. const directiveType = label.slice("eslint-".length);
  813. directives.push(new Directive({
  814. type: directiveType,
  815. node: comment,
  816. value,
  817. justification: justificationPart
  818. }));
  819. }
  820. // no default
  821. }
  822. });
  823. const result = { problems, directives };
  824. this[caches].set("disableDirectives", result);
  825. return result;
  826. }
  827. /**
  828. * Applies language options sent in from the core.
  829. * @param {Object} languageOptions The language options for this run.
  830. * @returns {void}
  831. */
  832. applyLanguageOptions(languageOptions) {
  833. /*
  834. * Add configured globals and language globals
  835. *
  836. * Using Object.assign instead of object spread for performance reasons
  837. * https://github.com/eslint/eslint/issues/16302
  838. */
  839. const configGlobals = Object.assign(
  840. Object.create(null), // https://github.com/eslint/eslint/issues/18363
  841. getGlobalsForEcmaVersion(languageOptions.ecmaVersion),
  842. languageOptions.sourceType === "commonjs" ? globals.commonjs : void 0,
  843. languageOptions.globals
  844. );
  845. const varsCache = this[caches].get("vars");
  846. varsCache.set("configGlobals", configGlobals);
  847. }
  848. /**
  849. * Applies configuration found inside of the source code. This method is only
  850. * called when ESLint is running with inline configuration allowed.
  851. * @returns {{problems:Array<Problem>,configs:{config:FlatConfigArray,loc:Location}}} Information
  852. * that ESLint needs to further process the inline configuration.
  853. */
  854. applyInlineConfig() {
  855. const problems = [];
  856. const configs = [];
  857. const exportedVariables = {};
  858. const inlineGlobals = Object.create(null);
  859. this.getInlineConfigNodes().forEach(comment => {
  860. const { label, value } = commentParser.parseDirective(comment.value);
  861. switch (label) {
  862. case "exported":
  863. Object.assign(exportedVariables, commentParser.parseListConfig(value));
  864. break;
  865. case "globals":
  866. case "global":
  867. for (const [id, idSetting] of Object.entries(commentParser.parseStringConfig(value))) {
  868. let normalizedValue;
  869. try {
  870. normalizedValue = normalizeConfigGlobal(idSetting);
  871. } catch (err) {
  872. problems.push({
  873. ruleId: null,
  874. loc: comment.loc,
  875. message: err.message
  876. });
  877. continue;
  878. }
  879. if (inlineGlobals[id]) {
  880. inlineGlobals[id].comments.push(comment);
  881. inlineGlobals[id].value = normalizedValue;
  882. } else {
  883. inlineGlobals[id] = {
  884. comments: [comment],
  885. value: normalizedValue
  886. };
  887. }
  888. }
  889. break;
  890. case "eslint": {
  891. const parseResult = commentParser.parseJSONLikeConfig(value);
  892. if (parseResult.ok) {
  893. configs.push({
  894. config: {
  895. rules: parseResult.config
  896. },
  897. loc: comment.loc
  898. });
  899. } else {
  900. problems.push({
  901. ruleId: null,
  902. loc: comment.loc,
  903. message: parseResult.error.message
  904. });
  905. }
  906. break;
  907. }
  908. // no default
  909. }
  910. });
  911. // save all the new variables for later
  912. const varsCache = this[caches].get("vars");
  913. varsCache.set("inlineGlobals", inlineGlobals);
  914. varsCache.set("exportedVariables", exportedVariables);
  915. return {
  916. configs,
  917. problems
  918. };
  919. }
  920. /**
  921. * Called by ESLint core to indicate that it has finished providing
  922. * information. We now add in all the missing variables and ensure that
  923. * state-changing methods cannot be called by rules.
  924. * @returns {void}
  925. */
  926. finalize() {
  927. const varsCache = this[caches].get("vars");
  928. const configGlobals = varsCache.get("configGlobals");
  929. const inlineGlobals = varsCache.get("inlineGlobals");
  930. const exportedVariables = varsCache.get("exportedVariables");
  931. const globalScope = this.scopeManager.scopes[0];
  932. addDeclaredGlobals(globalScope, configGlobals, inlineGlobals);
  933. if (exportedVariables) {
  934. markExportedVariables(globalScope, exportedVariables);
  935. }
  936. }
  937. /**
  938. * Traverse the source code and return the steps that were taken.
  939. * @returns {Array<TraversalStep>} The steps that were taken while traversing the source code.
  940. */
  941. traverse() {
  942. // Because the AST doesn't mutate, we can cache the steps
  943. if (this.#steps) {
  944. return this.#steps;
  945. }
  946. const steps = this.#steps = [];
  947. /*
  948. * This logic works for any AST, not just ESTree. Because ESLint has allowed
  949. * custom parsers to return any AST, we need to ensure that the traversal
  950. * logic works for any AST.
  951. */
  952. const emitter = createEmitter();
  953. let analyzer = {
  954. enterNode(node) {
  955. steps.push(new VisitNodeStep({
  956. target: node,
  957. phase: 1,
  958. args: [node, node.parent]
  959. }));
  960. },
  961. leaveNode(node) {
  962. steps.push(new VisitNodeStep({
  963. target: node,
  964. phase: 2,
  965. args: [node, node.parent]
  966. }));
  967. },
  968. emitter
  969. };
  970. /*
  971. * We do code path analysis for ESTree only. Code path analysis is not
  972. * necessary for other ASTs, and it's also not possible to do for other
  973. * ASTs because the necessary information is not available.
  974. *
  975. * Generally speaking, we can tell that the AST is an ESTree if it has a
  976. * Program node at the top level. This is not a perfect heuristic, but it
  977. * is good enough for now.
  978. */
  979. if (this.isESTree) {
  980. analyzer = new CodePathAnalyzer(analyzer);
  981. CODE_PATH_EVENTS.forEach(eventName => {
  982. emitter.on(eventName, (...args) => {
  983. steps.push(new CallMethodStep({
  984. target: eventName,
  985. args
  986. }));
  987. });
  988. });
  989. }
  990. /*
  991. * The actual AST traversal is done by the `Traverser` class. This class
  992. * is responsible for walking the AST and calling the appropriate methods
  993. * on the `analyzer` object, which is appropriate for the given AST.
  994. */
  995. Traverser.traverse(this.ast, {
  996. enter(node, parent) {
  997. // save the parent node on a property for backwards compatibility
  998. node.parent = parent;
  999. analyzer.enterNode(node);
  1000. },
  1001. leave(node) {
  1002. analyzer.leaveNode(node);
  1003. },
  1004. visitorKeys: this.visitorKeys
  1005. });
  1006. return steps;
  1007. }
  1008. }
  1009. module.exports = SourceCode;