UNPKG

55.9 kBJavaScriptView Raw
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"
946 ? new CodePathAnalyzer(new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys }))
947 : new NodeEventGenerator(emitter, { visitorKeys: sourceCode.visitorKeys, fallback: Traverser.getKeys });
948
949 nodeQueue.forEach(traversalInfo => {
950 currentNode = traversalInfo.node;
951
952 try {
953 if (traversalInfo.isEntering) {
954 eventGenerator.enterNode(currentNode);
955 } else {
956 eventGenerator.leaveNode(currentNode);
957 }
958 } catch (err) {
959 err.currentNode = currentNode;
960 throw err;
961 }
962 });
963
964 return lintingProblems;
965}
966
967/**
968 * Ensure the source code to be a string.
969 * @param {string|SourceCode} textOrSourceCode The text or source code object.
970 * @returns {string} The source code text.
971 */
972function ensureText(textOrSourceCode) {
973 if (typeof textOrSourceCode === "object") {
974 const { hasBOM, text } = textOrSourceCode;
975 const bom = hasBOM ? "\uFEFF" : "";
976
977 return bom + text;
978 }
979
980 return String(textOrSourceCode);
981}
982
983/**
984 * Get an environment.
985 * @param {LinterInternalSlots} slots The internal slots of Linter.
986 * @param {string} envId The environment ID to get.
987 * @returns {Environment|null} The environment.
988 */
989function getEnv(slots, envId) {
990 return (
991 (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) ||
992 BuiltInEnvironments.get(envId) ||
993 null
994 );
995}
996
997/**
998 * Get a rule.
999 * @param {LinterInternalSlots} slots The internal slots of Linter.
1000 * @param {string} ruleId The rule ID to get.
1001 * @returns {Rule|null} The rule.
1002 */
1003function getRule(slots, ruleId) {
1004 return (
1005 (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) ||
1006 slots.ruleMap.get(ruleId)
1007 );
1008}
1009
1010/**
1011 * Normalize the value of the cwd
1012 * @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.
1013 * @returns {string | undefined} normalized cwd
1014 */
1015function normalizeCwd(cwd) {
1016 if (cwd) {
1017 return cwd;
1018 }
1019 if (typeof process === "object") {
1020 return process.cwd();
1021 }
1022
1023 // It's more explicit to assign the undefined
1024 // eslint-disable-next-line no-undefined
1025 return undefined;
1026}
1027
1028/**
1029 * The map to store private data.
1030 * @type {WeakMap<Linter, LinterInternalSlots>}
1031 */
1032const internalSlotsMap = new WeakMap();
1033
1034//------------------------------------------------------------------------------
1035// Public Interface
1036//------------------------------------------------------------------------------
1037
1038/**
1039 * Object that is responsible for verifying JavaScript text
1040 * @name eslint
1041 */
1042class Linter {
1043
1044 /**
1045 * Initialize the Linter.
1046 * @param {Object} [config] the config object
1047 * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined.
1048 */
1049 constructor({ cwd } = {}) {
1050 internalSlotsMap.set(this, {
1051 cwd: normalizeCwd(cwd),
1052 lastConfigArray: null,
1053 lastSourceCode: null,
1054 parserMap: new Map([["espree", espree]]),
1055 ruleMap: new Rules()
1056 });
1057
1058 this.version = pkg.version;
1059 }
1060
1061 /**
1062 * Getter for package version.
1063 * @static
1064 * @returns {string} The version from package.json.
1065 */
1066 static get version() {
1067 return pkg.version;
1068 }
1069
1070 /**
1071 * Same as linter.verify, except without support for processors.
1072 * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
1073 * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything.
1074 * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked.
1075 * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
1076 */
1077 _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) {
1078 const slots = internalSlotsMap.get(this);
1079 const config = providedConfig || {};
1080 const options = normalizeVerifyOptions(providedOptions, config);
1081 let text;
1082
1083 // evaluate arguments
1084 if (typeof textOrSourceCode === "string") {
1085 slots.lastSourceCode = null;
1086 text = textOrSourceCode;
1087 } else {
1088 slots.lastSourceCode = textOrSourceCode;
1089 text = textOrSourceCode.text;
1090 }
1091
1092 // Resolve parser.
1093 let parserName = DEFAULT_PARSER_NAME;
1094 let parser = espree;
1095
1096 if (typeof config.parser === "object" && config.parser !== null) {
1097 parserName = config.parser.filePath;
1098 parser = config.parser.definition;
1099 } else if (typeof config.parser === "string") {
1100 if (!slots.parserMap.has(config.parser)) {
1101 return [{
1102 ruleId: null,
1103 fatal: true,
1104 severity: 2,
1105 message: `Configured parser '${config.parser}' was not found.`,
1106 line: 0,
1107 column: 0
1108 }];
1109 }
1110 parserName = config.parser;
1111 parser = slots.parserMap.get(config.parser);
1112 }
1113
1114 // search and apply "eslint-env *".
1115 const envInFile = options.allowInlineConfig && !options.warnInlineConfig
1116 ? findEslintEnv(text)
1117 : {};
1118 const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile);
1119 const enabledEnvs = Object.keys(resolvedEnvConfig)
1120 .filter(envName => resolvedEnvConfig[envName])
1121 .map(envName => getEnv(slots, envName))
1122 .filter(env => env);
1123
1124 const parserOptions = resolveParserOptions(parserName, config.parserOptions || {}, enabledEnvs);
1125 const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
1126 const settings = config.settings || {};
1127
1128 if (!slots.lastSourceCode) {
1129 const parseResult = parse(
1130 text,
1131 parser,
1132 parserOptions,
1133 options.filename
1134 );
1135
1136 if (!parseResult.success) {
1137 return [parseResult.error];
1138 }
1139
1140 slots.lastSourceCode = parseResult.sourceCode;
1141 } else {
1142
1143 /*
1144 * If the given source code object as the first argument does not have scopeManager, analyze the scope.
1145 * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
1146 */
1147 if (!slots.lastSourceCode.scopeManager) {
1148 slots.lastSourceCode = new SourceCode({
1149 text: slots.lastSourceCode.text,
1150 ast: slots.lastSourceCode.ast,
1151 parserServices: slots.lastSourceCode.parserServices,
1152 visitorKeys: slots.lastSourceCode.visitorKeys,
1153 scopeManager: analyzeScope(slots.lastSourceCode.ast, parserOptions)
1154 });
1155 }
1156 }
1157
1158 const sourceCode = slots.lastSourceCode;
1159 const commentDirectives = options.allowInlineConfig
1160 ? getDirectiveComments(options.filename, sourceCode.ast, ruleId => getRule(slots, ruleId), options.warnInlineConfig)
1161 : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
1162
1163 // augment global scope with declared global variables
1164 addDeclaredGlobals(
1165 sourceCode.scopeManager.scopes[0],
1166 configuredGlobals,
1167 { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
1168 );
1169
1170 const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
1171
1172 let lintingProblems;
1173
1174 try {
1175 lintingProblems = runRules(
1176 sourceCode,
1177 configuredRules,
1178 ruleId => getRule(slots, ruleId),
1179 parserOptions,
1180 parserName,
1181 settings,
1182 options.filename,
1183 options.disableFixes,
1184 slots.cwd
1185 );
1186 } catch (err) {
1187 err.message += `\nOccurred while linting ${options.filename}`;
1188 debug("An error occurred while traversing");
1189 debug("Filename:", options.filename);
1190 if (err.currentNode) {
1191 const { line } = err.currentNode.loc.start;
1192
1193 debug("Line:", line);
1194 err.message += `:${line}`;
1195 }
1196 debug("Parser Options:", parserOptions);
1197 debug("Parser Path:", parserName);
1198 debug("Settings:", settings);
1199 throw err;
1200 }
1201
1202 return applyDisableDirectives({
1203 directives: commentDirectives.disableDirectives,
1204 problems: lintingProblems
1205 .concat(commentDirectives.problems)
1206 .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
1207 reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
1208 });
1209 }
1210
1211 /**
1212 * Verifies the text against the rules specified by the second argument.
1213 * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
1214 * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything.
1215 * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked.
1216 * If this is not set, the filename will default to '<input>' in the rule context. If
1217 * an object, then it has "filename", "allowInlineConfig", and some properties.
1218 * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages.
1219 */
1220 verify(textOrSourceCode, config, filenameOrOptions) {
1221 debug("Verify");
1222 const options = typeof filenameOrOptions === "string"
1223 ? { filename: filenameOrOptions }
1224 : filenameOrOptions || {};
1225
1226 // CLIEngine passes a `ConfigArray` object.
1227 if (config && typeof config.extractConfig === "function") {
1228 return this._verifyWithConfigArray(textOrSourceCode, config, options);
1229 }
1230
1231 /*
1232 * `Linter` doesn't support `overrides` property in configuration.
1233 * So we cannot apply multiple processors.
1234 */
1235 if (options.preprocess || options.postprocess) {
1236 return this._verifyWithProcessor(textOrSourceCode, config, options);
1237 }
1238 return this._verifyWithoutProcessors(textOrSourceCode, config, options);
1239 }
1240
1241 /**
1242 * Verify a given code with `ConfigArray`.
1243 * @param {string|SourceCode} textOrSourceCode The source code.
1244 * @param {ConfigArray} configArray The config array.
1245 * @param {VerifyOptions&ProcessorOptions} options The options.
1246 * @returns {LintMessage[]} The found problems.
1247 */
1248 _verifyWithConfigArray(textOrSourceCode, configArray, options) {
1249 debug("With ConfigArray: %s", options.filename);
1250
1251 // Store the config array in order to get plugin envs and rules later.
1252 internalSlotsMap.get(this).lastConfigArray = configArray;
1253
1254 // Extract the final config for this file.
1255 const config = configArray.extractConfig(options.filename);
1256 const processor =
1257 config.processor &&
1258 configArray.pluginProcessors.get(config.processor);
1259
1260 // Verify.
1261 if (processor) {
1262 debug("Apply the processor: %o", config.processor);
1263 const { preprocess, postprocess, supportsAutofix } = processor;
1264 const disableFixes = options.disableFixes || !supportsAutofix;
1265
1266 return this._verifyWithProcessor(
1267 textOrSourceCode,
1268 config,
1269 { ...options, disableFixes, postprocess, preprocess },
1270 configArray
1271 );
1272 }
1273 return this._verifyWithoutProcessors(textOrSourceCode, config, options);
1274 }
1275
1276 /**
1277 * Verify with a processor.
1278 * @param {string|SourceCode} textOrSourceCode The source code.
1279 * @param {ConfigData|ExtractedConfig} config The config array.
1280 * @param {VerifyOptions&ProcessorOptions} options The options.
1281 * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively.
1282 * @returns {LintMessage[]} The found problems.
1283 */
1284 _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) {
1285 const filename = options.filename || "<input>";
1286 const filenameToExpose = normalizeFilename(filename);
1287 const text = ensureText(textOrSourceCode);
1288 const preprocess = options.preprocess || (rawText => [rawText]);
1289 const postprocess = options.postprocess || lodash.flatten;
1290 const filterCodeBlock =
1291 options.filterCodeBlock ||
1292 (blockFilename => blockFilename.endsWith(".js"));
1293 const originalExtname = path.extname(filename);
1294 const messageLists = preprocess(text, filenameToExpose).map((block, i) => {
1295 debug("A code block was found: %o", block.filename || "(unnamed)");
1296
1297 // Keep the legacy behavior.
1298 if (typeof block === "string") {
1299 return this._verifyWithoutProcessors(block, config, options);
1300 }
1301
1302 const blockText = block.text;
1303 const blockName = path.join(filename, `${i}_${block.filename}`);
1304
1305 // Skip this block if filtered.
1306 if (!filterCodeBlock(blockName, blockText)) {
1307 debug("This code block was skipped.");
1308 return [];
1309 }
1310
1311 // Resolve configuration again if the file extension was changed.
1312 if (configForRecursive && path.extname(blockName) !== originalExtname) {
1313 debug("Resolving configuration again because the file extension was changed.");
1314 return this._verifyWithConfigArray(
1315 blockText,
1316 configForRecursive,
1317 { ...options, filename: blockName }
1318 );
1319 }
1320
1321 // Does lint.
1322 return this._verifyWithoutProcessors(
1323 blockText,
1324 config,
1325 { ...options, filename: blockName }
1326 );
1327 });
1328
1329 return postprocess(messageLists, filenameToExpose);
1330 }
1331
1332 /**
1333 * Gets the SourceCode object representing the parsed source.
1334 * @returns {SourceCode} The SourceCode object.
1335 */
1336 getSourceCode() {
1337 return internalSlotsMap.get(this).lastSourceCode;
1338 }
1339
1340 /**
1341 * Defines a new linting rule.
1342 * @param {string} ruleId A unique rule identifier
1343 * @param {Function | Rule} ruleModule Function from context to object mapping AST node types to event handlers
1344 * @returns {void}
1345 */
1346 defineRule(ruleId, ruleModule) {
1347 internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule);
1348 }
1349
1350 /**
1351 * Defines many new linting rules.
1352 * @param {Record<string, Function | Rule>} rulesToDefine map from unique rule identifier to rule
1353 * @returns {void}
1354 */
1355 defineRules(rulesToDefine) {
1356 Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
1357 this.defineRule(ruleId, rulesToDefine[ruleId]);
1358 });
1359 }
1360
1361 /**
1362 * Gets an object with all loaded rules.
1363 * @returns {Map<string, Rule>} All loaded rules
1364 */
1365 getRules() {
1366 const { lastConfigArray, ruleMap } = internalSlotsMap.get(this);
1367
1368 return new Map(function *() {
1369 yield* ruleMap;
1370
1371 if (lastConfigArray) {
1372 yield* lastConfigArray.pluginRules;
1373 }
1374 }());
1375 }
1376
1377 /**
1378 * Define a new parser module
1379 * @param {string} parserId Name of the parser
1380 * @param {Parser} parserModule The parser object
1381 * @returns {void}
1382 */
1383 defineParser(parserId, parserModule) {
1384 internalSlotsMap.get(this).parserMap.set(parserId, parserModule);
1385 }
1386
1387 /**
1388 * Performs multiple autofix passes over the text until as many fixes as possible
1389 * have been applied.
1390 * @param {string} text The source text to apply fixes to.
1391 * @param {ConfigData|ConfigArray} config The ESLint config object to use.
1392 * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use.
1393 * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the
1394 * SourceCodeFixer.
1395 */
1396 verifyAndFix(text, config, options) {
1397 let messages = [],
1398 fixedResult,
1399 fixed = false,
1400 passNumber = 0,
1401 currentText = text;
1402 const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`;
1403 const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
1404
1405 /**
1406 * This loop continues until one of the following is true:
1407 *
1408 * 1. No more fixes have been applied.
1409 * 2. Ten passes have been made.
1410 *
1411 * That means anytime a fix is successfully applied, there will be another pass.
1412 * Essentially, guaranteeing a minimum of two passes.
1413 */
1414 do {
1415 passNumber++;
1416
1417 debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`);
1418 messages = this.verify(currentText, config, options);
1419
1420 debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`);
1421 fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
1422
1423 /*
1424 * stop if there are any syntax errors.
1425 * 'fixedResult.output' is a empty string.
1426 */
1427 if (messages.length === 1 && messages[0].fatal) {
1428 break;
1429 }
1430
1431 // keep track if any fixes were ever applied - important for return value
1432 fixed = fixed || fixedResult.fixed;
1433
1434 // update to use the fixed output instead of the original text
1435 currentText = fixedResult.output;
1436
1437 } while (
1438 fixedResult.fixed &&
1439 passNumber < MAX_AUTOFIX_PASSES
1440 );
1441
1442 /*
1443 * If the last result had fixes, we need to lint again to be sure we have
1444 * the most up-to-date information.
1445 */
1446 if (fixedResult.fixed) {
1447 fixedResult.messages = this.verify(currentText, config, options);
1448 }
1449
1450 // ensure the last result properly reflects if fixes were done
1451 fixedResult.fixed = fixed;
1452 fixedResult.output = currentText;
1453
1454 return fixedResult;
1455 }
1456}
1457
1458module.exports = {
1459 Linter,
1460
1461 /**
1462 * Get the internal slots of a given Linter instance for tests.
1463 * @param {Linter} instance The Linter instance to get.
1464 * @returns {LinterInternalSlots} The internal slots.
1465 */
1466 getLinterInternalSlots(instance) {
1467 return internalSlotsMap.get(instance);
1468 }
1469};