linter.js 54 KB

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