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