2 * @fileoverview Main Linter Class
3 * @author Gyandeep Singh
9 //------------------------------------------------------------------------------
11 //------------------------------------------------------------------------------
14 path = require("path"),
15 eslintScope = require("eslint-scope"),
16 evk = require("eslint-visitor-keys"),
17 espree = require("espree"),
18 merge = require("lodash.merge"),
19 BuiltInEnvironments = require("@eslint/eslintrc/conf/environments"),
20 pkg = require("../../package.json"),
21 astUtils = require("../shared/ast-utils"),
22 ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"),
23 ConfigValidator = require("@eslint/eslintrc/lib/shared/config-validator"),
24 Traverser = require("../shared/traverser"),
25 { SourceCode } = require("../source-code"),
26 CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"),
27 applyDisableDirectives = require("./apply-disable-directives"),
28 ConfigCommentParser = require("./config-comment-parser"),
29 NodeEventGenerator = require("./node-event-generator"),
30 createReportTranslator = require("./report-translator"),
31 Rules = require("./rules"),
32 createEmitter = require("./safe-emitter"),
33 SourceCodeFixer = require("./source-code-fixer"),
34 timing = require("./timing"),
35 ruleReplacements = require("../../conf/replacements.json");
37 const debug = require("debug")("eslint:linter");
38 const MAX_AUTOFIX_PASSES = 10;
39 const DEFAULT_PARSER_NAME = "espree";
40 const DEFAULT_ECMA_VERSION = 5;
41 const commentParser = new ConfigCommentParser();
42 const DEFAULT_ERROR_LOC = { start: { line: 1, column: 0 }, end: { line: 1, column: 1 } };
43 const parserSymbol = Symbol.for("eslint.RuleTester.parser");
45 //------------------------------------------------------------------------------
47 //------------------------------------------------------------------------------
49 /** @typedef {InstanceType<import("../cli-engine/config-array")["ConfigArray"]>} ConfigArray */
50 /** @typedef {InstanceType<import("../cli-engine/config-array")["ExtractedConfig"]>} ExtractedConfig */
51 /** @typedef {import("../shared/types").ConfigData} ConfigData */
52 /** @typedef {import("../shared/types").Environment} Environment */
53 /** @typedef {import("../shared/types").GlobalConf} GlobalConf */
54 /** @typedef {import("../shared/types").LintMessage} LintMessage */
55 /** @typedef {import("../shared/types").ParserOptions} ParserOptions */
56 /** @typedef {import("../shared/types").Processor} Processor */
57 /** @typedef {import("../shared/types").Rule} Rule */
61 * @typedef {{ [P in keyof T]-?: T[P] }} Required
65 * @typedef {Object} DisableDirective
66 * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type
67 * @property {number} line
68 * @property {number} column
69 * @property {(string|null)} ruleId
73 * The private data for `Linter` instance.
74 * @typedef {Object} LinterInternalSlots
75 * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used.
76 * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used.
77 * @property {Map<string, Parser>} parserMap The loaded parsers.
78 * @property {Rules} ruleMap The loaded rules.
82 * @typedef {Object} VerifyOptions
83 * @property {boolean} [allowInlineConfig] Allow/disallow inline comments' ability
84 * to change config once it is set. Defaults to true if not supplied.
85 * Useful if you want to validate JS without comments overriding rules.
86 * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix`
87 * properties into the lint result.
88 * @property {string} [filename] the filename of the source code.
89 * @property {boolean | "off" | "warn" | "error"} [reportUnusedDisableDirectives] Adds reported errors for
90 * unused `eslint-disable` directives.
94 * @typedef {Object} ProcessorOptions
95 * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the
96 * predicate function that selects adopt code blocks.
97 * @property {Processor["postprocess"]} [postprocess] postprocessor for report
98 * messages. If provided, this should accept an array of the message lists
99 * for each code block returned from the preprocessor, apply a mapping to
100 * the messages as appropriate, and return a one-dimensional array of
102 * @property {Processor["preprocess"]} [preprocess] preprocessor for source text.
103 * If provided, this should accept a string of source text, and return an
104 * array of code blocks to lint.
108 * @typedef {Object} FixOptions
109 * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines
110 * whether fixes should be applied.
114 * @typedef {Object} InternalOptions
115 * @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.
116 * @property {"off" | "warn" | "error"} reportUnusedDisableDirectives (boolean values were normalized)
119 //------------------------------------------------------------------------------
121 //------------------------------------------------------------------------------
124 * Ensures that variables representing built-in properties of the Global Object,
125 * and any globals declared by special block comments, are present in the global
127 * @param {Scope} globalScope The global scope.
128 * @param {Object} configGlobals The globals declared in configuration
129 * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration
132 function addDeclaredGlobals(globalScope, configGlobals, { exportedVariables, enabledGlobals }) {
134 // Define configured global variables.
135 for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(enabledGlobals)])) {
138 * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would
139 * typically be caught when validating a config anyway (validity for inline global comments is checked separately).
141 const configValue = configGlobals[id] === void 0 ? void 0 : ConfigOps.normalizeConfigGlobal(configGlobals[id]);
142 const commentValue = enabledGlobals[id] && enabledGlobals[id].value;
143 const value = commentValue || configValue;
144 const sourceComments = enabledGlobals[id] && enabledGlobals[id].comments;
146 if (value === "off") {
150 let variable = globalScope.set.get(id);
153 variable = new eslintScope.Variable(id, globalScope);
155 globalScope.variables.push(variable);
156 globalScope.set.set(id, variable);
159 variable.eslintImplicitGlobalSetting = configValue;
160 variable.eslintExplicitGlobal = sourceComments !== void 0;
161 variable.eslintExplicitGlobalComments = sourceComments;
162 variable.writeable = (value === "writable");
165 // mark all exported variables as such
166 Object.keys(exportedVariables).forEach(name => {
167 const variable = globalScope.set.get(name);
170 variable.eslintUsed = true;
175 * "through" contains all references which definitions cannot be found.
176 * Since we augment the global scope using configuration, we need to update
177 * references and remove the ones that were added by configuration.
179 globalScope.through = globalScope.through.filter(reference => {
180 const name = reference.identifier.name;
181 const variable = globalScope.set.get(name);
186 * Links the variable and the reference.
187 * And this reference is removed from `Scope#through`.
189 reference.resolved = variable;
190 variable.references.push(reference);
200 * creates a missing-rule message.
201 * @param {string} ruleId the ruleId to create
202 * @returns {string} created error message
205 function createMissingRuleMessage(ruleId) {
206 return Object.prototype.hasOwnProperty.call(ruleReplacements.rules, ruleId)
207 ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}`
208 : `Definition for rule '${ruleId}' was not found.`;
212 * creates a linting problem
213 * @param {Object} options to create linting error
214 * @param {string} [options.ruleId] the ruleId to report
215 * @param {Object} [options.loc] the loc to report
216 * @param {string} [options.message] the error message to report
217 * @param {string} [options.severity] the error message to report
218 * @returns {LintMessage} created problem, returns a missing-rule problem if only provided ruleId.
221 function createLintingProblem(options) {
224 loc = DEFAULT_ERROR_LOC,
225 message = createMissingRuleMessage(options.ruleId),
232 line: loc.start.line,
233 column: loc.start.column + 1,
234 endLine: loc.end.line,
235 endColumn: loc.end.column + 1,
242 * Creates a collection of disable directives from a comment
243 * @param {Object} options to create disable directives
244 * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment
245 * @param {{line: number, column: number}} options.loc The 0-based location of the comment token
246 * @param {string} options.value The value after the directive in the comment
247 * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`)
248 * @param {function(string): {create: Function}} options.ruleMapper A map from rule IDs to defined rules
249 * @returns {Object} Directives and problems from the comment
251 function createDisableDirectives(options) {
252 const { type, loc, value, ruleMapper } = options;
253 const ruleIds = Object.keys(commentParser.parseListConfig(value));
254 const directiveRules = ruleIds.length ? ruleIds : [null];
256 directives: [], // valid disable directives
257 directiveProblems: [] // problems in directives
260 for (const ruleId of directiveRules) {
262 // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/)
263 if (ruleId === null || ruleMapper(ruleId) !== null) {
264 result.directives.push({ type, line: loc.start.line, column: loc.start.column + 1, ruleId });
266 result.directiveProblems.push(createLintingProblem({ ruleId, loc }));
273 * Remove the ignored part from a given directive comment and trim it.
274 * @param {string} value The comment text to strip.
275 * @returns {string} The stripped text.
277 function stripDirectiveComment(value) {
278 return value.split(/\s-{2,}\s/u)[0].trim();
282 * Parses comments in file to extract file-specific config of rules, globals
283 * and environments and merges them with global config; also code blocks
284 * where reporting is disabled or enabled and merges them with reporting config.
285 * @param {string} filename The file being checked.
286 * @param {ASTNode} ast The top node of the AST.
287 * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
288 * @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.
289 * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], exportedVariables: Object, problems: Problem[], disableDirectives: DisableDirective[]}}
290 * A collection of the directive comments that were found, along with any problems that occurred when parsing
292 function getDirectiveComments(filename, ast, ruleMapper, warnInlineConfig) {
293 const configuredRules = {};
294 const enabledGlobals = Object.create(null);
295 const exportedVariables = {};
297 const disableDirectives = [];
298 const validator = new ConfigValidator({
302 ast.comments.filter(token => token.type !== "Shebang").forEach(comment => {
303 const trimmedCommentText = stripDirectiveComment(comment.value);
304 const match = /^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u.exec(trimmedCommentText);
309 const directiveText = match[1];
310 const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(directiveText);
312 if (comment.type === "Line" && !lineCommentSupported) {
316 if (warnInlineConfig) {
317 const kind = comment.type === "Block" ? `/*${directiveText}*/` : `//${directiveText}`;
319 problems.push(createLintingProblem({
321 message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`,
328 if (lineCommentSupported && comment.loc.start.line !== comment.loc.end.line) {
329 const message = `${directiveText} comment should not span multiple lines.`;
331 problems.push(createLintingProblem({
339 const directiveValue = trimmedCommentText.slice(match.index + directiveText.length);
341 switch (directiveText) {
342 case "eslint-disable":
343 case "eslint-enable":
344 case "eslint-disable-next-line":
345 case "eslint-disable-line": {
346 const directiveType = directiveText.slice("eslint-".length);
347 const options = { type: directiveType, loc: comment.loc, value: directiveValue, ruleMapper };
348 const { directives, directiveProblems } = createDisableDirectives(options);
350 disableDirectives.push(...directives);
351 problems.push(...directiveProblems);
356 Object.assign(exportedVariables, commentParser.parseStringConfig(directiveValue, comment));
361 for (const [id, { value }] of Object.entries(commentParser.parseStringConfig(directiveValue, comment))) {
365 normalizedValue = ConfigOps.normalizeConfigGlobal(value);
367 problems.push(createLintingProblem({
375 if (enabledGlobals[id]) {
376 enabledGlobals[id].comments.push(comment);
377 enabledGlobals[id].value = normalizedValue;
379 enabledGlobals[id] = {
381 value: normalizedValue
388 const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc);
390 if (parseResult.success) {
391 Object.keys(parseResult.config).forEach(name => {
392 const rule = ruleMapper(name);
393 const ruleValue = parseResult.config[name];
396 problems.push(createLintingProblem({ ruleId: name, loc: comment.loc }));
401 validator.validateRuleOptions(rule, name, ruleValue);
403 problems.push(createLintingProblem({
405 message: err.message,
409 // do not apply the config, if found invalid options.
413 configuredRules[name] = ruleValue;
416 problems.push(parseResult.error);
436 * Normalize ECMAScript version from the initial config
437 * @param {Parser} parser The parser which uses this options.
438 * @param {number} ecmaVersion ECMAScript version from the initial config
439 * @returns {number} normalized ECMAScript version
441 function normalizeEcmaVersion(parser, ecmaVersion) {
442 if ((parser[parserSymbol] || parser) === espree) {
443 if (ecmaVersion === "latest") {
444 return espree.latestEcmaVersion;
449 * Calculate ECMAScript edition number from official year version starting with
450 * ES2015, which corresponds with ES6 (or a difference of 2009).
452 return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion;
455 const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gsu;
458 * Checks whether or not there is a comment which has "eslint-env *" in a given text.
459 * @param {string} text A source code text to check.
460 * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment.
462 function findEslintEnv(text) {
465 eslintEnvPattern.lastIndex = 0;
467 while ((match = eslintEnvPattern.exec(text)) !== null) {
468 retv = Object.assign(
470 commentParser.parseListConfig(stripDirectiveComment(match[1]))
478 * Convert "/path/to/<text>" to "<text>".
479 * `CLIEngine#executeOnText()` method gives "/path/to/<text>" if the filename
480 * was omitted because `configArray.extractConfig()` requires an absolute path.
481 * But the linter should pass `<text>` to `RuleContext#getFilename()` in that
483 * Also, code blocks can have their virtual filename. If the parent filename was
484 * `<text>`, the virtual filename is `<text>/0_foo.js` or something like (i.e.,
485 * it's not an absolute path).
486 * @param {string} filename The filename to normalize.
487 * @returns {string} The normalized filename.
489 function normalizeFilename(filename) {
490 const parts = filename.split(path.sep);
491 const index = parts.lastIndexOf("<text>");
493 return index === -1 ? filename : parts.slice(index).join(path.sep);
497 * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
499 * @param {VerifyOptions} providedOptions Options
500 * @param {ConfigData} config Config.
501 * @returns {Required<VerifyOptions> & InternalOptions} Normalized options
503 function normalizeVerifyOptions(providedOptions, config) {
504 const disableInlineConfig = config.noInlineConfig === true;
505 const ignoreInlineConfig = providedOptions.allowInlineConfig === false;
506 const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig
507 ? ` (${config.configNameOfNoInlineConfig})`
510 let reportUnusedDisableDirectives = providedOptions.reportUnusedDisableDirectives;
512 if (typeof reportUnusedDisableDirectives === "boolean") {
513 reportUnusedDisableDirectives = reportUnusedDisableDirectives ? "error" : "off";
515 if (typeof reportUnusedDisableDirectives !== "string") {
516 reportUnusedDisableDirectives = config.reportUnusedDisableDirectives ? "warn" : "off";
520 filename: normalizeFilename(providedOptions.filename || "<input>"),
521 allowInlineConfig: !ignoreInlineConfig,
522 warnInlineConfig: disableInlineConfig && !ignoreInlineConfig
523 ? `your config${configNameOfNoInlineConfig}`
525 reportUnusedDisableDirectives,
526 disableFixes: Boolean(providedOptions.disableFixes)
531 * Combines the provided parserOptions with the options from environments
532 * @param {Parser} parser The parser which uses this options.
533 * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config
534 * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
535 * @returns {ParserOptions} Resulting parser options after merge
537 function resolveParserOptions(parser, providedOptions, enabledEnvironments) {
539 const parserOptionsFromEnv = enabledEnvironments
540 .filter(env => env.parserOptions)
541 .reduce((parserOptions, env) => merge(parserOptions, env.parserOptions), {});
542 const mergedParserOptions = merge(parserOptionsFromEnv, providedOptions || {});
543 const isModule = mergedParserOptions.sourceType === "module";
548 * can't have global return inside of modules
549 * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add)
551 mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
554 mergedParserOptions.ecmaVersion = normalizeEcmaVersion(parser, mergedParserOptions.ecmaVersion);
556 return mergedParserOptions;
560 * Combines the provided globals object with the globals from environments
561 * @param {Record<string, GlobalConf>} providedGlobals The 'globals' key in a config
562 * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
563 * @returns {Record<string, GlobalConf>} The resolved globals object
565 function resolveGlobals(providedGlobals, enabledEnvironments) {
566 return Object.assign(
568 ...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
574 * Strips Unicode BOM from a given text.
575 * @param {string} text A text to strip.
576 * @returns {string} The stripped text.
578 function stripUnicodeBOM(text) {
582 * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF.
583 * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters
585 if (text.charCodeAt(0) === 0xFEFF) {
586 return text.slice(1);
592 * Get the options for a rule (not including severity), if any
593 * @param {Array|number} ruleConfig rule configuration
594 * @returns {Array} of rule options, empty Array if none
596 function getRuleOptions(ruleConfig) {
597 if (Array.isArray(ruleConfig)) {
598 return ruleConfig.slice(1);
605 * Analyze scope of the given AST.
606 * @param {ASTNode} ast The `Program` node to analyze.
607 * @param {ParserOptions} parserOptions The parser options.
608 * @param {Record<string, string[]>} visitorKeys The visitor keys.
609 * @returns {ScopeManager} The analysis result.
611 function analyzeScope(ast, parserOptions, visitorKeys) {
612 const ecmaFeatures = parserOptions.ecmaFeatures || {};
613 const ecmaVersion = parserOptions.ecmaVersion || DEFAULT_ECMA_VERSION;
615 return eslintScope.analyze(ast, {
617 nodejsScope: ecmaFeatures.globalReturn,
618 impliedStrict: ecmaFeatures.impliedStrict,
620 sourceType: parserOptions.sourceType || "script",
621 childVisitorKeys: visitorKeys || evk.KEYS,
622 fallback: Traverser.getKeys
627 * Parses text into an AST. Moved out here because the try-catch prevents
628 * optimization of functions, so it's best to keep the try-catch as isolated
630 * @param {string} text The text to parse.
631 * @param {Parser} parser The parser to parse.
632 * @param {ParserOptions} providedParserOptions Options to pass to the parser
633 * @param {string} filePath The path to the file being parsed.
634 * @returns {{success: false, error: Problem}|{success: true, sourceCode: SourceCode}}
635 * An object containing the AST and parser services if parsing was successful, or the error if parsing failed
638 function parse(text, parser, providedParserOptions, filePath) {
639 const textToParse = stripUnicodeBOM(text).replace(astUtils.shebangPattern, (match, captured) => `//${captured}`);
640 const parserOptions = Object.assign({}, providedParserOptions, {
646 eslintVisitorKeys: true,
647 eslintScopeManager: true,
652 * Check for parsing errors first. If there's a parsing error, nothing
653 * else can happen. However, a parsing error does not throw an error
654 * from this method - it's just considered a fatal error message, a
655 * problem that ESLint identified just like any other.
658 const parseResult = (typeof parser.parseForESLint === "function")
659 ? parser.parseForESLint(textToParse, parserOptions)
660 : { ast: parser.parse(textToParse, parserOptions) };
661 const ast = parseResult.ast;
662 const parserServices = parseResult.services || {};
663 const visitorKeys = parseResult.visitorKeys || evk.KEYS;
664 const scopeManager = parseResult.scopeManager || analyzeScope(ast, parserOptions, visitorKeys);
670 * Save all values that `parseForESLint()` returned.
671 * If a `SourceCode` object is given as the first parameter instead of source code text,
672 * linter skips the parsing process and reuses the source code object.
673 * In that case, linter needs all the values that `parseForESLint()` returned.
675 sourceCode: new SourceCode({
685 // If the message includes a leading line number, strip it:
686 const message = `Parsing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
688 debug("%s\n%s", message, ex.stack);
705 * Gets the scope for the current node
706 * @param {ScopeManager} scopeManager The scope manager for this AST
707 * @param {ASTNode} currentNode The node to get the scope of
708 * @returns {eslint-scope.Scope} The scope information for this node
710 function getScope(scopeManager, currentNode) {
712 // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
713 const inner = currentNode.type !== "Program";
715 for (let node = currentNode; node; node = node.parent) {
716 const scope = scopeManager.acquire(node, inner);
719 if (scope.type === "function-expression-name") {
720 return scope.childScopes[0];
726 return scopeManager.scopes[0];
730 * Marks a variable as used in the current scope
731 * @param {ScopeManager} scopeManager The scope manager for this AST. The scope may be mutated by this function.
732 * @param {ASTNode} currentNode The node currently being traversed
733 * @param {Object} parserOptions The options used to parse this text
734 * @param {string} name The name of the variable that should be marked as used.
735 * @returns {boolean} True if the variable was found and marked as used, false if not.
737 function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
738 const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn;
739 const specialScope = hasGlobalReturn || parserOptions.sourceType === "module";
740 const currentScope = getScope(scopeManager, currentNode);
742 // Special Node.js scope means we need to start one level deeper
743 const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
745 for (let scope = initialScope; scope; scope = scope.upper) {
746 const variable = scope.variables.find(scopeVar => scopeVar.name === name);
749 variable.eslintUsed = true;
758 * Runs a rule, and gets its listeners
759 * @param {Rule} rule A normalized rule with a `create` method
760 * @param {Context} ruleContext The context that should be passed to the rule
761 * @returns {Object} A map of selector listeners provided by the rule
763 function createRuleListeners(rule, ruleContext) {
765 return rule.create(ruleContext);
767 ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
773 * Gets all the ancestors of a given node
774 * @param {ASTNode} node The node
775 * @returns {ASTNode[]} All the ancestor nodes in the AST, not including the provided node, starting
776 * from the root node and going inwards to the parent node.
778 function getAncestors(node) {
779 const ancestorsStartingAtParent = [];
781 for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
782 ancestorsStartingAtParent.push(ancestor);
785 return ancestorsStartingAtParent.reverse();
788 // methods that exist on SourceCode object
789 const DEPRECATED_SOURCECODE_PASSTHROUGHS = {
790 getSource: "getText",
791 getSourceLines: "getLines",
792 getAllComments: "getAllComments",
793 getNodeByRangeIndex: "getNodeByRangeIndex",
794 getComments: "getComments",
795 getCommentsBefore: "getCommentsBefore",
796 getCommentsAfter: "getCommentsAfter",
797 getCommentsInside: "getCommentsInside",
798 getJSDocComment: "getJSDocComment",
799 getFirstToken: "getFirstToken",
800 getFirstTokens: "getFirstTokens",
801 getLastToken: "getLastToken",
802 getLastTokens: "getLastTokens",
803 getTokenAfter: "getTokenAfter",
804 getTokenBefore: "getTokenBefore",
805 getTokenByRangeStart: "getTokenByRangeStart",
806 getTokens: "getTokens",
807 getTokensAfter: "getTokensAfter",
808 getTokensBefore: "getTokensBefore",
809 getTokensBetween: "getTokensBetween"
812 const BASE_TRAVERSAL_CONTEXT = Object.freeze(
813 Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).reduce(
814 (contextInfo, methodName) =>
815 Object.assign(contextInfo, {
816 [methodName](...args) {
817 return this.getSourceCode()[DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]](...args);
825 * Runs the given rules on the given SourceCode object
826 * @param {SourceCode} sourceCode A SourceCode object for the given text
827 * @param {Object} configuredRules The rules configuration
828 * @param {function(string): Rule} ruleMapper A mapper function from rule names to rules
829 * @param {Object} parserOptions The options that were passed to the parser
830 * @param {string} parserName The name of the parser in the config
831 * @param {Object} settings The settings that were enabled in the config
832 * @param {string} filename The reported filename of the code
833 * @param {boolean} disableFixes If true, it doesn't make `fix` properties.
834 * @param {string | undefined} cwd cwd of the cli
835 * @param {string} physicalFilename The full path of the file on disk without any code block information
836 * @returns {Problem[]} An array of reported problems
838 function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parserName, settings, filename, disableFixes, cwd, physicalFilename) {
839 const emitter = createEmitter();
840 const nodeQueue = [];
841 let currentNode = sourceCode.ast;
843 Traverser.traverse(sourceCode.ast, {
844 enter(node, parent) {
845 node.parent = parent;
846 nodeQueue.push({ isEntering: true, node });
849 nodeQueue.push({ isEntering: false, node });
851 visitorKeys: sourceCode.visitorKeys
855 * Create a frozen object with the ruleContext properties and methods that are shared by all rules.
856 * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the
857 * properties once for each rule.
859 const sharedTraversalContext = Object.freeze(
861 Object.create(BASE_TRAVERSAL_CONTEXT),
863 getAncestors: () => getAncestors(currentNode),
864 getDeclaredVariables: sourceCode.scopeManager.getDeclaredVariables.bind(sourceCode.scopeManager),
866 getFilename: () => filename,
867 getPhysicalFilename: () => physicalFilename || filename,
868 getScope: () => getScope(sourceCode.scopeManager, currentNode),
869 getSourceCode: () => sourceCode,
870 markVariableAsUsed: name => markVariableAsUsed(sourceCode.scopeManager, currentNode, parserOptions, name),
872 parserPath: parserName,
873 parserServices: sourceCode.parserServices,
880 const lintingProblems = [];
882 Object.keys(configuredRules).forEach(ruleId => {
883 const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]);
885 // not load disabled rules
886 if (severity === 0) {
890 const rule = ruleMapper(ruleId);
893 lintingProblems.push(createLintingProblem({ ruleId }));
897 const messageIds = rule.meta && rule.meta.messages;
898 let reportTranslator = null;
899 const ruleContext = Object.freeze(
901 Object.create(sharedTraversalContext),
904 options: getRuleOptions(configuredRules[ruleId]),
908 * Create a report translator lazily.
909 * In a vast majority of cases, any given rule reports zero errors on a given
910 * piece of code. Creating a translator lazily avoids the performance cost of
911 * creating a new translator function for each rule that usually doesn't get
914 * Using lazy report translators improves end-to-end performance by about 3%
917 if (reportTranslator === null) {
918 reportTranslator = createReportTranslator({
926 const problem = reportTranslator(...args);
928 if (problem.fix && rule.meta && !rule.meta.fixable) {
929 throw new Error("Fixable rules should export a `meta.fixable` property.");
931 lintingProblems.push(problem);
937 const ruleListeners = createRuleListeners(rule, ruleContext);
939 // add all the selectors from the rule as listeners
940 Object.keys(ruleListeners).forEach(selector => {
944 ? timing.time(ruleId, ruleListeners[selector])
945 : ruleListeners[selector]
950 // only run code path analyzer if the top level node is "Program", skip otherwise
951 const eventGenerator = nodeQueue[0].node.type === "Program"
952 ? new CodePathAnalyzer(new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys }))
953 : new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys });
955 nodeQueue.forEach(traversalInfo => {
956 currentNode = traversalInfo.node;
959 if (traversalInfo.isEntering) {
960 eventGenerator.enterNode(currentNode);
962 eventGenerator.leaveNode(currentNode);
965 err.currentNode = currentNode;
970 return lintingProblems;
974 * Ensure the source code to be a string.
975 * @param {string|SourceCode} textOrSourceCode The text or source code object.
976 * @returns {string} The source code text.
978 function ensureText(textOrSourceCode) {
979 if (typeof textOrSourceCode === "object") {
980 const { hasBOM, text } = textOrSourceCode;
981 const bom = hasBOM ? "\uFEFF" : "";
986 return String(textOrSourceCode);
990 * Get an environment.
991 * @param {LinterInternalSlots} slots The internal slots of Linter.
992 * @param {string} envId The environment ID to get.
993 * @returns {Environment|null} The environment.
995 function getEnv(slots, envId) {
997 (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) ||
998 BuiltInEnvironments.get(envId) ||
1005 * @param {LinterInternalSlots} slots The internal slots of Linter.
1006 * @param {string} ruleId The rule ID to get.
1007 * @returns {Rule|null} The rule.
1009 function getRule(slots, ruleId) {
1011 (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) ||
1012 slots.ruleMap.get(ruleId)
1017 * Normalize the value of the cwd
1018 * @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.
1019 * @returns {string | undefined} normalized cwd
1021 function normalizeCwd(cwd) {
1025 if (typeof process === "object") {
1026 return process.cwd();
1029 // It's more explicit to assign the undefined
1030 // eslint-disable-next-line no-undefined
1035 * The map to store private data.
1036 * @type {WeakMap<Linter, LinterInternalSlots>}
1038 const internalSlotsMap = new WeakMap();
1040 //------------------------------------------------------------------------------
1042 //------------------------------------------------------------------------------
1045 * Object that is responsible for verifying JavaScript text
1051 * Initialize the Linter.
1052 * @param {Object} [config] the config object
1053 * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined.
1055 constructor({ cwd } = {}) {
1056 internalSlotsMap.set(this, {
1057 cwd: normalizeCwd(cwd),
1058 lastConfigArray: null,
1059 lastSourceCode: null,
1060 parserMap: new Map([["espree", espree]]),
1061 ruleMap: new Rules()
1064 this.version = pkg.version;
1068 * Getter for package version.
1070 * @returns {string} The version from package.json.
1072 static get version() {
1077 * Same as linter.verify, except without support for processors.
1078 * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
1079 * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything.
1080 * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
1081 * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
1083 _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
1084 const slots = internalSlotsMap.get(this);
1085 const config = providedConfig || {};
1086 const options = normalizeVerifyOptions(providedOptions, config);
1089 // evaluate arguments
1090 if (typeof textOrSourceCode === "string") {
1091 slots.lastSourceCode = null;
1092 text = textOrSourceCode;
1094 slots.lastSourceCode = textOrSourceCode;
1095 text = textOrSourceCode.text;
1099 let parserName = DEFAULT_PARSER_NAME;
1100 let parser = espree;
1102 if (typeof config.parser === "object" && config.parser !== null) {
1103 parserName = config.parser.filePath;
1104 parser = config.parser.definition;
1105 } else if (typeof config.parser === "string") {
1106 if (!slots.parserMap.has(config.parser)) {
1111 message: `Configured parser '${config.parser}' was not found.`,
1116 parserName = config.parser;
1117 parser = slots.parserMap.get(config.parser);
1120 // search and apply "eslint-env *".
1121 const envInFile = options.allowInlineConfig && !options.warnInlineConfig
1122 ? findEslintEnv(text)
1124 const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile);
1125 const enabledEnvs = Object.keys(resolvedEnvConfig)
1126 .filter(envName => resolvedEnvConfig[envName])
1127 .map(envName => getEnv(slots, envName))
1128 .filter(env => env);
1130 const parserOptions = resolveParserOptions(parser, config.parserOptions || {}, enabledEnvs);
1131 const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
1132 const settings = config.settings || {};
1134 if (!slots.lastSourceCode) {
1135 const parseResult = parse(
1142 if (!parseResult.success) {
1143 return [parseResult.error];
1146 slots.lastSourceCode = parseResult.sourceCode;
1150 * If the given source code object as the first argument does not have scopeManager, analyze the scope.
1151 * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
1153 if (!slots.lastSourceCode.scopeManager) {
1154 slots.lastSourceCode = new SourceCode({
1155 text: slots.lastSourceCode.text,
1156 ast: slots.lastSourceCode.ast,
1157 parserServices: slots.lastSourceCode.parserServices,
1158 visitorKeys: slots.lastSourceCode.visitorKeys,
1159 scopeManager: analyzeScope(slots.lastSourceCode.ast, parserOptions)
1164 const sourceCode = slots.lastSourceCode;
1165 const commentDirectives = options.allowInlineConfig
1166 ? getDirectiveComments(options.filename, sourceCode.ast, ruleId => getRule(slots, ruleId), options.warnInlineConfig)
1167 : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
1169 // augment global scope with declared global variables
1171 sourceCode.scopeManager.scopes[0],
1173 { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
1176 const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
1178 let lintingProblems;
1181 lintingProblems = runRules(
1184 ruleId => getRule(slots, ruleId),
1189 options.disableFixes,
1191 providedOptions.physicalFilename
1194 err.message += `\nOccurred while linting ${options.filename}`;
1195 debug("An error occurred while traversing");
1196 debug("Filename:", options.filename);
1197 if (err.currentNode) {
1198 const { line } = err.currentNode.loc.start;
1200 debug("Line:", line);
1201 err.message += `:${line}`;
1203 debug("Parser Options:", parserOptions);
1204 debug("Parser Path:", parserName);
1205 debug("Settings:", settings);
1209 return applyDisableDirectives({
1210 directives: commentDirectives.disableDirectives,
1211 problems: lintingProblems
1212 .concat(commentDirectives.problems)
1213 .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
1214 reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
1219 * Verifies the text against the rules specified by the second argument.
1220 * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
1221 * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything.
1222 * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked.
1223 * If this is not set, the filename will default to '<input>' in the rule context. If
1224 * an object, then it has "filename", "allowInlineConfig", and some properties.
1225 * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
1227 verify(textOrSourceCode, config, filenameOrOptions) {
1229 const options = typeof filenameOrOptions === "string"
1230 ? { filename: filenameOrOptions }
1231 : filenameOrOptions || {};
1233 // CLIEngine passes a `ConfigArray` object.
1234 if (config && typeof config.extractConfig === "function") {
1235 return this._verifyWithConfigArray(textOrSourceCode, config, options);
1239 * `Linter` doesn't support `overrides` property in configuration.
1240 * So we cannot apply multiple processors.
1242 if (options.preprocess || options.postprocess) {
1243 return this._verifyWithProcessor(textOrSourceCode, config, options);
1245 return this._verifyWithoutProcessors(textOrSourceCode, config, options);
1249 * Verify a given code with `ConfigArray`.
1250 * @param {string|SourceCode} textOrSourceCode The source code.
1251 * @param {ConfigArray} configArray The config array.
1252 * @param {VerifyOptions&ProcessorOptions} options The options.
1253 * @returns {LintMessage[]} The found problems.
1255 _verifyWithConfigArray(textOrSourceCode, configArray, options) {
1256 debug("With ConfigArray: %s", options.filename);
1258 // Store the config array in order to get plugin envs and rules later.
1259 internalSlotsMap.get(this).lastConfigArray = configArray;
1261 // Extract the final config for this file.
1262 const config = configArray.extractConfig(options.filename);
1265 configArray.pluginProcessors.get(config.processor);
1269 debug("Apply the processor: %o", config.processor);
1270 const { preprocess, postprocess, supportsAutofix } = processor;
1271 const disableFixes = options.disableFixes || !supportsAutofix;
1273 return this._verifyWithProcessor(
1276 { ...options, disableFixes, postprocess, preprocess },
1280 return this._verifyWithoutProcessors(textOrSourceCode, config, options);
1284 * Verify with a processor.
1285 * @param {string|SourceCode} textOrSourceCode The source code.
1286 * @param {ConfigData|ExtractedConfig} config The config array.
1287 * @param {VerifyOptions&ProcessorOptions} options The options.
1288 * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
1289 * @returns {LintMessage[]} The found problems.
1291 _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) {
1292 const filename = options.filename || "<input>";
1293 const filenameToExpose = normalizeFilename(filename);
1294 const physicalFilename = options.physicalFilename || filenameToExpose;
1295 const text = ensureText(textOrSourceCode);
1296 const preprocess = options.preprocess || (rawText => [rawText]);
1298 // TODO(stephenwade): Replace this with array.flat() when we drop support for Node v10
1299 const postprocess = options.postprocess || (array => [].concat(...array));
1300 const filterCodeBlock =
1301 options.filterCodeBlock ||
1302 (blockFilename => blockFilename.endsWith(".js"));
1303 const originalExtname = path.extname(filename);
1304 const messageLists = preprocess(text, filenameToExpose).map((block, i) => {
1305 debug("A code block was found: %o", block.filename || "(unnamed)");
1307 // Keep the legacy behavior.
1308 if (typeof block === "string") {
1309 return this._verifyWithoutProcessors(block, config, options);
1312 const blockText = block.text;
1313 const blockName = path.join(filename, `${i}_${block.filename}`);
1315 // Skip this block if filtered.
1316 if (!filterCodeBlock(blockName, blockText)) {
1317 debug("This code block was skipped.");
1321 // Resolve configuration again if the file content or extension was changed.
1322 if (configForRecursive && (text !== blockText || path.extname(blockName) !== originalExtname)) {
1323 debug("Resolving configuration again because the file content or extension was changed.");
1324 return this._verifyWithConfigArray(
1327 { ...options, filename: blockName, physicalFilename }
1332 return this._verifyWithoutProcessors(
1335 { ...options, filename: blockName, physicalFilename }
1339 return postprocess(messageLists, filenameToExpose);
1343 * Gets the SourceCode object representing the parsed source.
1344 * @returns {SourceCode} The SourceCode object.
1347 return internalSlotsMap.get(this).lastSourceCode;
1351 * Defines a new linting rule.
1352 * @param {string} ruleId A unique rule identifier
1353 * @param {Function | Rule} ruleModule Function from context to object mapping AST node types to event handlers
1356 defineRule(ruleId, ruleModule) {
1357 internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule);
1361 * Defines many new linting rules.
1362 * @param {Record<string, Function | Rule>} rulesToDefine map from unique rule identifier to rule
1365 defineRules(rulesToDefine) {
1366 Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
1367 this.defineRule(ruleId, rulesToDefine[ruleId]);
1372 * Gets an object with all loaded rules.
1373 * @returns {Map<string, Rule>} All loaded rules
1376 const { lastConfigArray, ruleMap } = internalSlotsMap.get(this);
1378 return new Map(function *() {
1381 if (lastConfigArray) {
1382 yield* lastConfigArray.pluginRules;
1388 * Define a new parser module
1389 * @param {string} parserId Name of the parser
1390 * @param {Parser} parserModule The parser object
1393 defineParser(parserId, parserModule) {
1394 internalSlotsMap.get(this).parserMap.set(parserId, parserModule);
1398 * Performs multiple autofix passes over the text until as many fixes as possible
1399 * have been applied.
1400 * @param {string} text The source text to apply fixes to.
1401 * @param {ConfigData|ConfigArray} config The ESLint config object to use.
1402 * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use.
1403 * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the
1406 verifyAndFix(text, config, options) {
1412 const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`;
1413 const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
1416 * This loop continues until one of the following is true:
1418 * 1. No more fixes have been applied.
1419 * 2. Ten passes have been made.
1421 * That means anytime a fix is successfully applied, there will be another pass.
1422 * Essentially, guaranteeing a minimum of two passes.
1427 debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`);
1428 messages = this.verify(currentText, config, options);
1430 debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`);
1431 fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
1434 * stop if there are any syntax errors.
1435 * 'fixedResult.output' is a empty string.
1437 if (messages.length === 1 && messages[0].fatal) {
1441 // keep track if any fixes were ever applied - important for return value
1442 fixed = fixed || fixedResult.fixed;
1444 // update to use the fixed output instead of the original text
1445 currentText = fixedResult.output;
1448 fixedResult.fixed &&
1449 passNumber < MAX_AUTOFIX_PASSES
1453 * If the last result had fixes, we need to lint again to be sure we have
1454 * the most up-to-date information.
1456 if (fixedResult.fixed) {
1457 fixedResult.messages = this.verify(currentText, config, options);
1460 // ensure the last result properly reflects if fixes were done
1461 fixedResult.fixed = fixed;
1462 fixedResult.output = currentText;
1472 * Get the internal slots of a given Linter instance for tests.
1473 * @param {Linter} instance The Linter instance to get.
1474 * @returns {LinterInternalSlots} The internal slots.
1476 getLinterInternalSlots(instance) {
1477 return internalSlotsMap.get(instance);