UNPKG

42.5 kBJavaScriptView Raw
1/**
2 * @fileoverview Main Linter Class
3 * @author Gyandeep Singh
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const eslintScope = require("eslint-scope"),
13 evk = require("eslint-visitor-keys"),
14 espree = require("espree"),
15 lodash = require("lodash"),
16 CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"),
17 ConfigOps = require("./config/config-ops"),
18 validator = require("./config/config-validator"),
19 Environments = require("./config/environments"),
20 applyDisableDirectives = require("./util/apply-disable-directives"),
21 createEmitter = require("./util/safe-emitter"),
22 NodeEventGenerator = require("./util/node-event-generator"),
23 SourceCode = require("./util/source-code"),
24 Traverser = require("./util/traverser"),
25 createReportTranslator = require("./util/report-translator"),
26 Rules = require("./rules"),
27 timing = require("./util/timing"),
28 ConfigCommentParser = require("./util/config-comment-parser"),
29 astUtils = require("./util/ast-utils"),
30 pkg = require("../package.json"),
31 SourceCodeFixer = require("./util/source-code-fixer");
32
33const debug = require("debug")("eslint:linter");
34const MAX_AUTOFIX_PASSES = 10;
35const DEFAULT_PARSER_NAME = "espree";
36const commentParser = new ConfigCommentParser();
37
38//------------------------------------------------------------------------------
39// Typedefs
40//------------------------------------------------------------------------------
41
42/**
43 * The result of a parsing operation from parseForESLint()
44 * @typedef {Object} CustomParseResult
45 * @property {ASTNode} ast The ESTree AST Program node.
46 * @property {Object} services An object containing additional services related
47 * to the parser.
48 * @property {ScopeManager|null} scopeManager The scope manager object of this AST.
49 * @property {Object|null} visitorKeys The visitor keys to traverse this AST.
50 */
51
52/**
53 * @typedef {Object} DisableDirective
54 * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type
55 * @property {number} line
56 * @property {number} column
57 * @property {(string|null)} ruleId
58 */
59
60//------------------------------------------------------------------------------
61// Helpers
62//------------------------------------------------------------------------------
63
64/**
65 * Ensures that variables representing built-in properties of the Global Object,
66 * and any globals declared by special block comments, are present in the global
67 * scope.
68 * @param {Scope} globalScope The global scope.
69 * @param {Object} configGlobals The globals declared in configuration
70 * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration
71 * @returns {void}
72 */
73function addDeclaredGlobals(globalScope, configGlobals, commentDirectives) {
74 const mergedGlobalsInfo = Object.assign(
75 {},
76 lodash.mapValues(configGlobals, value => ({ sourceComment: null, value: ConfigOps.normalizeConfigGlobal(value) })),
77 lodash.mapValues(commentDirectives.enabledGlobals, ({ comment, value }) => ({ sourceComment: comment, value: ConfigOps.normalizeConfigGlobal(value) }))
78 );
79
80 Object.keys(mergedGlobalsInfo)
81 .filter(name => mergedGlobalsInfo[name].value !== "off")
82 .forEach(name => {
83 let variable = globalScope.set.get(name);
84
85 if (!variable) {
86 variable = new eslintScope.Variable(name, globalScope);
87 if (mergedGlobalsInfo[name].sourceComment === null) {
88 variable.eslintExplicitGlobal = false;
89 } else {
90 variable.eslintExplicitGlobal = true;
91 variable.eslintExplicitGlobalComment = mergedGlobalsInfo[name].sourceComment;
92 }
93 globalScope.variables.push(variable);
94 globalScope.set.set(name, variable);
95 }
96 variable.writeable = (mergedGlobalsInfo[name].value === "writeable");
97 });
98
99 // mark all exported variables as such
100 Object.keys(commentDirectives.exportedVariables).forEach(name => {
101 const variable = globalScope.set.get(name);
102
103 if (variable) {
104 variable.eslintUsed = true;
105 }
106 });
107
108 /*
109 * "through" contains all references which definitions cannot be found.
110 * Since we augment the global scope using configuration, we need to update
111 * references and remove the ones that were added by configuration.
112 */
113 globalScope.through = globalScope.through.filter(reference => {
114 const name = reference.identifier.name;
115 const variable = globalScope.set.get(name);
116
117 if (variable) {
118
119 /*
120 * Links the variable and the reference.
121 * And this reference is removed from `Scope#through`.
122 */
123 reference.resolved = variable;
124 variable.references.push(reference);
125
126 return false;
127 }
128
129 return true;
130 });
131}
132
133/**
134 * Creates a collection of disable directives from a comment
135 * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} type The type of directive comment
136 * @param {{line: number, column: number}} loc The 0-based location of the comment token
137 * @param {string} value The value after the directive in the comment
138 * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`)
139 * @returns {DisableDirective[]} Directives from the comment
140 */
141function createDisableDirectives(type, loc, value) {
142 const ruleIds = Object.keys(commentParser.parseListConfig(value));
143 const directiveRules = ruleIds.length ? ruleIds : [null];
144
145 return directiveRules.map(ruleId => ({ type, line: loc.line, column: loc.column + 1, ruleId }));
146}
147
148/**
149 * Parses comments in file to extract file-specific config of rules, globals
150 * and environments and merges them with global config; also code blocks
151 * where reporting is disabled or enabled and merges them with reporting config.
152 * @param {string} filename The file being checked.
153 * @param {ASTNode} ast The top node of the AST.
154 * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules
155 * @returns {{configuredRules: Object, enabledGlobals: Object, exportedVariables: Object, problems: Problem[], disableDirectives: DisableDirective[]}}
156 * A collection of the directive comments that were found, along with any problems that occurred when parsing
157 */
158function getDirectiveComments(filename, ast, ruleMapper) {
159 const configuredRules = {};
160 const enabledGlobals = {};
161 const exportedVariables = {};
162 const problems = [];
163 const disableDirectives = [];
164
165 ast.comments.filter(token => token.type !== "Shebang").forEach(comment => {
166 const trimmedCommentText = comment.value.trim();
167 const match = /^(eslint(-\w+){0,3}|exported|globals?)(\s|$)/u.exec(trimmedCommentText);
168
169 if (!match) {
170 return;
171 }
172
173 const directiveValue = trimmedCommentText.slice(match.index + match[1].length);
174
175 if (/^eslint-disable-(next-)?line$/u.test(match[1])) {
176 if (comment.loc.start.line === comment.loc.end.line) {
177 const directiveType = match[1].slice("eslint-".length);
178
179 disableDirectives.push(...createDisableDirectives(directiveType, comment.loc.start, directiveValue));
180 } else {
181 problems.push({
182 ruleId: null,
183 severity: 2,
184 message: `${match[1]} comment should not span multiple lines.`,
185 line: comment.loc.start.line,
186 column: comment.loc.start.column + 1,
187 endLine: comment.loc.end.line,
188 endColumn: comment.loc.end.column + 1,
189 nodeType: null
190 });
191 }
192 } else if (comment.type === "Block") {
193 switch (match[1]) {
194 case "exported":
195 Object.assign(exportedVariables, commentParser.parseStringConfig(directiveValue, comment));
196 break;
197
198 case "globals":
199 case "global":
200 Object.assign(enabledGlobals, commentParser.parseStringConfig(directiveValue, comment));
201 break;
202
203 case "eslint-disable":
204 disableDirectives.push(...createDisableDirectives("disable", comment.loc.start, directiveValue));
205 break;
206
207 case "eslint-enable":
208 disableDirectives.push(...createDisableDirectives("enable", comment.loc.start, directiveValue));
209 break;
210
211 case "eslint": {
212 const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc);
213
214 if (parseResult.success) {
215 Object.keys(parseResult.config).forEach(name => {
216 const ruleValue = parseResult.config[name];
217
218 try {
219 validator.validateRuleOptions(ruleMapper(name), name, ruleValue);
220 } catch (err) {
221 problems.push({
222 ruleId: name,
223 severity: 2,
224 message: err.message,
225 line: comment.loc.start.line,
226 column: comment.loc.start.column + 1,
227 endLine: comment.loc.end.line,
228 endColumn: comment.loc.end.column + 1,
229 nodeType: null
230 });
231 }
232 configuredRules[name] = ruleValue;
233 });
234 } else {
235 problems.push(parseResult.error);
236 }
237
238 break;
239 }
240
241 // no default
242 }
243 }
244 });
245
246 return {
247 configuredRules,
248 enabledGlobals,
249 exportedVariables,
250 problems,
251 disableDirectives
252 };
253}
254
255/**
256 * Normalize ECMAScript version from the initial config
257 * @param {number} ecmaVersion ECMAScript version from the initial config
258 * @param {boolean} isModule Whether the source type is module or not
259 * @returns {number} normalized ECMAScript version
260 */
261function normalizeEcmaVersion(ecmaVersion, isModule) {
262
263 // Need at least ES6 for modules
264 if (isModule && (!ecmaVersion || ecmaVersion < 6)) {
265 return 6;
266 }
267
268 /*
269 * Calculate ECMAScript edition number from official year version starting with
270 * ES2015, which corresponds with ES6 (or a difference of 2009).
271 */
272 if (ecmaVersion >= 2015) {
273 return ecmaVersion - 2009;
274 }
275
276 return ecmaVersion;
277}
278
279const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gu;
280
281/**
282 * Checks whether or not there is a comment which has "eslint-env *" in a given text.
283 * @param {string} text - A source code text to check.
284 * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment.
285 */
286function findEslintEnv(text) {
287 let match, retv;
288
289 eslintEnvPattern.lastIndex = 0;
290
291 while ((match = eslintEnvPattern.exec(text))) {
292 retv = Object.assign(retv || {}, commentParser.parseListConfig(match[1]));
293 }
294
295 return retv;
296}
297
298/**
299 * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a
300 * consistent shape.
301 * @param {(string|{reportUnusedDisableDirectives: boolean, filename: string, allowInlineConfig: boolean})} providedOptions Options
302 * @returns {{reportUnusedDisableDirectives: boolean, filename: string, allowInlineConfig: boolean}} Normalized options
303 */
304function normalizeVerifyOptions(providedOptions) {
305 const isObjectOptions = typeof providedOptions === "object";
306 const providedFilename = isObjectOptions ? providedOptions.filename : providedOptions;
307
308 return {
309 filename: typeof providedFilename === "string" ? providedFilename : "<input>",
310 allowInlineConfig: !isObjectOptions || providedOptions.allowInlineConfig !== false,
311 reportUnusedDisableDirectives: isObjectOptions && !!providedOptions.reportUnusedDisableDirectives
312 };
313}
314
315/**
316 * Combines the provided parserOptions with the options from environments
317 * @param {string} parserName The parser name which uses this options.
318 * @param {Object} providedOptions The provided 'parserOptions' key in a config
319 * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments
320 * @returns {Object} Resulting parser options after merge
321 */
322function resolveParserOptions(parserName, providedOptions, enabledEnvironments) {
323 const parserOptionsFromEnv = enabledEnvironments
324 .filter(env => env.parserOptions)
325 .reduce((parserOptions, env) => ConfigOps.merge(parserOptions, env.parserOptions), {});
326
327 const mergedParserOptions = ConfigOps.merge(parserOptionsFromEnv, providedOptions || {});
328
329 const isModule = mergedParserOptions.sourceType === "module";
330
331 if (isModule) {
332
333 // can't have global return inside of modules
334 mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false });
335 }
336
337 mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion, isModule);
338
339 // TODO: For backward compatibility. Will remove on v6.0.0.
340 if (
341 parserName === DEFAULT_PARSER_NAME &&
342 mergedParserOptions.ecmaFeatures &&
343 mergedParserOptions.ecmaFeatures.experimentalObjectRestSpread &&
344 (!mergedParserOptions.ecmaVersion || mergedParserOptions.ecmaVersion < 9)
345 ) {
346 mergedParserOptions.ecmaVersion = 9;
347 }
348
349 return mergedParserOptions;
350}
351
352/**
353 * Combines the provided globals object with the globals from environments
354 * @param {Object} providedGlobals The 'globals' key in a config
355 * @param {Environments[]} enabledEnvironments The environments enabled in configuration and with inline comments
356 * @returns {Object} The resolved globals object
357 */
358function resolveGlobals(providedGlobals, enabledEnvironments) {
359 return Object.assign(
360 {},
361 ...enabledEnvironments.filter(env => env.globals).map(env => env.globals),
362 providedGlobals
363 );
364}
365
366/**
367 * Strips Unicode BOM from a given text.
368 *
369 * @param {string} text - A text to strip.
370 * @returns {string} The stripped text.
371 */
372function stripUnicodeBOM(text) {
373
374 /*
375 * Check Unicode BOM.
376 * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF.
377 * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters
378 */
379 if (text.charCodeAt(0) === 0xFEFF) {
380 return text.slice(1);
381 }
382 return text;
383}
384
385/**
386 * Get the options for a rule (not including severity), if any
387 * @param {Array|number} ruleConfig rule configuration
388 * @returns {Array} of rule options, empty Array if none
389 */
390function getRuleOptions(ruleConfig) {
391 if (Array.isArray(ruleConfig)) {
392 return ruleConfig.slice(1);
393 }
394 return [];
395
396}
397
398/**
399 * Analyze scope of the given AST.
400 * @param {ASTNode} ast The `Program` node to analyze.
401 * @param {Object} parserOptions The parser options.
402 * @param {Object} visitorKeys The visitor keys.
403 * @returns {ScopeManager} The analysis result.
404 */
405function analyzeScope(ast, parserOptions, visitorKeys) {
406 const ecmaFeatures = parserOptions.ecmaFeatures || {};
407 const ecmaVersion = parserOptions.ecmaVersion || 5;
408
409 return eslintScope.analyze(ast, {
410 ignoreEval: true,
411 nodejsScope: ecmaFeatures.globalReturn,
412 impliedStrict: ecmaFeatures.impliedStrict,
413 ecmaVersion,
414 sourceType: parserOptions.sourceType || "script",
415 childVisitorKeys: visitorKeys || evk.KEYS,
416 fallback: Traverser.getKeys
417 });
418}
419
420/**
421 * Parses text into an AST. Moved out here because the try-catch prevents
422 * optimization of functions, so it's best to keep the try-catch as isolated
423 * as possible
424 * @param {string} text The text to parse.
425 * @param {Object} providedParserOptions Options to pass to the parser
426 * @param {string} parserName The name of the parser
427 * @param {Map<string, Object>} parserMap A map from names to loaded parsers
428 * @param {string} filePath The path to the file being parsed.
429 * @returns {{success: false, error: Problem}|{success: true, sourceCode: SourceCode}}
430 * An object containing the AST and parser services if parsing was successful, or the error if parsing failed
431 * @private
432 */
433function parse(text, providedParserOptions, parserName, parserMap, filePath) {
434
435
436 const textToParse = stripUnicodeBOM(text).replace(astUtils.SHEBANG_MATCHER, (match, captured) => `//${captured}`);
437 const parserOptions = Object.assign({}, providedParserOptions, {
438 loc: true,
439 range: true,
440 raw: true,
441 tokens: true,
442 comment: true,
443 eslintVisitorKeys: true,
444 eslintScopeManager: true,
445 filePath
446 });
447
448 let parser;
449
450 try {
451 parser = parserMap.get(parserName) || require(parserName);
452 } catch (ex) {
453 return {
454 success: false,
455 error: {
456 ruleId: null,
457 fatal: true,
458 severity: 2,
459 message: ex.message,
460 line: 0,
461 column: 0
462 }
463 };
464 }
465
466 /*
467 * Check for parsing errors first. If there's a parsing error, nothing
468 * else can happen. However, a parsing error does not throw an error
469 * from this method - it's just considered a fatal error message, a
470 * problem that ESLint identified just like any other.
471 */
472 try {
473 const parseResult = (typeof parser.parseForESLint === "function")
474 ? parser.parseForESLint(textToParse, parserOptions)
475 : { ast: parser.parse(textToParse, parserOptions) };
476 const ast = parseResult.ast;
477 const parserServices = parseResult.services || {};
478 const visitorKeys = parseResult.visitorKeys || evk.KEYS;
479 const scopeManager = parseResult.scopeManager || analyzeScope(ast, parserOptions, visitorKeys);
480
481 return {
482 success: true,
483
484 /*
485 * Save all values that `parseForESLint()` returned.
486 * If a `SourceCode` object is given as the first parameter instead of source code text,
487 * linter skips the parsing process and reuses the source code object.
488 * In that case, linter needs all the values that `parseForESLint()` returned.
489 */
490 sourceCode: new SourceCode({
491 text,
492 ast,
493 parserServices,
494 scopeManager,
495 visitorKeys
496 })
497 };
498 } catch (ex) {
499
500 // If the message includes a leading line number, strip it:
501 const message = `Parsing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
502
503 return {
504 success: false,
505 error: {
506 ruleId: null,
507 fatal: true,
508 severity: 2,
509 message,
510 line: ex.lineNumber,
511 column: ex.column
512 }
513 };
514 }
515}
516
517/**
518 * Gets the scope for the current node
519 * @param {ScopeManager} scopeManager The scope manager for this AST
520 * @param {ASTNode} currentNode The node to get the scope of
521 * @returns {eslint-scope.Scope} The scope information for this node
522 */
523function getScope(scopeManager, currentNode) {
524
525 // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope.
526 const inner = currentNode.type !== "Program";
527
528 for (let node = currentNode; node; node = node.parent) {
529 const scope = scopeManager.acquire(node, inner);
530
531 if (scope) {
532 if (scope.type === "function-expression-name") {
533 return scope.childScopes[0];
534 }
535 return scope;
536 }
537 }
538
539 return scopeManager.scopes[0];
540}
541
542/**
543 * Marks a variable as used in the current scope
544 * @param {ScopeManager} scopeManager The scope manager for this AST. The scope may be mutated by this function.
545 * @param {ASTNode} currentNode The node currently being traversed
546 * @param {Object} parserOptions The options used to parse this text
547 * @param {string} name The name of the variable that should be marked as used.
548 * @returns {boolean} True if the variable was found and marked as used, false if not.
549 */
550function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
551 const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn;
552 const specialScope = hasGlobalReturn || parserOptions.sourceType === "module";
553 const currentScope = getScope(scopeManager, currentNode);
554
555 // Special Node.js scope means we need to start one level deeper
556 const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope;
557
558 for (let scope = initialScope; scope; scope = scope.upper) {
559 const variable = scope.variables.find(scopeVar => scopeVar.name === name);
560
561 if (variable) {
562 variable.eslintUsed = true;
563 return true;
564 }
565 }
566
567 return false;
568}
569
570/**
571 * Runs a rule, and gets its listeners
572 * @param {Rule} rule A normalized rule with a `create` method
573 * @param {Context} ruleContext The context that should be passed to the rule
574 * @returns {Object} A map of selector listeners provided by the rule
575 */
576function createRuleListeners(rule, ruleContext) {
577 try {
578 return rule.create(ruleContext);
579 } catch (ex) {
580 ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`;
581 throw ex;
582 }
583}
584
585/**
586 * Gets all the ancestors of a given node
587 * @param {ASTNode} node The node
588 * @returns {ASTNode[]} All the ancestor nodes in the AST, not including the provided node, starting
589 * from the root node and going inwards to the parent node.
590 */
591function getAncestors(node) {
592 const ancestorsStartingAtParent = [];
593
594 for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
595 ancestorsStartingAtParent.push(ancestor);
596 }
597
598 return ancestorsStartingAtParent.reverse();
599}
600
601// methods that exist on SourceCode object
602const DEPRECATED_SOURCECODE_PASSTHROUGHS = {
603 getSource: "getText",
604 getSourceLines: "getLines",
605 getAllComments: "getAllComments",
606 getNodeByRangeIndex: "getNodeByRangeIndex",
607 getComments: "getComments",
608 getCommentsBefore: "getCommentsBefore",
609 getCommentsAfter: "getCommentsAfter",
610 getCommentsInside: "getCommentsInside",
611 getJSDocComment: "getJSDocComment",
612 getFirstToken: "getFirstToken",
613 getFirstTokens: "getFirstTokens",
614 getLastToken: "getLastToken",
615 getLastTokens: "getLastTokens",
616 getTokenAfter: "getTokenAfter",
617 getTokenBefore: "getTokenBefore",
618 getTokenByRangeStart: "getTokenByRangeStart",
619 getTokens: "getTokens",
620 getTokensAfter: "getTokensAfter",
621 getTokensBefore: "getTokensBefore",
622 getTokensBetween: "getTokensBetween"
623};
624
625const BASE_TRAVERSAL_CONTEXT = Object.freeze(
626 Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).reduce(
627 (contextInfo, methodName) =>
628 Object.assign(contextInfo, {
629 [methodName](...args) {
630 return this.getSourceCode()[DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]](...args);
631 }
632 }),
633 {}
634 )
635);
636
637/**
638 * Runs the given rules on the given SourceCode object
639 * @param {SourceCode} sourceCode A SourceCode object for the given text
640 * @param {Object} configuredRules The rules configuration
641 * @param {function(string): Rule} ruleMapper A mapper function from rule names to rules
642 * @param {Object} parserOptions The options that were passed to the parser
643 * @param {string} parserName The name of the parser in the config
644 * @param {Object} settings The settings that were enabled in the config
645 * @param {string} filename The reported filename of the code
646 * @returns {Problem[]} An array of reported problems
647 */
648function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parserName, settings, filename) {
649 const emitter = createEmitter();
650 const nodeQueue = [];
651 let currentNode = sourceCode.ast;
652
653 Traverser.traverse(sourceCode.ast, {
654 enter(node, parent) {
655 node.parent = parent;
656 nodeQueue.push({ isEntering: true, node });
657 },
658 leave(node) {
659 nodeQueue.push({ isEntering: false, node });
660 },
661 visitorKeys: sourceCode.visitorKeys
662 });
663
664 /*
665 * Create a frozen object with the ruleContext properties and methods that are shared by all rules.
666 * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the
667 * properties once for each rule.
668 */
669 const sharedTraversalContext = Object.freeze(
670 Object.assign(
671 Object.create(BASE_TRAVERSAL_CONTEXT),
672 {
673 getAncestors: () => getAncestors(currentNode),
674 getDeclaredVariables: sourceCode.scopeManager.getDeclaredVariables.bind(sourceCode.scopeManager),
675 getFilename: () => filename,
676 getScope: () => getScope(sourceCode.scopeManager, currentNode),
677 getSourceCode: () => sourceCode,
678 markVariableAsUsed: name => markVariableAsUsed(sourceCode.scopeManager, currentNode, parserOptions, name),
679 parserOptions,
680 parserPath: parserName,
681 parserServices: sourceCode.parserServices,
682 settings
683 }
684 )
685 );
686
687
688 const lintingProblems = [];
689
690 Object.keys(configuredRules).forEach(ruleId => {
691 const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]);
692
693 if (severity === 0) {
694 return;
695 }
696
697 const rule = ruleMapper(ruleId);
698 const messageIds = rule.meta && rule.meta.messages;
699 let reportTranslator = null;
700 const ruleContext = Object.freeze(
701 Object.assign(
702 Object.create(sharedTraversalContext),
703 {
704 id: ruleId,
705 options: getRuleOptions(configuredRules[ruleId]),
706 report(...args) {
707
708 /*
709 * Create a report translator lazily.
710 * In a vast majority of cases, any given rule reports zero errors on a given
711 * piece of code. Creating a translator lazily avoids the performance cost of
712 * creating a new translator function for each rule that usually doesn't get
713 * called.
714 *
715 * Using lazy report translators improves end-to-end performance by about 3%
716 * with Node 8.4.0.
717 */
718 if (reportTranslator === null) {
719 reportTranslator = createReportTranslator({ ruleId, severity, sourceCode, messageIds });
720 }
721 const problem = reportTranslator(...args);
722
723 if (problem.fix && rule.meta && !rule.meta.fixable) {
724 throw new Error("Fixable rules should export a `meta.fixable` property.");
725 }
726 lintingProblems.push(problem);
727 }
728 }
729 )
730 );
731
732 const ruleListeners = createRuleListeners(rule, ruleContext);
733
734 // add all the selectors from the rule as listeners
735 Object.keys(ruleListeners).forEach(selector => {
736 emitter.on(
737 selector,
738 timing.enabled
739 ? timing.time(ruleId, ruleListeners[selector])
740 : ruleListeners[selector]
741 );
742 });
743 });
744
745 const eventGenerator = new CodePathAnalyzer(new NodeEventGenerator(emitter));
746
747 nodeQueue.forEach(traversalInfo => {
748 currentNode = traversalInfo.node;
749
750 try {
751 if (traversalInfo.isEntering) {
752 eventGenerator.enterNode(currentNode);
753 } else {
754 eventGenerator.leaveNode(currentNode);
755 }
756 } catch (err) {
757 err.currentNode = currentNode;
758 throw err;
759 }
760 });
761
762 return lintingProblems;
763}
764
765const lastSourceCodes = new WeakMap();
766const loadedParserMaps = new WeakMap();
767const ruleMaps = new WeakMap();
768
769//------------------------------------------------------------------------------
770// Public Interface
771//------------------------------------------------------------------------------
772
773/**
774 * Object that is responsible for verifying JavaScript text
775 * @name eslint
776 */
777module.exports = class Linter {
778
779 constructor() {
780 lastSourceCodes.set(this, null);
781 loadedParserMaps.set(this, new Map());
782 ruleMaps.set(this, new Rules());
783 this.version = pkg.version;
784 this.environments = new Environments();
785
786 this.defineParser("espree", espree);
787 }
788
789 /**
790 * Getter for package version.
791 * @static
792 * @returns {string} The version from package.json.
793 */
794 static get version() {
795 return pkg.version;
796 }
797
798 /**
799 * Configuration object for the `verify` API. A JS representation of the eslintrc files.
800 * @typedef {Object} ESLintConfig
801 * @property {Object} rules The rule configuration to verify against.
802 * @property {string} [parser] Parser to use when generatig the AST.
803 * @property {Object} [parserOptions] Options for the parsed used.
804 * @property {Object} [settings] Global settings passed to each rule.
805 * @property {Object} [env] The environment to verify in.
806 * @property {Object} [globals] Available globals to the code.
807 */
808
809 /**
810 * Same as linter.verify, except without support for processors.
811 * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
812 * @param {ESLintConfig} providedConfig An ESLintConfig instance to configure everything.
813 * @param {(string|Object)} [filenameOrOptions] The optional filename of the file being checked.
814 * If this is not set, the filename will default to '<input>' in the rule context. If
815 * an object, then it has "filename", "saveState", and "allowInlineConfig" properties.
816 * @param {boolean} [filenameOrOptions.allowInlineConfig=true] Allow/disallow inline comments' ability to change config once it is set. Defaults to true if not supplied.
817 * Useful if you want to validate JS without comments overriding rules.
818 * @param {boolean} [filenameOrOptions.reportUnusedDisableDirectives=false] Adds reported errors for unused
819 * eslint-disable directives
820 * @returns {Object[]} The results as an array of messages or an empty array if no messages.
821 */
822 _verifyWithoutProcessors(textOrSourceCode, providedConfig, filenameOrOptions) {
823 const config = providedConfig || {};
824 const options = normalizeVerifyOptions(filenameOrOptions);
825 let text;
826
827 // evaluate arguments
828 if (typeof textOrSourceCode === "string") {
829 lastSourceCodes.set(this, null);
830 text = textOrSourceCode;
831 } else {
832 lastSourceCodes.set(this, textOrSourceCode);
833 text = textOrSourceCode.text;
834 }
835
836 // search and apply "eslint-env *".
837 const envInFile = findEslintEnv(text);
838 const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile);
839 const enabledEnvs = Object.keys(resolvedEnvConfig)
840 .filter(envName => resolvedEnvConfig[envName])
841 .map(envName => this.environments.get(envName))
842 .filter(env => env);
843
844 const parserName = config.parser || DEFAULT_PARSER_NAME;
845 const parserOptions = resolveParserOptions(parserName, config.parserOptions || {}, enabledEnvs);
846 const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
847 const settings = config.settings || {};
848
849 if (!lastSourceCodes.get(this)) {
850 const parseResult = parse(
851 text,
852 parserOptions,
853 parserName,
854 loadedParserMaps.get(this),
855 options.filename
856 );
857
858 if (!parseResult.success) {
859 return [parseResult.error];
860 }
861
862 lastSourceCodes.set(this, parseResult.sourceCode);
863 } else {
864
865 /*
866 * If the given source code object as the first argument does not have scopeManager, analyze the scope.
867 * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
868 */
869 const lastSourceCode = lastSourceCodes.get(this);
870
871 if (!lastSourceCode.scopeManager) {
872 lastSourceCodes.set(this, new SourceCode({
873 text: lastSourceCode.text,
874 ast: lastSourceCode.ast,
875 parserServices: lastSourceCode.parserServices,
876 visitorKeys: lastSourceCode.visitorKeys,
877 scopeManager: analyzeScope(lastSourceCode.ast, parserOptions)
878 }));
879 }
880 }
881
882 const sourceCode = lastSourceCodes.get(this);
883 const commentDirectives = options.allowInlineConfig
884 ? getDirectiveComments(options.filename, sourceCode.ast, ruleId => ruleMaps.get(this).get(ruleId))
885 : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
886
887 // augment global scope with declared global variables
888 addDeclaredGlobals(
889 sourceCode.scopeManager.scopes[0],
890 configuredGlobals,
891 { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
892 );
893
894 const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
895
896 let lintingProblems;
897
898 try {
899 lintingProblems = runRules(
900 sourceCode,
901 configuredRules,
902 ruleId => ruleMaps.get(this).get(ruleId),
903 parserOptions,
904 parserName,
905 settings,
906 options.filename
907 );
908 } catch (err) {
909 err.message += `\nOccurred while linting ${options.filename}`;
910 debug("An error occurred while traversing");
911 debug("Filename:", options.filename);
912 if (err.currentNode) {
913 const { line } = err.currentNode.loc.start;
914
915 debug("Line:", line);
916 err.message += `:${line}`;
917 }
918 debug("Parser Options:", parserOptions);
919 debug("Parser Path:", parserName);
920 debug("Settings:", settings);
921 throw err;
922 }
923
924 return applyDisableDirectives({
925 directives: commentDirectives.disableDirectives,
926 problems: lintingProblems
927 .concat(commentDirectives.problems)
928 .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
929 reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
930 });
931 }
932
933 /**
934 * Verifies the text against the rules specified by the second argument.
935 * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
936 * @param {ESLintConfig} config An ESLintConfig instance to configure everything.
937 * @param {(string|Object)} [filenameOrOptions] The optional filename of the file being checked.
938 * If this is not set, the filename will default to '<input>' in the rule context. If
939 * an object, then it has "filename", "saveState", and "allowInlineConfig" properties.
940 * @param {boolean} [filenameOrOptions.allowInlineConfig] Allow/disallow inline comments' ability to change config once it is set. Defaults to true if not supplied.
941 * Useful if you want to validate JS without comments overriding rules.
942 * @param {function(string): string[]} [filenameOrOptions.preprocess] preprocessor for source text. If provided,
943 * this should accept a string of source text, and return an array of code blocks to lint.
944 * @param {function(Array<Object[]>): Object[]} [filenameOrOptions.postprocess] postprocessor for report messages. If provided,
945 * this should accept an array of the message lists for each code block returned from the preprocessor,
946 * apply a mapping to the messages as appropriate, and return a one-dimensional array of messages
947 * @returns {Object[]} The results as an array of messages or an empty array if no messages.
948 */
949 verify(textOrSourceCode, config, filenameOrOptions) {
950 const preprocess = filenameOrOptions && filenameOrOptions.preprocess || (rawText => [rawText]);
951 const postprocess = filenameOrOptions && filenameOrOptions.postprocess || lodash.flatten;
952
953 return postprocess(
954 preprocess(textOrSourceCode).map(
955 textBlock => this._verifyWithoutProcessors(textBlock, config, filenameOrOptions)
956 )
957 );
958 }
959
960 /**
961 * Gets the SourceCode object representing the parsed source.
962 * @returns {SourceCode} The SourceCode object.
963 */
964 getSourceCode() {
965 return lastSourceCodes.get(this);
966 }
967
968 /**
969 * Defines a new linting rule.
970 * @param {string} ruleId A unique rule identifier
971 * @param {Function} ruleModule Function from context to object mapping AST node types to event handlers
972 * @returns {void}
973 */
974 defineRule(ruleId, ruleModule) {
975 ruleMaps.get(this).define(ruleId, ruleModule);
976 }
977
978 /**
979 * Defines many new linting rules.
980 * @param {Object} rulesToDefine map from unique rule identifier to rule
981 * @returns {void}
982 */
983 defineRules(rulesToDefine) {
984 Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
985 this.defineRule(ruleId, rulesToDefine[ruleId]);
986 });
987 }
988
989 /**
990 * Gets an object with all loaded rules.
991 * @returns {Map} All loaded rules
992 */
993 getRules() {
994 return ruleMaps.get(this).getAllLoadedRules();
995 }
996
997 /**
998 * Define a new parser module
999 * @param {any} parserId Name of the parser
1000 * @param {any} parserModule The parser object
1001 * @returns {void}
1002 */
1003 defineParser(parserId, parserModule) {
1004 loadedParserMaps.get(this).set(parserId, parserModule);
1005 }
1006
1007 /**
1008 * Performs multiple autofix passes over the text until as many fixes as possible
1009 * have been applied.
1010 * @param {string} text The source text to apply fixes to.
1011 * @param {Object} config The ESLint config object to use.
1012 * @param {Object} options The ESLint options object to use.
1013 * @param {string} options.filename The filename from which the text was read.
1014 * @param {boolean} options.allowInlineConfig Flag indicating if inline comments
1015 * should be allowed.
1016 * @param {boolean|Function} options.fix Determines whether fixes should be applied
1017 * @param {Function} options.preprocess preprocessor for source text. If provided, this should
1018 * accept a string of source text, and return an array of code blocks to lint.
1019 * @param {Function} options.postprocess postprocessor for report messages. If provided,
1020 * this should accept an array of the message lists for each code block returned from the preprocessor,
1021 * apply a mapping to the messages as appropriate, and return a one-dimensional array of messages
1022 * @returns {Object} The result of the fix operation as returned from the
1023 * SourceCodeFixer.
1024 */
1025 verifyAndFix(text, config, options) {
1026 let messages = [],
1027 fixedResult,
1028 fixed = false,
1029 passNumber = 0,
1030 currentText = text;
1031 const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`;
1032 const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
1033
1034 /**
1035 * This loop continues until one of the following is true:
1036 *
1037 * 1. No more fixes have been applied.
1038 * 2. Ten passes have been made.
1039 *
1040 * That means anytime a fix is successfully applied, there will be another pass.
1041 * Essentially, guaranteeing a minimum of two passes.
1042 */
1043 do {
1044 passNumber++;
1045
1046 debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`);
1047 messages = this.verify(currentText, config, options);
1048
1049 debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`);
1050 fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
1051
1052 /*
1053 * stop if there are any syntax errors.
1054 * 'fixedResult.output' is a empty string.
1055 */
1056 if (messages.length === 1 && messages[0].fatal) {
1057 break;
1058 }
1059
1060 // keep track if any fixes were ever applied - important for return value
1061 fixed = fixed || fixedResult.fixed;
1062
1063 // update to use the fixed output instead of the original text
1064 currentText = fixedResult.output;
1065
1066 } while (
1067 fixedResult.fixed &&
1068 passNumber < MAX_AUTOFIX_PASSES
1069 );
1070
1071 /*
1072 * If the last result had fixes, we need to lint again to be sure we have
1073 * the most up-to-date information.
1074 */
1075 if (fixedResult.fixed) {
1076 fixedResult.messages = this.verify(currentText, config, options);
1077 }
1078
1079 // ensure the last result properly reflects if fixes were done
1080 fixedResult.fixed = fixed;
1081 fixedResult.output = currentText;
1082
1083 return fixedResult;
1084 }
1085};