linter.js 41 KB

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