linter.js 55 KB

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