UNPKG

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