Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

linter.js 44KB

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