linter.js 45 KB

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