massive update, probably broken
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / eslint / lib / linter / linter.js
1 /**
2  * @fileoverview Main Linter Class
3  * @author Gyandeep Singh
4  * @author aladdin-add
5  */
6
7 "use strict";
8
9 //------------------------------------------------------------------------------
10 // Requirements
11 //------------------------------------------------------------------------------
12
13 const
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");
36
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");
44
45 //------------------------------------------------------------------------------
46 // Typedefs
47 //------------------------------------------------------------------------------
48
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 */
58
59 /**
60  * @template T
61  * @typedef {{ [P in keyof T]-?: T[P] }} Required
62  */
63
64 /**
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
70  */
71
72 /**
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.
79  */
80
81 /**
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.
91  */
92
93 /**
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
101  *      messages.
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.
105  */
106
107 /**
108  * @typedef {Object} FixOptions
109  * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines
110  *      whether fixes should be applied.
111  */
112
113 /**
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)
117  */
118
119 //------------------------------------------------------------------------------
120 // Helpers
121 //------------------------------------------------------------------------------
122
123 /**
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
126  * scope.
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
130  * @returns {void}
131  */
132 function addDeclaredGlobals(globalScope, configGlobals, { exportedVariables, enabledGlobals }) {
133
134     // Define configured global variables.
135     for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(enabledGlobals)])) {
136
137         /*
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).
140          */
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;
145
146         if (value === "off") {
147             continue;
148         }
149
150         let variable = globalScope.set.get(id);
151
152         if (!variable) {
153             variable = new eslintScope.Variable(id, globalScope);
154
155             globalScope.variables.push(variable);
156             globalScope.set.set(id, variable);
157         }
158
159         variable.eslintImplicitGlobalSetting = configValue;
160         variable.eslintExplicitGlobal = sourceComments !== void 0;
161         variable.eslintExplicitGlobalComments = sourceComments;
162         variable.writeable = (value === "writable");
163     }
164
165     // mark all exported variables as such
166     Object.keys(exportedVariables).forEach(name => {
167         const variable = globalScope.set.get(name);
168
169         if (variable) {
170             variable.eslintUsed = true;
171         }
172     });
173
174     /*
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.
178      */
179     globalScope.through = globalScope.through.filter(reference => {
180         const name = reference.identifier.name;
181         const variable = globalScope.set.get(name);
182
183         if (variable) {
184
185             /*
186              * Links the variable and the reference.
187              * And this reference is removed from `Scope#through`.
188              */
189             reference.resolved = variable;
190             variable.references.push(reference);
191
192             return false;
193         }
194
195         return true;
196     });
197 }
198
199 /**
200  * creates a missing-rule message.
201  * @param {string} ruleId the ruleId to create
202  * @returns {string} created error message
203  * @private
204  */
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.`;
209 }
210
211 /**
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.
219  * @private
220  */
221 function createLintingProblem(options) {
222     const {
223         ruleId = null,
224         loc = DEFAULT_ERROR_LOC,
225         message = createMissingRuleMessage(options.ruleId),
226         severity = 2
227     } = options;
228
229     return {
230         ruleId,
231         message,
232         line: loc.start.line,
233         column: loc.start.column + 1,
234         endLine: loc.end.line,
235         endColumn: loc.end.column + 1,
236         severity,
237         nodeType: null
238     };
239 }
240
241 /**
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
250  */
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];
255     const result = {
256         directives: [], // valid disable directives
257         directiveProblems: [] // problems in directives
258     };
259
260     for (const ruleId of directiveRules) {
261
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 });
265         } else {
266             result.directiveProblems.push(createLintingProblem({ ruleId, loc }));
267         }
268     }
269     return result;
270 }
271
272 /**
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.
276  */
277 function stripDirectiveComment(value) {
278     return value.split(/\s-{2,}\s/u)[0].trim();
279 }
280
281 /**
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
291  */
292 function getDirectiveComments(filename, ast, ruleMapper, warnInlineConfig) {
293     const configuredRules = {};
294     const enabledGlobals = Object.create(null);
295     const exportedVariables = {};
296     const problems = [];
297     const disableDirectives = [];
298     const validator = new ConfigValidator({
299         builtInRules: Rules
300     });
301
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);
305
306         if (!match) {
307             return;
308         }
309         const directiveText = match[1];
310         const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(directiveText);
311
312         if (comment.type === "Line" && !lineCommentSupported) {
313             return;
314         }
315
316         if (warnInlineConfig) {
317             const kind = comment.type === "Block" ? `/*${directiveText}*/` : `//${directiveText}`;
318
319             problems.push(createLintingProblem({
320                 ruleId: null,
321                 message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`,
322                 loc: comment.loc,
323                 severity: 1
324             }));
325             return;
326         }
327
328         if (lineCommentSupported && comment.loc.start.line !== comment.loc.end.line) {
329             const message = `${directiveText} comment should not span multiple lines.`;
330
331             problems.push(createLintingProblem({
332                 ruleId: null,
333                 message,
334                 loc: comment.loc
335             }));
336             return;
337         }
338
339         const directiveValue = trimmedCommentText.slice(match.index + directiveText.length);
340
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);
349
350                 disableDirectives.push(...directives);
351                 problems.push(...directiveProblems);
352                 break;
353             }
354
355             case "exported":
356                 Object.assign(exportedVariables, commentParser.parseStringConfig(directiveValue, comment));
357                 break;
358
359             case "globals":
360             case "global":
361                 for (const [id, { value }] of Object.entries(commentParser.parseStringConfig(directiveValue, comment))) {
362                     let normalizedValue;
363
364                     try {
365                         normalizedValue = ConfigOps.normalizeConfigGlobal(value);
366                     } catch (err) {
367                         problems.push(createLintingProblem({
368                             ruleId: null,
369                             loc: comment.loc,
370                             message: err.message
371                         }));
372                         continue;
373                     }
374
375                     if (enabledGlobals[id]) {
376                         enabledGlobals[id].comments.push(comment);
377                         enabledGlobals[id].value = normalizedValue;
378                     } else {
379                         enabledGlobals[id] = {
380                             comments: [comment],
381                             value: normalizedValue
382                         };
383                     }
384                 }
385                 break;
386
387             case "eslint": {
388                 const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc);
389
390                 if (parseResult.success) {
391                     Object.keys(parseResult.config).forEach(name => {
392                         const rule = ruleMapper(name);
393                         const ruleValue = parseResult.config[name];
394
395                         if (rule === null) {
396                             problems.push(createLintingProblem({ ruleId: name, loc: comment.loc }));
397                             return;
398                         }
399
400                         try {
401                             validator.validateRuleOptions(rule, name, ruleValue);
402                         } catch (err) {
403                             problems.push(createLintingProblem({
404                                 ruleId: name,
405                                 message: err.message,
406                                 loc: comment.loc
407                             }));
408
409                             // do not apply the config, if found invalid options.
410                             return;
411                         }
412
413                         configuredRules[name] = ruleValue;
414                     });
415                 } else {
416                     problems.push(parseResult.error);
417                 }
418
419                 break;
420             }
421
422             // no default
423         }
424     });
425
426     return {
427         configuredRules,
428         enabledGlobals,
429         exportedVariables,
430         problems,
431         disableDirectives
432     };
433 }
434
435 /**
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
440  */
441 function normalizeEcmaVersion(parser, ecmaVersion) {
442     if ((parser[parserSymbol] || parser) === espree) {
443         if (ecmaVersion === "latest") {
444             return espree.latestEcmaVersion;
445         }
446     }
447
448     /*
449      * Calculate ECMAScript edition number from official year version starting with
450      * ES2015, which corresponds with ES6 (or a difference of 2009).
451      */
452     return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion;
453 }
454
455 const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gsu;
456
457 /**
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.
461  */
462 function findEslintEnv(text) {
463     let match, retv;
464
465     eslintEnvPattern.lastIndex = 0;
466
467     while ((match = eslintEnvPattern.exec(text)) !== null) {
468         retv = Object.assign(
469             retv || {},
470             commentParser.parseListConfig(stripDirectiveComment(match[1]))
471         );
472     }
473
474     return retv;
475 }
476
477 /**
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
482  * case.
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.
488  */
489 function normalizeFilename(filename) {
490     const parts = filename.split(path.sep);
491     const index = parts.lastIndexOf("<text>");
492
493     return index === -1 ? filename : parts.slice(index).join(path.sep);
494 }
495
496 /**
497  * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
498  * consistent shape.
499  * @param {VerifyOptions} providedOptions Options
500  * @param {ConfigData} config Config.
501  * @returns {Required<VerifyOptions> & InternalOptions} Normalized options
502  */
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})`
508         : "";
509
510     let reportUnusedDisableDirectives = providedOptions.reportUnusedDisableDirectives;
511
512     if (typeof reportUnusedDisableDirectives === "boolean") {
513         reportUnusedDisableDirectives = reportUnusedDisableDirectives ? "error" : "off";
514     }
515     if (typeof reportUnusedDisableDirectives !== "string") {
516         reportUnusedDisableDirectives = config.reportUnusedDisableDirectives ? "warn" : "off";
517     }
518
519     return {
520         filename: normalizeFilename(providedOptions.filename || "<input>"),
521         allowInlineConfig: !ignoreInlineConfig,
522         warnInlineConfig: disableInlineConfig && !ignoreInlineConfig
523             ? `your config${configNameOfNoInlineConfig}`
524             : null,
525         reportUnusedDisableDirectives,
526         disableFixes: Boolean(providedOptions.disableFixes)
527     };
528 }
529
530 /**
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
536  */
537 function resolveParserOptions(parser, providedOptions, enabledEnvironments) {
538
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";
544
545     if (isModule) {
546
547         /*
548          * can't have global return inside of modules
549          * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add)
550          */
551         mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
552     }
553
554     mergedParserOptions.ecmaVersion = normalizeEcmaVersion(parser, mergedParserOptions.ecmaVersion);
555
556     return mergedParserOptions;
557 }
558
559 /**
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
564  */
565 function resolveGlobals(providedGlobals, enabledEnvironments) {
566     return Object.assign(
567         {},
568         ...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
569         providedGlobals
570     );
571 }
572
573 /**
574  * Strips Unicode BOM from a given text.
575  * @param {string} text A text to strip.
576  * @returns {string} The stripped text.
577  */
578 function stripUnicodeBOM(text) {
579
580     /*
581      * Check Unicode BOM.
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
584      */
585     if (text.charCodeAt(0) === 0xFEFF) {
586         return text.slice(1);
587     }
588     return text;
589 }
590
591 /**
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
595  */
596 function getRuleOptions(ruleConfig) {
597     if (Array.isArray(ruleConfig)) {
598         return ruleConfig.slice(1);
599     }
600     return [];
601
602 }
603
604 /**
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.
610  */
611 function analyzeScope(ast, parserOptions, visitorKeys) {
612     const ecmaFeatures = parserOptions.ecmaFeatures || {};
613     const ecmaVersion = parserOptions.ecmaVersion || DEFAULT_ECMA_VERSION;
614
615     return eslintScope.analyze(ast, {
616         ignoreEval: true,
617         nodejsScope: ecmaFeatures.globalReturn,
618         impliedStrict: ecmaFeatures.impliedStrict,
619         ecmaVersion,
620         sourceType: parserOptions.sourceType || "script",
621         childVisitorKeys: visitorKeys || evk.KEYS,
622         fallback: Traverser.getKeys
623     });
624 }
625
626 /**
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
629  * as possible
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
636  * @private
637  */
638 function parse(text, parser, providedParserOptions, filePath) {
639     const textToParse = stripUnicodeBOM(text).replace(astUtils.shebangPattern, (match, captured) => `//${captured}`);
640     const parserOptions = Object.assign({}, providedParserOptions, {
641         loc: true,
642         range: true,
643         raw: true,
644         tokens: true,
645         comment: true,
646         eslintVisitorKeys: true,
647         eslintScopeManager: true,
648         filePath
649     });
650
651     /*
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.
656      */
657     try {
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);
665
666         return {
667             success: true,
668
669             /*
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.
674              */
675             sourceCode: new SourceCode({
676                 text,
677                 ast,
678                 parserServices,
679                 scopeManager,
680                 visitorKeys
681             })
682         };
683     } catch (ex) {
684
685         // If the message includes a leading line number, strip it:
686         const message = `Parsing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
687
688         debug("%s\n%s", message, ex.stack);
689
690         return {
691             success: false,
692             error: {
693                 ruleId: null,
694                 fatal: true,
695                 severity: 2,
696                 message,
697                 line: ex.lineNumber,
698                 column: ex.column
699             }
700         };
701     }
702 }
703
704 /**
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
709  */
710 function getScope(scopeManager, currentNode) {
711
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";
714
715     for (let node = currentNode; node; node = node.parent) {
716         const scope = scopeManager.acquire(node, inner);
717
718         if (scope) {
719             if (scope.type === "function-expression-name") {
720                 return scope.childScopes[0];
721             }
722             return scope;
723         }
724     }
725
726     return scopeManager.scopes[0];
727 }
728
729 /**
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.
736  */
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);
741
742     // Special Node.js scope means we need to start one level deeper
743     const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
744
745     for (let scope = initialScope; scope; scope = scope.upper) {
746         const variable = scope.variables.find(scopeVar => scopeVar.name === name);
747
748         if (variable) {
749             variable.eslintUsed = true;
750             return true;
751         }
752     }
753
754     return false;
755 }
756
757 /**
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
762  */
763 function createRuleListeners(rule, ruleContext) {
764     try {
765         return rule.create(ruleContext);
766     } catch (ex) {
767         ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
768         throw ex;
769     }
770 }
771
772 /**
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.
777  */
778 function getAncestors(node) {
779     const ancestorsStartingAtParent = [];
780
781     for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
782         ancestorsStartingAtParent.push(ancestor);
783     }
784
785     return ancestorsStartingAtParent.reverse();
786 }
787
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"
810 };
811
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);
818                 }
819             }),
820         {}
821     )
822 );
823
824 /**
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
837  */
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;
842
843     Traverser.traverse(sourceCode.ast, {
844         enter(node, parent) {
845             node.parent = parent;
846             nodeQueue.push({ isEntering: true, node });
847         },
848         leave(node) {
849             nodeQueue.push({ isEntering: false, node });
850         },
851         visitorKeys: sourceCode.visitorKeys
852     });
853
854     /*
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.
858      */
859     const sharedTraversalContext = Object.freeze(
860         Object.assign(
861             Object.create(BASE_TRAVERSAL_CONTEXT),
862             {
863                 getAncestors: () => getAncestors(currentNode),
864                 getDeclaredVariables: sourceCode.scopeManager.getDeclaredVariables.bind(sourceCode.scopeManager),
865                 getCwd: () => cwd,
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),
871                 parserOptions,
872                 parserPath: parserName,
873                 parserServices: sourceCode.parserServices,
874                 settings
875             }
876         )
877     );
878
879
880     const lintingProblems = [];
881
882     Object.keys(configuredRules).forEach(ruleId => {
883         const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]);
884
885         // not load disabled rules
886         if (severity === 0) {
887             return;
888         }
889
890         const rule = ruleMapper(ruleId);
891
892         if (rule === null) {
893             lintingProblems.push(createLintingProblem({ ruleId }));
894             return;
895         }
896
897         const messageIds = rule.meta && rule.meta.messages;
898         let reportTranslator = null;
899         const ruleContext = Object.freeze(
900             Object.assign(
901                 Object.create(sharedTraversalContext),
902                 {
903                     id: ruleId,
904                     options: getRuleOptions(configuredRules[ruleId]),
905                     report(...args) {
906
907                         /*
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
912                          * called.
913                          *
914                          * Using lazy report translators improves end-to-end performance by about 3%
915                          * with Node 8.4.0.
916                          */
917                         if (reportTranslator === null) {
918                             reportTranslator = createReportTranslator({
919                                 ruleId,
920                                 severity,
921                                 sourceCode,
922                                 messageIds,
923                                 disableFixes
924                             });
925                         }
926                         const problem = reportTranslator(...args);
927
928                         if (problem.fix && rule.meta && !rule.meta.fixable) {
929                             throw new Error("Fixable rules should export a `meta.fixable` property.");
930                         }
931                         lintingProblems.push(problem);
932                     }
933                 }
934             )
935         );
936
937         const ruleListeners = createRuleListeners(rule, ruleContext);
938
939         // add all the selectors from the rule as listeners
940         Object.keys(ruleListeners).forEach(selector => {
941             emitter.on(
942                 selector,
943                 timing.enabled
944                     ? timing.time(ruleId, ruleListeners[selector])
945                     : ruleListeners[selector]
946             );
947         });
948     });
949
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 });
954
955     nodeQueue.forEach(traversalInfo => {
956         currentNode = traversalInfo.node;
957
958         try {
959             if (traversalInfo.isEntering) {
960                 eventGenerator.enterNode(currentNode);
961             } else {
962                 eventGenerator.leaveNode(currentNode);
963             }
964         } catch (err) {
965             err.currentNode = currentNode;
966             throw err;
967         }
968     });
969
970     return lintingProblems;
971 }
972
973 /**
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.
977  */
978 function ensureText(textOrSourceCode) {
979     if (typeof textOrSourceCode === "object") {
980         const { hasBOM, text } = textOrSourceCode;
981         const bom = hasBOM ? "\uFEFF" : "";
982
983         return bom + text;
984     }
985
986     return String(textOrSourceCode);
987 }
988
989 /**
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.
994  */
995 function getEnv(slots, envId) {
996     return (
997         (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) ||
998         BuiltInEnvironments.get(envId) ||
999         null
1000     );
1001 }
1002
1003 /**
1004  * Get a rule.
1005  * @param {LinterInternalSlots} slots The internal slots of Linter.
1006  * @param {string} ruleId The rule ID to get.
1007  * @returns {Rule|null} The rule.
1008  */
1009 function getRule(slots, ruleId) {
1010     return (
1011         (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) ||
1012         slots.ruleMap.get(ruleId)
1013     );
1014 }
1015
1016 /**
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
1020  */
1021 function normalizeCwd(cwd) {
1022     if (cwd) {
1023         return cwd;
1024     }
1025     if (typeof process === "object") {
1026         return process.cwd();
1027     }
1028
1029     // It's more explicit to assign the undefined
1030     // eslint-disable-next-line no-undefined
1031     return undefined;
1032 }
1033
1034 /**
1035  * The map to store private data.
1036  * @type {WeakMap<Linter, LinterInternalSlots>}
1037  */
1038 const internalSlotsMap = new WeakMap();
1039
1040 //------------------------------------------------------------------------------
1041 // Public Interface
1042 //------------------------------------------------------------------------------
1043
1044 /**
1045  * Object that is responsible for verifying JavaScript text
1046  * @name eslint
1047  */
1048 class Linter {
1049
1050     /**
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.
1054      */
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()
1062         });
1063
1064         this.version = pkg.version;
1065     }
1066
1067     /**
1068      * Getter for package version.
1069      * @static
1070      * @returns {string} The version from package.json.
1071      */
1072     static get version() {
1073         return pkg.version;
1074     }
1075
1076     /**
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.
1082      */
1083     _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
1084         const slots = internalSlotsMap.get(this);
1085         const config = providedConfig || {};
1086         const options = normalizeVerifyOptions(providedOptions, config);
1087         let text;
1088
1089         // evaluate arguments
1090         if (typeof textOrSourceCode === "string") {
1091             slots.lastSourceCode = null;
1092             text = textOrSourceCode;
1093         } else {
1094             slots.lastSourceCode = textOrSourceCode;
1095             text = textOrSourceCode.text;
1096         }
1097
1098         // Resolve parser.
1099         let parserName = DEFAULT_PARSER_NAME;
1100         let parser = espree;
1101
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)) {
1107                 return [{
1108                     ruleId: null,
1109                     fatal: true,
1110                     severity: 2,
1111                     message: `Configured parser '${config.parser}' was not found.`,
1112                     line: 0,
1113                     column: 0
1114                 }];
1115             }
1116             parserName = config.parser;
1117             parser = slots.parserMap.get(config.parser);
1118         }
1119
1120         // search and apply "eslint-env *".
1121         const envInFile = options.allowInlineConfig && !options.warnInlineConfig
1122             ? findEslintEnv(text)
1123             : {};
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);
1129
1130         const parserOptions = resolveParserOptions(parser, config.parserOptions || {}, enabledEnvs);
1131         const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
1132         const settings = config.settings || {};
1133
1134         if (!slots.lastSourceCode) {
1135             const parseResult = parse(
1136                 text,
1137                 parser,
1138                 parserOptions,
1139                 options.filename
1140             );
1141
1142             if (!parseResult.success) {
1143                 return [parseResult.error];
1144             }
1145
1146             slots.lastSourceCode = parseResult.sourceCode;
1147         } else {
1148
1149             /*
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).
1152              */
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)
1160                 });
1161             }
1162         }
1163
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: [] };
1168
1169         // augment global scope with declared global variables
1170         addDeclaredGlobals(
1171             sourceCode.scopeManager.scopes[0],
1172             configuredGlobals,
1173             { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
1174         );
1175
1176         const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
1177
1178         let lintingProblems;
1179
1180         try {
1181             lintingProblems = runRules(
1182                 sourceCode,
1183                 configuredRules,
1184                 ruleId => getRule(slots, ruleId),
1185                 parserOptions,
1186                 parserName,
1187                 settings,
1188                 options.filename,
1189                 options.disableFixes,
1190                 slots.cwd,
1191                 providedOptions.physicalFilename
1192             );
1193         } catch (err) {
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;
1199
1200                 debug("Line:", line);
1201                 err.message += `:${line}`;
1202             }
1203             debug("Parser Options:", parserOptions);
1204             debug("Parser Path:", parserName);
1205             debug("Settings:", settings);
1206             throw err;
1207         }
1208
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
1215         });
1216     }
1217
1218     /**
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.
1226      */
1227     verify(textOrSourceCode, config, filenameOrOptions) {
1228         debug("Verify");
1229         const options = typeof filenameOrOptions === "string"
1230             ? { filename: filenameOrOptions }
1231             : filenameOrOptions || {};
1232
1233         // CLIEngine passes a `ConfigArray` object.
1234         if (config && typeof config.extractConfig === "function") {
1235             return this._verifyWithConfigArray(textOrSourceCode, config, options);
1236         }
1237
1238         /*
1239          * `Linter` doesn't support `overrides` property in configuration.
1240          * So we cannot apply multiple processors.
1241          */
1242         if (options.preprocess || options.postprocess) {
1243             return this._verifyWithProcessor(textOrSourceCode, config, options);
1244         }
1245         return this._verifyWithoutProcessors(textOrSourceCode, config, options);
1246     }
1247
1248     /**
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.
1254      */
1255     _verifyWithConfigArray(textOrSourceCode, configArray, options) {
1256         debug("With ConfigArray: %s", options.filename);
1257
1258         // Store the config array in order to get plugin envs and rules later.
1259         internalSlotsMap.get(this).lastConfigArray = configArray;
1260
1261         // Extract the final config for this file.
1262         const config = configArray.extractConfig(options.filename);
1263         const processor =
1264             config.processor &&
1265             configArray.pluginProcessors.get(config.processor);
1266
1267         // Verify.
1268         if (processor) {
1269             debug("Apply the processor: %o", config.processor);
1270             const { preprocess, postprocess, supportsAutofix } = processor;
1271             const disableFixes = options.disableFixes || !supportsAutofix;
1272
1273             return this._verifyWithProcessor(
1274                 textOrSourceCode,
1275                 config,
1276                 { ...options, disableFixes, postprocess, preprocess },
1277                 configArray
1278             );
1279         }
1280         return this._verifyWithoutProcessors(textOrSourceCode, config, options);
1281     }
1282
1283     /**
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.
1290      */
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]);
1297
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)");
1306
1307             // Keep the legacy behavior.
1308             if (typeof block === "string") {
1309                 return this._verifyWithoutProcessors(block, config, options);
1310             }
1311
1312             const blockText = block.text;
1313             const blockName = path.join(filename, `${i}_${block.filename}`);
1314
1315             // Skip this block if filtered.
1316             if (!filterCodeBlock(blockName, blockText)) {
1317                 debug("This code block was skipped.");
1318                 return [];
1319             }
1320
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(
1325                     blockText,
1326                     configForRecursive,
1327                     { ...options, filename: blockName, physicalFilename }
1328                 );
1329             }
1330
1331             // Does lint.
1332             return this._verifyWithoutProcessors(
1333                 blockText,
1334                 config,
1335                 { ...options, filename: blockName, physicalFilename }
1336             );
1337         });
1338
1339         return postprocess(messageLists, filenameToExpose);
1340     }
1341
1342     /**
1343      * Gets the SourceCode object representing the parsed source.
1344      * @returns {SourceCode} The SourceCode object.
1345      */
1346     getSourceCode() {
1347         return internalSlotsMap.get(this).lastSourceCode;
1348     }
1349
1350     /**
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
1354      * @returns {void}
1355      */
1356     defineRule(ruleId, ruleModule) {
1357         internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule);
1358     }
1359
1360     /**
1361      * Defines many new linting rules.
1362      * @param {Record<string, Function | Rule>} rulesToDefine map from unique rule identifier to rule
1363      * @returns {void}
1364      */
1365     defineRules(rulesToDefine) {
1366         Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
1367             this.defineRule(ruleId, rulesToDefine[ruleId]);
1368         });
1369     }
1370
1371     /**
1372      * Gets an object with all loaded rules.
1373      * @returns {Map<string, Rule>} All loaded rules
1374      */
1375     getRules() {
1376         const { lastConfigArray, ruleMap } = internalSlotsMap.get(this);
1377
1378         return new Map(function *() {
1379             yield* ruleMap;
1380
1381             if (lastConfigArray) {
1382                 yield* lastConfigArray.pluginRules;
1383             }
1384         }());
1385     }
1386
1387     /**
1388      * Define a new parser module
1389      * @param {string} parserId Name of the parser
1390      * @param {Parser} parserModule The parser object
1391      * @returns {void}
1392      */
1393     defineParser(parserId, parserModule) {
1394         internalSlotsMap.get(this).parserMap.set(parserId, parserModule);
1395     }
1396
1397     /**
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
1404      *      SourceCodeFixer.
1405      */
1406     verifyAndFix(text, config, options) {
1407         let messages = [],
1408             fixedResult,
1409             fixed = false,
1410             passNumber = 0,
1411             currentText = text;
1412         const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`;
1413         const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
1414
1415         /**
1416          * This loop continues until one of the following is true:
1417          *
1418          * 1. No more fixes have been applied.
1419          * 2. Ten passes have been made.
1420          *
1421          * That means anytime a fix is successfully applied, there will be another pass.
1422          * Essentially, guaranteeing a minimum of two passes.
1423          */
1424         do {
1425             passNumber++;
1426
1427             debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`);
1428             messages = this.verify(currentText, config, options);
1429
1430             debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`);
1431             fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
1432
1433             /*
1434              * stop if there are any syntax errors.
1435              * 'fixedResult.output' is a empty string.
1436              */
1437             if (messages.length === 1 && messages[0].fatal) {
1438                 break;
1439             }
1440
1441             // keep track if any fixes were ever applied - important for return value
1442             fixed = fixed || fixedResult.fixed;
1443
1444             // update to use the fixed output instead of the original text
1445             currentText = fixedResult.output;
1446
1447         } while (
1448             fixedResult.fixed &&
1449             passNumber < MAX_AUTOFIX_PASSES
1450         );
1451
1452         /*
1453          * If the last result had fixes, we need to lint again to be sure we have
1454          * the most up-to-date information.
1455          */
1456         if (fixedResult.fixed) {
1457             fixedResult.messages = this.verify(currentText, config, options);
1458         }
1459
1460         // ensure the last result properly reflects if fixes were done
1461         fixedResult.fixed = fixed;
1462         fixedResult.output = currentText;
1463
1464         return fixedResult;
1465     }
1466 }
1467
1468 module.exports = {
1469     Linter,
1470
1471     /**
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.
1475      */
1476     getLinterInternalSlots(instance) {
1477         return internalSlotsMap.get(instance);
1478     }
1479 };