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