UNPKG

42.1 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 if (traversalInfo.isEntering) {
751 eventGenerator.enterNode(currentNode);
752 } else {
753 eventGenerator.leaveNode(currentNode);
754 }
755 });
756
757 return lintingProblems;
758}
759
760const lastSourceCodes = new WeakMap();
761const loadedParserMaps = new WeakMap();
762const ruleMaps = new WeakMap();
763
764//------------------------------------------------------------------------------
765// Public Interface
766//------------------------------------------------------------------------------
767
768/**
769 * Object that is responsible for verifying JavaScript text
770 * @name eslint
771 */
772module.exports = class Linter {
773
774 constructor() {
775 lastSourceCodes.set(this, null);
776 loadedParserMaps.set(this, new Map());
777 ruleMaps.set(this, new Rules());
778 this.version = pkg.version;
779 this.environments = new Environments();
780
781 this.defineParser("espree", espree);
782 }
783
784 /**
785 * Getter for package version.
786 * @static
787 * @returns {string} The version from package.json.
788 */
789 static get version() {
790 return pkg.version;
791 }
792
793 /**
794 * Configuration object for the `verify` API. A JS representation of the eslintrc files.
795 * @typedef {Object} ESLintConfig
796 * @property {Object} rules The rule configuration to verify against.
797 * @property {string} [parser] Parser to use when generatig the AST.
798 * @property {Object} [parserOptions] Options for the parsed used.
799 * @property {Object} [settings] Global settings passed to each rule.
800 * @property {Object} [env] The environment to verify in.
801 * @property {Object} [globals] Available globals to the code.
802 */
803
804 /**
805 * Same as linter.verify, except without support for processors.
806 * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
807 * @param {ESLintConfig} providedConfig An ESLintConfig instance to configure everything.
808 * @param {(string|Object)} [filenameOrOptions] The optional filename of the file being checked.
809 * If this is not set, the filename will default to '<input>' in the rule context. If
810 * an object, then it has "filename", "saveState", and "allowInlineConfig" properties.
811 * @param {boolean} [filenameOrOptions.allowInlineConfig=true] Allow/disallow inline comments' ability to change config once it is set. Defaults to true if not supplied.
812 * Useful if you want to validate JS without comments overriding rules.
813 * @param {boolean} [filenameOrOptions.reportUnusedDisableDirectives=false] Adds reported errors for unused
814 * eslint-disable directives
815 * @returns {Object[]} The results as an array of messages or an empty array if no messages.
816 */
817 _verifyWithoutProcessors(textOrSourceCode, providedConfig, filenameOrOptions) {
818 const config = providedConfig || {};
819 const options = normalizeVerifyOptions(filenameOrOptions);
820 let text;
821
822 // evaluate arguments
823 if (typeof textOrSourceCode === "string") {
824 lastSourceCodes.set(this, null);
825 text = textOrSourceCode;
826 } else {
827 lastSourceCodes.set(this, textOrSourceCode);
828 text = textOrSourceCode.text;
829 }
830
831 // search and apply "eslint-env *".
832 const envInFile = findEslintEnv(text);
833 const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile);
834 const enabledEnvs = Object.keys(resolvedEnvConfig)
835 .filter(envName => resolvedEnvConfig[envName])
836 .map(envName => this.environments.get(envName))
837 .filter(env => env);
838
839 const parserName = config.parser || DEFAULT_PARSER_NAME;
840 const parserOptions = resolveParserOptions(parserName, config.parserOptions || {}, enabledEnvs);
841 const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs);
842 const settings = config.settings || {};
843
844 if (!lastSourceCodes.get(this)) {
845 const parseResult = parse(
846 text,
847 parserOptions,
848 parserName,
849 loadedParserMaps.get(this),
850 options.filename
851 );
852
853 if (!parseResult.success) {
854 return [parseResult.error];
855 }
856
857 lastSourceCodes.set(this, parseResult.sourceCode);
858 } else {
859
860 /*
861 * If the given source code object as the first argument does not have scopeManager, analyze the scope.
862 * This is for backward compatibility (SourceCode is frozen so it cannot rebind).
863 */
864 const lastSourceCode = lastSourceCodes.get(this);
865
866 if (!lastSourceCode.scopeManager) {
867 lastSourceCodes.set(this, new SourceCode({
868 text: lastSourceCode.text,
869 ast: lastSourceCode.ast,
870 parserServices: lastSourceCode.parserServices,
871 visitorKeys: lastSourceCode.visitorKeys,
872 scopeManager: analyzeScope(lastSourceCode.ast, parserOptions)
873 }));
874 }
875 }
876
877 const sourceCode = lastSourceCodes.get(this);
878 const commentDirectives = options.allowInlineConfig
879 ? getDirectiveComments(options.filename, sourceCode.ast, ruleId => ruleMaps.get(this).get(ruleId))
880 : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] };
881
882 // augment global scope with declared global variables
883 addDeclaredGlobals(
884 sourceCode.scopeManager.scopes[0],
885 configuredGlobals,
886 { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals }
887 );
888
889 const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules);
890
891 let lintingProblems;
892
893 try {
894 lintingProblems = runRules(
895 sourceCode,
896 configuredRules,
897 ruleId => ruleMaps.get(this).get(ruleId),
898 parserOptions,
899 parserName,
900 settings,
901 options.filename
902 );
903 } catch (err) {
904 debug("An error occurred while traversing");
905 debug("Filename:", options.filename);
906 debug("Parser Options:", parserOptions);
907 debug("Parser Path:", parserName);
908 debug("Settings:", settings);
909 throw err;
910 }
911
912 return applyDisableDirectives({
913 directives: commentDirectives.disableDirectives,
914 problems: lintingProblems
915 .concat(commentDirectives.problems)
916 .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column),
917 reportUnusedDisableDirectives: options.reportUnusedDisableDirectives
918 });
919 }
920
921 /**
922 * Verifies the text against the rules specified by the second argument.
923 * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object.
924 * @param {ESLintConfig} config An ESLintConfig instance to configure everything.
925 * @param {(string|Object)} [filenameOrOptions] The optional filename of the file being checked.
926 * If this is not set, the filename will default to '<input>' in the rule context. If
927 * an object, then it has "filename", "saveState", and "allowInlineConfig" properties.
928 * @param {boolean} [filenameOrOptions.allowInlineConfig] Allow/disallow inline comments' ability to change config once it is set. Defaults to true if not supplied.
929 * Useful if you want to validate JS without comments overriding rules.
930 * @param {function(string): string[]} [filenameOrOptions.preprocess] preprocessor for source text. If provided,
931 * this should accept a string of source text, and return an array of code blocks to lint.
932 * @param {function(Array<Object[]>): Object[]} [filenameOrOptions.postprocess] postprocessor for report messages. If provided,
933 * this should accept an array of the message lists for each code block returned from the preprocessor,
934 * apply a mapping to the messages as appropriate, and return a one-dimensional array of messages
935 * @returns {Object[]} The results as an array of messages or an empty array if no messages.
936 */
937 verify(textOrSourceCode, config, filenameOrOptions) {
938 const preprocess = filenameOrOptions && filenameOrOptions.preprocess || (rawText => [rawText]);
939 const postprocess = filenameOrOptions && filenameOrOptions.postprocess || lodash.flatten;
940
941 return postprocess(
942 preprocess(textOrSourceCode).map(
943 textBlock => this._verifyWithoutProcessors(textBlock, config, filenameOrOptions)
944 )
945 );
946 }
947
948 /**
949 * Gets the SourceCode object representing the parsed source.
950 * @returns {SourceCode} The SourceCode object.
951 */
952 getSourceCode() {
953 return lastSourceCodes.get(this);
954 }
955
956 /**
957 * Defines a new linting rule.
958 * @param {string} ruleId A unique rule identifier
959 * @param {Function} ruleModule Function from context to object mapping AST node types to event handlers
960 * @returns {void}
961 */
962 defineRule(ruleId, ruleModule) {
963 ruleMaps.get(this).define(ruleId, ruleModule);
964 }
965
966 /**
967 * Defines many new linting rules.
968 * @param {Object} rulesToDefine map from unique rule identifier to rule
969 * @returns {void}
970 */
971 defineRules(rulesToDefine) {
972 Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => {
973 this.defineRule(ruleId, rulesToDefine[ruleId]);
974 });
975 }
976
977 /**
978 * Gets an object with all loaded rules.
979 * @returns {Map} All loaded rules
980 */
981 getRules() {
982 return ruleMaps.get(this).getAllLoadedRules();
983 }
984
985 /**
986 * Define a new parser module
987 * @param {any} parserId Name of the parser
988 * @param {any} parserModule The parser object
989 * @returns {void}
990 */
991 defineParser(parserId, parserModule) {
992 loadedParserMaps.get(this).set(parserId, parserModule);
993 }
994
995 /**
996 * Performs multiple autofix passes over the text until as many fixes as possible
997 * have been applied.
998 * @param {string} text The source text to apply fixes to.
999 * @param {Object} config The ESLint config object to use.
1000 * @param {Object} options The ESLint options object to use.
1001 * @param {string} options.filename The filename from which the text was read.
1002 * @param {boolean} options.allowInlineConfig Flag indicating if inline comments
1003 * should be allowed.
1004 * @param {boolean|Function} options.fix Determines whether fixes should be applied
1005 * @param {Function} options.preprocess preprocessor for source text. If provided, this should
1006 * accept a string of source text, and return an array of code blocks to lint.
1007 * @param {Function} options.postprocess postprocessor for report messages. If provided,
1008 * this should accept an array of the message lists for each code block returned from the preprocessor,
1009 * apply a mapping to the messages as appropriate, and return a one-dimensional array of messages
1010 * @returns {Object} The result of the fix operation as returned from the
1011 * SourceCodeFixer.
1012 */
1013 verifyAndFix(text, config, options) {
1014 let messages = [],
1015 fixedResult,
1016 fixed = false,
1017 passNumber = 0,
1018 currentText = text;
1019 const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`;
1020 const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true;
1021
1022 /**
1023 * This loop continues until one of the following is true:
1024 *
1025 * 1. No more fixes have been applied.
1026 * 2. Ten passes have been made.
1027 *
1028 * That means anytime a fix is successfully applied, there will be another pass.
1029 * Essentially, guaranteeing a minimum of two passes.
1030 */
1031 do {
1032 passNumber++;
1033
1034 debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`);
1035 messages = this.verify(currentText, config, options);
1036
1037 debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`);
1038 fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix);
1039
1040 /*
1041 * stop if there are any syntax errors.
1042 * 'fixedResult.output' is a empty string.
1043 */
1044 if (messages.length === 1 && messages[0].fatal) {
1045 break;
1046 }
1047
1048 // keep track if any fixes were ever applied - important for return value
1049 fixed = fixed || fixedResult.fixed;
1050
1051 // update to use the fixed output instead of the original text
1052 currentText = fixedResult.output;
1053
1054 } while (
1055 fixedResult.fixed &&
1056 passNumber < MAX_AUTOFIX_PASSES
1057 );
1058
1059 /*
1060 * If the last result had fixes, we need to lint again to be sure we have
1061 * the most up-to-date information.
1062 */
1063 if (fixedResult.fixed) {
1064 fixedResult.messages = this.verify(currentText, config, options);
1065 }
1066
1067 // ensure the last result properly reflects if fixes were done
1068 fixedResult.fixed = fixed;
1069 fixedResult.output = currentText;
1070
1071 return fixedResult;
1072 }
1073};