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.

1464 lines
54 KiB

4 years ago
  1. /**
  2. * @fileoverview Main Linter Class
  3. * @author Gyandeep Singh
  4. * @author aladdin-add
  5. */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Requirements
  9. //------------------------------------------------------------------------------
  10. const
  11. path = require("path"),
  12. eslintScope = require("eslint-scope"),
  13. evk = require("eslint-visitor-keys"),
  14. espree = require("espree"),
  15. lodash = require("lodash"),
  16. BuiltInEnvironments = require("../../conf/environments"),
  17. pkg = require("../../package.json"),
  18. astUtils = require("../shared/ast-utils"),
  19. ConfigOps = require("../shared/config-ops"),
  20. validator = require("../shared/config-validator"),
  21. Traverser = require("../shared/traverser"),
  22. { SourceCode } = require("../source-code"),
  23. CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"),
  24. applyDisableDirectives = require("./apply-disable-directives"),
  25. ConfigCommentParser = require("./config-comment-parser"),
  26. NodeEventGenerator = require("./node-event-generator"),
  27. createReportTranslator = require("./report-translator"),
  28. Rules = require("./rules"),
  29. createEmitter = require("./safe-emitter"),
  30. SourceCodeFixer = require("./source-code-fixer"),
  31. timing = require("./timing"),
  32. ruleReplacements = require("../../conf/replacements.json");
  33. const debug = require("debug")("eslint:linter");
  34. const MAX_AUTOFIX_PASSES = 10;
  35. const DEFAULT_PARSER_NAME = "espree";
  36. const commentParser = new ConfigCommentParser();
  37. const DEFAULT_ERROR_LOC = { start: { line: 1, column: 0 }, end: { line: 1, column: 1 } };
  38. //------------------------------------------------------------------------------
  39. // Typedefs
  40. //------------------------------------------------------------------------------
  41. /** @typedef {InstanceType<import("../cli-engine/config-array")["ConfigArray"]>} ConfigArray */
  42. /** @typedef {InstanceType<import("../cli-engine/config-array")["ExtractedConfig"]>} ExtractedConfig */
  43. /** @typedef {import("../shared/types").ConfigData} ConfigData */
  44. /** @typedef {import("../shared/types").Environment} Environment */
  45. /** @typedef {import("../shared/types").GlobalConf} GlobalConf */
  46. /** @typedef {import("../shared/types").LintMessage} LintMessage */
  47. /** @typedef {import("../shared/types").ParserOptions} ParserOptions */
  48. /** @typedef {import("../shared/types").Processor} Processor */
  49. /** @typedef {import("../shared/types").Rule} Rule */
  50. /**
  51. * @template T
  52. * @typedef {{ [P in keyof T]-?: T[P] }} Required
  53. */
  54. /**
  55. * @typedef {Object} DisableDirective
  56. * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type
  57. * @property {number} line
  58. * @property {number} column
  59. * @property {(string|null)} ruleId
  60. */
  61. /**
  62. * The private data for `Linter` instance.
  63. * @typedef {Object} LinterInternalSlots
  64. * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used.
  65. * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used.
  66. * @property {Map<string, Parser>} parserMap The loaded parsers.
  67. * @property {Rules} ruleMap The loaded rules.
  68. */
  69. /**
  70. * @typedef {Object} VerifyOptions
  71. * @property {boolean} [allowInlineConfig] Allow/disallow inline comments' ability
  72. * to change config once it is set. Defaults to true if not supplied.
  73. * Useful if you want to validate JS without comments overriding rules.
  74. * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix`
  75. * properties into the lint result.
  76. * @property {string} [filename] the filename of the source code.
  77. * @property {boolean | "off" | "warn" | "error"} [reportUnusedDisableDirectives] Adds reported errors for
  78. * unused `eslint-disable` directives.
  79. */
  80. /**
  81. * @typedef {Object} ProcessorOptions
  82. * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the
  83. * predicate function that selects adopt code blocks.
  84. * @property {Processor["postprocess"]} [postprocess] postprocessor for report
  85. * messages. If provided, this should accept an array of the message lists
  86. * for each code block returned from the preprocessor, apply a mapping to
  87. * the messages as appropriate, and return a one-dimensional array of
  88. * messages.
  89. * @property {Processor["preprocess"]} [preprocess] preprocessor for source text.
  90. * If provided, this should accept a string of source text, and return an
  91. * array of code blocks to lint.
  92. */
  93. /**
  94. * @typedef {Object} FixOptions
  95. * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines
  96. * whether fixes should be applied.
  97. */
  98. /**
  99. * @typedef {Object} InternalOptions
  100. * @property {string | null} warnInlineConfig The config name what `noInlineConfig` setting came from. If `noInlineConfig` setting didn't exist, this is null. If this is a config name, then the linter warns directive comments.
  101. * @property {"off" | "warn" | "error"} reportUnusedDisableDirectives (boolean values were normalized)
  102. */
  103. //------------------------------------------------------------------------------
  104. // Helpers
  105. //------------------------------------------------------------------------------
  106. /**
  107. * Ensures that variables representing built-in properties of the Global Object,
  108. * and any globals declared by special block comments, are present in the global
  109. * scope.
  110. * @param {Scope} globalScope The global scope.
  111. * @param {Object} configGlobals The globals declared in configuration
  112. * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration
  113. * @returns {void}
  114. */
  115. function addDeclaredGlobals(globalScope, configGlobals, { exportedVariables, enabledGlobals }) {
  116. // Define configured global variables.
  117. for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(enabledGlobals)])) {
  118. /*
  119. * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would
  120. * typically be caught when validating a config anyway (validity for inline global comments is checked separately).
  121. */
  122. const configValue = configGlobals[id] === void 0 ? void 0 : ConfigOps.normalizeConfigGlobal(configGlobals[id]);
  123. const commentValue = enabledGlobals[id] && enabledGlobals[id].value;
  124. const value = commentValue || configValue;
  125. const sourceComments = enabledGlobals[id] && enabledGlobals[id].comments;
  126. if (value === "off") {
  127. continue;
  128. }
  129. let variable = globalScope.set.get(id);
  130. if (!variable) {
  131. variable = new eslintScope.Variable(id, globalScope);
  132. globalScope.variables.push(variable);
  133. globalScope.set.set(id, variable);
  134. }
  135. variable.eslintImplicitGlobalSetting = configValue;
  136. variable.eslintExplicitGlobal = sourceComments !== void 0;
  137. variable.eslintExplicitGlobalComments = sourceComments;
  138. variable.writeable = (value === "writable");
  139. }
  140. // mark all exported variables as such
  141. Object.keys(exportedVariables).forEach(name => {
  142. const variable = globalScope.set.get(name);
  143. if (variable) {
  144. variable.eslintUsed = true;
  145. }
  146. });
  147. /*
  148. * "through" contains all references which definitions cannot be found.
  149. * Since we augment the global scope using configuration, we need to update
  150. * references and remove the ones that were added by configuration.
  151. */
  152. globalScope.through = globalScope.through.filter(reference => {
  153. const name = reference.identifier.name;
  154. const variable = globalScope.set.get(name);
  155. if (variable) {
  156. /*
  157. * Links the variable and the reference.
  158. * And this reference is removed from `Scope#through`.
  159. */
  160. reference.resolved = variable;
  161. variable.references.push(reference);
  162. return false;
  163. }
  164. return true;
  165. });
  166. }
  167. /**
  168. * creates a missing-rule message.
  169. * @param {string} ruleId the ruleId to create
  170. * @returns {string} created error message
  171. * @private
  172. */
  173. function createMissingRuleMessage(ruleId) {
  174. return Object.prototype.hasOwnProperty.call(ruleReplacements.rules, ruleId)
  175. ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}`
  176. : `Definition for rule '${ruleId}' was not found.`;
  177. }
  178. /**
  179. * creates a linting problem
  180. * @param {Object} options to create linting error
  181. * @param {string} [options.ruleId] the ruleId to report
  182. * @param {Object} [options.loc] the loc to report
  183. * @param {string} [options.message] the error message to report
  184. * @param {string} [options.severity] the error message to report
  185. * @returns {LintMessage} created problem, returns a missing-rule problem if only provided ruleId.
  186. * @private
  187. */
  188. function createLintingProblem(options) {
  189. const {
  190. ruleId = null,
  191. loc = DEFAULT_ERROR_LOC,
  192. message = createMissingRuleMessage(options.ruleId),
  193. severity = 2
  194. } = options;
  195. return {
  196. ruleId,
  197. message,
  198. line: loc.start.line,
  199. column: loc.start.column + 1,
  200. endLine: loc.end.line,
  201. endColumn: loc.end.column + 1,
  202. severity,
  203. nodeType: null
  204. };
  205. }
  206. /**
  207. * Creates a collection of disable directives from a comment
  208. * @param {Object} options to create disable directives
  209. * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment
  210. * @param {{line: number, column: number}} options.loc The 0-based location of the comment token
  211. * @param {string} options.value The value after the directive in the comment
  212. * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`)
  213. * @param {function(string): {create: Function}} options.ruleMapper A map from rule IDs to defined rules
  214. * @returns {Object} Directives and problems from the comment
  215. */
  216. function createDisableDirectives(options) {
  217. const { type, loc, value, ruleMapper } = options;
  218. const ruleIds = Object.keys(commentParser.parseListConfig(value));
  219. const directiveRules = ruleIds.length ? ruleIds : [null];
  220. const result = {
  221. directives: [], // valid disable directives
  222. directiveProblems: [] // problems in directives
  223. };
  224. for (const ruleId of directiveRules) {
  225. // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/)
  226. if (ruleId === null || ruleMapper(ruleId) !== null) {
  227. result.directives.push({ type, line: loc.start.line, column: loc.start.column + 1, ruleId });
  228. } else {
  229. result.directiveProblems.push(createLintingProblem({ ruleId, loc }));
  230. }
  231. }
  232. return result;
  233. }
  234. /**
  235. * Remove the ignored part from a given directive comment and trim it.
  236. * @param {string} value The comment text to strip.
  237. * @returns {string} The stripped text.
  238. */
  239. function stripDirectiveComment(value) {
  240. return value.split(/\s-{2,}\s/u)[0].trim();
  241. }
  242. /**
  243. * Parses comments in file to extract file-specific config of rules, globals
  244. * and environments and merges them with global config; also code blocks
  245. * where reporting is disabled or enabled and merges them with reporting config.
  246. * @param {string} filename The file being checked.
  247. * @param {ASTNode} ast The top node of the AST.
  248. * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
  249. * @param {string|null} warnInlineConfig If a string then it should warn directive comments as disabled. The string value is the config name what the setting came from.
  250. * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], exportedVariables: Object, problems: Problem[], disableDirectives: DisableDirective[]}}
  251. * A collection of the directive comments that were found, along with any problems that occurred when parsing
  252. */
  253. function getDirectiveComments(filename, ast, ruleMapper, warnInlineConfig) {
  254. const configuredRules = {};
  255. const enabledGlobals = Object.create(null);
  256. const exportedVariables = {};
  257. const problems = [];
  258. const disableDirectives = [];
  259. ast.comments.filter(token => token.type !== "Shebang").forEach(comment => {
  260. const trimmedCommentText = stripDirectiveComment(comment.value);
  261. const match = /^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u.exec(trimmedCommentText);
  262. if (!match) {
  263. return;
  264. }
  265. const directiveText = match[1];
  266. const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(directiveText);
  267. if (comment.type === "Line" && !lineCommentSupported) {
  268. return;
  269. }
  270. if (warnInlineConfig) {
  271. const kind = comment.type === "Block" ? `/*${directiveText}*/` : `//${directiveText}`;
  272. problems.push(createLintingProblem({
  273. ruleId: null,
  274. message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`,
  275. loc: comment.loc,
  276. severity: 1
  277. }));
  278. return;
  279. }
  280. if (lineCommentSupported && comment.loc.start.line !== comment.loc.end.line) {
  281. const message = `${directiveText} comment should not span multiple lines.`;
  282. problems.push(createLintingProblem({
  283. ruleId: null,
  284. message,
  285. loc: comment.loc
  286. }));
  287. return;
  288. }
  289. const directiveValue = trimmedCommentText.slice(match.index + directiveText.length);
  290. switch (directiveText) {
  291. case "eslint-disable":
  292. case "eslint-enable":
  293. case "eslint-disable-next-line":
  294. case "eslint-disable-line": {
  295. const directiveType = directiveText.slice("eslint-".length);
  296. const options = { type: directiveType, loc: comment.loc, value: directiveValue, ruleMapper };
  297. const { directives, directiveProblems } = createDisableDirectives(options);
  298. disableDirectives.push(...directives);
  299. problems.push(...directiveProblems);
  300. break;
  301. }
  302. case "exported":
  303. Object.assign(exportedVariables, commentParser.parseStringConfig(directiveValue, comment));
  304. break;
  305. case "globals":
  306. case "global":
  307. for (const [id, { value }] of Object.entries(commentParser.parseStringConfig(directiveValue, comment))) {
  308. let normalizedValue;
  309. try {
  310. normalizedValue = ConfigOps.normalizeConfigGlobal(value);
  311. } catch (err) {
  312. problems.push(createLintingProblem({
  313. ruleId: null,
  314. loc: comment.loc,
  315. message: err.message
  316. }));
  317. continue;
  318. }
  319. if (enabledGlobals[id]) {
  320. enabledGlobals[id].comments.push(comment);
  321. enabledGlobals[id].value = normalizedValue;
  322. } else {
  323. enabledGlobals[id] = {
  324. comments: [comment],
  325. value: normalizedValue
  326. };
  327. }
  328. }
  329. break;
  330. case "eslint": {
  331. const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc);
  332. if (parseResult.success) {
  333. Object.keys(parseResult.config).forEach(name => {
  334. const rule = ruleMapper(name);
  335. const ruleValue = parseResult.config[name];
  336. if (rule === null) {
  337. problems.push(createLintingProblem({ ruleId: name, loc: comment.loc }));
  338. return;
  339. }
  340. try {
  341. validator.validateRuleOptions(rule, name, ruleValue);
  342. } catch (err) {
  343. problems.push(createLintingProblem({
  344. ruleId: name,
  345. message: err.message,
  346. loc: comment.loc
  347. }));
  348. // do not apply the config, if found invalid options.
  349. return;
  350. }
  351. configuredRules[name] = ruleValue;
  352. });
  353. } else {
  354. problems.push(parseResult.error);
  355. }
  356. break;
  357. }
  358. // no default
  359. }
  360. });
  361. return {
  362. configuredRules,
  363. enabledGlobals,
  364. exportedVariables,
  365. problems,
  366. disableDirectives
  367. };
  368. }
  369. /**
  370. * Normalize ECMAScript version from the initial config
  371. * @param {number} ecmaVersion ECMAScript version from the initial config
  372. * @returns {number} normalized ECMAScript version
  373. */
  374. function normalizeEcmaVersion(ecmaVersion) {
  375. /*
  376. * Calculate ECMAScript edition number from official year version starting with
  377. * ES2015, which corresponds with ES6 (or a difference of 2009).
  378. */
  379. return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion;
  380. }
  381. const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gu;
  382. /**
  383. * Checks whether or not there is a comment which has "eslint-env *" in a given text.
  384. * @param {string} text A source code text to check.
  385. * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment.
  386. */
  387. function findEslintEnv(text) {
  388. let match, retv;
  389. eslintEnvPattern.lastIndex = 0;
  390. while ((match = eslintEnvPattern.exec(text)) !== null) {
  391. retv = Object.assign(
  392. retv || {},
  393. commentParser.parseListConfig(stripDirectiveComment(match[1]))
  394. );
  395. }
  396. return retv;
  397. }
  398. /**
  399. * Convert "/path/to/<text>" to "<text>".
  400. * `CLIEngine#executeOnText()` method gives "/path/to/<text>" if the filename
  401. * was omitted because `configArray.extractConfig()` requires an absolute path.
  402. * But the linter should pass `<text>` to `RuleContext#getFilename()` in that
  403. * case.
  404. * Also, code blocks can have their virtual filename. If the parent filename was
  405. * `<text>`, the virtual filename is `<text>/0_foo.js` or something like (i.e.,
  406. * it's not an absolute path).
  407. * @param {string} filename The filename to normalize.
  408. * @returns {string} The normalized filename.
  409. */
  410. function normalizeFilename(filename) {
  411. const parts = filename.split(path.sep);
  412. const index = parts.lastIndexOf("<text>");
  413. return index === -1 ? filename : parts.slice(index).join(path.sep);
  414. }
  415. /**
  416. * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
  417. * consistent shape.
  418. * @param {VerifyOptions} providedOptions Options
  419. * @param {ConfigData} config Config.
  420. * @returns {Required<VerifyOptions> & InternalOptions} Normalized options
  421. */
  422. function normalizeVerifyOptions(providedOptions, config) {
  423. const disableInlineConfig = config.noInlineConfig === true;
  424. const ignoreInlineConfig = providedOptions.allowInlineConfig === false;
  425. const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig
  426. ? ` (${config.configNameOfNoInlineConfig})`
  427. : "";
  428. let reportUnusedDisableDirectives = providedOptions.reportUnusedDisableDirectives;
  429. if (typeof reportUnusedDisableDirectives === "boolean") {
  430. reportUnusedDisableDirectives = reportUnusedDisableDirectives ? "error" : "off";
  431. }
  432. if (typeof reportUnusedDisableDirectives !== "string") {
  433. reportUnusedDisableDirectives = config.reportUnusedDisableDirectives ? "warn" : "off";
  434. }
  435. return {
  436. filename: normalizeFilename(providedOptions.filename || "<input>"),
  437. allowInlineConfig: !ignoreInlineConfig,
  438. warnInlineConfig: disableInlineConfig && !ignoreInlineConfig
  439. ? `your config${configNameOfNoInlineConfig}`
  440. : null,
  441. reportUnusedDisableDirectives,
  442. disableFixes: Boolean(providedOptions.disableFixes)
  443. };
  444. }
  445. /**
  446. * Combines the provided parserOptions with the options from environments
  447. * @param {string} parserName The parser name which uses this options.
  448. * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config
  449. * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
  450. * @returns {ParserOptions} Resulting parser options after merge
  451. */
  452. function resolveParserOptions(parserName, providedOptions, enabledEnvironments) {
  453. const parserOptionsFromEnv = enabledEnvironments
  454. .filter(env => env.parserOptions)
  455. .reduce((parserOptions, env) => lodash.merge(parserOptions, env.parserOptions), {});
  456. const mergedParserOptions = lodash.merge(parserOptionsFromEnv, providedOptions || {});
  457. const isModule = mergedParserOptions.sourceType === "module";
  458. if (isModule) {
  459. /*
  460. * can't have global return inside of modules
  461. * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add)
  462. */
  463. mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
  464. }
  465. /*
  466. * TODO: @aladdin-add
  467. * 1. for a 3rd-party parser, do not normalize parserOptions
  468. * 2. for espree, no need to do this (espree will do it)
  469. */
  470. mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion);
  471. return mergedParserOptions;
  472. }
  473. /**
  474. * Combines the provided globals object with the globals from environments
  475. * @param {Record<string, GlobalConf>} providedGlobals The 'globals' key in a config
  476. * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
  477. * @returns {Record<string, GlobalConf>} The resolved globals object
  478. */
  479. function resolveGlobals(providedGlobals, enabledEnvironments) {
  480. return Object.assign(
  481. {},
  482. ...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
  483. providedGlobals
  484. );
  485. }
  486. /**
  487. * Strips Unicode BOM from a given text.
  488. * @param {string} text A text to strip.
  489. * @returns {string} The stripped text.
  490. */
  491. function stripUnicodeBOM(text) {
  492. /*
  493. * Check Unicode BOM.
  494. * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF.
  495. * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters
  496. */
  497. if (text.charCodeAt(0) === 0xFEFF) {
  498. return text.slice(1);
  499. }
  500. return text;
  501. }
  502. /**
  503. * Get the options for a rule (not including severity), if any
  504. * @param {Array|number} ruleConfig rule configuration
  505. * @returns {Array} of rule options, empty Array if none
  506. */
  507. function getRuleOptions(ruleConfig) {
  508. if (Array.isArray(ruleConfig)) {
  509. return ruleConfig.slice(1);
  510. }
  511. return [];
  512. }
  513. /**
  514. * Analyze scope of the given AST.
  515. * @param {ASTNode} ast The `Program` node to analyze.
  516. * @param {ParserOptions} parserOptions The parser options.
  517. * @param {Record<string, string[]>} visitorKeys The visitor keys.
  518. * @returns {ScopeManager} The analysis result.
  519. */
  520. function analyzeScope(ast, parserOptions, visitorKeys) {
  521. const ecmaFeatures = parserOptions.ecmaFeatures || {};
  522. const ecmaVersion = parserOptions.ecmaVersion || 5;
  523. return eslintScope.analyze(ast, {
  524. ignoreEval: true,
  525. nodejsScope: ecmaFeatures.globalReturn,
  526. impliedStrict: ecmaFeatures.impliedStrict,
  527. ecmaVersion,
  528. sourceType: parserOptions.sourceType || "script",
  529. childVisitorKeys: visitorKeys || evk.KEYS,
  530. fallback: Traverser.getKeys
  531. });
  532. }
  533. /**
  534. * Parses text into an AST. Moved out here because the try-catch prevents
  535. * optimization of functions, so it's best to keep the try-catch as isolated
  536. * as possible
  537. * @param {string} text The text to parse.
  538. * @param {Parser} parser The parser to parse.
  539. * @param {ParserOptions} providedParserOptions Options to pass to the parser
  540. * @param {string} filePath The path to the file being parsed.
  541. * @returns {{success: false, error: Problem}|{success: true, sourceCode: SourceCode}}
  542. * An object containing the AST and parser services if parsing was successful, or the error if parsing failed
  543. * @private
  544. */
  545. function parse(text, parser, providedParserOptions, filePath) {
  546. const textToParse = stripUnicodeBOM(text).replace(astUtils.shebangPattern, (match, captured) => `//${captured}`);
  547. const parserOptions = Object.assign({}, providedParserOptions, {
  548. loc: true,
  549. range: true,
  550. raw: true,
  551. tokens: true,
  552. comment: true,
  553. eslintVisitorKeys: true,
  554. eslintScopeManager: true,
  555. filePath
  556. });
  557. /*
  558. * Check for parsing errors first. If there's a parsing error, nothing
  559. * else can happen. However, a parsing error does not throw an error
  560. * from this method - it's just considered a fatal error message, a
  561. * problem that ESLint identified just like any other.
  562. */
  563. try {
  564. const parseResult = (typeof parser.parseForESLint === "function")
  565. ? parser.parseForESLint(textToParse, parserOptions)
  566. : { ast: parser.parse(textToParse, parserOptions) };
  567. const ast = parseResult.ast;
  568. const parserServices = parseResult.services || {};
  569. const visitorKeys = parseResult.visitorKeys || evk.KEYS;
  570. const scopeManager = parseResult.scopeManager || analyzeScope(ast, parserOptions, visitorKeys);
  571. return {
  572. success: true,
  573. /*
  574. * Save all values that `parseForESLint()` returned.
  575. * If a `SourceCode` object is given as the first parameter instead of source code text,
  576. * linter skips the parsing process and reuses the source code object.
  577. * In that case, linter needs all the values that `parseForESLint()` returned.
  578. */
  579. sourceCode: new SourceCode({
  580. text,
  581. ast,
  582. parserServices,
  583. scopeManager,
  584. visitorKeys
  585. })
  586. };
  587. } catch (ex) {
  588. // If the message includes a leading line number, strip it:
  589. const message = `Parsing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
  590. debug("%s\n%s", message, ex.stack);
  591. return {
  592. success: false,
  593. error: {
  594. ruleId: null,
  595. fatal: true,
  596. severity: 2,
  597. message,
  598. line: ex.lineNumber,
  599. column: ex.column
  600. }
  601. };
  602. }
  603. }
  604. /**
  605. * Gets the scope for the current node
  606. * @param {ScopeManager} scopeManager The scope manager for this AST
  607. * @param {ASTNode} currentNode The node to get the scope of
  608. * @returns {eslint-scope.Scope} The scope information for this node
  609. */
  610. function getScope(scopeManager, currentNode) {
  611. // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
  612. const inner = currentNode.type !== "Program";
  613. for (let node = currentNode; node; node = node.parent) {
  614. const scope = scopeManager.acquire(node, inner);
  615. if (scope) {
  616. if (scope.type === "function-expression-name") {
  617. return scope.childScopes[0];
  618. }
  619. return scope;
  620. }
  621. }
  622. return scopeManager.scopes[0];
  623. }
  624. /**
  625. * Marks a variable as used in the current scope
  626. * @param {ScopeManager} scopeManager The scope manager for this AST. The scope may be mutated by this function.
  627. * @param {ASTNode} currentNode The node currently being traversed
  628. * @param {Object} parserOptions The options used to parse this text
  629. * @param {string} name The name of the variable that should be marked as used.
  630. * @returns {boolean} True if the variable was found and marked as used, false if not.
  631. */
  632. function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
  633. const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn;
  634. const specialScope = hasGlobalReturn || parserOptions.sourceType === "module";
  635. const currentScope = getScope(scopeManager, currentNode);
  636. // Special Node.js scope means we need to start one level deeper
  637. const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
  638. for (let scope = initialScope; scope; scope = scope.upper) {
  639. const variable = scope.variables.find(scopeVar => scopeVar.name === name);
  640. if (variable) {
  641. variable.eslintUsed = true;
  642. return true;
  643. }
  644. }
  645. return false;
  646. }
  647. /**
  648. * Runs a rule, and gets its listeners
  649. * @param {Rule} rule A normalized rule with a `create` method
  650. * @param {Context} ruleContext The context that should be passed to the rule
  651. * @returns {Object} A map of selector listeners provided by the rule
  652. */
  653. function createRuleListeners(rule, ruleContext) {
  654. try {
  655. return rule.create(ruleContext);
  656. } catch (ex) {
  657. ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
  658. throw ex;
  659. }
  660. }
  661. /**
  662. * Gets all the ancestors of a given node
  663. * @param {ASTNode} node The node
  664. * @returns {ASTNode[]} All the ancestor nodes in the AST, not including the provided node, starting
  665. * from the root node and going inwards to the parent node.
  666. */
  667. function getAncestors(node) {
  668. const ancestorsStartingAtParent = [];
  669. for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
  670. ancestorsStartingAtParent.push(ancestor);
  671. }
  672. return ancestorsStartingAtParent.reverse();
  673. }
  674. // methods that exist on SourceCode object
  675. const DEPRECATED_SOURCECODE_PASSTHROUGHS = {
  676. getSource: "getText",
  677. getSourceLines: "getLines",
  678. getAllComments: "getAllComments",
  679. getNodeByRangeIndex: "getNodeByRangeIndex",
  680. getComments: "getComments",
  681. getCommentsBefore: "getCommentsBefore",
  682. getCommentsAfter: "getCommentsAfter",
  683. getCommentsInside: "getCommentsInside",
  684. getJSDocComment: "getJSDocComment",
  685. getFirstToken: "getFirstToken",
  686. getFirstTokens: "getFirstTokens",
  687. getLastToken: "getLastToken",
  688. getLastTokens: "getLastTokens",
  689. getTokenAfter: "getTokenAfter",
  690. getTokenBefore: "getTokenBefore",
  691. getTokenByRangeStart: "getTokenByRangeStart",
  692. getTokens: "getTokens",
  693. getTokensAfter: "getTokensAfter",
  694. getTokensBefore: "getTokensBefore",
  695. getTokensBetween: "getTokensBetween"
  696. };
  697. const BASE_TRAVERSAL_CONTEXT = Object.freeze(
  698. Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).reduce(
  699. (contextInfo, methodName) =>
  700. Object.assign(contextInfo, {
  701. [methodName](...args) {
  702. return this.getSourceCode()[DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]](...args);
  703. }
  704. }),
  705. {}
  706. )
  707. );
  708. /**
  709. * Runs the given rules on the given SourceCode object
  710. * @param {SourceCode} sourceCode A SourceCode object for the given text
  711. * @param {Object} configuredRules The rules configuration
  712. * @param {function(string): Rule} ruleMapper A mapper function from rule names to rules
  713. * @param {Object} parserOptions The options that were passed to the parser
  714. * @param {string} parserName The name of the parser in the config
  715. * @param {Object} settings The settings that were enabled in the config
  716. * @param {string} filename The reported filename of the code
  717. * @param {boolean} disableFixes If true, it doesn't make `fix` properties.
  718. * @param {string | undefined} cwd cwd of the cli
  719. * @returns {Problem[]} An array of reported problems
  720. */
  721. function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parserName, settings, filename, disableFixes, cwd) {
  722. const emitter = createEmitter();
  723. const nodeQueue = [];
  724. let currentNode = sourceCode.ast;
  725. Traverser.traverse(sourceCode.ast, {
  726. enter(node, parent) {
  727. node.parent = parent;
  728. nodeQueue.push({ isEntering: true, node });
  729. },
  730. leave(node) {
  731. nodeQueue.push({ isEntering: false, node });
  732. },
  733. visitorKeys: sourceCode.visitorKeys
  734. });
  735. /*
  736. * Create a frozen object with the ruleContext properties and methods that are shared by all rules.
  737. * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the
  738. * properties once for each rule.
  739. */
  740. const sharedTraversalContext = Object.freeze(
  741. Object.assign(
  742. Object.create(BASE_TRAVERSAL_CONTEXT),
  743. {
  744. getAncestors: () => getAncestors(currentNode),
  745. getDeclaredVariables: sourceCode.scopeManager.getDeclaredVariables.bind(sourceCode.scopeManager),
  746. getCwd: () => cwd,
  747. getFilename: () => filename,
  748. getScope: () => getScope(sourceCode.scopeManager, currentNode),
  749. getSourceCode: () => sourceCode,
  750. markVariableAsUsed: name => markVariableAsUsed(sourceCode.scopeManager, currentNode, parserOptions, name),
  751. parserOptions,
  752. parserPath: parserName,
  753. parserServices: sourceCode.parserServices,
  754. settings
  755. }
  756. )
  757. );
  758. const lintingProblems = [];
  759. Object.keys(configuredRules).forEach(ruleId => {
  760. const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]);
  761. // not load disabled rules
  762. if (severity === 0) {
  763. return;
  764. }
  765. const rule = ruleMapper(ruleId);
  766. if (rule === null) {
  767. lintingProblems.push(createLintingProblem({ ruleId }));
  768. return;
  769. }
  770. const messageIds = rule.meta && rule.meta.messages;
  771. let reportTranslator = null;
  772. const ruleContext = Object.freeze(
  773. Object.assign(
  774. Object.create(sharedTraversalContext),
  775. {
  776. id: ruleId,
  777. options: getRuleOptions(configuredRules[ruleId]),
  778. report(...args) {
  779. /*
  780. * Create a report translator lazily.
  781. * In a vast majority of cases, any given rule reports zero errors on a given
  782. * piece of code. Creating a translator lazily avoids the performance cost of
  783. * creating a new translator function for each rule that usually doesn't get
  784. * called.
  785. *
  786. * Using lazy report translators improves end-to-end performance by about 3%
  787. * with Node 8.4.0.
  788. */
  789. if (reportTranslator === null) {
  790. reportTranslator = createReportTranslator({
  791. ruleId,
  792. severity,
  793. sourceCode,
  794. messageIds,
  795. disableFixes
  796. });
  797. }
  798. const problem = reportTranslator(...args);
  799. if (problem.fix && rule.meta && !rule.meta.fixable) {
  800. throw new Error("Fixable rules should export a `meta.fixable` property.");
  801. }
  802. lintingProblems.push(problem);
  803. }
  804. }
  805. )
  806. );
  807. const ruleListeners = createRuleListeners(rule, ruleContext);
  808. // add all the selectors from the rule as listeners
  809. Object.keys(ruleListeners).forEach(selector => {
  810. emitter.on(
  811. selector,
  812. timing.enabled
  813. ? timing.time(ruleId, ruleListeners[selector])
  814. : ruleListeners[selector]
  815. );
  816. });
  817. });
  818. // only run code path analyzer if the top level node is "Program", skip otherwise
  819. const eventGenerator = nodeQueue[0].node.type === "Program" ? new CodePathAnalyzer(new NodeEventGenerator(emitter)) : new NodeEventGenerator(emitter);
  820. nodeQueue.forEach(traversalInfo => {
  821. currentNode = traversalInfo.node;
  822. try {
  823. if (traversalInfo.isEntering) {
  824. eventGenerator.enterNode(currentNode);
  825. } else {
  826. eventGenerator.leaveNode(currentNode);
  827. }
  828. } catch (err) {
  829. err.currentNode = currentNode;
  830. throw err;
  831. }
  832. });
  833. return lintingProblems;
  834. }
  835. /**
  836. * Ensure the source code to be a string.
  837. * @param {string|SourceCode} textOrSourceCode The text or source code object.
  838. * @returns {string} The source code text.
  839. */
  840. function ensureText(textOrSourceCode) {
  841. if (typeof textOrSourceCode === "object") {
  842. const { hasBOM, text } = textOrSourceCode;
  843. const bom = hasBOM ? "\uFEFF" : "";
  844. return bom + text;
  845. }
  846. return String(textOrSourceCode);
  847. }
  848. /**
  849. * Get an environment.
  850. * @param {LinterInternalSlots} slots The internal slots of Linter.
  851. * @param {string} envId The environment ID to get.
  852. * @returns {Environment|null} The environment.
  853. */
  854. function getEnv(slots, envId) {
  855. return (
  856. (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) ||
  857. BuiltInEnvironments.get(envId) ||
  858. null
  859. );
  860. }
  861. /**
  862. * Get a rule.
  863. * @param {LinterInternalSlots} slots The internal slots of Linter.
  864. * @param {string} ruleId The rule ID to get.
  865. * @returns {Rule|null} The rule.
  866. */
  867. function getRule(slots, ruleId) {
  868. return (
  869. (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) ||
  870. slots.ruleMap.get(ruleId)
  871. );
  872. }
  873. /**
  874. * Normalize the value of the cwd
  875. * @param {string | undefined} cwd raw value of the cwd, path to a directory that should be considered as the current working directory, can be undefined.
  876. * @returns {string | undefined} normalized cwd
  877. */
  878. function normalizeCwd(cwd) {
  879. if (cwd) {
  880. return cwd;
  881. }
  882. if (typeof process === "object") {
  883. return process.cwd();
  884. }
  885. // It's more explicit to assign the undefined
  886. // eslint-disable-next-line no-undefined
  887. return undefined;
  888. }
  889. /**
  890. * The map to store private data.
  891. * @type {WeakMap<Linter, LinterInternalSlots>}
  892. */
  893. const internalSlotsMap = new WeakMap();
  894. //------------------------------------------------------------------------------
  895. // Public Interface
  896. //------------------------------------------------------------------------------
  897. /**
  898. * Object that is responsible for verifying JavaScript text
  899. * @name eslint
  900. */
  901. class Linter {
  902. /**
  903. * Initialize the Linter.
  904. * @param {Object} [config] the config object
  905. * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined.
  906. */
  907. constructor({ cwd } = {}) {
  908. internalSlotsMap.set(this, {
  909. cwd: normalizeCwd(cwd),
  910. lastConfigArray: null,
  911. lastSourceCode: null,
  912. parserMap: new Map([["espree", espree]]),
  913. ruleMap: new Rules()
  914. });
  915. this.version = pkg.version;
  916. }
  917. /**
  918. * Getter for package version.
  919. * @static
  920. * @returns {string} The version from package.json.
  921. */
  922. static get version() {
  923. return pkg.version;
  924. }
  925. /**
  926. * Same as linter.verify, except without support for processors.
  927. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  928. * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything.
  929. * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
  930. * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
  931. */
  932. _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
  933. const slots = internalSlotsMap.get(this);
  934. const config = providedConfig || {};
  935. const options = normalizeVerifyOptions(providedOptions, config);
  936. let text;
  937. // evaluate arguments
  938. if (typeof textOrSourceCode === "string") {
  939. slots.lastSourceCode = null;
  940. text = textOrSourceCode;
  941. } else {
  942. slots.lastSourceCode = textOrSourceCode;
  943. text = textOrSourceCode.text;
  944. }
  945. // Resolve parser.
  946. let parserName = DEFAULT_PARSER_NAME;
  947. let parser = espree;
  948. if (typeof config.parser === "object" && config.parser !== null) {
  949. parserName = config.parser.filePath;
  950. parser = config.parser.definition;
  951. } else if (typeof config.parser === "string") {
  952. if (!slots.parserMap.has(config.parser)) {
  953. return [{
  954. ruleId: null,
  955. fatal: true,
  956. severity: 2,
  957. message: `Configured parser '${config.parser}' was not found.`,
  958. line: 0,
  959. column: 0
  960. }];
  961. }
  962. parserName = config.parser;
  963. parser = slots.parserMap.get(config.parser);
  964. }
  965. // search and apply "eslint-env *".
  966. const envInFile = options.allowInlineConfig && !options.warnInlineConfig
  967. ? findEslintEnv(text)
  968. : {};
  969. const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile);
  970. const enabledEnvs = Object.keys(resolvedEnvConfig)
  971. .filter(envName => resolvedEnvConfig[envName])
  972. .map(envName => getEnv(slots, envName))
  973. .filter(env => env);
  974. const parserOptions = resolveParserOptions(parserName, config.parserOptions || {}, enabledEnvs);
  975. const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
  976. const settings = config.settings || {};
  977. if (!slots.lastSourceCode) {
  978. const parseResult = parse(
  979. text,
  980. parser,
  981. parserOptions,
  982. options.filename
  983. );
  984. if (!parseResult.success) {
  985. return [parseResult.error];
  986. }
  987. slots.lastSourceCode = parseResult.sourceCode;
  988. } else {
  989. /*
  990. * If the given source code object as the first argument does not have scopeManager, analyze the scope.
  991. * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
  992. */
  993. if (!slots.lastSourceCode.scopeManager) {
  994. slots.lastSourceCode = new SourceCode({
  995. text: slots.lastSourceCode.text,
  996. ast: slots.lastSourceCode.ast,
  997. parserServices: slots.lastSourceCode.parserServices,
  998. visitorKeys: slots.lastSourceCode.visitorKeys,
  999. scopeManager: analyzeScope(slots.lastSourceCode.ast, parserOptions)
  1000. });
  1001. }
  1002. }
  1003. const sourceCode = slots.lastSourceCode;
  1004. const commentDirectives = options.allowInlineConfig
  1005. ? getDirectiveComments(options.filename, sourceCode.ast, ruleId => getRule(slots, ruleId), options.warnInlineConfig)
  1006. : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
  1007. // augment global scope with declared global variables
  1008. addDeclaredGlobals(
  1009. sourceCode.scopeManager.scopes[0],
  1010. configuredGlobals,
  1011. { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
  1012. );
  1013. const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
  1014. let lintingProblems;
  1015. try {
  1016. lintingProblems = runRules(
  1017. sourceCode,
  1018. configuredRules,
  1019. ruleId => getRule(slots, ruleId),
  1020. parserOptions,
  1021. parserName,
  1022. settings,
  1023. options.filename,
  1024. options.disableFixes,
  1025. slots.cwd
  1026. );
  1027. } catch (err) {
  1028. err.message += `\nOccurred while linting ${options.filename}`;
  1029. debug("An error occurred while traversing");
  1030. debug("Filename:", options.filename);
  1031. if (err.currentNode) {
  1032. const { line } = err.currentNode.loc.start;
  1033. debug("Line:", line);
  1034. err.message += `:${line}`;
  1035. }
  1036. debug("Parser Options:", parserOptions);
  1037. debug("Parser Path:", parserName);
  1038. debug("Settings:", settings);
  1039. throw err;
  1040. }
  1041. return applyDisableDirectives({
  1042. directives: commentDirectives.disableDirectives,
  1043. problems: lintingProblems
  1044. .concat(commentDirectives.problems)
  1045. .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
  1046. reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
  1047. });
  1048. }
  1049. /**
  1050. * Verifies the text against the rules specified by the second argument.
  1051. * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
  1052. * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything.
  1053. * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked.
  1054. * If this is not set, the filename will default to '<input>' in the rule context. If
  1055. * an object, then it has "filename", "allowInlineConfig", and some properties.
  1056. * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
  1057. */
  1058. verify(textOrSourceCode, config, filenameOrOptions) {
  1059. debug("Verify");
  1060. const options = typeof filenameOrOptions === "string"
  1061. ? { filename: filenameOrOptions }
  1062. : filenameOrOptions || {};
  1063. // CLIEngine passes a `ConfigArray` object.
  1064. if (config && typeof config.extractConfig === "function") {
  1065. return this._verifyWithConfigArray(textOrSourceCode, config, options);
  1066. }
  1067. /*
  1068. * `Linter` doesn't support `overrides` property in configuration.
  1069. * So we cannot apply multiple processors.
  1070. */
  1071. if (options.preprocess || options.postprocess) {
  1072. return this._verifyWithProcessor(textOrSourceCode, config, options);
  1073. }
  1074. return this._verifyWithoutProcessors(textOrSourceCode, config, options);
  1075. }
  1076. /**
  1077. * Verify a given code with `ConfigArray`.
  1078. * @param {string|SourceCode} textOrSourceCode The source code.
  1079. * @param {ConfigArray} configArray The config array.
  1080. * @param {VerifyOptions&ProcessorOptions} options The options.
  1081. * @returns {LintMessage[]} The found problems.
  1082. */
  1083. _verifyWithConfigArray(textOrSourceCode, configArray, options) {
  1084. debug("With ConfigArray: %s", options.filename);
  1085. // Store the config array in order to get plugin envs and rules later.
  1086. internalSlotsMap.get(this).lastConfigArray = configArray;
  1087. // Extract the final config for this file.
  1088. const config = configArray.extractConfig(options.filename);
  1089. const processor =
  1090. config.processor &&
  1091. configArray.pluginProcessors.get(config.processor);
  1092. // Verify.
  1093. if (processor) {
  1094. debug("Apply the processor: %o", config.processor);
  1095. const { preprocess, postprocess, supportsAutofix } = processor;
  1096. const disableFixes = options.disableFixes || !supportsAutofix;
  1097. return this._verifyWithProcessor(
  1098. textOrSourceCode,
  1099. config,
  1100. { ...options, disableFixes, postprocess, preprocess },
  1101. configArray
  1102. );
  1103. }
  1104. return this._verifyWithoutProcessors(textOrSourceCode, config, options);
  1105. }
  1106. /**
  1107. * Verify with a processor.
  1108. * @param {string|SourceCode} textOrSourceCode The source code.
  1109. * @param {ConfigData|ExtractedConfig} config The config array.
  1110. * @param {VerifyOptions&ProcessorOptions} options The options.
  1111. * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
  1112. * @returns {LintMessage[]} The found problems.
  1113. */
  1114. _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) {
  1115. const filename = options.filename || "<input>";
  1116. const filenameToExpose = normalizeFilename(filename);
  1117. const text = ensureText(textOrSourceCode);
  1118. const preprocess = options.preprocess || (rawText => [rawText]);
  1119. const postprocess = options.postprocess || lodash.flatten;
  1120. const filterCodeBlock =
  1121. options.filterCodeBlock ||
  1122. (blockFilename => blockFilename.endsWith(".js"));
  1123. const originalExtname = path.extname(filename);
  1124. const messageLists = preprocess(text, filenameToExpose).map((block, i) => {
  1125. debug("A code block was found: %o", block.filename || "(unnamed)");
  1126. // Keep the legacy behavior.
  1127. if (typeof block === "string") {
  1128. return this._verifyWithoutProcessors(block, config, options);
  1129. }
  1130. const blockText = block.text;
  1131. const blockName = path.join(filename, `${i}_${block.filename}`);
  1132. // Skip this block if filtered.
  1133. if (!filterCodeBlock(blockName, blockText)) {
  1134. debug("This code block was skipped.");
  1135. return [];
  1136. }
  1137. // Resolve configuration again if the file extension was changed.
  1138. if (configForRecursive && path.extname(blockName) !== originalExtname) {
  1139. debug("Resolving configuration again because the file extension was changed.");
  1140. return this._verifyWithConfigArray(
  1141. blockText,
  1142. configForRecursive,
  1143. { ...options, filename: blockName }
  1144. );
  1145. }
  1146. // Does lint.
  1147. return this._verifyWithoutProcessors(
  1148. blockText,
  1149. config,
  1150. { ...options, filename: blockName }
  1151. );
  1152. });
  1153. return postprocess(messageLists, filenameToExpose);
  1154. }
  1155. /**
  1156. * Gets the SourceCode object representing the parsed source.
  1157. * @returns {SourceCode} The SourceCode object.
  1158. */
  1159. getSourceCode() {
  1160. return internalSlotsMap.get(this).lastSourceCode;
  1161. }
  1162. /**
  1163. * Defines a new linting rule.
  1164. * @param {string} ruleId A unique rule identifier
  1165. * @param {Function | Rule} ruleModule Function from context to object mapping AST node types to event handlers
  1166. * @returns {void}
  1167. */
  1168. defineRule(ruleId, ruleModule) {
  1169. internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule);
  1170. }
  1171. /**
  1172. * Defines many new linting rules.
  1173. * @param {Record<string, Function | Rule>} rulesToDefine map from unique rule identifier to rule
  1174. * @returns {void}
  1175. */
  1176. defineRules(rulesToDefine) {
  1177. Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
  1178. this.defineRule(ruleId, rulesToDefine[ruleId]);
  1179. });
  1180. }
  1181. /**
  1182. * Gets an object with all loaded rules.
  1183. * @returns {Map<string, Rule>} All loaded rules
  1184. */
  1185. getRules() {
  1186. const { lastConfigArray, ruleMap } = internalSlotsMap.get(this);
  1187. return new Map(function *() {
  1188. yield* ruleMap;
  1189. if (lastConfigArray) {
  1190. yield* lastConfigArray.pluginRules;
  1191. }
  1192. }());
  1193. }
  1194. /**
  1195. * Define a new parser module
  1196. * @param {string} parserId Name of the parser
  1197. * @param {Parser} parserModule The parser object
  1198. * @returns {void}
  1199. */
  1200. defineParser(parserId, parserModule) {
  1201. internalSlotsMap.get(this).parserMap.set(parserId, parserModule);
  1202. }
  1203. /**
  1204. * Performs multiple autofix passes over the text until as many fixes as possible
  1205. * have been applied.
  1206. * @param {string} text The source text to apply fixes to.
  1207. * @param {ConfigData|ConfigArray} config The ESLint config object to use.
  1208. * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use.
  1209. * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the
  1210. * SourceCodeFixer.
  1211. */
  1212. verifyAndFix(text, config, options) {
  1213. let messages = [],
  1214. fixedResult,
  1215. fixed = false,
  1216. passNumber = 0,
  1217. currentText = text;
  1218. const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`;
  1219. const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
  1220. /**
  1221. * This loop continues until one of the following is true:
  1222. *
  1223. * 1. No more fixes have been applied.
  1224. * 2. Ten passes have been made.
  1225. *
  1226. * That means anytime a fix is successfully applied, there will be another pass.
  1227. * Essentially, guaranteeing a minimum of two passes.
  1228. */
  1229. do {
  1230. passNumber++;
  1231. debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`);
  1232. messages = this.verify(currentText, config, options);
  1233. debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`);
  1234. fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
  1235. /*
  1236. * stop if there are any syntax errors.
  1237. * 'fixedResult.output' is a empty string.
  1238. */
  1239. if (messages.length === 1 && messages[0].fatal) {
  1240. break;
  1241. }
  1242. // keep track if any fixes were ever applied - important for return value
  1243. fixed = fixed || fixedResult.fixed;
  1244. // update to use the fixed output instead of the original text
  1245. currentText = fixedResult.output;
  1246. } while (
  1247. fixedResult.fixed &&
  1248. passNumber < MAX_AUTOFIX_PASSES
  1249. );
  1250. /*
  1251. * If the last result had fixes, we need to lint again to be sure we have
  1252. * the most up-to-date information.
  1253. */
  1254. if (fixedResult.fixed) {
  1255. fixedResult.messages = this.verify(currentText, config, options);
  1256. }
  1257. // ensure the last result properly reflects if fixes were done
  1258. fixedResult.fixed = fixed;
  1259. fixedResult.output = currentText;
  1260. return fixedResult;
  1261. }
  1262. }
  1263. module.exports = {
  1264. Linter,
  1265. /**
  1266. * Get the internal slots of a given Linter instance for tests.
  1267. * @param {Linter} instance The Linter instance to get.
  1268. * @returns {LinterInternalSlots} The internal slots.
  1269. */
  1270. getLinterInternalSlots(instance) {
  1271. return internalSlotsMap.get(instance);
  1272. }
  1273. };